State machines: asset, tab, State branch and Set state nodes (#51)

A state machine is an asset whose graph holds one `State` node per state
(no ports, name as title), edited in a new "State machine" tab that reuses
the graph canvas: right-click places "State n", snap toggle shared with the
Behavior tab via SnapToggle. `statemachine` is a value kind like texture
(port, literal node, variable, struct field, tagged list item).

Behaviors use it through `State branch` (one exec output per state) and
`Set state` (one exec input per state; the interpreter now hands `run` the
entry port). States live per behavior instance in NodeContext.states, with
no initial state. Ports derive from the inline picker or a wired
`State machine` literal; BehaviorLookup became GraphLookup with
behavior(id) and machine(id).

The Graph tab is labelled "Behavior" (key unchanged). Unit tests
(state-machine, kinds, catalog, ports), e2e step 26 and README added.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
rootandClaude Fable 5.1 committed 2026-09-12 18:00:23 +02:00
1 parent ce42d16657
commit e7d82bd1a9
60 files changed
+1269 -213

No files matched your search

+1 -1
View File
@@ -30,7 +30,7 @@ export interface AssetTabOptions {
}
/**
* The Graph, Texture and Container tabs; each keeps its last asset when the selection moves elsewhere.
* The Behavior, State machine, Texture and Container tabs; each keeps its last asset when the selection moves elsewhere.
* A subclass must call `mount()`: header and canvas depend on each other, so the base cannot build them.
*/
export abstract class AssetTabEditor<
+25 -5
View File
@@ -17,19 +17,31 @@ import { HierarchyPanel } from './panels/HierarchyPanel';
import { Toolbar } from './panels/Toolbar';
import { type PlayHost, PlaySession, type WorldSnapshot } from './PlaySession';
import { ProjectSession } from './ProjectSession';
import { StateMachineEditor } from './statemachine/StateMachineEditor';
import { installShortcuts } from './shortcuts';
import type { EditorState } from './state';
import { TextureEditor } from './texture/TextureEditor';
import { installTextureImport } from './textureImport';
export type CentreTab = 'scene' | 'graph' | 'game' | 'texture' | 'animation' | 'container' | 'list';
export type CentreTab =
'scene' | 'graph' | 'statemachine' | 'game' | 'texture' | 'animation' | 'container' | 'list';
const TAB_ORDER = ['scene', 'game', 'graph', 'texture', 'animation', 'container', 'list'] as const;
const TAB_ORDER = [
'scene',
'game',
'graph',
'statemachine',
'texture',
'animation',
'container',
'list',
] as const;
const TAB_LABELS: Record<CentreTab, string> = {
scene: 'Scene',
game: 'Game',
graph: 'Graph',
graph: 'Behavior',
statemachine: 'State machine',
texture: 'Texture',
animation: 'Animation',
container: 'Container',
@@ -52,6 +64,7 @@ export class Editor implements PlayHost {
/** Game tab: the running world through its camera. */
readonly gameView: GameViewport;
readonly graphEditor: GraphEditor;
readonly stateMachineEditor: StateMachineEditor;
readonly textureEditor: TextureEditor;
readonly animationEditor: AnimationEditor;
readonly containerEditor: ContainerEditor;
@@ -88,6 +101,7 @@ export class Editor implements PlayHost {
this.viewport = new SceneViewport(state);
this.gameView = new GameViewport(state);
this.graphEditor = new GraphEditor(state);
this.stateMachineEditor = new StateMachineEditor(state);
this.textureEditor = new TextureEditor(state);
this.animationEditor = new AnimationEditor(state);
this.containerEditor = new ContainerEditor(state);
@@ -132,6 +146,7 @@ export class Editor implements PlayHost {
scene: this.viewport,
game: this.gameView,
graph: this.graphEditor,
statemachine: this.stateMachineEditor,
texture: this.textureEditor,
animation: this.animationEditor,
container: this.containerEditor,
@@ -141,6 +156,7 @@ export class Editor implements PlayHost {
scene: this.tabButton('scene'),
game: this.tabButton('game'),
graph: this.tabButton('graph'),
statemachine: this.tabButton('statemachine'),
texture: this.tabButton('texture'),
animation: this.tabButton('animation'),
container: this.tabButton('container'),
@@ -182,10 +198,14 @@ export class Editor implements PlayHost {
});
app.ticker.add((ticker) => this.tick(ticker.deltaMS / 1000));
// A node, a frame and a template object exist only in their own tab, so selecting one
// switches to it; selecting the behavior, texture or container asset itself does not.
// switches to it; selecting the behavior, texture or container asset itself does not. A state
// machine asset does switch (user's choice): its tab is the only place it shows anything.
state.on('selection', () => {
const s = state.selection;
if (s?.kind === 'node' && this.tab !== 'graph') this.showTab('graph');
const machine = state.selectedStateMachineId !== null;
if (s?.kind === 'node' && !machine && this.tab !== 'graph') this.showTab('graph');
if ((s?.kind === 'node' || s?.kind === 'asset') && machine && this.tab !== 'statemachine')
this.showTab('statemachine');
if (s?.kind === 'frame' && this.tab !== 'texture') this.showTab('texture');
if (
s?.kind === 'object' &&
+10
View File
@@ -230,6 +230,16 @@ export function installDebugHook(app: Application, state: EditorState, editor: E
snapping: () => graphEditor.canvas.snapEnabled,
crumbs: () => graphEditor.breadcrumb.crumbsDrawn(),
},
stateMachine: {
current: () => editor.stateMachineEditor.currentAssetId,
pickerAt: () => centreOf(editor.stateMachineEditor.picker),
nodeAt: (nodeId: string) => editor.stateMachineEditor.canvas.nodeGlobal(nodeId),
nodeLabel: (nodeId: string) => editor.stateMachineEditor.canvas.nodeLabel(nodeId),
nodeRect: (nodeId: string) => editor.stateMachineEditor.canvas.nodeRect(nodeId),
canvasRect: () => editor.stateMachineEditor.canvas.canvasRect(),
center: () => centreOf(editor.stateMachineEditor.canvas),
snapping: () => editor.stateMachineEditor.canvas.snapEnabled,
},
/** The open image picker: what it offers, what is picked, and where a tile sits. */
imagePicker: () => currentImagePicker()?.debugInfo() ?? null,
imagePickerTile: (file: string) => currentImagePicker()?.tileGlobal(file) ?? null,
+22 -20
View File
@@ -17,17 +17,18 @@ import {
edgesInto,
edgesOutOf,
firstPortFor,
type Graph,
type GraphNode,
type BehaviorLookup,
type GraphLookup,
type PortSide,
type PortType,
portTypeOf,
resolveDef,
RUN_BEHAVIOR,
} from '../../core/graph';
import type { BehaviorAsset } from '../../core/model/Asset';
import { behaviorLookup } from '../../core/model/behaviorPrograms';
import { findAsset } from '../../core/model/Project';
import type { GraphAsset } from '../../core/model/Asset';
import { graphLookup } from '../../core/model/graphLookup';
import { findAsset, findGraphAsset } from '../../core/model/Project';
import { type Trace, TRACE_FADE } from '../../runtime/systems/BehaviorSystem';
import { beadsInFlight, launchBead } from './beads';
import {
@@ -69,8 +70,8 @@ const DRAG_THRESHOLD = 3;
const LIVE_VALUE_INTERVAL_MS = 100;
/**
* The node graph of one behavior asset. Which behavior that is comes from the outside (`show`),
* so the canvas never has an opinion about the selection – the GraphEditor around it does.
* The node graph of one behavior or state machine asset. Which one that is comes from the outside
* (`show`), so the canvas never has an opinion about the selection – the tab around it does.
*/
export class GraphCanvas extends Widget {
private readonly bg = new Graphics();
@@ -123,7 +124,11 @@ export class GraphCanvas extends Widget {
/** A double-clicked call node; the tab opens the behavior and records the step. */
onOpenBehavior: (assetId: string) => void = (assetId) => this.state.select({ kind: 'asset', assetId });
constructor(private readonly state: EditorState) {
constructor(
private readonly state: EditorState,
/** Names the asset kind in the empty state: "No behavior selected …". */
private readonly noun = 'behavior',
) {
super();
this.canvas.addChild(this.edgeLayer, this.nodeLayer, this.tempEdge);
this.addChild(this.bg, this.grid, this.canvas, this.band, this.hint, this.clip);
@@ -187,20 +192,19 @@ export class GraphCanvas extends Widget {
return { w: Math.max(this.minWidth, 200), h: Math.max(this.minHeight, 200) };
}
private behaviors(): BehaviorLookup {
return behaviorLookup(this.state.project);
private behaviors(): GraphLookup {
return graphLookup(this.state.project);
}
private asset(): BehaviorAsset | null {
const asset = this.assetId ? findAsset(this.state.project, this.assetId) : undefined;
return asset && asset.type === 'behavior' ? asset : null;
private asset(): GraphAsset | null {
return (this.assetId && findGraphAsset(this.state.project, this.assetId)) || null;
}
/** Rebuilds node views from the model (cheap: views are reused by node id). */
private sync(): void {
const asset = this.asset();
if (!asset) {
// A behavior that was deleted (or undone away) must not linger as a graph.
// An asset that was deleted (or undone away) must not linger as a graph.
this.assetId = '';
for (const view of this.views.values()) view.destroy({ children: true });
this.views.clear();
@@ -208,7 +212,7 @@ export class GraphCanvas extends Widget {
return;
}
const seen = new Set<string>();
const lookup = behaviorLookup(this.state.project);
const lookup = graphLookup(this.state.project);
for (const node of asset.graph.nodes) {
const def = resolveDef(node, asset.graph, lookup);
if (!def) continue;
@@ -435,7 +439,8 @@ export class GraphCanvas extends Widget {
const local = this.toLocal(e.global);
const inside = local.x >= 0 && local.x <= this.w && local.y >= 0 && local.y <= this.h;
const asset = dragged.kind === 'asset' ? findAsset(this.state.project, dragged.id) : undefined;
if (!inside || !this.assetId || asset?.type !== 'behavior') {
// Only a behavior graph runs other behaviors; a state machine has nothing to drop in.
if (!inside || this.asset()?.type !== 'behavior' || asset?.type !== 'behavior') {
this.setIncoming(null);
return;
}
@@ -631,10 +636,7 @@ export class GraphCanvas extends Widget {
this.state.select(nodeSelection(this.assetId, [add.node.id]));
}
private openLinks(
pick: (graph: BehaviorAsset['graph']) => BehaviorAsset['graph']['edges'],
at: { x: number; y: number },
): void {
private openLinks(pick: (graph: Graph) => Graph['edges'], at: { x: number; y: number }): void {
const graph = this.asset()?.graph;
if (graph) openLinkMenu(this.state, this.assetId, pick(graph), at.x, at.y);
}
@@ -652,7 +654,7 @@ export class GraphCanvas extends Widget {
const asset = this.asset();
this.canvas.visible = asset !== null;
if (!asset) {
this.hint.text = 'No behavior selected – pick one above, or add a behavior asset.';
this.hint.text = `No ${this.noun} selected – pick one above, or add a ${this.noun} asset.`;
return;
}
const playing = this.state.mode === 'play';
+4 -9
View File
@@ -1,29 +1,24 @@
import type { Asset, BehaviorAsset } from '../../core/model/Asset';
import { findAsset, findAssetOf } from '../../core/model/Project';
import { Checkbox, Label } from '../../ui';
import { AssetTabEditor } from '../AssetTabEditor';
import type { EditorState } from '../state';
import { Breadcrumb } from './Breadcrumb';
import { GraphCanvas } from './GraphCanvas';
import { SnapToggle } from './SnapToggle';
import { backTo, descend, follow, type Trail } from './trail';
/** Room kept for the "N nodes · M links" readout, wide enough for a three-digit graph. */
const INFO_WIDTH = 150;
export class GraphEditor extends AssetTabEditor<BehaviorAsset, GraphCanvas> {
private readonly snapBox = new Checkbox();
private readonly snap = new SnapToggle(() => this.canvas);
readonly breadcrumb = new Breadcrumb();
private trail: Trail = [];
constructor(state: EditorState) {
super(state, { noun: 'Behavior', infoWidth: INFO_WIDTH });
this.snapBox.onChange = (on) => this.canvas.setSnapping(on);
this.breadcrumb.onPick = (index) => this.open(this.trail[index]!, backTo(this.trail, index));
this.mount(
new GraphCanvas(state),
[new Label('Snap', { style: 'muted' }), this.snapBox],
this.breadcrumb,
);
this.mount(new GraphCanvas(state), this.snap.widgets, this.breadcrumb);
this.canvas.onOpenBehavior = (id) => this.open(id, descend(this.trail, this.currentAssetId, id));
// Play swaps in the runtime copy of the project, and back.
state.on('mode', () => this.refresh());
@@ -69,6 +64,6 @@ export class GraphEditor extends AssetTabEditor<BehaviorAsset, GraphCanvas> {
}
protected override syncExtras(asset: BehaviorAsset | null): void {
this.snapBox.setEnabled(Boolean(asset));
this.snap.setEnabled(Boolean(asset));
}
}
+1 -1
View File
@@ -2,7 +2,7 @@ import type { NodeCategory, NodeDef } from '../../core/graph';
import { ListView, Popup, ScrollContainer, TextField, Theme, ui } from '../../ui';
import type { PaletteEntry } from './paletteEntries';
const CATEGORY_ORDER: NodeCategory[] = ['event', 'flow', 'variable', 'data', 'action'];
const CATEGORY_ORDER: NodeCategory[] = ['event', 'flow', 'variable', 'data', 'action', 'state'];
/** Searchable list of node types; right-click menu of the graph editor. */
export class NodePalette extends Popup {
+2
View File
@@ -49,6 +49,8 @@ export function categoryColor(category: NodeCategory): number {
return c.categoryVariable;
case 'action':
return c.categoryAction;
case 'state':
return c.categoryState;
}
}
+17
View File
@@ -0,0 +1,17 @@
import { Checkbox, Label, type Widget } from '../../ui';
import type { GraphCanvas } from './GraphCanvas';
/** The "Snap" checkbox every tab on the graph canvas carries in its header. */
export class SnapToggle {
private readonly box = new Checkbox();
readonly widgets: readonly Widget[];
constructor(canvas: () => GraphCanvas) {
this.box.onChange = (on) => canvas().setSnapping(on);
this.widgets = [new Label('Snap', { style: 'muted' }), this.box];
}
setEnabled(on: boolean): void {
this.box.setEnabled(on);
}
}
+15 -7
View File
@@ -3,13 +3,16 @@ import {
BEHAVIOR_PARAM,
createEmptyGraph,
isTerminalType,
nextStateName,
type NodeDef,
resolveDef,
RUN_BEHAVIOR,
State,
STATE_NAME_PARAM,
terminalNode,
} from '../../core/graph';
import type { BehaviorAsset } from '../../core/model/Asset';
import { behaviorLookup } from '../../core/model/behaviorPrograms';
import type { GraphAsset } from '../../core/model/Asset';
import { graphLookup } from '../../core/model/graphLookup';
import type { PropertyBag } from '../../core/model/Properties';
import type { Project } from '../../core/model/Project';
@@ -25,17 +28,22 @@ export interface PaletteEntry {
}
/**
* The node types offerable in `asset`'s graph. Every other behavior appears under its own name
* instead of behind a generic "Run behavior"; the two terminals drop out once the graph has them.
* The node types offerable in `asset`'s graph. A state machine holds states and nothing else, each
* new one named by its number. In a behavior, every other behavior appears under its own name
* instead of behind a generic "Run behavior", and the two terminals drop out once the graph has them.
*/
export function paletteEntries(project: Project, asset: BehaviorAsset): PaletteEntry[] {
export function paletteEntries(project: Project, asset: GraphAsset): PaletteEntry[] {
if (asset.type === 'statemachine') {
const params = { [STATE_NAME_PARAM]: nextStateName(asset.graph) };
return [{ id: State.type, hint: State.category, def: State, params }];
}
const entries: PaletteEntry[] = [];
for (const def of allNodeDefs()) {
if (def.type === RUN_BEHAVIOR) continue;
if (def.type === RUN_BEHAVIOR || def.category === 'state') continue;
if (isTerminalType(def.type) && terminalNode(asset.graph, def.type)) continue;
entries.push({ id: def.type, hint: def.category, def, params: {} });
}
const lookup = behaviorLookup(project);
const lookup = graphLookup(project);
for (const other of project.assets) {
// A behavior running itself is an endless loop, so it is not on offer.
if (other.type !== 'behavior' || other.id === asset.id) continue;
+7
View File
@@ -231,6 +231,12 @@ const REFERENCES: Record<ReferenceKind, Reference> = {
})),
},
texture: { none: NO_TEXTURE_LABEL, label: textureRefLabel, choices: textureRefChoices },
statemachine: {
none: NO_ASSET_LABEL,
label: assetRefLabel,
choices: (project) =>
assetRefChoices(project, ['statemachine']).map((a) => ({ id: a.id, label: a.name })),
},
};
/** An id in the words of its reference kind; nothing for a kind that names nothing. */
@@ -355,6 +361,7 @@ export function createField(
}
case 'asset':
case 'texture':
case 'statemachine':
return referenceField(ctx, def, REFERENCES[def.kind], value, handlers);
}
}
+17 -11
View File
@@ -11,8 +11,9 @@ import {
portSignature,
resolveDef,
} from '../../core/graph';
import { behaviorLookup } from '../../core/model/behaviorPrograms';
import { findAssetOf, type Project } from '../../core/model/Project';
import type { GraphAsset } from '../../core/model/Asset';
import { graphLookup } from '../../core/model/graphLookup';
import { findGraphAsset, type Project } from '../../core/model/Project';
import { textOf } from '../../core/model/Properties';
import type { PropertyDef } from '../../core/properties/PropertySchema';
import { Label } from '../../ui';
@@ -24,11 +25,11 @@ import { currentNode, nodeParamValue } from './valueSpecs';
/** Structure-defining facts of a node selection: ports, connected inputs, declared variables. */
export function nodeSignature(project: Project, assetId: string, nodeId: string): string {
const asset = findAssetOf(project, assetId, 'behavior');
const asset = findGraphAsset(project, assetId);
if (!asset) return 'missing';
const node = asset.graph.nodes.find((n) => n.id === nodeId);
if (!node) return 'missing';
const lookup = behaviorLookup(project);
const lookup = graphLookup(project);
const def = resolveDef(node, asset.graph, lookup);
const connected = def
? inlineInputs(def)
@@ -38,23 +39,28 @@ export function nodeSignature(project: Project, assetId: string, nodeId: string)
const declared = (node.ports ?? []).map((p) => `${p.key}:${p.kind}${p.write ? ':set' : ''}`).join(',');
// They decide which rows the inspector builds, and two behaviors may share a name in the title.
const target = `${textOf(node.params[OBJECT_TYPE_PARAM] ?? '')}:${textOf(node.params[OBJECT_BEHAVIOR_PARAM] ?? '')}`;
return `${portSignature(node, asset.graph, lookup, assetId)}|${declared}|${connected.join(',')}|${asset.variables
return `${portSignature(node, asset.graph, lookup, assetId)}|${declared}|${connected.join(',')}|${variablesOf(
asset,
)
.map((v) => v.key)
.join(',')}|${target}`;
}
/** A state machine declares no variables; its one node type has none to name. */
const variablesOf = (asset: GraphAsset): PropertyDef[] => (asset.type === 'behavior' ? asset.variables : []);
/** Description, settings (params) and the inline values of unconnected data inputs. */
export function buildNodeSection(host: InspectorHost, assetId: string, nodeId: string): void {
const asset = findAssetOf(host.state.project, assetId, 'behavior');
const asset = findGraphAsset(host.state.project, assetId);
if (!asset) return;
const node = asset.graph.nodes.find((n) => n.id === nodeId);
const def = node && resolveDef(node, asset.graph, behaviorLookup(host.state.project));
const def = node && resolveDef(node, asset.graph, graphLookup(host.state.project));
if (!node || !def) return;
addTitle(host, `${def.category.toUpperCase()} NODE`);
host.body.add(new Label(def.label, { style: 'bodyBold' }));
addNote(host, def.description);
const problem = callProblem(node, behaviorLookup(host.state.project), assetId);
const problem = callProblem(node, graphLookup(host.state.project), assetId);
if (problem) addNote(host, problem, 'warning');
const addSetting = (param: PropertyDef) => {
const row = createFieldRow(
@@ -67,9 +73,9 @@ export function buildNodeSection(host: InspectorHost, assetId: string, nodeId: s
host.body.add(row.row);
};
const ownSettings = declaresPropertyPorts(node.type);
if (declaresVariablePorts(node.type)) buildVariablePortSection(host, assetId, node, asset.variables);
if (declaresVariablePorts(node.type)) buildVariablePortSection(host, assetId, node, variablesOf(asset));
else if (ownSettings) buildPropertyPortSection(host, assetId, node, addSetting);
else if (def.declaresPorts) buildPortSection(host, assetId, node, asset.variables);
else if (def.declaresPorts) buildPortSection(host, assetId, node, variablesOf(asset));
if (!ownSettings && def.params.length > 0) {
addTitle(host, 'SETTINGS');
@@ -94,7 +100,7 @@ export function buildNodeSection(host: InspectorHost, assetId: string, nodeId: s
/** Pushes the node's current params into the rows. False when the node is gone (rebuild). */
export function refreshNodeSection(host: InspectorHost, assetId: string, nodeId: string): boolean {
const found = currentNode(host.state.project, assetId, nodeId);
const def = found && resolveDef(found.node, found.graph, behaviorLookup(host.state.project));
const def = found && resolveDef(found.node, found.graph, graphLookup(host.state.project));
if (!found || !def) return false;
for (const [key, row] of host.fields) {
const [scope, name] = key.split(':') as ['param' | 'input', string];
+2 -2
View File
@@ -4,7 +4,7 @@ import { SetOverrideCommand } from '../../core/commands/sceneObjectCommands';
import { findNode, type Graph, type GraphNode } from '../../core/graph/Graph';
import type { Asset } from '../../core/model/Asset';
import type { ObjectRef } from '../../core/model/instance';
import { findAsset, findAssetOf, type Project } from '../../core/model/Project';
import { findAsset, findGraphAsset, type Project } from '../../core/model/Project';
import type { EditorState } from '../state';
import { currentProps, currentRef } from './objectQueries';
import type { PreviewedValue } from './previewHandlers';
@@ -57,7 +57,7 @@ export function currentNode(
assetId: string,
nodeId: string,
): { node: GraphNode; graph: Graph } | undefined {
const asset = findAssetOf(project, assetId, 'behavior');
const asset = findGraphAsset(project, assetId);
if (!asset) return undefined;
const node = findNode(asset.graph, nodeId);
return node && { node, graph: asset.graph };
+2 -2
View File
@@ -6,7 +6,7 @@ import { edgesInto, type Graph, type GraphNode } from '../../core/graph/Graph';
import { resolveDef } from '../../core/graph/nested';
import { inlineInputDef, inlineInputs, type NodeDef } from '../../core/graph/NodeRegistry';
import type { Asset } from '../../core/model/Asset';
import { behaviorLookup } from '../../core/model/behaviorPrograms';
import { graphLookup } from '../../core/model/graphLookup';
import type { ObjectRef } from '../../core/model/instance';
import { isList, type ListValue, type PropertyValue, type StructValue } from '../../core/model/Properties';
import { findAsset } from '../../core/model/Project';
@@ -181,7 +181,7 @@ function objectOwner(
function nodeOwner(state: EditorState, slot: Extract<ListSlot, { kind: 'node' }>): Owner<GraphNode> | null {
const found = currentNode(state.project, slot.assetId, slot.nodeId);
if (!found) return null;
const nodeDef = resolveDef(found.node, found.graph, behaviorLookup(state.project));
const nodeDef = resolveDef(found.node, found.graph, graphLookup(state.project));
const def =
nodeDef && (nodeDef.params.find((p) => p.key === slot.key) ?? inlineListDef(nodeDef, found, slot.key));
if (!nodeDef || !def) return null;
+15 -5
View File
@@ -7,6 +7,7 @@ import {
createEmptyProject,
findAsset,
findAssetOf,
findGraphAsset,
findObjectHolder,
findScene,
type Project,
@@ -313,8 +314,8 @@ export class EditorState {
if (alive.length !== s.objectIds.length) this.select(objectSelection(s.holderId, alive, s.objectId));
}
if (s.kind === 'node') {
const asset = findAssetOf(this.project, s.assetId, 'behavior');
// Fall back to the behavior asset so the graph stays open when its node vanished (undo).
const asset = findGraphAsset(this.project, s.assetId);
// Fall back to the asset so the graph stays open when its node vanished (undo).
if (!asset) this.select(null);
else {
const alive = s.nodeIds.filter((id) => asset.graph.nodes.some((n) => n.id === id));
@@ -346,12 +347,21 @@ export class EditorState {
/** The behavior asset the current selection refers to (asset, placed object or node), if any. */
get selectedBehaviorId(): string | null {
return this.selectedGraphId('behavior');
}
/** The state machine the current selection refers to: the asset, or one of its states. */
get selectedStateMachineId(): string | null {
return this.selectedGraphId('statemachine');
}
private selectedGraphId(type: 'behavior' | 'statemachine'): string | null {
const s = this.selection;
if (!s) return null;
if (s.kind === 'node') return s.assetId;
if (s.kind === 'frame') return null;
const asset = this.assetBehind(s);
return asset && asset.type === 'behavior' ? asset.id : null;
// A node names its asset; which tab that is depends on what the asset is.
const asset = s.kind === 'node' ? findAsset(this.project, s.assetId) : this.assetBehind(s);
return asset && asset.type === type ? asset.id : null;
}
/**
@@ -0,0 +1,42 @@
import { statesOf } from '../../core/graph';
import type { Asset, StateMachineAsset } from '../../core/model/Asset';
import { AssetTabEditor } from '../AssetTabEditor';
import { GraphCanvas } from '../graph/GraphCanvas';
import { SnapToggle } from '../graph/SnapToggle';
import type { EditorState } from '../state';
/** Room kept for the "N states" readout. */
const INFO_WIDTH = 90;
/**
* The states of one state machine, on the graph canvas the Behavior tab uses: a state is a node,
* so placing (right-click), moving, snapping, renaming, deleting and undo are the graph's.
* Transitions are a later step.
*/
export class StateMachineEditor extends AssetTabEditor<StateMachineAsset, GraphCanvas> {
private readonly snap = new SnapToggle(() => this.canvas);
constructor(state: EditorState) {
super(state, { noun: 'State machine', infoWidth: INFO_WIDTH });
this.mount(new GraphCanvas(state, 'state machine'), this.snap.widgets);
// Play swaps in the runtime copy of the project, and back.
state.on('mode', () => this.refresh());
}
protected override selectedId(): string {
return this.state.selectedStateMachineId ?? '';
}
protected override isMine(asset: Asset): asset is StateMachineAsset {
return asset.type === 'statemachine';
}
protected override infoText(asset: StateMachineAsset): string {
const count = statesOf(asset.graph).length;
return `${count} ${count === 1 ? 'state' : 'states'}`;
}
protected override syncExtras(asset: StateMachineAsset | null): void {
this.snap.setEnabled(Boolean(asset));
}
}