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
// Generates the built-in UI widget prefabs from the factories (single source)
// and verifies the captured tree. Writing the .esprefab files is the codegen;
// the assertions are the guard that the factory still round-trips to a prefab.
import { describe, it, expect, afterAll } from 'vitest';
import { writeFileSync, mkdirSync, readFileSync, existsSync } from 'node:fs';
import { resolve } from 'node:path';
import type { World } from '../src/ecs/world';
import type { PrefabData } from '../src/prefab/types';
import { widgetToPrefab } from '../src/ui/widgets/toPrefab';
import { createButton } from '../src/ui/widgets/button';
import { createVirtualJoystick, createVirtualButton } from '../src/ui/widgets/virtual-controls';
import { VirtualJoystick, VirtualButton } from '../src/ui/behavior/virtual-controls';
import { createToggle } from '../src/ui/widgets/toggle';
import { createSlider } from '../src/ui/widgets/slider';
import { createProgress } from '../src/ui/widgets/progress';
import { createDropdown } from '../src/ui/widgets/dropdown';
import { createDialog } from '../src/ui/widgets/dialog';
import { createTextInput } from '../src/ui/widgets/text-input';
import { UISlider } from '../src/ui/behavior/slider';
import { UIToggle } from '../src/ui/behavior/toggle';
import { UIDropdown } from '../src/ui/behavior/dropdown';
import { registerComponent } from '../src/ecs/component';
import { spawnUIEntity } from '../src/ui/core/compose';
import { UIMask, MaskMode } from '../src/ui/core/ui-mask';
import { UIScroll, ScrollMovement } from '../src/ui/core/ui-scroll';
import { UIPositionType } from '../src/ui/core/ui-node';
import { Interactable } from '../src/ui/input/interactable';
import { themeColors } from '../src/ui/theme/tokens';
import { markThemed } from '../src/ui/theme/theme-style';
import { px } from '../src/ui/core/dimension';
import { UITabView } from '../src/ui/behavior/tab-view';
import { UITooltip } from '../src/ui/behavior/tooltip';
import { createTabView } from '../src/ui/widgets/tab-view';
import { createTooltip } from '../src/ui/widgets/tooltip';
import { UITreeView } from '../src/ui/behavior/tree-view';
import { UIColorPicker } from '../src/ui/behavior/color-picker';
import { createTreeView } from '../src/ui/widgets/tree-view';
import { createColorPicker } from '../src/ui/widgets/color-picker';
import { TextInput } from '../src/ui/text/text-input';
const OUT_DIR = resolve(__dirname, '../src/ui/widgets/prefabs');
/** Rewriting identical bytes still moves the mtime, and these are SOURCES: every
* freshness check that compares a build against them then calls a current dist
* stale, and release criteria that read one refuse to answer. */
function writeIfChanged(file: string, body: string): void {
if (existsSync(file) && readFileSync(file, 'utf8') === body) return;
writeFileSync(file, body);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const noEvents = { on: () => {} } as any;
const c = themeColors();
function entityById(p: PrefabData, id: string) {
return p.entities.find((e) => e.prefabEntityId === id)!;
}
function typesOf(p: PrefabData, id: string): string[] {
return entityById(p, id).components.map((cc) => cc.type);
}
const GENERATED: Record<string, PrefabData> = {};
function generate(name: string, build: (w: World) => number): PrefabData {
const prefab = widgetToPrefab(build, name);
mkdirSync(OUT_DIR, { recursive: true });
writeIfChanged(resolve(OUT_DIR, `${name}.esprefab`), JSON.stringify(prefab, null, 2) + '\n');
GENERATED[name] = prefab;
return prefab;
}
// Emit the SDK-exported data module the editor's "Create → UI" menu instantiates.
afterAll(() => {
const names = Object.keys(GENERATED);
const body =
'// AUTO-GENERATED by tests/ui-widget-prefabs.gen.test.ts — do not edit by hand.\n' +
"import type { PrefabData } from '../../../prefab/types';\n\n" +
`export const BUILTIN_UI_PREFABS: Record<string, PrefabData> = ${JSON.stringify(GENERATED, null, 2)};\n\n` +
`export const BUILTIN_UI_WIDGET_NAMES = ${JSON.stringify(names)} as const;\n`;
writeIfChanged(resolve(OUT_DIR, 'generated.ts'), body);
});
describe('UI widget prefab codegen', () => {
it('TreeView: authored data is optional; runtime rows are never captured', () => {
registerComponent('UITreeView', UITreeView);
const p = generate('TreeView', world => createTreeView({ world, events: noEvents }).entity);
expect(p.entities).toHaveLength(1);
expect(typesOf(p, p.rootEntityId)).toContain('UITreeView');
});
it('ColorPicker: composes standard inputs and remaps every child reference', () => {
for (const component of [UIColorPicker, UISlider, TextInput]) registerComponent(component._name, component);
const p = generate('ColorPicker', world => createColorPicker({ world, events: noEvents }).entity);
const data = entityById(p, p.rootEntityId).components.find(c => c.type === 'UIColorPicker')!.data;
for (const ref of [data.sv, data.alphaRamp, data.cursor, data.hue, data.alpha,
data.hex, data.historyRoot, data.rememberButton, data.preview, ...data.fields as string[]]) expect(entityById(p, ref as string)).toBeDefined();
expect(p.entities.filter(e => e.components.some(c => c.type === 'TextInput'))).toHaveLength(5);
});
it('TabView: ordered tab and page references survive prefab capture', () => {
registerComponent('UITabView', UITabView);
registerComponent('UIToggle', UIToggle);
const p = generate('TabView', world => createTabView({ world, events: noEvents, labels: ['Graphics', 'Audio', 'Controls'] }).entity);
const d = entityById(p, p.rootEntityId).components.find(c => c.type === 'UITabView')!.data;
for (const ref of [...d.tabs as string[], ...d.pages as string[]]) expect(entityById(p, ref)).toBeDefined();
expect(d.tabs).toHaveLength(3);
expect(d.pages).toHaveLength(3);
});
it('Tooltip: persists target configuration, never a transient popup', () => {
registerComponent('UITooltip', UITooltip);
const p = generate('Tooltip', world => createTooltip({ world }).entity);
expect(p.entities).toHaveLength(1);
expect(typesOf(p, p.rootEntityId)).toContain('UITooltip');
});
it('VirtualJoystick: captures base/handle entity references for scene authoring', () => {
registerComponent('VirtualJoystick', VirtualJoystick);
const p = generate('VirtualJoystick', world => createVirtualJoystick({ world }).entity as number);
const root = entityById(p, p.rootEntityId);
const control = root.components.find(c => c.type === 'VirtualJoystick')!;
expect(root.children).toContain(control.data.base);
expect(root.children).toContain(control.data.handle);
expect(control.data.inputId).toBe('move');
const baseIndex = p.entities.findIndex(e => e.prefabEntityId === control.data.base);
const handleIndex = p.entities.findIndex(e => e.prefabEntityId === control.data.handle);
expect(baseIndex).toBeLessThan(handleIndex);
});
it('VirtualButton: exports a held action with the normal button appearance', () => {
registerComponent('VirtualButton', VirtualButton);
const p = generate('VirtualButton', world => createVirtualButton({ world, events: noEvents, text: 'Fire' }).entity as number);
expect(typesOf(p, p.rootEntityId)).toContain('VirtualButton');
});
it('Button: factory → prefab captures the full clickable tree + label', () => {
const prefab = generate('Button', (world) =>
// No explicit states/colors: the factory's theme defaults also tag the
// entities with ThemeStyle roles, so the prefab re-themes at runtime.
createButton({
world, events: noEvents,
node: { width: px(140), height: px(40) },
text: { content: 'Button', fontSize: 14 },
}).entity as unknown as number,
);
const root = typesOf(prefab, prefab.rootEntityId);
expect(root).toEqual(expect.arrayContaining([
'Transform', 'UINode', 'UIVisual', 'Interactable', 'Focusable', 'UIController', 'UIGear',
]));
const rootEnt = entityById(prefab, prefab.rootEntityId);
expect(rootEnt.children.length).toBe(1);
const label = entityById(prefab, rootEnt.children[0]!);
expect(label.components.map((x) => x.type)).toEqual(expect.arrayContaining(['UINode', 'Text']));
expect(label.parent).toBe(prefab.rootEntityId);
});
it('Toggle: box + checkmark child, behavior in UIToggle', () => {
registerComponent('UIToggle', UIToggle);
const prefab = generate('Toggle', (world) =>
createToggle({
world, events: noEvents,
node: { width: px(28), height: px(28) },
isOn: true,
}).entity as unknown as number,
);
expect(typesOf(prefab, prefab.rootEntityId)).toEqual(expect.arrayContaining(
['UINode', 'Interactable', 'UIGear', 'UIToggle']));
const rootEnt = entityById(prefab, prefab.rootEntityId);
const toggleComp = rootEnt.components.find((cc) => cc.type === 'UIToggle')!;
// The check-indicator ref is remapped to a prefab-local id.
expect(rootEnt.children).toContain(toggleComp.data.check);
});
it('Slider: track + fill + handle', () => {
// The suite-wide beforeEach clears user components; capture-side entity
// ref remapping resolves UISlider by name, so put it back (the behavior
// plugin does this in a real app).
registerComponent('UISlider', UISlider);
const prefab = generate('Slider', (world) =>
createSlider({
world, events: noEvents, node: { width: px(200), height: px(18) },
min: 0, max: 100, step: 1, value: 50, handleWidth: 14,
}).entity as unknown as number,
);
expect(entityById(prefab, prefab.rootEntityId).children.length).toBe(2);
// The behavior component rides along, with its intra-prefab entity refs
// remapped to prefab-local ids — an editor-placed slider is functional.
const sliderComp = entityById(prefab, prefab.rootEntityId).components
.find((cc) => cc.type === 'UISlider')!;
expect(sliderComp).toBeDefined();
const kids = entityById(prefab, prefab.rootEntityId).children;
expect(kids).toContain(sliderComp.data.fill);
expect(kids).toContain(sliderComp.data.handle);
});
it('Dialog: backdrop scrim + panel, dismissal data-driven by UIDialog', () => {
const prefab = generate('Dialog', (world) =>
createDialog({
world, events: noEvents,
startHidden: false, // an editor-placed dialog should be visible
}).entity as unknown as number,
);
expect(typesOf(prefab, prefab.rootEntityId)).toEqual(expect.arrayContaining([
'UINode', 'UIVisual', 'Interactable', 'UIDialog',
]));
const rootEnt = entityById(prefab, prefab.rootEntityId);
expect(rootEnt.children.length).toBe(1);
expect(typesOf(prefab, rootEnt.children[0]!)).toEqual(
expect.arrayContaining(['UINode', 'UIVisual', 'Interactable']));
});
it('TextInput: an editable field over the SDF input plugin', () => {
const prefab = generate('TextInput', (world) =>
createTextInput({
world, events: noEvents,
placeholder: 'Text…',
}).entity as unknown as number,
);
expect(typesOf(prefab, prefab.rootEntityId)).toEqual(expect.arrayContaining([
'UINode', 'Interactable', 'Focusable', 'TextInput', 'ThemeStyle',
]));
});
it('Progress: track + fill', () => {
const prefab = generate('Progress', (world) =>
createProgress({
world, node: { width: px(200), height: px(14) },
value: 0.4,
}).entity as unknown as number,
);
expect(entityById(prefab, prefab.rootEntityId).children.length).toBe(1);
});
it('Dropdown: button + label, options + selection in UIDropdown (popup is runtime-only)', () => {
registerComponent('UIDropdown', UIDropdown);
const prefab = generate('Dropdown', (world) =>
createDropdown<string>({
world, events: noEvents,
node: { width: px(150), height: px(34) },
options: ['One', 'Two', 'Three'], optionToLabel: (o) => o, optionHeight: 30,
}).entity as unknown as number,
);
const rootEnt = entityById(prefab, prefab.rootEntityId);
expect(typesOf(prefab, prefab.rootEntityId)).toEqual(expect.arrayContaining(
['UINode', 'Interactable', 'UIDropdown']));
const ddComp = rootEnt.components.find((cc) => cc.type === 'UIDropdown')!;
expect(ddComp.data.options).toEqual(['One', 'Two', 'Three']);
expect(rootEnt.children).toContain(ddComp.data.label);
});
it('ListView: a clipped viewport shell (items are populated by createListView in code)', () => {
const prefab = generate('ListView', (world) => {
// The serializable half of createListView: a sized viewport with a
// Scissor mask + a hover hit-target, plus a placeholder label. Data and
// item rows are runtime-only — wire them with createListView in code.
const viewport = spawnUIEntity({
world,
node: { width: px(240), height: px(320) },
visual: { color: c.control },
});
markThemed(world, viewport, { visual: 'control' });
world.insert(viewport, UIMask, { enabled: true, mode: MaskMode.Scissor });
world.insert(viewport, Interactable, { enabled: true, blockRaycast: true, raycastTarget: true });
const label = spawnUIEntity({
world, parent: viewport,
node: { fill: true },
text: { content: 'List View', color: c.text, fontSize: 14 },
});
markThemed(world, label, { text: 'text' });
return viewport as unknown as number;
});
expect(typesOf(prefab, prefab.rootEntityId)).toEqual(expect.arrayContaining([
'UINode', 'UIVisual', 'UIMask', 'Interactable',
]));
expect(entityById(prefab, prefab.rootEntityId).children.length).toBe(1);
});
it('ScrollView: a clipped viewport that scrolls where it is dropped', () => {
const prefab = generate('ScrollView', (world) => {
// A Scissor-masked viewport over a content frame taller than it.
// UIScroll is what makes it scroll WHERE IT IS DROPPED — the widget
// builds that half in code, so a prefab without it clipped and sat.
const viewport = spawnUIEntity({
world,
node: { width: px(240), height: px(320) },
visual: { color: c.control },
});
markThemed(world, viewport, { visual: 'control' });
world.insert(viewport, UIMask, { enabled: true, mode: MaskMode.Scissor });
world.insert(viewport, Interactable, { enabled: true, blockRaycast: true, raycastTarget: true });
const content = spawnUIEntity({
world, parent: viewport,
node: {
position: UIPositionType.Absolute,
insetLeft: px(0), insetTop: px(0), width: px(240), height: px(640),
},
});
// Named rather than left to the "first child" sentinel: 0 is also a
// legal entity id, and the prefab writer maps an entity field through
// its own ids — a 0 comes out pointing at the viewport itself.
world.insert(viewport, UIScroll, {
enabled: true, content, horizontal: false, vertical: true,
movement: ScrollMovement.Clamped, wheelSpeed: 1, dragScroll: true,
decelerationRate: 0.135,
});
return viewport as unknown as number;
});
expect(typesOf(prefab, prefab.rootEntityId)).toEqual(expect.arrayContaining([
'UINode', 'UIVisual', 'UIMask', 'Interactable', 'UIScroll',
]));
const root = entityById(prefab, prefab.rootEntityId);
expect(root.children.length).toBe(1);
// The thing that MOVES is the frame, never the window it moves behind:
// a scroller pointed at itself clips nothing and slides the whole widget.
const scroll = root.components.find((cc) => cc.type === 'UIScroll')!;
expect((scroll.data as { content: string }).content).toBe(root.children[0]);
});
});