Replace the property nodes with one Properties node

Get/Set property, Get/Set properties, Set enabled and Set text are gone.
A single Properties node takes a fixed "object" input; every chosen
property is an output that reads the current value, and one switched to
Set is also an input written when the flow arrives. Exec pins only exist
while at least one entry writes.

The node carries a type (Sprite, Text, Collider, Camera, Container,
Behavior, Any) that decides what "+ Property" offers: the fields of that
type, the variables of the chosen behavior, or for Any a kind to pick
and a name to type. Each port takes the default and field of its type,
so a Camera width starts at 640. Switching the type keeps the ports and
marks those the new type lacks. At runtime the type is only an editor
aid; the node writes to whatever object it gets.

Old project files are converted on load. The type is inferred from the
keys: the first object type that has them all, else the one behavior
that declares them all, else Any. enabled belongs to every object, so a
converted Set enabled lands on Any.

The jump-run and tetris seeders use Properties throughout; draw-piece
switches its cell on in the same node that sets the colour.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
rootandClaude Opus 5 committed 2026-09-11 18:40:47 +02:00
1 parent 7c63c884ef
commit 58f19a3451
36 files changed
+1040 -719

No files matched your search

+21 -4
View File
@@ -1,6 +1,7 @@
import {
BEHAVIOR_PARAM,
BEHAVIOR_START,
declaresPropertyPorts,
declaresVariablePorts,
type DeclaredPort,
findNode,
@@ -10,6 +11,8 @@ import {
type GraphNode,
isTerminalNode,
isValidPortName,
OBJECT_BEHAVIOR_PARAM,
propertyTargetOf,
RUN_BEHAVIOR,
} from '../graph';
import type { PropertyValue } from '../model/Properties';
@@ -292,7 +295,7 @@ export class RenamePortCommand implements Command {
/** Renames one declared port on one node, taking its edges and its typed-in value along. */
function renamePortOn(graph: Graph, node: GraphNode, from: string, to: string): void {
const ports = node.ports ?? [];
if (from === to || !ports.some((p) => p.key === from)) return;
if (from === to || !ports.some((p) => p.key === from) || ports.some((p) => p.key === to)) return;
node.ports = ports.map((p) => (p.key === from ? { ...p, key: to } : p));
for (const site of ownSites(graph, node)) carryPort(site, from, to);
}
@@ -339,11 +342,25 @@ export class RepointPortCommand implements Command {
}
/**
* Follows a renamed variable into the nodes that name it as a port. Their edges and typed-in
* Follows a renamed variable into the nodes that name it as a port: the Variables nodes of its own
* behavior, and Properties nodes anywhere that point at that behavior. Their edges and typed-in
* values move with it – the port key *is* the variable name there.
*/
export function renameVariablePorts(graph: Graph, from: string, to: string): void {
for (const node of graph.nodes) if (declaresVariablePorts(node.type)) renamePortOn(graph, node, from, to);
export function renameVariablePorts(project: Project, behaviorId: string, from: string, to: string): void {
for (const asset of project.assets) {
if (asset.type !== 'behavior') continue;
for (const node of asset.graph.nodes)
if (namesVariablesOf(node, asset.id, behaviorId)) renamePortOn(asset.graph, node, from, to);
}
}
function namesVariablesOf(node: GraphNode, graphOwner: string, behaviorId: string): boolean {
if (declaresVariablePorts(node.type)) return graphOwner === behaviorId;
return (
declaresPropertyPorts(node.type) &&
propertyTargetOf(node.params) === 'behavior' &&
node.params[OBJECT_BEHAVIOR_PARAM] === behaviorId
);
}
/** "in1", "in2", … – the first port name the terminal node does not use yet. */
+1 -1
View File
@@ -138,7 +138,7 @@ export class RenameVariableCommand implements Command {
bag[to] = bag[from]!;
delete bag[from];
}
renameVariablePorts(asset.graph, from, to);
renameVariablePorts(project, this.assetId, from, to);
}
}
+20 -8
View File
@@ -2,7 +2,14 @@ import { edgesInto, edgesOutOf, type Graph, type GraphNode } from './Graph';
import { type BehaviorLookup, NO_BEHAVIORS } from './lookup';
import { BEHAVIOR_END, BEHAVIOR_START, resolveDef, terminalNode } from './nested';
import type { NodeContext } from './NodeContext';
import { type CallResult, hasExecInput, inlineValue, isEventNode, type RepeatResult } from './NodeRegistry';
import {
type CallResult,
hasExecInput,
inlineValue,
isEventNode,
type PortDef,
type RepeatResult,
} from './NodeRegistry';
import type { Value } from './values';
/** How much work one pulse may do. A Repeat over a 10×20 board is 200 rounds, so this is generous. */
@@ -150,15 +157,16 @@ export class GraphInterpreter {
/** Resolves every data input: connected → pulled from the source, else the inline param. */
private collectInputs(node: GraphNode, ctx: NodeContext): Record<string, Value> {
const inputs: Record<string, Value> = {};
for (const port of this.def(node)?.inputs ?? []) {
if (port.type === 'exec') continue;
const edge = edgesInto(this.frame.graph, node.id, port.key)[0];
if (edge) inputs[port.key] = this.readOutput(edge.from.node, edge.from.port, ctx);
else inputs[port.key] = inlineValue(node, port);
}
for (const port of this.def(node)?.inputs ?? [])
if (port.type !== 'exec') inputs[port.key] = this.inputValue(node, port, ctx);
return inputs;
}
private inputValue(node: GraphNode, port: PortDef, ctx: NodeContext): Value {
const edge = edgesInto(this.frame.graph, node.id, port.key)[0];
return edge ? this.readOutput(edge.from.node, edge.from.port, ctx) : inlineValue(node, port);
}
/** Value of one output port: from the pulse cache, or by evaluating a pure data node. */
private readOutput(nodeId: string, port: string, ctx: NodeContext): Value {
const cached = this.frame.outputCache.get(nodeId) ?? this.frame.dataCache.get(nodeId);
@@ -169,7 +177,11 @@ export class GraphInterpreter {
if (!def) return null;
if (def.read) {
this.trace?.onNode(nodeId);
return def.read(ctx, source.params)[port] ?? null;
const input = (key: string): Value => {
const found = def.inputs.find((p) => p.key === key);
return found ? this.inputValue(source, found, ctx) : null;
};
return def.read(ctx, source.params, input)[port] ?? null;
}
// Exec nodes that have not run in this pulse have no value yet.
if (isEventNode(def) || hasExecInput(def) || !def.run) return null;
+4 -3
View File
@@ -80,7 +80,7 @@ export interface NodeDef {
*/
declaresPorts?: 'inputs' | 'outputs' | 'both';
/** How a declared port becomes a port; without it, named after its key and typed by its kind. */
declaredPort?(port: DeclaredPort): PortDef;
declaredPort?(port: DeclaredPort, node: GraphNode): PortDef;
/**
* Ports this node computes beyond the fixed and the declared ones – how many outputs a Sequence
* offers, which values the behavior a call node names takes. `resolveDef` applies it.
@@ -88,9 +88,10 @@ export interface NodeDef {
derivePorts?(source: PortSource): DerivedShape;
/**
* Outputs readable at any moment, even while the node's exec input has not fired in this pulse.
* Never cached, so a read after a write sees the new value.
* Never cached, so a read after a write sees the new value. `input` pulls one input on demand:
* pulling all of them would loop through an edge that feeds the node's own output back in.
*/
read?(ctx: NodeContext, params: PropertyBag): Record<string, Value>;
read?(ctx: NodeContext, params: PropertyBag, input: (key: string) => Value): Record<string, Value>;
/**
* Event nodes have no `run` – the interpreter seeds their outputs. `def` is resolved for the node at
* hand, the only way a node with derived ports knows how many it has.
+15 -13
View File
@@ -8,8 +8,7 @@ export const BEHAVIOR_START = 'BehaviorStart';
export const BEHAVIOR_END = 'BehaviorEnd';
export const RUN_BEHAVIOR = 'RunBehavior';
export const VARIABLES = 'Variables';
export const GET_PROPERTIES = 'GetProperties';
export const SET_PROPERTIES = 'SetProperties';
export const PROPERTIES = 'Properties';
export const BEHAVIOR_PARAM = 'behavior';
@@ -24,7 +23,7 @@ export function declaresVariablePorts(type: string): boolean {
/** Nodes whose declared ports are properties of the object they are handed. */
export function declaresPropertyPorts(type: string): boolean {
return type === GET_PROPERTIES || type === SET_PROPERTIES;
return type === PROPERTIES;
}
/** Identifier-like, and not `exec`: that key belongs to the fixed flow port of every terminal node. */
@@ -32,12 +31,15 @@ export function isValidPortName(name: string): boolean {
return isValidFieldName(name) && name !== 'exec';
}
/** Keys a declared port cannot take: the node's fixed ports on the side it declares (`object`). */
/**
* Keys a declared port cannot take: the node's fixed ports on the side it declares (`object`), and
* its settings, which share the params bag with the typed-in values of its inputs.
*/
export function fixedPortKeys(def: NodeDef): string[] {
const side = def.declaresPorts;
const fixed =
side === 'inputs' ? def.inputs : side === 'outputs' ? def.outputs : [...def.inputs, ...def.outputs];
return fixed.map((p) => p.key);
return [...fixed.map((p) => p.key), ...def.params.map((p) => p.key)];
}
export function declaredOn(
@@ -81,16 +83,16 @@ export function resolveDef(node: GraphNode, graph: Graph, lookup: BehaviorLookup
if (!def || (!def.declaresPorts && !def.derivePorts)) return def;
const own = (side: 'inputs' | 'outputs') =>
declaredOn(def, node.ports ?? [], side).map((p) =>
def.declaredPort ? def.declaredPort(p) : portDefOf(p),
def.declaredPort ? def.declaredPort(p, node) : portDefOf(p),
);
const grown = def.derivePorts?.({ node, graph, behaviors: lookup }) ?? {};
// Derived before declared: a derived exec pin belongs at the top.
return {
...def,
label: grown.label ?? def.label,
inputs: [...def.inputs, ...(grown.inputs ?? []), ...own('inputs')],
outputs: [...def.outputs, ...(grown.outputs ?? []), ...own('outputs')],
};
const side = (key: 'inputs' | 'outputs') => execFirst([...def[key], ...(grown[key] ?? []), ...own(key)]);
return { ...def, label: grown.label ?? def.label, inputs: side('inputs'), outputs: side('outputs') };
}
/** A derived exec pin belongs at the top, above the fixed data ports too. */
function execFirst(ports: PortDef[]): PortDef[] {
return [...ports.filter((p) => p.type === 'exec'), ...ports.filter((p) => p.type !== 'exec')];
}
/**
-20
View File
@@ -1,20 +0,0 @@
import type { NodeDef } from '../../NodeRegistry';
import { asBoolean, asEntity } from '../../values';
import { bool, exec, obj, withDefault } from '../shared';
export const SetEnabled: NodeDef = {
type: 'SetEnabled',
label: 'Set enabled',
category: 'action',
description:
'Switches an object on or off. A disabled object is not drawn, does not collide and its behavior stops – ' +
'and so does everything parented below it. This is how screens (title, win, lose) are shown and hidden.',
inputs: [exec(), obj('object'), withDefault(bool('enabled'), true)],
outputs: [exec()],
params: [],
run: (_ctx, inputs) => {
const target = asEntity(inputs.object);
if (target) target.props.enabled = asBoolean(inputs.enabled);
return { next: 'exec' };
},
};
@@ -1,28 +0,0 @@
import { SET_PROPERTIES } from '../../nested';
import type { NodeDef } from '../../NodeRegistry';
import { propertyPort } from '../../propertyPorts';
import { asEntity, writeTyped } from '../../values';
import { exec, obj } from '../shared';
/**
* The plural of Set property: one input per property picked. Like Set variables it writes every
* property it lists each time it runs – an unconnected input writes the value typed on the node.
*/
export const SetProperties: NodeDef = {
type: SET_PROPERTIES,
label: 'Set properties',
category: 'action',
description: 'Writes several properties (width, color, …) of an object at once, one input per property.',
inputs: [exec(), obj('object')],
outputs: [exec()],
params: [],
declaresPorts: 'inputs',
declaredPort: propertyPort,
run: (_ctx, inputs, _params, def) => {
const target = asEntity(inputs.object);
if (target)
for (const port of def.inputs.slice(SetProperties.inputs.length))
writeTyped(target.props, port.key, inputs[port.key]);
return { next: 'exec' };
},
};
@@ -1,20 +0,0 @@
import { textOf } from '../../../model/Properties';
import type { NodeDef } from '../../NodeRegistry';
import { asEntity, writeTyped } from '../../values';
import { any, exec, obj, PROPERTY_PARAM } from '../shared';
export const SetProperty: NodeDef = {
type: 'SetProperty',
label: 'Set property',
category: 'action',
description: 'Writes a property (width, color, …) of an object.',
inputs: [exec(), obj('object'), any('value')],
outputs: [exec()],
params: [PROPERTY_PARAM],
run: (_ctx, inputs, params) => {
const target = asEntity(inputs.object);
const key = textOf(params.property ?? '');
if (target && key) writeTyped(target.props, key, inputs.value);
return { next: 'exec' };
},
};
-18
View File
@@ -1,18 +0,0 @@
import type { NodeDef } from '../../NodeRegistry';
import { asEntity, asString } from '../../values';
import { any, exec, obj } from '../shared';
export const SetText: NodeDef = {
type: 'SetText',
label: 'Set text',
category: 'action',
description: 'Writes the content of a text object (same as Set property "text").',
inputs: [exec(), obj('object'), any('text')],
outputs: [exec()],
params: [],
run: (_ctx, inputs) => {
const target = asEntity(inputs.object);
if (target) target.props.text = asString(inputs.text);
return { next: 'exec' };
},
};
@@ -1,24 +0,0 @@
import { GET_PROPERTIES } from '../../nested';
import type { NodeDef } from '../../NodeRegistry';
import { propertyPort } from '../../propertyPorts';
import { asEntity, type Value } from '../../values';
import { obj } from '../shared';
/** The plural of Get property: one output per property picked, the way Get variables reads. */
export const GetProperties: NodeDef = {
type: GET_PROPERTIES,
label: 'Get properties',
category: 'data',
description: 'Reads several properties (width, color, …) of an object at once, one output per property.',
inputs: [obj('object')],
outputs: [],
params: [],
declaresPorts: 'outputs',
declaredPort: propertyPort,
run: (_ctx, inputs, _params, def) => {
const target = asEntity(inputs.object);
const outputs: Record<string, Value> = {};
for (const port of def.outputs) outputs[port.key] = target?.props[port.key] ?? null;
return { outputs };
},
};
-17
View File
@@ -1,17 +0,0 @@
import { textOf } from '../../../model/Properties';
import type { NodeDef } from '../../NodeRegistry';
import { asEntity } from '../../values';
import { any, obj, PROPERTY_PARAM } from '../shared';
export const GetProperty: NodeDef = {
type: 'GetProperty',
label: 'Get property',
category: 'data',
description: 'Reads a property (width, color, …) of an object.',
inputs: [obj('object')],
outputs: [any('value')],
params: [PROPERTY_PARAM],
run: (_ctx, inputs, params) => ({
outputs: { value: asEntity(inputs.object)?.props[textOf(params.property ?? '')] ?? null },
}),
};
+38
View File
@@ -0,0 +1,38 @@
import { PROPERTIES } from '../../nested';
import type { NodeDef } from '../../NodeRegistry';
import {
OBJECT_BEHAVIOR_SETTING,
OBJECT_TYPE_SETTING,
propertiesTitle,
propertyPort,
} from '../../propertyPorts';
import { asEntity, writeTyped } from '../../values';
import { exec, obj } from '../shared';
export const Properties: NodeDef = {
type: PROPERTIES,
label: 'Properties',
category: 'data',
description:
'Reads properties (width, color, a variable, …) of the object it is handed, at any time. Those ' +
'switched to Set are written together when the flow arrives.',
inputs: [obj('object')],
outputs: [],
params: [OBJECT_TYPE_SETTING, OBJECT_BEHAVIOR_SETTING],
// The title names both ("Sprite properties", "Game properties").
hiddenParams: () => [OBJECT_TYPE_SETTING.key, OBJECT_BEHAVIOR_SETTING.key],
declaresPorts: 'both',
declaredPort: (port, node) => propertyPort(port, node.params),
derivePorts: ({ node, behaviors }) => {
const label = propertiesTitle(node, behaviors);
return (node.ports ?? []).some((p) => p.write) ? { label, inputs: [exec()], outputs: [exec()] } : { label };
},
read: (_ctx, _params, input) => asEntity(input('object'))?.props ?? {},
run: (_ctx, inputs, _params, def) => {
const target = asEntity(inputs.object);
if (target)
for (const port of def.inputs)
if (port.type !== 'exec' && port.key !== 'object') writeTyped(target.props, port.key, inputs[port.key]);
return { next: 'exec' };
},
};
+2 -12
View File
@@ -3,11 +3,7 @@ import { Destroy } from './action/Destroy';
import { Log } from './action/Log';
import { Move } from './action/Move';
import { RestartGame } from './action/RestartGame';
import { SetEnabled } from './action/SetEnabled';
import { SetPosition } from './action/SetPosition';
import { SetProperties } from './action/SetProperties';
import { SetProperty } from './action/SetProperty';
import { SetText } from './action/SetText';
import { Spawn } from './action/Spawn';
import { StopGame } from './action/StopGame';
import { Abs } from './data/Abs';
@@ -24,8 +20,6 @@ import { Equals } from './data/Equals';
import { FindText } from './data/FindText';
import { Floor } from './data/Floor';
import { GetPosition } from './data/GetPosition';
import { GetProperties } from './data/GetProperties';
import { GetProperty } from './data/GetProperty';
import { IsAsset } from './data/IsAsset';
import { IsEnabled } from './data/IsEnabled';
import { IsHovered } from './data/IsHovered';
@@ -47,6 +41,7 @@ import { ObjectByName } from './data/ObjectByName';
import { Or } from './data/Or';
import { Owner } from './data/Owner';
import { PackStruct } from './data/PackStruct';
import { Properties } from './data/Properties';
import { Parent } from './data/Parent';
import { Random } from './data/Random';
import { Round } from './data/Round';
@@ -118,8 +113,7 @@ export const BUILT_IN_NODES: readonly NodeDef[] = [
NameOf,
IsAsset,
IsEnabled,
GetProperty,
GetProperties,
Properties,
GetPosition,
// data: literals and math
NumberLiteral,
@@ -176,10 +170,6 @@ export const BUILT_IN_NODES: readonly NodeDef[] = [
// actions
Move,
SetPosition,
SetProperty,
SetProperties,
SetEnabled,
SetText,
Spawn,
Destroy,
Log,
+1 -10
View File
@@ -1,17 +1,8 @@
import type { PropertyValue } from '../../model/Properties';
import { OBJECT_PROPERTY_SUGGESTIONS, type PropertyDef } from '../../properties/PropertySchema';
import type { PropertyDef } from '../../properties/PropertySchema';
import type { NodeDef, PortDef } from '../NodeRegistry';
import { asBoolean, asNumber } from '../values';
/** The property a Get/Set property node names: typed freely, or picked from the built-in ones. */
export const PROPERTY_PARAM: PropertyDef = {
key: 'property',
label: 'Property',
kind: 'text',
default: 'width',
suggestions: OBJECT_PROPERTY_SUGGESTIONS,
};
export const exec = (key = 'exec', label = ''): PortDef => ({ key, label, type: 'exec' });
export const num = (key: string, label = key): PortDef => ({ key, label, type: 'number' });
export const bool = (key: string, label = key): PortDef => ({ key, label, type: 'boolean' });
+61 -13
View File
@@ -1,24 +1,72 @@
import { OBJECT_PROPERTIES, type PropertyDef } from '../properties/PropertySchema';
import type { DeclaredPort } from './Graph';
import { ASSET_TYPE_LABELS } from '../model/AssetTypes';
import { type PropertyBag, textOf } from '../model/Properties';
import { type PropertyDef, type PropertySchema, schemaFor } from '../properties/PropertySchema';
import type { DeclaredPort, GraphNode } from './Graph';
import type { BehaviorLookup } from './lookup';
import { portDefOf } from './nested';
import { type PortDef, withInlineDefault } from './NodeRegistry';
import { portKindOf } from './variablePorts';
export function objectPropertyDef(key: string): PropertyDef | undefined {
return OBJECT_PROPERTIES.find((def) => def.key === key);
}
export function propertyPortOf(def: PropertyDef): DeclaredPort {
return { key: def.key, kind: portKindOf(def) };
}
/** Keys no behavior variable is likely to have: a port cannot take a setting's key (`fixedPortKeys`). */
export const OBJECT_TYPE_PARAM = 'objectType';
export const OBJECT_BEHAVIOR_PARAM = 'objectBehavior';
/**
* A port naming a built-in property carries its def: a typed-in value starts at its default and is
* edited with its field. A custom name, or a kind the property does not travel as, stays plain.
* What a Properties node offers ports from. Textures and scenes are not objects in a running game,
* so there is nothing to hand the node for them.
*/
export function propertyPort(port: DeclaredPort): PortDef {
export const PROPERTY_TARGETS = [
'any',
'sprite',
'text',
'collider',
'camera',
'container',
'behavior',
] as const;
export type PropertyTarget = (typeof PROPERTY_TARGETS)[number];
export function targetLabel(target: PropertyTarget): string {
return target === 'any' ? 'Any' : ASSET_TYPE_LABELS[target];
}
export const OBJECT_TYPE_SETTING: PropertyDef = {
key: OBJECT_TYPE_PARAM,
label: 'Type',
kind: 'enum',
default: 'any',
options: PROPERTY_TARGETS.map((value) => ({ value, label: targetLabel(value) })),
};
export const OBJECT_BEHAVIOR_SETTING: PropertyDef = {
key: OBJECT_BEHAVIOR_PARAM,
label: 'Behavior',
kind: 'asset',
default: '',
assetTypes: ['behavior'],
};
export function propertyTargetOf(params: PropertyBag): PropertyTarget {
const value = textOf(params[OBJECT_TYPE_PARAM] ?? '');
return (PROPERTY_TARGETS as readonly string[]).includes(value) ? (value as PropertyTarget) : 'any';
}
/** A behavior's own variables come on top of these, from its asset. */
export function targetProperties(target: PropertyTarget): PropertySchema {
return target === 'any' ? [] : schemaFor(target);
}
/** Carries the def its type has under that key (default, field); under Any or at another kind, none. */
export function propertyPort(port: DeclaredPort, params: PropertyBag): PortDef {
const plain = withInlineDefault(portDefOf(port));
const field = objectPropertyDef(port.key);
const field = targetProperties(propertyTargetOf(params)).find((def) => def.key === port.key);
if (!field || portKindOf(field) !== port.kind) return plain;
return { ...plain, field, default: field.default };
}
export function propertiesTitle(node: GraphNode, behaviors: BehaviorLookup): string {
const target = propertyTargetOf(node.params);
if (target === 'any') return 'Properties';
const behavior = target === 'behavior' ? behaviors(textOf(node.params[OBJECT_BEHAVIOR_PARAM] ?? '')) : null;
return `${behavior?.name ?? targetLabel(target)} properties`;
}
+2 -34
View File
@@ -1,5 +1,5 @@
import type { Asset } from '../model/Asset';
import { ASSET_TYPE_LABELS, type AssetType, isPlaceableType } from '../model/AssetTypes';
import { type AssetType, isPlaceableType } from '../model/AssetTypes';
import {
type FieldValue,
isList,
@@ -13,12 +13,6 @@ import {
colorOf,
} from '../model/Properties';
/** A value a text field offers to fill in; the text stays free to type. */
export interface TextSuggestion {
value: string;
label: string;
}
/** The inspector is generated from these entries, so a new property is one line in a schema below. */
export type PropertyDef =
/**
@@ -36,7 +30,7 @@ export type PropertyDef =
step?: number;
decimals?: number;
}
| { key: string; label: string; kind: 'text'; default: string; suggestions?: readonly TextSuggestion[] }
| { key: string; label: string; kind: 'text'; default: string }
| { key: string; label: string; kind: 'color'; default: number }
| { key: string; label: string; kind: 'boolean'; default: boolean }
| { key: string; label: string; kind: 'enum'; default: string; options: { value: string; label: string }[] }
@@ -203,32 +197,6 @@ const FULL_SCHEMAS: Record<AssetType, PropertySchema> = Object.fromEntries(
]),
) as Record<AssetType, PropertySchema>;
const OBJECT_TYPES = ['sprite', 'text', 'collider', 'camera'] as const;
/** A built-in property with the type it belongs to ("Sprite width"); a shared key appears once per type. */
export const OBJECT_PROPERTY_CHOICES: readonly { label: string; def: PropertyDef }[] = [
...COMMON_PROPS.map((def) => ({ label: `Object ${def.key}`, def })),
...OBJECT_TYPES.flatMap((type) =>
ASSET_SCHEMAS[type].map((def) => ({ label: `${ASSET_TYPE_LABELS[type]} ${def.key}`, def })),
),
];
/**
* Every built-in property once per key – what a Get/Set properties port resolves to. Sprite comes
* first so a shared key (`width`) keeps its def, not the camera's whole-pixel view width.
*/
export const OBJECT_PROPERTIES: PropertySchema = firstPerKey(OBJECT_PROPERTY_CHOICES.map((c) => c.def));
export const OBJECT_PROPERTY_SUGGESTIONS: readonly TextSuggestion[] = OBJECT_PROPERTY_CHOICES.map((c) => ({
value: c.def.key,
label: c.label,
}));
function firstPerKey(defs: readonly PropertyDef[]): PropertyDef[] {
const seen = new Set<string>();
return defs.filter((def) => !seen.has(def.key) && seen.add(def.key));
}
export function schemaFor(type: AssetType): PropertySchema {
return FULL_SCHEMAS[type];
}
+167
View File
@@ -0,0 +1,167 @@
import { PROPERTIES, VARIABLES } from '../graph/nested';
import { OBJECT_BEHAVIOR_PARAM, OBJECT_TYPE_PARAM, targetProperties } from '../graph/propertyPorts';
import { portKindOf } from '../graph/variablePorts';
import type { PropertyBag } from '../model/Properties';
import { COMMON_PROPS, type PropertyDef, type PropertySchema } from '../properties/PropertySchema';
/** The nodes `Variables` replaced, and whether they wrote. */
const SINGLE: Record<string, boolean> = { GetVariable: false, SetVariable: true, Variable: true };
const PLURAL: Record<string, boolean> = { GetVariables: false, SetVariables: true };
type Raw = Record<string, unknown>;
const record = (value: unknown): Raw =>
value && typeof value === 'object' && !Array.isArray(value) ? (value as Raw) : {};
/**
* Rewrites the variable nodes of an older file into `Variables`, on the raw graph before it is
* normalized. A single node's `value` port is renamed to the variable, which is the key there; one
* without a variable has no pins left and loses its edges, flow included.
*/
export function upgradeVariableNodes(raw: unknown, variables: readonly PropertyDef[]): unknown {
const graph = record(raw);
if (!Array.isArray(graph.nodes)) return raw;
const renamed = new Map<string, string>();
const nodes = (graph.nodes as unknown[]).map((item) => {
const node = record(item);
const type = String(node.type);
if (type in PLURAL) {
const write = PLURAL[type];
const ports = Array.isArray(node.ports)
? (node.ports as unknown[]).map((p) => (write ? { ...record(p), write } : p))
: [];
return { ...node, type: VARIABLES, ports };
}
if (!(type in SINGLE)) return item;
const write = SINGLE[type];
const { variable, value, ...params } = record(node.params);
const key = typeof variable === 'string' ? variable : '';
renamed.set(String(node.id), key);
if (!key) return { ...node, type: VARIABLES, params, ports: [] };
const declared = variables.find((v) => v.key === key);
const kind = declared ? portKindOf(declared) : 'text';
if (write && value !== undefined) params[key] = value;
return { ...node, type: VARIABLES, params, ports: [write ? { key, kind, write } : { key, kind }] };
});
const edges = (Array.isArray(graph.edges) ? graph.edges : []).flatMap((item) => {
const edge = record(item);
const end = (side: unknown) => {
const at = record(side);
const key = renamed.get(String(at.node));
if (key === '') return null;
return key !== undefined && at.port === 'value' ? { ...at, port: key } : at;
};
const from = end(edge.from);
const to = end(edge.to);
return from && to ? [{ ...edge, from, to }] : [];
});
return { ...graph, nodes, edges };
}
const SINGLE_PROPERTY: Record<string, boolean> = { GetProperty: false, SetProperty: true };
const PLURAL_PROPERTY: Record<string, boolean> = { GetProperties: false, SetProperties: true };
const FIXED_TARGETS = ['sprite', 'text', 'collider', 'camera', 'container'] as const;
interface Pinned {
params: PropertyBag;
defs: PropertySchema;
}
/**
* The type an old node's ports fit: the first object type holding every key, else the one behavior
* declaring them all as variables, else Any.
*/
export function pinPropertyTarget(
keys: readonly string[],
behaviors: ReadonlyMap<string, readonly PropertyDef[]>,
): Pinned {
const holds = (defs: PropertySchema) => keys.every((key) => defs.some((d) => d.key === key));
if (keys.length === 0) return { params: {}, defs: [] };
// Every object has these, so they say nothing about which type the node was meant for.
if (holds(COMMON_PROPS)) return { params: {}, defs: COMMON_PROPS };
for (const target of FIXED_TARGETS) {
const defs = targetProperties(target);
if (holds(defs)) return { params: { [OBJECT_TYPE_PARAM]: target }, defs };
}
const owners = [...behaviors].filter(([, defs]) => holds(defs));
const [owner] = owners;
if (owners.length !== 1 || !owner) return { params: {}, defs: [] };
return { params: { [OBJECT_TYPE_PARAM]: 'behavior', [OBJECT_BEHAVIOR_PARAM]: owner[0] }, defs: owner[1] };
}
/**
* Nodes that were a `Set property` of one key, with what their unconnected input wrote. It has to
* be spelled out: the new port would write the type's default instead (a text object's is "Text").
*/
const SETTERS: Record<string, { key: string; unset: boolean | string }> = {
SetEnabled: { key: 'enabled', unset: true },
SetText: { key: 'text', unset: '' },
};
function fromSetter(node: Raw): Raw {
const setter = SETTERS[String(node.type)];
if (!setter) return node;
const { [setter.key]: value = setter.unset } = record(node.params);
return { ...node, type: 'SetProperty', params: { property: setter.key, value } };
}
/**
* Rewrites Get/Set property(ies), Set enabled and Set text of an older file into `Properties`, on
* the raw graph before it is normalized. A single node's `value` port is renamed to the property; one
* without a property keeps only its object input and loses its other edges.
*/
export function upgradePropertyNodes(
raw: unknown,
behaviors: ReadonlyMap<string, readonly PropertyDef[]>,
): unknown {
const graph = record(raw);
if (!Array.isArray(graph.nodes)) return raw;
const renamed = new Map<string, string>();
const nodes = (graph.nodes as unknown[]).map((item) => {
const node = fromSetter(record(item));
const type = String(node.type);
if (type in PLURAL_PROPERTY) {
const write = PLURAL_PROPERTY[type];
const ports = (Array.isArray(node.ports) ? (node.ports as unknown[]) : []).map(record);
const pinned = pinPropertyTarget(
ports.map((p) => String(p.key)),
behaviors,
);
return {
...node,
type: PROPERTIES,
params: { ...record(node.params), ...pinned.params },
ports: ports.map((p) => (write ? { ...p, write } : p)),
};
}
if (!(type in SINGLE_PROPERTY)) return node;
const write = SINGLE_PROPERTY[type];
const { property, value, ...params } = record(node.params);
const key = typeof property === 'string' ? property : '';
renamed.set(String(node.id), key);
if (!key) return { ...node, type: PROPERTIES, params, ports: [] };
const pinned = pinPropertyTarget([key], behaviors);
const def = pinned.defs.find((d) => d.key === key);
const kind = def ? portKindOf(def) : 'text';
if (write && value !== undefined) params[key] = value;
return {
...node,
type: PROPERTIES,
params: { ...params, ...pinned.params },
ports: [write ? { key, kind, write } : { key, kind }],
};
});
const edges = (Array.isArray(graph.edges) ? graph.edges : []).flatMap((item) => {
const edge = record(item);
const end = (side: unknown) => {
const at = record(side);
const key = renamed.get(String(at.node));
if (key === undefined || at.port === 'object') return at;
if (key === '') return null;
return at.port === 'value' ? { ...at, port: key } : at;
};
const from = end(edge.from);
const to = end(edge.to);
return from && to ? [{ ...edge, from, to }] : [];
});
return { ...graph, nodes, edges };
}
-56
View File
@@ -1,56 +0,0 @@
import { VARIABLES } from '../graph/nested';
import { portKindOf } from '../graph/variablePorts';
import type { PropertyDef } from '../properties/PropertySchema';
/** The nodes `Variables` replaced, and whether they wrote. */
const SINGLE: Record<string, boolean> = { GetVariable: false, SetVariable: true, Variable: true };
const PLURAL: Record<string, boolean> = { GetVariables: false, SetVariables: true };
type Raw = Record<string, unknown>;
const record = (value: unknown): Raw =>
value && typeof value === 'object' && !Array.isArray(value) ? (value as Raw) : {};
/**
* Rewrites the variable nodes of an older file into `Variables`, on the raw graph before it is
* normalized. A single node's `value` port is renamed to the variable, which is the key there; one
* without a variable has no pins left and loses its edges, flow included.
*/
export function upgradeVariableNodes(raw: unknown, variables: readonly PropertyDef[]): unknown {
const graph = record(raw);
if (!Array.isArray(graph.nodes)) return raw;
const renamed = new Map<string, string>();
const nodes = (graph.nodes as unknown[]).map((item) => {
const node = record(item);
const type = String(node.type);
if (type in PLURAL) {
const write = PLURAL[type];
const ports = Array.isArray(node.ports)
? (node.ports as unknown[]).map((p) => (write ? { ...record(p), write } : p))
: [];
return { ...node, type: VARIABLES, ports };
}
if (!(type in SINGLE)) return item;
const write = SINGLE[type];
const { variable, value, ...params } = record(node.params);
const key = typeof variable === 'string' ? variable : '';
renamed.set(String(node.id), key);
if (!key) return { ...node, type: VARIABLES, params, ports: [] };
const declared = variables.find((v) => v.key === key);
const kind = declared ? portKindOf(declared) : 'text';
if (write && value !== undefined) params[key] = value;
return { ...node, type: VARIABLES, params, ports: [write ? { key, kind, write } : { key, kind }] };
});
const edges = (Array.isArray(graph.edges) ? graph.edges : []).flatMap((item) => {
const edge = record(item);
const end = (side: unknown) => {
const at = record(side);
const key = renamed.get(String(at.node));
if (key === '') return null;
return key !== undefined && at.port === 'value' ? { ...at, port: key } : at;
};
const from = end(edge.from);
const to = end(edge.to);
return from && to ? [{ ...edge, from, to }] : [];
});
return { ...graph, nodes, edges };
}
+4 -2
View File
@@ -19,7 +19,7 @@ import { PROJECT_FORMAT_VERSION, type Project } from '../model/Project';
import type { SceneObject } from '../model/SceneObject';
import { isTextureFile, normalizeFrameRect } from '../model/texture';
import { hasParentCycle } from '../model/walk';
import { upgradeVariableNodes } from './legacyVariableNodes';
import { upgradePropertyNodes, upgradeVariableNodes } from './legacyNodes';
import {
coerceValue,
COMMON_PROPS,
@@ -80,7 +80,9 @@ export function deserializeProject(raw: unknown, fallbackId = ''): Project {
name,
props,
variables: variables.get(id) ?? [],
graph: normalizeGraph(upgradeVariableNodes(a.graph, variables.get(id) ?? [])),
graph: normalizeGraph(
upgradePropertyNodes(upgradeVariableNodes(a.graph, variables.get(id) ?? []), variables),
),
});
} else if (type === 'texture') {
assets.push({ id, type, name, props, ...normalizeTexture(a, takenIds) });
+1 -19
View File
@@ -251,25 +251,7 @@ export function createField(
}
case 'text': {
const field = new TextField(textOf(value), { onInput: handlers.onInput, onChange: handlers.onChange });
const setValue = (v: PropertyValue) => field.setValue(textOf(v));
const suggestions = def.suggestions;
if (!suggestions) return { widget: field, grow: true, setValue };
const pick = new Dropdown('', { variant: 'ghost', width: MARK_WIDTH });
pick.onClick = () => {
const current = field.value.trim();
const items = suggestions.map((s) => ({
label: s.value === current ? `● ${s.label}` : s.label,
onSelect: () => {
setValue(s.value);
handlers.onChange(s.value);
},
}));
new Menu(items, { searchable: true }).openBelow(pick);
};
const combo = new HStack({ gap: Theme.gap, align: 'center' });
combo.add(field, 1);
combo.add(pick);
return { widget: combo, grow: true, setValue };
return { widget: field, grow: true, setValue: (v) => field.setValue(textOf(v)) };
}
case 'color': {
const field = new ColorField(Number(value), { onInput: handlers.onInput, onChange: handlers.onChange });
+16 -7
View File
@@ -6,11 +6,14 @@ import {
type GraphNode,
inlineInputDef,
inlineInputs,
OBJECT_BEHAVIOR_PARAM,
OBJECT_TYPE_PARAM,
portSignature,
resolveDef,
} from '../../core/graph';
import { behaviorLookup } from '../../core/model/behaviorPrograms';
import { findAssetOf, type Project } from '../../core/model/Project';
import { textOf } from '../../core/model/Properties';
import type { PropertyDef } from '../../core/properties/PropertySchema';
import { Label } from '../../ui';
import { createFieldRow, type FieldHandlers } from './fieldFactory';
@@ -33,9 +36,11 @@ export function nodeSignature(project: Project, assetId: string, nodeId: string)
.map((p) => p.key)
: [];
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
.map((v) => v.key)
.join(',')}`;
.join(',')}|${target}`;
}
/** Description, settings (params) and the inline values of unconnected data inputs. */
@@ -51,12 +56,7 @@ export function buildNodeSection(host: InspectorHost, assetId: string, nodeId: s
addNote(host, def.description);
const problem = callProblem(node, behaviorLookup(host.state.project), assetId);
if (problem) addNote(host, problem, 'warning');
if (declaresVariablePorts(node.type)) buildVariablePortSection(host, assetId, node, asset.variables);
else if (declaresPropertyPorts(node.type)) buildPropertyPortSection(host, assetId, node);
else if (def.declaresPorts) buildPortSection(host, assetId, node, asset.variables);
if (def.params.length > 0) addTitle(host, 'SETTINGS');
for (const param of def.params) {
const addSetting = (param: PropertyDef) => {
const row = createFieldRow(
host,
param,
@@ -65,6 +65,15 @@ export function buildNodeSection(host: InspectorHost, assetId: string, nodeId: s
);
host.fields.set(`param:${param.key}`, row);
host.body.add(row.row);
};
const ownSettings = declaresPropertyPorts(node.type);
if (declaresVariablePorts(node.type)) buildVariablePortSection(host, assetId, node, asset.variables);
else if (ownSettings) buildPropertyPortSection(host, assetId, node, addSetting);
else if (def.declaresPorts) buildPortSection(host, assetId, node, asset.variables);
if (!ownSettings && def.params.length > 0) {
addTitle(host, 'SETTINGS');
for (const param of def.params) addSetting(param);
}
const free = inlineInputs(def).filter((p) => edgesInto(asset.graph, node.id, p.key).length === 0);
+69 -53
View File
@@ -14,16 +14,18 @@ import {
type GraphNode,
isTerminalNode,
missingFieldPorts,
objectPropertyDef,
OBJECT_BEHAVIOR_PARAM,
OBJECT_BEHAVIOR_SETTING,
OBJECT_TYPE_SETTING,
portKindOf,
propertyPortOf,
propertyTargetOf,
structShapeOf,
targetLabel,
targetProperties,
} from '../../core/graph';
import {
OBJECT_PROPERTY_CHOICES,
type PropertyDef,
VARIABLE_KINDS,
} from '../../core/properties/PropertySchema';
import { findAssetOf } from '../../core/model/Project';
import { textOf } from '../../core/model/Properties';
import { type PropertyDef, schemaForAsset, VARIABLE_KINDS } from '../../core/properties/PropertySchema';
import {
Checkbox,
Dropdown,
@@ -50,25 +52,54 @@ export function buildVariablePortSection(
node: GraphNode,
variables: readonly PropertyDef[],
): void {
const choices = variables.map((def) => ({ label: def.key, def }));
buildPickedPortSection(host, assetId, node, { noun: 'Variable', choices });
buildPickedPortSection(host, assetId, node, {
noun: 'Variable',
choices: variables,
owner: 'this behavior',
empty: 'This behavior has no variables yet.',
});
}
/**
* The ports of a Get/Set properties node: a built-in property is picked like a variable, and a name
* the list does not know (a variable of another behavior's object) is typed, with a kind of its own.
*/
export function buildPropertyPortSection(host: InspectorHost, assetId: string, node: GraphNode): void {
/** The type decides what the ports are picked from; Any names them by hand, with a kind picked. */
export function buildPropertyPortSection(
host: InspectorHost,
assetId: string,
node: GraphNode,
addSetting: (def: PropertyDef) => void,
): void {
const target = propertyTargetOf(node.params);
addSetting(OBJECT_TYPE_SETTING);
if (target === 'any') {
buildPickedPortSection(host, assetId, node, { noun: 'Property', choices: [], owner: '', custom: true });
return;
}
if (target !== 'behavior') {
const owner = `a ${targetLabel(target)}`;
buildPickedPortSection(host, assetId, node, {
noun: 'Property',
choices: targetProperties(target),
owner,
});
return;
}
addSetting(OBJECT_BEHAVIOR_SETTING);
const id = textOf(node.params[OBJECT_BEHAVIOR_PARAM] ?? '');
const behavior = id ? findAssetOf(host.state.project, id, 'behavior') : undefined;
buildPickedPortSection(host, assetId, node, {
noun: 'Property',
choices: OBJECT_PROPERTY_CHOICES,
custom: true,
choices: behavior ? schemaForAsset(behavior) : [],
owner: behavior ? `"${behavior.name}"` : 'a behavior',
empty: id ? 'That behavior is gone.' : 'Pick a behavior first.',
});
}
interface PickedPorts {
noun: 'Variable' | 'Property';
choices: readonly { label: string; def: PropertyDef }[];
choices: readonly PropertyDef[];
/** Whose ports these are, for the warning on one it does not have. */
owner: string;
empty?: string;
/** Named by hand instead of picked. */
custom?: boolean;
}
@@ -76,82 +107,67 @@ function buildPickedPortSection(
host: InspectorHost,
assetId: string,
node: GraphNode,
{ noun, choices, custom = false }: PickedPorts,
{ noun, choices, owner, empty, custom = false }: PickedPorts,
): void {
const plural = noun === 'Property' ? 'properties' : 'variables';
const ports = node.ports ?? [];
const taken = new Set(ports.map((p) => p.key));
const portOf = (def: PropertyDef): DeclaredPort => ({ key: def.key, kind: portKindOf(def) });
const pick = (own: string, onPick: (port: DeclaredPort) => void): MenuItem[] =>
choices.map(({ label, def }) => ({
label,
choices.map((def) => ({
label: def.key,
disabled: taken.has(def.key) && def.key !== own,
onSelect: () => onPick(portOf(def)),
}));
const typed = (): MenuItem[] =>
VARIABLE_KINDS.map((kind) => ({
label: `Custom ${KIND_LABELS[kind].toLowerCase()}`,
label: KIND_LABELS[kind],
onSelect: () =>
host.state.execute(
new AddPortCommand(assetId, node.id, { key: nextPortName(node, noun.toLowerCase()), kind }),
),
}));
const searchable = noun === 'Property';
const header = new HStack({ gap: Theme.gap, align: 'center' });
header.add(new Label(plural.toUpperCase(), { style: 'title' }), 1);
const add = new Dropdown(`+ ${noun}`, { variant: 'ghost' });
add.onClick = () => {
const items = pick('', (port) => host.state.execute(new AddPortCommand(assetId, node.id, port)));
new Menu(custom ? [...items, ...typed()] : items, { searchable: custom }).openBelow(add);
new Menu(custom ? typed() : items, { searchable }).openBelow(add);
};
add.setEnabled(custom || choices.some(({ def }) => !taken.has(def.key)));
add.setEnabled(custom || choices.some((def) => !taken.has(def.key)));
header.add(add);
host.body.add(header);
if (choices.length === 0) addNote(host, `This behavior has no ${plural} yet.`);
if (!custom && choices.length === 0 && empty) addNote(host, empty);
else if (ports.length === 0) addNote(host, `No ${plural} picked yet. Each one adds a port.`);
for (const port of ports) {
const known = choices.some(({ def }) => def.key === port.key);
if (!known && custom) {
portRow(host, assetId, node, port, customName(host, assetId, node, port));
const toggle = writeToggle(host, assetId, node, port);
if (custom) {
const name = new TextField(port.key, {
width: NAME_WIDTH,
onChange: (next) =>
host.state.execute(new RenamePortCommand(assetId, node.id, port.key, next.trim())),
});
portRow(host, assetId, node, port, name, toggle);
continue;
}
const def = choices.find((d) => d.key === port.key);
const known = def !== undefined && portKindOf(def) === port.kind;
const choose = new Dropdown(port.key, { variant: known ? 'default' : 'danger' });
choose.onClick = () => {
const items = pick(port.key, (next) =>
host.state.execute(new RepointPortCommand(assetId, node.id, port.key, next)),
);
new Menu(items, { searchable: custom }).openBelow(choose);
new Menu(items, { searchable }).openBelow(choose);
};
portRow(
host,
assetId,
node,
port,
choose,
noun === 'Variable' ? writeToggle(host, assetId, node, port) : [],
);
if (!known) addNote(host, `"${port.key}" is not a variable of this behavior.`, 'warning');
portRow(host, assetId, node, port, choose, toggle);
if (!known) addNote(host, `"${port.key}" is not a ${noun.toLowerCase()} of ${owner}.`, 'warning');
}
}
/** Typing a built-in property's name turns the port into that property, kind included. */
function customName(host: InspectorHost, assetId: string, node: GraphNode, port: DeclaredPort): TextField {
return new TextField(port.key, {
width: NAME_WIDTH,
onChange: (text) => {
const next = text.trim();
const builtIn = objectPropertyDef(next);
host.state.execute(
builtIn
? new RepointPortCommand(assetId, node.id, port.key, propertyPortOf(builtIn))
: new RenamePortCommand(assetId, node.id, port.key, next),
);
},
});
}
/**
* The ports a node declares for itself: the signature of a behavior seen as a node, or the fields
* of a struct. A start node's are named from the caller's side – what it hands into the graph is