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.

refactor(editor): one rule for what an enum field may be handed

yhhf30b1a59765c
diff --git a/desktop/src/engine/EditorControlSurface.ts b/desktop/src/engine/EditorControlSurface.ts
index 7faf4c75c..c72c17906 100644
--- a/desktop/src/engine/EditorControlSurface.ts
+++ b/desktop/src/engine/EditorControlSurface.ts
@@ -26,7 +26,7 @@ import type {
import type { SceneData, PrefabData, SubsystemStatus, EventBindingRow } from 'esengine';
import { Material, Sprite, Renderer } from 'esengine';
import { EngineHost } from './EngineHost';
-import { isRequiredEmpty, componentByName, userSchema } from './schema';
+import { isRequiredEmpty, componentByName, userSchema, coerceEnumInput } from './schema';
import { ViewportController } from './ViewportController';
import { PerfMonitor, type PerfSnapshot, type FrameSample, type SessionCapture } from './PerfMonitor';
import type { SceneCommandsImpl, EditorTransaction } from './SceneCommands';
@@ -152,19 +152,23 @@ export function coerceFieldValue(
};
switch (declared) {
case 'enum': {
- // Name-valued options: accept the name (or a label spelling it), and refuse
- // anything the field cannot actually hold, rather than silently writing NaN.
- const named = options?.some((o) => typeof o.value === 'string');
- 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(', ')}`);
+ // Whether a value the options don't list is a new layer/key or a typo is the
+ // field's own answer, and coerceEnumInput is where every writer asks it —
+ // this door used to answer it separately and disagree with the control.
+ if (!options?.length) {
+ // No options to check against (a source that isn't warm, a test): the
+ // field is an ordinal, so all that is knowable is that it is a number.
+ const n = Number(value);
+ return Number.isFinite(n) ? n : fail('a number');
}
- const n = Number(value);
- return Number.isFinite(n) ? n : fail('a number');
+ if (typeof value !== 'string' && typeof value !== 'number') return fail('a name or a number');
+ const v = coerceEnumInput(value, options, open ?? false);
+ if (v !== null) return v;
+ return fail(
+ open
+ ? 'a whole number'
+ : `one of: ${options.map((o) => (o.label === String(o.value) ? o.label : `${o.value} (${o.label})`)).join(', ')}`,
+ );
}
case 'number':
case 'flags':
diff --git a/desktop/src/engine/schema.ts b/desktop/src/engine/schema.ts
index e7fec6656..0ebbf16f4 100644
--- a/desktop/src/engine/schema.ts
+++ b/desktop/src/engine/schema.ts
@@ -592,6 +592,45 @@ export function setEnumSource(name: string, provider: EnumOptionProvider | null,
export function isEnumSourceExhaustive(name: string): boolean {
return enumSources.get(name)?.exhaustive ?? true;
}
+
+/**
+ * What an enum field may be handed, for every writer of one: the inspector's
+ * control (where it arrives as typed text) and the MCP/agent door (where it
+ * arrives as whatever the client sent). `null` = not a value this field can hold.
+ *
+ * One implementation because the two doors kept drifting: they disagreed about
+ * whether a name outside an open source's options was legal, and then about
+ * whether `7.5` was a sorting layer — the control refused it and the automation
+ * path wrote it. Both questions have one answer per field, and it is here.
+ *
+ * In order: an exact option value, an option's LABEL (what a person types, and
+ * what a client sends when it read the list), then — only for an open source —
+ * the input on its own terms. Ordinals and layer indices are whole numbers, so a
+ * numeric enum takes an integer and nothing else.
+ */
+export function coerceEnumInput(
+ input: string | number,
+ options: readonly EnumOption[],
+ open: boolean,
+): string | number | null {
+ const exact = options.find((o) => o.value === input);
+ if (exact) return exact.value;
+ const text = String(input).trim();
+ const byLabel = options.find((o) => o.label.trim().toLowerCase() === text.toLowerCase());
+ if (byLabel) return byLabel.value;
+ if (!text) return null;
+ // Which kind of value the field stores comes from what its options store.
+ if (typeof input === 'number' || options.some((o) => typeof o.value === 'number')) {
+ // Ordinals and layer indices are whole numbers. "1" is one too: a text
+ // transport sends every value as a string, and refusing that spelling was
+ // how this rule first broke an ordinary MCP write.
+ const n = Number(text);
+ if (!Number.isInteger(n)) return null;
+ const byOrdinal = options.find((o) => o.value === n);
+ return byOrdinal ? byOrdinal.value : open ? n : null;
+ }
+ return open ? text : null;
+}
function enumSourceOptions(
name: string,
data: Readonly<Record<string, unknown>>,
diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsx
index cedd970a1..4a325ccbf 100644
--- a/desktop/src/panels/Details.tsx
+++ b/desktop/src/panels/Details.tsx
@@ -77,7 +77,7 @@ import { sourceById, createFromSource } from '@/engine/entitySources';
import { PlayInspect } from '@/engine/PlayInspect';
import { DimensionUnit, AnchorAxis, detectAnchorAxes, UIPositionType, FlexDirection, FlexWrap, JustifyContent, AlignItems, INTERACTION_CONTROLLER, INTERACTION_PAGES, parseLocaleTable, EasingType, BUILTIN_SHADER_TEMPLATES, INVALID_ENTITY } from 'esengine';
import type { SceneData, InputMapAsset, ActionType, Binding, LocaleTableAsset, PluralCategory, GearValue, GearTween, MaterialAssetData } from 'esengine';
-import { modelAddableComponentEntries, subscribeSchemas, getSchemaRevision, prettyLabel, hexToRgba, boxGroupsFor, isRequiredEmpty, inspectorFields, type BoxGroupDef } from '@/engine/schema';
+import { modelAddableComponentEntries, subscribeSchemas, getSchemaRevision, prettyLabel, hexToRgba, boxGroupsFor, isRequiredEmpty, inspectorFields, coerceEnumInput, type BoxGroupDef } from '@/engine/schema';
import { inspectorRegistry, buildContributedSection, isInfoRow } from '@/plugins/inspector';
import { localizePlugin } from '@/plugins/localize';
import type { AssetInspectorContribution, ComponentInspectorContribution } from '@/plugins/types';
@@ -320,20 +320,6 @@ 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,
@@ -363,12 +349,12 @@ export function EnumControl({
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 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;
+ // What the draft would write, by the field's own rule (an option, its label, or
+ // — open only — the text on its own terms).
+ const drafted = open && draft !== null ? coerceEnumInput(draft, options, true) : null;
+ // Show it as its own row only when it is NOT one of the options: those are in
+ // the list already, and a duplicate row reads as a different choice.
+ const typedValue = drafted !== null && !options.some((o) => o.value === drafted) ? drafted : null;
const { triggerProps, listProps } = useListbox(pop.isOpen, { seedFocus: !searchable && !open });
const close = () => {
pop.close();
@@ -391,7 +377,7 @@ export function EnumControl({
const onKey = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (e.key === 'Enter') {
e.preventDefault();
- if (typedValue !== null) commit(typedValue);
+ if (drafted !== null) commit(drafted);
else if (filtered.length === 1) commit(filtered[0].value);
else close();
} else if (e.key === 'Escape') {
@@ -419,11 +405,9 @@ export function EnumControl({
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);
+ // Clicking away commits what was typed rather than losing it; a draft
+ // the field cannot hold is simply dropped back to the stored value.
+ if (drafted !== null) onChange(drafted);
setDraft(null);
}}
/>
diff --git a/desktop/tests/inspector-write-values.test.ts b/desktop/tests/inspector-write-values.test.ts
index 7733c0b69..db52d04ae 100644
--- a/desktop/tests/inspector-write-values.test.ts
+++ b/desktop/tests/inspector-write-values.test.ts
@@ -13,7 +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 { coerceEnumInput } from '@/engine/schema';
import type { InspectorFieldValue } from '@/types';
describe('toModelValue', () => {
@@ -60,6 +60,23 @@ describe('coerceFieldValue (the automation door)', () => {
expect(coerceFieldValue('enum', 'projectionType', 2)).toBe(2);
});
+ // A C++ enum is as closed as a skeleton's animation list; only the spelling of
+ // its options differed, and that is what this door used to key off. Writing
+ // BlendMode 99 is the ordinal version of writing animation "sprint".
+ it('refuses an ordinal the enum does not define, naming what it does', () => {
+ const MODES = [{ label: 'Alpha', value: 0 }, { label: 'Additive', value: 1 }];
+ expect(coerceFieldValue('enum', 'blendMode', 1, MODES)).toBe(1);
+ expect(() => coerceFieldValue('enum', 'blendMode', 99, MODES)).toThrow(/Additive/);
+ });
+
+ // An open numeric enum takes any LAYER, and a layer is a whole number — the
+ // control refused 7.5 while this door wrote it.
+ it('takes an unnamed layer but not a fractional one', () => {
+ const LAYERS = [{ label: 'back', value: 0 }];
+ expect(coerceFieldValue('enum', 'layer', 7, LAYERS, true)).toBe(7);
+ expect(() => coerceFieldValue('enum', 'layer', 7.5, LAYERS, true)).toThrow(/whole number/);
+ });
+
// 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
@@ -117,25 +134,45 @@ describe('structural field members (the "position.x" door)', () => {
});
});
-// 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();
+// The one rule every writer of an enum asks: the inspector control (where the
+// input is typed text) and the automation door (where it is whatever a client
+// sent). They used to answer it separately and disagree — on whether a name
+// outside an open source was legal, and then on whether 7.5 was a sorting layer.
+describe('coerceEnumInput (what an enum field may be handed)', () => {
+ const LAYERS = [{ label: 'back', value: 0 }, { label: 'ground', value: 1 }];
+ const ANIMS = [{ label: 'stand', value: 'stand' }, { label: 'walk', value: 'walk' }];
+
+ it('takes an option by value, and by the label a person actually types', () => {
+ expect(coerceEnumInput(1, LAYERS, true)).toBe(1);
+ expect(coerceEnumInput('ground', LAYERS, true)).toBe(1);
+ expect(coerceEnumInput(' GROUND ', LAYERS, true)).toBe(1);
+ expect(coerceEnumInput('walk', ANIMS, false)).toBe('walk');
+ });
+
+ it('takes an ordinal spelled as text, which is how a text transport sends it', () => {
+ expect(coerceEnumInput('1', LAYERS, false)).toBe(1);
+ expect(coerceEnumInput('0', LAYERS, false)).toBe(0);
+ });
+
+ it('takes a whole number past the named layers when the source is open', () => {
+ expect(coerceEnumInput('7', LAYERS, true)).toBe(7);
+ expect(coerceEnumInput(7, LAYERS, true)).toBe(7);
+ expect(coerceEnumInput('-3', LAYERS, true)).toBe(-3);
+ });
+
+ it('refuses a number that is not a layer index — the same answer on both doors', () => {
+ expect(coerceEnumInput('7.5', LAYERS, true)).toBeNull();
+ expect(coerceEnumInput('nope', LAYERS, 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('takes a new name for an open name source, and refuses one for a closed one', () => {
+ expect(coerceEnumInput('menu.quit', ANIMS, true)).toBe('menu.quit');
+ expect(coerceEnumInput('sprint', ANIMS, false)).toBeNull();
+ expect(coerceEnumInput(99, LAYERS, false)).toBeNull();
});
- it('refuses an empty draft either way — that is a cleared box, not a value', () => {
- expect(parseOpenEnumText(' ', true)).toBeNull();
- expect(parseOpenEnumText('', false)).toBeNull();
+ it('refuses an empty input — that is a cleared box, not a value', () => {
+ expect(coerceEnumInput(' ', LAYERS, true)).toBeNull();
+ expect(coerceEnumInput('', ANIMS, true)).toBeNull();
});
});