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 Slider, Dropdown, ScrollContainer + mouse-wheel system

esengine1cf2e5757fdf
diff --git a/sdk/src/ui2/collection/scroll-container.ts b/sdk/src/ui2/collection/scroll-container.ts
new file mode 100644
index 000000000..bc2ed4990
--- /dev/null
+++ b/sdk/src/ui2/collection/scroll-container.ts
@@ -0,0 +1,143 @@
+import type { Vec2 } from '../../types';
+
+export interface ScrollContainerOptions {
+ viewportSize: Vec2;
+ contentSize: Vec2;
+ initialOffset?: Vec2;
+ /** Axis restrictions. Default 'vertical'. */
+ direction?: 'both' | 'vertical' | 'horizontal';
+ /** Multiplier applied to wheel deltas. Default 1. */
+ wheelSpeed?: number;
+}
+
+export type ScrollListener = (offset: Vec2) => void;
+
+/**
+ * Scroll state for a virtualized view. Clamps offset to the legal range
+ * `[0, contentSize - viewportSize]` and notifies listeners on any change.
+ *
+ * The ScrollContainer itself has no input knowledge; a system pushes
+ * wheel / drag deltas into `scrollBy`. Consumers that need to react
+ * (e.g. a ListView) subscribe via `onScroll`.
+ */
+export class ScrollContainer {
+ private viewportSize_: Vec2;
+ private contentSize_: Vec2;
+ private offset_: Vec2 = { x: 0, y: 0 };
+ private readonly direction_: 'both' | 'vertical' | 'horizontal';
+ private readonly wheelSpeed_: number;
+ private readonly listeners_ = new Set<ScrollListener>();
+
+ constructor(opts: ScrollContainerOptions) {
+ this.viewportSize_ = { x: opts.viewportSize.x, y: opts.viewportSize.y };
+ this.contentSize_ = { x: opts.contentSize.x, y: opts.contentSize.y };
+ this.direction_ = opts.direction ?? 'vertical';
+ this.wheelSpeed_ = opts.wheelSpeed ?? 1;
+ this.setOffset(opts.initialOffset ?? { x: 0, y: 0 });
+ }
+
+ getOffset(): Vec2 {
+ return { x: this.offset_.x, y: this.offset_.y };
+ }
+
+ getViewportSize(): Vec2 {
+ return { x: this.viewportSize_.x, y: this.viewportSize_.y };
+ }
+
+ getContentSize(): Vec2 {
+ return { x: this.contentSize_.x, y: this.contentSize_.y };
+ }
+
+ getMaxOffset(): Vec2 {
+ return {
+ x: Math.max(0, this.contentSize_.x - this.viewportSize_.x),
+ y: Math.max(0, this.contentSize_.y - this.viewportSize_.y),
+ };
+ }
+
+ getWheelSpeed(): number {
+ return this.wheelSpeed_;
+ }
+
+ setOffset(offset: Vec2): void {
+ const max = this.getMaxOffset();
+ const lockX = this.direction_ === 'vertical';
+ const lockY = this.direction_ === 'horizontal';
+ const next: Vec2 = {
+ x: lockX ? 0 : clamp(offset.x, 0, max.x),
+ y: lockY ? 0 : clamp(offset.y, 0, max.y),
+ };
+ if (next.x === this.offset_.x && next.y === this.offset_.y) return;
+ this.offset_ = next;
+ for (const listener of Array.from(this.listeners_)) {
+ try {
+ listener({ x: next.x, y: next.y });
+ } catch (err) {
+ console.error('[ScrollContainer] listener error:', err);
+ }
+ }
+ }
+
+ scrollBy(delta: Vec2): void {
+ this.setOffset({
+ x: this.offset_.x + delta.x,
+ y: this.offset_.y + delta.y,
+ });
+ }
+
+ setViewportSize(size: Vec2): void {
+ if (size.x === this.viewportSize_.x && size.y === this.viewportSize_.y) return;
+ this.viewportSize_ = { x: size.x, y: size.y };
+ this.setOffset(this.offset_); // re-clamp
+ }
+
+ setContentSize(size: Vec2): void {
+ if (size.x === this.contentSize_.x && size.y === this.contentSize_.y) return;
+ this.contentSize_ = { x: size.x, y: size.y };
+ this.setOffset(this.offset_);
+ }
+
+ onScroll(listener: ScrollListener): () => void {
+ this.listeners_.add(listener);
+ return () => {
+ this.listeners_.delete(listener);
+ };
+ }
+
+ dispose(): void {
+ this.listeners_.clear();
+ }
+}
+
+/** Registry of scroll containers keyed by the entity they're attached to. */
+export class ScrollContainerRegistry {
+ private readonly entries_ = new Map<number, ScrollContainer>();
+
+ attach(entity: number, container: ScrollContainer): void {
+ this.entries_.set(entity, container);
+ }
+
+ detach(entity: number): void {
+ this.entries_.delete(entity);
+ }
+
+ get(entity: number): ScrollContainer | undefined {
+ return this.entries_.get(entity);
+ }
+
+ entries(): IterableIterator<[number, ScrollContainer]> {
+ return this.entries_.entries();
+ }
+
+ size(): number {
+ return this.entries_.size;
+ }
+
+ clear(): void {
+ this.entries_.clear();
+ }
+}
+
+function clamp(value: number, lo: number, hi: number): number {
+ return value < lo ? lo : value > hi ? hi : value;
+}
diff --git a/sdk/src/ui2/index.ts b/sdk/src/ui2/index.ts
index 39d4b022e..a1993fe74 100644
--- a/sdk/src/ui2/index.ts
+++ b/sdk/src/ui2/index.ts
@@ -132,6 +132,13 @@ export {
type ListViewItemTemplate,
} from './collection/list-view';
+export {
+ ScrollContainer,
+ ScrollContainerRegistry,
+ type ScrollContainerOptions,
+ type ScrollListener,
+} from './collection/scroll-container';
+
// Widgets
export {
@@ -171,3 +178,15 @@ export {
type DialogOptions,
type DialogHandle,
} from './widgets/dialog';
+
+export {
+ createSlider,
+ type SliderOptions,
+ type SliderHandle,
+} from './widgets/slider';
+
+export {
+ createDropdown,
+ type DropdownOptions,
+ type DropdownHandle,
+} from './widgets/dropdown';
diff --git a/sdk/src/ui2/plugin.ts b/sdk/src/ui2/plugin.ts
index f97aa9586..f4b5c1b5d 100644
--- a/sdk/src/ui2/plugin.ts
+++ b/sdk/src/ui2/plugin.ts
@@ -1,5 +1,8 @@
import type { App, Plugin } from '../app';
+import { Res } from '../resource';
import { defineSystem, Schedule } from '../system';
+import { Input, type InputState } from '../input';
+import type { Entity } from '../types';
import { UIEventBus, UIEventQueue } from './core/events';
import {
@@ -8,6 +11,8 @@ import {
createStateVisualsApplySystem,
} from './behavior/systems';
import { ListView, ListViewRegistry } from './collection/list-view';
+import { ScrollContainer, ScrollContainerRegistry } from './collection/scroll-container';
+import { UIInteraction, type UIInteractionData } from './behavior/interactable';
/**
* Wires the Layer 2 behavior systems — interactable-driven state machine
@@ -21,6 +26,7 @@ export class UIBehaviorPlugin implements Plugin {
private events_: UIEventQueue | null = null;
private listViews_: ListViewRegistry | null = null;
+ private scrollContainers_: ScrollContainerRegistry | null = null;
/** The authoritative event queue for this app instance. */
get events(): UIEventQueue {
@@ -32,8 +38,6 @@ export class UIBehaviorPlugin implements Plugin {
/**
* Register a ListView so its `update()` is invoked each frame.
- * ListView is typically constructed right after the plugin is
- * installed, so callers hold onto this plugin to register.
*/
registerListView(list: ListView<unknown>): void {
if (!this.listViews_) {
@@ -46,6 +50,22 @@ export class UIBehaviorPlugin implements Plugin {
this.listViews_?.remove(list);
}
+ /**
+ * Attach a ScrollContainer to an entity. A wheel-driven system
+ * applies mouse-wheel input to the container whenever the entity's
+ * UIInteraction.hovered flag is true.
+ */
+ attachScrollContainer(entity: Entity, container: ScrollContainer): void {
+ if (!this.scrollContainers_) {
+ throw new Error('UIBehaviorPlugin.attachScrollContainer called before build()');
+ }
+ this.scrollContainers_.attach(entity, container);
+ }
+
+ detachScrollContainer(entity: Entity): void {
+ this.scrollContainers_?.detach(entity);
+ }
+
build(app: App): void {
const events = new UIEventQueue();
this.events_ = events;
@@ -55,6 +75,12 @@ export class UIBehaviorPlugin implements Plugin {
const listViews = new ListViewRegistry();
this.listViews_ = listViews;
+ const scrollContainers = new ScrollContainerRegistry();
+ this.scrollContainers_ = scrollContainers;
+ app.world.onDespawn((entity) => scrollContainers.detach(entity));
+
+ const world = app.world;
+
app.addSystemToSchedule(
Schedule.Update,
createInteractableDriverSystem(app.world),
@@ -73,6 +99,21 @@ export class UIBehaviorPlugin implements Plugin {
Schedule.Update,
defineSystem([], () => listViews.tick(), { name: 'ListViewSystem' }),
);
+ app.addSystemToSchedule(
+ Schedule.Update,
+ defineSystem([Res(Input)], (input: InputState) => {
+ const dx = input.scrollDeltaX;
+ const dy = input.scrollDeltaY;
+ if (dx === 0 && dy === 0) return;
+ for (const [entity, container] of scrollContainers.entries()) {
+ if (!world.has(entity as Entity, UIInteraction)) continue;
+ const ui = world.get(entity as Entity, UIInteraction) as UIInteractionData;
+ if (!ui.hovered) continue;
+ const speed = container.getWheelSpeed();
+ container.scrollBy({ x: dx * speed, y: dy * speed });
+ }
+ }, { name: 'ScrollWheelSystem' }),
+ );
}
}
diff --git a/sdk/src/ui2/widgets/dropdown.ts b/sdk/src/ui2/widgets/dropdown.ts
new file mode 100644
index 000000000..9417432cb
--- /dev/null
+++ b/sdk/src/ui2/widgets/dropdown.ts
@@ -0,0 +1,239 @@
+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 { Text, type TextData } from '../core/text';
+
+import { spawnUIEntity, type UIRectInit, type UIRendererInit } from './helpers';
+
+export interface DropdownOptions<T> {
+ world: World;
+ events: UIEventQueue;
+ parent?: Entity;
+ rect?: UIRectInit;
+
+ options: readonly T[];
+ selectedIndex?: number;
+ optionToLabel?: (option: T, index: number) => string;
+
+ /** Visual state overrides for the main button. */
+ buttonStates?: {
+ normal?: Color;
+ hover?: Color;
+ pressed?: Color;
+ };
+ /** Visual state overrides for option rows in the popup. */
+ optionStates?: {
+ normal?: Color;
+ hover?: Color;
+ pressed?: Color;
+ };
+ /** Popup panel background. */
+ popupRenderer?: UIRendererInit;
+ /** Height of each option row in pixels. Default 32. */
+ optionHeight?: number;
+
+ onSelect?: (index: number, option: T, entity: Entity) => void;
+}
+
+export interface DropdownHandle<T> {
+ readonly entity: Entity;
+ readonly labelEntity: Entity;
+ isOpen(): boolean;
+ getSelectedIndex(): number;
+ getSelected(): T;
+ setSelectedIndex(index: number, silent?: boolean): void;
+ open(): void;
+ close(): void;
+ dispose(): void;
+}
+
+const DEFAULT_BTN_NORMAL: Color = { r: 0.22, g: 0.22, b: 0.26, a: 1 };
+const DEFAULT_BTN_HOVER: Color = { r: 0.28, g: 0.28, b: 0.32, a: 1 };
+const DEFAULT_BTN_PRESS: Color = { r: 0.18, g: 0.18, b: 0.22, a: 1 };
+const DEFAULT_OPT_NORMAL: Color = { r: 0.20, g: 0.20, b: 0.24, a: 1 };
+const DEFAULT_OPT_HOVER: Color = { r: 0.30, g: 0.50, b: 0.90, a: 1 };
+const DEFAULT_OPT_PRESS: Color = { r: 0.20, g: 0.40, b: 0.75, a: 1 };
+const DEFAULT_POPUP_BG: Color = { r: 0.14, g: 0.14, b: 0.16, a: 1 };
+
+const INTERACTION_DEFAULT = {
+ hovered: false, pressed: false, justPressed: false, justReleased: false,
+};
+
+function makeStatesSV(colors: {
+ normal: Color; hover: Color; pressed: Color;
+}): StateVisualsData {
+ const white = { r: 1, g: 1, b: 1, a: 1 };
+ return {
+ targetGraphic: 0 as Entity,
+ transitionFlags: TransitionFlag.ColorTint,
+ fadeDuration: 0,
+ slot0Name: 'normal', slot0Color: colors.normal, slot0Sprite: 0, slot0Scale: 1,
+ slot1Name: 'hover', slot1Color: colors.hover, slot1Sprite: 0, slot1Scale: 1,
+ slot2Name: 'pressed', slot2Color: colors.pressed, slot2Sprite: 0, slot2Scale: 1,
+ slot3Name: '', slot3Color: white, slot3Sprite: 0, slot3Scale: 1,
+ slot4Name: '', slot4Color: white, slot4Sprite: 0, slot4Scale: 1,
+ slot5Name: '', slot5Color: white, slot5Sprite: 0, slot5Scale: 1,
+ slot6Name: '', slot6Color: white, slot6Sprite: 0, slot6Scale: 1,
+ slot7Name: '', slot7Color: white, slot7Sprite: 0, slot7Scale: 1,
+ };
+}
+
+/**
+ * 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.
+ */
+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 btnColors = {
+ normal: opts.buttonStates?.normal ?? DEFAULT_BTN_NORMAL,
+ hover: opts.buttonStates?.hover ?? DEFAULT_BTN_HOVER,
+ pressed: opts.buttonStates?.pressed ?? DEFAULT_BTN_PRESS,
+ };
+ const optColors = {
+ normal: opts.optionStates?.normal ?? DEFAULT_OPT_NORMAL,
+ hover: opts.optionStates?.hover ?? DEFAULT_OPT_HOVER,
+ pressed: opts.optionStates?.pressed ?? DEFAULT_OPT_PRESS,
+ };
+
+ // Button root.
+ const button = spawnUIEntity({
+ world,
+ parent: opts.parent,
+ rect: opts.rect,
+ renderer: { color: btnColors.normal },
+ });
+ world.insert(button, Interactable, { enabled: true, blockRaycast: true, raycastTarget: true });
+ world.insert(button, UIInteraction, INTERACTION_DEFAULT);
+ world.insert(button, StateMachine, { current: 'normal', previous: '' });
+ world.insert(button, StateVisuals, makeStatesSV(btnColors));
+
+ const label = spawnUIEntity({
+ world,
+ parent: button,
+ rect: { anchorMin: { x: 0, y: 0 }, anchorMax: { x: 1, y: 1 } },
+ text: { content: labelOf(opts.options[selectedIndex]!, selectedIndex) },
+ });
+
+ 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;
+
+ popupPanel = spawnUIEntity({
+ world,
+ parent: button,
+ rect: {
+ anchorMin: { x: 0, y: 0 },
+ anchorMax: { x: 1, y: 0 },
+ offsetMin: { x: 0, y: -totalHeight },
+ offsetMax: { x: 0, y: 0 },
+ },
+ renderer: opts.popupRenderer ?? { color: DEFAULT_POPUP_BG },
+ });
+
+ for (let i = 0; i < opts.options.length; i++) {
+ const index = i;
+ const row = spawnOptionRow(index, totalHeight);
+ const off = events.on(row, UIEventType.StateChanged, (e) => {
+ const d = e.data as { from: string; to: string };
+ if (d.from === 'pressed' && d.to === 'hover') {
+ selectAndClose(index);
+ }
+ });
+ optionUnsubs.push(off);
+ }
+ }
+
+ function spawnOptionRow(index: number, totalHeight: number): Entity {
+ const yTop = 1 - (index * optionHeight) / totalHeight;
+ const yBottom = 1 - ((index + 1) * optionHeight) / totalHeight;
+ const row = spawnUIEntity({
+ world,
+ parent: popupPanel!,
+ rect: {
+ anchorMin: { x: 0, y: yBottom },
+ anchorMax: { x: 1, y: yTop },
+ },
+ renderer: { color: optColors.normal },
+ });
+ world.insert(row, Interactable, { enabled: true, blockRaycast: true, raycastTarget: true });
+ world.insert(row, UIInteraction, INTERACTION_DEFAULT);
+ world.insert(row, StateMachine, { current: 'normal', previous: '' });
+ world.insert(row, StateVisuals, makeStatesSV(optColors));
+
+ spawnUIEntity({
+ world,
+ parent: row,
+ rect: { anchorMin: { x: 0, y: 0 }, anchorMax: { x: 1, y: 1 } },
+ text: { content: labelOf(opts.options[index]!, index) },
+ });
+
+ 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);
+ }
+
+ 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);
+ }
+ }
+
+ // Click on button toggles popup.
+ const offButtonClick = events.on(button, UIEventType.StateChanged, (e) => {
+ const d = e.data as { from: string; to: string };
+ if (d.from === 'pressed' && d.to === 'hover') {
+ isOpen() ? close() : open();
+ }
+ });
+
+ return {
+ entity: button,
+ labelEntity: label,
+ isOpen,
+ getSelectedIndex: () => selectedIndex,
+ getSelected: () => opts.options[selectedIndex]!,
+ setSelectedIndex,
+ open,
+ close,
+ dispose: () => {
+ offButtonClick();
+ close();
+ if (world.valid(button)) world.despawn(button);
+ },
+ };
+}
diff --git a/sdk/src/ui2/widgets/slider.ts b/sdk/src/ui2/widgets/slider.ts
new file mode 100644
index 000000000..48f402c4b
--- /dev/null
+++ b/sdk/src/ui2/widgets/slider.ts
@@ -0,0 +1,156 @@
+import type { 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 SliderOptions {
+ world: World;
+ parent?: Entity;
+ rect?: UIRectInit;
+ min?: number;
+ max?: number;
+ value?: number;
+ /**
+ * Optional quantization step. `0` (default) = continuous.
+ */
+ step?: number;
+ /** Handle width in pixels. Default 12. */
+ handleWidth?: number;
+
+ trackRenderer?: UIRendererInit;
+ fillRenderer?: UIRendererInit;
+ handleRenderer?: UIRendererInit;
+
+ onChange?: (value: number, entity: Entity) => void;
+}
+
+export interface SliderHandle {
+ readonly entity: Entity;
+ readonly trackEntity: Entity;
+ readonly fillEntity: Entity;
+ readonly handleEntity: Entity;
+ getValue(): number;
+ setValue(value: number): void;
+ /**
+ * Translate a track-local x position (pixels from left) to a slider
+ * value, clamped and optionally snapped to `step`. Caller wires
+ * this to their drag / click handlers — v1 has no built-in input.
+ */
+ valueAtLocalX(localX: number, trackWidth: number): number;
+ dispose(): void;
+}
+
+const DEFAULT_TRACK: UIRendererInit = { color: { r: 0.15, g: 0.15, b: 0.15, a: 1 } };
+const DEFAULT_FILL: UIRendererInit = { color: { r: 0.25, g: 0.56, b: 0.96, a: 1 } };
+const DEFAULT_HANDLE: UIRendererInit = { color: { r: 1, g: 1, b: 1, a: 1 } };
+
+/**
+ * Horizontal slider composed of a track, a fill bar, and a handle thumb.
+ * Interaction (drag, click-to-snap) is not wired here — use
+ * `valueAtLocalX()` with your own pointer handler, or call `setValue`
+ * directly.
+ */
+export function createSlider(opts: SliderOptions): SliderHandle {
+ const min = opts.min ?? 0;
+ const max = opts.max ?? 1;
+ const step = opts.step ?? 0;
+ const handleWidth = opts.handleWidth ?? 12;
+ let value = clampAndSnap(opts.value ?? min, min, max, step);
+
+ const track = spawnUIEntity({
+ world: opts.world,
+ parent: opts.parent,
+ rect: opts.rect,
+ renderer: opts.trackRenderer ?? DEFAULT_TRACK,
+ });
+
+ const fill = spawnUIEntity({
+ world: opts.world,
+ parent: track,
+ rect: fillRectAt(fraction(value, min, max)),
+ renderer: opts.fillRenderer ?? DEFAULT_FILL,
+ });
+
+ const handle = spawnUIEntity({
+ world: opts.world,
+ parent: track,
+ rect: handleRectAt(fraction(value, min, max), handleWidth),
+ renderer: opts.handleRenderer ?? DEFAULT_HANDLE,
+ });
+
+ function writeVisuals(t: number): void {
+ const fillRect = opts.world.get(fill, UIRect) as UIRectData;
+ fillRect.anchorMax = { x: t, y: 1 };
+ opts.world.insert(fill, UIRect, fillRect);
+
+ const handleRect = opts.world.get(handle, UIRect) as UIRectData;
+ handleRect.anchorMin = { x: t, y: 0 };
+ handleRect.anchorMax = { x: t, y: 1 };
+ opts.world.insert(handle, UIRect, handleRect);
+ }
+
+ function setValue(next: number): void {
+ const v = clampAndSnap(next, min, max, step);
+ if (v === value) return;
+ value = v;
+ writeVisuals(fraction(value, min, max));
+ opts.onChange?.(value, track);
+ }
+
+ function valueAtLocalX(localX: number, trackWidth: number): number {
+ if (trackWidth <= 0) return min;
+ const t = clamp(localX / trackWidth, 0, 1);
+ return clampAndSnap(min + t * (max - min), min, max, step);
+ }
+
+ return {
+ entity: track,
+ trackEntity: track,
+ fillEntity: fill,
+ handleEntity: handle,
+ getValue: () => value,
+ setValue,
+ valueAtLocalX,
+ dispose: () => {
+ if (opts.world.valid(track)) opts.world.despawn(track);
+ },
+ };
+}
+
+function fraction(value: number, min: number, max: number): number {
+ if (max <= min) return 0;
+ return clamp((value - min) / (max - min), 0, 1);
+}
+
+function fillRectAt(t: number): UIRectInit {
+ return {
+ anchorMin: { x: 0, y: 0 },
+ anchorMax: { x: t, y: 1 },
+ offsetMin: { x: 0, y: 0 },
+ offsetMax: { x: 0, y: 0 },
+ };
+}
+
+function handleRectAt(t: number, width: number): UIRectInit {
+ return {
+ anchorMin: { x: t, y: 0 },
+ anchorMax: { x: t, y: 1 },
+ offsetMin: { x: 0, y: 0 },
+ offsetMax: { x: 0, y: 0 },
+ size: { x: width, y: 0 },
+ pivot: { x: 0.5, y: 0.5 },
+ };
+}
+
+function clamp(value: number, lo: number, hi: number): number {
+ return value < lo ? lo : value > hi ? hi : value;
+}
+
+function clampAndSnap(value: number, min: number, max: number, step: number): number {
+ const clamped = clamp(value, min, max);
+ if (step <= 0) return clamped;
+ const snapped = Math.round((clamped - min) / step) * step + min;
+ return clamp(snapped, min, max);
+}
diff --git a/sdk/tests/ui2-scroll-container.test.ts b/sdk/tests/ui2-scroll-container.test.ts
new file mode 100644
index 000000000..dd180bcd7
--- /dev/null
+++ b/sdk/tests/ui2-scroll-container.test.ts
@@ -0,0 +1,138 @@
+import { describe, it, expect, vi } from 'vitest';
+import { ScrollContainer, ScrollContainerRegistry } from '../src/ui2';
+
+describe('ScrollContainer', () => {
+ it('clamps initial offset to [0, max]', () => {
+ const c = new ScrollContainer({
+ viewportSize: { x: 200, y: 100 },
+ contentSize: { x: 200, y: 500 },
+ initialOffset: { x: 0, y: 999 },
+ });
+ // max Y = 500 - 100 = 400
+ expect(c.getOffset()).toEqual({ x: 0, y: 400 });
+ });
+
+ it('clamps negative offsets to 0', () => {
+ const c = new ScrollContainer({
+ viewportSize: { x: 200, y: 100 },
+ contentSize: { x: 200, y: 500 },
+ });
+ c.setOffset({ x: -50, y: -50 });
+ expect(c.getOffset()).toEqual({ x: 0, y: 0 });
+ });
+
+ it('clamps to max for oversized content', () => {
+ const c = new ScrollContainer({
+ viewportSize: { x: 200, y: 100 },
+ contentSize: { x: 200, y: 500 },
+ });
+ c.setOffset({ x: 0, y: 1000 });
+ expect(c.getOffset()).toEqual({ x: 0, y: 400 });
+ });
+
+ it('vertical direction locks x to 0', () => {
+ const c = new ScrollContainer({
+ viewportSize: { x: 200, y: 100 },
+ contentSize: { x: 500, y: 500 },
+ direction: 'vertical',
+ });
+ c.setOffset({ x: 100, y: 50 });
+ expect(c.getOffset()).toEqual({ x: 0, y: 50 });
+ });
+
+ it('horizontal direction locks y to 0', () => {
+ const c = new ScrollContainer({
+ viewportSize: { x: 200, y: 100 },
+ contentSize: { x: 500, y: 500 },
+ direction: 'horizontal',
+ });
+ c.setOffset({ x: 100, y: 50 });
+ expect(c.getOffset()).toEqual({ x: 100, y: 0 });
+ });
+
+ it('scrollBy adds delta then clamps', () => {
+ const c = new ScrollContainer({
+ viewportSize: { x: 200, y: 100 },
+ contentSize: { x: 200, y: 500 },
+ });
+ c.scrollBy({ x: 0, y: 150 });
+ c.scrollBy({ x: 0, y: 200 });
+ expect(c.getOffset().y).toBe(350);
+ c.scrollBy({ x: 0, y: 999 });
+ expect(c.getOffset().y).toBe(400); // clamped
+ });
+
+ it('onScroll fires only when offset actually changes', () => {
+ const c = new ScrollContainer({
+ viewportSize: { x: 200, y: 100 },
+ contentSize: { x: 200, y: 500 },
+ });
+ const spy = vi.fn();
+ c.onScroll(spy);
+
+ c.setOffset({ x: 0, y: 50 });
+ c.setOffset({ x: 0, y: 50 }); // same value — no fire
+ expect(spy).toHaveBeenCalledTimes(1);
+ expect(spy).toHaveBeenCalledWith({ x: 0, y: 50 });
+ });
+
+ it('unsubscribe stops notifications', () => {
+ const c = new ScrollContainer({
+ viewportSize: { x: 200, y: 100 },
+ contentSize: { x: 200, y: 500 },
+ });
+ const spy = vi.fn();
+ const off = c.onScroll(spy);
+
+ off();
+ c.setOffset({ x: 0, y: 50 });
+ expect(spy).not.toHaveBeenCalled();
+ });
+
+ it('setContentSize re-clamps current offset', () => {
+ const c = new ScrollContainer({
+ viewportSize: { x: 200, y: 100 },
+ contentSize: { x: 200, y: 500 },
+ initialOffset: { x: 0, y: 380 },
+ });
+ expect(c.getOffset().y).toBe(380);
+
+ c.setContentSize({ x: 200, y: 300 }); // new max = 200
+ expect(c.getOffset().y).toBe(200);
+ });
+
+ it('setViewportSize re-clamps current offset', () => {
+ const c = new ScrollContainer({
+ viewportSize: { x: 200, y: 100 },
+ contentSize: { x: 200, y: 500 },
+ initialOffset: { x: 0, y: 350 },
+ });
+ c.setViewportSize({ x: 200, y: 300 }); // new max = 500 - 300 = 200
+ expect(c.getOffset().y).toBe(200);
+ });
+
+ it('wheel speed multiplier is stored and readable', () => {
+ const c = new ScrollContainer({
+ viewportSize: { x: 200, y: 100 },
+ contentSize: { x: 200, y: 500 },
+ wheelSpeed: 2.5,
+ });
+ expect(c.getWheelSpeed()).toBe(2.5);
+ });
+});
+
+describe('ScrollContainerRegistry', () => {
+ it('attach, get, detach round-trip', () => {
+ const reg = new ScrollContainerRegistry();
+ const c = new ScrollContainer({
+ viewportSize: { x: 1, y: 1 }, contentSize: { x: 1, y: 1 },
+ });
+ reg.attach(42, c);
+ expect(reg.get(42)).toBe(c);
+ expect(reg.size()).toBe(1);
+
+ reg.detach(42);
+ expect(reg.get(42)).toBeUndefined();
+ expect(reg.size()).toBe(0);
+ });
+});
diff --git a/sdk/tests/ui2-slider-dropdown.test.ts b/sdk/tests/ui2-slider-dropdown.test.ts
new file mode 100644
index 000000000..bc01afded
--- /dev/null
+++ b/sdk/tests/ui2-slider-dropdown.test.ts
@@ -0,0 +1,272 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import {
+ createSlider,
+ createDropdown,
+ UIEventQueue,
+ UIEventType,
+ UIRect,
+ Text,
+} from '../src/ui2';
+import type { Entity } from '../src/types';
+import type { World } from '../src/world';
+
+interface MockWorld {
+ _entities: Set<number>;
+ _components: Map<number, Map<object, unknown>>;
+ _nextId: number;
+ _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;
+ onDespawn(cb: (e: Entity) => void): () => void;
+}
+
+function createMockWorld(): MockWorld {
+ const w: MockWorld = {
+ _entities: new Set(), _components: 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);
+ },
+ valid(e) { return w._entities.has(e as number); },
+ setParent() { /* no-op for these tests */ },
+ 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); },
+ onDespawn(cb) {
+ w._despawnListeners.push(cb);
+ return () => {
+ const idx = w._despawnListeners.indexOf(cb);
+ if (idx !== -1) w._despawnListeners.splice(idx, 1);
+ };
+ },
+ };
+ return w;
+}
+
+describe('createSlider', () => {
+ let world: MockWorld;
+
+ beforeEach(() => {
+ world = createMockWorld();
+ });
+
+ it('initializes at the provided value, clamped to [min, max]', () => {
+ const slider = createSlider({
+ world: world as unknown as World,
+ min: 0, max: 10, value: 5,
+ });
+ expect(slider.getValue()).toBe(5);
+
+ const clipped = createSlider({
+ world: world as unknown as World,
+ min: 0, max: 10, value: 99,
+ });
+ expect(clipped.getValue()).toBe(10);
+ });
+
+ it('setValue clamps and triggers onChange', () => {
+ const onChange = vi.fn();
+ const slider = createSlider({
+ world: world as unknown as World,
+ min: 0, max: 1, value: 0,
+ onChange,
+ });
+ slider.setValue(0.5);
+ expect(slider.getValue()).toBe(0.5);
+ expect(onChange).toHaveBeenCalledWith(0.5, slider.entity);
+
+ slider.setValue(2);
+ expect(slider.getValue()).toBe(1);
+ });
+
+ it('setValue with step snaps to the nearest step', () => {
+ const slider = createSlider({
+ world: world as unknown as World,
+ min: 0, max: 10, step: 2, value: 0,
+ });
+ slider.setValue(3); // nearest 2-step → 2 or 4 (round half up in JS → 4)
+ expect([2, 4]).toContain(slider.getValue());
+
+ slider.setValue(7.7);
+ expect(slider.getValue()).toBe(8);
+ });
+
+ it('setValue does not fire onChange when value is unchanged', () => {
+ const onChange = vi.fn();
+ const slider = createSlider({
+ world: world as unknown as World,
+ min: 0, max: 1, value: 0.5, onChange,
+ });
+ slider.setValue(0.5);
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('updates fill anchorMax.x on setValue', () => {
+ const slider = createSlider({
+ world: world as unknown as World,
+ min: 0, max: 1, value: 0,
+ });
+ slider.setValue(0.25);
+ const rect = world.get(slider.fillEntity, UIRect) as {
+ anchorMax: { x: number; y: number };
+ };
+ expect(rect.anchorMax.x).toBe(0.25);
+ });
+
+ it('updates handle anchorMin/Max.x together to position it at t', () => {
+ const slider = createSlider({
+ world: world as unknown as World,
+ min: 0, max: 1, value: 0,
+ });
+ slider.setValue(0.5);
+ const rect = world.get(slider.handleEntity, UIRect) as {
+ anchorMin: { x: number; y: number };
+ anchorMax: { x: number; y: number };
+ };
+ expect(rect.anchorMin.x).toBe(0.5);
+ expect(rect.anchorMax.x).toBe(0.5);
+ });
+
+ it('valueAtLocalX maps pointer X to value (with clamping)', () => {
+ const slider = createSlider({
+ world: world as unknown as World,
+ min: 0, max: 100,
+ });
+ expect(slider.valueAtLocalX(0, 200)).toBe(0);
+ expect(slider.valueAtLocalX(100, 200)).toBe(50);
+ expect(slider.valueAtLocalX(200, 200)).toBe(100);
+ expect(slider.valueAtLocalX(-50, 200)).toBe(0);
+ expect(slider.valueAtLocalX(1000, 200)).toBe(100);
+ });
+
+ it('dispose despawns the track root', () => {
+ const slider = createSlider({
+ world: world as unknown as World,
+ });
+ expect(world.valid(slider.entity)).toBe(true);
+ slider.dispose();
+ expect(world.valid(slider.entity)).toBe(false);
+ });
+});
+
+describe('createDropdown', () => {
+ let world: MockWorld;
+ let events: UIEventQueue;
+
+ beforeEach(() => {
+ world = createMockWorld();
+ events = new UIEventQueue();
+ });
+
+ it('shows the current selection label', () => {
+ const dd = createDropdown({
+ world: world as unknown as World, events,
+ options: ['Apple', 'Banana', 'Cherry'],
+ selectedIndex: 1,
+ });
+ const label = world.get(dd.labelEntity, Text) as { content: string };
+ expect(label.content).toBe('Banana');
+ });
+
+ it('opens popup on button click (pressed → hover)', () => {
+ const dd = createDropdown({
+ world: world as unknown as World, events,
+ options: ['a', 'b'],
+ });
+ expect(dd.isOpen()).toBe(false);
+
+ events.emit(dd.entity, UIEventType.StateChanged, { from: 'pressed', to: 'hover' });
+ expect(dd.isOpen()).toBe(true);
+ });
+
+ it('closes popup on second button click', () => {
+ const dd = createDropdown({
+ world: world as unknown as World, events,
+ options: ['a', 'b'],
+ });
+
+ events.emit(dd.entity, UIEventType.StateChanged, { from: 'pressed', to: 'hover' });
+ expect(dd.isOpen()).toBe(true);
+
+ events.emit(dd.entity, UIEventType.StateChanged, { from: 'pressed', to: 'hover' });
+ expect(dd.isOpen()).toBe(false);
+ });
+
+ it('setSelectedIndex updates the label text and fires onSelect (unless silent)', () => {
+ const onSelect = vi.fn();
+ const dd = createDropdown({
+ world: world as unknown as World, events,
+ options: ['x', 'y', 'z'],
+ onSelect,
+ });
+
+ dd.setSelectedIndex(2);
+ 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);
+ expect(dd.getSelectedIndex()).toBe(0);
+ expect(onSelect).toHaveBeenCalledTimes(1); // silent
+ });
+
+ it('open() / close() imperatively toggle the popup', () => {
+ const dd = createDropdown({
+ world: world as unknown as World, events,
+ options: ['a', 'b', 'c'],
+ });
+
+ dd.open();
+ expect(dd.isOpen()).toBe(true);
+ dd.open(); // idempotent
+ expect(dd.isOpen()).toBe(true);
+
+ dd.close();
+ expect(dd.isOpen()).toBe(false);
+ });
+
+ it('optionToLabel controls the displayed text', () => {
+ const dd = createDropdown<{ id: number; label: string }>({
+ world: world as unknown as World, events,
+ options: [
+ { id: 1, label: 'Alpha' },
+ { id: 2, label: 'Beta' },
+ ],
+ optionToLabel: (o) => o.label,
+ });
+ const lbl = world.get(dd.labelEntity, Text) as { content: string };
+ expect(lbl.content).toBe('Alpha');
+ });
+
+ it('getSelected returns the typed option object', () => {
+ const dd = createDropdown({
+ world: world as unknown as World, events,
+ options: ['a', 'b', 'c'],
+ selectedIndex: 2,
+ });
+ expect(dd.getSelected()).toBe('c');
+ });
+
+ it('dispose despawns the button root', () => {
+ const dd = createDropdown({
+ world: world as unknown as World, events,
+ options: ['a'],
+ });
+ expect(world.valid(dd.entity)).toBe(true);
+ dd.dispose();
+ expect(world.valid(dd.entity)).toBe(false);
+ });
+});