# Build a reusable interactive control

Build a play/pause toggle that works with a mouse, touch, or keyboard. Drawing a button shape is the easy part; a reusable control also needs rules for cancellation, focus, and disabled state.

This example activates on a completed pointer press. Drag outside and release to cancel. Press Tab to focus it, then use Space or Return. The pink outline shows keyboard focus.

<div class="docs-demo-layout">

```csharp
using System;
using Xui.Core.Abstract.Events;
using Xui.Core.Canvas;
using Xui.Core.Math2D;
using Xui.Core.UI;
using Xui.Core.UI.Input;

public sealed class ActionToggle : View
{
    private int? pointer;
    private bool enabled = true;
    private bool isOn;
    public ActionToggle()
    {
        HorizontalAlignment = HorizontalAlignment.Center;
        VerticalAlignment = VerticalAlignment.Middle;
        MinimumWidth = 240;
        MinimumHeight = 80;
    }

    public event Action<bool>? Changed;
    public bool IsOn => isOn;
    public override bool Focusable => enabled;

    public bool Enabled
    {
        get => enabled;
        set
        {
            if (enabled == value)
                return;
            enabled = value;
            if (!enabled)
            {
                CancelPress();
                Blur();
            }

            InvalidateRender();
        }
    }

    private void Toggle()
    {
        isOn = !isOn;
        InvalidateRender();
        Changed?.Invoke(isOn);
    }

    public override void OnPointerEvent(ref PointerEventRef e, EventPhase phase)
    {
        if (phase != EventPhase.Bubble || !enabled)
            return;
        if (e.Type == PointerEventType.Down && pointer is null && e.State.Button == PointerButton.Left)
        {
            Focus();
            pointer = e.PointerId;
            CapturePointer(e.PointerId, PointerGestures.Tap);
            InvalidateRender();
        }
        else if (pointer == e.PointerId && e.Type == PointerEventType.Up)
        {
            bool inside = Frame.Contains(e.State.Position);
            CancelPress();
            if (inside)
                Toggle();
        }
        else if (pointer == e.PointerId && e.Type is PointerEventType.Cancel or PointerEventType.LostCapture)
            CancelPress();
    }

    public override void OnKeyDown(ref KeyEventRef e)
    {
        if (enabled && e.Key is VirtualKey.Return or VirtualKey.Space)
        {
            if (!e.IsRepeat)
                Toggle();
            e.Handled = true;
        }
    }

    private void CancelPress()
    {
        int? captured = pointer;
        pointer = null;
        if (captured is int id)
            ReleasePointer(id);
        InvalidateRender();
    }

    protected override void OnDeactivate() => CancelPress();
    protected override void OnFocus() => InvalidateRender();
    protected override void OnBlur() => InvalidateRender();
    protected override void RenderCore(IContext context)
    {
        context.SetFill(new Color(!enabled ? 0xB6ADBFFFu : pointer is not null ? 0x59218AFFu : 0x8538CEFFu));
        context.BeginPath();
        context.RoundRect(Frame, 20);
        context.Fill();
        if (IsFocused)
        {
            context.SetStroke(new Color(0xD957A8FF));
            context.LineWidth = 3;
            context.Stroke();
        }

        context.SetFill(Colors.White);
        context.SetFont(new Font(22, "Inter"));
        context.TextAlign = TextAlign.Center;
        context.TextBaseline = TextBaseline.Middle;
        context.FillText(isOn ? "Playing - tap to pause" : "Paused - tap to play", Frame.Center);
    }
}
```

<figure class="docs-demo" data-demo-url="../../../wasm/?embed=1&amp;demo=views/action-toggle">
<div class="docs-demo-stage">
<img src="views-action-toggle.svg" width="400" height="600" alt="Pointer and keyboard toggle: initial rendered view" />
<button type="button" class="docs-demo-start" hidden><span class="docs-demo-pill">Start demo</span></button>
</div>
<div class="docs-demo-actions">
<button type="button" class="docs-demo-close" hidden>Close demo</button>
<span class="docs-demo-status" role="status" aria-live="polite"></span>
</div>
<figcaption>Pointer and keyboard toggle · <a href="views-action-toggle.cs">C# source</a> · <a href="views-action-toggle.svg">SVG</a> · <a href="../../../wasm/?embed=1&amp;demo=views/action-toggle">Open demo</a></figcaption>
</figure>

</div>


## Make activation one operation

`Toggle` changes the state, invalidates the appearance, and raises `Changed`. Both pointer and keyboard paths call it. A consumer subscribes to `Changed` instead of duplicating the input logic.

Pointer-down only starts a pending press. Store the pointer ID so a second finger cannot complete the first finger's action. Capture that pointer to receive its release even if it leaves the control. Use `PointerGestures.Tap` to tell an ancestor scroll view that it may take over when the gesture becomes a drag.

On pointer-up, test the routed position against the frame, release capture, then activate only if the release is inside. On cancellation or lost capture, clear the press without activating. Clear the stored ID before releasing capture because releasing may itself deliver a capture-change notification.

The example keeps its pressed appearance until release or cancellation. A more polished control can track inside/outside movement separately while retaining capture.

## Offer a keyboard path

`Focusable` makes the enabled control eligible for focus traversal. A pointer press also requests focus. `OnFocus` and `OnBlur` repaint the outline.

`OnKeyDown` handles Return and Space, ignores automatic repeats for activation, and marks the key handled. This implementation activates on key-down because this view contract exposes key-down rather than a paired key-up override. State that behavior deliberately instead of assuming it exactly matches every native button.

Changing `Enabled` to false cancels a pending press, releases focus, and repaints. It also removes the control from subsequent focus traversal. Disabled behavior must affect input as well as color.

## Test the unpleasant cases

Press, drag out, and release: the state must stay unchanged. Start a press, then disable or remove the control: it must not activate later. Hold Space: one physical press should not toggle repeatedly. Put it in a scroll view and drag: scrolling should be able to cancel the tap.

These interaction rules do not by themselves publish a native accessibility role or label. Use the existing ToolKit controls when they fit, and verify accessibility integration on each target before claiming screen-reader parity.
