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.

fix: dropdown placeholder, inspector schemas, color NaN, and texture handle guards

esengine62daa7d906e6
diff --git a/editor/src/panels/inspector/EntityInspector.ts b/editor/src/panels/inspector/EntityInspector.ts
index dae7d2fff..5c50395af 100644
--- a/editor/src/panels/inspector/EntityInspector.ts
+++ b/editor/src/panels/inspector/EntityInspector.ts
@@ -11,6 +11,7 @@ import {
getComponentSchema,
getDefaultComponentData,
getInitialComponentData,
+ inferPropertyType,
isComponentRemovable,
} from '../../schemas/ComponentSchemas';
import { icons } from '../../utils/icons';
@@ -452,10 +453,55 @@ export function renderComponent(
section.appendChild(propsContainer);
} else {
- const rawView = document.createElement('pre');
- rawView.className = 'es-component-raw';
- rawView.textContent = JSON.stringify(component.data, null, 2);
- section.appendChild(rawView);
+ const propsContainer = document.createElement('div');
+ propsContainer.className = 'es-component-properties es-collapsible-content';
+
+ const fullData = { ...defaults, ...component.data };
+ for (const [key, value] of Object.entries(fullData)) {
+ const row = document.createElement('div');
+ row.className = 'es-property-row';
+
+ const label = document.createElement('label');
+ label.className = 'es-property-label';
+ label.textContent = key;
+
+ const editorContainer = document.createElement('div');
+ editorContainer.className = 'es-property-editor';
+
+ const propMeta: import('../../property/PropertyEditor').PropertyMeta = {
+ name: key,
+ type: inferPropertyType(value),
+ };
+
+ let currentValue = component.data[key];
+ if (currentValue === undefined) {
+ currentValue = defaults[key];
+ }
+ const editor = createPropertyEditor(editorContainer, {
+ value: currentValue,
+ meta: propMeta,
+ onChange: (newValue) => {
+ const oldValue = component.data[key] ?? currentValue;
+ store.updateProperty(entity, component.type, key, oldValue, newValue);
+ },
+ componentData: component.data,
+ getComponentValue: (name: string) => component.data[name],
+ });
+
+ if (editor) {
+ editors.push({
+ editor,
+ componentType: component.type,
+ propertyName: key,
+ });
+ }
+
+ row.appendChild(label);
+ row.appendChild(editorContainer);
+ propsContainer.appendChild(row);
+ }
+
+ section.appendChild(propsContainer);
}
container.appendChild(section);
diff --git a/editor/src/panels/inspector/InspectorHelpers.ts b/editor/src/panels/inspector/InspectorHelpers.ts
index 11a83ad7e..1a84a6690 100644
--- a/editor/src/panels/inspector/InspectorHelpers.ts
+++ b/editor/src/panels/inspector/InspectorHelpers.ts
@@ -123,10 +123,15 @@ export function getAssetServer(): EditorAssetServer | null {
}
const COMPONENT_ICON_MAP = new Map<string, (size: number) => string>([
+ ['Name', icons.tag],
+ ['Parent', icons.box],
+ ['Children', icons.box],
['Transform', icons.move],
['Sprite', icons.image],
['NinePatch', icons.image],
['Camera', icons.camera],
+ ['Velocity', icons.zap],
+ ['SceneOwner', icons.layers],
['Text', icons.type],
['TextInput', icons.type],
['RigidBody', icons.zap],
@@ -139,6 +144,7 @@ const COMPONENT_ICON_MAP = new Map<string, (size: number) => string>([
['UIRect', icons.scan],
['LayoutGroup', icons.layoutGrid],
['UIMask', icons.shield],
+ ['UIInteraction', icons.zap],
]);
export function getComponentIcon(type: string): string {
diff --git a/editor/src/panels/inspector/SharedEditors.ts b/editor/src/panels/inspector/SharedEditors.ts
index bd299cd97..f5c5f83a0 100644
--- a/editor/src/panels/inspector/SharedEditors.ts
+++ b/editor/src/panels/inspector/SharedEditors.ts
@@ -231,9 +231,10 @@ export function createVec4Editor(
// =============================================================================
export function colorToHex(color: { r: number; g: number; b: number; a: number }): string {
- const r = Math.round(color.r * 255).toString(16).padStart(2, '0');
- const g = Math.round(color.g * 255).toString(16).padStart(2, '0');
- const b = Math.round(color.b * 255).toString(16).padStart(2, '0');
+ const clamp = (v: number) => Math.max(0, Math.min(255, Math.round((Number.isFinite(v) ? v : 0) * 255)));
+ const r = clamp(color.r).toString(16).padStart(2, '0');
+ const g = clamp(color.g).toString(16).padStart(2, '0');
+ const b = clamp(color.b).toString(16).padStart(2, '0');
return `#${r}${g}${b}`;
}
diff --git a/editor/src/property/editorUtils.ts b/editor/src/property/editorUtils.ts
index 2e9141160..ded31819a 100644
--- a/editor/src/property/editorUtils.ts
+++ b/editor/src/property/editorUtils.ts
@@ -41,9 +41,10 @@ export function setupDragLabel(
}
export function colorToHex(color: { r: number; g: number; b: number; a: number }): string {
- const r = Math.round(color.r * 255).toString(16).padStart(2, '0');
- const g = Math.round(color.g * 255).toString(16).padStart(2, '0');
- const b = Math.round(color.b * 255).toString(16).padStart(2, '0');
+ const clamp = (v: number) => Math.max(0, Math.min(255, Math.round((Number.isFinite(v) ? v : 0) * 255)));
+ const r = clamp(color.r).toString(16).padStart(2, '0');
+ const g = clamp(color.g).toString(16).padStart(2, '0');
+ const b = clamp(color.b).toString(16).padStart(2, '0');
return `#${r}${g}${b}`;
}
diff --git a/editor/src/property/editors.ts b/editor/src/property/editors.ts
index 63f2ae40b..483ad282a 100644
--- a/editor/src/property/editors.ts
+++ b/editor/src/property/editors.ts
@@ -400,12 +400,21 @@ function createVec4Editor(
// Color Editor
// =============================================================================
+type RGBA = { r: number; g: number; b: number; a: number };
+
+function sanitizeColor(color: RGBA | null | undefined): RGBA {
+ if (!color || typeof color !== 'object') return { r: 1, g: 1, b: 1, a: 1 };
+ const s = (v: unknown) => (typeof v === 'number' && Number.isFinite(v)) ? v : 0;
+ return { r: s(color.r), g: s(color.g), b: s(color.b), a: s(color.a) || 1 };
+}
+
function createColorEditor(
container: HTMLElement,
ctx: PropertyEditorContext
): PropertyEditorInstance {
const { value, onChange } = ctx;
- const color = (value as { r: number; g: number; b: number; a: number }) ?? { r: 1, g: 1, b: 1, a: 1 };
+ const raw = value as { r: number; g: number; b: number; a: number } | null | undefined;
+ const color = sanitizeColor(raw);
const wrapper = document.createElement('div');
wrapper.className = 'es-color-editor';
@@ -463,7 +472,7 @@ function createColorEditor(
return {
update(v: unknown) {
- const newColor = (v as { r: number; g: number; b: number; a: number }) ?? { r: 1, g: 1, b: 1, a: 1 };
+ const newColor = sanitizeColor(v as { r: number; g: number; b: number; a: number } | null | undefined);
colorInput.value = colorToHex(newColor);
hexInput.value = colorToHex(newColor).toUpperCase();
alphaInput.value = String(newColor.a);
@@ -885,8 +894,8 @@ function createTextureEditor(
return {
update(v: unknown) {
- const raw = String(v ?? '');
- const newValue = raw === String(INVALID_TEXTURE) ? '' : raw;
+ const raw = (typeof v === 'string') ? v : '';
+ const newValue = (!raw || raw === String(INVALID_TEXTURE)) ? '' : raw;
input.value = newValue ? resolveDisplayName(newValue) : '';
if (newValue !== currentRef) {
currentRef = newValue;
diff --git a/editor/src/renderer/EditorTextureManager.ts b/editor/src/renderer/EditorTextureManager.ts
index 71ad9bdeb..54612e8d0 100644
--- a/editor/src/renderer/EditorTextureManager.ts
+++ b/editor/src/renderer/EditorTextureManager.ts
@@ -40,6 +40,8 @@ export class EditorTextureManager {
* @returns Texture handle ID, or 0 if failed
*/
async loadTexture(texturePath: string): Promise<number> {
+ if (!texturePath || /^\d+$/.test(texturePath)) return 0;
+
const fullPath = this.pathResolver_.toAbsolutePath(texturePath);
const existing = this.pathToEntry_.get(fullPath);
diff --git a/editor/src/schemas/ComponentSchemas.ts b/editor/src/schemas/ComponentSchemas.ts
index a2c4f1403..0e939829b 100644
--- a/editor/src/schemas/ComponentSchemas.ts
+++ b/editor/src/schemas/ComponentSchemas.ts
@@ -39,13 +39,17 @@ function isVec4OrColor(v: unknown): boolean {
return 'x' in v && 'y' in v && 'z' in v && 'w' in v;
}
-function inferPropertyType(value: unknown): string {
+export function inferPropertyType(value: unknown): string {
if (typeof value === 'number') return 'number';
if (typeof value === 'string') return 'string';
if (typeof value === 'boolean') return 'boolean';
+ if (Array.isArray(value)) return 'string-array';
if (isVec2(value)) return 'vec2';
if (isVec3(value)) return 'vec3';
- if (isVec4OrColor(value)) return 'vec4';
+ if (typeof value === 'object' && value !== null) {
+ if ('r' in value && 'g' in value && 'b' in value && 'a' in value) return 'color';
+ if ('x' in value && 'y' in value && 'z' in value && 'w' in value) return 'vec4';
+ }
return 'string';
}
@@ -53,6 +57,31 @@ function inferPropertyType(value: unknown): string {
// Built-in Schemas
// =============================================================================
+export const NameSchema: ComponentSchema = {
+ name: 'Name',
+ category: 'builtin',
+ removable: false,
+ properties: [
+ { name: 'value', type: 'string' },
+ ],
+};
+
+export const ParentSchema: ComponentSchema = {
+ name: 'Parent',
+ category: 'builtin',
+ removable: false,
+ properties: [
+ { name: 'entity', type: 'entity' },
+ ],
+};
+
+export const ChildrenSchema: ComponentSchema = {
+ name: 'Children',
+ category: 'tag',
+ removable: false,
+ properties: [],
+};
+
export const TransformSchema: ComponentSchema = {
name: 'Transform',
category: 'builtin',
@@ -277,6 +306,25 @@ export const TextInputSchema: ComponentSchema = {
],
};
+export const VelocitySchema: ComponentSchema = {
+ name: 'Velocity',
+ category: 'builtin',
+ properties: [
+ { name: 'linear', type: 'vec3' },
+ { name: 'angular', type: 'vec3' },
+ ],
+};
+
+export const SceneOwnerSchema: ComponentSchema = {
+ name: 'SceneOwner',
+ category: 'builtin',
+ removable: false,
+ properties: [
+ { name: 'scene', type: 'string' },
+ { name: 'persistent', type: 'boolean' },
+ ],
+};
+
export const SpineAnimationSchema: ComponentSchema = {
name: 'SpineAnimation',
category: 'builtin',
@@ -407,6 +455,14 @@ export const ToggleSchema: ComponentSchema = {
],
};
+export const ToggleGroupSchema: ComponentSchema = {
+ name: 'ToggleGroup',
+ category: 'ui',
+ properties: [
+ { name: 'allowSwitchOff', type: 'boolean' },
+ ],
+};
+
export const ProgressBarSchema: ComponentSchema = {
name: 'ProgressBar',
category: 'ui',
@@ -600,6 +656,13 @@ export const LayoutGroupSchema: ComponentSchema = {
],
};
+export const UIInteractionSchema: ComponentSchema = {
+ name: 'UIInteraction',
+ category: 'tag',
+ removable: false,
+ properties: [],
+};
+
// =============================================================================
// Registry
// =============================================================================
@@ -658,6 +721,7 @@ export function clearExtensionComponentSchemas(): void {
export function clearScriptComponents(): void {
for (const [name, schema] of schemaRegistry.entries()) {
+ if (builtinSchemaNames.has(name)) continue;
if (schema.category === 'script' || schema.category === 'tag') {
schemaRegistry.delete(name);
}
@@ -706,20 +770,27 @@ export interface BuiltinSchemaOptions {
export function registerBuiltinSchemas(options?: BuiltinSchemaOptions): void {
const enableSpine = options?.enableSpine ?? true;
+ registerComponentSchema(NameSchema);
+ registerComponentSchema(ParentSchema);
+ registerComponentSchema(ChildrenSchema);
registerComponentSchema(TransformSchema);
registerComponentSchema(SpriteSchema);
registerComponentSchema(CameraSchema);
+ registerComponentSchema(VelocitySchema);
+ registerComponentSchema(SceneOwnerSchema);
registerComponentSchema(TextSchema);
registerComponentSchema(UIRectSchema);
registerComponentSchema(CanvasSchema);
registerComponentSchema(BitmapTextSchema);
registerComponentSchema(UIMaskSchema);
registerComponentSchema(InteractableSchema);
+ registerComponentSchema(UIInteractionSchema);
registerComponentSchema(ButtonSchema);
registerComponentSchema(ScreenSpaceSchema);
registerComponentSchema(TextInputSchema);
registerComponentSchema(ImageSchema);
registerComponentSchema(ToggleSchema);
+ registerComponentSchema(ToggleGroupSchema);
registerComponentSchema(ProgressBarSchema);
registerComponentSchema(DraggableSchema);
registerComponentSchema(ScrollViewSchema);
diff --git a/sdk/src/ui/DropdownPlugin.ts b/sdk/src/ui/DropdownPlugin.ts
index daa64674e..fd54525f0 100644
--- a/sdk/src/ui/DropdownPlugin.ts
+++ b/sdk/src/ui/DropdownPlugin.ts
@@ -19,11 +19,13 @@ import { UIMask, MaskMode } from './UIMask';
import { Input } from '../input';
import type { InputState } from '../input';
import { isEditor } from '../env';
+import { INVALID_TEXTURE } from '../types';
import { ensureComponent } from './uiHelpers';
import { DROPDOWN_ITEM_HEIGHT, DROPDOWN_FONT_SIZE, DROPDOWN_HIGHLIGHT_COLOR } from './uiConstants';
interface DropdownState {
optionEntities: Entity[];
+ textEntities: Entity[];
highlightIndex: number;
}
@@ -54,8 +56,11 @@ export class DropdownPlugin implements Plugin {
let state = dropdownStates.get(entity);
if (!state) {
- state = { optionEntities: [], highlightIndex: -1 };
+ state = { optionEntities: [], textEntities: [], highlightIndex: -1 };
dropdownStates.set(entity, state);
+ if (!dropdown.isOpen) {
+ setListVisible(dropdown.listEntity, false);
+ }
}
if (interaction?.justPressed) {
@@ -134,30 +139,19 @@ export class DropdownPlugin implements Plugin {
world.insert(optEntity, UIRect, {
anchorMin: { x: 0, y: 1 },
anchorMax: { x: 1, y: 1 },
- offsetMin: { x: 0, y: 0 },
+ offsetMin: { x: 0, y: -i * DROPDOWN_ITEM_HEIGHT },
offsetMax: { x: 0, y: 0 },
size: { x: listWidth, y: DROPDOWN_ITEM_HEIGHT },
pivot: { x: 0.5, y: 1 },
});
world.insert(optEntity, Transform, {
- position: { x: 0, y: -(i * DROPDOWN_ITEM_HEIGHT), z: 0 },
+ position: { x: 0, y: 0, z: 0 },
rotation: { w: 1, x: 0, y: 0, z: 0 },
scale: { x: 1, y: 1, z: 1 },
});
- world.insert(optEntity, Text, {
- content: dropdown.options[i],
- fontSize: DROPDOWN_FONT_SIZE,
- fontFamily: 'Arial',
- color: { r: 1, g: 1, b: 1, a: 1 },
- align: TextAlign.Left,
- verticalAlign: TextVerticalAlign.Middle,
- wordWrap: false,
- overflow: TextOverflow.Clip,
- lineHeight: 1.2,
- });
world.insert(optEntity, Sprite, {
- texture: 0,
- color: { r: 1, g: 1, b: 1, a: 0 },
+ texture: INVALID_TEXTURE,
+ color: { r: 0.95, g: 0.95, b: 0.95, a: 1 },
size: { x: listWidth, y: DROPDOWN_ITEM_HEIGHT },
uvOffset: { x: 0, y: 0 },
uvScale: { x: 1, y: 1 },
@@ -170,6 +164,34 @@ export class DropdownPlugin implements Plugin {
world.insert(optEntity, Interactable, { enabled: true, blockRaycast: true, raycastTarget: true });
world.setParent(optEntity, listEntity);
state.optionEntities.push(optEntity);
+
+ const textEntity = world.spawn();
+ world.insert(textEntity, Transform, {
+ position: { x: 0, y: 0, z: 0 },
+ rotation: { w: 1, x: 0, y: 0, z: 0 },
+ scale: { x: 1, y: 1, z: 1 },
+ });
+ world.insert(textEntity, Text, {
+ content: dropdown.options[i],
+ fontSize: DROPDOWN_FONT_SIZE,
+ fontFamily: 'Arial',
+ color: { r: 0, g: 0, b: 0, a: 1 },
+ align: TextAlign.Left,
+ verticalAlign: TextVerticalAlign.Middle,
+ wordWrap: false,
+ overflow: TextOverflow.Clip,
+ lineHeight: 1.2,
+ });
+ world.insert(textEntity, UIRect, {
+ anchorMin: { x: 0, y: 0 },
+ anchorMax: { x: 1, y: 1 },
+ offsetMin: { x: 0, y: 0 },
+ offsetMax: { x: 0, y: 0 },
+ size: { x: listWidth, y: DROPDOWN_ITEM_HEIGHT },
+ pivot: { x: 0.5, y: 0.5 },
+ });
+ world.setParent(textEntity, optEntity);
+ state.textEntities.push(textEntity);
}
if (listRect) {
@@ -203,24 +225,38 @@ export class DropdownPlugin implements Plugin {
if (labelEntity === 0 || !world.valid(labelEntity)) return;
if (!world.has(labelEntity, Text)) return;
+ if (dropdown.selectedIndex < 0 || dropdown.selectedIndex >= dropdown.options.length) return;
+
const text = world.get(labelEntity, Text) as TextData;
- const selectedText = dropdown.selectedIndex >= 0 && dropdown.selectedIndex < dropdown.options.length
- ? dropdown.options[dropdown.selectedIndex]
- : '';
+ const selectedText = dropdown.options[dropdown.selectedIndex];
+ let changed = false;
if (text.content !== selectedText) {
text.content = selectedText;
+ changed = true;
+ }
+ if (text.color.r === 1 && text.color.g === 1 && text.color.b === 1 && text.color.a === 1) {
+ text.color = { r: 0, g: 0, b: 0, a: 1 };
+ changed = true;
+ }
+ if (changed) {
world.insert(labelEntity, Text, text);
}
}
function destroyOptions(state: DropdownState): void {
+ for (const textEntity of state.textEntities) {
+ if (world.valid(textEntity)) {
+ world.despawn(textEntity);
+ }
+ }
for (const optEntity of state.optionEntities) {
if (world.valid(optEntity)) {
world.despawn(optEntity);
}
}
state.optionEntities = [];
+ state.textEntities = [];
}
function setListVisible(entity: Entity, visible: boolean): void {
@@ -245,7 +281,7 @@ export class DropdownPlugin implements Plugin {
if (i === state.highlightIndex) {
sprite.color = { ...DROPDOWN_HIGHLIGHT_COLOR };
} else {
- sprite.color = { r: 1, g: 1, b: 1, a: 0 };
+ sprite.color = { r: 0.95, g: 0.95, b: 0.95, a: 1 };
}
world.insert(optEntity, Sprite, sprite);
}
diff --git a/sdk/tests/dropdown-layout.test.ts b/sdk/tests/dropdown-layout.test.ts
new file mode 100644
index 000000000..8590962e8
--- /dev/null
+++ b/sdk/tests/dropdown-layout.test.ts
@@ -0,0 +1,365 @@
+/**
+ * Regression test: Dropdown option entities must have distinct positions.
+ *
+ * Bug: C++ UILayoutSystem overwrites manually-set Transform positions based on
+ * UIRect anchors. When all options share the same UIRect anchors, they overlap.
+ * Fix: use UIRect offsetMin.y to differentiate positions so the layout system
+ * computes unique positions for each option.
+ */
+import { describe, it, expect, beforeAll } from 'vitest';
+import { existsSync } from 'fs';
+import { resolve } from 'path';
+import { App } from '../src/app';
+import { Transform, Sprite, Name } from '../src/component';
+import type { SpriteData } from '../src/component';
+import { UIRect } from '../src/ui/UIRect';
+import { ScreenSpace } from '../src/ui/ScreenSpace';
+import { UICameraInfo } from '../src/ui/UICameraInfo';
+import { Input, InputState } from '../src/input';
+import { UIEvents, UIEventQueue } from '../src/ui/UIEvents';
+import { uiLayoutPlugin } from '../src/ui/UILayoutPlugin';
+import { uiRenderOrderPlugin } from '../src/ui/UIRenderOrderPlugin';
+import { uiInteractionPlugin } from '../src/ui/UIInteractionPlugin';
+import { dropdownPlugin } from '../src/ui/DropdownPlugin';
+import { Dropdown } from '../src/ui/Dropdown';
+import type { DropdownData } from '../src/ui/Dropdown';
+import { Interactable } from '../src/ui/Interactable';
+import type { InteractableData } from '../src/ui/Interactable';
+import { UIInteraction } from '../src/ui/UIInteraction';
+import { Text } from '../src/ui/text';
+import type { TextData } from '../src/ui/text';
+import { DROPDOWN_ITEM_HEIGHT } from '../src/ui/uiConstants';
+import type { ESEngineModule, CppRegistry } from '../src/wasm';
+import { loadWasmModule } from './helpers/loadWasm';
+
+const WASM_PATH = resolve(__dirname, '../../desktop/public/wasm/esengine.wasm');
+const HAS_WASM = existsSync(WASM_PATH);
+
+describe.skipIf(!HAS_WASM)('Dropdown Layout (WASM integration)', () => {
+ let module: ESEngineModule;
+
+ beforeAll(async () => {
+ module = await loadWasmModule();
+ });
+
+ function createDropdownApp() {
+ const app = App.new();
+ const registry = new module.Registry() as unknown as CppRegistry;
+ app.connectCpp(registry, module);
+
+ app.insertResource(UICameraInfo, {
+ viewProjection: new Float32Array(16),
+ vpX: 0, vpY: 0, vpW: 0, vpH: 0,
+ screenW: 0, screenH: 0,
+ worldLeft: -400, worldBottom: -300, worldRight: 400, worldTop: 300,
+ worldMouseX: 0, worldMouseY: 0,
+ valid: true,
+ });
+ app.insertResource(Input, new InputState());
+ app.insertResource(UIEvents, new UIEventQueue());
+
+ app.addPlugin(uiLayoutPlugin);
+ app.addPlugin(uiRenderOrderPlugin);
+ app.addPlugin(uiInteractionPlugin);
+ app.addPlugin(dropdownPlugin);
+
+ return { app, registry };
+ }
+
+ function disposeApp(app: App, registry: CppRegistry): void {
+ const world = app.world;
+ for (const e of world.getAllEntities()) {
+ try { world.despawn(e); } catch (_) {}
+ }
+ world.disconnectCpp();
+ (registry as any).delete();
+ }
+
+ function makeTransform() {
+ return {
+ position: { x: 0, y: 0, z: 0 },
+ rotation: { x: 0, y: 0, z: 0, w: 1 },
+ scale: { x: 1, y: 1, z: 1 },
+ };
+ }
+
+ function createDropdownHierarchy(app: App) {
+ const world = app.world;
+
+ const root = world.spawn();
+ world.insert(root, ScreenSpace, {});
+ world.insert(root, UIRect, {
+ anchorMin: { x: 0, y: 0 },
+ anchorMax: { x: 1, y: 1 },
+ offsetMin: { x: 0, y: 0 },
+ offsetMax: { x: 0, y: 0 },
+ size: { x: 0, y: 0 },
+ pivot: { x: 0.5, y: 0.5 },
+ });
+ world.insert(root, Transform, makeTransform());
+
+ const ddEntity = world.spawn();
+ world.setParent(ddEntity, root);
+ world.insert(ddEntity, UIRect, {
+ anchorMin: { x: 0.5, y: 0.5 },
+ anchorMax: { x: 0.5, y: 0.5 },
+ offsetMin: { x: 0, y: 0 },
+ offsetMax: { x: 0, y: 0 },
+ size: { x: 160, y: 30 },
+ pivot: { x: 0.5, y: 0.5 },
+ });
+ world.insert(ddEntity, Transform, makeTransform());
+ world.insert(ddEntity, Sprite, {
+ texture: 0, color: { r: 0.9, g: 0.9, b: 0.9, a: 1 },
+ size: { x: 160, y: 30 }, uvOffset: { x: 0, y: 0 },
+ uvScale: { x: 1, y: 1 }, layer: 0, flipX: false, flipY: false,
+ });
+ world.insert(ddEntity, Interactable, { enabled: true, blockRaycast: true, raycastTarget: true });
+
+ // List entity (positioned below dropdown)
+ const listEntity = world.spawn();
+ world.setParent(listEntity, ddEntity);
+ world.insert(listEntity, UIRect, {
+ anchorMin: { x: 0, y: 0 },
+ anchorMax: { x: 1, y: 0 },
+ offsetMin: { x: 0, y: -90 },
+ offsetMax: { x: 0, y: 0 },
+ size: { x: 160, y: 90 },
+ pivot: { x: 0.5, y: 1 },
+ });
+ world.insert(listEntity, Transform, makeTransform());
+ world.insert(listEntity, Sprite, {
+ texture: 0, color: { r: 1, g: 1, b: 1, a: 1 },
+ size: { x: 160, y: 90 }, uvOffset: { x: 0, y: 0 },
+ uvScale: { x: 1, y: 1 }, layer: 0, flipX: false, flipY: false,
+ enabled: false,
+ });
+ world.insert(listEntity, Interactable, { enabled: false, blockRaycast: true, raycastTarget: true });
+
+ // Label entity with Text (default white color — simulates real scene)
+ const labelEntity = world.spawn();
+ world.setParent(labelEntity, ddEntity);
+ world.insert(labelEntity, Transform, makeTransform());
+ world.insert(labelEntity, Text, {
+ content: '',
+ fontFamily: 'Arial',
+ fontSize: 16,
+ color: { r: 1, g: 1, b: 1, a: 1 },
+ align: 0,
+ verticalAlign: 1,
+ wordWrap: false,
+ overflow: 1,
+ lineHeight: 1.2,
+ });
+
+ world.insert(ddEntity, Dropdown, {
+ options: ['Option A', 'Option B', 'Option C'],
+ selectedIndex: 0,
+ isOpen: false,
+ listEntity,
+ labelEntity,
+ });
+
+ return { root, ddEntity, listEntity, labelEntity };
+ }
+
+ it('should create option entities with distinct Y positions after opening', () => {
+ const { app, registry } = createDropdownApp();
+ const { ddEntity, listEntity } = createDropdownHierarchy(app);
+
+ // Initial tick to set up layout
+ app.tick(1 / 60);
+
+ // Simulate click on dropdown to open it:
+ // Force isOpen via component update and tick
+ const world = app.world;
+ const dd = world.get(ddEntity, Dropdown) as any;
+ dd.isOpen = false;
+
+ // Simulate UIInteraction justPressed on the dropdown
+ world.insert(ddEntity, UIInteraction, {
+ hovered: true, pressed: true,
+ justPressed: true, justReleased: false,
+ });
+
+ app.tick(1 / 60);
+
+ // After tick, the dropdown should be open and options should exist
+ const ddData = world.get(ddEntity, Dropdown) as any;
+
+ // Find option entities (children of listEntity that have Sprite + Interactable)
+ const allEntities = world.getAllEntities();
+ const optionEntities: number[] = [];
+ for (const e of allEntities) {
+ if (e === listEntity || e === ddEntity) continue;
+ if (!world.has(e, Sprite) || !world.has(e, Interactable)) continue;
+ if (!world.has(e, UIRect)) continue;
+ // Check if this is a child of listEntity
+ if (world.has(e, Transform)) {
+ const name = world.has(e, Name) ? (world.get(e, Name) as any).value : '';
+ if (name.startsWith('Option_')) {
+ optionEntities.push(e);
+ }
+ }
+ }
+
+ // Should have 3 option entities
+ expect(optionEntities.length).toBe(3);
+
+ // Run another tick so layout computes positions
+ app.tick(1 / 60);
+
+ // Each option should have a DISTINCT Y position
+ const yPositions = optionEntities.map(e => {
+ const t = registry.getTransform(e);
+ return t.position.y;
+ });
+
+ console.log('Option Y positions:', yPositions);
+
+ // All Y positions must be different
+ const uniqueY = new Set(yPositions.map(y => Math.round(y)));
+ expect(uniqueY.size).toBe(3);
+
+ // Options should be spaced by DROPDOWN_ITEM_HEIGHT
+ yPositions.sort((a, b) => b - a); // highest first
+ for (let i = 1; i < yPositions.length; i++) {
+ const gap = yPositions[i - 1] - yPositions[i];
+ expect(gap).toBeCloseTo(DROPDOWN_ITEM_HEIGHT, 0);
+ }
+
+ disposeApp(app, registry);
+ });
+
+ it('should have option sprites with non-zero size after layout', () => {
+ const { app, registry } = createDropdownApp();
+ const { ddEntity, listEntity } = createDropdownHierarchy(app);
+
+ app.tick(1 / 60);
+
+ const world = app.world;
+ world.insert(ddEntity, UIInteraction, {
+ hovered: true, pressed: true,
+ justPressed: true, justReleased: false,
+ });
+
+ app.tick(1 / 60);
+ app.tick(1 / 60);
+
+ const allEntities = world.getAllEntities();
+ const optionEntities: number[] = [];
+ for (const e of allEntities) {
+ if (!world.has(e, Name)) continue;
+ const name = (world.get(e, Name) as any).value;
+ if (name.startsWith('Option_')) {
+ optionEntities.push(e);
+ }
+ }
+
+ expect(optionEntities.length).toBe(3);
+
+ for (const e of optionEntities) {
+ const sprite = registry.getSprite(e);
+ expect(sprite.size.x).toBeGreaterThan(0);
+ expect(sprite.size.y).toBeGreaterThan(0);
+ expect(sprite.enabled).toBe(true);
+ }
+
+ disposeApp(app, registry);
+ });
+
+ it('should hide list entity on initialization when dropdown is closed', () => {
+ const { app, registry } = createDropdownApp();
+ const { listEntity } = createDropdownHierarchy(app);
+ const world = app.world;
+
+ // Simulate list entity starting with enabled=true (scene not pre-configured)
+ world.insert(listEntity, Sprite, {
+ texture: 0, color: { r: 1, g: 1, b: 1, a: 1 },
+ size: { x: 160, y: 90 }, uvOffset: { x: 0, y: 0 },
+ uvScale: { x: 1, y: 1 }, layer: 0, flipX: false, flipY: false,
+ enabled: true,
+ });
+ world.insert(listEntity, Interactable, { enabled: true, blockRaycast: true, raycastTarget: true });
+
+ app.tick(1 / 60);
+
+ const sprite = registry.getSprite(listEntity);
+ expect(sprite.enabled).toBe(false);
+
+ const interactable = world.get(listEntity, Interactable) as InteractableData;
+ expect(interactable.enabled).toBe(false);
+
+ disposeApp(app, registry);
+ });
+
+ it('should set label text color to non-white after sync', () => {
+ const { app, registry } = createDropdownApp();
+ const { labelEntity } = createDropdownHierarchy(app);
+ const world = app.world;
+
+ app.tick(1 / 60);
+
+ const text = world.get(labelEntity, Text) as TextData;
+ const isWhite = text.color.r === 1 && text.color.g === 1 && text.color.b === 1;
+ expect(isWhite).toBe(false);
+ expect(text.content).toBe('Option A');
+
+ disposeApp(app, registry);
+ });
+
+ it('should preserve label placeholder text when selectedIndex is -1', () => {
+ const { app, registry } = createDropdownApp();
+ const { ddEntity, labelEntity } = createDropdownHierarchy(app);
+ const world = app.world;
+
+ // Set label placeholder text and reset selectedIndex to -1
+ world.insert(labelEntity, Text, {
+ content: 'Select...',
+ fontFamily: 'Arial',
+ fontSize: 16,
+ color: { r: 0.5, g: 0.5, b: 0.5, a: 1 },
+ align: 0, verticalAlign: 1,
+ wordWrap: false, overflow: 1, lineHeight: 1.2,
+ });
+
+ const dd = world.get(ddEntity, Dropdown) as DropdownData;
+ dd.selectedIndex = -1;
+ world.insert(ddEntity, Dropdown, dd);
+
+ app.tick(1 / 60);
+
+ const text = world.get(labelEntity, Text) as TextData;
+ expect(text.content).toBe('Select...');
+
+ disposeApp(app, registry);
+ });
+
+ it('should open dropdown and show list entity on click', () => {
+ const { app, registry } = createDropdownApp();
+ const { ddEntity, listEntity } = createDropdownHierarchy(app);
+ const world = app.world;
+
+ app.tick(1 / 60);
+
+ // Verify list is hidden initially
+ let sprite = registry.getSprite(listEntity);
+ expect(sprite.enabled).toBe(false);
+
+ // Simulate click
+ world.insert(ddEntity, UIInteraction, {
+ hovered: true, pressed: true,
+ justPressed: true, justReleased: false,
+ });
+
+ app.tick(1 / 60);
+
+ const dd = world.get(ddEntity, Dropdown) as any;
+ expect(dd.isOpen).toBe(true);
+
+ sprite = registry.getSprite(listEntity);
+ expect(sprite.enabled).toBe(true);
+
+ disposeApp(app, registry);
+ });
+});