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
fix(ui): reconcile dropdown options and guard popup teardown
yhhba61670f1702
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8498694a4..67f2b14a5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,8 @@ published separately; it ships inside the editor.### Fixed+- **Dropdown labels and open rows follow live option edits.** Renames and label replacements repaint without a false selection event; changed option lists or row heights rebuild an open popup and keep the selection in range. Stale rows cannot choose a newly substituted option, popup teardown cannot resurrect a disposed owner, and change callbacks may remove later controls safely.+- **Toggle indicators follow target replacements safely.** Replacing a check entity immediately applies the current on/off state without a false change event. Change callbacks may dispose later toggles in the same update, while stable frames avoid repeated visual writes and reuse cached state during transitions.- **Slider capture expires with input and target availability.** Disabled, inactive or hidden tracks and lost pointer projections cancel capture before a value update, so restoring the control cannot resume an old drag. A consumed release followed by another press cannot retain capture, and track width is read from the slider's own World instead of shared UI helper bindings.diff --git a/sdk/src/ui/behavior/dropdown.ts b/sdk/src/ui/behavior/dropdown.tsindex b11a6bffe..b80fb8d46 100644--- a/sdk/src/ui/behavior/dropdown.ts+++ b/sdk/src/ui/behavior/dropdown.ts@@ -54,6 +54,14 @@ interface PopupState {panel: Entity;rows: Entity[];unsubs: Array<() => void>;+ options: string[];+ optionHeight: number;+}++function popupMatches(p: PopupState, d: UIDropdownData): boolean {+ if (p.optionHeight !== d.optionHeight || p.options.length !== d.options.length) return false;+ for (let i = 0; i < p.options.length; i++) if (p.options[i] !== d.options[i]) return false;+ return true;}// Popup registries are runtime-only and per-world (unit tests run many worlds).@@ -83,8 +91,9 @@ export function closeDropdown(world: World, e: Entity): void {export function openDropdown(world: World, events: UIEventQueue, e: Entity): void {const popups = popupsOf(world);- if (popups.has(e) || !world.has(e, UIDropdown)) return;+ if (popups.has(e) || !world.valid(e) || !world.has(e, UIDropdown)) return;const d = world.get(e, UIDropdown) as UIDropdownData;+ const options = [...d.options], optionHeight = d.optionHeight;// Fresh theme resolution per open — the popup is transient, so a stale// capture would pin whatever theme was active earlier.@@ -98,7 +107,7 @@ export function openDropdown(world: World, events: UIEventQueue, e: Entity): voiinsetLeft: px(0),insetRight: px(0),insetTop: percent(100),- height: px(d.options.length * d.optionHeight),+ height: px(options.length * optionHeight),},visual: { color: t.surfaceElevated },});@@ -106,7 +115,7 @@ export function openDropdown(world: World, events: UIEventQueue, e: Entity): voiconst unsubs: Array<() => void> = [];const rows: Entity[] = [];- for (let i = 0; i < d.options.length; i++) {+ for (let i = 0; i < options.length; i++) {const row = spawnUIEntity({world,parent: panel,@@ -114,8 +123,8 @@ export function openDropdown(world: World, events: UIEventQueue, e: Entity): voiposition: 1,insetLeft: px(0),insetRight: px(0),- insetTop: px(i * d.optionHeight),- height: px(d.optionHeight),+ insetTop: px(i * optionHeight),+ height: px(optionHeight),},visual: { color: t.control },});@@ -145,14 +154,16 @@ export function openDropdown(world: World, events: UIEventQueue, e: Entity): voiworld,parent: row,node: { fill: true },- text: { content: d.options[i]!, color: t.text },+ text: { content: options[i]!, color: t.text },});markThemed(world, rowLabel, { text: 'text' });const index = i;unsubs.push(events.on(row, UIEventType.Click, () => {- const cur = world.get(e, UIDropdown) as UIDropdownData;closeDropdown(world, e);+ if (!world.valid(e) || !world.has(e, UIDropdown)) return;+ const cur = world.get(e, UIDropdown) as UIDropdownData;+ if (cur.options[index] !== options[index]) return;if (cur.selectedIndex !== index) {cur.selectedIndex = index;world.insert(e, UIDropdown, cur);@@ -160,7 +171,7 @@ export function openDropdown(world: World, events: UIEventQueue, e: Entity): voi}));rows.push(row);}- popups.set(e, { panel, rows, unsubs });+ popups.set(e, { panel, rows, unsubs, options, optionHeight });highlightRow(world, rows, d.selectedIndex);}@@ -204,7 +215,7 @@ function insideAnyPopup(world: World, entity: Entity): boolean {* Popup lifecycle + selection + keyboard + label sync for every UIDropdown.*/export function createDropdownSystem(world: World, events: UIEventQueue): SystemDef {- const shown = new EntityStateMap<number>(); // last index whose label was applied+ const shown = new EntityStateMap<{ index: number; label: Entity; content: string }>();// One global click handler arbitrates: the dropdown root toggles its own// popup; a click inside a popup is the row handler's business; any other@@ -230,7 +241,21 @@ export function createDropdownSystem(world: World, events: UIEventQueue): Systemreturn defineSystem([Res(Input)], (input: InputState) => {for (const e of world.getEntitiesWithComponents([UIDropdown])) {- const d = world.get(e, UIDropdown) as UIDropdownData;+ if (!world.valid(e) || !world.has(e, UIDropdown)) continue;+ let d = world.get(e, UIDropdown) as UIDropdownData;+ const index = Number.isFinite(d.selectedIndex) ? Math.trunc(d.selectedIndex) : 0;+ const clamped = Math.max(0, Math.min(index, d.options.length - 1));+ if (clamped !== d.selectedIndex) {+ d.selectedIndex = clamped;+ world.insert(e, UIDropdown, d);+ }+ const previousPopup = popupsOf(world).get(e);+ if (previousPopup && !popupMatches(previousPopup, d)) {+ closeDropdown(world, e);+ if (!world.valid(e) || !world.has(e, UIDropdown)) continue;+ openDropdown(world, events, e);+ d = world.get(e, UIDropdown) as UIDropdownData;+ }// Keyboard: arrows step the selection whether the popup is open// (moving the row highlight) or closed (the native <select>@@ -253,14 +278,21 @@ export function createDropdownSystem(world: World, events: UIEventQueue): System}}+ if (!world.valid(e) || !world.has(e, UIDropdown)) continue;+// Selection → label + row highlight + change event, whoever wrote// the index.- if (shown.get(e) !== d.selectedIndex) {- const emitChange = shown.has(e); // first sync is initial paint- shown.set(e, d.selectedIndex);+ const content = d.options[d.selectedIndex] ?? '';+ const previous = shown.get(e);+ if (!previous || previous.index !== d.selectedIndex || previous.label !== d.label || previous.content !== content) {+ const emitChange = previous !== undefined && previous.index !== d.selectedIndex;+ if (previous) {+ previous.index = d.selectedIndex; previous.label = d.label; previous.content = content;+ } else {+ shown.set(e, { index: d.selectedIndex, label: d.label, content });+ }if (world.valid(d.label) && world.has(d.label, Text)) {const txt = world.get(d.label, Text) as TextData;- const content = d.options[d.selectedIndex] ?? '';if (txt.content !== content) {txt.content = content;world.insert(d.label, Text, txt);diff --git a/sdk/tests/ui-dropdown-options-wasm.test.ts b/sdk/tests/ui-dropdown-options-wasm.test.tsnew file mode 100644index 000000000..45988c103--- /dev/null+++ b/sdk/tests/ui-dropdown-options-wasm.test.ts@@ -0,0 +1,80 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import { App } from '../src/app/app';+import { AppContext, setDefaultContext } from '../src/ecs/context';+import { Schedule } from '../src/ecs/system';+import { Parent } from '../src/ecs/component';+import { Text } from '../src/ui/core/text';+import { UIEventQueue } from '../src/ui/core/events';+import { UIDropdown, createDropdownSystem } from '../src/ui/behavior/dropdown';+import { createDropdown } from '../src/ui/widgets/dropdown';+import { UIController } from '../src/ui/controller/ui-controller';+import type { CppRegistry, ESEngineModule } from '../src/wasm';+import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';++describe.skipIf(!HAS_WASM)('dropdown live options on real WASM', () => {+ let engine: ESEngineModule, registry: CppRegistry, app: App, events: UIEventQueue;+ beforeAll(async () => { engine = await loadWasmModule(); });+ beforeEach(() => {+ setDefaultContext(new AppContext()); registry = new engine.Registry();+ app = App.new(); app.connectCpp(registry, engine); events = new UIEventQueue();+ app.addSystemToSchedule(Schedule.Update, createDropdownSystem(app.world, events));+ });+ afterEach(() => { app.quit({ keepRenderer: true }); registry.delete(); });+ it('renaming the selected option repaints the label without changing selection', async () => {+ const changed = vi.fn(), dd = createDropdown({ world: app.world, events, options: ['old'], onSelect: changed });+ await app.tick(1 / 60);+ app.world.update(dd.entity, UIDropdown, d => { d.options[0] = 'new'; }); await app.tick(1 / 60);+ expect(app.world.get(dd.labelEntity, Text).content).toBe('new');+ expect(changed).not.toHaveBeenCalled();+ });+ it('an open popup rebuilds changed rows and clamps a removed selection', async () => {+ const dd = createDropdown({ world: app.world, events, options: ['old-a','old-b'], selectedIndex: 1 });+ await app.tick(1 / 60); dd.open();+ app.world.update(dd.entity, UIDropdown, d => { d.options = ['new-a']; }); await app.tick(1 / 60);+ expect(dd.getSelectedIndex()).toBe(0);+ expect(app.world.getEntitiesWithComponents([Text]).map(e => app.world.get(e, Text).content)).not.toContain('old-b');+ expect(dd.isOpen()).toBe(true);+ });+ it('replacement label receives the current option immediately', async () => {+ const dd = createDropdown({ world: app.world, events, options: ['current'] }); await app.tick(1 / 60);+ const label = app.world.spawn(); app.world.insert(label, Text);+ app.world.update(dd.entity, UIDropdown, d => { d.label = label; }); await app.tick(1 / 60);+ expect(app.world.get(label, Text).content).toBe('current');+ });+ it('change callbacks may dispose a later dropdown without a system error', async () => {+ let later: ReturnType<typeof createDropdown>;+ const error = vi.fn(); app.onError(error);+ const first = createDropdown({ world: app.world, events, options: ['a','b'], onSelect: () => later.dispose() });+ later = createDropdown({ world: app.world, events, options: ['a','b'] }); await app.tick(1 / 60);+ first.setSelectedIndex(1); later.setSelectedIndex(1); await app.tick(1 / 60);+ expect(error).not.toHaveBeenCalled(); expect(app.world.valid(later.entity)).toBe(false);+ });+ it('a stale popup row cannot select an option changed before the next update', async () => {+ const dd = createDropdown({ world: app.world, events, options: ['a','b'] });+ await app.tick(1 / 60); dd.open();+ const rows = app.world.getEntitiesWithComponents([UIController]).filter(e => e !== dd.entity);+ expect(rows).toHaveLength(2);+ app.world.update(dd.entity, UIDropdown, d => { d.options = ['a','replacement']; });+ events.emit(rows[1]!, 'click');+ expect(dd.getSelectedIndex()).toBe(0);+ expect(dd.isOpen()).toBe(false);+ });+ it('closing a row cannot resurrect an owner disposed by popup teardown', async () => {+ const dd = createDropdown({ world: app.world, events, options: ['a','b'] });+ await app.tick(1 / 60); dd.open();+ const row = app.world.getEntitiesWithComponents([UIController]).filter(e => e !== dd.entity)[1]!;+ const panel = app.world.get(row, Parent).entity;+ const off = app.world.onDespawn(e => { if (e === panel) app.world.despawn(dd.entity); });+ try { events.emit(row, 'click'); } finally { off(); }+ expect(app.world.valid(dd.entity)).toBe(false);+ expect(app.world.has(dd.entity, UIDropdown)).toBe(false);+ });+ it('closed dropdowns do not rewrite stable labels', async () => {+ createDropdown({ world: app.world, events, options: ['a','b'] }); await app.tick(1 / 60);+ const write = vi.spyOn(app.world, 'insert');+ for (let i = 0; i < 100; i++) await app.tick(1 / 60);+ expect(write).not.toHaveBeenCalled();+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 9dd0caa8c..b5208688e 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'fix(ui): reconcile dropdown options and guard popup teardown':+ { note: 'Dropdown labels and open rows follow live option edits.' },'fix(ui): reconcile toggle indicator targets and callback removals':{ note: 'Toggle indicators follow target replacements safely.' },'fix(ui): cancel unavailable slider capture and use local track dimensions':