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): add Button, Toggle, Progress, Dialog widget factories

esengine372c16c541d2
diff --git a/sdk/src/ui2/index.ts b/sdk/src/ui2/index.ts
index bd1fdcf76..39d4b022e 100644
--- a/sdk/src/ui2/index.ts
+++ b/sdk/src/ui2/index.ts
@@ -131,3 +131,43 @@ export {
type ListViewOptions,
type ListViewItemTemplate,
} from './collection/list-view';
+
+// Widgets
+
+export {
+ identityTransform,
+ buildUIRect,
+ buildUIRenderer,
+ buildText,
+ spawnUIEntity,
+ setUIVisible,
+ type UIRectInit,
+ type UIRendererInit,
+ type TextInit,
+ type UIEntityInit,
+} from './widgets/helpers';
+
+export {
+ createButton,
+ setButtonState,
+ type ButtonOptions,
+ type ButtonStateVisual,
+} from './widgets/button';
+
+export {
+ createToggle,
+ type ToggleOptions,
+ type ToggleHandle,
+} from './widgets/toggle';
+
+export {
+ createProgress,
+ type ProgressOptions,
+ type ProgressHandle,
+} from './widgets/progress';
+
+export {
+ createDialog,
+ type DialogOptions,
+ type DialogHandle,
+} from './widgets/dialog';
diff --git a/sdk/src/ui2/widgets/button.ts b/sdk/src/ui2/widgets/button.ts
new file mode 100644
index 000000000..5935aa915
--- /dev/null
+++ b/sdk/src/ui2/widgets/button.ts
@@ -0,0 +1,157 @@
+import type { Color, Entity } from '../../types';
+import type { World } from '../../world';
+
+import { Interactable, UIInteraction } from '../behavior/interactable';
+import { StateMachine } from '../behavior/state-machine';
+import {
+ StateVisuals,
+ TransitionFlag,
+ type StateVisualsData,
+} from '../behavior/state-visuals';
+import { UIEventType, type UIEventQueue } from '../core/events';
+
+import {
+ spawnUIEntity,
+ type UIRectInit,
+ type UIRendererInit,
+ type TextInit,
+} from './helpers';
+
+/**
+ * Visual overrides for a single button state. Omitted fields stay at
+ * their slot default (color white, scale 1, no sprite).
+ */
+export interface ButtonStateVisual {
+ color?: Color;
+ sprite?: number;
+ scale?: number;
+}
+
+export interface ButtonOptions {
+ world: World;
+ events: UIEventQueue;
+ parent?: Entity;
+ rect?: UIRectInit;
+ /** Background renderer config. Default: solid white quad. */
+ background?: UIRendererInit;
+ /** Label text. Omit to skip spawning a child label entity. */
+ text?: string | TextInit;
+ /**
+ * Map of state name (e.g. "normal", "hover", "pressed", "disabled")
+ * to its visual override. The Interactable driver writes the four
+ * canonical state names; callers may add more (e.g. "loading") and
+ * flip them manually via `setState`.
+ */
+ states: Record<string, ButtonStateVisual>;
+ /** Combination of TransitionFlag values. Default: ColorTint. */
+ transitionFlags?: number;
+ /** Lerp time for ColorTint/Scale transitions. Default 0 (snap). */
+ fadeDuration?: number;
+ /** Start in the disabled state (Interactable.enabled = false). */
+ disabled?: boolean;
+ onClick?: (entity: Entity) => void;
+}
+
+const MAX_STATE_SLOTS = 8;
+
+function writeSlots(
+ data: StateVisualsData,
+ states: Record<string, ButtonStateVisual>,
+): void {
+ const names = Object.keys(states);
+ if (names.length > MAX_STATE_SLOTS) {
+ throw new Error(
+ `[createButton] up to ${MAX_STATE_SLOTS} states are supported, got ${names.length}`,
+ );
+ }
+ const record = data as unknown as Record<string, unknown>;
+ for (let i = 0; i < names.length; i++) {
+ const name = names[i];
+ const slot = states[name]!;
+ record[`slot${i}Name`] = name;
+ record[`slot${i}Color`] = slot.color ?? { r: 1, g: 1, b: 1, a: 1 };
+ record[`slot${i}Sprite`] = slot.sprite ?? 0;
+ record[`slot${i}Scale`] = slot.scale ?? 1;
+ }
+}
+
+/**
+ * Spawn a clickable button entity composed of Interactable +
+ * StateMachine + StateVisuals, optionally with a child Text label.
+ *
+ * Click is detected via state_changed (`pressed` → `hover`): the
+ * canonical "released while still over the button" gesture.
+ */
+export function createButton(opts: ButtonOptions): Entity {
+ const { world, events } = opts;
+
+ const entity = spawnUIEntity({
+ world,
+ parent: opts.parent,
+ rect: opts.rect,
+ renderer: opts.background ?? {},
+ });
+
+ world.insert(entity, Interactable, {
+ enabled: !opts.disabled,
+ blockRaycast: true,
+ raycastTarget: true,
+ });
+ world.insert(entity, UIInteraction, {
+ hovered: false, pressed: false, justPressed: false, justReleased: false,
+ });
+ world.insert(entity, StateMachine, {
+ current: opts.disabled ? 'disabled' : 'normal',
+ previous: '',
+ });
+
+ const visuals: StateVisualsData = {
+ targetGraphic: 0 as Entity,
+ transitionFlags: opts.transitionFlags ?? TransitionFlag.ColorTint,
+ fadeDuration: opts.fadeDuration ?? 0,
+ slot0Name: '', slot0Color: { r: 1, g: 1, b: 1, a: 1 }, slot0Sprite: 0, slot0Scale: 1,
+ slot1Name: '', slot1Color: { r: 1, g: 1, b: 1, a: 1 }, slot1Sprite: 0, slot1Scale: 1,
+ slot2Name: '', slot2Color: { r: 1, g: 1, b: 1, a: 1 }, slot2Sprite: 0, slot2Scale: 1,
+ slot3Name: '', slot3Color: { r: 1, g: 1, b: 1, a: 1 }, slot3Sprite: 0, slot3Scale: 1,
+ slot4Name: '', slot4Color: { r: 1, g: 1, b: 1, a: 1 }, slot4Sprite: 0, slot4Scale: 1,
+ slot5Name: '', slot5Color: { r: 1, g: 1, b: 1, a: 1 }, slot5Sprite: 0, slot5Scale: 1,
+ slot6Name: '', slot6Color: { r: 1, g: 1, b: 1, a: 1 }, slot6Sprite: 0, slot6Scale: 1,
+ slot7Name: '', slot7Color: { r: 1, g: 1, b: 1, a: 1 }, slot7Sprite: 0, slot7Scale: 1,
+ };
+ writeSlots(visuals, opts.states);
+ world.insert(entity, StateVisuals, visuals);
+
+ if (opts.text !== undefined) {
+ const textInit = typeof opts.text === 'string' ? { content: opts.text } : opts.text;
+ spawnUIEntity({
+ world,
+ parent: entity,
+ rect: { anchorMin: { x: 0, y: 0 }, anchorMax: { x: 1, y: 1 } },
+ text: textInit,
+ });
+ }
+
+ if (opts.onClick) {
+ const handler = opts.onClick;
+ events.on(entity, UIEventType.StateChanged, (event) => {
+ const data = event.data as { from: string; to: string };
+ if (data.from === 'pressed' && data.to === 'hover') {
+ handler(entity);
+ }
+ });
+ }
+
+ return entity;
+}
+
+/**
+ * Imperatively set a button's state string. Useful for custom states
+ * like "loading" that the Interactable driver does not manage.
+ */
+export function setButtonState(world: World, entity: Entity, state: string): void {
+ if (!world.has(entity, StateMachine)) return;
+ const sm = world.get(entity, StateMachine) as { current: string; previous: string };
+ if (sm.current === state) return;
+ sm.current = state;
+ world.insert(entity, StateMachine, sm);
+}
diff --git a/sdk/src/ui2/widgets/dialog.ts b/sdk/src/ui2/widgets/dialog.ts
new file mode 100644
index 000000000..3f2e4cc9d
--- /dev/null
+++ b/sdk/src/ui2/widgets/dialog.ts
@@ -0,0 +1,110 @@
+import type { Color, Entity } from '../../types';
+import type { World } from '../../world';
+
+import { Interactable, UIInteraction } from '../behavior/interactable';
+
+import { spawnUIEntity, setUIVisible, type UIRectInit, type UIRendererInit } from './helpers';
+
+export interface DialogOptions {
+ world: World;
+ parent?: Entity;
+ /** Full-viewport backdrop rect. Default: stretched to parent. */
+ backdropRect?: UIRectInit;
+ /** Backdrop visuals. Default: 50% black overlay. */
+ backdropRenderer?: UIRendererInit;
+ /** Panel rect (the modal box). Default: 400x300 centered. */
+ panelRect?: UIRectInit;
+ panelRenderer?: UIRendererInit;
+ /** Start hidden. Default true. */
+ startHidden?: boolean;
+}
+
+export interface DialogHandle {
+ readonly backdropEntity: Entity;
+ readonly panelEntity: Entity;
+ isOpen(): boolean;
+ open(): void;
+ close(): void;
+ dispose(): void;
+}
+
+const DEFAULT_BACKDROP_COLOR: Color = { r: 0, g: 0, b: 0, a: 0.5 };
+const DEFAULT_PANEL_COLOR: Color = { r: 0.16, g: 0.16, b: 0.18, a: 1 };
+
+/**
+ * Modal dialog: backdrop entity (blocks clicks behind it) with a
+ * centered panel child. Hidden by default; `open()` / `close()`
+ * toggle visibility + interactivity.
+ *
+ * Add children to `panelEntity` to populate the dialog.
+ */
+export function createDialog(opts: DialogOptions): DialogHandle {
+ const { world } = opts;
+
+ const backdrop = spawnUIEntity({
+ world,
+ parent: opts.parent,
+ rect: opts.backdropRect ?? { anchorMin: { x: 0, y: 0 }, anchorMax: { x: 1, y: 1 } },
+ renderer: opts.backdropRenderer ?? { color: DEFAULT_BACKDROP_COLOR },
+ });
+
+ // Blocks hit-test on the scene behind the dialog.
+ world.insert(backdrop, Interactable, {
+ enabled: true,
+ blockRaycast: true,
+ raycastTarget: true,
+ });
+ world.insert(backdrop, UIInteraction, {
+ hovered: false, pressed: false, justPressed: false, justReleased: false,
+ });
+
+ const panel = spawnUIEntity({
+ world,
+ parent: backdrop,
+ rect: opts.panelRect ?? {
+ anchorMin: { x: 0.5, y: 0.5 },
+ anchorMax: { x: 0.5, y: 0.5 },
+ size: { x: 400, y: 300 },
+ pivot: { x: 0.5, y: 0.5 },
+ },
+ renderer: opts.panelRenderer ?? { color: DEFAULT_PANEL_COLOR },
+ });
+
+ let open = !(opts.startHidden ?? true);
+ applyOpen(open);
+
+ function applyOpen(value: boolean): void {
+ setUIVisible(world, backdrop, value);
+ setUIVisible(world, panel, value);
+ // Disable the backdrop's raycast blocker when hidden so clicks
+ // fall through to scene behind.
+ if (world.has(backdrop, Interactable)) {
+ const i = world.get(backdrop, Interactable) as {
+ enabled: boolean;
+ blockRaycast: boolean;
+ raycastTarget: boolean;
+ };
+ i.enabled = value;
+ world.insert(backdrop, Interactable, i);
+ }
+ }
+
+ return {
+ backdropEntity: backdrop,
+ panelEntity: panel,
+ isOpen: () => open,
+ open: () => {
+ if (open) return;
+ open = true;
+ applyOpen(true);
+ },
+ close: () => {
+ if (!open) return;
+ open = false;
+ applyOpen(false);
+ },
+ dispose: () => {
+ if (world.valid(backdrop)) world.despawn(backdrop);
+ },
+ };
+}
diff --git a/sdk/src/ui2/widgets/helpers.ts b/sdk/src/ui2/widgets/helpers.ts
new file mode 100644
index 000000000..807c1e67c
--- /dev/null
+++ b/sdk/src/ui2/widgets/helpers.ts
@@ -0,0 +1,142 @@
+import {
+ Transform,
+ type TransformData,
+} from '../../component';
+import type { Entity, Vec2 } from '../../types';
+import type { World } from '../../world';
+
+import { UIRect, type UIRectData } from '../core/ui-rect';
+import { UIRenderer, UIVisualType, type UIRendererData } from '../core/ui-renderer';
+import { Text, TextAlign, TextVerticalAlign, type TextData } from '../core/text';
+
+/** Identity Transform. Fresh object per call — safe to insert into ECS. */
+export function identityTransform(): TransformData {
+ return {
+ position: { x: 0, y: 0, z: 0 },
+ rotation: { w: 1, x: 0, y: 0, z: 0 },
+ scale: { x: 1, y: 1, z: 1 },
+ worldPosition: { x: 0, y: 0, z: 0 },
+ worldRotation: { w: 1, x: 0, y: 0, z: 0 },
+ worldScale: { x: 1, y: 1, z: 1 },
+ };
+}
+
+export interface UIRectInit {
+ anchorMin?: Vec2;
+ anchorMax?: Vec2;
+ offsetMin?: Vec2;
+ offsetMax?: Vec2;
+ size?: Vec2;
+ pivot?: Vec2;
+}
+
+/**
+ * Default rect covers the full parent (stretched anchors). Override with
+ * size + pivot for fixed-size elements.
+ */
+export function buildUIRect(init: UIRectInit = {}): UIRectData {
+ return {
+ anchorMin: init.anchorMin ?? { x: 0, y: 0 },
+ anchorMax: init.anchorMax ?? { x: 1, y: 1 },
+ offsetMin: init.offsetMin ?? { x: 0, y: 0 },
+ offsetMax: init.offsetMax ?? { x: 0, y: 0 },
+ size: init.size ?? { x: 0, y: 0 },
+ pivot: init.pivot ?? { x: 0.5, y: 0.5 },
+ };
+}
+
+export interface UIRendererInit {
+ visualType?: UIVisualType;
+ texture?: number;
+ color?: { r: number; g: number; b: number; a: number };
+ uvOffset?: Vec2;
+ uvScale?: Vec2;
+ sliceBorder?: { x: number; y: number; z: number; w: number };
+ material?: number;
+ enabled?: boolean;
+}
+
+export function buildUIRenderer(init: UIRendererInit = {}): UIRendererData {
+ return {
+ visualType: init.visualType ?? UIVisualType.SolidColor,
+ texture: init.texture ?? 0,
+ color: init.color ?? { r: 1, g: 1, b: 1, a: 1 },
+ uvOffset: init.uvOffset ?? { x: 0, y: 0 },
+ uvScale: init.uvScale ?? { x: 1, y: 1 },
+ sliceBorder: init.sliceBorder ?? { x: 0, y: 0, z: 0, w: 0 },
+ material: init.material ?? 0,
+ enabled: init.enabled ?? true,
+ };
+}
+
+export interface TextInit extends Partial<TextData> {}
+
+export function buildText(init: TextInit = {}): TextData {
+ return {
+ content: init.content ?? '',
+ fontFamily: init.fontFamily ?? 'Arial',
+ fontSize: init.fontSize ?? 14,
+ color: init.color ?? { r: 1, g: 1, b: 1, a: 1 },
+ align: init.align ?? TextAlign.Center,
+ verticalAlign: init.verticalAlign ?? TextVerticalAlign.Middle,
+ wordWrap: init.wordWrap ?? false,
+ overflow: init.overflow ?? 0,
+ lineHeight: init.lineHeight ?? 1.2,
+ bold: init.bold ?? false,
+ italic: init.italic ?? false,
+ strokeColor: init.strokeColor ?? { r: 0, g: 0, b: 0, a: 1 },
+ strokeWidth: init.strokeWidth ?? 0,
+ shadowColor: init.shadowColor ?? { r: 0, g: 0, b: 0, a: 1 },
+ shadowBlur: init.shadowBlur ?? 0,
+ shadowOffsetX: init.shadowOffsetX ?? 0,
+ shadowOffsetY: init.shadowOffsetY ?? 0,
+ richText: init.richText ?? false,
+ };
+}
+
+export interface UIEntityInit {
+ world: World;
+ parent?: Entity;
+ rect?: UIRectInit;
+ renderer?: UIRendererInit;
+ text?: TextInit;
+}
+
+/**
+ * Spawn a UI entity with Transform + UIRect, optionally UIRenderer and
+ * Text, optionally parented. Returns the entity.
+ *
+ * Widgets compose with this to avoid repeating the same insert dance.
+ */
+export function spawnUIEntity(init: UIEntityInit): Entity {
+ const { world } = init;
+ const entity = world.spawn();
+
+ world.insert(entity, Transform, identityTransform());
+ world.insert(entity, UIRect, buildUIRect(init.rect));
+
+ if (init.renderer) {
+ world.insert(entity, UIRenderer, buildUIRenderer(init.renderer));
+ }
+ if (init.text) {
+ world.insert(entity, Text, buildText(init.text));
+ }
+ if (init.parent !== undefined) {
+ world.setParent(entity, init.parent);
+ }
+
+ return entity;
+}
+
+/**
+ * Toggle visibility of a UI entity via UIRenderer.enabled. Safe if the
+ * entity has no UIRenderer — no-op in that case.
+ */
+export function setUIVisible(world: World, entity: Entity, visible: boolean): void {
+ if (!world.valid(entity) || !world.has(entity, UIRenderer)) return;
+ const r = world.get(entity, UIRenderer) as UIRendererData;
+ if (r.enabled !== visible) {
+ r.enabled = visible;
+ world.insert(entity, UIRenderer, r);
+ }
+}
diff --git a/sdk/src/ui2/widgets/progress.ts b/sdk/src/ui2/widgets/progress.ts
new file mode 100644
index 000000000..e14ae7cd4
--- /dev/null
+++ b/sdk/src/ui2/widgets/progress.ts
@@ -0,0 +1,98 @@
+import type { Color, Entity } from '../../types';
+import type { World } from '../../world';
+
+import { UIRect, type UIRectData } from '../core/ui-rect';
+
+import { spawnUIEntity, type UIRectInit, type UIRendererInit } from './helpers';
+
+export interface ProgressOptions {
+ world: World;
+ parent?: Entity;
+ rect?: UIRectInit;
+ /** Background (track) renderer. */
+ background?: UIRendererInit;
+ /** Fill renderer config (the filled bar). */
+ fill?: { color?: Color; sprite?: number };
+ /** Direction the fill grows. Default: 'right'. */
+ direction?: 'right' | 'left' | 'up' | 'down';
+ /** Initial progress 0..1. Default 0. */
+ value?: number;
+}
+
+export interface ProgressHandle {
+ readonly entity: Entity;
+ readonly fillEntity: Entity;
+ value(): number;
+ setValue(v: number): void;
+ dispose(): void;
+}
+
+/**
+ * Linear progress bar. Two entities: a track (background) and a fill
+ * child whose rect anchors are rewritten each setValue to grow along
+ * the configured direction.
+ */
+export function createProgress(opts: ProgressOptions): ProgressHandle {
+ const { world } = opts;
+ const direction = opts.direction ?? 'right';
+ let value = clamp01(opts.value ?? 0);
+
+ const track = spawnUIEntity({
+ world,
+ parent: opts.parent,
+ rect: opts.rect,
+ renderer: opts.background ?? { color: { r: 0.15, g: 0.15, b: 0.15, a: 1 } },
+ });
+
+ const fill = spawnUIEntity({
+ world,
+ parent: track,
+ rect: anchorsForProgress(direction, value),
+ renderer: {
+ color: opts.fill?.color ?? { r: 0.25, g: 0.56, b: 0.96, a: 1 },
+ texture: opts.fill?.sprite ?? 0,
+ visualType: opts.fill?.sprite ? 2 /* Image */ : 1 /* SolidColor */,
+ },
+ });
+
+ function setValue(v: number): void {
+ const next = clamp01(v);
+ if (next === value) return;
+ value = next;
+ const rect = world.get(fill, UIRect) as UIRectData;
+ const updated = anchorsForProgress(direction, value);
+ rect.anchorMin = updated.anchorMin!;
+ rect.anchorMax = updated.anchorMax!;
+ world.insert(fill, UIRect, rect);
+ }
+
+ return {
+ entity: track,
+ fillEntity: fill,
+ value: () => value,
+ setValue,
+ dispose: () => {
+ if (world.valid(track)) world.despawn(track);
+ },
+ };
+}
+
+function clamp01(v: number): number {
+ return v < 0 ? 0 : v > 1 ? 1 : v;
+}
+
+function anchorsForProgress(
+ dir: 'right' | 'left' | 'up' | 'down',
+ t: number,
+): UIRectInit {
+ switch (dir) {
+ case 'right':
+ return { anchorMin: { x: 0, y: 0 }, anchorMax: { x: t, y: 1 } };
+ case 'left':
+ return { anchorMin: { x: 1 - t, y: 0 }, anchorMax: { x: 1, y: 1 } };
+ case 'up':
+ return { anchorMin: { x: 0, y: 0 }, anchorMax: { x: 1, y: t } };
+ case 'down':
+ return { anchorMin: { x: 0, y: 1 - t }, anchorMax: { x: 1, y: 1 } };
+ }
+}
diff --git a/sdk/src/ui2/widgets/toggle.ts b/sdk/src/ui2/widgets/toggle.ts
new file mode 100644
index 000000000..c76afe043
--- /dev/null
+++ b/sdk/src/ui2/widgets/toggle.ts
@@ -0,0 +1,107 @@
+import type { Color, Entity } from '../../types';
+import type { World } from '../../world';
+
+import { UIEventType, type UIEventQueue } from '../core/events';
+
+import { createButton, type ButtonStateVisual } from './button';
+import { spawnUIEntity, setUIVisible, type UIRectInit, type UIRendererInit } from './helpers';
+
+export interface ToggleOptions {
+ world: World;
+ events: UIEventQueue;
+ parent?: Entity;
+ rect?: UIRectInit;
+
+ /** Background renderer for the frame. */
+ background?: UIRendererInit;
+
+ /** Interaction states (normal / hover / pressed / disabled) for the frame. */
+ interactionStates: Record<string, ButtonStateVisual>;
+
+ /**
+ * Optional rendering for the on-state indicator ("check mark").
+ * A child entity hidden when off, shown when on. Size defaults to
+ * the parent rect; override via `checkRect`.
+ */
+ check?: {
+ rect?: UIRectInit;
+ color?: Color;
+ sprite?: number;
+ };
+
+ /** Initial on/off state. */
+ isOn?: boolean;
+ /** Start disabled. */
+ disabled?: boolean;
+
+ onChange?: (isOn: boolean, entity: Entity) => void;
+}
+
+export interface ToggleHandle {
+ readonly entity: Entity;
+ isOn(): boolean;
+ setIsOn(value: boolean, silent?: boolean): void;
+ dispose(): void;
+}
+
+/**
+ * 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.
+ */
+export function createToggle(opts: ToggleOptions): ToggleHandle {
+ const { world, events } = opts;
+ let isOn = opts.isOn ?? false;
+
+ const button = createButton({
+ world,
+ events,
+ parent: opts.parent,
+ rect: opts.rect,
+ background: opts.background,
+ states: opts.interactionStates,
+ disabled: opts.disabled,
+ });
+
+ const check = spawnUIEntity({
+ world,
+ parent: button,
+ rect: opts.check?.rect ?? { anchorMin: { x: 0, y: 0 }, anchorMax: { x: 1, y: 1 } },
+ renderer: opts.check
+ ? {
+ color: opts.check.color,
+ texture: opts.check.sprite,
+ visualType: opts.check.sprite ? 2 /* Image */ : 1 /* SolidColor */,
+ }
+ : {},
+ });
+
+ setUIVisible(world, check, isOn);
+
+ const offClick = events.on(button, UIEventType.StateChanged, (event) => {
+ const data = event.data as { from: string; to: string };
+ if (data.from === 'pressed' && data.to === 'hover') {
+ 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);
+ }
+ }
+
+ return {
+ entity: button,
+ isOn: () => isOn,
+ setIsOn,
+ dispose: () => {
+ offClick();
+ if (world.valid(button)) world.despawn(button);
+ },
+ };
+}
diff --git a/sdk/tests/ui2-widgets.test.ts b/sdk/tests/ui2-widgets.test.ts
new file mode 100644
index 000000000..e9eafdb01
--- /dev/null
+++ b/sdk/tests/ui2-widgets.test.ts
@@ -0,0 +1,364 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import {
+ createButton,
+ createToggle,
+ createProgress,
+ createDialog,
+ setButtonState,
+ Interactable,
+ StateMachine,
+ StateVisuals,
+ UIRect,
+ UIRenderer,
+ UIEventQueue,
+ UIEventType,
+ TransitionFlag,
+} from '../src/ui2';
+import type { Entity } from '../src/types';
+import type { World } from '../src/world';
+
+// Minimal mock world — only the surface widgets + helpers touch.
+
+interface MockWorld {
+ _entities: Set<number>;
+ _components: Map<number, Map<object, unknown>>;
+ _parents: Map<number, number>;
+ _names: Map<number, string>;
+ _nextId: number;
+ _despawnListeners: Array<(e: Entity) => void>;
+
+ spawn(): Entity;
+ despawn(e: Entity): void;
+ valid(e: Entity): boolean;
+ setParent(child: Entity, parent: Entity): void;
+ has(e: Entity, c: object): boolean;
+ get(e: Entity, c: object): unknown;
+ insert(e: Entity, c: object, data: unknown): void;
+ onDespawn(cb: (e: Entity) => void): () => void;
+}
+
+function createMockWorld(): MockWorld {
+ const w: MockWorld = {
+ _entities: new Set<number>(),
+ _components: new Map(),
+ _parents: new Map(),
+ _names: new Map(),
+ _nextId: 1,
+ _despawnListeners: [],
+
+ spawn() {
+ const id = w._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);
+ w._parents.delete(e as number);
+ },
+ valid(e) {
+ return w._entities.has(e as number);
+ },
+ setParent(child, parent) {
+ w._parents.set(child as number, parent as number);
+ },
+ 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, data) {
+ w._components.get(e as number)?.set(c, data);
+ },
+ onDespawn(cb) {
+ w._despawnListeners.push(cb);
+ return () => {
+ const idx = w._despawnListeners.indexOf(cb);
+ if (idx !== -1) w._despawnListeners.splice(idx, 1);
+ };
+ },
+ };
+ return w;
+}
+
+describe('createButton', () => {
+ let world: MockWorld;
+ let events: UIEventQueue;
+
+ beforeEach(() => {
+ world = createMockWorld();
+ events = new UIEventQueue();
+ });
+
+ it('attaches the required components', () => {
+ const btn = createButton({
+ world: world as unknown as World,
+ events,
+ states: {
+ normal: { color: { r: 1, g: 1, b: 1, a: 1 } },
+ hover: { color: { r: 0.9, g: 0.9, b: 0.9, a: 1 } },
+ pressed: { color: { r: 0.8, g: 0.8, b: 0.8, a: 1 } },
+ disabled: { color: { r: 0.5, g: 0.5, b: 0.5, a: 1 } },
+ },
+ });
+
+ expect(world.has(btn, UIRect)).toBe(true);
+ expect(world.has(btn, UIRenderer)).toBe(true);
+ expect(world.has(btn, Interactable)).toBe(true);
+ expect(world.has(btn, StateMachine)).toBe(true);
+ expect(world.has(btn, StateVisuals)).toBe(true);
+ });
+
+ it('populates StateVisuals slots from the `states` map', () => {
+ const btn = createButton({
+ world: world as unknown as World,
+ events,
+ states: {
+ normal: { color: { r: 1, g: 0, b: 0, a: 1 } },
+ hover: { color: { r: 0, g: 1, b: 0, a: 1 } },
+ },
+ transitionFlags: TransitionFlag.ColorTint,
+ });
+
+ const sv = world.get(btn, StateVisuals) as Record<string, unknown>;
+ expect(sv['slot0Name']).toBe('normal');
+ expect(sv['slot1Name']).toBe('hover');
+ expect(sv['slot0Color']).toEqual({ r: 1, g: 0, b: 0, a: 1 });
+ expect(sv['transitionFlags']).toBe(TransitionFlag.ColorTint);
+ });
+
+ it('starts in "disabled" state when opts.disabled is true', () => {
+ const btn = createButton({
+ world: world as unknown as World,
+ events,
+ disabled: true,
+ states: {
+ normal: {}, hover: {}, pressed: {}, disabled: {},
+ },
+ });
+
+ const sm = world.get(btn, StateMachine) as { current: string };
+ const i = world.get(btn, Interactable) as { enabled: boolean };
+ expect(sm.current).toBe('disabled');
+ expect(i.enabled).toBe(false);
+ });
+
+ it('throws when more than 8 states are supplied', () => {
+ expect(() =>
+ createButton({
+ world: world as unknown as World,
+ events,
+ states: Object.fromEntries(
+ Array.from({ length: 9 }, (_, i) => [`s${i}`, {}]),
+ ),
+ }),
+ ).toThrow(/up to 8/);
+ });
+
+ it('fires onClick when the state transitions pressed → hover', () => {
+ const onClick = vi.fn();
+ const btn = createButton({
+ world: world as unknown as World,
+ events,
+ states: { normal: {}, hover: {}, pressed: {} },
+ onClick,
+ });
+
+ events.emit(btn, UIEventType.StateChanged, { from: 'pressed', to: 'hover' });
+ expect(onClick).toHaveBeenCalledWith(btn);
+ });
+
+ it('does not fire onClick on pressed → normal (released outside)', () => {
+ const onClick = vi.fn();
+ const btn = createButton({
+ world: world as unknown as World,
+ events,
+ states: { normal: {}, hover: {}, pressed: {} },
+ onClick,
+ });
+
+ events.emit(btn, UIEventType.StateChanged, { from: 'pressed', to: 'normal' });
+ expect(onClick).not.toHaveBeenCalled();
+ });
+
+ it('setButtonState writes StateMachine.current', () => {
+ const btn = createButton({
+ world: world as unknown as World,
+ events,
+ states: { normal: {}, loading: {} },
+ });
+
+ setButtonState(world as unknown as World, btn, 'loading');
+ expect((world.get(btn, StateMachine) as { current: string }).current).toBe('loading');
+ });
+});
+
+describe('createToggle', () => {
+ let world: MockWorld;
+ let events: UIEventQueue;
+
+ beforeEach(() => {
+ world = createMockWorld();
+ events = new UIEventQueue();
+ });
+
+ it('starts with the provided isOn value', () => {
+ const on = createToggle({
+ world: world as unknown as World,
+ events,
+ interactionStates: { normal: {}, hover: {}, pressed: {} },
+ isOn: true,
+ });
+ expect(on.isOn()).toBe(true);
+ });
+
+ it('flips isOn on click and emits change', () => {
+ const onChange = vi.fn();
+ const toggle = createToggle({
+ world: world as unknown as World,
+ events,
+ interactionStates: { normal: {}, hover: {}, pressed: {} },
+ isOn: false,
+ onChange,
+ });
+
+ events.emit(toggle.entity, UIEventType.StateChanged, { from: 'pressed', to: 'hover' });
+
+ expect(toggle.isOn()).toBe(true);
+ expect(onChange).toHaveBeenCalledWith(true, toggle.entity);
+ });
+
+ it('setIsOn emits change unless silent is true', () => {
+ const onChange = vi.fn();
+ const toggle = createToggle({
+ world: world as unknown as World,
+ events,
+ interactionStates: { normal: {}, hover: {}, pressed: {} },
+ onChange,
+ });
+
+ toggle.setIsOn(true);
+ expect(onChange).toHaveBeenCalledTimes(1);
+
+ toggle.setIsOn(false, true);
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(toggle.isOn()).toBe(false);
+ });
+
+ it('dispose despawns the root entity', () => {
+ const toggle = createToggle({
+ world: world as unknown as World,
+ events,
+ interactionStates: { normal: {}, hover: {}, pressed: {} },
+ });
+ expect(world.valid(toggle.entity)).toBe(true);
+
+ toggle.dispose();
+ expect(world.valid(toggle.entity)).toBe(false);
+ });
+});
+
+describe('createProgress', () => {
+ let world: MockWorld;
+
+ beforeEach(() => {
+ world = createMockWorld();
+ });
+
+ it('clamps the initial value to [0, 1]', () => {
+ const p = createProgress({
+ world: world as unknown as World,
+ value: 1.5,
+ });
+ expect(p.value()).toBe(1);
+
+ const q = createProgress({
+ world: world as unknown as World,
+ value: -0.2,
+ });
+ expect(q.value()).toBe(0);
+ });
+
+ it('setValue clamps and updates fill anchorMax.x (default "right")', () => {
+ const p = createProgress({
+ world: world as unknown as World,
+ value: 0,
+ });
+ p.setValue(0.4);
+ const rect = world.get(p.fillEntity, UIRect) as {
+ anchorMin: { x: number; y: number };
+ anchorMax: { x: number; y: number };
+ };
+ expect(rect.anchorMin).toEqual({ x: 0, y: 0 });
+ expect(rect.anchorMax).toEqual({ x: 0.4, y: 1 });
+ });
+
+ it('uses reversed anchors when direction = "left"', () => {
+ const p = createProgress({
+ world: world as unknown as World,
+ direction: 'left',
+ value: 0.25,
+ });
+ const rect = world.get(p.fillEntity, UIRect) as {
+ anchorMin: { x: number; y: number };
+ anchorMax: { x: number; y: number };
+ };
+ expect(rect.anchorMin.x).toBe(0.75);
+ expect(rect.anchorMax.x).toBe(1);
+ });
+
+ it('dispose despawns the track', () => {
+ const p = createProgress({ world: world as unknown as World });
+ expect(world.valid(p.entity)).toBe(true);
+ p.dispose();
+ expect(world.valid(p.entity)).toBe(false);
+ });
+});
+
+describe('createDialog', () => {
+ let world: MockWorld;
+
+ beforeEach(() => {
+ world = createMockWorld();
+ });
+
+ it('starts hidden by default', () => {
+ const dialog = createDialog({ world: world as unknown as World });
+ expect(dialog.isOpen()).toBe(false);
+ const bg = world.get(dialog.backdropEntity, UIRenderer) as { enabled: boolean };
+ expect(bg.enabled).toBe(false);
+ });
+
+ it('open() shows backdrop + panel and enables Interactable', () => {
+ const dialog = createDialog({ world: world as unknown as World });
+ dialog.open();
+ expect(dialog.isOpen()).toBe(true);
+
+ const bg = world.get(dialog.backdropEntity, UIRenderer) as { enabled: boolean };
+ const panel = world.get(dialog.panelEntity, UIRenderer) as { enabled: boolean };
+ const inter = world.get(dialog.backdropEntity, Interactable) as { enabled: boolean };
+ expect(bg.enabled).toBe(true);
+ expect(panel.enabled).toBe(true);
+ expect(inter.enabled).toBe(true);
+ });
+
+ it('close() hides and disables the backdrop Interactable', () => {
+ const dialog = createDialog({ world: world as unknown as World, startHidden: false });
+ expect(dialog.isOpen()).toBe(true);
+
+ dialog.close();
+ const inter = world.get(dialog.backdropEntity, Interactable) as { enabled: boolean };
+ expect(dialog.isOpen()).toBe(false);
+ expect(inter.enabled).toBe(false);
+ });
+
+ it('dispose despawns the backdrop', () => {
+ const dialog = createDialog({ world: world as unknown as World });
+ expect(world.valid(dialog.backdropEntity)).toBe(true);
+ dialog.dispose();
+ expect(world.valid(dialog.backdropEntity)).toBe(false);
+ });
+});