105 lines
3 KiB
C#
105 lines
3 KiB
C#
using Godot;
|
|
using SpacetimeDB;
|
|
using SpacetimeDB.Types;
|
|
|
|
public partial class ChatOptions : HBoxContainer
|
|
{
|
|
public LineEdit Username { get; private set; }
|
|
public ColorPickerButton ColorPicker { get; private set; }
|
|
|
|
public override void _EnterTree()
|
|
{
|
|
Username = GetNode<LineEdit>("Username");
|
|
ColorPicker = GetNode<ColorPickerButton>("ColorPicker");
|
|
|
|
Username.TextSubmitted += OnUsernameChanged;
|
|
Username.FocusExited += ResetUsername;
|
|
|
|
ColorPicker.ColorChanged += OnColorChange;
|
|
}
|
|
|
|
public override void _Ready()
|
|
{
|
|
DbConnection conn = Spacetime.Instance.Connection;
|
|
RegisterSubscriptions(conn);
|
|
}
|
|
|
|
void ResetUsername()
|
|
{
|
|
Username.Text = UserUtils.UserNameOrIdentity(Spacetime.Instance.Me);
|
|
}
|
|
|
|
void OnUsernameChanged(string text)
|
|
{
|
|
Spacetime.Instance.Connection.Reducers.SetName(text);
|
|
}
|
|
|
|
void OnColorChange(Color color)
|
|
{
|
|
Spacetime.Instance.Connection.Reducers.SetColor(color.ToHtml(false));
|
|
}
|
|
|
|
void RegisterSubscriptions(DbConnection conn)
|
|
{
|
|
conn.Db.User.OnInsert += User_OnInsert;
|
|
conn.Db.User.OnUpdate += User_OnUpdate;
|
|
conn.Reducers.OnSetName += Reducer_OnSetNameEvent;
|
|
conn.Reducers.OnSetColor += Reducer_OnSetColorEvent;
|
|
}
|
|
|
|
void User_OnInsert(EventContext ctx, User insertedValue)
|
|
{
|
|
// It's me
|
|
if (ctx.Identity == insertedValue.Identity)
|
|
{
|
|
Username.Text = insertedValue.Name;
|
|
ColorPicker.Color =
|
|
insertedValue.Color != null && Color.HtmlIsValid(insertedValue.Color)
|
|
? Color.FromHtml(insertedValue.Color)
|
|
: Colors.AliceBlue;
|
|
}
|
|
}
|
|
|
|
void User_OnUpdate(EventContext ctx, User oldValue, User newValue)
|
|
{
|
|
if (ctx.Identity == oldValue.Identity && ctx.Identity == newValue.Identity)
|
|
{
|
|
Username.Text = newValue.Name;
|
|
ColorPicker.Color =
|
|
newValue.Color != null && Color.HtmlIsValid(newValue.Color)
|
|
? Color.FromHtml(newValue.Color)
|
|
: Colors.AliceBlue;
|
|
}
|
|
}
|
|
|
|
/// Our `OnSetNameEvent` callback: print a warning if the reducer failed.
|
|
void Reducer_OnSetNameEvent(ReducerEventContext ctx, string name)
|
|
{
|
|
var e = ctx.Event;
|
|
if (e.CallerIdentity != Spacetime.Instance.Identity)
|
|
{
|
|
// Not me
|
|
return;
|
|
}
|
|
if (e.Status is Status.Failed(var error))
|
|
{
|
|
GD.PrintErr($"Failed to change name to {name}: {error}");
|
|
return;
|
|
}
|
|
}
|
|
|
|
void Reducer_OnSetColorEvent(ReducerEventContext ctx, string color)
|
|
{
|
|
var e = ctx.Event;
|
|
if (e.CallerIdentity != Spacetime.Instance.Identity)
|
|
{
|
|
// Not me
|
|
return;
|
|
}
|
|
if (e.Status is Status.Failed(var error))
|
|
{
|
|
GD.PrintErr($"Failed to change color to {color}: {error}");
|
|
return;
|
|
}
|
|
}
|
|
}
|