A Razor UI component for a toggle switch. It defines a visual toggle with a label and manages its state by reporting changes to its parent component.
@namespace CitySim.Punchboard
@using Sandbox.UI
@inherits Panel
<root class="pb-toggle @(Value ? "on" : "")">
<div class="pb-toggle-track"><div class="pb-toggle-thumb"></div></div>
@if ( !string.IsNullOrEmpty( Label ) )
{
<span class="pb-toggle-label">@(GameText.Plain(Label))</span>
}
</root>
@code
{
[Parameter] public string Label { get; set; }
[Parameter] public bool Value { get; set; }
/// <summary>Called with the new value. Update Value in the parent (controlled component).</summary>
[Parameter] public Action<bool> ValueChanged { get; set; }
protected override void OnParametersSet() { base.OnParametersSet(); AcceptsFocus = true; }
protected override void OnClick( MousePanelEvent e ) { base.OnClick( e ); Activate(); }
public override void OnButtonEvent( ButtonEvent e )
{
base.OnButtonEvent( e );
if ( HasFocus && e.Pressed && (e.Button == "enter" || e.Button == "space") ) Activate();
}
float lastActivation = -100;
void Activate() { if (lastActivation == Time.Now) return; lastActivation=Time.Now; TabletopAudio.Switch(); ValueChanged?.Invoke(!Value); }
protected override int BuildHash() => HashCode.Combine(GameText.LanguageCode, HashCode.Combine( Label, Value ));
}