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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(ui): add P2 Layer 0 infrastructure (UIEventQueue, ViewPool)
esengine68ac0bf320cc
diff --git a/sdk/src/ui2/collection/view-pool.ts b/sdk/src/ui2/collection/view-pool.tsnew file mode 100644index 000000000..98da01460--- /dev/null+++ b/sdk/src/ui2/collection/view-pool.ts@@ -0,0 +1,219 @@+/**+ * @file view-pool.ts+ * @brief Entity recycler for virtualized lists.+ *+ * A ViewPool keeps idle item entities around instead of despawning them,+ * so scrolling through a 10 000-row list only ever has ~(viewport items)+ * active. When an item scrolls off-screen, it is released back to the+ * pool; when a new item scrolls on, one is acquired from the pool (or a+ * fresh one is created).+ *+ * Visibility is toggled through an injected `setVisible` hook; this keeps+ * ViewPool decoupled from the UIRenderer component shape.+ */++import type { Entity } from '../../types';+import type { World } from '../../world';++/**+ * Factory + binder pair for a single item type. Registered per type+ * (e.g. `'default'`, `'header'`, `'footer'`).+ */+export interface ViewPoolTemplate<TData = unknown> {+ /**+ * Create a new entity when the pool has no free instances.+ * Attach any child entities / components needed to render one item.+ */+ factory: (world: World, parent: Entity) => Entity;+ /**+ * Apply data to an entity just acquired from the pool (or freshly+ * created). Called every time the item is bound, so binders must be+ * idempotent — do not rely on prior state.+ */+ binder: (entity: Entity, data: TData, index: number) => void;+}++export interface ViewPoolOptions {+ world: World;+ /**+ * Hook called on acquire/release to toggle item visibility. Default:+ * noop (ViewPool tracks free/used state without touching the entity).+ *+ * Typical implementation toggles `UIRenderer.enabled` on the entity+ * and its UI-visible descendants. Passed as a hook so ViewPool does+ * not depend on the UI primitives.+ */+ setVisible?: (world: World, entity: Entity, visible: boolean) => void;+}++/**+ * Pool of reusable item entities, keyed by item type.+ *+ * @example+ * ```ts+ * const pool = new ViewPool({+ * world,+ * setVisible: (w, e, v) => setEntityEnabled(w, e, v),+ * });+ *+ * pool.setTemplate('default', {+ * factory: (w, parent) => createRow(w, { parent, height: 40 }),+ * binder: (row, data: Player, i) => setText(row.meta.name, data.name),+ * });+ *+ * // when an item scrolls on-screen:+ * const entity = pool.acquire('default', contentEntity);+ * pool.bind('default', entity, players[i], i);+ *+ * // when it scrolls off:+ * pool.release('default', entity);+ * ```+ */+export class ViewPool {+ private readonly world_: World;+ private readonly setVisible_: (+ world: World,+ entity: Entity,+ visible: boolean,+ ) => void;+ private readonly templates_ = new Map<string, ViewPoolTemplate<unknown>>();+ private readonly free_ = new Map<string, Entity[]>();+ private unsubscribeDespawn_: (() => void) | null = null;+ private disposed_ = false;++ constructor(opts: ViewPoolOptions) {+ this.world_ = opts.world;+ this.setVisible_ = opts.setVisible ?? (() => {});++ // Auto-evict pooled entities that are despawned externally (e.g.+ // via cascading despawn from a parent). Without this, the pool+ // would hold dangling IDs that later acquire() would return.+ this.unsubscribeDespawn_ = this.world_.onDespawn((entity) => {+ for (const pool of this.free_.values()) {+ const idx = pool.indexOf(entity);+ if (idx !== -1) pool.splice(idx, 1);+ }+ });+ }++ /**+ * Register a template for an item type. Must be called before+ * `acquire` / `warmup` for that type.+ */+ setTemplate<TData>(itemType: string, template: ViewPoolTemplate<TData>): void {+ this.assertLive_();+ this.templates_.set(itemType, template as ViewPoolTemplate<unknown>);+ if (!this.free_.has(itemType)) this.free_.set(itemType, []);+ }++ /** True if a template has been registered for `itemType`. */+ hasTemplate(itemType: string): boolean {+ return this.templates_.has(itemType);+ }++ /**+ * Get an entity for display. Pops from the pool if available,+ * otherwise invokes the factory. The returned entity is visible.+ */+ acquire(itemType: string, parent: Entity): Entity {+ this.assertLive_();+ const template = this.templates_.get(itemType);+ if (!template) {+ throw new Error(+ `[ViewPool] No template registered for item type "${itemType}".`,+ );+ }++ const pool = this.free_.get(itemType)!;+ let entity: Entity;+ if (pool.length > 0) {+ entity = pool.pop() as Entity;+ this.setVisible_(this.world_, entity, true);+ } else {+ entity = template.factory(this.world_, parent);+ // Newly created entities are assumed visible by their factory.+ }+ return entity;+ }++ /**+ * Bind data to an entity via the registered template's binder.+ * Usually called right after `acquire`.+ */+ bind<TData>(itemType: string, entity: Entity, data: TData, index: number): void {+ this.assertLive_();+ const template = this.templates_.get(itemType);+ if (!template) {+ throw new Error(+ `[ViewPool] No template registered for item type "${itemType}".`,+ );+ }+ (template as ViewPoolTemplate<TData>).binder(entity, data, index);+ }++ /**+ * Return an entity to the pool. The entity is hidden (via `setVisible`)+ * but not despawned. No-op if the entity has already been despawned.+ */+ release(itemType: string, entity: Entity): void {+ this.assertLive_();+ if (!this.world_.valid(entity)) return;+ this.setVisible_(this.world_, entity, false);++ let pool = this.free_.get(itemType);+ if (!pool) {+ pool = [];+ this.free_.set(itemType, pool);+ }+ pool.push(entity);+ }++ /**+ * Pre-create N entities of a type and park them in the pool (hidden).+ * Useful to avoid first-frame allocation spikes.+ */+ warmup(itemType: string, count: number, parent: Entity): void {+ this.assertLive_();+ const template = this.templates_.get(itemType);+ if (!template) {+ throw new Error(+ `[ViewPool] No template registered for item type "${itemType}".`,+ );+ }+ let pool = this.free_.get(itemType);+ if (!pool) {+ pool = [];+ this.free_.set(itemType, pool);+ }+ for (let i = 0; i < count; i++) {+ const entity = template.factory(this.world_, parent);+ this.setVisible_(this.world_, entity, false);+ pool.push(entity);+ }+ }++ /** Number of currently-free entities of the given type. */+ freeCount(itemType: string): number {+ return this.free_.get(itemType)?.length ?? 0;+ }++ /**+ * Release resources: unsubscribe from world events and clear+ * internal tables. Does NOT despawn pooled entities (their lifetime+ * is tied to whatever parent they are attached to).+ */+ dispose(): void {+ if (this.disposed_) return;+ this.disposed_ = true;+ this.unsubscribeDespawn_?.();+ this.unsubscribeDespawn_ = null;+ this.templates_.clear();+ this.free_.clear();+ }++ private assertLive_(): void {+ if (this.disposed_) {+ throw new Error('[ViewPool] Operation on disposed pool.');+ }+ }+}diff --git a/sdk/src/ui2/core/events.ts b/sdk/src/ui2/core/events.tsnew file mode 100644index 000000000..ea7ad23a0--- /dev/null+++ b/sdk/src/ui2/core/events.ts@@ -0,0 +1,279 @@+/**+ * @file events.ts+ * @brief UI event queue with bubbling, per-entity/global handlers, and+ * pending-event queue (drain).+ *+ * v4 redesign: entity subscription is owned by the plugin, which wires+ * `world.onDespawn(e => queue.removeAll(e))` to guarantee cleanup on+ * entity destruction — UIEventQueue itself has no World dependency.+ */++import type { Entity } from '../../types';++/**+ * Common UI event types. Event type strings are open — users may emit any+ * string they like (e.g. `'item_selected'` from a ListView). These constants+ * document the standard set emitted by built-in widgets.+ */+export const UIEventType = {+ Click: 'click',+ Press: 'press',+ Release: 'release',+ HoverEnter: 'hover_enter',+ HoverExit: 'hover_exit',+ Focus: 'focus',+ Blur: 'blur',+ Change: 'change',+ Submit: 'submit',+ DragStart: 'drag_start',+ DragMove: 'drag_move',+ DragEnd: 'drag_end',+ Scroll: 'scroll',+ Select: 'select',+ Deselect: 'deselect',+ StateChanged: 'state_changed',+} as const;++export interface UIEvent<TData = unknown> {+ /** Event type string (e.g. `'click'`, `'state_changed'`). */+ readonly type: string;+ /** The entity where the event originated. */+ readonly target: Entity;+ /** The entity currently handling the event (differs from target during bubbling). */+ readonly currentTarget: Entity;+ /** User-provided payload (shape depends on `type`). */+ readonly data: TData;+ /** True if any handler called `stopPropagation()`. */+ propagationStopped: boolean;+ /** True if any handler called `preventDefault()`. */+ defaultPrevented: boolean;+ /** Stop the event from bubbling further up the parent chain. */+ stopPropagation(): void;+ /** Signal that the default action (if any) should be skipped. */+ preventDefault(): void;+}++export type UIEventHandler<TData = unknown> = (event: UIEvent<TData>) => void;+export type Unsubscribe = () => void;++/**+ * UI event queue: pub/sub with bubbling support.+ *+ * @example+ * ```ts+ * const events = new UIEventQueue();+ * world.onDespawn(e => events.removeAll(e)); // one-time wiring+ *+ * events.on(buttonEntity, 'click', e => console.log('clicked'));+ * events.emit(buttonEntity, 'click');+ * ```+ */+export class UIEventQueue {+ private readonly entityHandlers_ = new Map<+ Entity,+ Map<string, Set<UIEventHandler>>+ >();+ private readonly globalHandlers_ = new Map<string, Set<UIEventHandler>>();+ private pending_: UIEvent[] = [];+ private readonly activeKeys_ = new Set<string>();++ /**+ * Subscribe to an entity-specific event.+ * Returns an unsubscribe function.+ */+ on(entity: Entity, type: string, handler: UIEventHandler): Unsubscribe;+ /**+ * Subscribe to all events of a type, from any entity.+ */+ on(type: string, handler: UIEventHandler): Unsubscribe;+ on(+ arg1: Entity | string,+ arg2: string | UIEventHandler,+ arg3?: UIEventHandler,+ ): Unsubscribe {+ // Entity-specific: on(entity, type, handler)+ if (typeof arg1 === 'number' && typeof arg2 === 'string' && typeof arg3 === 'function') {+ const entity = arg1 as Entity;+ const type = arg2;+ const handler = arg3;++ let typeMap = this.entityHandlers_.get(entity);+ if (!typeMap) {+ typeMap = new Map();+ this.entityHandlers_.set(entity, typeMap);+ }+ let set = typeMap.get(type);+ if (!set) {+ set = new Set();+ typeMap.set(type, set);+ }+ set.add(handler);++ return () => {+ const tm = this.entityHandlers_.get(entity);+ const s = tm?.get(type);+ if (s) {+ s.delete(handler);+ if (s.size === 0) tm!.delete(type);+ if (tm && tm.size === 0) this.entityHandlers_.delete(entity);+ }+ };+ }++ // Global: on(type, handler)+ const type = arg1 as string;+ const handler = arg2 as UIEventHandler;++ let set = this.globalHandlers_.get(type);+ if (!set) {+ set = new Set();+ this.globalHandlers_.set(type, set);+ }+ set.add(handler);++ return () => {+ const s = this.globalHandlers_.get(type);+ if (s) {+ s.delete(handler);+ if (s.size === 0) this.globalHandlers_.delete(type);+ }+ };+ }++ /**+ * Remove all entity-specific handlers for `entity`.+ * Wire this to `world.onDespawn` for automatic cleanup.+ */+ removeAll(entity: Entity): void {+ this.entityHandlers_.delete(entity);+ }++ /**+ * Emit an event for `entity`. Synchronously dispatches to registered+ * handlers and queues the event for `drain()` / `query()`. Returns the+ * event so callers can inspect propagationStopped / defaultPrevented+ * (e.g. to drive bubbling to parents).+ */+ emit<TData = unknown>(+ entity: Entity,+ type: string,+ data?: TData,+ ): UIEvent<TData> {+ const event: UIEvent<TData> = {+ type,+ target: entity,+ currentTarget: entity,+ data: data as TData,+ propagationStopped: false,+ defaultPrevented: false,+ stopPropagation() {+ this.propagationStopped = true;+ },+ preventDefault() {+ this.defaultPrevented = true;+ },+ };+ this.pending_.push(event);+ this.dispatch_(entity, event);+ return event;+ }++ /**+ * Emit a bubbled event to an ancestor. Shares propagation state with+ * the root event: calling stopPropagation on the bubbled event marks+ * the root as stopped so callers can halt the bubbling walk.+ *+ * Callers are responsible for walking the parent chain; this queue+ * does not know about hierarchy.+ */+ emitBubbled(ancestor: Entity, rootEvent: UIEvent): UIEvent {+ if (rootEvent.propagationStopped) return rootEvent;++ const bubbled: UIEvent = {+ type: rootEvent.type,+ target: rootEvent.target,+ currentTarget: ancestor,+ data: rootEvent.data,+ propagationStopped: false,+ defaultPrevented: rootEvent.defaultPrevented,+ stopPropagation() {+ this.propagationStopped = true;+ rootEvent.propagationStopped = true;+ },+ preventDefault() {+ this.defaultPrevented = true;+ (rootEvent as { defaultPrevented: boolean }).defaultPrevented = true;+ },+ };+ this.pending_.push(bubbled);+ this.dispatch_(ancestor, bubbled);+ return bubbled;+ }++ /**+ * Return all events queued since the last drain and clear the queue.+ * Typically called once per frame by a UI system.+ */+ drain(): readonly UIEvent[] {+ const events = this.pending_;+ this.pending_ = [];+ return events;+ }++ /** Non-destructively inspect currently-pending events of a type. */+ query(type: string): readonly UIEvent[] {+ return this.pending_.filter((e) => e.type === type);+ }++ /** Remove all handlers and pending events. */+ clear(): void {+ this.entityHandlers_.clear();+ this.globalHandlers_.clear();+ this.pending_ = [];+ this.activeKeys_.clear();+ }++ private dispatch_(entity: Entity, event: UIEvent): void {+ // Re-entry guard: a handler that emits the same event on the same+ // entity would recurse forever. Block recursion for (entity, type).+ const key = `${entity as number}:${event.type}`;+ if (this.activeKeys_.has(key)) return;+ this.activeKeys_.add(key);++ try {+ const typeMap = this.entityHandlers_.get(entity);+ if (typeMap) {+ const set = typeMap.get(event.type);+ if (set) {+ // Snapshot so handler-side unsubscribe doesn't skip peers+ for (const h of Array.from(set)) {+ try {+ h(event);+ } catch (err) {+ console.error(+ `[UIEventQueue] handler error [${event.type}]:`,+ err,+ );+ }+ }+ }+ }++ const global = this.globalHandlers_.get(event.type);+ if (global) {+ for (const h of Array.from(global)) {+ try {+ h(event);+ } catch (err) {+ console.error(+ `[UIEventQueue] handler error [${event.type}]:`,+ err,+ );+ }+ }+ }+ } finally {+ this.activeKeys_.delete(key);+ }+ }+}diff --git a/sdk/src/ui2/index.ts b/sdk/src/ui2/index.tsnew file mode 100644index 000000000..b242c9335--- /dev/null+++ b/sdk/src/ui2/index.ts@@ -0,0 +1,22 @@+/**+ * @file ui2/index.ts+ * @brief Barrel for the v4 UI framework (WIP).+ *+ * This folder holds the rewritten UI system (see docs/ui-redesign.md).+ * It lives alongside the legacy `src/ui/` until P7, at which point the+ * old folder is removed and this one is renamed back to `ui/`.+ */++export {+ UIEventQueue,+ UIEventType,+ type UIEvent,+ type UIEventHandler,+ type Unsubscribe,+} from './core/events';++export {+ ViewPool,+ type ViewPoolOptions,+ type ViewPoolTemplate,+} from './collection/view-pool';diff --git a/sdk/tests/ui2-events.test.ts b/sdk/tests/ui2-events.test.tsnew file mode 100644index 000000000..9c417e378--- /dev/null+++ b/sdk/tests/ui2-events.test.ts@@ -0,0 +1,223 @@+/**+ * Unit tests for sdk/src/ui2/core/events.ts.+ * Pure TS; no WASM / World required.+ */+import { describe, it, expect, beforeEach, vi } from 'vitest';+import { UIEventQueue, UIEventType, type UIEvent } from '../src/ui2/core/events';+import type { Entity } from '../src/types';++const E1 = 1 as Entity;+const E2 = 2 as Entity;+const E3 = 3 as Entity;++describe('UIEventQueue', () => {+ let q: UIEventQueue;++ beforeEach(() => {+ q = new UIEventQueue();+ });++ describe('subscribe + emit', () => {+ it('fires entity-scoped handler synchronously on emit', () => {+ const fn = vi.fn();+ q.on(E1, UIEventType.Click, fn);+ q.emit(E1, UIEventType.Click);+ expect(fn).toHaveBeenCalledTimes(1);+ });++ it('does not fire handlers for a different entity', () => {+ const fn = vi.fn();+ q.on(E1, UIEventType.Click, fn);+ q.emit(E2, UIEventType.Click);+ expect(fn).not.toHaveBeenCalled();+ });++ it('fires global handler for any entity', () => {+ const fn = vi.fn();+ q.on(UIEventType.Click, fn);+ q.emit(E1, UIEventType.Click);+ q.emit(E2, UIEventType.Click);+ expect(fn).toHaveBeenCalledTimes(2);+ });++ it('supports arbitrary string event types', () => {+ const fn = vi.fn();+ q.on(E1, 'item_selected', fn);+ q.emit(E1, 'item_selected', { index: 3 });+ expect(fn).toHaveBeenCalledOnce();+ expect(fn.mock.calls[0][0].data).toEqual({ index: 3 });+ });+ });++ describe('unsubscribe', () => {+ it('entity unsubscribe stops handler from firing', () => {+ const fn = vi.fn();+ const off = q.on(E1, UIEventType.Click, fn);+ off();+ q.emit(E1, UIEventType.Click);+ expect(fn).not.toHaveBeenCalled();+ });++ it('global unsubscribe stops handler from firing', () => {+ const fn = vi.fn();+ const off = q.on(UIEventType.Click, fn);+ off();+ q.emit(E1, UIEventType.Click);+ expect(fn).not.toHaveBeenCalled();+ });++ it('is idempotent (double unsubscribe safe)', () => {+ const fn = vi.fn();+ const off = q.on(E1, UIEventType.Click, fn);+ off();+ off();+ q.emit(E1, UIEventType.Click);+ expect(fn).not.toHaveBeenCalled();+ });++ it('does not affect other handlers for same event', () => {+ const a = vi.fn();+ const b = vi.fn();+ const offA = q.on(E1, UIEventType.Click, a);+ q.on(E1, UIEventType.Click, b);+ offA();+ q.emit(E1, UIEventType.Click);+ expect(a).not.toHaveBeenCalled();+ expect(b).toHaveBeenCalledOnce();+ });+ });++ describe('removeAll', () => {+ it('removes entity-specific handlers but keeps globals', () => {+ const entityFn = vi.fn();+ const globalFn = vi.fn();+ q.on(E1, UIEventType.Click, entityFn);+ q.on(UIEventType.Click, globalFn);++ q.removeAll(E1);+ q.emit(E1, UIEventType.Click);++ expect(entityFn).not.toHaveBeenCalled();+ expect(globalFn).toHaveBeenCalledOnce();+ });+ });++ describe('drain / query', () => {+ it('drain returns queued events and clears the queue', () => {+ q.emit(E1, UIEventType.Click);+ q.emit(E2, UIEventType.HoverEnter);++ const first = q.drain();+ expect(first).toHaveLength(2);+ expect(first[0].type).toBe(UIEventType.Click);+ expect(first[1].type).toBe(UIEventType.HoverEnter);++ const second = q.drain();+ expect(second).toHaveLength(0);+ });++ it('query filters by type without draining', () => {+ q.emit(E1, UIEventType.Click);+ q.emit(E2, UIEventType.HoverEnter);+ q.emit(E3, UIEventType.Click);++ const clicks = q.query(UIEventType.Click);+ expect(clicks).toHaveLength(2);++ // Queue not consumed+ expect(q.drain()).toHaveLength(3);+ });+ });++ describe('bubbling', () => {+ it('emitBubbled fires ancestor handler and reports target = original entity', () => {+ const parentFn = vi.fn();+ q.on(E2, UIEventType.Click, parentFn);++ const root = q.emit(E1, UIEventType.Click);+ q.emitBubbled(E2, root);++ expect(parentFn).toHaveBeenCalledOnce();+ const evt = parentFn.mock.calls[0][0] as UIEvent;+ expect(evt.target).toBe(E1);+ expect(evt.currentTarget).toBe(E2);+ });++ it('stopPropagation on bubbled event halts further bubbling', () => {+ const b1 = vi.fn((e: UIEvent) => e.stopPropagation());+ const b2 = vi.fn();+ q.on(E2, UIEventType.Click, b1);+ q.on(E3, UIEventType.Click, b2);++ const root = q.emit(E1, UIEventType.Click);+ const afterB1 = q.emitBubbled(E2, root);++ // Respect the intended behavior: caller checks propagationStopped+ expect(afterB1.propagationStopped).toBe(true);+ expect(root.propagationStopped).toBe(true);++ // Caller (e.g. plugin walking the parent chain) would stop here.+ // If they mistakenly call emitBubbled again, handler is NOT invoked.+ q.emitBubbled(E3, root);+ expect(b2).not.toHaveBeenCalled();+ });++ it('preventDefault propagates to the root event', () => {+ q.on(E2, UIEventType.Click, (e) => e.preventDefault());+ const root = q.emit(E1, UIEventType.Click);+ q.emitBubbled(E2, root);+ expect(root.defaultPrevented).toBe(true);+ });+ });++ describe('reentry safety', () => {+ it('does not infinite-loop when a handler re-emits the same event on the same entity', () => {+ let nested = 0;+ q.on(E1, 'ping', () => {+ nested++;+ if (nested < 100) q.emit(E1, 'ping'); // try to recurse+ });+ q.emit(E1, 'ping');+ expect(nested).toBe(1); // reentry blocked+ });++ it('allows handler to emit a different event on the same entity', () => {+ const b = vi.fn();+ q.on(E1, 'a', () => q.emit(E1, 'b'));+ q.on(E1, 'b', b);++ q.emit(E1, 'a');+ expect(b).toHaveBeenCalledOnce();+ });+ });++ describe('error handling', () => {+ it('handler throw does not abort dispatch to peer handlers', () => {+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {});+ const peer = vi.fn();+ q.on(E1, UIEventType.Click, () => { throw new Error('boom'); });+ q.on(E1, UIEventType.Click, peer);++ q.emit(E1, UIEventType.Click);+ expect(peer).toHaveBeenCalledOnce();+ expect(spy).toHaveBeenCalled();+ spy.mockRestore();+ });+ });++ describe('clear', () => {+ it('removes handlers and pending events', () => {+ const fn = vi.fn();+ q.on(E1, UIEventType.Click, fn);+ q.emit(E1, UIEventType.Click);+ expect(fn).toHaveBeenCalledOnce();+ expect(q.query(UIEventType.Click)).toHaveLength(1);++ q.clear();+ expect(q.query(UIEventType.Click)).toHaveLength(0); // pending purged++ q.emit(E1, UIEventType.Click);+ expect(fn).toHaveBeenCalledOnce(); // handler gone+ });+ });+});diff --git a/sdk/tests/ui2-view-pool.test.ts b/sdk/tests/ui2-view-pool.test.tsnew file mode 100644index 000000000..f1184cd87--- /dev/null+++ b/sdk/tests/ui2-view-pool.test.ts@@ -0,0 +1,210 @@+/**+ * Unit tests for sdk/src/ui2/collection/view-pool.ts.+ * Uses a minimal mock World — enough to exercise onDespawn + valid.+ */+import { describe, it, expect, beforeEach, vi } from 'vitest';+import { ViewPool } from '../src/ui2/collection/view-pool';+import type { Entity } from '../src/types';+import type { World } from '../src/world';++// ---- Mock World (minimal surface ViewPool actually uses) ----++interface MockWorld {+ spawn(): Entity;+ despawn(entity: Entity): void;+ valid(entity: Entity): boolean;+ onDespawn(cb: (entity: Entity) => void): () => void;+ _entities: Set<number>;+ _nextId: number;+ _despawnCallbacks: Array<(e: Entity) => void>;+}++function createMockWorld(): MockWorld {+ const w: MockWorld = {+ _entities: new Set<number>(),+ _nextId: 1,+ _despawnCallbacks: [],+ spawn() {+ const id = w._nextId++;+ w._entities.add(id);+ return id as Entity;+ },+ despawn(entity: Entity) {+ for (const cb of w._despawnCallbacks) cb(entity);+ w._entities.delete(entity as number);+ },+ valid(entity: Entity) {+ return w._entities.has(entity as number);+ },+ onDespawn(cb) {+ w._despawnCallbacks.push(cb);+ return () => {+ const idx = w._despawnCallbacks.indexOf(cb);+ if (idx !== -1) w._despawnCallbacks.splice(idx, 1);+ };+ },+ };+ return w;+}++describe('ViewPool', () => {+ let world: MockWorld;+ let pool: ViewPool;+ let setVisible: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ world = createMockWorld();+ setVisible = vi.fn();+ pool = new ViewPool({+ world: world as unknown as World,+ setVisible: (w, e, v) => setVisible(w, e, v),+ });++ pool.setTemplate<{ name: string }>('default', {+ factory: (w) => (w as unknown as MockWorld).spawn(),+ binder: () => { /* noop for test */ },+ });+ });++ describe('acquire / release', () => {+ it('acquire creates a fresh entity when pool is empty', () => {+ const parent = world.spawn();+ const e = pool.acquire('default', parent);+ expect(world.valid(e)).toBe(true);+ expect(pool.freeCount('default')).toBe(0);+ });++ it('acquire does not call setVisible for fresh entities', () => {+ const parent = world.spawn();+ pool.acquire('default', parent);+ expect(setVisible).not.toHaveBeenCalled();+ });++ it('release marks entity invisible and increments free count', () => {+ const parent = world.spawn();+ const e = pool.acquire('default', parent);+ pool.release('default', e);++ expect(setVisible).toHaveBeenCalledWith(+ expect.anything(), e, false,+ );+ expect(pool.freeCount('default')).toBe(1);+ });++ it('acquire reuses a released entity (LIFO) and marks visible', () => {+ const parent = world.spawn();+ const first = pool.acquire('default', parent);+ pool.release('default', first);++ const second = pool.acquire('default', parent);+ expect(second).toBe(first);+ expect(setVisible).toHaveBeenLastCalledWith(+ expect.anything(), first, true,+ );+ expect(pool.freeCount('default')).toBe(0);+ });++ it('throws if acquire is called without a template', () => {+ const parent = world.spawn();+ expect(() => pool.acquire('missing', parent)).toThrow(/No template/);+ });+ });++ describe('bind', () => {+ it('invokes the registered binder', () => {+ const binder = vi.fn();+ pool.setTemplate('typed', {+ factory: () => world.spawn(),+ binder,+ });+ const parent = world.spawn();+ const e = pool.acquire('typed', parent);+ pool.bind('typed', e, { name: 'hi' }, 7);++ expect(binder).toHaveBeenCalledWith(e, { name: 'hi' }, 7);+ });+ });++ describe('warmup', () => {+ it('pre-creates N entities and parks them hidden', () => {+ const parent = world.spawn();+ pool.warmup('default', 5, parent);++ expect(pool.freeCount('default')).toBe(5);+ expect(setVisible).toHaveBeenCalledTimes(5);+ // All calls with visible=false+ for (const call of setVisible.mock.calls) {+ expect(call[2]).toBe(false);+ }+ });++ it('acquire after warmup draws from pool (no new factory call)', () => {+ const parent = world.spawn();+ const factorySpy = vi.fn((w: World, p: Entity) => {+ void p;+ return (w as unknown as MockWorld).spawn();+ });+ pool.setTemplate('spy', { factory: factorySpy, binder: () => {} });++ pool.warmup('spy', 3, parent);+ expect(factorySpy).toHaveBeenCalledTimes(3);++ pool.acquire('spy', parent);+ pool.acquire('spy', parent);+ expect(factorySpy).toHaveBeenCalledTimes(3); // still 3, not 5+ });+ });++ describe('auto-eviction on external despawn', () => {+ it('removes despawned entities from the free list', () => {+ const parent = world.spawn();+ const e1 = pool.acquire('default', parent);+ const e2 = pool.acquire('default', parent);+ pool.release('default', e1);+ pool.release('default', e2);+ expect(pool.freeCount('default')).toBe(2);++ world.despawn(e1); // cascading despawn style+ expect(pool.freeCount('default')).toBe(1);++ // Next acquire should return e2 (the remaining valid one)+ const next = pool.acquire('default', parent);+ expect(next).toBe(e2);+ });++ it('ignores release of already-despawned entity', () => {+ const parent = world.spawn();+ const e = pool.acquire('default', parent);+ world.despawn(e);+ pool.release('default', e);++ expect(pool.freeCount('default')).toBe(0);+ expect(setVisible).not.toHaveBeenCalled();+ });+ });++ describe('dispose', () => {+ it('throws on further operations after dispose', () => {+ const parent = world.spawn();+ pool.dispose();+ expect(() => pool.acquire('default', parent)).toThrow(/disposed/);+ });++ it('dispose is idempotent', () => {+ pool.dispose();+ expect(() => pool.dispose()).not.toThrow();+ });++ it('dispose unsubscribes from onDespawn', () => {+ pool.dispose();+ // Creating a new pool should work fine afterwards+ const pool2 = new ViewPool({ world: world as unknown as World });+ pool2.setTemplate('a', {+ factory: () => world.spawn(),+ binder: () => {},+ });+ const parent = world.spawn();+ expect(() => pool2.acquire('a', parent)).not.toThrow();+ });+ });+});