Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(ui)!: widgets ARE data — toggle/dropdown behavior components, compose sugar in core, two-way binding

esengine774b511f5e38
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index c8d8761b6..505efa36b 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1220 stable · 17 beta · 1 deprecated
+Symbols: 1228 stable · 17 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -2034,22 +2034,23 @@ getSelectedIndex: () => number
isOpen: () => boolean
labelEntity: number
open: () => void
-setSelectedIndex: (index: number, silent?: boolean) => void
+setSelectedIndex: (index: number) => void
```
## DropdownOptions — interface
```
buttonStates: { normal?: Color; hover?: Color; pressed?: Color; } | undefined
+disabled: boolean | undefined
events: UIEventQueue
+focusable: boolean | undefined
node: UINodeInit | undefined
onSelect: ((index: number, option: T, entity: Entity) => void) | undefined
optionHeight: number | undefined
-optionStates: { normal?: Color; hover?: Color; pressed?: Color; } | undefined
optionToLabel: ((option: T, index: number) => string) | undefined
options: readonly T[]
parent: number | undefined
-popupVisual: UIVisualInit | undefined
selectedIndex: number | undefined
+tabIndex: number | undefined
world: World
```
@@ -6662,7 +6663,7 @@ dispose: () => void
entity: number
isOn: () => boolean
setDisabled: (disabled: boolean) => void
-setIsOn: (value: boolean, silent?: boolean) => void
+setIsOn: (value: boolean) => void
```
## ToggleOptions — interface
@@ -6944,6 +6945,19 @@ Flex = 0
None = 1
```
+## UIDropdown — const
+```
+ComponentDef<UIDropdownData>
+```
+
+## UIDropdownData — interface
+```
+label: number
+optionHeight: number
+options: string[]
+selectedIndex: number
+```
+
## UIEntityInit — interface
```
node: UINodeInit | undefined
@@ -7129,6 +7143,17 @@ step: number
value: number
```
+## UIToggle — const
+```
+ComponentDef<UIToggleData>
+```
+
+## UIToggleData — interface
+```
+check: number
+isOn: boolean
+```
+
## UIVisual — const
```
BuiltinComponentDef<UIVisualData>
@@ -7643,6 +7668,11 @@ AudioPlugin
(world: World, entity: Entity, controller: string, source: ReadonlySignal<string>): () => void
```
+## bindWidgetValue — function
+```
+<C extends object, K extends keyof C>(world: World, events: UIEventQueue, entity: Entity, component: ComponentDef<C>, field: K, signal: Signal<C[K]>, payloadKey?: string): () => void
+```
+
## btEdges — function
```
(def: BtDefinition): BtEdge[]
@@ -7753,6 +7783,11 @@ BtPlugin
(metadata: Record<string, unknown>): Record<string, unknown>
```
+## closeDropdown — function
+```
+(world: World, e: Entity): void
+```
+
## col — const
```
{ readonly create: (r?: number, g?: number, b?: number, a?: number) => Color; readonly rgb: (r: number, g: number, b: number) => Color; readonly from255: (r: number, g: number, b: number, a?: number) => Color; readonly clone: (c: Color) => Color; readonly lerp: (a: Color, b: Color, t: number) => Color; readonly withAlpha: (c: Color, a: number) => Color; readonly multiply: (a: Color, b: Color) => Color; readonly scaleRgb: (c: Color, s: number) => Color; readonly fromHex: (hex: string) => Color; readonly toHex: (c: Color, withAlpha?: boolean) => string; readonly equals: (a: Color, b: Color, epsilon?: number) => boolean; }
@@ -8493,6 +8528,11 @@ InputRouter
(world: World, root: Entity): boolean
```
+## isDropdownOpen — function
+```
+(world: World, e: Entity): boolean
+```
+
## isEditor — function
```
(): boolean
@@ -8703,6 +8743,11 @@ NavPlugin
(mask: number): number
```
+## openDropdown — function
+```
+(world: World, events: UIEventQueue, e: Entity): void
+```
+
## orientationPerm — function
```
(flags: TileFlags): Perm
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 715342a88..c0898bc62 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1219 stable · 19 beta · 1 deprecated
+Symbols: 1227 stable · 19 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -2029,22 +2029,23 @@ getSelectedIndex: () => number
isOpen: () => boolean
labelEntity: number
open: () => void
-setSelectedIndex: (index: number, silent?: boolean) => void
+setSelectedIndex: (index: number) => void
```
## DropdownOptions — interface
```
buttonStates: { normal?: Color; hover?: Color; pressed?: Color; } | undefined
+disabled: boolean | undefined
events: UIEventQueue
+focusable: boolean | undefined
node: UINodeInit | undefined
onSelect: ((index: number, option: T, entity: Entity) => void) | undefined
optionHeight: number | undefined
-optionStates: { normal?: Color; hover?: Color; pressed?: Color; } | undefined
optionToLabel: ((option: T, index: number) => string) | undefined
options: readonly T[]
parent: number | undefined
-popupVisual: UIVisualInit | undefined
selectedIndex: number | undefined
+tabIndex: number | undefined
world: World
```
@@ -6657,7 +6658,7 @@ dispose: () => void
entity: number
isOn: () => boolean
setDisabled: (disabled: boolean) => void
-setIsOn: (value: boolean, silent?: boolean) => void
+setIsOn: (value: boolean) => void
```
## ToggleOptions — interface
@@ -6939,6 +6940,19 @@ Flex = 0
None = 1
```
+## UIDropdown — const
+```
+ComponentDef<UIDropdownData>
+```
+
+## UIDropdownData — interface
+```
+label: number
+optionHeight: number
+options: string[]
+selectedIndex: number
+```
+
## UIEntityInit — interface
```
node: UINodeInit | undefined
@@ -7124,6 +7138,17 @@ step: number
value: number
```
+## UIToggle — const
+```
+ComponentDef<UIToggleData>
+```
+
+## UIToggleData — interface
+```
+check: number
+isOn: boolean
+```
+
## UIVisual — const
```
BuiltinComponentDef<UIVisualData>
@@ -7638,6 +7663,11 @@ AudioPlugin
(world: World, entity: Entity, controller: string, source: ReadonlySignal<string>): () => void
```
+## bindWidgetValue — function
+```
+<C extends object, K extends keyof C>(world: World, events: UIEventQueue, entity: Entity, component: ComponentDef<C>, field: K, signal: Signal<C[K]>, payloadKey?: string): () => void
+```
+
## btEdges — function
```
(def: BtDefinition): BtEdge[]
@@ -7748,6 +7778,11 @@ BtPlugin
(metadata: Record<string, unknown>): Record<string, unknown>
```
+## closeDropdown — function
+```
+(world: World, e: Entity): void
+```
+
## col — const
```
{ readonly create: (r?: number, g?: number, b?: number, a?: number) => Color; readonly rgb: (r: number, g: number, b: number) => Color; readonly from255: (r: number, g: number, b: number, a?: number) => Color; readonly clone: (c: Color) => Color; readonly lerp: (a: Color, b: Color, t: number) => Color; readonly withAlpha: (c: Color, a: number) => Color; readonly multiply: (a: Color, b: Color) => Color; readonly scaleRgb: (c: Color, s: number) => Color; readonly fromHex: (hex: string) => Color; readonly toHex: (c: Color, withAlpha?: boolean) => string; readonly equals: (a: Color, b: Color, epsilon?: number) => boolean; }
@@ -8488,6 +8523,11 @@ InputRouter
(world: World, root: Entity): boolean
```
+## isDropdownOpen — function
+```
+(world: World, e: Entity): boolean
+```
+
## isEditor — function
```
(): boolean
@@ -8708,6 +8748,11 @@ NodePlatformAdapter
(mask: number): number
```
+## openDropdown — function
+```
+(world: World, events: UIEventQueue, e: Entity): void
+```
+
## orientationPerm — function
```
(flags: TileFlags): Perm
diff --git a/sdk/src/core-ui.ts b/sdk/src/core-ui.ts
index fdd098836..eb82842ee 100644
--- a/sdk/src/core-ui.ts
+++ b/sdk/src/core-ui.ts
@@ -100,6 +100,7 @@ export {
signal,
derived,
bind,
+ bindWidgetValue,
type Signal,
type ReadonlySignal,
} from './ui';
@@ -190,6 +191,13 @@ export {
type UISliderData,
type SliderOptions,
type SliderHandle,
+ UIToggle,
+ type UIToggleData,
+ UIDropdown,
+ isDropdownOpen,
+ openDropdown,
+ closeDropdown,
+ type UIDropdownData,
createProgress,
type ProgressOptions,
type ProgressHandle,
diff --git a/sdk/src/ui/ARCHITECTURE.md b/sdk/src/ui/ARCHITECTURE.md
index 4d1cf49c2..2a5a15771 100644
--- a/sdk/src/ui/ARCHITECTURE.md
+++ b/sdk/src/ui/ARCHITECTURE.md
@@ -39,11 +39,11 @@ collection, or widgets.
| Folder | Responsibility | Key files |
|--------|----------------|-----------|
-| `core/` | Layer 0–1 primitives: the components that *are* the UI | `ui-node`, `ui-visual`, `ui-mask`, `text`, `dimension`, `events`, `ui-camera-info` |
+| `core/` | Layer 0–1 primitives: the components that *are* the UI, plus composition sugar over them | `ui-node`, `ui-visual`, `ui-mask`, `text`, `dimension`, `events`, `ui-camera-info`, `compose` |
| `layout/` | Flexbox layout + safe area + layout bookkeeping | `anchor`, `flex`, `layout` (Yoga driver plugin), `safe-area`, `ui-layout-generation` |
| `input/` | Pointer/keyboard interaction primitives + their plugins | `interactable`, `draggable`, `focusable`, `drag`, `focus`, `interaction` |
-| `controller/` | The one widget-state mechanism: named pages + per-component property gears, tween-applied | `ui-controller`, `ui-gear`, `gear-apply`, `bind-page`, `ai-builtins`, `plugin` |
-| `behavior/` | Runtime systems: scroll/collection ticking, data-driven widget behavior, theme re-resolution | `plugin` (UIBehaviorPlugin), `dialog`, `slider`, `theme-apply` |
+| `controller/` | The one widget-state mechanism: named pages + per-component property gears, tween-applied | `ui-controller`, `ui-gear`, `gear-apply`, `interaction-gears`, `bind-page`, `ai-builtins`, `plugin` |
+| `behavior/` | Runtime systems: scroll/collection ticking, data-driven widget behavior, theme re-resolution | `plugin` (UIBehaviorPlugin), `dialog`, `slider`, `toggle`, `dropdown`, `theme-apply` |
| `render/` | UI-specific render concerns | `mask`, `render-order` |
| `collection/` | Data-driven collections + view recycling | `list-view`, `scroll-container`, `view-pool`, `data-source`, `layout-provider` |
| `text/` | SDF glyph atlas, text layout, rich text, editable text | `glyph-atlas`, `text-renderer`, `layout`, `rich-text-*`, `text-input`, `image-resolver` |
diff --git a/sdk/src/ui/behavior/dropdown.ts b/sdk/src/ui/behavior/dropdown.ts
new file mode 100644
index 000000000..3b028cb76
--- /dev/null
+++ b/sdk/src/ui/behavior/dropdown.ts
@@ -0,0 +1,241 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ui/behavior/dropdown.ts
+ * @brief UIDropdown — data-driven select control.
+ *
+ * The component holds the display labels + `selectedIndex` + the button-label
+ * entity ref; the system owns the popup lifecycle (click toggles it, a click
+ * anywhere else closes it), row selection, keyboard stepping while focused,
+ * and the label sync — the single writer, so `setSelectedIndex`, a binding,
+ * the editor inspector, and pointer selection all behave identically. A
+ * prefab-placed dropdown is fully functional without code.
+ *
+ * The popup is a transient runtime subtree, rebuilt on each open with fresh
+ * theme colors and tagged with ThemeStyle roles for live re-theming.
+ */
+import { defineComponent } from '../../component';
+import { defineSystem, type SystemDef } from '../../system';
+import { Res } from '../../resource';
+import { Input, type InputState } from '../../input';
+import type { World } from '../../world';
+import type { Entity } from '../../types';
+import { px, percent } from '../core/dimension';
+import { spawnUIEntity } from '../core/compose';
+import { Text, type TextData } from '../core/text';
+import { UIEventType, type UIEventQueue } from '../core/events';
+import { Interactable, makeWidgetInteractable, type InteractableData } from '../input/interactable';
+import { Focusable, type FocusableData } from '../input/focusable';
+import { UIController, interactionController } from '../controller/ui-controller';
+import { UIGear } from '../controller/ui-gear';
+import { interactionGears } from '../controller/interaction-gears';
+import { themeColors } from '../theme/tokens';
+import { markThemed } from '../theme/theme-style';
+import { EntityStateMap, walkParentChain } from '../util/helpers';
+
+export interface UIDropdownData {
+ /** Display labels, one per option. */
+ options: string[];
+ selectedIndex: number;
+ /** Popup row height in px. */
+ optionHeight: number;
+ /** The button's label Text entity (content tracks the selection). */
+ label: Entity;
+}
+
+export const UIDropdown = defineComponent<UIDropdownData>('UIDropdown', {
+ options: [],
+ selectedIndex: 0,
+ optionHeight: 32,
+ label: 0 as Entity,
+}, { entityFields: ['label'] });
+
+interface PopupState {
+ panel: Entity;
+ unsubs: Array<() => void>;
+}
+
+// Popup registries are runtime-only and per-world (unit tests run many worlds).
+const popupsByWorld = new WeakMap<World, Map<Entity, PopupState>>();
+
+function popupsOf(world: World): Map<Entity, PopupState> {
+ let m = popupsByWorld.get(world);
+ if (!m) {
+ m = new Map();
+ popupsByWorld.set(world, m);
+ }
+ return m;
+}
+
+export function isDropdownOpen(world: World, e: Entity): boolean {
+ return popupsOf(world).has(e);
+}
+
+export function closeDropdown(world: World, e: Entity): void {
+ const popups = popupsOf(world);
+ const p = popups.get(e);
+ if (!p) return;
+ popups.delete(e);
+ for (const off of p.unsubs) off();
+ if (world.valid(p.panel)) world.despawn(p.panel);
+}
+
+export function openDropdown(world: World, events: UIEventQueue, e: Entity): void {
+ const popups = popupsOf(world);
+ if (popups.has(e) || !world.has(e, UIDropdown)) return;
+ const d = world.get(e, UIDropdown) as UIDropdownData;
+
+ // Fresh theme resolution per open — the popup is transient, so a stale
+ // capture would pin whatever theme was active earlier.
+ const t = themeColors();
+ const panel = spawnUIEntity({
+ world,
+ parent: e,
+ // Below the button: absolute, full width, top at the button's bottom edge.
+ node: {
+ position: 1,
+ insetLeft: px(0),
+ insetRight: px(0),
+ insetTop: percent(100),
+ height: px(d.options.length * d.optionHeight),
+ },
+ visual: { color: t.surfaceElevated },
+ });
+ markThemed(world, panel, { visual: 'surfaceElevated' });
+
+ const unsubs: Array<() => void> = [];
+ for (let i = 0; i < d.options.length; i++) {
+ const row = spawnUIEntity({
+ world,
+ parent: panel,
+ node: {
+ position: 1,
+ insetLeft: px(0),
+ insetRight: px(0),
+ insetTop: px(i * d.optionHeight),
+ height: px(d.optionHeight),
+ },
+ visual: { color: t.control },
+ });
+ // Rows are pointer-only: the popup is transient, so they stay out of
+ // the Tab ring.
+ makeWidgetInteractable(world, row, { focusable: false });
+ world.insert(row, UIController, {
+ controllers: [interactionController(['normal', 'hover', 'pressed'])],
+ });
+ world.insert(row, UIGear, {
+ bindings: interactionGears({
+ normal: { color: t.control },
+ hover: { color: t.primaryHover },
+ pressed: { color: t.primaryActive },
+ }),
+ });
+ markThemed(world, row, {
+ states: { normal: 'control', hover: 'primaryHover', pressed: 'primaryActive' },
+ });
+
+ const rowLabel = spawnUIEntity({
+ world,
+ parent: row,
+ node: { fill: true },
+ text: { content: d.options[i]!, color: t.text },
+ });
+ markThemed(world, rowLabel, { text: 'text' });
+
+ const index = i;
+ unsubs.push(events.on(row, UIEventType.Click, () => {
+ const cur = world.get(e, UIDropdown) as UIDropdownData;
+ closeDropdown(world, e);
+ if (cur.selectedIndex !== index) {
+ cur.selectedIndex = index;
+ world.insert(e, UIDropdown, cur);
+ }
+ }));
+ }
+ popups.set(e, { panel, unsubs });
+}
+
+/** True when `entity` is inside the popup subtree of any open dropdown. */
+function insideAnyPopup(world: World, entity: Entity): boolean {
+ const popups = popupsOf(world);
+ if (popups.size === 0) return false;
+ const panels = new Set<number>();
+ for (const p of popups.values()) panels.add(p.panel as number);
+ if (panels.has(entity as number)) return true;
+ let inside = false;
+ walkParentChain(world, entity, (ancestor) => {
+ if (panels.has(ancestor as number)) {
+ inside = true;
+ return true;
+ }
+ return false;
+ });
+ return inside;
+}
+
+/**
+ * Popup lifecycle + selection + keyboard + label sync for every UIDropdown.
+ */
+export function createDropdownSystem(world: World, events: UIEventQueue): SystemDef {
+ const shown = new EntityStateMap<number>(); // last index whose label was applied
+
+ // One global click handler arbitrates: the dropdown root toggles its own
+ // popup; a click inside a popup is the row handler's business; any other
+ // click closes every open popup (click-outside-to-close).
+ events.on(UIEventType.Click, (ev) => {
+ const target = ev.target;
+ if (world.valid(target) && world.has(target, UIDropdown)) {
+ const enabled = !world.has(target, Interactable)
+ || (world.get(target, Interactable) as InteractableData).enabled;
+ if (!enabled) return;
+ if (isDropdownOpen(world, target)) closeDropdown(world, target);
+ else openDropdown(world, events, target);
+ return;
+ }
+ if (insideAnyPopup(world, target)) return;
+ for (const e of [...popupsOf(world).keys()]) closeDropdown(world, e);
+ });
+
+ world.onDespawn((e) => {
+ // The popup subtree dies with its parent; drop the bookkeeping.
+ if (popupsOf(world).has(e)) closeDropdown(world, e);
+ });
+
+ return defineSystem([Res(Input)], (input: InputState) => {
+ for (const e of world.getEntitiesWithComponents([UIDropdown])) {
+ const d = world.get(e, UIDropdown) as UIDropdownData;
+
+ // Keyboard: step the selection while focused and closed (the
+ // native <select> convention).
+ const focused = world.has(e, Focusable)
+ && (world.get(e, Focusable) as FocusableData).isFocused;
+ const enabled = !world.has(e, Interactable)
+ || (world.get(e, Interactable) as InteractableData).enabled;
+ if (focused && enabled && !isDropdownOpen(world, e) && d.options.length > 0) {
+ let next = d.selectedIndex;
+ if (input.isKeyPressed('ArrowDown')) next = Math.min(next + 1, d.options.length - 1);
+ if (input.isKeyPressed('ArrowUp')) next = Math.max(next - 1, 0);
+ if (next !== d.selectedIndex) {
+ d.selectedIndex = next;
+ world.insert(e, UIDropdown, d);
+ }
+ }
+
+ // Selection → label + change event, whoever wrote the index.
+ if (shown.get(e) !== d.selectedIndex) {
+ const emitChange = shown.has(e); // first sync is initial paint
+ shown.set(e, d.selectedIndex);
+ if (world.valid(d.label) && world.has(d.label, Text)) {
+ const txt = world.get(d.label, Text) as TextData;
+ const content = d.options[d.selectedIndex] ?? '';
+ if (txt.content !== content) {
+ txt.content = content;
+ world.insert(d.label, Text, txt);
+ }
+ }
+ if (emitChange) events.emit(e, UIEventType.Change, { index: d.selectedIndex });
+ }
+ }
+ shown.cleanup(world);
+ }, { name: 'UIDropdownSystem' });
+}
diff --git a/sdk/src/ui/behavior/plugin.ts b/sdk/src/ui/behavior/plugin.ts
index 2b3d548cb..5c2084eca 100644
--- a/sdk/src/ui/behavior/plugin.ts
+++ b/sdk/src/ui/behavior/plugin.ts
@@ -18,6 +18,8 @@ import { UIInteraction, type UIInteractionData } from '../input/interactable';
import { getEntityDepth } from '../util/helpers';
import { UIDialog, createDialogSystem } from './dialog';
import { UISlider, createSliderSystem } from './slider';
+import { UIToggle, createToggleSystem } from './toggle';
+import { UIDropdown, createDropdownSystem } from './dropdown';
import { registerComponent } from '../../component';
/** Screen-px slop before a press becomes a scroll drag (matches Draggable). */
@@ -107,6 +109,20 @@ export class UIBehaviorPlugin implements Plugin {
{ runIf: playModeOnly },
);
+ registerComponent('UIToggle', UIToggle);
+ app.addSystemToSchedule(
+ Schedule.Update,
+ createToggleSystem(world, events),
+ { runIf: playModeOnly },
+ );
+
+ registerComponent('UIDropdown', UIDropdown);
+ app.addSystemToSchedule(
+ Schedule.Update,
+ createDropdownSystem(world, events),
+ { runIf: playModeOnly },
+ );
+
app.addSystemToSchedule(
Schedule.Update,
defineSystem([], () => listViews.tick(), { name: 'ListViewSystem' }),
diff --git a/sdk/src/ui/behavior/toggle.ts b/sdk/src/ui/behavior/toggle.ts
new file mode 100644
index 000000000..ec114e22e
--- /dev/null
+++ b/sdk/src/ui/behavior/toggle.ts
@@ -0,0 +1,60 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ui/behavior/toggle.ts
+ * @brief UIToggle — data-driven on/off state.
+ *
+ * The component IS the state (`isOn` + the check-indicator entity ref); the
+ * system flips it on click and is the single writer of the check visual. Any
+ * writer — the pointer, `setIsOn`, a binding, the editor inspector — shows
+ * the indicator and fires `change` identically, so a prefab-placed toggle
+ * works without code.
+ */
+import { defineComponent } from '../../component';
+import { defineSystem, type SystemDef } from '../../system';
+import type { World } from '../../world';
+import type { Entity } from '../../types';
+import { setUIVisible } from '../core/compose';
+import { Interactable, type InteractableData } from '../input/interactable';
+import { UIEventType, type UIEventQueue } from '../core/events';
+import { EntityStateMap } from '../util/helpers';
+
+export interface UIToggleData {
+ isOn: boolean;
+ /** The on-state indicator entity (UIVisual.enabled tracks `isOn`). */
+ check: Entity;
+}
+
+export const UIToggle = defineComponent<UIToggleData>('UIToggle', {
+ isOn: false,
+ check: 0 as Entity,
+}, { entityFields: ['check'] });
+
+/** Flips on click; syncs `isOn` → check visibility; emits `change`. */
+export function createToggleSystem(world: World, events: UIEventQueue): SystemDef {
+ const shown = new EntityStateMap<boolean>(); // last isOn whose visual was applied
+
+ // The interaction layer defines what a click is (release over the pressed
+ // entity); the toggle just listens.
+ events.on(UIEventType.Click, (ev) => {
+ const e = ev.target;
+ if (!world.valid(e) || !world.has(e, UIToggle)) return;
+ if (world.has(e, Interactable)
+ && !(world.get(e, Interactable) as InteractableData).enabled) return;
+ const d = world.get(e, UIToggle) as UIToggleData;
+ d.isOn = !d.isOn;
+ world.insert(e, UIToggle, d);
+ });
+
+ return defineSystem([], () => {
+ for (const e of world.getEntitiesWithComponents([UIToggle])) {
+ const d = world.get(e, UIToggle) as UIToggleData;
+ if (shown.get(e) === d.isOn) continue;
+ const emitChange = shown.has(e); // first sync is initial paint
+ shown.set(e, d.isOn);
+ setUIVisible(world, d.check, d.isOn);
+ if (emitChange) events.emit(e, UIEventType.Change, { isOn: d.isOn });
+ }
+ shown.cleanup(world);
+ }, { name: 'UIToggleSystem' });
+}
diff --git a/sdk/src/ui/binding/two-way.ts b/sdk/src/ui/binding/two-way.ts
new file mode 100644
index 000000000..c90ac7288
--- /dev/null
+++ b/sdk/src/ui/binding/two-way.ts
@@ -0,0 +1,51 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ui/binding/two-way.ts
+ * @brief bindWidgetValue — two-way binding between a Signal and a widget's
+ * value component field.
+ *
+ * Down: `bind` writes the signal into the field (the widget's behavior system
+ * observes the component and updates visuals + emits `change`). Up: the
+ * widget's `change` event writes back into the signal. The signal is the
+ * loop breaker — `Signal.set` and the down-binding both no-op on equal
+ * values, so a round trip settles in one hop.
+ *
+ * Works with any component whose behavior system emits `change` with the new
+ * value in its payload: `UISlider.value` (`{ value }`), `UIToggle.isOn`
+ * (`{ isOn }`), `UIDropdown.selectedIndex` (`{ index }`).
+ */
+import type { World } from '../../world';
+import type { Entity } from '../../types';
+import type { ComponentDef } from '../../component';
+import { UIEventType, type UIEventQueue } from '../core/events';
+import type { Signal } from './signal';
+import { bind } from './bind';
+
+/**
+ * Two-way bind `signal` ↔ `entity`'s `component.field`, with the widget's
+ * `change` event as the upstream edge. `payloadKey` names the field in the
+ * change payload (e.g. `'value'` for UISlider, `'isOn'` for UIToggle,
+ * `'index'` for UIDropdown). Returns a dispose that tears down both
+ * directions (the down-binding also auto-disposes on despawn).
+ */
+export function bindWidgetValue<C extends object, K extends keyof C>(
+ world: World,
+ events: UIEventQueue,
+ entity: Entity,
+ component: ComponentDef<C>,
+ field: K,
+ signal: Signal<C[K]>,
+ payloadKey: string = field as string,
+): () => void {
+ const down = bind(world, entity, component, field, signal);
+ const up = events.on(entity, UIEventType.Change, (ev) => {
+ const payload = ev.data as Record<string, unknown> | undefined;
+ if (!payload || !(payloadKey in payload)) return;
+ signal.set(payload[payloadKey] as C[K]);
+ });
+ return () => {
+ down();
+ up();
+ };
+}
diff --git a/sdk/src/ui/controller/interaction-gears.ts b/sdk/src/ui/controller/interaction-gears.ts
new file mode 100644
index 000000000..f90b1d0a9
--- /dev/null
+++ b/sdk/src/ui/controller/interaction-gears.ts
@@ -0,0 +1,59 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ui/controller/interaction-gears.ts
+ * @brief Fold per-state visual overrides into `$interaction` gear bindings.
+ *
+ * Controller-layer sugar shared by every consumer that authors interaction
+ * visuals — the button/toggle factories and the dropdown popup rows built by
+ * the behavior system.
+ */
+import type { Color } from '../../types';
+import { EasingType } from '../../animation/Easing';
+import { INTERACTION_CONTROLLER } from './ui-controller';
+import { gearBinding, type GearBinding, type GearValue } from './ui-gear';
+
+/**
+ * Visual overrides for a single interaction state. Omitted fields leave the
+ * live value alone on that state (the gear's sparse-page semantics).
+ */
+export interface ButtonStateVisual {
+ color?: Color;
+ sprite?: number;
+ scale?: number;
+}
+
+/**
+ * Fold the state-name → override record into per-field gear bindings on the
+ * `$interaction` controller. A field a state doesn't override gets no page
+ * entry there (sparse pages: the gear leaves it alone). Sprite swaps are
+ * discrete and always snap; color and scale tween over `fadeDuration`.
+ */
+export function interactionGears(
+ states: Record<string, ButtonStateVisual>,
+ fadeDuration = 0,
+): GearBinding[] {
+ const color: Record<string, GearValue> = {};
+ const sprite: Record<string, GearValue> = {};
+ const scale: Record<string, GearValue> = {};
+ for (const [page, v] of Object.entries(states)) {
+ if (v.color !== undefined) color[page] = { ...v.color };
+ if (v.sprite !== undefined) sprite[page] = v.sprite;
+ if (v.scale !== undefined) scale[page] = { x: v.scale, y: v.scale, z: 1 };
+ }
+ const tween = fadeDuration > 0
+ ? { easing: EasingType.Linear, duration: fadeDuration }
+ : undefined;
+
+ const bindings: GearBinding[] = [];
+ if (Object.keys(color).length > 0) {
+ bindings.push(gearBinding(INTERACTION_CONTROLLER, 'UIVisual', 'color', color, tween));
+ }
+ if (Object.keys(sprite).length > 0) {
+ bindings.push(gearBinding(INTERACTION_CONTROLLER, 'UIVisual', 'texture', sprite));
+ }
+ if (Object.keys(scale).length > 0) {
+ bindings.push(gearBinding(INTERACTION_CONTROLLER, 'Transform', 'scale', scale, tween));
+ }
+ return bindings;
+}
diff --git a/sdk/src/ui/widgets/helpers.ts b/sdk/src/ui/core/compose.ts
similarity index 84%
rename from sdk/src/ui/widgets/helpers.ts
rename to sdk/src/ui/core/compose.ts
index 22fee0550..7a231642f 100644
--- a/sdk/src/ui/widgets/helpers.ts
+++ b/sdk/src/ui/core/compose.ts
@@ -1,5 +1,14 @@
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ui/core/compose.ts
+ * @brief Composition sugar over the Layer-1 primitives: build full component
+ * literals from sparse inits, and spawn a UI entity in one call.
+ *
+ * Lives in core (not widgets) because everything that assembles UI needs it —
+ * widget factories, the text-input plugin, and behavior systems that build
+ * transient subtrees (a dropdown popup). Pure over L1 components only.
+ */
import {
Transform,
type TransformData,
@@ -7,12 +16,10 @@ import {
import type { Entity, Vec2 } from '../../types';
import type { World } from '../../world';
-import { UINode, UIPositionType, UIDisplay, type UINodeData } from '../core/ui-node';
-import { Interactable } from '../input/interactable';
-import { Focusable } from '../input/focusable';
-import { px, percent, auto, type Dimension } from '../core/dimension';
-import { UIVisual, UIVisualType, FillMethod, FillOrigin, type UIVisualData } from '../core/ui-visual';
-import { Text, TextAlign, TextVerticalAlign, TextRenderMode, type TextData } from '../core/text';
+import { UINode, UIPositionType, UIDisplay, type UINodeData } from './ui-node';
+import { px, auto, type Dimension } from './dimension';
+import { UIVisual, UIVisualType, FillMethod, FillOrigin, type UIVisualData } from './ui-visual';
+import { Text, TextAlign, TextVerticalAlign, TextRenderMode, type TextData } from './text';
/** Identity Transform. Fresh object per call — safe to insert into ECS. */
export function identityTransform(): TransformData {
@@ -76,36 +83,6 @@ export function buildUINode(init: UINodeInit = {}): UINodeData {
};
}
-export interface WidgetInteractionInit {
- /** Start disabled (Interactable.enabled = false). */
- disabled?: boolean;
- /** Participate in Tab traversal + keyboard activation. Default true. */
- focusable?: boolean;
- /** Tab order within the focus ring. Default 0 (document order). */
- tabIndex?: number;
-}
-
-/**
- * The one interaction assembly every widget shares: a raycast-blocking
- * Interactable plus (by default) a Focusable so the control is keyboard-
- * reachable. Per-frame pointer state (UIInteraction) is transient — the
- * hit-test system creates it on demand, widgets never insert it.
- */
-export function makeWidgetInteractable(
- world: World,
- entity: Entity,
- init: WidgetInteractionInit = {},
-): void {
- world.insert(entity, Interactable, {
- enabled: !init.disabled,
- blockRaycast: true,
- raycastTarget: true,
- });
- if (init.focusable ?? true) {
- world.insert(entity, Focusable, { tabIndex: init.tabIndex ?? 0, isFocused: false });
- }
-}
-
export interface UIVisualInit {
visualType?: UIVisualType;
texture?: number;
diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.ts
index 5b1f1ad2d..ebafb05b5 100644
--- a/sdk/src/ui/index.ts
+++ b/sdk/src/ui/index.ts
@@ -90,8 +90,10 @@ export {
export {
Interactable,
UIInteraction,
+ makeWidgetInteractable,
type InteractableData,
type UIInteractionData,
+ type WidgetInteractionInit,
} from './input/interactable';
export {
@@ -126,6 +128,21 @@ export {
type UISliderData,
} from './behavior/slider';
+export {
+ UIToggle,
+ createToggleSystem,
+ type UIToggleData,
+} from './behavior/toggle';
+
+export {
+ UIDropdown,
+ isDropdownOpen,
+ openDropdown,
+ closeDropdown,
+ createDropdownSystem,
+ type UIDropdownData,
+} from './behavior/dropdown';
+
// ─── Controllers + Gears (shared UI state) ──────────────────────────────────
export {
@@ -217,24 +234,25 @@ export {
buildText,
spawnUIEntity,
setUIVisible,
- makeWidgetInteractable,
FILL_AXIS,
type LinearFillDirection,
type UINodeInit,
type UIVisualInit,
type TextInit,
type UIEntityInit,
- type WidgetInteractionInit,
-} from './widgets/helpers';
+} from './core/compose';
+
+export {
+ interactionGears,
+ type ButtonStateVisual,
+} from './controller/interaction-gears';
export {
createButton,
setButtonState,
themeButtonStates,
- interactionGears,
type ButtonOptions,
type ButtonHandle,
- type ButtonStateVisual,
} from './widgets/button';
export {
@@ -381,6 +399,7 @@ export { applyThemeToWorld, switchTheme } from './behavior/theme-apply';
export { signal, derived, type Signal, type ReadonlySignal } from './binding/signal';
export { bind } from './binding/bind';
+export { bindWidgetValue } from './binding/two-way';
// Property Path Utilities
export {
diff --git a/sdk/src/ui/input/interactable.ts b/sdk/src/ui/input/interactable.ts
index 8da4364d2..970b9224c 100644
--- a/sdk/src/ui/input/interactable.ts
+++ b/sdk/src/ui/input/interactable.ts
@@ -7,6 +7,9 @@
* system). Foundation that controllers + drag/focus build on.
*/
import { defineBuiltin } from '../../component';
+import type { Entity } from '../../types';
+import type { World } from '../../world';
+import { Focusable } from './focusable';
export interface InteractableData {
enabled: boolean;
@@ -35,3 +38,33 @@ export const UIInteraction = defineBuiltin<UIInteractionData>('UIInteraction', {
justPressed: false,
justReleased: false,
}, { transient: true });
+
+export interface WidgetInteractionInit {
+ /** Start disabled (Interactable.enabled = false). */
+ disabled?: boolean;
+ /** Participate in Tab traversal + keyboard activation. Default true. */
+ focusable?: boolean;
+ /** Tab order within the focus ring. Default 0 (document order). */
+ tabIndex?: number;
+}
+
+/**
+ * The one interaction assembly every widget shares: a raycast-blocking
+ * Interactable plus (by default) a Focusable so the control is keyboard-
+ * reachable. Per-frame pointer state (UIInteraction) is transient — the
+ * hit-test system creates it on demand, widgets never insert it.
+ */
+export function makeWidgetInteractable(
+ world: World,
+ entity: Entity,
+ init: WidgetInteractionInit = {},
+): void {
+ world.insert(entity, Interactable, {
+ enabled: !init.disabled,
+ blockRaycast: true,
+ raycastTarget: true,
+ });
+ if (init.focusable ?? true) {
+ world.insert(entity, Focusable, { tabIndex: init.tabIndex ?? 0, isFocused: false });
+ }
+}
diff --git a/sdk/src/ui/text/text-input-plugin.ts b/sdk/src/ui/text/text-input-plugin.ts
index 6204535c0..307da09d9 100644
--- a/sdk/src/ui/text/text-input-plugin.ts
+++ b/sdk/src/ui/text/text-input-plugin.ts
@@ -15,7 +15,7 @@ import { UIEvents, UIEventQueue } from '../core/events';
import { Res } from '../../resource';
import { playModeOnly } from '../../env';
import { ensureComponent, getUINodeWidth, getUINodeHeight } from '../util/helpers';
-import { spawnUIEntity } from '../widgets/helpers';
+import { spawnUIEntity } from '../core/compose';
import { px } from '../core/dimension';
import { SdfTextRenderer } from './text-renderer';
import { measureWidth } from './layout';
diff --git a/sdk/src/ui/widgets/button.ts b/sdk/src/ui/widgets/button.ts
index e9d4c031f..ac9476ad3 100644
--- a/sdk/src/ui/widgets/button.ts
+++ b/sdk/src/ui/widgets/button.ts
@@ -11,29 +11,16 @@ import {
interactionController,
type UIControllerData,
} from '../controller/ui-controller';
-import { UIGear, gearBinding, type GearBinding, type GearValue } from '../controller/ui-gear';
-import { EasingType } from '../../animation/Easing';
+import { UIGear } from '../controller/ui-gear';
+import { interactionGears, type ButtonStateVisual } from '../controller/interaction-gears';
import { UIEventType, type UIEventQueue } from '../core/events';
import { themeColors, themeType } from '../theme/tokens';
import { markThemed } from '../theme/theme-style';
-import {
- spawnUIEntity,
- makeWidgetInteractable,
- type UINodeInit,
- type UIVisualInit,
- type TextInit,
-} from './helpers';
+import { spawnUIEntity, type UINodeInit, type UIVisualInit, type TextInit } from '../core/compose';
+import { makeWidgetInteractable } from '../input/interactable';
-/**
- * Visual overrides for a single button state. Omitted fields leave the
- * live value alone on that state (the gear's sparse-page semantics).
- */
-export interface ButtonStateVisual {
- color?: Color;
- sprite?: number;
- scale?: number;
-}
+export type { ButtonStateVisual };
export interface ButtonOptions {
world: World;
@@ -70,41 +57,6 @@ export interface ButtonHandle {
dispose(): void;
}
-/**
- * Fold the state-name → override record into per-field gear bindings on the
- * `$interaction` controller. A field a state doesn't override gets no page
- * entry there (sparse pages: the gear leaves it alone). Sprite swaps are
- * discrete and always snap; color and scale tween over `fadeDuration`.
- */
-export function interactionGears(
- states: Record<string, ButtonStateVisual>,
- fadeDuration = 0,
-): GearBinding[] {
- const color: Record<string, GearValue> = {};
- const sprite: Record<string, GearValue> = {};
- const scale: Record<string, GearValue> = {};
- for (const [page, v] of Object.entries(states)) {
- if (v.color !== undefined) color[page] = { ...v.color };
- if (v.sprite !== undefined) sprite[page] = v.sprite;
- if (v.scale !== undefined) scale[page] = { x: v.scale, y: v.scale, z: 1 };
- }
- const tween = fadeDuration > 0
- ? { easing: EasingType.Linear, duration: fadeDuration }
- : undefined;
-
- const bindings: GearBinding[] = [];
- if (Object.keys(color).length > 0) {
- bindings.push(gearBinding(INTERACTION_CONTROLLER, 'UIVisual', 'color', color, tween));
- }
- if (Object.keys(sprite).length > 0) {
- bindings.push(gearBinding(INTERACTION_CONTROLLER, 'UIVisual', 'texture', sprite));
- }
- if (Object.keys(scale).length > 0) {
- bindings.push(gearBinding(INTERACTION_CONTROLLER, 'Transform', 'scale', scale, tween));
- }
- return bindings;
-}
-
/** The canonical button state colors from the active theme's control roles —
* `createButton`'s default when the caller passes no `states`. `disabled` reuses
* the resting control fill at reduced alpha. */
diff --git a/sdk/src/ui/widgets/dialog.ts b/sdk/src/ui/widgets/dialog.ts
index 1469b51f0..2348679f1 100644
--- a/sdk/src/ui/widgets/dialog.ts
+++ b/sdk/src/ui/widgets/dialog.ts
@@ -3,7 +3,8 @@
import type { Entity } from '../../types';
import type { World } from '../../world';
-import { spawnUIEntity, makeWidgetInteractable, type UINodeInit, type UIVisualInit } from './helpers';
+import { spawnUIEntity, type UINodeInit, type UIVisualInit } from '../core/compose';
+import { makeWidgetInteractable } from '../input/interactable';
import { UINode, UIDisplay, type UINodeData } from '../core/ui-node';
import { px, percent } from '../core/dimension';
import { themeColors } from '../theme/tokens';
diff --git a/sdk/src/ui/widgets/dropdown.ts b/sdk/src/ui/widgets/dropdown.ts
index 6063da5a2..e2f15af2a 100644
--- a/sdk/src/ui/widgets/dropdown.ts
+++ b/sdk/src/ui/widgets/dropdown.ts
@@ -5,14 +5,20 @@ import type { World } from '../../world';
import { UIController, interactionController } from '../controller/ui-controller';
import { UIGear } from '../controller/ui-gear';
-import { interactionGears } from './button';
+import { interactionGears } from '../controller/interaction-gears';
import { UIEventType, type UIEventQueue } from '../core/events';
-import { Text, type TextData } from '../core/text';
-import { spawnUIEntity, makeWidgetInteractable, type UINodeInit, type UIVisualInit } from './helpers';
-import { px, percent } from '../core/dimension';
+import { spawnUIEntity, type UINodeInit } from '../core/compose';
+import { makeWidgetInteractable } from '../input/interactable';
import { themeColors } from '../theme/tokens';
import { markThemed } from '../theme/theme-style';
+import {
+ UIDropdown,
+ isDropdownOpen,
+ openDropdown,
+ closeDropdown,
+ type UIDropdownData,
+} from '../behavior/dropdown';
export interface DropdownOptions<T> {
world: World;
@@ -30,17 +36,15 @@ export interface DropdownOptions<T> {
hover?: Color;
pressed?: Color;
};
- /** Visual state overrides for option rows in the popup. */
- optionStates?: {
- normal?: Color;
- hover?: Color;
- pressed?: Color;
- };
- /** Popup panel background. */
- popupVisual?: UIVisualInit;
/** Height of each option row in pixels. Default 32. */
optionHeight?: number;
+ /** Start disabled. */
+ disabled?: boolean;
+ /** Participate in Tab traversal + arrow-key selection. Default true. */
+ focusable?: boolean;
+ tabIndex?: number;
+
onSelect?: (index: number, option: T, entity: Entity) => void;
}
@@ -50,42 +54,24 @@ export interface DropdownHandle<T> {
isOpen(): boolean;
getSelectedIndex(): number;
getSelected(): T;
- setSelectedIndex(index: number, silent?: boolean): void;
+ setSelectedIndex(index: number): void;
open(): void;
close(): void;
dispose(): void;
}
-/** Attach a `$interaction` controller + a color gear over its three pages. */
-function addInteractionStates(
- world: World,
- entity: Entity,
- colors: { normal: Color; hover: Color; pressed: Color },
-): void {
- world.insert(entity, UIController, {
- controllers: [interactionController(['normal', 'hover', 'pressed'])],
- });
- world.insert(entity, UIGear, {
- bindings: interactionGears({
- normal: { color: colors.normal },
- hover: { color: colors.hover },
- pressed: { color: colors.pressed },
- }),
- });
-}
-
/**
- * Dropdown: a button showing the current selection that opens a popup
- * with clickable option rows. Click an option to select it (popup
- * closes automatically). Click the button again to close without
- * selecting. Click-outside-to-close is not wired in v1 — callers can
- * call `close()` from their own global input layer if needed.
+ * Dropdown: a button showing the current selection that opens a popup with
+ * clickable option rows. State + behavior live in the {@link UIDropdown}
+ * component and its system: click toggles the popup, a click anywhere else
+ * closes it, arrow keys step the selection while focused, and the label
+ * follows `selectedIndex` for any writer. The factory adds the generic-type
+ * mapping (`options: T[]` + `optionToLabel`) on top.
*/
export function createDropdown<T>(opts: DropdownOptions<T>): DropdownHandle<T> {
const { world, events } = opts;
const labelOf = opts.optionToLabel ?? ((o: T) => String(o));
- const optionHeight = opts.optionHeight ?? 32;
- let selectedIndex = opts.selectedIndex ?? 0;
+ const selectedIndex = opts.selectedIndex ?? 0;
const c = themeColors();
const btnColors = {
@@ -101,8 +87,21 @@ export function createDropdown<T>(opts: DropdownOptions<T>): DropdownHandle<T> {
node: opts.node ?? { fill: true },
visual: { color: btnColors.normal },
});
- makeWidgetInteractable(world, button);
- addInteractionStates(world, button, btnColors);
+ makeWidgetInteractable(world, button, {
+ disabled: opts.disabled,
+ focusable: opts.focusable,
+ tabIndex: opts.tabIndex,
+ });
+ world.insert(button, UIController, {
+ controllers: [interactionController(['normal', 'hover', 'pressed'])],
+ });
+ world.insert(button, UIGear, {
+ bindings: interactionGears({
+ normal: { color: btnColors.normal },
+ hover: { color: btnColors.hover },
+ pressed: { color: btnColors.pressed },
+ }),
+ });
if (opts.buttonStates === undefined) {
markThemed(world, button, { states: { normal: 'control', hover: 'controlHover', pressed: 'controlActive' } });
}
@@ -111,132 +110,45 @@ export function createDropdown<T>(opts: DropdownOptions<T>): DropdownHandle<T> {
world,
parent: button,
node: { fill: true },
- text: { content: labelOf(opts.options[selectedIndex]!, selectedIndex), color: themeColors().text },
+ text: { content: labelOf(opts.options[selectedIndex]!, selectedIndex), color: c.text },
});
markThemed(world, label, { text: 'text' });
- let popupPanel: Entity | null = null;
- const optionUnsubs: Array<() => void> = [];
-
- function isOpen(): boolean {
- return popupPanel !== null;
- }
-
- function open(): void {
- if (popupPanel) return;
- const totalHeight = opts.options.length * optionHeight;
-
- // Resolve theme colors at open time — the popup is rebuilt per open, so a
- // construction-time capture would pin the theme active back then.
- const t = themeColors();
- const optColors = {
- normal: opts.optionStates?.normal ?? t.control,
- hover: opts.optionStates?.hover ?? t.primaryHover,
- pressed: opts.optionStates?.pressed ?? t.primaryActive,
- };
-
- popupPanel = spawnUIEntity({
- world,
- parent: button,
- // Below the button: absolute, full width, top at the button's bottom edge.
- node: {
- position: 1,
- insetLeft: px(0),
- insetRight: px(0),
- insetTop: percent(100),
- height: px(totalHeight),
- },
- visual: opts.popupVisual ?? { color: t.surfaceElevated },
- });
- if (!opts.popupVisual) markThemed(world, popupPanel, { visual: 'surfaceElevated' });
-
- for (let i = 0; i < opts.options.length; i++) {
- const index = i;
- const row = spawnOptionRow(index, optColors, t.text);
- const off = events.on(row, UIEventType.Click, () => selectAndClose(index));
- optionUnsubs.push(off);
- }
- }
-
- function spawnOptionRow(
- index: number,
- optColors: { normal: Color; hover: Color; pressed: Color },
- textColor: Color,
- ): Entity {
- const row = spawnUIEntity({
- world,
- parent: popupPanel!,
- // Stacked top-down: absolute, full width, row i at i*optionHeight.
- node: {
- position: 1,
- insetLeft: px(0),
- insetRight: px(0),
- insetTop: px(index * optionHeight),
- height: px(optionHeight),
- },
- visual: { color: optColors.normal },
- });
- // Rows are pointer-only: the popup is transient, so they stay out of
- // the Tab ring (keyboard option navigation is a later step).
- makeWidgetInteractable(world, row, { focusable: false });
- addInteractionStates(world, row, optColors);
- if (opts.optionStates === undefined) {
- markThemed(world, row, { states: { normal: 'control', hover: 'primaryHover', pressed: 'primaryActive' } });
- }
-
- const rowLabel = spawnUIEntity({
- world,
- parent: row,
- node: { fill: true },
- text: { content: labelOf(opts.options[index]!, index), color: textColor },
- });
- markThemed(world, rowLabel, { text: 'text' });
-
- return row;
- }
-
- function close(): void {
- if (!popupPanel) return;
- for (const off of optionUnsubs) off();
- optionUnsubs.length = 0;
- if (world.valid(popupPanel)) world.despawn(popupPanel);
- popupPanel = null;
- }
-
- function selectAndClose(index: number): void {
- close();
- setSelectedIndex(index, false);
- }
+ world.insert(button, UIDropdown, {
+ options: opts.options.map((o, i) => labelOf(o, i)),
+ selectedIndex,
+ optionHeight: opts.optionHeight ?? 32,
+ label,
+ });
- function setSelectedIndex(index: number, silent = false): void {
- if (index < 0 || index >= opts.options.length) return;
- if (index === selectedIndex) return;
- selectedIndex = index;
- const labelData = world.get(label, Text) as TextData;
- labelData.content = labelOf(opts.options[index]!, index);
- world.insert(label, Text, labelData);
- if (!silent) {
- opts.onSelect?.(index, opts.options[index]!, button);
- }
- }
+ const offSelect = opts.onSelect
+ ? events.on(button, UIEventType.Change, (ev) => {
+ const data = ev.data as { index?: number };
+ if (typeof data?.index !== 'number') return;
+ opts.onSelect!(data.index, opts.options[data.index]!, button);
+ })
+ : undefined;
- // Click on button toggles popup.
- const offButtonClick = events.on(button, UIEventType.Click, () => {
- isOpen() ? close() : open();
- });
+ const selected = () => (world.get(button, UIDropdown) as UIDropdownData).selectedIndex;
return {
entity: button,
labelEntity: label,
- isOpen,
- getSelectedIndex: () => selectedIndex,
- getSelected: () => opts.options[selectedIndex]!,
- setSelectedIndex,
- open,
- close,
+ isOpen: () => isDropdownOpen(world, button),
+ getSelectedIndex: selected,
+ getSelected: () => opts.options[selected()]!,
+ setSelectedIndex: (index: number) => {
+ if (index < 0 || index >= opts.options.length) return;
+ const d = world.get(button, UIDropdown) as UIDropdownData;
+ if (d.selectedIndex === index) return;
+ d.selectedIndex = index;
+ world.insert(button, UIDropdown, d);
+ },
+ open: () => openDropdown(world, events, button),
+ close: () => closeDropdown(world, button),
dispose: () => {
- offButtonClick();
- close();
+ offSelect?.();
+ closeDropdown(world, button);
if (world.valid(button)) world.despawn(button);
},
};
diff --git a/sdk/src/ui/widgets/list-view.ts b/sdk/src/ui/widgets/list-view.ts
index 71f469992..811737f34 100644
--- a/sdk/src/ui/widgets/list-view.ts
+++ b/sdk/src/ui/widgets/list-view.ts
@@ -21,7 +21,8 @@ import { UINode, UIPositionType, type UINodeData } from '../core/ui-node';
import { px, auto } from '../core/dimension';
import { UIMask, MaskMode } from '../core/ui-mask';
-import { spawnUIEntity, setUIVisible, makeWidgetInteractable, type UINodeInit, type UIVisualInit } from './helpers';
+import { spawnUIEntity, setUIVisible, type UINodeInit, type UIVisualInit } from '../core/compose';
+import { makeWidgetInteractable } from '../input/interactable';
import {
type DataSource,
diff --git a/sdk/src/ui/widgets/prefabs/Dropdown.esprefab b/sdk/src/ui/widgets/prefabs/Dropdown.esprefab
index cc14a154a..6ec74ad0b 100644
--- a/sdk/src/ui/widgets/prefabs/Dropdown.esprefab
+++ b/sdk/src/ui/widgets/prefabs/Dropdown.esprefab
@@ -226,6 +226,19 @@
"pressed": "controlActive"
}
}
+ },
+ {
+ "type": "UIDropdown",
+ "data": {
+ "options": [
+ "One",
+ "Two",
+ "Three"
+ ],
+ "selectedIndex": 0,
+ "optionHeight": 30,
+ "label": "1"
+ }
}
],
"visible": true
diff --git a/sdk/src/ui/widgets/prefabs/Toggle.esprefab b/sdk/src/ui/widgets/prefabs/Toggle.esprefab
index 0de409eea..2dd2f73d8 100644
--- a/sdk/src/ui/widgets/prefabs/Toggle.esprefab
+++ b/sdk/src/ui/widgets/prefabs/Toggle.esprefab
@@ -242,6 +242,13 @@
"focused": "controlHover"
}
}
+ },
+ {
+ "type": "UIToggle",
+ "data": {
+ "isOn": true,
+ "check": "1"
+ }
}
],
"visible": true
diff --git a/sdk/src/ui/widgets/prefabs/generated.ts b/sdk/src/ui/widgets/prefabs/generated.ts
index 3f4cbb408..fba4c8753 100644
--- a/sdk/src/ui/widgets/prefabs/generated.ts
+++ b/sdk/src/ui/widgets/prefabs/generated.ts
@@ -659,6 +659,13 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {
"focused": "controlHover"
}
}
+ },
+ {
+ "type": "UIToggle",
+ "data": {
+ "isOn": true,
+ "check": "1"
+ }
}
],
"visible": true
@@ -2417,6 +2424,19 @@ export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = {
"pressed": "controlActive"
}
}
+ },
+ {
+ "type": "UIDropdown",
+ "data": {
+ "options": [
+ "One",
+ "Two",
+ "Three"
+ ],
+ "selectedIndex": 0,
+ "optionHeight": 30,
+ "label": "1"
+ }
}
],
"visible": true
diff --git a/sdk/src/ui/widgets/progress.ts b/sdk/src/ui/widgets/progress.ts
index cd75421a8..03ebe9d70 100644
--- a/sdk/src/ui/widgets/progress.ts
+++ b/sdk/src/ui/widgets/progress.ts
@@ -11,13 +11,7 @@ import {
type UIVisualData,
} from '../core/ui-visual';
-import {
- spawnUIEntity,
- FILL_AXIS,
- type UINodeInit,
- type UIVisualInit,
- type LinearFillDirection,
-} from './helpers';
+import { spawnUIEntity, FILL_AXIS, type UINodeInit, type UIVisualInit, type LinearFillDirection } from '../core/compose';
import { themeColors } from '../theme/tokens';
import { markThemed } from '../theme/theme-style';
diff --git a/sdk/src/ui/widgets/scroll-view.ts b/sdk/src/ui/widgets/scroll-view.ts
index 3be132483..afb437efe 100644
--- a/sdk/src/ui/widgets/scroll-view.ts
+++ b/sdk/src/ui/widgets/scroll-view.ts
@@ -17,7 +17,8 @@ import { px } from '../core/dimension';
import { UIMask, MaskMode } from '../core/ui-mask';
import { ScrollContainer } from '../collection/scroll-container';
-import { spawnUIEntity, makeWidgetInteractable, type UINodeInit, type UIVisualInit } from './helpers';
+import { spawnUIEntity, type UINodeInit, type UIVisualInit } from '../core/compose';
+import { makeWidgetInteractable } from '../input/interactable';
import type { ListViewHost } from './list-view';
export interface ScrollViewOptions {
diff --git a/sdk/src/ui/widgets/slider.ts b/sdk/src/ui/widgets/slider.ts
index 7d329d1b1..395f6784c 100644
--- a/sdk/src/ui/widgets/slider.ts
+++ b/sdk/src/ui/widgets/slider.ts
@@ -7,7 +7,8 @@ import { px, percent } from '../core/dimension';
import { UIVisualType } from '../core/ui-visual';
import { UIEventType, type UIEventQueue } from '../core/events';
-import { spawnUIEntity, makeWidgetInteractable, FILL_AXIS, type UINodeInit, type UIVisualInit } from './helpers';
+import { spawnUIEntity, FILL_AXIS, type UINodeInit, type UIVisualInit } from '../core/compose';
+import { makeWidgetInteractable } from '../input/interactable';
import { themeColors } from '../theme/tokens';
import { markThemed } from '../theme/theme-style';
import { UISlider, sliderClamp, sliderFraction, type UISliderData } from '../behavior/slider';
diff --git a/sdk/src/ui/widgets/text-input.ts b/sdk/src/ui/widgets/text-input.ts
index a23e84b07..afa375514 100644
--- a/sdk/src/ui/widgets/text-input.ts
+++ b/sdk/src/ui/widgets/text-input.ts
@@ -7,7 +7,8 @@ import { px } from '../core/dimension';
import { type UIEventQueue } from '../core/events';
import { TextInput, type TextInputData } from '../text/text-input';
-import { spawnUIEntity, makeWidgetInteractable, type UINodeInit } from './helpers';
+import { spawnUIEntity, type UINodeInit } from '../core/compose';
+import { makeWidgetInteractable } from '../input/interactable';
import { themeColors, themeType } from '../theme/tokens';
import { markThemed } from '../theme/theme-style';
diff --git a/sdk/src/ui/widgets/toggle.ts b/sdk/src/ui/widgets/toggle.ts
index f5ca6b769..c49c3d484 100644
--- a/sdk/src/ui/widgets/toggle.ts
+++ b/sdk/src/ui/widgets/toggle.ts
@@ -4,12 +4,13 @@ import type { Color, Entity } from '../../types';
import type { World } from '../../world';
import { UIEventType, type UIEventQueue } from '../core/events';
-import { Interactable, type InteractableData } from '../input/interactable';
+import type { ButtonStateVisual } from '../controller/interaction-gears';
-import { createButton, type ButtonStateVisual } from './button';
-import { spawnUIEntity, setUIVisible, type UINodeInit, type UIVisualInit } from './helpers';
+import { createButton } from './button';
+import { spawnUIEntity, setUIVisible, type UINodeInit, type UIVisualInit } from '../core/compose';
import { themeColors } from '../theme/tokens';
import { markThemed } from '../theme/theme-style';
+import { UIToggle, type UIToggleData } from '../behavior/toggle';
export interface ToggleOptions {
world: World;
@@ -49,7 +50,7 @@ export interface ToggleOptions {
export interface ToggleHandle {
readonly entity: Entity;
isOn(): boolean;
- setIsOn(value: boolean, silent?: boolean): void;
+ setIsOn(value: boolean): void;
setDisabled(disabled: boolean): void;
dispose(): void;
}
@@ -57,11 +58,13 @@ export interface ToggleHandle {
/**
* Compose a Toggle from a Button (interaction + visual states) plus a
* separate child entity driven by `isOn` for the check-mark visual.
- * Click flips isOn and emits `change` on the button entity.
+ * State + flipping live in the {@link UIToggle} component and its behavior
+ * system — click, `setIsOn`, a binding, or the editor inspector all flip the
+ * indicator and emit `change` identically.
*/
export function createToggle(opts: ToggleOptions): ToggleHandle {
const { world, events } = opts;
- let isOn = opts.isOn ?? false;
+ const isOn = opts.isOn ?? false;
const btn = createButton({
world,
@@ -91,29 +94,26 @@ export function createToggle(opts: ToggleOptions): ToggleHandle {
if (opts.check?.color === undefined) markThemed(world, check, { visual: 'primary' });
setUIVisible(world, check, isOn);
+ world.insert(button, UIToggle, { isOn, check });
- const offClick = events.on(button, UIEventType.Click, () => {
- const interactable = world.get(button, Interactable) as InteractableData;
- if (interactable.enabled) setIsOn(!isOn);
- });
-
- function setIsOn(value: boolean, silent = false): void {
- if (value === isOn) return;
- isOn = value;
- setUIVisible(world, check, isOn);
- if (!silent) {
- events.emit(button, UIEventType.Change, { isOn });
- opts.onChange?.(isOn, button);
- }
- }
+ const offChange = opts.onChange
+ ? events.on(button, UIEventType.Change, (ev) => {
+ opts.onChange!((ev.data as { isOn: boolean }).isOn, button);
+ })
+ : undefined;
return {
entity: button,
- isOn: () => isOn,
- setIsOn,
+ isOn: () => (world.get(button, UIToggle) as UIToggleData).isOn,
+ setIsOn: (value: boolean) => {
+ const d = world.get(button, UIToggle) as UIToggleData;
+ if (d.isOn === value) return;
+ d.isOn = value;
+ world.insert(button, UIToggle, d);
+ },
setDisabled: btn.setDisabled,
dispose: () => {
- offClick();
+ offChange?.();
btn.dispose();
},
};
diff --git a/sdk/tests/ui-list-view-widget.test.ts b/sdk/tests/ui-list-view-widget.test.ts
index 72ec4735a..c618c2b3c 100644
--- a/sdk/tests/ui-list-view-widget.test.ts
+++ b/sdk/tests/ui-list-view-widget.test.ts
@@ -12,7 +12,7 @@ import { App } from '../src/app';
import { UICameraInfo } from '../src/ui/core/ui-camera-info';
import { uiPlugin } from '../src/ui/ui-plugin';
import { createListView } from '../src/ui/widgets/list-view';
-import { spawnUIEntity } from '../src/ui/widgets/helpers';
+import { spawnUIEntity } from '../src/ui/core/compose';
import { arrayDataSource } from '../src/ui/collection/data-source';
import { px } from '../src/ui/core/dimension';
import type { ESEngineModule, CppRegistry } from '../src/wasm';
diff --git a/sdk/tests/ui-slider-dropdown.test.ts b/sdk/tests/ui-slider-dropdown.test.ts
index 2b319303f..cd22e9d34 100644
--- a/sdk/tests/ui-slider-dropdown.test.ts
+++ b/sdk/tests/ui-slider-dropdown.test.ts
@@ -7,6 +7,7 @@ import {
UISlider,
Focusable,
createDropdown,
+ createDropdownSystem,
UIEventQueue,
UIEventType,
UIRect,
@@ -199,10 +200,17 @@ describe('createSlider', () => {
describe('createDropdown', () => {
let world: MockWorld;
let events: UIEventQueue;
+ let keys: Set<string>;
+ let tick: () => void;
beforeEach(() => {
world = createMockWorld();
events = new UIEventQueue();
+ keys = new Set();
+ const sys = createDropdownSystem(world as unknown as World, events);
+ const input = { isKeyPressed: (k: string) => keys.has(k) };
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ tick = () => (sys as any)._fn(input);
});
it('shows the current selection label', () => {
@@ -239,22 +247,56 @@ describe('createDropdown', () => {
expect(dd.isOpen()).toBe(false);
});
- it('setSelectedIndex updates the label text and fires onSelect (unless silent)', () => {
+ it('setSelectedIndex writes the component; the system syncs the label and fires onSelect', () => {
const onSelect = vi.fn();
const dd = createDropdown({
world: world as unknown as World, events,
options: ['x', 'y', 'z'],
onSelect,
});
+ tick(); // initial paint — no change event
dd.setSelectedIndex(2);
+ tick();
expect(dd.getSelectedIndex()).toBe(2);
expect((world.get(dd.labelEntity, Text) as { content: string }).content).toBe('z');
expect(onSelect).toHaveBeenCalledWith(2, 'z', dd.entity);
+ });
- dd.setSelectedIndex(0, true);
+ it('a click outside the dropdown closes the popup', () => {
+ const dd = createDropdown({
+ world: world as unknown as World, events,
+ options: ['a', 'b'],
+ });
+ dd.open();
+ expect(dd.isOpen()).toBe(true);
+
+ const elsewhere = world.spawn();
+ events.emit(elsewhere, UIEventType.Click);
+ expect(dd.isOpen()).toBe(false);
+ });
+
+ it('arrow keys step the selection while focused and closed', () => {
+ const dd = createDropdown({
+ world: world as unknown as World, events,
+ options: ['a', 'b', 'c'],
+ });
+ tick();
+
+ const f = world.get(dd.entity, Focusable) as { isFocused: boolean };
+ f.isFocused = true;
+ world.insert(dd.entity, Focusable, f);
+
+ keys.add('ArrowDown');
+ tick();
+ expect(dd.getSelectedIndex()).toBe(1);
+
+ keys.clear();
+ keys.add('ArrowUp');
+ tick();
expect(dd.getSelectedIndex()).toBe(0);
- expect(onSelect).toHaveBeenCalledTimes(1); // silent
+ tick();
+ expect(dd.getSelectedIndex()).toBe(0); // clamped at the first option
});
it('open() / close() imperatively toggle the popup', () => {
diff --git a/sdk/tests/ui-two-way-binding.test.ts b/sdk/tests/ui-two-way-binding.test.ts
new file mode 100644
index 000000000..109f49ad2
--- /dev/null
+++ b/sdk/tests/ui-two-way-binding.test.ts
@@ -0,0 +1,144 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file bindWidgetValue — the two-way edge between a Signal and a widget's
+ * value component, with the behavior system in the loop.
+ */
+import { describe, it, expect, beforeEach } from 'vitest';
+import {
+ signal,
+ bindWidgetValue,
+ createSlider,
+ createSliderSystem,
+ createToggle,
+ createToggleSystem,
+ UISlider,
+ UIToggle,
+ UIEventQueue,
+ UIEventType,
+} from '../src/ui';
+import type { Entity } from '../src/types';
+import type { World } from '../src/world';
+
+interface MockWorld {
+ _entities: Set<number>;
+ _components: Map<number, Map<object, unknown>>;
+ _despawnListeners: Array<(e: Entity) => void>;
+ spawn(): Entity;
+ despawn(e: Entity): void;
+ valid(e: Entity): boolean;
+ setParent(c: Entity, p: Entity): void;
+ has(e: Entity, c: object): boolean;
+ get(e: Entity, c: object): unknown;
+ insert(e: Entity, c: object, data: unknown): void;
+ getEntitiesWithComponents(cs: object[]): Entity[];
+ onDespawn(cb: (e: Entity) => void): () => void;
+}
+
+function createMockWorld(): MockWorld {
+ let nextId = 1;
+ const w: MockWorld = {
+ _entities: new Set(),
+ _components: new Map(),
+ _despawnListeners: [],
+ spawn() {
+ const id = nextId++;
+ w._entities.add(id);
+ w._components.set(id, new Map());
+ return id as Entity;
+ },
+ despawn(e) {
+ for (const cb of w._despawnListeners) cb(e);
+ w._entities.delete(e as number);
+ w._components.delete(e as number);
+ },
+ valid(e) { return w._entities.has(e as number); },
+ setParent() { /* not needed */ },
+ has(e, c) { return w._components.get(e as number)?.has(c) ?? false; },
+ get(e, c) { return w._components.get(e as number)?.get(c); },
+ insert(e, c, d) { w._components.get(e as number)?.set(c, d); },
+ getEntitiesWithComponents(cs) {
+ return [...w._entities].filter((e) =>
+ cs.every((c) => w._components.get(e)?.has(c))) as Entity[];
+ },
+ onDespawn(cb) {
+ w._despawnListeners.push(cb);
+ return () => {
+ const i = w._despawnListeners.indexOf(cb);
+ if (i !== -1) w._despawnListeners.splice(i, 1);
+ };
+ },
+ };
+ return w;
+}
+
+const idleInput = { isMouseButtonDown: () => false, isKeyPressed: () => false };
+const noCamera = { valid: false };
+
+describe('bindWidgetValue', () => {
+ let world: MockWorld;
+ let events: UIEventQueue;
+
+ beforeEach(() => {
+ world = createMockWorld();
+ events = new UIEventQueue();
+ });
+
+ it('signal → UISlider.value → visuals; input change → signal (round trip settles)', () => {
+ const sys = createSliderSystem(world as unknown as World, events);
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const tick = () => (sys as any)._fn(idleInput, noCamera);
+
+ const slider = createSlider({
+ world: world as unknown as World, events,
+ min: 0, max: 100, value: 25,
+ });
+ tick();
+
+ const volume = signal(50);
+ const off = bindWidgetValue(
+ world as unknown as World, events, slider.entity, UISlider, 'value', volume);
+
+ // Down: the bind seeds the component immediately.
+ expect(slider.getValue()).toBe(50);
+ tick();
+
+ // Down again on set.
+ volume.set(80);
+ expect(slider.getValue()).toBe(80);
+ tick();
+
+ // Up: a widget-side write flows into the signal through change.
+ slider.setValue(30);
+ tick();
+ expect(volume.get()).toBe(30);
+
+ off();
+ volume.set(99);
+ expect(slider.getValue()).toBe(30); // unbound
+ });
+
+ it('signal ↔ UIToggle.isOn with the isOn payload key', () => {
+ const sys = createToggleSystem(world as unknown as World, events);
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const tick = () => (sys as any)._fn();
+
+ const toggle = createToggle({
+ world: world as unknown as World, events,
+ interactionStates: { normal: {}, hover: {}, pressed: {} },
+ isOn: false,
+ });
+ tick();
+
+ const muted = signal(true);
+ bindWidgetValue(
+ world as unknown as World, events, toggle.entity, UIToggle, 'isOn', muted);
+ expect(toggle.isOn()).toBe(true);
+ tick();
+
+ // Up: a click flips the component; change writes the signal.
+ events.emit(toggle.entity, UIEventType.Click);
+ tick();
+ expect(muted.get()).toBe(false);
+ });
+});
diff --git a/sdk/tests/ui-widget-prefabs.gen.test.ts b/sdk/tests/ui-widget-prefabs.gen.test.ts
index 5f660764c..6826f88d8 100644
--- a/sdk/tests/ui-widget-prefabs.gen.test.ts
+++ b/sdk/tests/ui-widget-prefabs.gen.test.ts
@@ -15,8 +15,10 @@ import { createDropdown } from '../src/ui/widgets/dropdown';
import { createDialog } from '../src/ui/widgets/dialog';
import { createTextInput } from '../src/ui/widgets/text-input';
import { UISlider } from '../src/ui/behavior/slider';
+import { UIToggle } from '../src/ui/behavior/toggle';
+import { UIDropdown } from '../src/ui/behavior/dropdown';
import { registerComponent } from '../src/component';
-import { spawnUIEntity } from '../src/ui/widgets/helpers';
+import { spawnUIEntity } from '../src/ui/core/compose';
import { UIMask, MaskMode } from '../src/ui/core/ui-mask';
import { Interactable } from '../src/ui/input/interactable';
import { themeColors } from '../src/ui/theme/tokens';
@@ -79,7 +81,8 @@ describe('UI widget prefab codegen', () => {
expect(label.parent).toBe(prefab.rootEntityId);
});
- it('Toggle: box + checkmark child', () => {
+ it('Toggle: box + checkmark child, behavior in UIToggle', () => {
+ registerComponent('UIToggle', UIToggle);
const prefab = generate('Toggle', (world) =>
createToggle({
world, events: noEvents,
@@ -87,8 +90,12 @@ describe('UI widget prefab codegen', () => {
isOn: true,
}).entity as unknown as number,
);
- expect(typesOf(prefab, prefab.rootEntityId)).toEqual(expect.arrayContaining(['UINode', 'Interactable', 'UIGear']));
- expect(entityById(prefab, prefab.rootEntityId).children.length).toBeGreaterThanOrEqual(1);
+ expect(typesOf(prefab, prefab.rootEntityId)).toEqual(expect.arrayContaining(
+ ['UINode', 'Interactable', 'UIGear', 'UIToggle']));
+ const rootEnt = entityById(prefab, prefab.rootEntityId);
+ const toggleComp = rootEnt.components.find((cc) => cc.type === 'UIToggle')!;
+ // The check-indicator ref is remapped to a prefab-local id.
+ expect(rootEnt.children).toContain(toggleComp.data.check);
});
it('Slider: track + fill + handle', () => {
@@ -151,7 +158,8 @@ describe('UI widget prefab codegen', () => {
expect(entityById(prefab, prefab.rootEntityId).children.length).toBe(1);
});
- it('Dropdown: button + label (popup lives outside the subtree)', () => {
+ it('Dropdown: button + label, options + selection in UIDropdown (popup is runtime-only)', () => {
+ registerComponent('UIDropdown', UIDropdown);
const prefab = generate('Dropdown', (world) =>
createDropdown<string>({
world, events: noEvents,
@@ -159,7 +167,12 @@ describe('UI widget prefab codegen', () => {
options: ['One', 'Two', 'Three'], optionToLabel: (o) => o, optionHeight: 30,
}).entity as unknown as number,
);
- expect(typesOf(prefab, prefab.rootEntityId)).toEqual(expect.arrayContaining(['UINode', 'Interactable']));
+ const rootEnt = entityById(prefab, prefab.rootEntityId);
+ expect(typesOf(prefab, prefab.rootEntityId)).toEqual(expect.arrayContaining(
+ ['UINode', 'Interactable', 'UIDropdown']));
+ const ddComp = rootEnt.components.find((cc) => cc.type === 'UIDropdown')!;
+ expect(ddComp.data.options).toEqual(['One', 'Two', 'Three']);
+ expect(rootEnt.children).toContain(ddComp.data.label);
});
it('ListView: a clipped viewport shell (items are populated by createListView in code)', () => {
diff --git a/sdk/tests/ui-widgets.test.ts b/sdk/tests/ui-widgets.test.ts
index 3f311633c..e53c7073d 100644
--- a/sdk/tests/ui-widgets.test.ts
+++ b/sdk/tests/ui-widgets.test.ts
@@ -21,6 +21,8 @@ import {
UIEventType,
UIDisplay,
UIDialog,
+ UIToggle,
+ createToggleSystem,
themeColors,
type UIControllerData,
type UIGearData,
@@ -45,6 +47,7 @@ interface MockWorld {
has(e: Entity, c: object): boolean;
get(e: Entity, c: object): unknown;
insert(e: Entity, c: object, data: unknown): void;
+ getEntitiesWithComponents(cs: object[]): Entity[];
onDespawn(cb: (e: Entity) => void): () => void;
}
@@ -84,6 +87,10 @@ function createMockWorld(): MockWorld {
insert(e, c, data) {
w._components.get(e as number)?.set(c, data);
},
+ getEntitiesWithComponents(cs) {
+ return [...w._entities].filter((e) =>
+ cs.every((c) => w._components.get(e)?.has(c))) as Entity[];
+ },
onDespawn(cb) {
w._despawnListeners.push(cb);
return () => {
@@ -257,13 +264,17 @@ describe('interactionGears', () => {
describe('createToggle', () => {
let world: MockWorld;
let events: UIEventQueue;
+ let tick: () => void;
beforeEach(() => {
world = createMockWorld();
events = new UIEventQueue();
+ const sys = createToggleSystem(world as unknown as World, events);
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ tick = () => (sys as any)._fn();
});
- it('starts with the provided isOn value', () => {
+ it('starts with the provided isOn value, carried in the UIToggle component', () => {
const on = createToggle({
world: world as unknown as World,
events,
@@ -271,9 +282,10 @@ describe('createToggle', () => {
isOn: true,
});
expect(on.isOn()).toBe(true);
+ expect((world.get(on.entity, UIToggle) as { isOn: boolean }).isOn).toBe(true);
});
- it('flips isOn on click and emits change', () => {
+ it('flips isOn on click through the behavior system and emits change', () => {
const onChange = vi.fn();
const toggle = createToggle({
world: world as unknown as World,
@@ -282,14 +294,16 @@ describe('createToggle', () => {
isOn: false,
onChange,
});
+ tick(); // initial paint — no change event
events.emit(toggle.entity, UIEventType.Click);
-
expect(toggle.isOn()).toBe(true);
+
+ tick();
expect(onChange).toHaveBeenCalledWith(true, toggle.entity);
});
- it('setIsOn emits change unless silent is true', () => {
+ it('setIsOn writes the component; the system emits one change per transition', () => {
const onChange = vi.fn();
const toggle = createToggle({
world: world as unknown as World,
@@ -297,12 +311,27 @@ describe('createToggle', () => {
interactionStates: { normal: {}, hover: {}, pressed: {} },
onChange,
});
+ tick();
toggle.setIsOn(true);
+ tick();
expect(onChange).toHaveBeenCalledTimes(1);
- toggle.setIsOn(false, true);
+ toggle.setIsOn(true); // no-op
+ tick();
expect(onChange).toHaveBeenCalledTimes(1);
+ expect(toggle.isOn()).toBe(true);
+ });
+
+ it('ignores clicks while disabled', () => {
+ const toggle = createToggle({
+ world: world as unknown as World,
+ events,
+ interactionStates: { normal: {}, hover: {}, pressed: {} },
+ disabled: true,
+ });
+ tick();
+ events.emit(toggle.entity, UIEventType.Click);
expect(toggle.isOn()).toBe(false);
});