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(editor): an enum source says whether its options are the only legal values
yhhabe964668968
diff --git a/desktop/src/engine/EditorControlSurface.ts b/desktop/src/engine/EditorControlSurface.tsindex 3966de58b..7faf4c75c 100644--- a/desktop/src/engine/EditorControlSurface.ts+++ b/desktop/src/engine/EditorControlSurface.ts@@ -135,6 +135,10 @@ export function coerceFieldValue(* ("walk", "Dragon", see EnumOption) stores the name, so the option set is what* says whether a string is a legal value or a typo. */options?: readonly EnumOption[],+ /** `InspectorField.open` — the options are suggestions and a value outside them+ * is legal. Comes from the enum source's own declaration (EnumSourceOptions),+ * which is also what the inspector control reads. */+ open?: boolean,): InspectorFieldValue {const fail = (expected: string): never => {throw new Error(`field "${key}" (${declared}) expects ${expected}, got ${JSON.stringify(value)}`);@@ -154,6 +158,9 @@ export function coerceFieldValue(if (named) {const hit = options!.find((o) => o.value === value || o.label === value);if (hit) return hit.value;+ // An open source offers suggestions, not a closed set: a locale key with+ // no table entry yet is a legal thing to bind, not a typo to refuse.+ if (open) return typeof value === 'string' ? value : String(value);return fail(`one of: ${options!.map((o) => String(o.value)).join(', ')}`);}const n = Number(value);@@ -393,7 +400,7 @@ export class EditorControlSurfaceImpl {const keys = [...comp.fields.map((f) => f.key), ...(comp.enable ? [comp.enable.key] : [])];throw new Error(`"${component}" has no field "${key}" (fields: ${keys.join(', ')})`);}- this.s.commands.setField(entity, component, key, declared, coerceFieldValue(declared, key, value, field?.options));+ this.s.commands.setField(entity, component, key, declared, coerceFieldValue(declared, key, value, field?.options, field?.open));}/*** Add a component (by schema name) to an entity — the Details "Add Component" door.diff --git a/desktop/src/engine/dragonBonesNames.ts b/desktop/src/engine/dragonBonesNames.tsindex 37c6b3215..e22309267 100644--- a/desktop/src/engine/dragonBonesNames.ts+++ b/desktop/src/engine/dragonBonesNames.ts@@ -77,7 +77,9 @@ const asOptions = (names: readonly string[]): EnumOption[] =>/** Register both dropdowns. Called once at boot, beside the other enum sources. */export function installDragonBonesEnumSources(): void {- setEnumSource('dragonbonesArmatures', (data) => asOptions(armaturesFor(data).map((a) => a.name)));+ // Both exhaustive: the names come out of the referenced file, so one that is+ // not in it names nothing the runtime can play.+ setEnumSource('dragonbonesArmatures', (data) => asOptions(armaturesFor(data).map((a) => a.name)), { exhaustive: true });setEnumSource('dragonbonesAnimations', (data) => {const armatures = armaturesFor(data);@@ -90,7 +92,7 @@ export function installDragonBonesEnumSources(): void {? armatures.find((a) => a.name === chosen): armatures[0];return asOptions(armature?.animations ?? []);- });+ }, { exhaustive: true });}/** Drop the cache — a project close, or an asset edited outside the editor. */diff --git a/desktop/src/engine/schema.ts b/desktop/src/engine/schema.tsindex 36cb46167..e7fec6656 100644--- a/desktop/src/engine/schema.ts+++ b/desktop/src/engine/schema.ts@@ -557,18 +557,47 @@ export type EnumOptionProvider = (entity?: EntityId,) => EnumOption[];-const enumSources = new Map<string, EnumOptionProvider>();-/** Register (or clear) a named source of dynamic enum options. */-export function setEnumSource(name: string, provider: EnumOptionProvider | null): void {- if (provider) enumSources.set(name, provider);+/**+ * Whether a source's options are the ONLY legal values, which is a property of+ * the thing being named and not of how it is spelled:+ *+ * - EXHAUSTIVE — a spine animation, a DragonBones armature. The names come out of+ * the referenced file; one that isn't in it is a typo, and the editor should+ * refuse it rather than store a reference to nothing.+ * - not exhaustive — a sorting layer (the names are aliases over an i32 the+ * renderer sorts on regardless), a locale key (binding one before its entry+ * exists is the normal authoring order). The options are SUGGESTIONS.+ *+ * Declared here once because both writers need the same answer: the inspector,+ * to decide whether the control may accept a value outside the list, and+ * coerceFieldValue, for the same decision on the MCP/agent path. That answer+ * used to be guessed independently from whether the value was a string, which+ * happened to be right for the skeleton sources and wrong for locale keys.+ */+export interface EnumSourceOptions {+ exhaustive: boolean;+}++const enumSources = new Map<string, { provider: EnumOptionProvider; exhaustive: boolean }>();+/** Register a named source of dynamic enum options. */+export function setEnumSource(name: string, provider: EnumOptionProvider, opts: EnumSourceOptions): void;+/** Clear a named source. */+export function setEnumSource(name: string, provider: null): void;+export function setEnumSource(name: string, provider: EnumOptionProvider | null, opts?: EnumSourceOptions): void {+ if (provider) enumSources.set(name, { provider, exhaustive: opts?.exhaustive ?? true });else enumSources.delete(name);}+/** Whether values outside `name`'s options are illegal. Unknown sources answer+ * true, but offer no options either, so the field stays freely editable. */+export function isEnumSourceExhaustive(name: string): boolean {+ return enumSources.get(name)?.exhaustive ?? true;+}function enumSourceOptions(name: string,data: Readonly<Record<string, unknown>>,entity?: EntityId,): EnumOption[] {- return enumSources.get(name)?.(data, entity) ?? [];+ return enumSources.get(name)?.provider(data, entity) ?? [];}/** The bit options for a bitmask field: its source's labels, else `Layer N`. */function bitmaskOptions(meta: { bits?: number; source?: string }): EnumOption[] {@@ -629,6 +658,8 @@ function fieldFor(const stringly = typeof options[0].value === 'string';const v = stringly ? (typeof value === 'string' ? value : '') : (Number(value) || 0);field = { key, label: prettyLabel(key), type: 'enum', value: v, options };+ // Suggestions, not a closed set — the control lets a value outside them in.+ if (!isEnumSourceExhaustive(meta.enumSource)) field.open = true;} else {field = inferField(key, value, isColor);if (field && field.type === 'number' && meta) {diff --git a/desktop/src/engine/spineEnums.ts b/desktop/src/engine/spineEnums.tsindex 844bf466e..5dba68a6c 100644--- a/desktop/src/engine/spineEnums.ts+++ b/desktop/src/engine/spineEnums.ts@@ -24,6 +24,8 @@ const options = (entity: number | undefined, pick: (rt: number) => string[]): En};export function installSpineEnumSources(): void {- setEnumSource('spineAnimations', (_data, entity) => options(entity, (rt) => EngineHost.spineAnimations(rt)));- setEnumSource('spineSkins', (_data, entity) => options(entity, (rt) => EngineHost.spineSkins(rt)));+ // Exhaustive: the names come out of the loaded skeleton, so one that isn't in it+ // names nothing.+ setEnumSource('spineAnimations', (_data, entity) => options(entity, (rt) => EngineHost.spineAnimations(rt)), { exhaustive: true });+ setEnumSource('spineSkins', (_data, entity) => options(entity, (rt) => EngineHost.spineSkins(rt)), { exhaustive: true });}diff --git a/desktop/src/i18n/messages/details.ts b/desktop/src/i18n/messages/details.tsindex bff87a288..24ceccf76 100644--- a/desktop/src/i18n/messages/details.ts+++ b/desktop/src/i18n/messages/details.ts@@ -27,6 +27,7 @@ export const detailsMessages = defineMessages({zh: '需要 Transform 来放置阴影盒 —— 该投影体被跳过。',},'det.noMatch': { en: 'No match', zh: '无匹配项' },+ 'det.useLiteral': { en: 'Use {value}', zh: '使用 {value}' },'det.none': { en: 'None', zh: '无' },'det.noneOption': { en: '(none)', zh: '(无)' },'det.mapKey': { en: 'key', zh: '键' },diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsxindex c42d29638..cedd970a1 100644--- a/desktop/src/panels/Details.tsx+++ b/desktop/src/panels/Details.tsx@@ -320,41 +320,121 @@ export function SidesControl({// list would offer "Stand" for a value spelled "stand". A value with no matching// option still shows as itself (an animation the skeleton no longer declares is a// thing to SEE, not a blank), and an empty one reads as "None".+/**+ * Parse text typed into an OPEN enum against what its options store: a numeric+ * source (sorting layers) takes an integer and nothing else, a name source takes+ * any non-empty name. `null` = not a value this field can hold, so the draft is+ * refused instead of written.+ */+export function parseOpenEnumText(text: string, numeric: boolean): string | number | null {+ const s = text.trim();+ if (!s) return null;+ if (!numeric) return s;+ const n = Number(s);+ return Number.isInteger(n) ? n : null;+}+export function EnumControl({value,options,+ open,mixed,onBegin,onEnd,onChange,-}: ControlGesture & { value: string | number; options: EnumOption[]; mixed?: boolean; onChange: (v: string | number) => void }) {+}: ControlGesture & {+ value: string | number;+ options: EnumOption[];+ /** Options are suggestions; typed values outside them are legal. See InspectorField.open. */+ open?: boolean;+ mixed?: boolean;+ onChange: (v: string | number) => void;+}) {const pop = usePopover();const trigger = useRef<HTMLButtonElement>(null);+ const input = useRef<HTMLInputElement>(null);const [q, setQ] = useState('');+ // What an open control is currently being typed into; null = showing its value.+ const [draft, setDraft] = useState<string | null>(null);const optLabel = (o: EnumOption): string => (typeof o.value === 'number' ? prettyLabel(o.label) : o.label);const cur = options.find((o) => o.value === value);const label = mixed ? '' : cur ? optLabel(cur) : String(value) || t('det.noneOption');- const searchable = options.length > 8;- const ql = q.trim().toLowerCase();+ // The open control's own input IS the filter, so it never grows a second one.+ const searchable = !open && options.length > 8;+ const ql = (open ? (draft ?? '') : q).trim().toLowerCase();const filtered = ql ? options.filter((o) => optLabel(o).toLowerCase().includes(ql)) : options;- const { triggerProps, listProps } = useListbox(pop.isOpen, { seedFocus: !searchable });+ const numeric = typeof value === 'number' || options.some((o) => typeof o.value === 'number');+ // A typed value that no option spells: offer it as its own row rather than+ // leaving the list empty and the keystroke looking rejected.+ const typedValue = open && draft !== null && !filtered.some((o) => optLabel(o).toLowerCase() === ql)+ ? parseOpenEnumText(draft, numeric)+ : null;+ const { triggerProps, listProps } = useListbox(pop.isOpen, { seedFocus: !searchable && !open });const close = () => {pop.close();- trigger.current?.focus();+ setDraft(null);+ (open ? input : trigger).current?.focus();onEnd?.();};+ const commit = (v: string | number) => {+ onChange(v);+ close();+ };const toggle = () => {if (pop.isOpen) return close();setQ('');onBegin?.();- pop.open(trigger.current);+ pop.open((open ? input : trigger).current);+ };+ // Enter takes the typed value (or the sole remaining suggestion); Escape drops+ // the draft without writing. Blur commits, so a click elsewhere isn't a silent loss.+ const onKey = (e: React.KeyboardEvent<HTMLInputElement>) => {+ if (e.key === 'Enter') {+ e.preventDefault();+ if (typedValue !== null) commit(typedValue);+ else if (filtered.length === 1) commit(filtered[0].value);+ else close();+ } else if (e.key === 'Escape') {+ e.preventDefault();+ close();+ }};return (<span className="field dropdown">- <button ref={trigger} type="button" className="dd-trigger" {...triggerProps} onMouseDown={(e) => e.stopPropagation()} onClick={toggle}>- <span className={`dd-val${mixed ? ' mixed' : ''}`}>{mixed ? '—' : label}</span>- <ChevronDown size={12} strokeWidth={2} />- </button>+ {open ? (+ <span className="dd-trigger dd-trigger--open">+ <input+ ref={input}+ className={`dd-input${mixed ? ' mixed' : ''}`}+ value={draft ?? (mixed ? '' : label)}+ placeholder={mixed ? '—' : undefined}+ spellCheck={false}+ onMouseDown={(e) => e.stopPropagation()}+ onFocus={() => {+ if (!pop.isOpen) {+ onBegin?.();+ pop.open(input.current);+ }+ }}+ onChange={(e) => setDraft(e.target.value)}+ onKeyDown={onKey}+ onBlur={() => {+ if (draft === null) return;+ const v = parseOpenEnumText(draft, numeric);+ const named = filtered.find((o) => optLabel(o).toLowerCase() === (draft ?? '').trim().toLowerCase());+ if (named) onChange(named.value);+ else if (v !== null) onChange(v);+ setDraft(null);+ }}+ />+ <ChevronDown size={12} strokeWidth={2} onMouseDown={(e: React.MouseEvent) => e.preventDefault()} onClick={toggle} />+ </span>+ ) : (+ <button ref={trigger} type="button" className="dd-trigger" {...triggerProps} onMouseDown={(e) => e.stopPropagation()} onClick={toggle}>+ <span className={`dd-val${mixed ? ' mixed' : ''}`}>{mixed ? '—' : label}</span>+ <ChevronDown size={12} strokeWidth={2} />+ </button>+ )}{pop.anchor && (<Popover anchor={pop.anchor} width={Math.max(pop.anchor.width, 150)} onClose={close}>{searchable && (@@ -368,16 +448,28 @@ export function EnumControl({role="option"aria-selected={o.value === value && !mixed}className={`dd-opt${o.value === value && !mixed ? ' on' : ''}`}- onClick={() => {- onChange(o.value);- close();- }}+ onMouseDown={(e) => e.preventDefault()}+ onClick={() => commit(o.value)}><span className="dd-opt-label">{optLabel(o)}</span>{o.value === value && !mixed && <Check size={12} strokeWidth={2.4} />}</button>))}- {filtered.length === 0 && <div className="empty-line empty-line--sm">{t('det.noMatch')}</div>}+ {typedValue !== null && (+ <button+ type="button"+ role="option"+ aria-selected={false}+ className="dd-opt dd-opt--literal"+ onMouseDown={(e) => e.preventDefault()}+ onClick={() => commit(typedValue)}+ >+ <span className="dd-opt-label">{t('det.useLiteral', { value: String(typedValue) })}</span>+ </button>+ )}+ {filtered.length === 0 && typedValue === null && (+ <div className="empty-line empty-line--sm">{t('det.noMatch')}</div>+ )}</div></Popover>)}@@ -1470,6 +1562,7 @@ function FieldRow({ entities, comp, field: rawField, write }: { entities: Entity<EnumControlvalue={field.value as string | number}options={field.options ?? []}+ open={field.open}mixed={mixed}onBegin={begin}onEnd={end}diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex d636775f1..7735b1f95 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -276,7 +276,9 @@ class ProjectStoreImpl {// (dragonBones armatures/animations), the skeleton an entity has LOADED (spine),// or the project's locale tables (i18n keys). One registry, one control, one// write path — see setEnumSource.- setEnumSource('sortingLayers', () => this.sortingLayerOptions());+ // Not exhaustive: the names alias an i32 the renderer sorts on either way, so+ // a layer nobody named is still a legal layer.+ setEnumSource('sortingLayers', () => this.sortingLayerOptions(), { exhaustive: false });installDragonBonesEnumSources();installSpineEnumSources();installLocaleKeyEnumSource(() => this.listAssets('locale'));diff --git a/desktop/src/project/localeKeys.ts b/desktop/src/project/localeKeys.tsindex 64c821fff..fe4bcc34e 100644--- a/desktop/src/project/localeKeys.ts+++ b/desktop/src/project/localeKeys.ts@@ -90,8 +90,10 @@ export function installLocaleKeyEnumSource(listAssets: () => ReadonlyArray<{ path: string }>,): void {listLocaleAssets = listAssets;+ // Not exhaustive: binding a key before its table entry exists is the normal+ // authoring order, and the runtime falls back to the key's own text meanwhile.setEnumSource('localeKeys', () => {kickScan();return options;- });+ }, { exhaustive: false });}diff --git a/desktop/src/theme/inspector.css b/desktop/src/theme/inspector.cssindex 022ef9a85..fd39f1b24 100644--- a/desktop/src/theme/inspector.css+++ b/desktop/src/theme/inspector.css@@ -255,6 +255,14 @@.dd-val.dd-none, .dd-opt-label.dd-none { color: var(--text-mute); font-style: italic; }.dd-trigger > svg { color: var(--text-mute); flex-shrink: 0; }.dd-trigger:hover > svg { color: var(--text-dim); }+/* Open enum (options are suggestions): the trigger IS the text field, so the value+ is typed in place and the chevron only reveals the suggestions. */+.dd-trigger--open { cursor: text; }+.dd-trigger--open > svg { cursor: pointer; }+.dd-input { flex: 1; min-width: 0; background: none; border: none; outline: none; padding: 0; color: var(--text); font-size: var(--fs-sm); }+.dd-input.mixed::placeholder { color: var(--text-mute); }+/* The "use what you typed" row — an escape from the list, not one of its entries. */+.dd-opt--literal { color: var(--text-mute); font-style: italic; }.popover { position: fixed; z-index: var(--z-popover); background: var(--srf-3); border: 1px solid var(--border-line); border-radius: var(--r-md); box-shadow: var(--shadow-3); padding: 3px; max-height: 320px; display: flex; flex-direction: column; min-width: 0; }/* popover-internal filter = the shared flush SearchField */diff --git a/desktop/src/types.ts b/desktop/src/types.tsindex 96831270f..ca9c6fa84 100644--- a/desktop/src/types.ts+++ b/desktop/src/types.ts@@ -131,6 +131,12 @@ export interface InspectorField {assetType?: string;/** For `type: 'enum'` — the selectable options (label + stored int). */options?: EnumOption[];+ /**+ * For `type: 'enum'` — the options are SUGGESTIONS, and a value outside them is+ * legal (a sorting layer past the named ones, a locale key not yet written).+ * Absent/false ⇒ the options are the only legal values. See EnumSourceOptions.+ */+ open?: boolean;/** For `type: 'select'` — the selectable string values. */selectOptions?: string[];/**diff --git a/desktop/tests/enum-source-context.test.ts b/desktop/tests/enum-source-context.test.tsindex 599694990..45a599397 100644--- a/desktop/tests/enum-source-context.test.ts+++ b/desktop/tests/enum-source-context.test.ts@@ -10,10 +10,15 @@// sees the component and the entity, an option may BE a name rather than an index// into one, and it may carry a label that reads differently from what it stores.import { describe, it, expect, afterEach } from 'vitest';-import { setEnumSource, inspectorFields } from '@/engine/schema';+import { setEnumSource, isEnumSourceExhaustive, inspectorFields } from '@/engine/schema';const FIELD = 'layer';+// Most cases here are about WHAT a provider sees and stores, not about whether its+// options are the only legal values, so they take the strict reading. Openness has+// its own describe block below.+const EXHAUSTIVE = { exhaustive: true } as const;+afterEach(() => {setEnumSource('sortingLayers', null);});@@ -27,7 +32,7 @@ describe('enum sources', () => {setEnumSource('sortingLayers', (data) => {seen = data as Record<string, unknown>;return [{ label: 'Default', value: 0 }];- });+ }, EXHAUSTIVE);fieldsOf('Sprite', { layer: 0, texture: 0 });expect(seen).not.toBeNull();@@ -40,7 +45,7 @@ describe('enum sources', () => {setEnumSource('sortingLayers', (data) =>data.texture === 1? [{ label: 'A', value: 0 }, { label: 'B', value: 1 }]- : [{ label: 'Only', value: 0 }]);+ : [{ label: 'Only', value: 0 }], EXHAUSTIVE);const one = fieldsOf('Sprite', { layer: 0, texture: 1 }).find((f) => f.key === FIELD);const two = fieldsOf('Sprite', { layer: 0, texture: 2 }).find((f) => f.key === FIELD);@@ -54,7 +59,7 @@ describe('enum sources', () => {setEnumSource('sortingLayers', () => [{ label: 'walk', value: 'walk' },{ label: 'idle', value: 'idle' },- ]);+ ], EXHAUSTIVE);const f = fieldsOf('Sprite', { layer: 'idle' }).find((x) => x.key === FIELD);expect(f?.type).toBe('enum');@@ -65,7 +70,7 @@ describe('enum sources', () => {setEnumSource('sortingLayers', () => [{ label: 'Default', value: 0 },{ label: 'Foreground', value: 3 },- ]);+ ], EXHAUSTIVE);const f = fieldsOf('Sprite', { layer: 3 }).find((x) => x.key === FIELD);expect(f?.type).toBe('enum');@@ -80,7 +85,7 @@ describe('enum sources', () => {setEnumSource('sortingLayers', (_data, entity) => {seen = entity;return [{ label: 'Default', value: 0 }];- });+ }, EXHAUSTIVE);fieldsOf('Sprite', { layer: 0 }, 42);expect(seen).toBe(42);@@ -88,7 +93,7 @@ describe('enum sources', () => {it('keeps a label that reads differently from the value it stores', () => {// An i18n key previews its translation; the key is still what gets written.- setEnumSource('sortingLayers', () => [{ label: 'menu.play · 开始', value: 'menu.play' }]);+ setEnumSource('sortingLayers', () => [{ label: 'menu.play · 开始', value: 'menu.play' }], EXHAUSTIVE);const f = fieldsOf('Sprite', { layer: 'menu.play' }).find((x) => x.key === FIELD);expect(f?.options).toEqual([{ label: 'menu.play · 开始', value: 'menu.play' }]);@@ -102,3 +107,30 @@ describe('enum sources', () => {expect(f?.type).not.toBe('enum');});});++// Whether a source's options are the ONLY legal values is a property of the thing+// being named, not of how it is spelled — and both writers (the inspector control+// and the MCP/agent path) have to get the same answer, which is why the source+// declares it once instead of each side guessing from the value's type.+describe('enum sources — exhaustive vs open', () => {+ it('marks a field open exactly when its source says its options are suggestions', () => {+ setEnumSource('sortingLayers', () => [{ label: 'back', value: 0 }], { exhaustive: false });+ expect(fieldsOf('Sprite', { layer: 0 }).find((f) => f.key === FIELD)?.open).toBe(true);++ setEnumSource('sortingLayers', () => [{ label: 'back', value: 0 }], EXHAUSTIVE);+ expect(fieldsOf('Sprite', { layer: 0 }).find((f) => f.key === FIELD)?.open).toBeFalsy();+ });++ it('keeps a value the options never offered — the layer nobody named', () => {+ // The renderer sorts on any i32; the names are aliases over it. A project+ // that named three layers must still be able to hold layer 7.+ setEnumSource('sortingLayers', () => [{ label: 'back', value: 0 }], { exhaustive: false });+ const f = fieldsOf('Sprite', { layer: 7 }).find((x) => x.key === FIELD);+ expect(f?.type).toBe('enum');+ expect(f?.value).toBe(7);+ });++ it('reports unknown sources as exhaustive, which offer nothing anyway', () => {+ expect(isEnumSourceExhaustive('nothing-registered-here')).toBe(true);+ });+});diff --git a/desktop/tests/inspector-model.test.ts b/desktop/tests/inspector-model.test.tsindex 4227e509b..93a6fc0f6 100644--- a/desktop/tests/inspector-model.test.ts+++ b/desktop/tests/inspector-model.test.ts@@ -379,13 +379,23 @@ describe('Sorting-layer enum source (render layer)', () => {});it('becomes a named dropdown once sorting layers are defined', () => {- setEnumSource('sortingLayers', () => [{ label: 'Background', value: 0 }, { label: 'Foreground', value: 1 }]);+ setEnumSource('sortingLayers', () => [{ label: 'Background', value: 0 }, { label: 'Foreground', value: 1 }], { exhaustive: false });const S = EditorSession.create();S.model.adopt(spriteScene(1), new Map([[1, 1]]));const lf = layerField(S);expect(lf.type).toBe('enum');expect(lf.value).toBe(1);expect(lf.options!.map((o) => o.label)).toEqual(['Background', 'Foreground']);+ // Naming two layers must not make the other thirty illegal — the dropdown+ // offers the names, and still takes a number outside them.+ expect(lf.open).toBe(true);+ });++ it('holds a layer past the named ones', () => {+ setEnumSource('sortingLayers', () => [{ label: 'Background', value: 0 }], { exhaustive: false });+ const S = EditorSession.create();+ S.model.adopt(spriteScene(9), new Map([[1, 1]]));+ expect(layerField(S).value).toBe(9);});});diff --git a/desktop/tests/inspector-write-values.test.ts b/desktop/tests/inspector-write-values.test.tsindex 60c602d2f..7733c0b69 100644--- a/desktop/tests/inspector-write-values.test.ts+++ b/desktop/tests/inspector-write-values.test.ts@@ -13,6 +13,7 @@import { describe, it, expect } from 'vitest';import { toModelValue } from '@/engine/SceneCommands';import { coerceFieldValue, splitFieldMember, patchFieldMember } from '@/engine/EditorControlSurface';+import { parseOpenEnumText } from '@/panels/Details';import type { InspectorFieldValue } from '@/types';describe('toModelValue', () => {@@ -58,6 +59,17 @@ describe('coerceFieldValue (the automation door)', () => {expect(coerceFieldValue('enum', 'projectionType', '1', [{ label: 'Ortho', value: 1 }])).toBe(1);expect(coerceFieldValue('enum', 'projectionType', 2)).toBe(2);});++ // An OPEN source offers suggestions, not a closed set: a locale key with no+ // table entry yet is the normal authoring order, not a typo. The refusal above+ // and the acceptance here are the same rule reading the source's own+ // declaration — before, this path guessed from the value being a string and so+ // refused a perfectly good new key.+ it('accepts a name outside the options when the source is open', () => {+ const KEYS = [{ label: 'menu.play', value: 'menu.play' }];+ expect(coerceFieldValue('enum', 'i18nKey', 'menu.quit', KEYS, true)).toBe('menu.quit');+ expect(() => coerceFieldValue('enum', 'i18nKey', 'menu.quit', KEYS, false)).toThrow(/menu\.play/);+ });});// A field path like "Transform.position.x" is what automation reaches for first —@@ -104,3 +116,26 @@ describe('structural field members (the "position.x" door)', () => {expect(patchFieldMember('vec2', [0, 0], 'y', '12.5')).toEqual([0, 12.5]);});});++// The open enum's text field decides what a keystroke MEANS: a sorting layer is+// an integer alias, so "back " picks the option and "7" is a layer, while "7.5"+// and "" are not values the field can hold and must not be written.+describe('parseOpenEnumText (what an open enum accepts typed)', () => {+ it('takes an integer for a numeric source, and nothing else numeric-ish', () => {+ expect(parseOpenEnumText('7', true)).toBe(7);+ expect(parseOpenEnumText(' 12 ', true)).toBe(12);+ expect(parseOpenEnumText('-3', true)).toBe(-3);+ expect(parseOpenEnumText('7.5', true)).toBeNull();+ expect(parseOpenEnumText('back', true)).toBeNull();+ });++ it('takes any non-empty name for a name source', () => {+ expect(parseOpenEnumText('menu.quit', false)).toBe('menu.quit');+ expect(parseOpenEnumText(' spaced ', false)).toBe('spaced');+ });++ it('refuses an empty draft either way — that is a cleared box, not a value', () => {+ expect(parseOpenEnumText(' ', true)).toBeNull();+ expect(parseOpenEnumText('', false)).toBeNull();+ });+});