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 virtualized Collection system (DataSource, Layout, ListView)

esengine70abedb10046
diff --git a/sdk/src/ui2/collection/data-source.ts b/sdk/src/ui2/collection/data-source.ts
new file mode 100644
index 000000000..9e92f8019
--- /dev/null
+++ b/sdk/src/ui2/collection/data-source.ts
@@ -0,0 +1,110 @@
+/**
+ * Change notification emitted by a DataSource.
+ */
+export type DataSourceChange =
+ | { type: 'insert'; index: number; count: number }
+ | { type: 'remove'; index: number; count: number }
+ | { type: 'update'; index: number; count: number }
+ | { type: 'reset' };
+
+export type Unsubscribe = () => void;
+
+/**
+ * Abstract backing store for a virtualized list. Producers implement
+ * `getCount` + `getItem` at minimum; optional methods provide
+ * heterogeneous item types, stable identity for diffing, and change
+ * notifications so consumers can mark themselves dirty.
+ */
+export interface DataSource<T = unknown> {
+ getCount(): number;
+ getItem(index: number): T;
+ /** Defaults to `'default'`. Used to route items to the matching template. */
+ getItemType?(index: number): string;
+ /** Stable identity to support future reorder-aware diffing. */
+ getItemId?(index: number, item: T): string | number;
+ /** Subscribe to change notifications; returns an unsubscribe fn. */
+ subscribe?(listener: (change: DataSourceChange) => void): Unsubscribe;
+}
+
+/**
+ * DataSource backed by a mutable array, with helper methods that mutate
+ * the array and notify subscribers in one call.
+ */
+export class ArrayDataSource<T> implements DataSource<T> {
+ private readonly items_: T[];
+ private readonly listeners_ = new Set<(c: DataSourceChange) => void>();
+
+ constructor(items: readonly T[] = []) {
+ this.items_ = items.slice();
+ }
+
+ getCount(): number {
+ return this.items_.length;
+ }
+
+ getItem(index: number): T {
+ const item = this.items_[index];
+ if (item === undefined && index >= this.items_.length) {
+ throw new Error(`[ArrayDataSource] index ${index} out of range (count=${this.items_.length})`);
+ }
+ return item as T;
+ }
+
+ subscribe(listener: (c: DataSourceChange) => void): Unsubscribe {
+ this.listeners_.add(listener);
+ return () => {
+ this.listeners_.delete(listener);
+ };
+ }
+
+ /** Replace all items. Emits a `reset`. */
+ setItems(items: readonly T[]): void {
+ this.items_.length = 0;
+ this.items_.push(...items);
+ this.emit_({ type: 'reset' });
+ }
+
+ /** Append items to the end. Emits `insert`. */
+ append(items: readonly T[]): void {
+ const at = this.items_.length;
+ this.items_.push(...items);
+ this.emit_({ type: 'insert', index: at, count: items.length });
+ }
+
+ /** Insert items at `index`. Emits `insert`. */
+ insert(index: number, items: readonly T[]): void {
+ const clamped = Math.max(0, Math.min(index, this.items_.length));
+ this.items_.splice(clamped, 0, ...items);
+ this.emit_({ type: 'insert', index: clamped, count: items.length });
+ }
+
+ /** Remove `count` items starting at `index`. Emits `remove`. */
+ remove(index: number, count = 1): void {
+ if (count <= 0) return;
+ const actual = Math.min(count, this.items_.length - index);
+ if (actual <= 0) return;
+ this.items_.splice(index, actual);
+ this.emit_({ type: 'remove', index, count: actual });
+ }
+
+ /** Replace item at `index`. Emits `update`. */
+ update(index: number, item: T): void {
+ this.items_[index] = item;
+ this.emit_({ type: 'update', index, count: 1 });
+ }
+
+ private emit_(change: DataSourceChange): void {
+ for (const listener of Array.from(this.listeners_)) {
+ try {
+ listener(change);
+ } catch (err) {
+ console.error('[ArrayDataSource] listener error:', err);
+ }
+ }
+ }
+}
+
+/** Convenience factory for ad-hoc arrays. */
+export function arrayDataSource<T>(items: readonly T[]): ArrayDataSource<T> {
+ return new ArrayDataSource(items);
+}
diff --git a/sdk/src/ui2/collection/layout-provider.ts b/sdk/src/ui2/collection/layout-provider.ts
new file mode 100644
index 000000000..bf8ebab2c
--- /dev/null
+++ b/sdk/src/ui2/collection/layout-provider.ts
@@ -0,0 +1,138 @@
+import type { Vec2 } from '../../types';
+
+export interface Rect {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+}
+
+/**
+ * Abstract layout math for a virtualized list. Implementations answer
+ * three questions for a list of fixed-size items:
+ *
+ * - how big is the total content?
+ * - where does item `i` sit inside that content?
+ * - which index range is visible in the given viewport?
+ *
+ * Variable-height items can be added later via an optional
+ * measure callback; this revision assumes fixed-size items.
+ */
+export interface LayoutProvider {
+ getContentSize(count: number): Vec2;
+ getItemRect(index: number): Rect;
+ /** Inclusive start, exclusive end. Returns [0, 0] when nothing is visible. */
+ getVisibleRange(viewport: Rect, count: number): [start: number, end: number];
+}
+
+// -- Linear (row or column) ---------------------------------------------------
+
+export interface LinearLayoutOptions {
+ direction?: 'row' | 'column';
+ spacing?: number;
+ itemSize: Vec2;
+}
+
+export class LinearLayoutProvider implements LayoutProvider {
+ private readonly dir_: 'row' | 'column';
+ private readonly spacing_: number;
+ private readonly itemSize_: Vec2;
+
+ constructor(opts: LinearLayoutOptions) {
+ this.dir_ = opts.direction ?? 'column';
+ this.spacing_ = opts.spacing ?? 0;
+ this.itemSize_ = opts.itemSize;
+ }
+
+ getContentSize(count: number): Vec2 {
+ if (count <= 0) return { x: 0, y: 0 };
+ const main = this.mainAxis_();
+ const extent = count * main + (count - 1) * this.spacing_;
+ return this.dir_ === 'column'
+ ? { x: this.itemSize_.x, y: extent }
+ : { x: extent, y: this.itemSize_.y };
+ }
+
+ getItemRect(index: number): Rect {
+ const stride = this.stride_();
+ const offset = index * stride;
+ return this.dir_ === 'column'
+ ? { x: 0, y: offset, width: this.itemSize_.x, height: this.itemSize_.y }
+ : { x: offset, y: 0, width: this.itemSize_.x, height: this.itemSize_.y };
+ }
+
+ getVisibleRange(viewport: Rect, count: number): [number, number] {
+ if (count <= 0) return [0, 0];
+ const stride = this.stride_();
+ if (stride <= 0) return [0, count];
+
+ const vStart = this.dir_ === 'column' ? viewport.y : viewport.x;
+ const vExtent = this.dir_ === 'column' ? viewport.height : viewport.width;
+ const vEnd = vStart + vExtent;
+
+ const firstRaw = Math.floor(vStart / stride);
+ const lastRaw = Math.ceil(vEnd / stride) - 1;
+ const start = Math.max(0, firstRaw);
+ const end = Math.min(count, lastRaw + 1);
+ return start < end ? [start, end] : [0, 0];
+ }
+
+ private mainAxis_(): number {
+ return this.dir_ === 'column' ? this.itemSize_.y : this.itemSize_.x;
+ }
+
+ private stride_(): number {
+ return this.mainAxis_() + this.spacing_;
+ }
+}
+
+// -- Grid ---------------------------------------------------------------------
+
+export interface GridLayoutOptions {
+ columns: number;
+ itemSize: Vec2;
+ spacing?: Vec2;
+}
+
+export class GridLayoutProvider implements LayoutProvider {
+ private readonly cols_: number;
+ private readonly itemSize_: Vec2;
+ private readonly spacing_: Vec2;
+
+ constructor(opts: GridLayoutOptions) {
+ this.cols_ = Math.max(1, opts.columns);
+ this.itemSize_ = opts.itemSize;
+ this.spacing_ = opts.spacing ?? { x: 0, y: 0 };
+ }
+
+ getContentSize(count: number): Vec2 {
+ if (count <= 0) return { x: 0, y: 0 };
+ const rows = Math.ceil(count / this.cols_);
+ const width = this.cols_ * this.itemSize_.x + (this.cols_ - 1) * this.spacing_.x;
+ const height = rows * this.itemSize_.y + (rows - 1) * this.spacing_.y;
+ return { x: width, y: height };
+ }
+
+ getItemRect(index: number): Rect {
+ const col = index % this.cols_;
+ const row = Math.floor(index / this.cols_);
+ return {
+ x: col * (this.itemSize_.x + this.spacing_.x),
+ y: row * (this.itemSize_.y + this.spacing_.y),
+ width: this.itemSize_.x,
+ height: this.itemSize_.y,
+ };
+ }
+
+ getVisibleRange(viewport: Rect, count: number): [number, number] {
+ if (count <= 0) return [0, 0];
+ const rowStride = this.itemSize_.y + this.spacing_.y;
+ if (rowStride <= 0) return [0, count];
+
+ const firstRow = Math.max(0, Math.floor(viewport.y / rowStride));
+ const lastRow = Math.ceil((viewport.y + viewport.height) / rowStride) - 1;
+ const start = firstRow * this.cols_;
+ const end = Math.min(count, (lastRow + 1) * this.cols_);
+ return start < end ? [start, end] : [0, 0];
+ }
+}
diff --git a/sdk/src/ui2/collection/list-view.ts b/sdk/src/ui2/collection/list-view.ts
new file mode 100644
index 000000000..7d1edb555
--- /dev/null
+++ b/sdk/src/ui2/collection/list-view.ts
@@ -0,0 +1,237 @@
+import { Transform, type TransformData } from '../../component';
+import type { Entity, Vec2 } from '../../types';
+import type { World } from '../../world';
+
+import type { DataSource } from './data-source';
+import type { LayoutProvider, Rect } from './layout-provider';
+import { ViewPool, type ViewPoolTemplate } from './view-pool';
+
+export interface ListViewItemTemplate<T = unknown> extends ViewPoolTemplate<T> {}
+
+export interface ListViewOptions<T = unknown> {
+ world: World;
+ /** Entity that hosts the scrolling content (items are parented here). */
+ parent: Entity;
+ dataSource: DataSource<T>;
+ layout: LayoutProvider;
+ /** Size of the visible window into the content, in content-local units. */
+ viewportSize: Vec2;
+ /** Map of item type → template; every `getItemType(i)` result must have a match. */
+ templates: Record<string, ListViewItemTemplate<T>>;
+ /**
+ * Extra index count kept mounted on each side of the strict visible range.
+ * Default 2. For grid layouts set this to `columns * 2` or similar for
+ * row-level padding.
+ */
+ recycleBuffer?: number;
+ /**
+ * Override how an item entity is positioned for its computed rect.
+ * Default writes `Transform.position = (centerX, -centerY, 0)` so the
+ * item's center lands on the layout rect center in a y-up world.
+ */
+ placeItem?: (world: World, entity: Entity, rect: Rect, index: number) => void;
+ /** Called after each bind, useful for ad-hoc per-item tweaks. */
+ onItemBound?: (entity: Entity, data: T, index: number) => void;
+ /** Toggle visibility on pool acquire/release. Forwarded to ViewPool. */
+ setVisible?: (world: World, entity: Entity, visible: boolean) => void;
+}
+
+function defaultPlaceItem(world: World, entity: Entity, rect: Rect): void {
+ const existing = world.has(entity, Transform)
+ ? (world.get(entity, Transform) as TransformData)
+ : {
+ 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 },
+ };
+ existing.position.x = rect.x + rect.width / 2;
+ // List coords grow down, world coords grow up → flip.
+ existing.position.y = -(rect.y + rect.height / 2);
+ world.insert(entity, Transform, existing);
+}
+
+interface MountRecord {
+ entity: Entity;
+ itemType: string;
+}
+
+/**
+ * Virtualized list driver. Owns a ViewPool + DataSource subscription;
+ * on each `update()` computes the visible index range and syncs the
+ * mounted item set to match.
+ *
+ * Does not own input — callers drive scrolling by calling
+ * `setScrollOffset()`. Typical wiring: a ScrollContainer primitive (or
+ * the app's input layer) computes a new offset and pushes it in.
+ */
+export class ListView<T = unknown> {
+ private readonly world_: World;
+ private readonly parent_: Entity;
+ private readonly dataSource_: DataSource<T>;
+ private readonly layout_: LayoutProvider;
+ private readonly pool_: ViewPool;
+ private readonly recycleBuffer_: number;
+ private readonly placeItem_: (world: World, entity: Entity, rect: Rect, index: number) => void;
+ private readonly onItemBound_: ((e: Entity, d: T, i: number) => void) | undefined;
+ private readonly mounted_ = new Map<number, MountRecord>();
+ private unsubscribeDataSource_: (() => void) | null = null;
+
+ private viewportSize_: Vec2;
+ private scrollOffset_: Vec2 = { x: 0, y: 0 };
+ private dirty_ = true;
+ private disposed_ = false;
+
+ constructor(opts: ListViewOptions<T>) {
+ this.world_ = opts.world;
+ this.parent_ = opts.parent;
+ this.dataSource_ = opts.dataSource;
+ this.layout_ = opts.layout;
+ this.viewportSize_ = { x: opts.viewportSize.x, y: opts.viewportSize.y };
+ this.recycleBuffer_ = opts.recycleBuffer ?? 2;
+ this.placeItem_ = opts.placeItem ?? defaultPlaceItem;
+ this.onItemBound_ = opts.onItemBound;
+
+ this.pool_ = new ViewPool({ world: opts.world, setVisible: opts.setVisible });
+ for (const [type, tpl] of Object.entries(opts.templates)) {
+ this.pool_.setTemplate(type, tpl);
+ }
+
+ if (this.dataSource_.subscribe) {
+ this.unsubscribeDataSource_ = this.dataSource_.subscribe(() => {
+ this.dirty_ = true;
+ });
+ }
+ }
+
+ /** Current visible window within the content, in content-local coords. */
+ getViewport(): Rect {
+ return {
+ x: this.scrollOffset_.x,
+ y: this.scrollOffset_.y,
+ width: this.viewportSize_.x,
+ height: this.viewportSize_.y,
+ };
+ }
+
+ /** Total size of the content for the current data count. */
+ getContentSize(): Vec2 {
+ return this.layout_.getContentSize(this.dataSource_.getCount());
+ }
+
+ /** Strict visible index range [start, end). */
+ getVisibleRange(): [number, number] {
+ return this.layout_.getVisibleRange(this.getViewport(), this.dataSource_.getCount());
+ }
+
+ /** Number of entities currently mounted (useful for virtualization tests). */
+ getMountedCount(): number {
+ return this.mounted_.size;
+ }
+
+ setScrollOffset(offset: Vec2): void {
+ if (offset.x === this.scrollOffset_.x && offset.y === this.scrollOffset_.y) return;
+ this.scrollOffset_ = { x: offset.x, y: offset.y };
+ this.dirty_ = true;
+ }
+
+ 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.dirty_ = true;
+ }
+
+ /** Mark the mount set dirty — the next `update()` will re-sync. */
+ refresh(): void {
+ this.dirty_ = true;
+ }
+
+ /**
+ * Sync mounted items to the current viewport + data source.
+ * Cheap when nothing has changed (short-circuits on !dirty).
+ */
+ update(): void {
+ if (this.disposed_ || !this.dirty_) return;
+ this.dirty_ = false;
+
+ const count = this.dataSource_.getCount();
+ const [visStart, visEnd] = this.layout_.getVisibleRange(this.getViewport(), count);
+
+ const bufferedStart = Math.max(0, visStart - this.recycleBuffer_);
+ const bufferedEnd = Math.min(count, visEnd + this.recycleBuffer_);
+
+ // Release anything outside the buffered range.
+ for (const [index, record] of Array.from(this.mounted_.entries())) {
+ if (index < bufferedStart || index >= bufferedEnd) {
+ this.pool_.release(record.itemType, record.entity);
+ this.mounted_.delete(index);
+ }
+ }
+
+ // Acquire anything inside the range that isn't already mounted.
+ for (let i = bufferedStart; i < bufferedEnd; i++) {
+ const existing = this.mounted_.get(i);
+ const itemType = this.dataSource_.getItemType?.(i) ?? 'default';
+
+ let entity: Entity;
+ if (existing) {
+ // Item already mounted; bind again in case data updated.
+ entity = existing.entity;
+ } else {
+ if (!this.pool_.hasTemplate(itemType)) {
+ console.warn(`[ListView] No template for item type "${itemType}" at index ${i}`);
+ continue;
+ }
+ entity = this.pool_.acquire(itemType, this.parent_);
+ this.mounted_.set(i, { entity, itemType });
+ }
+
+ const data = this.dataSource_.getItem(i);
+ this.pool_.bind(itemType, entity, data, i);
+ const rect = this.layout_.getItemRect(i);
+ this.placeItem_(this.world_, entity, rect, i);
+ this.onItemBound_?.(entity, data, i);
+ }
+ }
+
+ /** Release all mounted items and tear down subscriptions. */
+ dispose(): void {
+ if (this.disposed_) return;
+ this.disposed_ = true;
+ this.unsubscribeDataSource_?.();
+ this.unsubscribeDataSource_ = null;
+ for (const record of this.mounted_.values()) {
+ this.pool_.release(record.itemType, record.entity);
+ }
+ this.mounted_.clear();
+ this.pool_.dispose();
+ }
+}
+
+/**
+ * Registry of active ListView instances. A plugin owns one of these
+ * and invokes `tick()` from a per-frame system.
+ */
+export class ListViewRegistry {
+ private readonly instances_ = new Set<ListView<unknown>>();
+
+ add(list: ListView<unknown>): void {
+ this.instances_.add(list);
+ }
+
+ remove(list: ListView<unknown>): void {
+ this.instances_.delete(list);
+ }
+
+ tick(): void {
+ for (const list of this.instances_) {
+ list.update();
+ }
+ }
+
+ count(): number {
+ return this.instances_.size;
+ }
+}
diff --git a/sdk/src/ui2/index.ts b/sdk/src/ui2/index.ts
index 957248ce6..bd1fdcf76 100644
--- a/sdk/src/ui2/index.ts
+++ b/sdk/src/ui2/index.ts
@@ -106,3 +106,28 @@ export {
} from './behavior/systems';
export { UIBehaviorPlugin, uiBehaviorPlugin } from './plugin';
+
+// Collection
+
+export {
+ type DataSource,
+ type DataSourceChange,
+ ArrayDataSource,
+ arrayDataSource,
+} from './collection/data-source';
+
+export {
+ type LayoutProvider,
+ type Rect,
+ type LinearLayoutOptions,
+ type GridLayoutOptions,
+ LinearLayoutProvider,
+ GridLayoutProvider,
+} from './collection/layout-provider';
+
+export {
+ ListView,
+ ListViewRegistry,
+ type ListViewOptions,
+ type ListViewItemTemplate,
+} from './collection/list-view';
diff --git a/sdk/src/ui2/plugin.ts b/sdk/src/ui2/plugin.ts
index 4915c91fa..f97aa9586 100644
--- a/sdk/src/ui2/plugin.ts
+++ b/sdk/src/ui2/plugin.ts
@@ -1,5 +1,5 @@
import type { App, Plugin } from '../app';
-import { Schedule } from '../system';
+import { defineSystem, Schedule } from '../system';
import { UIEventBus, UIEventQueue } from './core/events';
import {
@@ -7,6 +7,7 @@ import {
createStateMachineDiffSystem,
createStateVisualsApplySystem,
} from './behavior/systems';
+import { ListView, ListViewRegistry } from './collection/list-view';
/**
* Wires the Layer 2 behavior systems — interactable-driven state machine
@@ -19,6 +20,7 @@ export class UIBehaviorPlugin implements Plugin {
name = 'uiBehavior';
private events_: UIEventQueue | null = null;
+ private listViews_: ListViewRegistry | null = null;
/** The authoritative event queue for this app instance. */
get events(): UIEventQueue {
@@ -28,12 +30,31 @@ export class UIBehaviorPlugin implements Plugin {
return this.events_;
}
+ /**
+ * 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_) {
+ throw new Error('UIBehaviorPlugin.registerListView called before build()');
+ }
+ this.listViews_.add(list);
+ }
+
+ unregisterListView(list: ListView<unknown>): void {
+ this.listViews_?.remove(list);
+ }
+
build(app: App): void {
const events = new UIEventQueue();
this.events_ = events;
app.insertResource(UIEventBus, events);
app.world.onDespawn((entity) => events.removeAll(entity));
+ const listViews = new ListViewRegistry();
+ this.listViews_ = listViews;
+
app.addSystemToSchedule(
Schedule.Update,
createInteractableDriverSystem(app.world),
@@ -48,6 +69,10 @@ export class UIBehaviorPlugin implements Plugin {
createStateVisualsApplySystem(app.world),
{ runAfter: ['StateMachineDiffSystem'] },
);
+ app.addSystemToSchedule(
+ Schedule.Update,
+ defineSystem([], () => listViews.tick(), { name: 'ListViewSystem' }),
+ );
}
}
diff --git a/sdk/tests/ui2-data-source.test.ts b/sdk/tests/ui2-data-source.test.ts
new file mode 100644
index 000000000..4ebe5657d
--- /dev/null
+++ b/sdk/tests/ui2-data-source.test.ts
@@ -0,0 +1,117 @@
+import { describe, it, expect, vi } from 'vitest';
+import { ArrayDataSource, arrayDataSource, type DataSourceChange } from '../src/ui2';
+
+describe('ArrayDataSource', () => {
+ it('reports count and items from initial array', () => {
+ const ds = arrayDataSource([10, 20, 30]);
+ expect(ds.getCount()).toBe(3);
+ expect(ds.getItem(0)).toBe(10);
+ expect(ds.getItem(2)).toBe(30);
+ });
+
+ it('copies the initial array (external mutation does not affect)', () => {
+ const src = [1, 2, 3];
+ const ds = new ArrayDataSource(src);
+ src.push(4);
+ expect(ds.getCount()).toBe(3);
+ });
+
+ it('throws when indexing out of range', () => {
+ const ds = arrayDataSource([1, 2]);
+ expect(() => ds.getItem(5)).toThrow(/out of range/);
+ });
+
+ describe('subscribe / notifications', () => {
+ it('delivers setItems as a reset change', () => {
+ const ds = arrayDataSource([1, 2, 3]);
+ const listener = vi.fn<(c: DataSourceChange) => void>();
+ ds.subscribe(listener);
+
+ ds.setItems([10, 20]);
+
+ expect(ds.getCount()).toBe(2);
+ expect(listener).toHaveBeenCalledWith({ type: 'reset' });
+ });
+
+ it('delivers append as insert at end', () => {
+ const ds = arrayDataSource([1]);
+ const listener = vi.fn<(c: DataSourceChange) => void>();
+ ds.subscribe(listener);
+
+ ds.append([2, 3]);
+
+ expect(ds.getCount()).toBe(3);
+ expect(listener).toHaveBeenCalledWith({ type: 'insert', index: 1, count: 2 });
+ });
+
+ it('delivers insert with the clamped target index', () => {
+ const ds = arrayDataSource([1, 2]);
+ const listener = vi.fn<(c: DataSourceChange) => void>();
+ ds.subscribe(listener);
+
+ ds.insert(10, [99]); // far past end, clamped to 2
+
+ expect(ds.getCount()).toBe(3);
+ expect(ds.getItem(2)).toBe(99);
+ expect(listener).toHaveBeenCalledWith({ type: 'insert', index: 2, count: 1 });
+ });
+
+ it('delivers remove with the actual removed count', () => {
+ const ds = arrayDataSource([1, 2, 3]);
+ const listener = vi.fn<(c: DataSourceChange) => void>();
+ ds.subscribe(listener);
+
+ ds.remove(1, 10); // tries to remove 10, only 2 remain
+
+ expect(ds.getCount()).toBe(1);
+ expect(listener).toHaveBeenCalledWith({ type: 'remove', index: 1, count: 2 });
+ });
+
+ it('remove with count <= 0 is a no-op (no emission)', () => {
+ const ds = arrayDataSource([1, 2]);
+ const listener = vi.fn<(c: DataSourceChange) => void>();
+ ds.subscribe(listener);
+
+ ds.remove(0, 0);
+
+ expect(ds.getCount()).toBe(2);
+ expect(listener).not.toHaveBeenCalled();
+ });
+
+ it('delivers update as a single-item update', () => {
+ const ds = arrayDataSource(['a', 'b', 'c']);
+ const listener = vi.fn<(c: DataSourceChange) => void>();
+ ds.subscribe(listener);
+
+ ds.update(1, 'B');
+
+ expect(ds.getItem(1)).toBe('B');
+ expect(listener).toHaveBeenCalledWith({ type: 'update', index: 1, count: 1 });
+ });
+
+ it('unsubscribe stops further notifications', () => {
+ const ds = arrayDataSource([1]);
+ const listener = vi.fn<(c: DataSourceChange) => void>();
+ const off = ds.subscribe(listener);
+ off();
+
+ ds.append([2]);
+
+ expect(listener).not.toHaveBeenCalled();
+ });
+
+ it('listener throw does not block peers', () => {
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const ds = arrayDataSource([1]);
+ const good = vi.fn<(c: DataSourceChange) => void>();
+ ds.subscribe(() => { throw new Error('boom'); });
+ ds.subscribe(good);
+
+ ds.append([2]);
+
+ expect(good).toHaveBeenCalledOnce();
+ expect(spy).toHaveBeenCalled();
+ spy.mockRestore();
+ });
+ });
+});
diff --git a/sdk/tests/ui2-layout-provider.test.ts b/sdk/tests/ui2-layout-provider.test.ts
new file mode 100644
index 000000000..dda3101ea
--- /dev/null
+++ b/sdk/tests/ui2-layout-provider.test.ts
@@ -0,0 +1,114 @@
+import { describe, it, expect } from 'vitest';
+import { LinearLayoutProvider, GridLayoutProvider, type Rect } from '../src/ui2';
+
+const VIEWPORT = (x: number, y: number, w: number, h: number): Rect =>
+ ({ x, y, width: w, height: h });
+
+describe('LinearLayoutProvider (column)', () => {
+ const p = new LinearLayoutProvider({
+ direction: 'column',
+ itemSize: { x: 200, y: 40 },
+ spacing: 4,
+ });
+
+ it('content height includes every item plus inter-item spacing', () => {
+ // 10 items * 40 height + 9 gaps * 4 = 400 + 36 = 436
+ expect(p.getContentSize(10)).toEqual({ x: 200, y: 436 });
+ });
+
+ it('empty content has zero size', () => {
+ expect(p.getContentSize(0)).toEqual({ x: 0, y: 0 });
+ });
+
+ it('item rects stride by itemSize + spacing', () => {
+ expect(p.getItemRect(0)).toEqual({ x: 0, y: 0, width: 200, height: 40 });
+ expect(p.getItemRect(1)).toEqual({ x: 0, y: 44, width: 200, height: 40 });
+ expect(p.getItemRect(5)).toEqual({ x: 0, y: 220, width: 200, height: 40 });
+ });
+
+ it('viewport at origin returns items that overlap the window', () => {
+ // viewport 0..120 (3 strides of 44 = 132) → items 0,1,2
+ const [start, end] = p.getVisibleRange(VIEWPORT(0, 0, 200, 120), 10);
+ expect(start).toBe(0);
+ expect(end).toBe(3);
+ });
+
+ it('scrolled viewport returns the offset range', () => {
+ // scroll to y=100 (mid item 2), height 80 → ends at 180
+ // start = floor(100/44) = 2; last = ceil(180/44)-1 = 4; range [2,5)
+ const [start, end] = p.getVisibleRange(VIEWPORT(0, 100, 200, 80), 10);
+ expect(start).toBe(2);
+ expect(end).toBe(5);
+ });
+
+ it('clamps to data count when viewport extends past end', () => {
+ const [start, end] = p.getVisibleRange(VIEWPORT(0, 400, 200, 200), 10);
+ expect(start).toBe(9); // item at y=396..436
+ expect(end).toBe(10);
+ });
+
+ it('returns [0,0] for empty data', () => {
+ const [start, end] = p.getVisibleRange(VIEWPORT(0, 0, 200, 100), 0);
+ expect([start, end]).toEqual([0, 0]);
+ });
+});
+
+describe('LinearLayoutProvider (row)', () => {
+ const p = new LinearLayoutProvider({
+ direction: 'row',
+ itemSize: { x: 100, y: 60 },
+ spacing: 10,
+ });
+
+ it('content size extends horizontally', () => {
+ expect(p.getContentSize(4)).toEqual({ x: 100 * 4 + 30, y: 60 });
+ });
+
+ it('item rect strides along x', () => {
+ expect(p.getItemRect(2)).toEqual({ x: 220, y: 0, width: 100, height: 60 });
+ });
+
+ it('getVisibleRange uses viewport.x / width', () => {
+ // 0..250 wide → items at x=0, 110, 220, each item 100 wide
+ // item 0: 0..100 ✓, item 1: 110..210 ✓, item 2: 220..320 overlaps 250 ✓
+ const [start, end] = p.getVisibleRange(VIEWPORT(0, 0, 250, 60), 10);
+ expect(start).toBe(0);
+ expect(end).toBe(3);
+ });
+});
+
+describe('GridLayoutProvider', () => {
+ const p = new GridLayoutProvider({
+ columns: 3,
+ itemSize: { x: 80, y: 80 },
+ spacing: { x: 10, y: 10 },
+ });
+
+ it('content size accounts for rows inferred from count + columns', () => {
+ // 10 items, 3 cols → 4 rows. width = 3*80 + 2*10 = 260. height = 4*80 + 3*10 = 350.
+ expect(p.getContentSize(10)).toEqual({ x: 260, y: 350 });
+ });
+
+ it('getItemRect places index along column-major then row', () => {
+ expect(p.getItemRect(0)).toEqual({ x: 0, y: 0, width: 80, height: 80 });
+ expect(p.getItemRect(2)).toEqual({ x: 180, y: 0, width: 80, height: 80 });
+ expect(p.getItemRect(3)).toEqual({ x: 0, y: 90, width: 80, height: 80 });
+ expect(p.getItemRect(7)).toEqual({ x: 90, y: 180, width: 80, height: 80 });
+ });
+
+ it('visible range covers full rows intersecting the viewport', () => {
+ // viewport y=0, height 100 → firstRow 0, lastRow ceil(100/90)-1 = 1. range [0, 6)
+ const [start, end] = p.getVisibleRange(VIEWPORT(0, 0, 260, 100), 20);
+ expect(start).toBe(0);
+ expect(end).toBe(6);
+ });
+
+ it('enforces at least one column even if caller passes zero', () => {
+ const pEdge = new GridLayoutProvider({ columns: 0, itemSize: { x: 50, y: 50 } });
+ expect(pEdge.getContentSize(3)).toEqual({ x: 50, y: 150 });
+ });
+
+ it('returns [0,0] for empty data', () => {
+ expect(p.getVisibleRange(VIEWPORT(0, 0, 100, 100), 0)).toEqual([0, 0]);
+ });
+});
diff --git a/sdk/tests/ui2-list-view.test.ts b/sdk/tests/ui2-list-view.test.ts
new file mode 100644
index 000000000..e982c399c
--- /dev/null
+++ b/sdk/tests/ui2-list-view.test.ts
@@ -0,0 +1,274 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import {
+ ListView,
+ LinearLayoutProvider,
+ arrayDataSource,
+ type DataSource,
+} from '../src/ui2';
+import type { Entity } from '../src/types';
+import type { World } from '../src/world';
+
+// ---- Minimal World stub: enough surface for ListView + ViewPool ----
+
+interface MockWorld {
+ _entities: Set<number>;
+ _components: Map<number, Map<object, unknown>>;
+ _despawnListeners: Array<(e: Entity) => void>;
+ _nextId: number;
+
+ spawn(): Entity;
+ despawn(entity: Entity): void;
+ valid(entity: Entity): boolean;
+ onDespawn(cb: (e: Entity) => void): () => void;
+
+ has(entity: Entity, comp: object): boolean;
+ get(entity: Entity, comp: object): unknown;
+ insert(entity: Entity, comp: object, data: unknown): void;
+}
+
+function createWorld(): MockWorld {
+ const w: MockWorld = {
+ _entities: new Set<number>(),
+ _components: new Map(),
+ _despawnListeners: [],
+ _nextId: 1,
+
+ spawn() {
+ const id = w._nextId++;
+ w._entities.add(id);
+ w._components.set(id, new Map());
+ return id as Entity;
+ },
+ despawn(entity: Entity) {
+ for (const cb of w._despawnListeners) cb(entity);
+ w._entities.delete(entity as number);
+ w._components.delete(entity as number);
+ },
+ valid(entity: Entity) {
+ return w._entities.has(entity as number);
+ },
+ onDespawn(cb) {
+ w._despawnListeners.push(cb);
+ return () => {
+ const idx = w._despawnListeners.indexOf(cb);
+ if (idx !== -1) w._despawnListeners.splice(idx, 1);
+ };
+ },
+ has(entity, comp) {
+ return w._components.get(entity as number)?.has(comp) ?? false;
+ },
+ get(entity, comp) {
+ return w._components.get(entity as number)?.get(comp);
+ },
+ insert(entity, comp, data) {
+ const map = w._components.get(entity as number);
+ if (map) map.set(comp, data);
+ },
+ };
+ return w;
+}
+
+const factory = (world: World) => (world as unknown as MockWorld).spawn();
+
+describe('ListView', () => {
+ let world: MockWorld;
+ let parent: Entity;
+
+ beforeEach(() => {
+ world = createWorld();
+ parent = world.spawn();
+ });
+
+ it('mounts visible items + buffer on first update', () => {
+ const data = arrayDataSource(Array.from({ length: 100 }, (_, i) => i));
+ const list = new ListView({
+ world: world as unknown as World,
+ parent,
+ dataSource: data,
+ layout: new LinearLayoutProvider({ itemSize: { x: 100, y: 40 } }),
+ viewportSize: { x: 100, y: 160 }, // 4 visible items
+ templates: { default: { factory, binder: () => {} } },
+ recycleBuffer: 2,
+ });
+
+ list.update();
+
+ // 4 visible + 2 buffer = 6 (no lead buffer at top since scroll=0)
+ // visible range [0,4); bufferedEnd = min(100, 4+2)=6; bufferedStart=max(0,0-2)=0; → 6 items
+ expect(list.getMountedCount()).toBe(6);
+ });
+
+ it('virtualization: 10000-item list mounts only items near viewport', () => {
+ const data = arrayDataSource(Array.from({ length: 10000 }, (_, i) => i));
+ const list = new ListView({
+ world: world as unknown as World,
+ parent,
+ dataSource: data,
+ layout: new LinearLayoutProvider({ itemSize: { x: 100, y: 40 } }),
+ viewportSize: { x: 100, y: 400 }, // 10 visible
+ templates: { default: { factory, binder: () => {} } },
+ recycleBuffer: 3,
+ });
+
+ list.update();
+ // 10 visible + 3 trailing (no lead since scroll=0) = 13
+ expect(list.getMountedCount()).toBe(13);
+
+ list.setScrollOffset({ x: 0, y: 1000 }); // mid-list
+ list.update();
+ // 10 visible + 3 lead + 3 trail = 16
+ expect(list.getMountedCount()).toBe(16);
+
+ // Never near 10000
+ expect(list.getMountedCount()).toBeLessThanOrEqual(20);
+ });
+
+ it('reuses released entities from the pool on scroll', () => {
+ const data = arrayDataSource(Array.from({ length: 100 }, (_, i) => i));
+ const spawnSpy = vi.fn(factory);
+ const list = new ListView({
+ world: world as unknown as World,
+ parent,
+ dataSource: data,
+ layout: new LinearLayoutProvider({ itemSize: { x: 100, y: 40 } }),
+ viewportSize: { x: 100, y: 80 }, // 2 visible
+ templates: { default: { factory: spawnSpy, binder: () => {} } },
+ recycleBuffer: 0,
+ });
+
+ list.update(); // mounts items 0,1 → 2 spawn calls
+ expect(spawnSpy).toHaveBeenCalledTimes(2);
+
+ // Scroll past them; released items should be reused for new mounts.
+ list.setScrollOffset({ x: 0, y: 400 }); // items 10, 11 visible
+ list.update();
+
+ // Zero new spawn calls — pool reuse.
+ expect(spawnSpy).toHaveBeenCalledTimes(2);
+ expect(list.getMountedCount()).toBe(2);
+ });
+
+ it('binder is called with (entity, data, index) for each mounted item', () => {
+ const data = arrayDataSource(['a', 'b', 'c', 'd']);
+ const binder = vi.fn<(entity: Entity, item: string, index: number) => void>();
+ const list = new ListView({
+ world: world as unknown as World,
+ parent,
+ dataSource: data,
+ layout: new LinearLayoutProvider({ itemSize: { x: 100, y: 40 } }),
+ viewportSize: { x: 100, y: 160 },
+ templates: { default: { factory, binder } },
+ recycleBuffer: 0,
+ });
+
+ list.update();
+
+ expect(binder).toHaveBeenCalledTimes(4);
+ const args = binder.mock.calls.map((c) => [c[1], c[2]]);
+ expect(args).toEqual([['a', 0], ['b', 1], ['c', 2], ['d', 3]]);
+ });
+
+ it('datasource change marks the list dirty and re-mounts on next update', () => {
+ const data = arrayDataSource([1, 2]);
+ const list = new ListView({
+ world: world as unknown as World,
+ parent,
+ dataSource: data,
+ layout: new LinearLayoutProvider({ itemSize: { x: 100, y: 40 } }),
+ viewportSize: { x: 100, y: 200 },
+ templates: { default: { factory, binder: () => {} } },
+ recycleBuffer: 0,
+ });
+
+ list.update();
+ expect(list.getMountedCount()).toBe(2);
+
+ data.append([3, 4, 5]);
+ list.update();
+
+ expect(list.getMountedCount()).toBe(5);
+ });
+
+ it('update is a no-op when clean', () => {
+ const data = arrayDataSource([1, 2]);
+ const spawnSpy = vi.fn(factory);
+ const list = new ListView({
+ world: world as unknown as World,
+ parent,
+ dataSource: data,
+ layout: new LinearLayoutProvider({ itemSize: { x: 100, y: 40 } }),
+ viewportSize: { x: 100, y: 200 },
+ templates: { default: { factory: spawnSpy, binder: () => {} } },
+ recycleBuffer: 0,
+ });
+
+ list.update();
+ const countAfterFirst = spawnSpy.mock.calls.length;
+
+ list.update();
+ list.update();
+
+ expect(spawnSpy.mock.calls.length).toBe(countAfterFirst);
+ });
+
+ it('dispose unsubscribes and releases all mounted items', () => {
+ const data = arrayDataSource([1, 2, 3]);
+ const list = new ListView({
+ world: world as unknown as World,
+ parent,
+ dataSource: data,
+ layout: new LinearLayoutProvider({ itemSize: { x: 100, y: 40 } }),
+ viewportSize: { x: 100, y: 200 },
+ templates: { default: { factory, binder: () => {} } },
+ });
+
+ list.update();
+ expect(list.getMountedCount()).toBeGreaterThan(0);
+
+ list.dispose();
+ expect(list.getMountedCount()).toBe(0);
+
+ // After dispose, further data-source events shouldn't reach the list.
+ data.append([4, 5]);
+ list.update(); // should be a no-op (disposed guard)
+ expect(list.getMountedCount()).toBe(0);
+ });
+
+ it('heterogeneous item types route to matching templates', () => {
+ interface Row {
+ kind: 'header' | 'body';
+ text: string;
+ }
+ const data = arrayDataSource<Row>([
+ { kind: 'header', text: 'A' },
+ { kind: 'body', text: 'a' },
+ { kind: 'body', text: 'b' },
+ ]);
+
+ const headerFactory = vi.fn(factory);
+ const bodyFactory = vi.fn(factory);
+
+ const list = new ListView<Row>({
+ world: world as unknown as World,
+ parent,
+ dataSource: {
+ getCount: () => data.getCount(),
+ getItem: (i) => data.getItem(i),
+ getItemType: (i) => data.getItem(i).kind,
+ subscribe: (l) => data.subscribe(l),
+ } as DataSource<Row>,
+ layout: new LinearLayoutProvider({ itemSize: { x: 100, y: 40 } }),
+ viewportSize: { x: 100, y: 160 },
+ templates: {
+ header: { factory: headerFactory, binder: () => {} },
+ body: { factory: bodyFactory, binder: () => {} },
+ },
+ recycleBuffer: 0,
+ });
+
+ list.update();
+
+ expect(headerFactory).toHaveBeenCalledTimes(1);
+ expect(bodyFactory).toHaveBeenCalledTimes(2);
+ });
+});