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
refactor(ui): collapse dual UIEventQueue into one
esengine92a8e30510c1
diff --git a/sdk/src/ui/DragPlugin.ts b/sdk/src/ui/DragPlugin.tsindex 1b722e088..9be5aec0d 100644--- a/sdk/src/ui/DragPlugin.ts+++ b/sdk/src/ui/DragPlugin.ts@@ -13,7 +13,7 @@ import { Draggable, DragState } from './behavior/draggable';import type { DraggableData, DragStateData } from './behavior/draggable';import { UIInteraction } from './behavior/interactable';import type { UIInteractionData } from './behavior/interactable';-import { UIEvents, UIEventQueue } from './UIEvents';+import { UIEvents, UIEventQueue } from './core/events';import { UICameraInfo } from './UICameraInfo';import type { UICameraData } from './UICameraInfo';import { playModeOnly } from '../env';diff --git a/sdk/src/ui/FocusPlugin.ts b/sdk/src/ui/FocusPlugin.tsindex f6c6ad963..a17df929e 100644--- a/sdk/src/ui/FocusPlugin.ts+++ b/sdk/src/ui/FocusPlugin.ts@@ -12,7 +12,7 @@ import type { InteractableData } from './behavior/interactable';import { UIInteraction } from './behavior/interactable';import type { UIInteractionData } from './behavior/interactable';import { playModeOnly } from '../env';-import { UIEvents, UIEventQueue } from './UIEvents';+import { UIEvents, UIEventQueue } from './core/events';import { PluginName } from '../systemLabels';export class FocusPlugin implements Plugin {@@ -86,13 +86,13 @@ export class FocusPlugin implements Plugin {if (prev !== null && world.valid(prev) && world.has(prev, Focusable)) {const prevF = world.get(prev, Focusable) as FocusableData;prevF.isFocused = false;- events.emit(prev, 'blur', prev);+ events.emit(prev, 'blur');}focusManager.focus(entity);const f = world.get(entity, Focusable) as FocusableData;f.isFocused = true;- events.emit(entity, 'focus', entity);+ events.emit(entity, 'focus');}},{ name: 'FocusSystem' }diff --git a/sdk/src/ui/TextInputPlugin.ts b/sdk/src/ui/TextInputPlugin.tsindex 58934f7bf..8648f7751 100644--- a/sdk/src/ui/TextInputPlugin.ts+++ b/sdk/src/ui/TextInputPlugin.ts@@ -10,7 +10,7 @@ import type { UIRendererData } from './core/ui-renderer';import { Interactable } from './behavior/interactable';import { Focusable } from './behavior/focusable';import { FocusManager, FocusManagerState } from './behavior/focusable';-import { UIEvents, UIEventQueue } from './UIEvents';+import { UIEvents, UIEventQueue } from './core/events';import { Res } from '../resource';import { platformCreateCanvas } from '../platform';import { requireResourceManager } from '../resourceManager';diff --git a/sdk/src/ui/UIEvents.ts b/sdk/src/ui/UIEvents.tsdeleted file mode 100644index 5bc2ec13f..000000000--- a/sdk/src/ui/UIEvents.ts+++ /dev/null@@ -1,168 +0,0 @@-import { defineResource } from '../resource';-import type { Entity } from '../types';--export type UIEventType = 'click' | 'press' | 'release' | 'hover_enter' | 'hover_exit' | 'focus' | 'blur' | 'submit' | 'change' | 'drag_start' | 'drag_move' | 'drag_end' | 'scroll' | 'select' | 'deselect';--export type UIEventHandler = (event: UIEvent) => void;-export type Unsubscribe = () => void;--export interface UIEvent {- entity: Entity;- type: UIEventType;- target: Entity;- currentTarget: Entity;- propagationStopped: boolean;- stopPropagation(): void;-}--export class UIEventQueue {- private events_: UIEvent[] = [];- private entityTypeHandlers_ = new Map<Entity, Map<UIEventType, UIEventHandler[]>>();- private globalHandlers_ = new Map<UIEventType, UIEventHandler[]>();- private activeDispatches_ = new Set<string>();- private entityValidator_: ((entity: Entity) => boolean) | null = null;-- on(entity: Entity, type: UIEventType, handler: UIEventHandler): Unsubscribe;- on(type: UIEventType, handler: UIEventHandler): Unsubscribe;- on(- entityOrType: Entity | UIEventType,- typeOrHandler: UIEventType | UIEventHandler,- handler?: UIEventHandler,- ): Unsubscribe {- if (handler !== undefined) {- const entity = entityOrType as Entity;- const type = typeOrHandler as UIEventType;- let typeMap = this.entityTypeHandlers_.get(entity);- if (!typeMap) {- typeMap = new Map();- this.entityTypeHandlers_.set(entity, typeMap);- }- let handlers = typeMap.get(type);- if (!handlers) {- handlers = [];- typeMap.set(type, handlers);- }- handlers.push(handler);- let removed = false;- return () => {- if (removed) return;- removed = true;- const arr = typeMap!.get(type);- if (arr) {- const idx = arr.indexOf(handler);- if (idx !== -1) arr.splice(idx, 1);- }- };- } else {- const type = entityOrType as UIEventType;- const h = typeOrHandler as UIEventHandler;- let handlers = this.globalHandlers_.get(type);- if (!handlers) {- handlers = [];- this.globalHandlers_.set(type, handlers);- }- handlers.push(h);- let removed = false;- return () => {- if (removed) return;- removed = true;- const arr = this.globalHandlers_.get(type);- if (arr) {- const idx = arr.indexOf(h);- if (idx !== -1) arr.splice(idx, 1);- }- };- }- }-- removeAll(entity: Entity): void {- this.entityTypeHandlers_.delete(entity);- }-- setEntityValidator(validator: (entity: Entity) => boolean): void {- this.entityValidator_ = validator;- }-- emit(entity: Entity, type: UIEventType, target?: Entity): UIEvent {- const t = target ?? entity;- const event: UIEvent = {- entity, type, target: t, currentTarget: entity,- propagationStopped: false,- stopPropagation() { this.propagationStopped = true; },- };- this.events_.push(event);-- const key = `${entity as number}:${type}`;- if (!this.activeDispatches_.has(key)) {- this.activeDispatches_.add(key);- this.dispatchToHandlers_(event);- this.activeDispatches_.delete(key);- }-- return event;- }-- emitBubbled(entity: Entity, type: UIEventType, target: Entity, shared: UIEvent): void {- const event: UIEvent = {- entity, type, target, currentTarget: entity,- propagationStopped: false,- stopPropagation() { shared.propagationStopped = true; },- };- this.events_.push(event);-- const key = `${entity as number}:${type}`;- if (!this.activeDispatches_.has(key)) {- this.activeDispatches_.add(key);- this.dispatchToHandlers_(event);- this.activeDispatches_.delete(key);- }- }-- drain(): UIEvent[] {- if (this.entityValidator_) {- for (const entity of this.entityTypeHandlers_.keys()) {- if (!this.entityValidator_(entity)) {- this.entityTypeHandlers_.delete(entity);- }- }- }- const events = this.events_;- this.events_ = [];- return events;- }-- query(type: UIEventType): UIEvent[] {- return this.events_.filter(e => e.type === type);- }-- hasEvent(entity: Entity, type: UIEventType): boolean {- return this.events_.some(e => e.entity === entity && e.type === type);- }-- private dispatchToHandlers_(event: UIEvent): void {- const typeMap = this.entityTypeHandlers_.get(event.entity);- if (typeMap) {- const handlers = typeMap.get(event.type);- if (handlers) {- this.invokeHandlers_([...handlers], event);- }- }-- const globalHandlers = this.globalHandlers_.get(event.type);- if (globalHandlers) {- this.invokeHandlers_([...globalHandlers], event);- }- }-- private invokeHandlers_(handlers: UIEventHandler[], event: UIEvent): void {- for (const handler of handlers) {- try {- handler(event);- } catch (e) {- console.error(`UIEvent handler error [${event.type}]:`, e);- }- }- }-}--export const UIEvents = defineResource<UIEventQueue>(new UIEventQueue(), 'UIEvents');diff --git a/sdk/src/ui/UIInteractionPlugin.ts b/sdk/src/ui/UIInteractionPlugin.tsindex a1c64d341..3e1aaf00d 100644--- a/sdk/src/ui/UIInteractionPlugin.ts+++ b/sdk/src/ui/UIInteractionPlugin.ts@@ -10,8 +10,7 @@ import { playModeOnly } from '../env';import { Interactable } from './behavior/interactable';import { UIInteraction } from './behavior/interactable';import type { UIInteractionData } from './behavior/interactable';-import { UIEvents, UIEventQueue } from './UIEvents';-import type { UIEventType } from './UIEvents';+import { UIEvents, UIEventQueue, UIEventType } from './core/events';import { UICameraInfo } from './UICameraInfo';import type { UICameraData } from './UICameraInfo';import type { InteractableData } from './behavior/interactable';@@ -30,16 +29,16 @@ function emitWithBubbling(world: World,events: UIEventQueue,entity: Entity,- type: UIEventType+ type: string,): void {- const event = events.emit(entity, type, entity);+ const event = events.emit(entity, type);walkParentChain(world, entity, (ancestor) => {if (event.propagationStopped) return true;if (!world.has(ancestor, Interactable)) return false;const interactable = world.get(ancestor, Interactable) as InteractableData;if (interactable.enabled) {- events.emitBubbled(ancestor, type, entity, event);+ events.emitBubbled(ancestor, event);}return interactable.blockRaycast;});@@ -56,8 +55,11 @@ export class UIInteractionPlugin implements Plugin {const module = app.wasmModule as ESEngineModule;const registry = world.getCppRegistry() as CppRegistry;const events = new UIEventQueue();- events.setEntityValidator((e) => world.valid(e));app.insertResource(UIEvents, events);+ // Prune handlers when an entity dies. Replaces the old+ // setEntityValidator pattern; canonical UIEventQueue has no+ // validator hook because it's the plugin's job to wire cleanup.+ app.world.onDespawn((e) => events.removeAll(e));let hoveredEntity: Entity | null = null;let pressedEntity: Entity | null = null;@@ -130,14 +132,14 @@ export class UIInteractionPlugin implements Plugin {const prev = world.get(hoveredEntity, UIInteraction) as UIInteractionData;prev.hovered = false;world.insert(hoveredEntity, UIInteraction, prev);- events.emit(hoveredEntity, 'hover_exit');+ events.emit(hoveredEntity, UIEventType.HoverExit);}if (hitEntity !== null) {ensureComponent(world, hitEntity, UIInteraction);const curr = world.get(hitEntity, UIInteraction) as UIInteractionData;curr.hovered = true;world.insert(hitEntity, UIInteraction, curr);- events.emit(hitEntity, 'hover_enter');+ events.emit(hitEntity, UIEventType.HoverEnter);}hoveredEntity = hitEntity;}@@ -148,7 +150,7 @@ export class UIInteractionPlugin implements Plugin {interaction.justPressed = true;world.insert(hitEntity, UIInteraction, interaction);pressedEntity = hitEntity;- emitWithBubbling(world, events, hitEntity, 'press');+ emitWithBubbling(world, events, hitEntity, UIEventType.Press);}if (mouseReleased && pressedEntity !== null) {@@ -157,9 +159,9 @@ export class UIInteractionPlugin implements Plugin {interaction.pressed = false;interaction.justReleased = true;world.insert(pressedEntity, UIInteraction, interaction);- emitWithBubbling(world, events, pressedEntity, 'release');+ emitWithBubbling(world, events, pressedEntity, UIEventType.Release);if (pressedEntity === hoveredEntity) {- emitWithBubbling(world, events, pressedEntity, 'click');+ emitWithBubbling(world, events, pressedEntity, UIEventType.Click);}}pressedEntity = null;diff --git a/sdk/src/ui/core/events.ts b/sdk/src/ui/core/events.tsindex d3668727f..a48fb5e2e 100644--- a/sdk/src/ui/core/events.ts+++ b/sdk/src/ui/core/events.ts@@ -25,6 +25,13 @@ export const UIEventType = {StateChanged: 'state_changed',} as const;+/**+ * Union of the string values in `UIEventType`. Event emitters accept+ * any string (widgets may define their own), but consumers can narrow+ * to this type when they only handle built-ins.+ */+export type UIEventType = typeof UIEventType[keyof typeof UIEventType];+export interface UIEvent<TData = unknown> {/** Event type string (e.g. `'click'`, `'state_changed'`). */readonly type: string;@@ -271,6 +278,11 @@ export class UIEventQueue {/*** Shared UIEventQueue resource. A plugin inserts the authoritative- * instance on startup; systems access it via `Res(UIEventBus)`.+ * instance on startup; systems access it via `Res(UIEvents)`.+ *+ * The default value exists only so the resource is well-typed before+ * the owning plugin constructs the real queue. Consumers should never+ * see the placeholder at runtime — UIInteractionPlugin inserts its+ * queue during `build()`.*/-export const UIEventBus = defineResource<UIEventQueue>(new UIEventQueue(), 'UIEventBus');+export const UIEvents = defineResource<UIEventQueue>(new UIEventQueue(), 'UIEvents');diff --git a/sdk/src/ui/index.ts b/sdk/src/ui/index.tsindex d92f2be22..545470622 100644--- a/sdk/src/ui/index.ts+++ b/sdk/src/ui/index.ts@@ -54,18 +54,14 @@ export {// ─── Layer 0: Events ────────────────────────────────────────────────────────export {+ UIEvents,UIEventQueue,UIEventType,- UIEventBus,type UIEvent,type UIEventHandler,type Unsubscribe,} from './core/events';-// Legacy UIEvents resource (still used by UIInteractionPlugin / DragPlugin /-// FocusPlugin / TextInputPlugin until those migrate to UIEventBus).-export { UIEvents } from './UIEvents';-// ─── Layer 1: Primitives ────────────────────────────────────────────────────export { UIRect, type UIRectData } from './core/ui-rect';diff --git a/sdk/src/ui/plugin.ts b/sdk/src/ui/plugin.tsindex f4b5c1b5d..2449346a6 100644--- a/sdk/src/ui/plugin.ts+++ b/sdk/src/ui/plugin.ts@@ -4,7 +4,8 @@ import { defineSystem, Schedule } from '../system';import { Input, type InputState } from '../input';import type { Entity } from '../types';-import { UIEventBus, UIEventQueue } from './core/events';+import { UIEvents, UIEventQueue } from './core/events';+import { PluginName } from '../systemLabels';import {createInteractableDriverSystem,createStateMachineDiffSystem,@@ -23,6 +24,7 @@ import { UIInteraction, type UIInteractionData } from './behavior/interactable';*/export class UIBehaviorPlugin implements Plugin {name = 'uiBehavior';+ dependencies = [PluginName.UIInteraction];private events_: UIEventQueue | null = null;private listViews_: ListViewRegistry | null = null;@@ -67,10 +69,11 @@ export class UIBehaviorPlugin implements Plugin {}build(app: App): void {- const events = new UIEventQueue();+ // UIInteractionPlugin (declared as our dependency) owns the+ // UIEvents resource and wires onDespawn cleanup. We just grab+ // the queue so our systems emit into the same bus.+ const events = app.getResource(UIEvents) as UIEventQueue;this.events_ = events;- app.insertResource(UIEventBus, events);- app.world.onDespawn((entity) => events.removeAll(entity));const listViews = new ListViewRegistry();this.listViews_ = listViews;diff --git a/sdk/tests/nested-text.test.ts b/sdk/tests/nested-text.test.tsindex eccafd24f..eae9a23da 100644--- a/sdk/tests/nested-text.test.ts+++ b/sdk/tests/nested-text.test.ts@@ -15,7 +15,7 @@ import { UIRect } from '../src/ui/core/ui-rect';import type { UIRectData } from '../src/ui/core/ui-rect';import { UICameraInfo } from '../src/ui/UICameraInfo';import { Input, InputState } from '../src/input';-import { UIEvents, UIEventQueue } from '../src/ui/UIEvents';+import { UIEvents, UIEventQueue } from '../src/ui/core/events';import { uiLayoutPlugin } from '../src/ui/UILayoutPlugin';import { uiRenderOrderPlugin } from '../src/ui/UIRenderOrderPlugin';import { Text } from '../src/ui/core/text';diff --git a/sdk/tests/scrollview.test.ts b/sdk/tests/scrollview.test.tsindex 9f50b3dba..af873e619 100644--- a/sdk/tests/scrollview.test.ts+++ b/sdk/tests/scrollview.test.ts@@ -7,7 +7,7 @@ import type { TransformData } from '../src/component';import { UIRect } from '../src/ui/core/ui-rect';import { UICameraInfo } from '../src/ui/UICameraInfo';import { Input, InputState } from '../src/input';-import { UIEvents, UIEventQueue } from '../src/ui/UIEvents';+import { UIEvents, UIEventQueue } from '../src/ui/core/events';import { uiLayoutPlugin } from '../src/ui/UILayoutPlugin';import { uiRenderOrderPlugin } from '../src/ui/UIRenderOrderPlugin';import { scrollViewPlugin } from '../src/ui/ScrollViewPlugin';diff --git a/sdk/tests/text-multi-render.test.ts b/sdk/tests/text-multi-render.test.tsindex ac204eb3d..986a816ef 100644--- a/sdk/tests/text-multi-render.test.ts+++ b/sdk/tests/text-multi-render.test.ts@@ -12,7 +12,7 @@ import type { SpriteData } from '../src/component';import { UIRect } from '../src/ui/core/ui-rect';import { UICameraInfo } from '../src/ui/UICameraInfo';import { Input, InputState } from '../src/input';-import { UIEvents, UIEventQueue } from '../src/ui/UIEvents';+import { UIEvents, UIEventQueue } from '../src/ui/core/events';import { uiLayoutPlugin } from '../src/ui/UILayoutPlugin';import { uiRenderOrderPlugin } from '../src/ui/UIRenderOrderPlugin';import { textPlugin } from '../src/ui/TextPlugin';diff --git a/sdk/tests/ui-events.test.ts b/sdk/tests/ui-events.test.tsdeleted file mode 100644index c6798554c..000000000--- a/sdk/tests/ui-events.test.ts+++ /dev/null@@ -1,267 +0,0 @@-import { describe, it, expect, vi } from 'vitest';-import { UIEventQueue } from '../src/ui/UIEvents';-import type { UIEvent, UIEventType } from '../src/ui/UIEvents';-import type { Entity } from '../src/types';--function createQueue(): UIEventQueue {- return new UIEventQueue();-}--describe('UIEventQueue callback API', () => {- describe('on(entity, type, handler)', () => {- it('should invoke handler when matching event is emitted', () => {- const q = createQueue();- const handler = vi.fn();- q.on(1 as Entity, 'click', handler);- q.emit(1 as Entity, 'click');- expect(handler).toHaveBeenCalledTimes(1);- expect(handler.mock.calls[0][0].entity).toBe(1);- expect(handler.mock.calls[0][0].type).toBe('click');- });-- it('should not invoke handler for different entity', () => {- const q = createQueue();- const handler = vi.fn();- q.on(1 as Entity, 'click', handler);- q.emit(2 as Entity, 'click');- expect(handler).not.toHaveBeenCalled();- });-- it('should not invoke handler for different event type', () => {- const q = createQueue();- const handler = vi.fn();- q.on(1 as Entity, 'click', handler);- q.emit(1 as Entity, 'press');- expect(handler).not.toHaveBeenCalled();- });-- it('should support multiple handlers on same entity+type', () => {- const q = createQueue();- const h1 = vi.fn();- const h2 = vi.fn();- q.on(1 as Entity, 'click', h1);- q.on(1 as Entity, 'click', h2);- q.emit(1 as Entity, 'click');- expect(h1).toHaveBeenCalledTimes(1);- expect(h2).toHaveBeenCalledTimes(1);- });- });-- describe('on(type, handler) - global', () => {- it('should invoke handler for any entity emitting matching type', () => {- const q = createQueue();- const handler = vi.fn();- q.on('click', handler);- q.emit(1 as Entity, 'click');- q.emit(2 as Entity, 'click');- expect(handler).toHaveBeenCalledTimes(2);- });-- it('should not invoke handler for different type', () => {- const q = createQueue();- const handler = vi.fn();- q.on('click', handler);- q.emit(1 as Entity, 'press');- expect(handler).not.toHaveBeenCalled();- });- });-- describe('both entity and global handlers fire', () => {- it('should invoke entity handler then global handler', () => {- const q = createQueue();- const order: string[] = [];- q.on(1 as Entity, 'click', () => order.push('entity'));- q.on('click', () => order.push('global'));- q.emit(1 as Entity, 'click');- expect(order).toEqual(['entity', 'global']);- });- });-- describe('Unsubscribe', () => {- it('should stop invoking handler after unsubscribe', () => {- const q = createQueue();- const handler = vi.fn();- const unsub = q.on(1 as Entity, 'click', handler);- q.emit(1 as Entity, 'click');- expect(handler).toHaveBeenCalledTimes(1);-- unsub();- q.emit(1 as Entity, 'click');- expect(handler).toHaveBeenCalledTimes(1);- });-- it('should stop invoking global handler after unsubscribe', () => {- const q = createQueue();- const handler = vi.fn();- const unsub = q.on('click', handler);- q.emit(1 as Entity, 'click');- unsub();- q.emit(1 as Entity, 'click');- expect(handler).toHaveBeenCalledTimes(1);- });-- it('should be safe to call unsubscribe multiple times', () => {- const q = createQueue();- const handler = vi.fn();- const unsub = q.on(1 as Entity, 'click', handler);- unsub();- unsub();- q.emit(1 as Entity, 'click');- expect(handler).not.toHaveBeenCalled();- });- });-- describe('removeAll', () => {- it('should remove all handlers for an entity', () => {- const q = createQueue();- const h1 = vi.fn();- const h2 = vi.fn();- q.on(1 as Entity, 'click', h1);- q.on(1 as Entity, 'press', h2);- q.removeAll(1 as Entity);- q.emit(1 as Entity, 'click');- q.emit(1 as Entity, 'press');- expect(h1).not.toHaveBeenCalled();- expect(h2).not.toHaveBeenCalled();- });-- it('should not affect other entities', () => {- const q = createQueue();- const h1 = vi.fn();- const h2 = vi.fn();- q.on(1 as Entity, 'click', h1);- q.on(2 as Entity, 'click', h2);- q.removeAll(1 as Entity);- q.emit(2 as Entity, 'click');- expect(h2).toHaveBeenCalledTimes(1);- });- });-- describe('emitBubbled dispatches to handlers', () => {- it('should dispatch to handlers registered on the bubbled entity', () => {- const q = createQueue();- const handler = vi.fn();- q.on(10 as Entity, 'click', handler);- const shared = q.emit(5 as Entity, 'click');- q.emitBubbled(10 as Entity, 'click', 5 as Entity, shared);- expect(handler).toHaveBeenCalledTimes(1);- expect(handler.mock.calls[0][0].entity).toBe(10);- expect(handler.mock.calls[0][0].target).toBe(5);- });- });-- describe('exception handling', () => {- it('should not stop other handlers when one throws', () => {- const q = createQueue();- const h1 = vi.fn(() => { throw new Error('boom'); });- const h2 = vi.fn();- q.on(1 as Entity, 'click', h1);- q.on(1 as Entity, 'click', h2);-- const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});- q.emit(1 as Entity, 'click');- expect(h2).toHaveBeenCalledTimes(1);- expect(consoleSpy).toHaveBeenCalled();- consoleSpy.mockRestore();- });-- it('should not stop global handlers when entity handler throws', () => {- const q = createQueue();- const h1 = vi.fn(() => { throw new Error('boom'); });- const h2 = vi.fn();- q.on(1 as Entity, 'click', h1);- q.on('click', h2);-- const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});- q.emit(1 as Entity, 'click');- expect(h2).toHaveBeenCalledTimes(1);- consoleSpy.mockRestore();- });- });-- describe('reentrant dispatch protection', () => {- it('should prevent same entity+type from recursively dispatching', () => {- const q = createQueue();- let count = 0;- q.on(1 as Entity, 'click', () => {- count++;- q.emit(1 as Entity, 'click');- });- q.emit(1 as Entity, 'click');- expect(count).toBe(1);- });-- it('should allow different entity+type chains', () => {- const q = createQueue();- const order: string[] = [];- q.on(1 as Entity, 'click', () => {- order.push('A.click');- q.emit(2 as Entity, 'focus');- });- q.on(2 as Entity, 'focus', () => {- order.push('B.focus');- });- q.emit(1 as Entity, 'click');- expect(order).toEqual(['A.click', 'B.focus']);- });-- it('should still enqueue event even when dispatch is skipped', () => {- const q = createQueue();- q.on(1 as Entity, 'click', () => {- q.emit(1 as Entity, 'click');- });- q.emit(1 as Entity, 'click');- expect(q.hasEvent(1 as Entity, 'click')).toBe(true);- });- });-- describe('drain cleans up invalid entities', () => {- it('should remove handlers for invalid entities during drain', () => {- const q = createQueue();- const handler = vi.fn();- q.on(1 as Entity, 'click', handler);- q.setEntityValidator((e) => e !== (1 as Entity));- q.drain();- q.emit(1 as Entity, 'click');- expect(handler).not.toHaveBeenCalled();- });-- it('should keep handlers for valid entities', () => {- const q = createQueue();- const handler = vi.fn();- q.on(1 as Entity, 'click', handler);- q.setEntityValidator(() => true);- q.drain();- q.emit(1 as Entity, 'click');- expect(handler).toHaveBeenCalledTimes(1);- });- });-- describe('existing API unchanged', () => {- it('emit still queues events for hasEvent/query', () => {- const q = createQueue();- q.emit(1 as Entity, 'click');- expect(q.hasEvent(1 as Entity, 'click')).toBe(true);- expect(q.query('click')).toHaveLength(1);- });-- it('drain clears the event queue', () => {- const q = createQueue();- q.emit(1 as Entity, 'click');- const drained = q.drain();- expect(drained).toHaveLength(1);- expect(q.hasEvent(1 as Entity, 'click')).toBe(false);- });- });-- describe('unsubscribe during dispatch is safe', () => {- it('should not skip handlers when earlier handler unsubscribes', () => {- const q = createQueue();- const h2 = vi.fn();- const unsub = q.on(1 as Entity, 'click', () => { unsub(); });- q.on(1 as Entity, 'click', h2);- q.emit(1 as Entity, 'click');- expect(h2).toHaveBeenCalledTimes(1);- });- });-});