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.

feat(editor): FSM/BT action pickers group by namespace and explain builtins

yhha53f1c9b25b5
diff --git a/desktop/src/components/SuggestInput.tsx b/desktop/src/components/SuggestInput.tsx
new file mode 100644
index 000000000..c2c2063a0
--- /dev/null
+++ b/desktop/src/components/SuggestInput.tsx
@@ -0,0 +1,168 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file SuggestInput.tsx
+ * @brief A free-text input with a grouped suggestion popover — the upgrade
+ * path from a bare <datalist>: candidates group by their `namespace.`
+ * prefix (un-namespaced project names first, no header), each may
+ * carry a description (builtins say what they do), and the list is
+ * keyboard-operable (arrows move, Enter picks or commits the raw
+ * text, Escape closes). Free text stays legal — the registry only
+ * knows names registered in the edit realm; a game can register more
+ * at runtime. List styling reuses the `.dd-*` popover vocabulary.
+ */
+import { useMemo, useRef, useState } from 'react';
+import { Popover, usePopover } from './Popover';
+
+export interface SuggestItem {
+ value: string;
+ /** One-line "what it does" (shown dimmed under the name; builtins carry these). */
+ desc?: string;
+}
+
+export type SuggestRow = { kind: 'header'; label: string } | { kind: 'item'; item: SuggestItem; index: number };
+type Row = SuggestRow;
+
+// Group by the `namespace.` prefix: un-namespaced names first (no header — a
+// project's own vocabulary), then each namespace under a header, alphabetically.
+// Pure and exported so the grouping/filter contract is unit-testable.
+export function buildSuggestRows(items: SuggestItem[], query: string): { rows: Row[]; flat: SuggestItem[] } {
+ const q = query.trim().toLowerCase();
+ const hits = q ? items.filter((i) => i.value.toLowerCase().includes(q)) : items;
+ const groups = new Map<string, SuggestItem[]>();
+ for (const it of hits) {
+ const dot = it.value.indexOf('.');
+ const g = dot > 0 ? it.value.slice(0, dot) : '';
+ const list = groups.get(g);
+ if (list) list.push(it);
+ else groups.set(g, [it]);
+ }
+ const names = [...groups.keys()].sort((a, b) => (a === '' ? -1 : b === '' ? 1 : a.localeCompare(b)));
+ const rows: Row[] = [];
+ const flat: SuggestItem[] = [];
+ for (const g of names) {
+ if (g !== '') rows.push({ kind: 'header', label: g });
+ for (const item of groups.get(g)!) {
+ rows.push({ kind: 'item', item, index: flat.length });
+ flat.push(item);
+ }
+ }
+ return { rows, flat };
+}
+
+export function SuggestInput({
+ defaultValue,
+ items,
+ placeholder,
+ ariaLabel,
+ onCommit,
+}: {
+ /** Initial text; callers remount via `key` on external change (defaultValue pattern). */
+ defaultValue: string;
+ items: SuggestItem[];
+ placeholder?: string;
+ ariaLabel?: string;
+ /** Fired on blur/Enter/pick with the final text (caller decides if it changed). */
+ onCommit: (v: string) => void;
+}) {
+ const pop = usePopover();
+ const input = useRef<HTMLInputElement>(null);
+ const [text, setText] = useState(defaultValue);
+ const [active, setActive] = useState(-1);
+ // A mousedown pick commits via click while keeping input focus — the blur
+ // that follows must not double-commit the stale raw text.
+ const picked = useRef(false);
+
+ const { rows, flat } = useMemo(() => buildSuggestRows(items, text), [items, text]);
+
+ const openList = () => {
+ if (!pop.isOpen && items.length > 0) pop.open(input.current);
+ };
+ const commit = (v: string) => {
+ pop.close();
+ setActive(-1);
+ onCommit(v.trim());
+ };
+
+ const onKeyDown = (e: React.KeyboardEvent) => {
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
+ e.preventDefault();
+ if (!pop.isOpen) return openList();
+ if (!flat.length) return;
+ const d = e.key === 'ArrowDown' ? 1 : -1;
+ setActive((a) => (a + d + flat.length) % flat.length);
+ } else if (e.key === 'Enter') {
+ e.preventDefault();
+ const chosen = active >= 0 && active < flat.length ? flat[active].value : text;
+ setText(chosen);
+ commit(chosen);
+ } else if (e.key === 'Escape' && pop.isOpen) {
+ e.stopPropagation(); // just close the list; a second Escape can bubble
+ pop.close();
+ setActive(-1);
+ }
+ };
+
+ return (
+ <>
+ <input
+ ref={input}
+ className="ng-input"
+ value={text}
+ placeholder={placeholder}
+ aria-label={ariaLabel}
+ aria-expanded={pop.isOpen}
+ role="combobox"
+ onChange={(e) => {
+ setText(e.target.value);
+ setActive(-1);
+ openList();
+ }}
+ onFocus={openList}
+ onKeyDown={onKeyDown}
+ onBlur={() => {
+ if (picked.current) {
+ picked.current = false;
+ return;
+ }
+ commit(text);
+ }}
+ />
+ {pop.anchor && rows.length > 0 && (
+ <Popover anchor={pop.anchor} width={Math.max(pop.anchor.width, 180)} onClose={() => pop.close()}>
+ <div className="dd-list" role="listbox">
+ {rows.map((r) =>
+ r.kind === 'header' ? (
+ <div key={`h:${r.label}`} className="dd-grp">{r.label}</div>
+ ) : (
+ <button
+ key={r.item.value}
+ type="button"
+ role="option"
+ aria-selected={r.index === active}
+ className={`dd-opt${r.index === active ? ' on' : ''}`}
+ // Commit on mousedown-then-click without surrendering input focus,
+ // so the input's blur never fires a stale raw-text commit.
+ onMouseDown={(e) => {
+ e.preventDefault();
+ picked.current = true;
+ }}
+ onClick={() => {
+ setText(r.item.value);
+ commit(r.item.value);
+ picked.current = false;
+ }}
+ >
+ <span className="dd-opt-label">
+ {r.item.value}
+ {r.item.desc && <span className="dd-opt-desc">{r.item.desc}</span>}
+ </span>
+ </button>
+ ),
+ )}
+ </div>
+ </Popover>
+ )}
+ </>
+ );
+}
diff --git a/desktop/src/components/aiSuggest.ts b/desktop/src/components/aiSuggest.ts
new file mode 100644
index 000000000..317a23fb8
--- /dev/null
+++ b/desktop/src/components/aiSuggest.ts
@@ -0,0 +1,34 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file aiSuggest.ts
+ * @brief Suggestion items for the FSM/BT editors' action & condition fields:
+ * the aiRegistry names, decorated with editor-side i18n descriptions
+ * for the engine builtins. Descriptions live HERE (not in the sdk
+ * registry) so they are bilingual via the editor's own i18n — the
+ * same display-side-label precedent as the asset importer.
+ */
+import { aiRegistry } from 'esengine';
+import { t } from '@/i18n';
+import type { SuggestItem } from './SuggestInput';
+
+// What each engine builtin does — keyed by registered name. A name the table
+// doesn't know (game-registered) simply shows without a description.
+const BUILTIN_DESC: Record<string, () => string> = {
+ 'timeline.play': () => t('ai.desc.timelinePlay'),
+ 'timeline.pause': () => t('ai.desc.timelinePause'),
+ 'timeline.finished': () => t('ai.desc.timelineFinished'),
+};
+
+const decorate = (names: string[]): SuggestItem[] =>
+ names.map((value) => ({ value, desc: BUILTIN_DESC[value]?.() }));
+
+/** Action-name suggestions (FSM state hooks, BT action nodes). */
+export function aiActionItems(): SuggestItem[] {
+ return decorate(aiRegistry.actionNames());
+}
+
+/** Condition-name suggestions (FSM transitions, BT condition nodes). */
+export function aiConditionItems(): SuggestItem[] {
+ return decorate(aiRegistry.conditionNames());
+}
diff --git a/desktop/src/i18n/messages/nodegraph.ts b/desktop/src/i18n/messages/nodegraph.ts
index 4fd3a02cf..62ce5ac63 100644
--- a/desktop/src/i18n/messages/nodegraph.ts
+++ b/desktop/src/i18n/messages/nodegraph.ts
@@ -34,6 +34,10 @@ export const nodegraphMessages = defineMessages({
'fsm.noActions': { en: 'no actions', zh: '无动作' },
'fsm.always': { en: '(always)', zh: '(总是)' },
'fsm.guardCount': { en: '{count} guards', zh: '{count} 个守卫' },
+ // — Builtin action/condition descriptions (suggest dropdowns) —
+ 'ai.desc.timelinePlay': { en: "Play the agent entity's TimelinePlayer", zh: '播放代理实体的 TimelinePlayer' },
+ 'ai.desc.timelinePause': { en: "Pause the agent entity's TimelinePlayer", zh: '暂停代理实体的 TimelinePlayer' },
+ 'ai.desc.timelineFinished': { en: 'True once the timeline has finished', zh: 'Timeline 播完后为真' },
'fsm.inspStateTitle': { en: 'State', zh: '状态' },
'fsm.inspTransitionTitle': { en: 'Transition', zh: '转移' },
'fsm.target': { en: 'Target', zh: '目标' },
diff --git a/desktop/src/main.tsx b/desktop/src/main.tsx
index 5ab21dcfd..8307c6a96 100644
--- a/desktop/src/main.tsx
+++ b/desktop/src/main.tsx
@@ -49,6 +49,8 @@ import { ViewportController } from './engine/ViewportController';
import { PerfMonitor } from './engine/PerfMonitor';
import { LogStore } from './store/LogStore';
import { initFsWatch } from './project/fsWatch';
+import { ASSET_OPEN } from './project/assetOpen';
+import { assetTypeOf } from './project/assetTypes';
import { initBackgroundThrottle } from './engine/backgroundThrottle';
// Register the built-in settings (side effect) and replay persisted ones.
import './settings';
@@ -97,6 +99,11 @@ if (new URLSearchParams(location.search).has('automation')) {
},
/** Dispatch any registered editor command by id (the UI's own channel). */
runCommand: (id: string) => commands.run(id),
+ /** Double-click-open an asset by project path (FSM/BT/tileset/clip editors…). */
+ openAsset: (path: string) => {
+ const name = path.split('/').pop() ?? path;
+ ASSET_OPEN[assetTypeOf(name)]?.(path, name);
+ },
reveal: (id: string) => dockApi.revealAndExpand(id),
togglePerfOverlay: () => PerfMonitor.toggleOverlay(),
captureThumbnail: () => ProjectStore.captureThumbnail(),
diff --git a/desktop/src/panels/BtTreeEditor.tsx b/desktop/src/panels/BtTreeEditor.tsx
index 884674c3f..e6029e8a6 100644
--- a/desktop/src/panels/BtTreeEditor.tsx
+++ b/desktop/src/panels/BtTreeEditor.tsx
@@ -14,7 +14,7 @@ import { useRef, useState, useSyncExternalStore } from 'react';
import { Trash2, Save } from 'lucide-react';
import {
btNodes, btEdges, addBtChild, addBtOrphan, removeBtNode, moveBtNode, setBtNodeField, reparentBtNode,
- canHaveChildren, maxChildren, aiRegistry,
+ canHaveChildren, maxChildren,
type BtNode, type BtNodeType, type BtDefinition, type BtEdge,
} from 'esengine';
import { BtDocument } from '@/bt/BtDocument';
@@ -23,6 +23,8 @@ import { EditorHistory } from '@/engine/EditorHistory';
import { NodeGraphCanvas, type CanvasNode, type MenuItem } from '@/components/NodeGraphCanvas';
import { Select } from '@/components/Select';
import { DirtyDot } from '@/components/DirtyDot';
+import { SuggestInput } from '@/components/SuggestInput';
+import { aiActionItems, aiConditionItems } from '@/components/aiSuggest';
type BtCanvasNode = BtNode & CanvasNode;
@@ -169,9 +171,11 @@ export function BtTreeEditor() {
{(selNode.type === 'action' || selNode.type === 'condition') && (
<label className="ng-field">{t('ng.name')}
- <input className="ng-input" list="bt-names" defaultValue={selNode.name ?? ''} key={`${selNode.id}-name`}
+ <SuggestInput
+ items={selNode.type === 'action' ? aiActionItems() : aiConditionItems()}
+ defaultValue={selNode.name ?? ''} key={`${selNode.id}-name`}
placeholder={selNode.type === 'action' ? t('ng.phActionName') : t('ng.phConditionName')}
- onBlur={e => patch(selNode.id, { name: e.target.value.trim() || undefined })} />
+ onCommit={v => patch(selNode.id, { name: v || undefined })} />
</label>
)}
{selNode.type === 'repeater' && (
@@ -215,9 +219,6 @@ export function BtTreeEditor() {
</div>
</>
)}
- <datalist id="bt-names">
- {[...aiRegistry.actionNames(), ...aiRegistry.conditionNames()].map(n => <option key={n} value={n} />)}
- </datalist>
</div>
)}
</div>
diff --git a/desktop/src/panels/StateMachineEditor.tsx b/desktop/src/panels/StateMachineEditor.tsx
index 62d43568c..7675a09e4 100644
--- a/desktop/src/panels/StateMachineEditor.tsx
+++ b/desktop/src/panels/StateMachineEditor.tsx
@@ -17,7 +17,7 @@ import { useRef, useState, useSyncExternalStore } from 'react';
import { Plus, Trash2, Save } from 'lucide-react';
import {
fsmEdges, addState, removeState, moveState, renameState, setStateHook, setInitial,
- addTransition, removeTransition, updateTransition, aiRegistry,
+ addTransition, removeTransition, updateTransition,
type FsmDefinition, type FsmState, type FsmEdge, type CompareOp,
} from 'esengine';
import { FsmGraphDocument } from '@/fsm/FsmGraphDocument';
@@ -26,6 +26,8 @@ import { EditorHistory } from '@/engine/EditorHistory';
import { NodeGraphCanvas, type CanvasNode } from '@/components/NodeGraphCanvas';
import { Select } from '@/components/Select';
import { DirtyDot } from '@/components/DirtyDot';
+import { SuggestInput } from '@/components/SuggestInput';
+import { aiActionItems, aiConditionItems } from '@/components/aiSuggest';
type FsmCanvasNode = FsmState & CanvasNode;
@@ -152,7 +154,7 @@ export function StateMachineEditor() {
}
function StateInspector({ def, state, onRename }: { def: FsmDefinition; state: FsmState; onRename: (n: string) => void }) {
- const actions = aiRegistry.actionNames();
+ const actions = aiActionItems();
const isInitial = def.initial === state.name;
return (
<div>
@@ -168,12 +170,11 @@ function StateInspector({ def, state, onRename }: { def: FsmDefinition; state: F
</label>
{HOOKS.map((h) => (
<label className="ng-field" key={h}>{h}
- <input className="ng-input" list="fsm-actions" defaultValue={state[h] ?? ''} key={`${state.name}-${h}-${state[h] ?? ''}`}
+ <SuggestInput items={actions} defaultValue={state[h] ?? ''} key={`${state.name}-${h}-${state[h] ?? ''}`}
placeholder={t('ng.phActionName')}
- onBlur={(e) => { const v = e.target.value.trim(); if (v !== (state[h] ?? '')) FsmGraphDocument.edit(`Set ${h}`, (d) => Object.assign(d, setStateHook(d, state.name, h, v))); }} />
+ onCommit={(v) => { if (v !== (state[h] ?? '')) FsmGraphDocument.edit(`Set ${h}`, (d) => Object.assign(d, setStateHook(d, state.name, h, v))); }} />
</label>
))}
- <datalist id="fsm-actions">{actions.map((a) => <option key={a} value={a} />)}</datalist>
</div>
);
}
@@ -184,7 +185,7 @@ function TransitionInspector({ def, edgeId }: { def: FsmDefinition; edgeId: stri
const src = def.states.find((s) => s.name === parsed.from);
const tr = src?.transitions?.[parsed.index];
if (!tr) return null;
- const conditions = aiRegistry.conditionNames();
+ const conditions = aiConditionItems();
const g = (tr.guard && !Array.isArray(tr.guard) ? tr.guard : undefined) as { key: string; op: CompareOp; value?: number | string | boolean } | undefined;
const patch = (p: Partial<typeof tr>) => FsmGraphDocument.edit('Edit transition', (d) => Object.assign(d, updateTransition(d, parsed.from, parsed.index, p)));
const patchGuard = (gp: Partial<NonNullable<typeof g>>) => {
@@ -207,10 +208,9 @@ function TransitionInspector({ def, edgeId }: { def: FsmDefinition; edgeId: stri
onBlur={(e) => patch({ trigger: e.target.value.trim() || undefined })} />
</label>
<label className="ng-field">{t('fsm.condition')}
- <input className="ng-input" list="fsm-conditions" defaultValue={tr.condition ?? ''} key={`cnd-${edgeId}`} placeholder={t('ng.phConditionName')}
- onBlur={(e) => patch({ condition: e.target.value.trim() || undefined })} />
+ <SuggestInput items={conditions} defaultValue={tr.condition ?? ''} key={`cnd-${edgeId}`} placeholder={t('ng.phConditionName')}
+ onCommit={(v) => patch({ condition: v || undefined })} />
</label>
- <datalist id="fsm-conditions">{conditions.map((c) => <option key={c} value={c} />)}</datalist>
<div className="ng-insp-sub">{t('fsm.guardSub')}</div>
<div className="ng-row">
<input className="ng-input" style={{ flex: 1 }} defaultValue={g?.key ?? ''} key={`gk-${edgeId}`} placeholder={t('fsm.phKey')}
diff --git a/desktop/src/theme/inspector.css b/desktop/src/theme/inspector.css
index 0c84b8195..ebb0db174 100644
--- a/desktop/src/theme/inspector.css
+++ b/desktop/src/theme/inspector.css
@@ -205,6 +205,10 @@
.dd-opt:hover { background: var(--acc-soft); color: var(--text); }
.dd-opt.on { color: var(--acc-hi); }
.dd-opt-label { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+/* Suggest-list extras: namespace group headers + a dimmed "what it does" line. */
+.dd-grp { padding: 5px 8px 2px; font-size: var(--fs-2xs); font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; color: var(--text-faint); }
+.dd-opt-desc { display: block; font-size: var(--fs-2xs); color: var(--text-faint); overflow: hidden; text-overflow: ellipsis; }
+.dd-opt:has(.dd-opt-desc) { height: auto; padding-top: 3px; padding-bottom: 3px; }
.dd-opt > svg { color: var(--acc-hi); flex-shrink: 0; }
.dd-opt .fchk { width: 13px; height: 13px; border: 1px solid var(--border-line); border-radius: var(--r-xs); display: grid; place-items: center; color: transparent; flex-shrink: 0; }
.dd-opt .fchk.on { background: var(--acc); border-color: var(--acc); color: var(--on-accent); }
diff --git a/desktop/tests/suggest-input.test.ts b/desktop/tests/suggest-input.test.ts
new file mode 100644
index 000000000..bebb83841
--- /dev/null
+++ b/desktop/tests/suggest-input.test.ts
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+// The suggest dropdown's grouping/filter contract (pure half of SuggestInput):
+// un-namespaced names lead without a header, namespaces follow alphabetically
+// under headers, filtering is a case-insensitive substring, and the flat pick
+// list stays index-aligned with the rendered item rows.
+import { describe, it, expect } from 'vitest';
+import { buildSuggestRows, type SuggestItem } from '@/components/SuggestInput';
+
+const items: SuggestItem[] = [
+ { value: 'timeline.play', desc: 'play it' },
+ { value: 'patrol' },
+ { value: 'timeline.pause' },
+ { value: 'audio.duck' },
+ { value: 'chase' },
+];
+
+describe('buildSuggestRows', () => {
+ it('groups: un-namespaced first (headerless), then namespaces alphabetically', () => {
+ const { rows } = buildSuggestRows(items, '');
+ const shape = rows.map((r) => (r.kind === 'header' ? `#${r.label}` : r.item.value));
+ expect(shape).toEqual([
+ 'patrol', 'chase',
+ '#audio', 'audio.duck',
+ '#timeline', 'timeline.play', 'timeline.pause',
+ ]);
+ });
+
+ it('flat list is index-aligned with the item rows', () => {
+ const { rows, flat } = buildSuggestRows(items, '');
+ for (const r of rows) {
+ if (r.kind === 'item') expect(flat[r.index]).toBe(r.item);
+ }
+ expect(flat).toHaveLength(5);
+ });
+
+ it('filters by case-insensitive substring and drops emptied groups', () => {
+ const { rows, flat } = buildSuggestRows(items, 'PLAY');
+ expect(flat.map((i) => i.value)).toEqual(['timeline.play']);
+ expect(rows).toEqual([
+ { kind: 'header', label: 'timeline' },
+ { kind: 'item', item: items[0], index: 0 },
+ ]);
+ });
+
+ it('keeps descriptions attached through grouping', () => {
+ const { flat } = buildSuggestRows(items, 'timeline.play');
+ expect(flat[0].desc).toBe('play it');
+ });
+
+ it('empty query returns everything; no-hit query returns nothing', () => {
+ expect(buildSuggestRows(items, '').flat).toHaveLength(5);
+ expect(buildSuggestRows(items, 'zzz').rows).toHaveLength(0);
+ });
+});