@fragiola/flow 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +12 -2
- package/dist/connect-session-nyEp02_P.js +375 -0
- package/dist/connect-session-nyEp02_P.js.map +1 -0
- package/dist/connection.d.ts +31 -0
- package/dist/connection.js +60 -0
- package/dist/connection.js.map +1 -0
- package/dist/core-queries-BPNbcM6k.js +452 -0
- package/dist/core-queries-BPNbcM6k.js.map +1 -0
- package/dist/document-schema-CPK5xkyO.js +369 -0
- package/dist/document-schema-CPK5xkyO.js.map +1 -0
- package/dist/drag.d.ts +19 -0
- package/dist/drag.js +175 -0
- package/dist/drag.js.map +1 -0
- package/dist/index.d.ts +876 -0
- package/dist/index.js +5711 -0
- package/dist/index.js.map +1 -0
- package/dist/keyboard-links-CVaTtlZg.js +8 -0
- package/dist/keyboard-links-CVaTtlZg.js.map +1 -0
- package/dist/keyboard.d.ts +40 -0
- package/dist/keyboard.js +342 -0
- package/dist/keyboard.js.map +1 -0
- package/dist/minimap.d.ts +26 -0
- package/dist/minimap.js +206 -0
- package/dist/minimap.js.map +1 -0
- package/dist/node-moves-DyWe-4dj.js +36 -0
- package/dist/node-moves-DyWe-4dj.js.map +1 -0
- package/dist/part-attributes-DuBltA__.js +71 -0
- package/dist/part-attributes-DuBltA__.js.map +1 -0
- package/dist/path-format-2OU7Eiyy.js +43 -0
- package/dist/path-format-2OU7Eiyy.js.map +1 -0
- package/dist/reconnection.d.ts +15 -0
- package/dist/reconnection.js +138 -0
- package/dist/reconnection.js.map +1 -0
- package/dist/rect-CmoREaR6.js +92 -0
- package/dist/rect-CmoREaR6.js.map +1 -0
- package/dist/resize.d.ts +33 -0
- package/dist/resize.js +316 -0
- package/dist/resize.js.map +1 -0
- package/dist/rules-DLOMrPBG.js +102 -0
- package/dist/rules-DLOMrPBG.js.map +1 -0
- package/dist/selection.d.ts +38 -0
- package/dist/selection.js +392 -0
- package/dist/selection.js.map +1 -0
- package/dist/subflows.d.ts +9 -0
- package/dist/subflows.js +237 -0
- package/dist/subflows.js.map +1 -0
- package/dist/types-CLHcZVCb.d.ts +2660 -0
- package/dist/viewport-math-B-9Pn2kN.js +69 -0
- package/dist/viewport-math-B-9Pn2kN.js.map +1 -0
- package/package.json +93 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["describe","controlPoint","distance","TOP_LEFT","ZERO_SIZE","viewOf","viewOf","viewOf"],"sources":["../src/commands/veto.ts","../src/document/flow-validation-error.ts","../src/document/type-guards.ts","../src/features/keys.ts","../src/features/registry.ts","../src/document/create-id.ts","../src/schema/validator.ts","../src/state/deep-freeze.ts","../src/state/replaced-items.ts","../src/state/draft.ts","../src/document/load-document.ts","../src/document/validate-flow.ts","../src/geometry/bezier-path.ts","../src/geometry/simple-bezier-path.ts","../src/geometry/smooth-step-path.ts","../src/geometry/straight-path.ts","../src/geometry/edge-geometry.ts","../src/geometry/node-layout.ts","../src/geometry/viewport-for-bounds.ts","../src/engine/auto-pan.ts","../src/engine/background-pattern.ts","../src/engine/dom.ts","../src/engine/edge-toolbar.ts","../src/geometry/spatial-grid.ts","../src/geometry/z-order.ts","../src/engine/engine-geometry.ts","../src/engine/interactivity.ts","../src/engine/measurements.ts","../src/engine/node-toolbar.ts","../src/engine/structural-style.ts","../src/engine/viewport-animation.ts","../src/engine/create-flow-engine.ts","../src/engine/event-callbacks.ts","../src/engine/watch-key-press.ts","../src/geometry/edge-center.ts","../src/geometry/static-geometry.ts","../src/commands/batch.ts","../src/commands/edge.ts","../src/commands/node.ts","../src/commands/catalogue.ts","../src/model/flow-model-bus.ts","../src/model/create-flow-model.ts","../src/state/same-flow-value.ts"],"sourcesContent":["import type { CommandError } from \"./types\";\n\n/** The vetoed result a middleware returns to stop a command. */\nexport function veto(message = \"vetoed by a middleware\"): {\n readonly ok: false;\n readonly error: CommandError;\n} {\n return { ok: false, error: { code: \"vetoed\", message } };\n}\n","import type { ValidationIssue } from \"../schema/types\";\n\n/** A flow document that cannot be loaded: every problem found, each with its JSON path. */\nexport class FlowValidationError extends Error {\n /** every problem found, each with its JSON path (RFC 6901) */\n readonly issues: readonly ValidationIssue[];\n\n constructor(issues: readonly ValidationIssue[]) {\n const [first] = issues;\n super(\n first\n ? `invalid flow document: ${first.path || \"/\"} ${first.message}${\n issues.length > 1\n ? ` (and ${issues.length - 1} more)`\n : \"\"\n }`\n : \"invalid flow document\",\n );\n this.name = \"FlowValidationError\";\n this.issues = issues;\n }\n}\n","// Whether a value is a node or an edge of a flow, by its shape: a node has an id and a position\n// and no ends; an edge has an id, a source and a target. They tell the two apart in a mixed list\n// (a selection, a context menu's target), not a full validation (`validateFlow` is that).\nimport type { AnyTypes, FlowEdge, FlowNode, FlowTypes } from \"./types\";\n\nconst recordOf = (value: unknown): Record<string, unknown> | undefined =>\n value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n\n/** Whether `value` has a node's shape: a string `id`, a `position` point, no `source` or `target`. */\nexport function isNode<T extends FlowTypes = AnyTypes>(\n value: unknown,\n): value is FlowNode<T> {\n const record = recordOf(value);\n const position = recordOf(record?.position);\n return (\n record !== undefined &&\n typeof record.id === \"string\" &&\n typeof position?.x === \"number\" &&\n typeof position.y === \"number\" &&\n !(\"source\" in record) &&\n !(\"target\" in record)\n );\n}\n\n/** Whether `value` has an edge's shape: a string `id`, `source` and `target`. */\nexport function isEdge<T extends FlowTypes = AnyTypes>(\n value: unknown,\n): value is FlowEdge<T> {\n const record = recordOf(value);\n return (\n record !== undefined &&\n typeof record.id === \"string\" &&\n typeof record.source === \"string\" &&\n typeof record.target === \"string\"\n );\n}\n","// What each opt-in feature owns, by name only (the tree's FEATURE_KEYS idea, fragiola/tree,\n// packages/core/src/features/keys.ts, same author and licence): its commands, its `get` / `is`\n// keys on the model and the engine, and its document fields on a node and on an edge. The core\n// reads this table to refuse what belongs to a feature that is not installed (a `not_found`\n// result, a document or payload issue naming the feature) and to type the verbs from the installed\n// features. The payload and result types stay in the core's maps (types cost no bytes); the code of\n// a feature lives only in its own entry (`@fragiola/flow/<feature>`), which nothing in the main\n// entry imports. The engine names (`engineRun`, `engineGet`, `engineIs`) are the keys each\n// feature's engine side adds to `engine.run` / `get` / `is` (fragiola/flow#3).\n\n/** Every feature's keys and fields. */\nexport const FEATURE_KEYS = Object.freeze({\n selection: {\n commands: [\"selection.set\", \"selection.clear\", \"selection.remove\"],\n get: [\"selected-nodes\", \"selected-edges\"],\n is: [\"node-selected\", \"edge-selected\"],\n engineRun: [],\n engineGet: [\"selection-box\", \"selection-rect\"],\n engineIs: [\"box-selecting\"],\n nodeFields: [\"selected\"],\n edgeFields: [\"selected\"],\n },\n subflows: {\n commands: [\"node.set-parent\"],\n get: [\"node-children-by\", \"node-parent-by\"],\n is: [],\n engineRun: [],\n engineGet: [],\n engineIs: [],\n nodeFields: [\"parentId\", \"extent\", \"expandParent\"],\n edgeFields: [],\n },\n drag: {\n commands: [],\n get: [],\n is: [],\n engineRun: [],\n engineGet: [\"dragging-node-ids\"],\n engineIs: [\"node-dragging\", \"dragging\"],\n nodeFields: [],\n edgeFields: [],\n },\n resize: {\n commands: [],\n get: [],\n is: [],\n engineRun: [],\n engineGet: [],\n engineIs: [\"node-resizing\", \"resizing\"],\n nodeFields: [],\n edgeFields: [],\n },\n connection: {\n commands: [],\n get: [],\n is: [],\n engineRun: [],\n engineGet: [\"connection\"],\n engineIs: [\"connecting\"],\n nodeFields: [],\n edgeFields: [],\n },\n reconnection: {\n commands: [\"edge.reconnect\"],\n get: [],\n is: [],\n engineRun: [],\n engineGet: [],\n engineIs: [\"edge-reconnecting\"],\n nodeFields: [],\n edgeFields: [],\n },\n keyboard: {\n commands: [],\n get: [],\n is: [],\n engineRun: [],\n engineGet: [],\n engineIs: [\"node-focusable\", \"edge-focusable\"],\n nodeFields: [],\n edgeFields: [],\n },\n minimap: {\n commands: [],\n get: [],\n is: [],\n engineRun: [],\n engineGet: [\"minimap-view\", \"minimap-point-to-flow\"],\n engineIs: [],\n nodeFields: [],\n edgeFields: [],\n },\n} as const);\n\n/** The name of an opt-in feature (`@fragiola/flow/<name>`). */\nexport type FeatureName = keyof typeof FEATURE_KEYS;\n\n/** The kinds of names a feature owns. */\nexport type FeatureKeyKind = keyof (typeof FEATURE_KEYS)[FeatureName];\n\n/** The names of kind `K` the features `N` own. */\nexport type OwnedBy<\n K extends FeatureKeyKind,\n N extends FeatureName = FeatureName,\n> = N extends FeatureName ? (typeof FEATURE_KEYS)[N][K][number] : never;\n\n/** Each kind's names, by the feature that owns them (a lookup per field of every loaded node). */\nconst owners = new Map<string, Map<string, FeatureName>>();\nfor (const [name, keys] of Object.entries(FEATURE_KEYS) as [\n FeatureName,\n (typeof FEATURE_KEYS)[FeatureName],\n][]) {\n for (const [kind, list] of Object.entries(keys)) {\n let names = owners.get(kind);\n if (!names) {\n names = new Map();\n owners.set(kind, names);\n }\n for (const key of list as readonly string[]) {\n // a name two features owned would name the first one in a message\n if (!names.has(key)) names.set(key, name);\n }\n }\n}\n\n/** The feature that owns `key` of kind `kind`, if one does. */\nexport function ownerOf(\n kind: FeatureKeyKind,\n key: string,\n): FeatureName | undefined {\n return owners.get(kind)?.get(key);\n}\n\n/** The message of a key or a field whose feature is not installed. */\nexport function requiresFeature(name: FeatureName): string {\n return `requires the ${name} feature (\\`@fragiola/flow/${name}\\`)`;\n}\n","// The registry (data-grid's, fragiola/data-grid, packages/core/src/feature/registry.ts, same\n// author and licence): a model's features composed once, when it is created. Each contribution\n// point is one function the core calls where it would have done the work itself; with no feature\n// having it, it does nothing more. The engine (fragiola/flow#3) finds a model's composition through\n// `featuresOf(model)`, never through the model's public surface, and composes the features' engine\n// sides with `featureEngine`.\n\nimport type { MutablePartAttributes } from \"../attributes/part-attributes\";\nimport type { CommandDefinition, Failure } from \"../commands/define\";\nimport type { FlowEdge, FlowNode, XY } from \"../document/types\";\nimport type { PressTarget } from \"../engine/adapter\";\nimport type { ValidationIssue } from \"../schema/types\";\nimport type { Draft } from \"../state/draft\";\nimport {\n type FeatureKeyKind,\n type FeatureName,\n ownerOf,\n requiresFeature,\n} from \"./keys\";\nimport type {\n AnyFlowFeature,\n FeatureEngine,\n FeatureEngineHost,\n FeatureGesture,\n FlowReader,\n} from \"./types\";\n\n/** A model's features, composed: what the model, its commands and its engines call. */\nexport interface ComposedFeatures {\n /** the features, as installed (fixed: the app's array changing later changes nothing) */\n readonly list: readonly AnyFlowFeature[];\n /** the installed features' names */\n readonly names: ReadonlySet<FeatureName>;\n /** their commands, by name */\n readonly commands: ReadonlyMap<string, CommandDefinition>;\n /** their `get` keys */\n readonly get: ReadonlyMap<\n string,\n (reader: FlowReader, payload: unknown) => unknown\n >;\n /** their `is` keys */\n readonly is: ReadonlyMap<\n string,\n (reader: FlowReader, payload: unknown) => boolean\n >;\n /** the feature that owns `key` of kind `kind` when it is not installed */\n missing(kind: FeatureKeyKind, key: string): FeatureName | undefined;\n /** the fields of `object` that belong to a feature not installed, as issues at `path` */\n missingFields(\n kind: \"nodeFields\" | \"edgeFields\",\n object: object,\n path: string,\n ): ValidationIssue[];\n documentIssues(reader: FlowReader): ValidationIssue[];\n checkNode(draft: Draft, node: FlowNode, path: string): Failure | undefined;\n checkEdge(draft: Draft, edge: FlowEdge, path: string): Failure | undefined;\n removing(draft: Draft, nodeIds: Set<string>): void;\n constrainPosition(draft: Draft, node: FlowNode, position: XY): XY;\n nodeChanged(draft: Draft, nodeId: string): void;\n flagsChanged(draft: Draft, kind: \"node\" | \"edge\", id: string): void;\n absolutePosition(reader: FlowReader, node: FlowNode): XY;\n}\n\n/** The installed features that have a contribution point. */\nfunction having<K extends keyof AnyFlowFeature>(\n list: readonly AnyFlowFeature[],\n key: K,\n): readonly AnyFlowFeature[] {\n return list.filter((feature) => feature[key] !== undefined);\n}\n\n/** A feature's keys of one kind into the model's: a key two features add throws. */\nfunction collect<V>(\n feature: AnyFlowFeature,\n kind: string,\n entries: Readonly<Record<string, unknown>> | undefined,\n into: Map<string, V>,\n): void {\n for (const [key, value] of Object.entries(entries ?? {})) {\n if (into.has(key)) {\n throw new TypeError(\n `feature \"${feature.name}\" adds the ${kind} \"${key}\", which another feature adds`,\n );\n }\n into.set(key, value as V);\n }\n}\n\n/**\n * Composes a list of features, once: it throws for a feature installed twice, or one missing a\n * requirement (`feature \"reconnection\" requires feature \"connection\": install it too`).\n */\nexport function composeFeatures(\n features: readonly AnyFlowFeature[] = [],\n): ComposedFeatures {\n const list = Object.freeze([...features]);\n const names = new Set<FeatureName>();\n for (const feature of list) {\n if (names.has(feature.name)) {\n throw new TypeError(\n `feature \"${feature.name}\" is installed twice: install it once`,\n );\n }\n names.add(feature.name);\n }\n for (const feature of list) {\n for (const required of feature.requires ?? []) {\n if (!names.has(required)) {\n throw new TypeError(\n `feature \"${feature.name}\" requires feature \"${required}\": install it too`,\n );\n }\n }\n }\n const commands = new Map<string, CommandDefinition>();\n const get = new Map<\n string,\n (reader: FlowReader, payload: unknown) => unknown\n >();\n const is = new Map<\n string,\n (reader: FlowReader, payload: unknown) => boolean\n >();\n for (const feature of list) {\n collect(\n feature,\n \"command\",\n Object.fromEntries(\n (feature.commands ?? []).map((command) => [\n command.name,\n command,\n ]),\n ),\n commands,\n );\n collect(feature, \"get key\", feature.get, get);\n collect(feature, \"is key\", feature.is, is);\n }\n const issuers = having(list, \"documentIssues\");\n const checkers = having(list, \"checkNode\");\n const edgeCheckers = having(list, \"checkEdge\");\n const removers = having(list, \"removing\");\n const constrainers = having(list, \"constrainPosition\");\n const followers = having(list, \"nodeChanged\");\n const flagWatchers = having(list, \"flagsChanged\");\n const positioner = list.find((feature) => feature.absolutePosition);\n\n const missing = (kind: FeatureKeyKind, key: string) => {\n const owner = ownerOf(kind, key);\n return owner !== undefined && !names.has(owner) ? owner : undefined;\n };\n\n return Object.freeze({\n list,\n names,\n commands,\n get,\n is,\n missing,\n missingFields: (kind, object, path) =>\n Object.keys(object).flatMap((key) => {\n const owner = missing(kind, key);\n return owner === undefined\n ? []\n : [\n {\n path: `${path}/${key}`,\n message: requiresFeature(owner),\n },\n ];\n }),\n documentIssues: (reader) =>\n issuers.flatMap(\n (feature) => feature.documentIssues?.(reader) ?? [],\n ),\n checkNode: (draft, node, path) => {\n for (const feature of checkers) {\n const failure = feature.checkNode?.(draft, node, path);\n if (failure) {\n return failure;\n }\n }\n return undefined;\n },\n checkEdge: (draft, edge, path) => {\n for (const feature of edgeCheckers) {\n const failure = feature.checkEdge?.(draft, edge, path);\n if (failure) {\n return failure;\n }\n }\n return undefined;\n },\n removing: (draft, nodeIds) => {\n for (const feature of removers) {\n feature.removing?.(draft, nodeIds);\n }\n },\n constrainPosition: (draft, node, position) => {\n let kept = position;\n for (const feature of constrainers) {\n kept = feature.constrainPosition?.(draft, node, kept) ?? kept;\n }\n return kept;\n },\n nodeChanged: (draft, nodeId) => {\n for (const feature of followers) {\n feature.nodeChanged?.(draft, nodeId);\n }\n },\n flagsChanged: (draft, kind, id) => {\n for (const feature of flagWatchers) {\n feature.flagsChanged?.(draft, kind, id);\n }\n },\n absolutePosition: (reader, node) =>\n positioner?.absolutePosition?.(reader, node) ?? node.position,\n } satisfies ComposedFeatures);\n}\n\n/** No feature: a bare flow. */\nexport const NO_FEATURES: ComposedFeatures = composeFeatures([]);\n\n/** The composed features of each model (`featuresOf`): the model's surface stays its verbs. */\nconst byModel = new WeakMap<object, ComposedFeatures>();\n\n/** Records a model's composed features (`createFlowModel`). */\nexport function registerFeatures(\n model: object,\n features: ComposedFeatures,\n): void {\n byModel.set(model, features);\n}\n\n/** A model's composed features (a bare flow's for an object that is not a model). */\nexport function featuresOf(model: object): ComposedFeatures {\n return byModel.get(model) ?? NO_FEATURES;\n}\n\n/** Every installed feature's engine side in one engine, composed: each list walked in install order. */\nexport interface ComposedFeatureEngine {\n readonly list: readonly FeatureEngine[];\n readonly run: ReadonlyMap<\n string,\n NonNullable<FeatureEngine[\"run\"]>[string]\n >;\n readonly get: ReadonlyMap<\n string,\n NonNullable<FeatureEngine[\"get\"]>[string]\n >;\n readonly is: ReadonlyMap<string, NonNullable<FeatureEngine[\"is\"]>[string]>;\n /** the gesture of the first feature that takes a press, if one does */\n pointerdown(\n event: PointerEvent,\n target: PressTarget,\n ): FeatureGesture | undefined;\n /** the first feature whose hook takes a tap: whether one did, or the gesture it started */\n tap(event: PointerEvent, target: PressTarget): boolean | FeatureGesture;\n /** the first feature whose hook takes the wheel: whether one did */\n wheel(event: WheelEvent, target: PressTarget): boolean;\n /** the first feature whose hook takes a key: whether one did, or the gesture it started */\n keydown(\n event: KeyboardEvent,\n target: PressTarget,\n ): boolean | FeatureGesture;\n focus(target: PressTarget): void;\n attributes(\n part: string,\n payload: Readonly<Record<string, unknown>>,\n into: MutablePartAttributes,\n ): void;\n attached(root: Element): void;\n detached(): void;\n destroy(): void;\n}\n\n/**\n * Every installed feature's engine side, made once for one engine with what it hands them\n * (fragiola/flow#3): their keys merged (a key two features add throws), their hooks in install\n * order.\n */\nexport function featureEngine(\n features: ComposedFeatures,\n host: FeatureEngineHost,\n): ComposedFeatureEngine {\n const owners: AnyFlowFeature[] = [];\n const list: FeatureEngine[] = [];\n for (const feature of features.list) {\n if (feature.engine) {\n owners.push(feature);\n list.push(feature.engine(host));\n }\n }\n const run = new Map<string, NonNullable<FeatureEngine[\"run\"]>[string]>();\n const get = new Map<string, NonNullable<FeatureEngine[\"get\"]>[string]>();\n const is = new Map<string, NonNullable<FeatureEngine[\"is\"]>[string]>();\n list.forEach((engine, i) => {\n const owner = owners[i] as AnyFlowFeature;\n collect(owner, \"engine action\", engine.run, run);\n collect(owner, \"engine get key\", engine.get, get);\n collect(owner, \"engine is key\", engine.is, is);\n });\n return {\n list,\n run,\n get,\n is,\n pointerdown: (event, target) => {\n for (const engine of list) {\n const gesture = engine.pointerdown?.(event, target);\n if (gesture) return gesture;\n }\n return undefined;\n },\n tap: (event, target) => {\n for (const engine of list) {\n const taken = engine.tap?.(event, target);\n if (taken === true || (taken && typeof taken === \"object\")) {\n return taken;\n }\n }\n return false;\n },\n wheel: (event, target) =>\n list.some((engine) => engine.wheel?.(event, target) === true),\n keydown: (event, target) => {\n for (const engine of list) {\n const taken = engine.keydown?.(event, target);\n if (taken === true || (taken && typeof taken === \"object\")) {\n return taken;\n }\n }\n return false;\n },\n focus: (target) => {\n for (const engine of list) engine.focus?.(target);\n },\n attributes: (part, payload, into) => {\n for (const engine of list) engine.attributes?.(part, payload, into);\n },\n attached: (root) => {\n for (const engine of list) engine.attached?.(root);\n },\n detached: () => {\n for (const engine of list) engine.detached?.();\n },\n destroy: () => {\n for (const engine of list) engine.destroy?.();\n },\n };\n}\n","// From Dockable (fragiola/dockable, packages/core/src/state/ids.ts), same author and licence.\n// Adapted: the kinds are a flow's (a node, an edge).\n\n/** What an id is generated for. */\nexport type IdKind = \"node\" | \"edge\";\n\n/**\n * Generates the id of a node or an edge given without one (the `createId` option). The model skips\n * an id already in use and asks again; no global `crypto` is ever used.\n */\nexport type CreateId = (kind: IdKind) => string;\n\n/** How many times a custom generator is asked before the default takes over. */\nconst ATTEMPTS = 100;\n\n/**\n * The ids of one model. The default generator is deterministic: `` `${kind}-${n}` `` with one\n * counter per kind.\n */\nexport class IdSource {\n private readonly counters = new Map<IdKind, number>();\n private readonly custom: CreateId | undefined;\n\n constructor(createId?: CreateId) {\n this.custom = createId;\n }\n\n /**\n * A copy with the same counters and no custom generator: a dry run draws ids from it, leaving\n * this one as it was and never asking the app's `createId` (so `check`'s id is only indicative).\n */\n dryClone(): IdSource {\n const copy = new IdSource();\n for (const [kind, n] of this.counters) {\n copy.counters.set(kind, n);\n }\n return copy;\n }\n\n /** A fresh id for `kind`, for which `isUsed` is false. */\n next(kind: IdKind, isUsed: (id: string) => boolean): string {\n if (this.custom) {\n for (let i = 0; i < ATTEMPTS; i++) {\n const id = this.custom(kind);\n if (typeof id === \"string\" && id !== \"\" && !isUsed(id)) {\n return id;\n }\n }\n }\n for (;;) {\n const n = (this.counters.get(kind) ?? 0) + 1;\n this.counters.set(kind, n);\n const id = `${kind}-${n}`;\n if (!isUsed(id)) {\n return id;\n }\n }\n }\n}\n","// From Dockable (fragiola/dockable, packages/core/src/schema/validator.ts), same author and licence.\nimport type { JsonSchema, ValidationIssue } from \"./types\";\n\n/** Escapes a key for a JSON pointer (RFC 6901). */\nexport function pointerSegment(key: string | number): string {\n if (typeof key === \"number\") return String(key);\n // most keys need no escape: no regular expression for them (a document's every field)\n if (!key.includes(\"~\") && !key.includes(\"/\")) return key;\n return key.replace(/~/g, \"~0\").replace(/\\//g, \"~1\");\n}\n\n/** Appends a key to a JSON pointer. */\nexport function joinPointer(path: string, key: string | number): string {\n return `${path}/${pointerSegment(key)}`;\n}\n\n/** A JSON object: not an array, not null. */\nexport function isObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction describe(value: unknown): string {\n return JSON.stringify(value) ?? String(value);\n}\n\nfunction typeMatches(type: string, value: unknown): boolean {\n switch (type) {\n case \"object\":\n return isObject(value);\n case \"array\":\n return Array.isArray(value);\n case \"string\":\n return typeof value === \"string\";\n case \"number\":\n return typeof value === \"number\" && Number.isFinite(value);\n case \"integer\":\n return Number.isInteger(value);\n case \"boolean\":\n return typeof value === \"boolean\";\n case \"null\":\n return value === null;\n default:\n return true;\n }\n}\n\nconst ARTICLE: Record<string, string> = {\n object: \"an object\",\n array: \"an array\",\n string: \"a string\",\n number: \"a number\",\n integer: \"an integer\",\n boolean: \"a boolean\",\n null: \"null\",\n};\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) {\n return true;\n }\n if (Array.isArray(a) && Array.isArray(b)) {\n return (\n a.length === b.length && a.every((item, i) => deepEqual(item, b[i]))\n );\n }\n if (isObject(a) && isObject(b)) {\n const keys = Object.keys(a);\n return (\n keys.length === Object.keys(b).length &&\n keys.every((key) => deepEqual(a[key], b[key]))\n );\n }\n return false;\n}\n\nfunction resolveRef(root: JsonSchema, ref: string): JsonSchema | undefined {\n const match = /^#\\/\\$defs\\/(.+)$/.exec(ref);\n const name = match?.[1]?.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n return name === undefined ? undefined : root.$defs?.[name];\n}\n\n/**\n * Validates `value` against `schema` (the subset in {@link JsonSchema}) and returns every problem,\n * each with a JSON pointer relative to `path`. `root` is the document local `$ref`s resolve in.\n */\nexport function validate(\n schema: JsonSchema,\n value: unknown,\n path = \"\",\n root: JsonSchema = schema,\n): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n check(schema, value, path, root, issues);\n return issues;\n}\n\nfunction check(\n schema: JsonSchema,\n value: unknown,\n path: string,\n root: JsonSchema,\n issues: ValidationIssue[],\n): void {\n if (schema.$ref !== undefined) {\n const target = resolveRef(root, schema.$ref);\n if (!target) {\n issues.push({ path, message: `unresolved $ref ${schema.$ref}` });\n return;\n }\n check(target, value, path, root, issues);\n return;\n }\n if (schema.anyOf) {\n checkAlternatives(schema.anyOf, value, path, root, issues, false);\n return;\n }\n if (schema.oneOf) {\n checkAlternatives(schema.oneOf, value, path, root, issues, true);\n return;\n }\n if (\"const\" in schema && !deepEqual(value, schema.const)) {\n issues.push({\n path,\n message: `must be ${describe(schema.const)}`,\n });\n return;\n }\n if (\n schema.enum &&\n !schema.enum.some((allowed) => deepEqual(allowed, value))\n ) {\n issues.push({\n path,\n message: `must be one of ${schema.enum.map(describe).join(\", \")}`,\n });\n return;\n }\n if (schema.type !== undefined && !typeMatches(schema.type, value)) {\n issues.push({\n path,\n message: `must be ${ARTICLE[schema.type] ?? schema.type}`,\n });\n return;\n }\n if (typeof value === \"number\") {\n if (schema.minimum !== undefined && value < schema.minimum) {\n issues.push({ path, message: `must be >= ${schema.minimum}` });\n }\n if (\n schema.exclusiveMinimum !== undefined &&\n value <= schema.exclusiveMinimum\n ) {\n issues.push({\n path,\n message: `must be > ${schema.exclusiveMinimum}`,\n });\n }\n }\n if (\n typeof value === \"string\" &&\n schema.minLength !== undefined &&\n value.length < schema.minLength\n ) {\n issues.push({\n path,\n message: `must have at least ${schema.minLength} character(s)`,\n });\n }\n if (Array.isArray(value)) {\n if (schema.minItems !== undefined && value.length < schema.minItems) {\n issues.push({\n path,\n message: `must have at least ${schema.minItems} item(s)`,\n });\n }\n if (schema.items) {\n for (const [i, item] of value.entries()) {\n check(schema.items, item, joinPointer(path, i), root, issues);\n }\n }\n }\n if (isObject(value)) {\n const properties = schema.properties ?? {};\n // own keys only: an inherited one (`toString`, `__proto__`) is not the document's\n for (const key of schema.required ?? []) {\n if (!Object.hasOwn(value, key) || value[key] === undefined) {\n issues.push({\n path: joinPointer(path, key),\n message: \"is required\",\n });\n }\n }\n for (const [key, child] of Object.entries(value)) {\n const property = Object.hasOwn(properties, key)\n ? properties[key]\n : undefined;\n if (property) {\n if (child !== undefined) {\n check(\n property,\n child,\n joinPointer(path, key),\n root,\n issues,\n );\n }\n } else if (schema.additionalProperties === false) {\n issues.push({\n path: joinPointer(path, key),\n message: \"is not allowed\",\n });\n }\n }\n }\n}\n\n/**\n * anyOf / oneOf. When every alternative fails, the issues of the alternative that matched the\n * value's discriminator (its `type` property, when the alternatives have one) are reported, so a\n * wrong field of one shape is not drowned in the other shapes' noise.\n */\nfunction checkAlternatives(\n alternatives: readonly JsonSchema[],\n value: unknown,\n path: string,\n root: JsonSchema,\n issues: ValidationIssue[],\n exactlyOne: boolean,\n): void {\n const results = alternatives.map((alternative) =>\n validate(alternative, value, path, root),\n );\n const passing = results.filter((result) => result.length === 0).length;\n if (exactlyOne ? passing === 1 : passing > 0) {\n return;\n }\n if (passing > 1) {\n issues.push({ path, message: \"must match exactly one shape\" });\n return;\n }\n const discriminator = joinPointer(path, \"type\");\n const matched = results.filter(\n (result) => !result.some((issue) => issue.path === discriminator),\n );\n const only = matched.length === 1 ? matched[0] : undefined;\n if (only) {\n issues.push(...only);\n return;\n }\n // the one alternative the value itself fits (its problems are all deeper)\n const shaped = results.filter(\n (result) => !result.some((issue) => issue.path === path),\n );\n const fitting = shaped.length === 1 ? shaped[0] : undefined;\n if (fitting) {\n issues.push(...fitting);\n return;\n }\n const shallow = results.filter((result) =>\n result.every((issue) => issue.path === path),\n );\n if (shallow.length === results.length) {\n // no alternative got past the value itself: report its accepted forms\n const messages = [\n ...new Set(results.flat().map((issue) => issue.message)),\n ];\n issues.push({ path, message: messages.join(\" or \") });\n return;\n }\n issues.push({ path, message: \"does not match any allowed shape\" });\n}\n","/** Freezes a JSON value and everything in it (already frozen parts are skipped, they are shared). */\nexport function deepFreeze<V>(value: V): V {\n if (\n typeof value === \"object\" &&\n value !== null &&\n !Object.isFrozen(value)\n ) {\n Object.freeze(value);\n for (const child of Object.values(value)) {\n deepFreeze(child);\n }\n }\n return value;\n}\n","// Which items a committed node or edge list replaced in place (Issue #59): a draft that only\n// replaced items (a move, a resize, a flag) records, beside the new list, the list it copied and the\n// ids it replaced. The engine's geometry then knows what a drag step changed without comparing the\n// whole list. Internal (not exported): the document keeps its shape and its public events. Lists are\n// the keys of a WeakMap, so a list nobody holds is forgotten with its record.\n\ninterface Replacement {\n readonly from: readonly unknown[];\n readonly ids: ReadonlySet<string>;\n}\n\nconst replacements = new WeakMap<readonly unknown[], Replacement>();\n\n/** The most commits a lookup walks back through before giving up (the caller compares instead). */\nconst MOST_STEPS = 32;\n\n/** Records that `list` is `from` with the items of `ids` replaced, at the same places. */\nexport function recordReplaced(\n list: readonly unknown[],\n from: readonly unknown[],\n ids: ReadonlySet<string>,\n): void {\n replacements.set(list, { from, ids });\n}\n\n/**\n * The ids of the items replaced between `since` and `list`, when every commit between them only\n * replaced items (so the ids and their places are the same); undefined when unknown.\n */\nexport function replacedSince(\n list: readonly unknown[],\n since: readonly unknown[],\n): ReadonlySet<string> | undefined {\n let at = list;\n let ids: Set<string> | undefined;\n let only: ReadonlySet<string> | undefined;\n for (let step = 0; step < MOST_STEPS; step++) {\n const record = replacements.get(at);\n if (!record) return undefined;\n if (only === undefined && ids === undefined) only = record.ids;\n else {\n ids ??= new Set(only);\n for (const id of record.ids) ids.add(id);\n }\n if (record.from === since) return ids ?? only;\n at = record.from;\n }\n return undefined;\n}\n","// What a command writes to: the committed document, copied on the first write, sharing every node\n// and edge it does not touch (`before.nodes[i] === after.nodes[i]` for an untouched node, so an\n// app's undo or a view can compare by identity). A dry run throws its draft away.\nimport type { IdSource } from \"../document/create-id\";\nimport type { FlowDocument, FlowEdge, FlowNode } from \"../document/types\";\nimport type { FlowReader } from \"../features/types\";\nimport { deepFreeze } from \"./deep-freeze\";\nimport { recordReplaced } from \"./replaced-items\";\n\n/** Each entity's index in its list, by id. */\nexport type EntityIndex = ReadonlyMap<string, number>;\n\n/** A document and the indexes of its nodes and edges: what the model holds and queries read. */\nexport interface IndexedDocument {\n readonly document: FlowDocument;\n readonly nodeIndex: EntityIndex;\n readonly edgeIndex: EntityIndex;\n}\n\n/** The index of a list of entities, by id. */\nexport function indexOf(list: readonly { readonly id: string }[]): EntityIndex {\n return new Map(list.map((entity, i) => [entity.id, i]));\n}\n\n/** A reader of a committed document (no writes, no ids drawn). */\nexport function readerOf(indexed: IndexedDocument): FlowReader {\n const { document: flow, nodeIndex, edgeIndex } = indexed;\n return {\n nodes: () => flow.nodes,\n edges: () => flow.edges,\n node: (id) => {\n const at = nodeIndex.get(id);\n return at === undefined ? undefined : flow.nodes[at];\n },\n edge: (id) => {\n const at = edgeIndex.get(id);\n return at === undefined ? undefined : flow.edges[at];\n },\n };\n}\n\n/** A copy-on-write document: what a command reads and changes. */\nexport class Draft implements FlowReader {\n readonly ids: IdSource;\n private readonly base: IndexedDocument;\n private nodeList: FlowNode[] | undefined;\n private edgeList: FlowEdge[] | undefined;\n private nodeIds: Map<string, number> | undefined;\n private edgeIds: Map<string, number> | undefined;\n /** the ids replaced in place; none once an item was added or removed */\n private replacedNodes: Set<string> | undefined = new Set();\n private replacedEdges: Set<string> | undefined = new Set();\n\n constructor(base: IndexedDocument, ids: IdSource) {\n this.base = base;\n this.ids = ids;\n }\n\n /** Whether a command changed anything. */\n get changed(): boolean {\n return this.nodeList !== undefined || this.edgeList !== undefined;\n }\n\n /** The nodes, in order. */\n nodes(): readonly FlowNode[] {\n return this.nodeList ?? this.base.document.nodes;\n }\n\n /** The edges, in order. */\n edges(): readonly FlowEdge[] {\n return this.edgeList ?? this.base.document.edges;\n }\n\n /** A node by its id. */\n node(id: string): FlowNode | undefined {\n const at = (this.nodeIds ?? this.base.nodeIndex).get(id);\n return at === undefined ? undefined : this.nodes()[at];\n }\n\n /** An edge by its id. */\n edge(id: string): FlowEdge | undefined {\n const at = (this.edgeIds ?? this.base.edgeIndex).get(id);\n return at === undefined ? undefined : this.edges()[at];\n }\n\n /** A fresh node id (`createId`). */\n nextNodeId(): string {\n return this.ids.next(\"node\", (id) => this.node(id) !== undefined);\n }\n\n /** A fresh edge id (`createId`). */\n nextEdgeId(): string {\n return this.ids.next(\"edge\", (id) => this.edge(id) !== undefined);\n }\n\n /** Appends a node (its id unused) or replaces the node of its id, in place. */\n putNode(node: FlowNode): void {\n const list = this.ownNodes();\n const at = (this.nodeIds ?? this.base.nodeIndex).get(node.id);\n if (at !== undefined) {\n // replaced in place: the index stays the base's (no copy of it per move)\n list[at] = node;\n this.replacedNodes?.add(node.id);\n return;\n }\n this.replacedNodes = undefined;\n const ids = this.nodeIds ?? new Map(this.base.nodeIndex);\n this.nodeIds = ids;\n ids.set(node.id, list.length);\n list.push(node);\n }\n\n /** Appends an edge (its id unused) or replaces the edge of its id, in place. */\n putEdge(edge: FlowEdge): void {\n const list = this.ownEdges();\n const at = (this.edgeIds ?? this.base.edgeIndex).get(edge.id);\n if (at !== undefined) {\n // replaced in place: the index stays the base's (no copy of it per move)\n list[at] = edge;\n this.replacedEdges?.add(edge.id);\n return;\n }\n this.replacedEdges = undefined;\n const ids = this.edgeIds ?? new Map(this.base.edgeIndex);\n this.edgeIds = ids;\n ids.set(edge.id, list.length);\n list.push(edge);\n }\n\n /** Removes the nodes of these ids (their edges are the caller's to remove). */\n removeNodes(ids: ReadonlySet<string>): void {\n if (ids.size === 0) {\n return;\n }\n this.replacedNodes = undefined;\n this.nodeList = this.nodes().filter((node) => !ids.has(node.id));\n this.nodeIds = new Map(indexOf(this.nodeList));\n }\n\n /** Removes the edges of these ids. */\n removeEdges(ids: ReadonlySet<string>): void {\n if (ids.size === 0) {\n return;\n }\n this.replacedEdges = undefined;\n this.edgeList = this.edges().filter((edge) => !ids.has(edge.id));\n this.edgeIds = new Map(indexOf(this.edgeList));\n }\n\n /** The document the draft holds now, frozen (or the base itself when nothing changed). */\n commit(freeze: boolean): IndexedDocument {\n if (!this.changed) {\n return this.base;\n }\n const flow: FlowDocument = {\n version: 1,\n nodes: this.nodes(),\n edges: this.edges(),\n };\n // what was only replaced in place, for the engine's geometry (replaced-items.ts)\n if (this.nodeList && this.replacedNodes) {\n recordReplaced(\n this.nodeList,\n this.base.document.nodes,\n this.replacedNodes,\n );\n }\n if (this.edgeList && this.replacedEdges) {\n recordReplaced(\n this.edgeList,\n this.base.document.edges,\n this.replacedEdges,\n );\n }\n return {\n document: freeze ? deepFreeze(flow) : flow,\n nodeIndex: this.nodeIds ?? this.base.nodeIndex,\n edgeIndex: this.edgeIds ?? this.base.edgeIndex,\n };\n }\n\n private ownNodes(): FlowNode[] {\n this.nodeList ??= [...this.base.document.nodes];\n return this.nodeList;\n }\n\n private ownEdges(): FlowEdge[] {\n this.edgeList ??= [...this.base.document.edges];\n return this.edgeList;\n }\n}\n","// Loads a flow document (D3): checks it against its JSON Schema and the rules a schema cannot say\n// (ids unique, edges between existing nodes, one edge per pair of handles, the installed features'\n// own rules), refuses a field of a feature that is not installed, generates the missing ids and\n// freezes the result. Every problem is reported, each with its JSON path.\nimport type { ComposedFeatures } from \"../features/registry\";\nimport type { ValidationIssue } from \"../schema/types\";\nimport { isObject, validate } from \"../schema/validator\";\nimport { cloneJson } from \"../state/clone-json\";\nimport { deepFreeze } from \"../state/deep-freeze\";\nimport { type IndexedDocument, indexOf, readerOf } from \"../state/draft\";\nimport type { IdSource } from \"./create-id\";\nimport { flowDocumentSchema } from \"./document-schema\";\nimport type { FlowDocument, FlowEdge, FlowNode } from \"./types\";\n\n/** A loaded document, or every problem found in it. */\nexport type Loaded =\n | { readonly ok: true; readonly indexed: IndexedDocument }\n | { readonly ok: false; readonly issues: readonly ValidationIssue[] };\n\n/** The entries of an array field of `json`, when it is one. */\nfunction entries(json: unknown, key: string): unknown[] {\n const list = isObject(json) ? json[key] : undefined;\n return Array.isArray(list) ? list : [];\n}\n\n/** A string field of an entry of unknown shape. */\nfunction stringField(entry: unknown, key: string): string | undefined {\n const value = isObject(entry) ? entry[key] : undefined;\n return typeof value === \"string\" ? value : undefined;\n}\n\n/** Ids given twice in a list, as issues at the later one's `/id`. */\nfunction duplicateIds(\n list: readonly unknown[],\n path: string,\n kind: string,\n): ValidationIssue[] {\n const first = new Map<string, number>();\n const issues: ValidationIssue[] = [];\n list.forEach((entity, i) => {\n const id = stringField(entity, \"id\");\n if (id === undefined) {\n return;\n }\n const seen = first.get(id);\n if (seen === undefined) {\n first.set(id, i);\n } else {\n issues.push({\n path: `${path}/${i}/id`,\n message: `duplicates the id of ${kind} ${path}/${seen}`,\n });\n }\n });\n return issues;\n}\n\n/** Edges whose ends are not nodes, and edges joining the same handles as an earlier one. */\nfunction edgeIssues(\n edges: readonly unknown[],\n nodeIds: ReadonlySet<string>,\n path: string,\n): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n const pairs = new Map<string, number>();\n edges.forEach((edge, i) => {\n const source = stringField(edge, \"source\");\n const target = stringField(edge, \"target\");\n for (const [end, id] of [\n [\"source\", source],\n [\"target\", target],\n ] as const) {\n if (id !== undefined && !nodeIds.has(id)) {\n issues.push({\n path: `${path}/${i}/${end}`,\n message: `no node \"${id}\"`,\n });\n }\n }\n if (source === undefined || target === undefined) {\n return;\n }\n const pair = JSON.stringify([\n source,\n stringField(edge, \"sourceHandle\") ?? null,\n target,\n stringField(edge, \"targetHandle\") ?? null,\n ]);\n const twin = pairs.get(pair);\n if (twin === undefined) {\n pairs.set(pair, i);\n } else {\n issues.push({\n path: `${path}/${i}`,\n message: `joins the same handles as edge ${path}/${twin}`,\n });\n }\n });\n return issues;\n}\n\n/**\n * Loads `json` as a flow document with the installed `features`; `prefix` places every path\n * (a document inside a payload). Every check runs on what it can read, so one load reports every\n * problem: the schema's, the ids', the edges' ends and the features' rules.\n */\nexport function loadDocument(\n json: unknown,\n ids: IdSource,\n features: ComposedFeatures,\n freeze: boolean,\n prefix = \"\",\n): Loaded {\n const nodeEntries = entries(json, \"nodes\");\n const edgeEntries = entries(json, \"edges\");\n const shape = validate(flowDocumentSchema, json, prefix);\n const issues: ValidationIssue[] = [\n ...shape,\n ...nodeEntries.flatMap((node, i) =>\n isObject(node)\n ? features.missingFields(\n \"nodeFields\",\n node,\n `${prefix}/nodes/${i}`,\n )\n : [],\n ),\n ...edgeEntries.flatMap((edge, i) =>\n isObject(edge)\n ? features.missingFields(\n \"edgeFields\",\n edge,\n `${prefix}/edges/${i}`,\n )\n : [],\n ),\n ...duplicateIds(nodeEntries, `${prefix}/nodes`, \"node\"),\n ...duplicateIds(edgeEntries, `${prefix}/edges`, \"edge\"),\n ];\n\n // ids: the given ones, then one for each entry without\n const nodeIds = new Set(\n nodeEntries.flatMap((node) => stringField(node, \"id\") ?? []),\n );\n const edgeIds = new Set(\n edgeEntries.flatMap((edge) => stringField(edge, \"id\") ?? []),\n );\n const withId = <E>(\n entry: unknown,\n kind: \"node\" | \"edge\",\n taken: Set<string>,\n ): E => {\n if (!isObject(entry)) {\n return entry as E;\n }\n const { id, ...fields } = cloneJson(entry);\n const given = typeof id === \"string\" ? id : undefined;\n const entryId =\n given ?? ids.next(kind, (candidate) => taken.has(candidate));\n taken.add(entryId);\n return { id: entryId, ...fields } as E;\n };\n const nodes = nodeEntries.map((node) =>\n withId<FlowNode>(node, \"node\", nodeIds),\n );\n const edges = edgeEntries.map((edge) =>\n withId<FlowEdge>(edge, \"edge\", edgeIds),\n );\n issues.push(...edgeIssues(edges, nodeIds, `${prefix}/edges`));\n\n const flow: FlowDocument = { version: 1, nodes, edges };\n const indexed: IndexedDocument = {\n document: flow,\n nodeIndex: indexOf(nodes.filter(isObject)),\n edgeIndex: indexOf(edges.filter(isObject)),\n };\n // a feature's rules read nodes and edges: only when every entry is one\n if (nodes.every(isObject) && edges.every(isObject)) {\n issues.push(\n ...features.documentIssues(readerOf(indexed)).map((issue) => ({\n path: `${prefix}${issue.path}`,\n message: issue.message,\n })),\n );\n }\n if (issues.length > 0) {\n return { ok: false, issues };\n }\n if (freeze) {\n deepFreeze(flow);\n }\n return { ok: true, indexed };\n}\n","import { composeFeatures } from \"../features/registry\";\nimport type { FlowFeatures } from \"../features/types\";\nimport type { ValidationIssue } from \"../schema/types\";\nimport { IdSource } from \"./create-id\";\nimport { loadDocument } from \"./load-document\";\n\n/** What `validateFlow` checks against: the features the document will be loaded with. */\nexport interface ValidateFlowOptions {\n /** the features installed (a field of one not given is an issue); default none */\n features?: FlowFeatures | undefined;\n}\n\n/**\n * Every problem of a flow document, each with its JSON path, or none: what `createFlowModel`\n * would throw a `FlowValidationError` with. It never throws for a document (only for a features\n * list `createFlowModel` would refuse too: a feature twice, or one missing a requirement).\n */\nexport function validateFlow(\n json: unknown,\n options: ValidateFlowOptions = {},\n): readonly ValidationIssue[] {\n const loaded = loadDocument(\n json,\n new IdSource(),\n composeFeatures(options.features),\n false,\n );\n return loaded.ok ? [] : loaded.issues;\n}\n","// A bezier edge: one cubic curve whose control points stand out from each end in the direction of\n// its side, so the edge leaves and enters its handles square. How far a control point stands out\n// is a share (`curvature`) of how far the other end lies along that direction, and never less than\n// a minimum, so an end whose other end is behind it still bends out before turning back.\nimport type { XY } from \"../document/types\";\nimport { formatPoint, sideDirection } from \"./path-format\";\nimport type { HandleSide, PathEnds, PathResult } from \"./types\";\n\n/** Options of {@link bezierPath}. */\nexport interface BezierPathOptions extends PathEnds {\n /** the share of the distance along a side its control point stands out by; default 0.5 */\n readonly curvature?: number | undefined;\n}\n\n/** What {@link bezierPath} returns: its path, its label point and how far that lies from the source. */\nexport interface BezierPathResult extends PathResult {\n /** the distance across (x) and down (y) from the source to the label point, both positive */\n readonly labelOffset: XY;\n}\n\n/** The least distance a control point stands out from its end, in flow units. */\nconst MIN_REACH = 20;\n\n/** The control point of the end at `from` (leaving by `side`), with the other end at `to`. */\nfunction controlPoint(\n from: XY,\n side: HandleSide,\n to: XY,\n curvature: number,\n): XY {\n const direction = sideDirection(side);\n const along = (to.x - from.x) * direction.x + (to.y - from.y) * direction.y;\n const reach = Math.max(MIN_REACH, Math.abs(along) * curvature);\n return {\n x: from.x + direction.x * reach,\n y: from.y + direction.y * reach,\n };\n}\n\n/**\n * A bezier edge's path from `source` to `target`, its label point (the curve's middle,\n * `t = 0.5`) and that point's offset from the source.\n */\nexport function bezierPath(options: BezierPathOptions): BezierPathResult {\n const { source, target, sourceSide, targetSide } = options;\n const curvature = options.curvature ?? 0.5;\n const c1 = controlPoint(source, sourceSide, target, curvature);\n const c2 = controlPoint(target, targetSide, source, curvature);\n // B(1/2) = (P0 + 3 P1 + 3 P2 + P3) / 8\n const label = {\n x: (source.x + 3 * c1.x + 3 * c2.x + target.x) / 8,\n y: (source.y + 3 * c1.y + 3 * c2.y + target.y) / 8,\n };\n return {\n path: `M${formatPoint(source)} C${formatPoint(c1)} ${formatPoint(c2)} ${formatPoint(target)}`,\n label,\n labelOffset: {\n x: Math.abs(label.x - source.x),\n y: Math.abs(label.y - source.y),\n },\n };\n}\n","// A simple bezier edge: one cubic curve whose control points lie on each end's side axis (the\n// line through the end in its side's direction), halfway to where the other end projects on that\n// axis. Unlike the bezier it has no least reach: two ends on one line draw a straight curve, and\n// an end whose other end is behind it turns back at once. The shape depends only on the ends and\n// their sides' axes (a side and its opposite give the same curve).\nimport type { XY } from \"../document/types\";\nimport { formatPoint, sideDirection } from \"./path-format\";\nimport type { HandleSide, PathEnds, PathResult } from \"./types\";\n\n/** Options of {@link simpleBezierPath}: the two ends and their sides. */\nexport interface SimpleBezierPathOptions extends PathEnds {}\n\n/** The control point of the end at `from` (on a `side`), halfway along its axis to `to`. */\nfunction controlPoint(from: XY, side: HandleSide, to: XY): XY {\n const axis = sideDirection(side);\n // the signed distance from `from` to `to`'s projection on the axis, halved\n const half = ((to.x - from.x) * axis.x + (to.y - from.y) * axis.y) / 2;\n return { x: from.x + axis.x * half, y: from.y + axis.y * half };\n}\n\n/**\n * A simple bezier edge's path from `source` to `target`, and its label point (the curve's middle,\n * `t = 0.5`).\n */\nexport function simpleBezierPath(options: SimpleBezierPathOptions): PathResult {\n const { source, target, sourceSide, targetSide } = options;\n const c1 = controlPoint(source, sourceSide, target);\n const c2 = controlPoint(target, targetSide, source);\n // B(1/2) = (P0 + 3 P1 + 3 P2 + P3) / 8\n const label = {\n x: (source.x + 3 * c1.x + 3 * c2.x + target.x) / 8,\n y: (source.y + 3 * c1.y + 3 * c2.y + target.y) / 8,\n };\n return {\n path: `M${formatPoint(source)} C${formatPoint(c1)} ${formatPoint(c2)} ${formatPoint(target)}`,\n label,\n };\n}\n","// Step and smooth step edges: an orthogonal route (horizontal and vertical segments only) from the\n// source to the target, leaving and entering each handle along its side. A smooth step rounds each\n// corner with a quadratic curve of `borderRadius`; a step is a smooth step with square corners.\n//\n// The route: each end first stands out from its node by `offset` along its side. Then\n// - two ends on parallel axes facing each other (right to left), the target ahead: one turn halfway\n// between them (at `stepPosition` of the way, or at `centerX` / `centerY`);\n// - facing each other, the target behind: out by `offset`, across halfway (the same options), and\n// back in; both ends on one line, the run across is `offset` below (right of) them: a loop;\n// - on the same side (right and right): out to the farther of the two, across, and in;\n// - on perpendicular axes: one corner where the two lines meet when both ends reach it going\n// forward, otherwise out from both ends by `offset` and joined with one more corner.\n// The label goes halfway along the route's length.\nimport type { XY } from \"../document/types\";\nimport { formatPoint, sideDirection } from \"./path-format\";\nimport type { PathEnds, PathResult } from \"./types\";\n\n/** Where the turn between two ends facing each other goes (`smoothStepPath`, `stepPath`). */\nexport interface StepTurnOptions {\n /**\n * where the turn sits between the source (0) and the target (1), along the ends' axis (across\n * it when the target is behind), counted from the points `offset` out from each end so that\n * 0 and 1 keep the stand-out; default 0.5 (also for a value that is not a finite number)\n */\n readonly stepPosition?: number | undefined;\n /** the turn's x (flow units) when it runs vertically, over `stepPosition` (when finite) */\n readonly centerX?: number | undefined;\n /** the turn's y (flow units) when it runs horizontally, over `stepPosition` (when finite) */\n readonly centerY?: number | undefined;\n}\n\n/** Options of {@link smoothStepPath}. */\nexport interface SmoothStepPathOptions extends PathEnds, StepTurnOptions {\n /** the radius of each rounded corner, in flow units; default 5 */\n readonly borderRadius?: number | undefined;\n /** how far each end stands out from its node before the route turns, in flow units; default 20 */\n readonly offset?: number | undefined;\n}\n\n/** Options of {@link stepPath}. */\nexport interface StepPathOptions extends PathEnds, StepTurnOptions {\n /** how far each end stands out from its node before the route turns, in flow units; default 20 */\n readonly offset?: number | undefined;\n}\n\n/** The value `share` of the way from `from` to `to` (exactly the middle at 0.5). */\nfunction between(from: number, to: number, share: number): number {\n return share === 0.5 ? (from + to) / 2 : from + (to - from) * share;\n}\n\n/** A finite number as given; anything else (none, NaN, an infinity) as `fallback`. */\nfunction finiteOr<T>(value: number | undefined, fallback: T): number | T {\n return typeof value === \"number\" && Number.isFinite(value)\n ? value\n : fallback;\n}\n\nfunction plus(point: XY, direction: XY, distance: number): XY {\n return {\n x: point.x + direction.x * distance,\n y: point.y + direction.y * distance,\n };\n}\n\nfunction dot(a: XY, b: XY): number {\n return a.x * b.x + a.y * b.y;\n}\n\nfunction minus(a: XY, b: XY): XY {\n return { x: a.x - b.x, y: a.y - b.y };\n}\n\nfunction distance(a: XY, b: XY): number {\n return Math.hypot(b.x - a.x, b.y - a.y);\n}\n\n/** The corners of the orthogonal route between two ends, both ends included. */\nexport function orthogonalRoute(\n ends: PathEnds,\n offset: number,\n turn: StepTurnOptions = {},\n): XY[] {\n const { source, target } = ends;\n const share = Math.min(Math.max(finiteOr(turn.stepPosition, 0.5), 0), 1);\n const centerX = finiteOr(turn.centerX, undefined);\n const centerY = finiteOr(turn.centerY, undefined);\n const a = sideDirection(ends.sourceSide);\n const b = sideDirection(ends.targetSide);\n const out = plus(source, a, offset);\n const into = plus(target, b, offset);\n const sourceHorizontal = a.x !== 0;\n let middle: XY[];\n if (sourceHorizontal === (b.x !== 0)) {\n const horizontal = sourceHorizontal;\n const along = (p: XY) => (horizontal ? p.x : p.y);\n const across = (p: XY) => (horizontal ? p.y : p.x);\n const at = (alongValue: number, acrossValue: number): XY =>\n horizontal\n ? { x: alongValue, y: acrossValue }\n : { x: acrossValue, y: alongValue };\n const sign = horizontal ? a.x : a.y;\n const targetSign = horizontal ? b.x : b.y;\n if (sign === targetSign) {\n // the same side: out to the farther end, across, in\n const reach =\n sign > 0\n ? Math.max(along(out), along(into))\n : Math.min(along(out), along(into));\n middle = [at(reach, across(source)), at(reach, across(target))];\n } else if ((along(target) - along(source)) * sign >= 0) {\n // facing each other, the target ahead: turn halfway (or where asked), the share taken\n // between the stood-out points so that a turn near an end keeps its `offset` (halfway\n // between the handles is the same point)\n const half =\n (horizontal ? centerX : centerY) ??\n (share === 0.5\n ? between(along(source), along(target), share)\n : between(along(out), along(into), share));\n middle = [at(half, across(source)), at(half, across(target))];\n } else {\n // facing each other, the target behind: out, across halfway (or where asked), back in;\n // on one line (within a pixel), the run across is `offset` aside of both, a loop\n // instead of a line back on itself\n const half =\n (horizontal ? centerY : centerX) ??\n (Math.abs(across(out) - across(into)) < 1\n ? Math.max(across(out), across(into)) + offset\n : between(across(out), across(into), share));\n middle = [out, at(along(out), half), at(along(into), half), into];\n }\n } else {\n const corner = sourceHorizontal\n ? { x: target.x, y: source.y }\n : { x: source.x, y: target.y };\n if (\n dot(minus(corner, source), a) >= 0 &&\n dot(minus(target, corner), b) <= 0\n ) {\n middle = [corner];\n } else {\n const ahead = dot(minus(into, out), a) >= 0;\n const turn =\n ahead === sourceHorizontal\n ? { x: into.x, y: out.y }\n : { x: out.x, y: into.y };\n middle = [out, turn, into];\n }\n }\n return simplified([source, ...middle, target]);\n}\n\n/** A route without repeated points, nor corners that do not turn (three points on one line). */\nfunction simplified(points: XY[]): XY[] {\n const unique = points.filter(\n (point, i) => i === 0 || distance(point, points[i - 1] as XY) > 1e-9,\n );\n return unique.filter((point, i) => {\n const before = unique[i - 1];\n const after = unique[i + 1];\n if (!before || !after) return true;\n const cross =\n (point.x - before.x) * (after.y - point.y) -\n (point.y - before.y) * (after.x - point.x);\n // a straight run is dropped; a turn back on itself is kept (it is a corner of the route)\n return (\n Math.abs(cross) > 1e-9 ||\n dot(minus(point, before), minus(after, point)) < 0\n );\n });\n}\n\n/** The point halfway along a polyline's length. */\nexport function halfwayAlong(points: readonly XY[]): XY {\n const first = points[0] ?? { x: 0, y: 0 };\n const lengths = points\n .slice(1)\n .map((point, i) => distance(points[i] as XY, point));\n let remaining = lengths.reduce((sum, length) => sum + length, 0) / 2;\n for (let i = 0; i < lengths.length; i++) {\n const length = lengths[i] as number;\n const from = points[i] as XY;\n const to = points[i + 1] as XY;\n if (remaining <= length && length > 0) {\n const t = remaining / length;\n return {\n x: from.x + (to.x - from.x) * t,\n y: from.y + (to.y - from.y) * t,\n };\n }\n remaining -= length;\n }\n return points.at(-1) ?? first;\n}\n\n/** Path data through the route's corners, each rounded by `radius` (at most half its segments). */\nexport function roundedPath(points: readonly XY[], radius: number): string {\n const first = points[0];\n if (!first) return \"\";\n const parts = [`M${formatPoint(first)}`];\n for (let i = 1; i < points.length - 1; i++) {\n const before = points[i - 1] as XY;\n const corner = points[i] as XY;\n const after = points[i + 1] as XY;\n const r = Math.min(\n radius,\n distance(before, corner) / 2,\n distance(corner, after) / 2,\n );\n if (r <= 0) {\n parts.push(`L${formatPoint(corner)}`);\n continue;\n }\n const inLength = distance(before, corner);\n const outLength = distance(corner, after);\n const start = {\n x: corner.x - ((corner.x - before.x) / inLength) * r,\n y: corner.y - ((corner.y - before.y) / inLength) * r,\n };\n const end = {\n x: corner.x + ((after.x - corner.x) / outLength) * r,\n y: corner.y + ((after.y - corner.y) / outLength) * r,\n };\n parts.push(\n `L${formatPoint(start)}`,\n `Q${formatPoint(corner)} ${formatPoint(end)}`,\n );\n }\n const last = points.at(-1);\n if (last && points.length > 1) parts.push(`L${formatPoint(last)}`);\n return parts.join(\" \");\n}\n\n/** A smooth step edge's path (orthogonal, rounded corners) and its label point. */\nexport function smoothStepPath(options: SmoothStepPathOptions): PathResult {\n const route = orthogonalRoute(options, options.offset ?? 20, options);\n return {\n path: roundedPath(route, options.borderRadius ?? 5),\n label: halfwayAlong(route),\n };\n}\n\n/** A step edge's path (orthogonal, square corners) and its label point. */\nexport function stepPath(options: StepPathOptions): PathResult {\n return smoothStepPath({ ...options, borderRadius: 0 });\n}\n","// A straight edge: one line from end to end, its label halfway.\nimport type { XY } from \"../document/types\";\nimport { formatPoint } from \"./path-format\";\nimport type { PathResult } from \"./types\";\n\n/** Options of {@link straightPath}: its two ends (the sides do not change a straight line). */\nexport interface StraightPathOptions {\n readonly source: XY;\n readonly target: XY;\n}\n\n/** A straight edge's path and its label point (the middle of the line). */\nexport function straightPath(options: StraightPathOptions): PathResult {\n const { source, target } = options;\n return {\n path: `M${formatPoint(source)} L${formatPoint(target)}`,\n label: { x: (source.x + target.x) / 2, y: (source.y + target.y) / 2 },\n };\n}\n","// An edge as it is drawn (D9), with or without an engine: its ends at its handles' centres (or,\n// for a node with no handle for that end, the middle of its default side: its `sourcePosition` /\n// `targetPosition`, else a source leaves by the bottom and a target enters by the top), and its\n// path by its type. Pure: no DOM and nothing of the engine (the server render calls it too).\nimport type { FlowEdge, XY } from \"../document/types\";\nimport type { HandleType } from \"../state/queries\";\nimport { bezierPath } from \"./bezier-path\";\nimport { simpleBezierPath } from \"./simple-bezier-path\";\nimport { smoothStepPath, stepPath } from \"./smooth-step-path\";\nimport { straightPath } from \"./straight-path\";\nimport type { EdgePath, HandleSide, PathEnds, Rect } from \"./types\";\n\n/** The shape options of the built-in paths (the engine's `pathOptions`). */\nexport interface PathOptions {\n /** bezier: the share of the distance a control point stands out by; default 0.5 */\n readonly curvature?: number | undefined;\n /** smooth step: the corners' radius; default 5 */\n readonly borderRadius?: number | undefined;\n /** smooth step and step: how far an end stands out before turning; default 20 */\n readonly offset?: number | undefined;\n /** smooth step and step: where the turn sits between the source (0) and the target (1); default 0.5 */\n readonly stepPosition?: number | undefined;\n /** smooth step and step: the x of a vertical turn, in flow coordinates; default none */\n readonly centerX?: number | undefined;\n /** smooth step and step: the y of a horizontal turn, in flow coordinates; default none */\n readonly centerY?: number | undefined;\n}\n\n/** A handle as the edge geometry reads it: its side and, once placed, its absolute centre. */\nexport interface EdgeEndHandle {\n /** the side of its node it sits on */\n readonly side: HandleSide;\n /** its centre in absolute flow coordinates (none: the middle of its side is used) */\n readonly center: XY | undefined;\n}\n\n/** What the edge geometry reads: the engine's measured flow, or a document's declared one. */\nexport interface EdgeLookup {\n /** a node's absolute box, when its size is known */\n rect(nodeId: string): Rect | undefined;\n /** a node's handle of a type and id (the first of that type for none), placed */\n handle(\n nodeId: string,\n type: HandleType,\n handleId: string | undefined,\n ): EdgeEndHandle | undefined;\n /** the side an end at a node with no handle for it takes (its `sourcePosition` / `targetPosition`) */\n side(nodeId: string, type: HandleType): HandleSide | undefined;\n}\n\n/** The middle of a rectangle's side. */\nexport function sidePoint(rect: Rect, side: HandleSide): XY {\n switch (side) {\n case \"top\":\n return { x: rect.x + rect.width / 2, y: rect.y };\n case \"right\":\n return { x: rect.x + rect.width, y: rect.y + rect.height / 2 };\n case \"bottom\":\n return { x: rect.x + rect.width / 2, y: rect.y + rect.height };\n case \"left\":\n return { x: rect.x, y: rect.y + rect.height / 2 };\n }\n}\n\nfunction endOf(\n lookup: EdgeLookup,\n nodeId: string,\n type: HandleType,\n handleId: string | undefined,\n): { point: XY; side: HandleSide } | undefined {\n const rect = lookup.rect(nodeId);\n if (!rect) return undefined;\n const handle = lookup.handle(nodeId, type, handleId);\n if (handle?.center) return { point: handle.center, side: handle.side };\n const side =\n handle?.side ??\n lookup.side(nodeId, type) ??\n (type === \"source\" ? \"bottom\" : \"top\");\n return { point: sidePoint(rect, side), side };\n}\n\n/** An edge's ends, once both its nodes have a size. */\nexport function edgeEnds(\n edge: FlowEdge,\n lookup: EdgeLookup,\n): PathEnds | undefined {\n const source = endOf(lookup, edge.source, \"source\", edge.sourceHandle);\n const target = endOf(lookup, edge.target, \"target\", edge.targetHandle);\n return source && target\n ? {\n source: source.point,\n sourceSide: source.side,\n target: target.point,\n targetSide: target.side,\n }\n : undefined;\n}\n\n/** The path of an edge of `type` between its ends (an app's type gets the bezier). */\nexport function pathOf(\n type: string | undefined,\n ends: PathEnds,\n options: PathOptions,\n): EdgePath {\n switch (type) {\n case \"smoothstep\":\n return {\n ...ends,\n ...smoothStepPath({\n ...ends,\n borderRadius: options.borderRadius,\n offset: options.offset,\n stepPosition: options.stepPosition,\n centerX: options.centerX,\n centerY: options.centerY,\n }),\n };\n case \"step\":\n return {\n ...ends,\n ...stepPath({\n ...ends,\n offset: options.offset,\n stepPosition: options.stepPosition,\n centerX: options.centerX,\n centerY: options.centerY,\n }),\n };\n case \"straight\":\n return { ...ends, ...straightPath(ends) };\n case \"simplebezier\":\n return { ...ends, ...simpleBezierPath(ends) };\n default: {\n const { path, label } = bezierPath({\n ...ends,\n curvature: options.curvature,\n });\n return { ...ends, path, label };\n }\n }\n}\n","// Where a node stands, with or without an engine: its origin (the engine's `nodeOrigin`, or its own\n// `origin`), its absolute position through its parents and its box (`nodeBox`), from a size lookup.\n// The engine reads sizes as given, measured, then initial; the static geometry (a server render, a\n// first client render) as given, then initial. One function for both, so the two agree. Pure: no\n// DOM and nothing of the engine.\nimport type { FlowNode, XY } from \"../document/types\";\nimport type { HandleType } from \"../state/queries\";\nimport type { EdgeEndHandle } from \"./edge-geometry\";\nimport { nodeBox } from \"./rect\";\nimport type { Rect } from \"./types\";\n\n/** A node's size, in flow units. */\nexport interface NodeSize {\n readonly width: number;\n readonly height: number;\n}\n\n/** What a node's place is computed from: the nodes by id, their sizes and the flow's origin. */\nexport interface NodeLayout {\n /** a node by id */\n node(nodeId: string): FlowNode | undefined;\n /** a node's size, when it is known */\n size(node: FlowNode): NodeSize | undefined;\n /** the engine's `nodeOrigin` (none: the top-left corner) */\n readonly nodeOrigin: XY | undefined;\n}\n\nconst TOP_LEFT: XY = Object.freeze({ x: 0, y: 0 });\nconst ZERO_SIZE: NodeSize = Object.freeze({ width: 0, height: 0 });\n\n/**\n * A node's size: per dimension, the document's `width` / `height`, else the measured one, else its\n * `initialWidth` / `initialHeight` (used only until it is measured); none while a dimension is\n * unknown.\n */\nexport function nodeSize(\n node: FlowNode,\n measured?: NodeSize | undefined,\n): NodeSize | undefined {\n const width = node.width ?? (measured ? measured.width : node.initialWidth);\n const height =\n node.height ?? (measured ? measured.height : node.initialHeight);\n return width === undefined || height === undefined\n ? undefined\n : { width, height };\n}\n\n/**\n * The share of a node's size its position stands at: its own `origin`, else the flow's\n * `nodeOrigin`, for a node on the flow; the top-left corner for a child (its position is relative\n * to its parent's top-left corner, so the model's sub-flow rules hold as they are).\n */\nexport function nodeOriginOf(node: FlowNode, layout: NodeLayout): XY {\n if (node.parentId !== undefined && layout.node(node.parentId)) {\n return TOP_LEFT;\n }\n return node.origin ?? layout.nodeOrigin ?? TOP_LEFT;\n}\n\n/** A node's position in absolute flow coordinates: its parent's top-left corner plus its own. */\nexport function nodeAbsolutePosition(\n node: FlowNode,\n layout: NodeLayout,\n seen: Set<string> = new Set<string>(),\n): XY {\n seen.add(node.id);\n const parent =\n node.parentId === undefined || seen.has(node.parentId)\n ? undefined\n : layout.node(node.parentId);\n if (!parent) return node.position;\n const corner = nodeRectOf(parent, layout, seen);\n return {\n x: corner.x + node.position.x,\n y: corner.y + node.position.y,\n };\n}\n\n/** A node's absolute box (`nodeBox`: its position at its origin), its size zero until known. */\nexport function nodeRectOf(\n node: FlowNode,\n layout: NodeLayout,\n seen: Set<string> = new Set<string>(),\n): Rect {\n return nodeBox(\n nodeAbsolutePosition(node, layout, seen),\n layout.size(node) ?? ZERO_SIZE,\n nodeOriginOf(node, layout),\n );\n}\n\n/**\n * A node's handle of a type and id, by the engine's rule: with an id, the one of that type and id,\n * else the one of that id; without, the first of that type with no id, else the first of that type.\n */\nexport function matchHandle<\n H extends {\n readonly type: HandleType;\n readonly handleId: string | undefined;\n },\n>(\n handles: readonly H[],\n type: HandleType,\n handleId: string | undefined,\n): H | undefined {\n return handleId === undefined\n ? (handles.find(\n (handle) => handle.type === type && handle.handleId === undefined,\n ) ?? handles.find((handle) => handle.type === type))\n : (handles.find(\n (handle) => handle.type === type && handle.handleId === handleId,\n ) ?? handles.find((handle) => handle.handleId === handleId));\n}\n\n/**\n * A node's declared handle (`handles`) of a type and id, placed on its box `rect`: its centre is\n * the middle of its declared box (the point the engine measures for a rendered handle).\n */\nexport function declaredHandleOf(\n node: FlowNode,\n rect: Rect,\n type: HandleType,\n handleId: string | undefined,\n): EdgeEndHandle | undefined {\n const declared = node.handles;\n if (!declared || declared.length === 0) return undefined;\n const found = matchHandle(\n declared.map((handle) => ({\n handle,\n type: handle.type,\n handleId: handle.id,\n })),\n type,\n handleId,\n )?.handle;\n if (!found) return undefined;\n return {\n side: found.position,\n center: {\n x: rect.x + found.x + (found.width ?? 0) / 2,\n y: rect.y + found.y + (found.height ?? 0) / 2,\n },\n };\n}\n","// The viewport that frames a flow rectangle in a root of a given size: what `fit-view` sets and\n// what `engine.get(\"viewport-for-bounds\", …)` answers, as a pure function an app can call too (a\n// server render, a thumbnail, a saved view).\nimport type { Rect, Viewport } from \"./types\";\nimport { centeredOn, clampZoom } from \"./viewport-math\";\n\n/**\n * One side's padding: a number is a share of the root's size along it (its width for the left and\n * right, its height for the top and bottom), a `\"<n>px\"` string pixels.\n */\nexport type PaddingValue = number | `${number}px`;\n\n/**\n * The room kept free around framed bounds: one value for every side, or each side's (a side left\n * out keeps none).\n */\nexport type FitPadding =\n | PaddingValue\n | {\n readonly top?: PaddingValue | undefined;\n readonly right?: PaddingValue | undefined;\n readonly bottom?: PaddingValue | undefined;\n readonly left?: PaddingValue | undefined;\n };\n\n/** Whether a value is one side's padding: a finite number, or a `\"<n>px\"` string. */\nfunction paddingValue(value: unknown): value is PaddingValue {\n if (typeof value === \"number\") return Number.isFinite(value);\n return (\n typeof value === \"string\" &&\n /^-?(\\d+\\.?\\d*|\\.\\d+)(e[+-]?\\d+)?px$/i.test(value.trim())\n );\n}\n\n/** Whether a value is a padding {@link viewportForBounds} takes (a side's or every side's). */\nexport function isFitPadding(value: unknown): value is FitPadding {\n if (paddingValue(value)) return true;\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n return false;\n }\n const record = value as Record<string, unknown>;\n return (\n Object.keys(record).every((key) =>\n [\"top\", \"right\", \"bottom\", \"left\"].includes(key),\n ) &&\n Object.values(record).every(\n (side) => side === undefined || paddingValue(side),\n )\n );\n}\n\n/** One side's padding in pixels, along a dimension of `length` pixels. */\nfunction pixels(value: PaddingValue | undefined, length: number): number {\n if (value === undefined) return 0;\n return typeof value === \"number\"\n ? value * length\n : Number.parseFloat(value);\n}\n\n/** Options of {@link viewportForBounds}. */\nexport interface ViewportForBoundsOptions {\n /**\n * the room kept free on every side (a number: a share of the root's size), or each side's\n * (`{ top, right, bottom, left }`, a `\"<n>px\"` string in pixels); default 0.1\n */\n readonly padding?: FitPadding | undefined;\n /** the least zoom it may pick; default 0.5 */\n readonly minZoom?: number | undefined;\n /** the greatest zoom it may pick; default 2 */\n readonly maxZoom?: number | undefined;\n}\n\n/**\n * The viewport that shows `bounds` (flow coordinates) whole and centred in a root of `width` ×\n * `height` pixels, `padding` kept free on every side (or each side's: the bounds are centred in\n * what is left), its zoom between `minZoom` and `maxZoom` (a rectangle without a size gets the\n * greatest zoom, centred on it; a `maxZoom` below `minZoom` wins).\n */\nexport function viewportForBounds(\n bounds: Rect,\n width: number,\n height: number,\n options: ViewportForBoundsOptions = {},\n): Viewport {\n const padding = options.padding ?? 0.1;\n const minZoom = options.minZoom ?? 0.5;\n const maxZoom = options.maxZoom ?? 2;\n if (typeof padding !== \"number\") {\n return framedIn(bounds, width, height, padding, minZoom, maxZoom);\n }\n // the share of each dimension the bounds may take\n const room = Math.max(0, 1 - 2 * padding);\n const along = (screen: number, flow: number) =>\n flow > 0 ? (screen * room) / flow : Number.POSITIVE_INFINITY;\n const fitting = Math.min(\n along(width, bounds.width),\n along(height, bounds.height),\n );\n const zoom = clampZoom(\n Number.isFinite(fitting) ? fitting : maxZoom,\n minZoom,\n maxZoom,\n );\n return centeredOn(\n { x: bounds.x + bounds.width / 2, y: bounds.y + bounds.height / 2 },\n zoom,\n { width, height },\n );\n}\n\n/** {@link viewportForBounds} with each side's padding: the bounds centred in the room left. */\nfunction framedIn(\n bounds: Rect,\n width: number,\n height: number,\n padding: Exclude<FitPadding, number>,\n minZoom: number,\n maxZoom: number,\n): Viewport {\n const sides =\n typeof padding === \"string\"\n ? { top: padding, right: padding, bottom: padding, left: padding }\n : padding;\n const top = pixels(sides.top, height);\n const right = pixels(sides.right, width);\n const bottom = pixels(sides.bottom, height);\n const left = pixels(sides.left, width);\n const roomX = Math.max(0, width - left - right);\n const roomY = Math.max(0, height - top - bottom);\n const along = (room: number, flow: number) =>\n flow > 0 ? room / flow : Number.POSITIVE_INFINITY;\n const fitting = Math.min(\n along(roomX, bounds.width),\n along(roomY, bounds.height),\n );\n const zoom = clampZoom(\n Number.isFinite(fitting) ? fitting : maxZoom,\n minZoom,\n maxZoom,\n );\n return {\n x: left + roomX / 2 - (bounds.x + bounds.width / 2) * zoom,\n y: top + roomY / 2 - (bounds.y + bounds.height / 2) * zoom,\n zoom,\n };\n}\n","// Auto-pan (the `autoPan` engine option): while a gesture that follows the pointer (a node drag,\n// a connection, a reconnection, a selection box, a resize) has its pointer within `margin` pixels\n// of the root's edge, or past it, the viewport pans towards that edge every frame, faster nearer\n// it: no speed at `margin` pixels in, `speed` pixels a frame at the edge and beyond. The engine\n// runs the one loop (`createFlowEngine`); this is its step.\nimport type { XY } from \"../document/types\";\nimport type { Size } from \"../geometry/viewport-math\";\n\n/** The gestures auto-pan follows, each of which may be turned off alone. */\nexport type AutoPanGesture = \"node\" | \"connect\" | \"selection\" | \"resize\";\n\n/**\n * How auto-pan pans (`autoPan: { speed, margin }`), and which gestures it follows (each one left\n * out does: `{ connect: false }` keeps the view still while drawing an edge).\n */\nexport interface AutoPanOptions {\n /** a node drag; default true */\n node?: boolean | undefined;\n /** a connection or a reconnection; default true */\n connect?: boolean | undefined;\n /** a selection box; default true */\n selection?: boolean | undefined;\n /** a resize; default true */\n resize?: boolean | undefined;\n /** the pixels a frame it pans with the pointer at the edge (or past it); default 10 */\n speed?: number | undefined;\n /** how near the edge (in pixels) the pointer starts it; default 30 */\n margin?: number | undefined;\n}\n\nconst DEFAULT_SPEED = 10;\nconst DEFAULT_MARGIN = 30;\n\n/** Whether auto-pan follows a gesture of a kind (`true`: one that names no kind) under `option`. */\nexport function autoPans(\n option: boolean | AutoPanOptions | undefined,\n gesture: boolean | AutoPanGesture | undefined,\n): boolean {\n if (gesture === undefined || gesture === false || option === false)\n return false;\n if (gesture === true || option === true || option === undefined)\n return true;\n return option[gesture] !== false;\n}\n\n/**\n * The viewport offset of one auto-pan frame (zero when it does not pan) for a pointer at `point`\n * (relative to the root's top-left corner) in a root of `size`: positive towards the right and the\n * bottom, so a pointer near the left edge moves the flow right and shows what is left of the view.\n */\nexport function autoPanOffset(\n point: XY,\n size: Size,\n option: boolean | AutoPanOptions | undefined,\n): XY {\n if (option === false || size.width <= 0 || size.height <= 0) {\n return { x: 0, y: 0 };\n }\n const own = option === true || option === undefined ? {} : option;\n const speed = Math.max(0, own.speed ?? DEFAULT_SPEED);\n const margin = Math.max(0, own.margin ?? DEFAULT_MARGIN);\n const axis = (at: number, length: number) => {\n const near = (gap: number) =>\n gap <= 0 || margin === 0 ? 1 : Math.max(0, 1 - gap / margin);\n if (at < margin) return speed * near(at);\n if (at > length - margin) return -speed * near(length - at);\n return 0;\n };\n // `+ 0` drops the sign of a zero\n return {\n x: axis(point.x, size.width) + 0,\n y: axis(point.y, size.height) + 0,\n };\n}\n","// The Background's pattern at the current viewport: one tile of an SVG pattern on the screen,\n// its marks on the flow's grid (every `gap` flow units from `offset`), scaled by the zoom.\nimport { formatNumber } from \"../geometry/path-format\";\nimport type { Viewport } from \"../geometry/types\";\nimport type { BackgroundPattern, BackgroundPatternPayload } from \"./verbs\";\n\nfunction pair(\n value: number | readonly [number, number] | undefined,\n fallback: number,\n): [number, number] {\n if (value === undefined) return [fallback, fallback];\n return typeof value === \"number\" ? [value, value] : [value[0], value[1]];\n}\n\n/** `value` modulo `period`, in `[0, period)`. */\nfunction wrap(value: number, period: number): number {\n return period > 0 ? ((value % period) + period) % period : 0;\n}\n\n/** The tile of a background pattern (its marks at the tile's centre, the tile shifted to match). */\nexport function backgroundPattern(\n viewport: Viewport,\n payload: BackgroundPatternPayload,\n): BackgroundPattern {\n const variant = payload.variant ?? \"dots\";\n const [gapX, gapY] = pair(payload.gap, 20);\n const [offsetX, offsetY] = pair(payload.offset, 0);\n const { zoom } = viewport;\n const width = gapX * zoom;\n const height = gapY * zoom;\n const cx = width / 2;\n const cy = height / 2;\n // a mark sits at the tile's centre: the tile starts half a gap before a grid point\n const x = wrap(viewport.x + offsetX * zoom - cx, width);\n const y = wrap(viewport.y + offsetY * zoom - cy, height);\n const f = formatNumber;\n if (variant === \"dots\") {\n const size = payload.size ?? 1;\n return {\n variant,\n x,\n y,\n width,\n height,\n dot: { cx, cy, r: (size * zoom) / 2 },\n path: undefined,\n strokeWidth: 0,\n };\n }\n if (variant === \"lines\") {\n return {\n variant,\n x,\n y,\n width,\n height,\n dot: undefined,\n path: `M${f(cx)},0 V${f(height)} M0,${f(cy)} H${f(width)}`,\n strokeWidth: payload.size ?? 1,\n };\n }\n const arm = ((payload.size ?? 6) * zoom) / 2;\n return {\n variant,\n x,\n y,\n width,\n height,\n dot: undefined,\n path: `M${f(cx - arm)},${f(cy)} H${f(cx + arm)} M${f(cx)},${f(cy - arm)} V${f(cy + arm)}`,\n strokeWidth: 1,\n };\n}\n","// The DOM the engine reaches, always through an element: its document and window (an iframe's or\n// a popup's own, never the global ones), and what a press, a key or the wheel hit, read from the\n// part attributes (D11).\nimport {\n DIRECTION_ATTRIBUTE,\n DRAG_HANDLE_ATTRIBUTE,\n END_ATTRIBUTE,\n ID_ATTRIBUTE,\n NO_GESTURE_ATTRIBUTE,\n PART_ATTRIBUTE,\n POSITION_ATTRIBUTE,\n} from \"../attributes/part-attributes\";\nimport type { FlowHandle, PressTarget } from \"./adapter\";\n\n/** The window an element renders in, if any (never the global one). */\nexport function viewOf(\n element: Element | null | undefined,\n): Window | undefined {\n return element?.ownerDocument?.defaultView ?? undefined;\n}\n\n/** An event target as an element (a text node's parent), if it is one. */\nexport function asElement(target: EventTarget | null): Element | undefined {\n if (target === null || typeof target !== \"object\") return undefined;\n const node = target as Node;\n if (node.nodeType === 1) return node as Element;\n return node.parentElement ?? undefined;\n}\n\n/** What a press inside a node never starts a gesture from: its own controls. */\nconst NO_GESTURE = [\n \"input\",\n \"textarea\",\n \"select\",\n \"option\",\n \"button\",\n \"a[href]\",\n '[contenteditable]:not([contenteditable=\"false\"])',\n `[${NO_GESTURE_ATTRIBUTE}]`,\n].join(\", \");\n\n/** The parts that are the flow's background: a press there pans, or draws a selection box. */\nconst PANE_PARTS = new Set([\n \"root\",\n \"viewport\",\n \"background\",\n \"nodes\",\n \"edges\",\n \"edges-layer\",\n]);\n\nconst EDGE_PARTS = new Set([\"edge\", \"edge-path\", \"edge-label\"]);\n\nconst MINIMAP_PARTS = new Set([\"minimap\", \"minimap-node\", \"minimap-mask\"]);\n\nconst OTHER: PressTarget = { kind: \"other\", element: undefined };\n\n/** The nearest element with a part attribute, from `element` up to `root`. */\nfunction partOf(element: Element, root: Element): Element | undefined {\n const part = element.closest(`[${PART_ATTRIBUTE}]`);\n return part && root.contains(part) ? part : undefined;\n}\n\nfunction idOf(element: Element | null | undefined): string | undefined {\n return element?.getAttribute(ID_ATTRIBUTE) ?? undefined;\n}\n\nfunction nodeIdAround(element: Element, root: Element): string | undefined {\n const node = element.closest(`[${PART_ATTRIBUTE}=\"node\"]`);\n return node && root.contains(node) ? idOf(node) : undefined;\n}\n\n/**\n * Whether a press at `element` on a node (`node`, its part) is outside the node's drag handle: the\n * node holds one (`data-flow-drag-handle`, not inside another node's part) and the press is not in\n * it.\n */\nfunction outsideDragHandle(element: Element, node: Element): boolean {\n const own = (handle: Element) =>\n handle.closest(`[${PART_ATTRIBUTE}=\"node\"]`) === node;\n const pressed = element.closest(`[${DRAG_HANDLE_ATTRIBUTE}]`);\n if (pressed && node.contains(pressed) && own(pressed)) return false;\n return [...node.querySelectorAll(`[${DRAG_HANDLE_ATTRIBUTE}]`)].some(own);\n}\n\n/** A resize handle's own direction, when its `data-direction` names one. */\nfunction directionOf(\n value: string | null,\n): \"horizontal\" | \"vertical\" | undefined {\n return value === \"horizontal\" || value === \"vertical\" ? value : undefined;\n}\n\n/** What `target` (an event's) is in the flow under `root`. */\nexport function pressTargetOf(\n root: Element,\n target: EventTarget | null,\n handleOf: (element: Element) => FlowHandle | undefined,\n): PressTarget {\n const element = asElement(target);\n if (!element || !root.contains(element)) return OTHER;\n const part = partOf(element, root);\n if (!part) return OTHER;\n // a control inside a part (a node's field) keeps its own presses\n const control = element.closest(NO_GESTURE);\n if (control && part.contains(control) && control !== part) {\n return { kind: \"other\", element: part };\n }\n const name = part.getAttribute(PART_ATTRIBUTE) ?? \"\";\n if (PANE_PARTS.has(name)) return { kind: \"pane\", element: part };\n if (name === \"node\") {\n return outsideDragHandle(element, part)\n ? {\n kind: \"node\",\n element: part,\n nodeId: idOf(part),\n outsideDragHandle: true,\n }\n : { kind: \"node\", element: part, nodeId: idOf(part) };\n }\n if (name === \"handle\") {\n const handle = handleOf(part);\n return handle\n ? { kind: \"handle\", element: part, nodeId: handle.nodeId, handle }\n : { kind: \"other\", element: part };\n }\n if (name === \"resize-handle\") {\n return {\n kind: \"resize-handle\",\n element: part,\n nodeId: nodeIdAround(part, root),\n position: part.getAttribute(POSITION_ATTRIBUTE) ?? undefined,\n direction: directionOf(part.getAttribute(DIRECTION_ATTRIBUTE)),\n };\n }\n if (name === \"reconnect-anchor\") {\n const end = part.getAttribute(END_ATTRIBUTE);\n return {\n kind: \"edge\",\n element: part,\n edgeId: idOf(part),\n end: end === \"source\" || end === \"target\" ? end : undefined,\n };\n }\n if (EDGE_PARTS.has(name)) {\n const edge =\n name === \"edge-label\"\n ? part\n : (part.closest(`[${PART_ATTRIBUTE}=\"edge\"]`) ?? part);\n return {\n kind: \"edge\",\n element: edge,\n edgeId: idOf(edge) ?? idOf(part),\n };\n }\n if (name === \"nodes-selection\")\n return { kind: \"nodes-selection\", element: part };\n if (MINIMAP_PARTS.has(name)) {\n const minimap = part.closest(`[${PART_ATTRIBUTE}=\"minimap\"]`) ?? part;\n return { kind: \"minimap\", element: minimap };\n }\n return { kind: \"other\", element: part };\n}\n","// Where an edge's toolbar goes (EdgeToolbar geometry): at a point of its drawn path on the screen\n// (its label point, or one of its ends) or at a flow point given, outside the zoom, so it keeps its\n// size whatever the zoom, centred on that point (or aligned by its start or end) and moved by a\n// screen offset.\n\nimport type { EdgePath, Viewport } from \"../geometry/types\";\nimport { toScreen } from \"../geometry/viewport-math\";\nimport type { EdgeToolbarPayload, EdgeToolbarPosition } from \"./verbs\";\n\n/** A toolbar's anchor for an edge's drawn path. */\nexport function edgeToolbarPosition(\n path: EdgePath,\n viewport: Viewport,\n payload: EdgeToolbarPayload,\n): EdgeToolbarPosition {\n const at =\n payload.point ??\n (payload.position === \"source\"\n ? path.source\n : payload.position === \"target\"\n ? path.target\n : path.label);\n const point = toScreen(viewport, at);\n return {\n x: point.x + (payload.offset?.x ?? 0),\n y: point.y + (payload.offset?.y ?? 0),\n anchorX: share(payload.alignX),\n anchorY: share(payload.alignY),\n };\n}\n\n/** The share of the toolbar's size an alignment puts at the point. */\nfunction share(align: EdgeToolbarPayload[\"alignX\"]): number {\n return align === \"start\" ? 0 : align === \"end\" ? 1 : 0.5;\n}\n","// A uniform grid of rectangles by id (Epic #61): each rectangle is filed in the square cells it\n// touches, so the rectangles meeting an area are found from that area's cells instead of a scan of\n// them all. A rectangle spanning too many cells (a large group, a long edge), or one too far out\n// for the cell keys, is kept in a list every query checks. A query whose area covers more cells\n// than there are rectangles scans the rectangles instead. Simpler than an R-tree and enough for a\n// flow's nodes and edges, which are mostly small and spread out. Pure: no DOM and nothing of the\n// engine.\nimport { overlaps } from \"./rect\";\nimport type { Rect } from \"./types\";\n\n/** The side of a cell, in the rectangles' units, unless one is given. */\nexport const GRID_CELL = 256;\n\n/** The most cells a rectangle is filed in; a larger one is kept in the list every query checks. */\nconst MOST_CELLS = 64;\n/** Cell coordinates stay within ±2^20, so a cell's key (both coordinates) is an exact number. */\nconst REACH = 2 ** 20;\n\ninterface Entry {\n readonly id: string;\n readonly rect: Rect;\n /** the cells it is filed in (none: it is in the large list) */\n readonly cells: readonly number[] | undefined;\n /** the last query that took it (a rectangle in several cells is taken once) */\n seen: number;\n}\n\n/**\n * Rectangles by id, queried by area: `query(area)` gives the ids of those that meet it, touching\n * included (as `overlaps`), in no given order.\n */\nexport class SpatialGrid {\n private readonly cell: number;\n private readonly entries = new Map<string, Entry>();\n private readonly cells = new Map<number, Set<Entry>>();\n private readonly large = new Set<Entry>();\n private queries = 0;\n\n constructor(cell: number = GRID_CELL) {\n this.cell = cell > 0 && Number.isFinite(cell) ? cell : GRID_CELL;\n }\n\n /** How many rectangles it holds. */\n get size(): number {\n return this.entries.size;\n }\n\n /** Whether it holds a rectangle of this id. */\n has(id: string): boolean {\n return this.entries.has(id);\n }\n\n /** The rectangle of an id, as it was filed. */\n get(id: string): Rect | undefined {\n return this.entries.get(id)?.rect;\n }\n\n /** Files (or moves) the rectangle of an id. */\n set(id: string, rect: Rect): void {\n const previous = this.entries.get(id);\n if (\n previous &&\n previous.rect.x === rect.x &&\n previous.rect.y === rect.y &&\n previous.rect.width === rect.width &&\n previous.rect.height === rect.height\n ) {\n return;\n }\n if (previous) this.unfile(previous);\n const cells = this.cellsOf(rect);\n const entry: Entry = { id, rect, cells, seen: 0 };\n this.entries.set(id, entry);\n if (!cells) {\n this.large.add(entry);\n return;\n }\n for (const key of cells) {\n let set = this.cells.get(key);\n if (!set) {\n set = new Set();\n this.cells.set(key, set);\n }\n set.add(entry);\n }\n }\n\n /** Forgets the rectangle of an id. */\n delete(id: string): void {\n const entry = this.entries.get(id);\n if (!entry) return;\n this.entries.delete(id);\n this.unfile(entry);\n }\n\n /** Forgets every rectangle. */\n clear(): void {\n this.entries.clear();\n this.cells.clear();\n this.large.clear();\n }\n\n /** The ids of the rectangles that meet `area` (touching counts), in no given order. */\n query(area: Rect): string[] {\n const found: string[] = [];\n const range = this.rangeOf(area);\n const count = range\n ? (range.x1 - range.x0 + 1) * (range.y1 - range.y0 + 1)\n : Number.POSITIVE_INFINITY;\n if (!range || count > this.entries.size) {\n for (const entry of this.entries.values()) {\n if (overlaps(entry.rect, area)) found.push(entry.id);\n }\n return found;\n }\n const stamp = ++this.queries;\n const take = (entry: Entry) => {\n if (entry.seen === stamp) return;\n entry.seen = stamp;\n if (overlaps(entry.rect, area)) found.push(entry.id);\n };\n for (let x = range.x0; x <= range.x1; x++) {\n for (let y = range.y0; y <= range.y1; y++) {\n const set = this.cells.get(keyOf(x, y));\n if (set) for (const entry of set) take(entry);\n }\n }\n for (const entry of this.large) take(entry);\n return found;\n }\n\n /** Every id it holds, in filing order. */\n ids(): IterableIterator<string> {\n return this.entries.keys();\n }\n\n private unfile(entry: Entry): void {\n if (!entry.cells) {\n this.large.delete(entry);\n return;\n }\n for (const key of entry.cells) {\n const set = this.cells.get(key);\n if (!set) continue;\n set.delete(entry);\n if (set.size === 0) this.cells.delete(key);\n }\n }\n\n /** The cell range of a rectangle; none when it is not finite or out of the keys' reach. */\n private rangeOf(\n rect: Rect,\n ): { x0: number; y0: number; x1: number; y1: number } | undefined {\n const x0 = Math.floor(rect.x / this.cell);\n const y0 = Math.floor(rect.y / this.cell);\n const x1 = Math.floor((rect.x + rect.width) / this.cell);\n const y1 = Math.floor((rect.y + rect.height) / this.cell);\n if (\n !Number.isFinite(x0) ||\n !Number.isFinite(y0) ||\n !Number.isFinite(x1) ||\n !Number.isFinite(y1) ||\n x1 < x0 ||\n y1 < y0 ||\n x0 < -REACH ||\n y0 < -REACH ||\n x1 >= REACH ||\n y1 >= REACH\n ) {\n return undefined;\n }\n return { x0, y0, x1, y1 };\n }\n\n /** The cells a rectangle is filed in; none when it goes to the large list. */\n private cellsOf(rect: Rect): number[] | undefined {\n const range = this.rangeOf(rect);\n if (!range) return undefined;\n const count = (range.x1 - range.x0 + 1) * (range.y1 - range.y0 + 1);\n if (count > MOST_CELLS) return undefined;\n const cells: number[] = [];\n for (let x = range.x0; x <= range.x1; x++) {\n for (let y = range.y0; y <= range.y1; y++) cells.push(keyOf(x, y));\n }\n return cells;\n }\n}\n\n/** A cell's key: both coordinates in one exact number. */\nfunction keyOf(x: number, y: number): number {\n return (x + REACH) * 2 * REACH + (y + REACH);\n}\n","// The stacking order of nodes and edges, with or without an engine: each one's stack value by the\n// `zIndexMode`, the edges' drawing order, and the render layers that let an edge stand above nodes\n// (`render-layers`). Pure: no DOM and nothing of the engine.\nimport type { FlowEdge, FlowNode } from \"../document/types\";\n\n/**\n * How the stack values are worked out:\n * - `\"basic\"`: nodes by `zIndex` (a selected one raised with `elevateNodesOnSelect`, a child above\n * its parent), edges by `zIndex` (a selected one raised with `elevateEdgesOnSelect`), edges\n * always below the nodes;\n * - `\"auto\"` (the default): the same for nodes; an edge stands at least as high as its ends when\n * one of them is a child, and a selected one is raised (`elevateEdgesOnSelect` defaults to true),\n * so it may be drawn above nodes;\n * - `\"manual\"`: only the given `zIndex` values count.\n */\nexport type ZIndexMode = \"basic\" | \"auto\" | \"manual\";\n\n/** The options the stack values read. */\nexport interface ZOrderOptions {\n /** how stack values are worked out; default `\"auto\"` */\n readonly zIndexMode?: ZIndexMode | undefined;\n /** a selected node, and its children with it, is raised; default true */\n readonly elevateNodesOnSelect?: boolean | undefined;\n /** a selected edge is raised; default false in `\"basic\"`, true in `\"auto\"` */\n readonly elevateEdgesOnSelect?: boolean | undefined;\n}\n\n/** What a selected node (with `elevateNodesOnSelect`) or edge (`elevateEdgesOnSelect`) is raised by. */\nexport const SELECTED_RAISE = 10_000;\n\n/** A stacking value from a document's `zIndex` (anything but a finite number counts as 0). */\nfunction zOf(value: unknown): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : 0;\n}\n\n/** A node's own value: its `zIndex`, raised when selected (with `elevateNodesOnSelect`). */\nfunction ownValue(\n node: FlowNode,\n options: ZOrderOptions,\n raise: boolean,\n): number {\n const raised =\n raise &&\n node.selected === true &&\n (options.elevateNodesOnSelect ?? true);\n return zOf(node.zIndex) + (raised ? SELECTED_RAISE : 0);\n}\n\n/**\n * A node's stack value: in `\"manual\"` its `zIndex`; otherwise its own, always above its parent's.\n * A selected node is raised, and its descendants with it; `raiseSelf: false` leaves out the node's\n * own selection raise only (its ancestors' still counts).\n */\nexport function nodeStackValue(\n node: FlowNode,\n nodeById: (nodeId: string) => FlowNode | undefined,\n options: ZOrderOptions,\n raiseSelf = true,\n): number {\n if (options.zIndexMode === \"manual\") return zOf(node.zIndex);\n // most nodes have no parent: no chain to walk\n if (node.parentId === undefined) return ownValue(node, options, raiseSelf);\n const chain: FlowNode[] = [];\n const seen = new Set<string>();\n for (\n let at: FlowNode | undefined = node;\n at !== undefined && !seen.has(at.id);\n at = at.parentId === undefined ? undefined : nodeById(at.parentId)\n ) {\n seen.add(at.id);\n chain.push(at);\n }\n let z: number | undefined;\n for (const at of chain.reverse()) {\n const own = ownValue(at, options, at !== node || raiseSelf);\n z = z === undefined ? own : Math.max(own, z + 1);\n }\n return z ?? 0;\n}\n\n/**\n * An edge's stack value: in `\"manual\"` its `zIndex`; in `\"basic\"` its `zIndex`, raised when\n * selected with `elevateEdgesOnSelect` (default false); in `\"auto\"`, at least its ends' node values\n * (without their own selection raise, with their ancestors') when one of them is a child, raised when selected with\n * `elevateEdgesOnSelect` (default true).\n */\nexport function edgeStackValue(\n edge: FlowEdge,\n nodeById: (nodeId: string) => FlowNode | undefined,\n options: ZOrderOptions,\n): number {\n const mode = options.zIndexMode ?? \"auto\";\n const own = zOf(edge.zIndex);\n if (mode === \"manual\") return own;\n const auto = mode === \"auto\";\n let value = own;\n if (auto) {\n const ends = [nodeById(edge.source), nodeById(edge.target)].filter(\n (node): node is FlowNode => node !== undefined,\n );\n const nested = ends.some(\n (node) =>\n node.parentId !== undefined &&\n nodeById(node.parentId) !== undefined,\n );\n if (nested) {\n for (const node of ends) {\n value = Math.max(\n value,\n nodeStackValue(node, nodeById, options, false),\n );\n }\n }\n }\n const raised =\n edge.selected === true && (options.elevateEdgesOnSelect ?? auto);\n return value + (raised ? SELECTED_RAISE : 0);\n}\n\n/** Items in drawing order: by their value, their given order among equals. */\nexport function drawingOrder<E>(\n items: readonly E[],\n value: (item: E) => number,\n): E[] {\n return items\n .map((item, i) => ({ item, i, z: value(item) }))\n .sort((a, b) => a.z - b.z || a.i - b.i)\n .map(({ item }) => item);\n}\n\n/**\n * One level of the drawing (`render-layers`): its edges, drawn above the nodes of the levels\n * below it and below its own nodes.\n */\nexport interface RenderLayer {\n /** its place, 0 the lowest */\n readonly level: number;\n /**\n * the structural `z-index` of its edges' layer, in the viewport's stacking context; none with\n * a single level (today's DOM: the edges below the nodes)\n */\n readonly zIndex: number | undefined;\n /** the shown nodes of this level, in the document's order */\n readonly nodeIds: readonly string[];\n /** the edges of this level, in drawing order */\n readonly edgeIds: readonly string[];\n}\n\n/** A node or an edge with its stack value. */\nexport interface Stacked {\n readonly id: string;\n readonly value: number;\n}\n\n/** The render layers and, with more than one, each node's structural `z-index`. */\nexport interface Layering {\n readonly layers: readonly RenderLayer[];\n /** each layered node's structural `z-index`; none with a single level (its stack value is) */\n readonly zIndexes: ReadonlyMap<string, number> | undefined;\n}\n\n/**\n * The node side of the render layers for a set of thresholds (`layerThresholds`): each level's\n * shown nodes and its edges' layer `z-index`, and each node's structural `z-index` with several\n * levels. It holds no edge: a change of the drawn edges that keeps the thresholds keeps it.\n */\nexport interface NodeLevels {\n /** the edge values that start a level, ascending (none: one level) */\n readonly thresholds: readonly number[];\n /** each level's shown nodes, in the document's order */\n readonly nodeIds: readonly (readonly string[])[];\n /** each level's edges layer `z-index` (none with a single level) */\n readonly zIndex: readonly (number | undefined)[];\n /** each node's structural `z-index`; none with a single level */\n readonly zIndexes: ReadonlyMap<string, number> | undefined;\n}\n\n/** The distinct edge values above the lowest node value, ascending: each starts a level. */\nexport function layerThresholds(\n lowest: number,\n edges: readonly Stacked[],\n): number[] {\n return [\n ...new Set(\n edges.map((edge) => edge.value).filter((value) => value > lowest),\n ),\n ].sort((a, b) => a - b);\n}\n\n/**\n * The nodes' levels for `thresholds`: a node's level is how many thresholds are at or below its\n * value; the ranks run level 0's edges, level 0's nodes by value, level 1's edges, …, each rank r\n * of M mapped to r - M (negative). No threshold: one level of every node.\n */\nexport function nodeLevels(\n nodes: readonly Stacked[],\n thresholds: readonly number[],\n): NodeLevels {\n if (thresholds.length === 0) {\n return {\n thresholds,\n nodeIds: [Object.freeze(nodes.map((node) => node.id))],\n zIndex: [undefined],\n zIndexes: undefined,\n };\n }\n const nodeLevel = (value: number) =>\n thresholds.filter((threshold) => threshold <= value).length;\n const count = thresholds.length + 1;\n const nodeIds: string[][] = Array.from({ length: count }, () => []);\n const valuesOf: Set<number>[] = Array.from(\n { length: count },\n () => new Set<number>(),\n );\n for (const node of nodes) {\n const level = nodeLevel(node.value);\n nodeIds[level]?.push(node.id);\n valuesOf[level]?.add(node.value);\n }\n // the ranks: each level's edges, then its nodes by value\n const edgeRank: number[] = [];\n const nodeRank = new Map<string, number>();\n let rank = 0;\n for (let level = 0; level < count; level++) {\n edgeRank.push(rank++);\n for (const value of [...(valuesOf[level] ?? [])].sort((a, b) => a - b))\n nodeRank.set(`${level}:${value}`, rank++);\n }\n const total = rank;\n const zIndexes = new Map<string, number>();\n for (const node of nodes) {\n const key = `${nodeLevel(node.value)}:${node.value}`;\n zIndexes.set(node.id, (nodeRank.get(key) ?? 0) - total);\n }\n return {\n thresholds,\n nodeIds: Array.from({ length: count }, (_, level) =>\n Object.freeze(nodeIds[level] ?? []),\n ),\n zIndex: Array.from(\n { length: count },\n (_, level) => (edgeRank[level] ?? 0) - total,\n ),\n zIndexes,\n };\n}\n\n/**\n * The render layers of the nodes' levels and the drawn edges (in drawing order): an edge of value\n * T[j-1] is in level j, any other in level 0.\n */\nexport function layersOf(\n levels: NodeLevels,\n edges: readonly Stacked[],\n): Layering {\n const count = levels.nodeIds.length;\n const levelOf = new Map(\n levels.thresholds.map((threshold, i) => [threshold, i + 1]),\n );\n const edgeIds: string[][] = Array.from({ length: count }, () => []);\n for (const edge of edges)\n edgeIds[levelOf.get(edge.value) ?? 0]?.push(edge.id);\n return {\n layers: Object.freeze(\n Array.from({ length: count }, (_, level) =>\n Object.freeze({\n level,\n zIndex: levels.zIndex[level],\n nodeIds: levels.nodeIds[level] ?? Object.freeze([]),\n edgeIds: Object.freeze(edgeIds[level] ?? []),\n }),\n ),\n ),\n zIndexes: levels.zIndexes,\n };\n}\n\n/**\n * Splits the shown nodes and the drawn edges (in drawing order) into levels. In `\"basic\"`, or when\n * no edge stands above the lowest node, one level. Otherwise each distinct edge value above the\n * lowest node value starts a level: its edges are drawn above the nodes whose value is below it,\n * and below the others (an edge at a node's value stays below it). The structural `z-index` values\n * are then ranks, negative, so what the app draws after the layers stays above them.\n */\nexport function renderLayers(\n nodes: readonly Stacked[],\n edges: readonly Stacked[],\n mode: ZIndexMode = \"auto\",\n): Layering {\n if (mode === \"basic\" || nodes.length === 0) {\n return layersOf(nodeLevels(nodes, []), edges);\n }\n const lowest = nodes.reduce(\n (least, node) => Math.min(least, node.value),\n Number.POSITIVE_INFINITY,\n );\n return layersOf(nodeLevels(nodes, layerThresholds(lowest, edges)), edges);\n}\n","// The engine's geometry, cached (Epic #61, Issue #59): each node's box, size and flags, each edge's\n// ends and path, two uniform grids (the shown nodes of known size, the drawable edges by the box\n// of their ends) and the lists built from them (`visible-nodes`, `visible-edges`, `drawn-edges`,\n// `render-layers`). It follows the document by identity: a read first syncs (the node and edge\n// lists compared item by item with the last ones seen, the measurements' touched nodes taken, the\n// options compared), and recomputes only the nodes that changed, their descendants (a child stands\n// in its parent) and the edges at any of them. So a viewport step costs a grid query, and a drag\n// step the moved nodes and their edges. A list keeps its array while its content is unchanged.\n// Everything it gives equals a from-scratch computation (tests/engine/geometry-equivalence.test.ts).\nimport type { FlowEdge, FlowNode, XY } from \"../document/types\";\nimport {\n type EdgeEndHandle,\n edgeEnds,\n type PathOptions,\n pathOf,\n} from \"../geometry/edge-geometry\";\nimport {\n declaredHandleOf,\n matchHandle,\n type NodeLayout,\n nodeRectOf,\n nodeSize,\n} from \"../geometry/node-layout\";\nimport { boundsOf, contains, sharesArea } from \"../geometry/rect\";\nimport { SpatialGrid } from \"../geometry/spatial-grid\";\nimport type { EdgePath, PathEnds, Rect } from \"../geometry/types\";\nimport {\n drawingOrder,\n edgeStackValue,\n type Layering,\n layersOf,\n layerThresholds,\n type NodeLevels,\n nodeLevels,\n nodeStackValue,\n type Stacked,\n type ZIndexMode,\n} from \"../geometry/z-order\";\nimport type { FlowModel } from \"../model/create-flow-model\";\nimport type { HandleType } from \"../state/queries\";\nimport { replacedSince } from \"../state/replaced-items\";\nimport type { FlowHandle } from \"./adapter\";\nimport type { Measurements } from \"./measurements\";\n\n/** The engine options the geometry reads. */\nexport interface GeometryOptions {\n readonly nodeOrigin?: XY | undefined;\n readonly pathOptions?: PathOptions | undefined;\n readonly zIndexMode?: ZIndexMode | undefined;\n readonly elevateNodesOnSelect?: boolean | undefined;\n readonly elevateEdgesOnSelect?: boolean | undefined;\n}\n\n/** What the geometry reads: the model's document, the measurements and the engine's options. */\nexport interface GeometrySource {\n readonly model: FlowModel;\n readonly measurements: Measurements;\n options(): GeometryOptions;\n}\n\n/** Whether the shown nodes are sized and measured (`ready`, the fit on init). */\nexport interface Readiness {\n /** how many nodes are shown */\n readonly shown: number;\n /** every shown node has a size (given, measured or initial) */\n readonly sized: boolean;\n /** every shown node is measured or given its size (`node-measured`) */\n readonly measured: boolean;\n}\n\ninterface NodeEntry {\n readonly node: FlowNode;\n /** its absolute box, its size zero until known (`node-rect-by`) */\n readonly box: Rect;\n /** its size is known: given, measured or initial */\n readonly known: boolean;\n /** its size is measured or given (`node-measured`) */\n readonly measured: boolean;\n /** it is not hidden */\n readonly shown: boolean;\n}\n\ninterface EdgeEntry {\n readonly edge: FlowEdge;\n /** its ends, once both its nodes have a size */\n readonly ends: PathEnds | undefined;\n /** it is drawn (not hidden, its nodes shown and sized) */\n readonly drawable: boolean;\n /** its path, built when first read for the current path options */\n path: EdgePath | undefined;\n pathVersion: number;\n}\n\ninterface Memo<K, V> {\n readonly key: K;\n readonly value: V;\n}\n\nconst EMPTY: readonly never[] = Object.freeze([]);\n\n/** Whether a node's change moves its stack value or its place in the drawing (not its geometry). */\nfunction stackChanged(a: FlowNode, b: FlowNode): boolean {\n return (\n a.hidden !== b.hidden ||\n a.zIndex !== b.zIndex ||\n a.selected !== b.selected ||\n a.parentId !== b.parentId\n );\n}\n\n/** The same items, in the same order. */\nfunction sameItems<V>(a: readonly V[], b: readonly V[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;\n return true;\n}\n\n/** Shallow equality of two option records (path options), absent ones equal. */\nfunction sameRecord(a: object | undefined, b: object | undefined): boolean {\n if (a === b) return true;\n const left: Readonly<Record<string, unknown>> = { ...a };\n const right: Readonly<Record<string, unknown>> = { ...b };\n const keys = new Set([...Object.keys(left), ...Object.keys(right)]);\n for (const key of keys) if (left[key] !== right[key]) return false;\n return true;\n}\n\n/** The engine's cached geometry: see the file's header. */\nexport class EngineGeometry {\n private readonly source: GeometrySource;\n private nodes: readonly FlowNode[] = EMPTY;\n private edges: readonly FlowEdge[] = EMPTY;\n private readonly nodeIndex = new Map<string, number>();\n private readonly edgeIndex = new Map<string, number>();\n private readonly nodeEntries = new Map<string, NodeEntry>();\n private readonly edgeEntries = new Map<string, EdgeEntry>();\n /** each parent id's children ids */\n private readonly children = new Map<string, Set<string>>();\n /** each node id's edges (either end) */\n private readonly edgesAt = new Map<string, Set<string>>();\n /** the shown nodes of known size, by their box */\n private readonly nodeGrid = new SpatialGrid();\n /** the drawable edges, by the box of their ends */\n private readonly edgeGrid = new SpatialGrid();\n /** the shown nodes of unknown size (always in view) */\n private readonly unsized = new Set<string>();\n private shownCount = 0;\n private unsizedCount = 0;\n private unmeasuredCount = 0;\n private seenOptions: GeometryOptions | undefined;\n private origin: { x: number; y: number } | undefined;\n private pathOptions: PathOptions | undefined;\n private stackOptions = \"\";\n /** the whole geometry is to be recomputed (the first read, an origin change) */\n private stale = true;\n /** bumped when stack values or the drawn edges' membership may change */\n private orderVersion = 0;\n /** bumped when a node's box may change */\n private shapeVersion = 0;\n /** bumped when the path options change */\n private pathVersion = 0;\n /** bumped when an edge's entry may change */\n private edgeVersion = 0;\n /** the view and versions the last `visible-nodes` / `visible-edges` were worked out for */\n private visibleNodesKey = \"\";\n private visibleEdgesKey = \"\";\n private readonly nodeValues = new Map<\n string,\n { version: number; value: number }\n >();\n private readonly edgeValues = new Map<\n string,\n { version: number; value: number }\n >();\n private shownMemo:\n | Memo<readonly FlowNode[], readonly FlowNode[]>\n | undefined;\n private drawableMemo:\n | Memo<readonly [readonly FlowEdge[], number], readonly FlowEdge[]>\n | undefined;\n private drawnMemo:\n | Memo<readonly [readonly FlowEdge[], number], readonly FlowEdge[]>\n | undefined;\n private nodePartMemo:\n | Memo<\n number,\n {\n readonly stacked: readonly Stacked[];\n readonly lowest: number;\n }\n >\n | undefined;\n private levelsMemo: Memo<readonly [object, string], NodeLevels> | undefined;\n private layeringMemo:\n | Memo<readonly [object, readonly FlowEdge[], ZIndexMode], Layering>\n | undefined;\n private boundsMemo: Memo<number, Rect | undefined> | undefined;\n private lastVisibleNodes: readonly FlowNode[] = EMPTY;\n private lastVisibleEdges: readonly FlowEdge[] = EMPTY;\n private lastDrawn: readonly FlowEdge[] = EMPTY;\n\n /** The layout the pure node helpers read: the synced nodes, their sizes, the origin. */\n private readonly layout: NodeLayout;\n\n constructor(source: GeometrySource) {\n this.source = source;\n const geometry = this;\n this.layout = {\n node: (nodeId) => this.nodeById(nodeId),\n size: (node) => this.sizeOf(node),\n get nodeOrigin() {\n return geometry.source.options().nodeOrigin;\n },\n };\n }\n\n /**\n * Drops every cache (the engine's `destroy`): its maps, grids and lists. A later read builds\n * them again from the document, as the first read does.\n */\n release(): void {\n this.nodes = EMPTY;\n this.edges = EMPTY;\n this.nodeIndex.clear();\n this.edgeIndex.clear();\n this.nodeEntries.clear();\n this.edgeEntries.clear();\n this.children.clear();\n this.edgesAt.clear();\n this.nodeGrid.clear();\n this.edgeGrid.clear();\n this.unsized.clear();\n this.nodeValues.clear();\n this.edgeValues.clear();\n this.shownCount = 0;\n this.unsizedCount = 0;\n this.unmeasuredCount = 0;\n this.stale = true;\n this.visibleNodesKey = \"\";\n this.visibleEdgesKey = \"\";\n this.shownMemo = undefined;\n this.drawableMemo = undefined;\n this.drawnMemo = undefined;\n this.nodePartMemo = undefined;\n this.levelsMemo = undefined;\n this.layeringMemo = undefined;\n this.boundsMemo = undefined;\n this.lastVisibleNodes = EMPTY;\n this.lastVisibleEdges = EMPTY;\n this.lastDrawn = EMPTY;\n }\n\n // ---------------------------------------------------------------------------------------------\n // reads\n // ---------------------------------------------------------------------------------------------\n\n /** A node of the document by id (the synced document's). */\n node(nodeId: string): FlowNode | undefined {\n this.sync();\n return this.nodeById(nodeId);\n }\n\n /** An edge of the document by id (the synced document's). */\n edge(edgeId: string): FlowEdge | undefined {\n this.sync();\n const at = this.edgeIndex.get(edgeId);\n return at === undefined ? undefined : this.edges[at];\n }\n\n /** A node's absolute box, its size zero until known (`node-rect-by`). */\n box(nodeId: string): Rect | undefined {\n this.sync();\n return this.nodeEntries.get(nodeId)?.box;\n }\n\n /** A node's absolute box once its size is known. */\n knownRect(nodeId: string): Rect | undefined {\n this.sync();\n const entry = this.nodeEntries.get(nodeId);\n return entry?.known ? entry.box : undefined;\n }\n\n /** The box of a node object: the cached one when it is the document's, else computed. */\n boxOf(node: FlowNode): Rect {\n this.sync();\n const entry = this.nodeEntries.get(node.id);\n return entry?.node === node ? entry.box : nodeRectOf(node, this.layout);\n }\n\n /** A registered handle with its absolute centre (once it and its node are measured). */\n placed(handle: FlowHandle): FlowHandle {\n if (!handle.bounds) return handle;\n const rect = this.box(handle.nodeId);\n if (!rect) return handle;\n return {\n ...handle,\n center: {\n x: rect.x + handle.bounds.x + handle.bounds.width / 2,\n y: rect.y + handle.bounds.y + handle.bounds.height / 2,\n },\n };\n }\n\n /** An edge's ends and path (`edge-path-by`), once both its nodes have a size. */\n edgePath(edgeId: string): EdgePath | undefined {\n this.sync();\n const entry = this.edgeEntries.get(edgeId);\n if (!entry?.ends) return undefined;\n if (!entry.path || entry.pathVersion !== this.pathVersion) {\n const path = pathOf(entry.edge.type, entry.ends, {\n ...this.pathOptions,\n ...entry.edge.pathOptions,\n });\n entry.path = Object.freeze(path);\n entry.pathVersion = this.pathVersion;\n }\n return entry.path;\n }\n\n /** A node's stack value by the `zIndexMode` (`nodeStackValue`). */\n nodeValue(node: FlowNode): number {\n this.sync();\n const cached = this.nodeValues.get(node.id);\n if (\n cached?.version === this.orderVersion &&\n this.nodeById(node.id) === node\n ) {\n return cached.value;\n }\n const value = nodeStackValue(\n node,\n (id) => this.nodeById(id),\n this.source.options(),\n );\n if (this.nodeById(node.id) === node) {\n this.nodeValues.set(node.id, { version: this.orderVersion, value });\n }\n return value;\n }\n\n /** An edge's stack value by the `zIndexMode` (`edgeStackValue`). */\n edgeValue(edge: FlowEdge): number {\n this.sync();\n const cached = this.edgeValues.get(edge.id);\n const current = this.edgeEntries.get(edge.id)?.edge === edge;\n if (cached?.version === this.orderVersion && current) {\n return cached.value;\n }\n const value = edgeStackValue(\n edge,\n (id) => this.nodeById(id),\n this.source.options(),\n );\n if (current) {\n this.edgeValues.set(edge.id, { version: this.orderVersion, value });\n }\n return value;\n }\n\n /**\n * The shown nodes in `view` (and those of unknown size), in the document's order; every shown\n * node without a view, none when `culled` (`onlyRenderVisible`: nothing mounts before the root\n * has a size).\n */\n visibleNodes(view: Rect | undefined, culled: boolean): readonly FlowNode[] {\n this.sync();\n if (!view) return culled ? EMPTY : this.shownNodes();\n // a read per node and per edge: the list is worked out once per view and change\n const key = `${view.x},${view.y},${view.width},${view.height}|${this.shapeVersion}`;\n if (key === this.visibleNodesKey) return this.lastVisibleNodes;\n this.visibleNodesKey = key;\n const indexes: number[] = [];\n for (const id of this.nodeGrid.query(view)) {\n const at = this.nodeIndex.get(id);\n if (at !== undefined) indexes.push(at);\n }\n for (const id of this.unsized) {\n const at = this.nodeIndex.get(id);\n if (at !== undefined) indexes.push(at);\n }\n indexes.sort((a, b) => a - b);\n const list = indexes.map((at) => this.nodes[at] as FlowNode);\n if (sameItems(list, this.lastVisibleNodes))\n return this.lastVisibleNodes;\n this.lastVisibleNodes = Object.freeze(list);\n return this.lastVisibleNodes;\n }\n\n /**\n * The drawable edges whose ends' box meets `view`, in the document's order; every drawable\n * edge without a view, none when `culled`.\n */\n visibleEdges(view: Rect | undefined, culled: boolean): readonly FlowEdge[] {\n this.sync();\n if (!view) return culled ? EMPTY : this.drawableEdges();\n const key = `${view.x},${view.y},${view.width},${view.height}|${this.edgeVersion}`;\n if (key === this.visibleEdgesKey) return this.lastVisibleEdges;\n this.visibleEdgesKey = key;\n const indexes: number[] = [];\n for (const id of this.edgeGrid.query(view)) {\n const at = this.edgeIndex.get(id);\n if (at !== undefined) indexes.push(at);\n }\n indexes.sort((a, b) => a - b);\n const list = indexes.map((at) => this.edges[at] as FlowEdge);\n if (sameItems(list, this.lastVisibleEdges))\n return this.lastVisibleEdges;\n this.lastVisibleEdges = Object.freeze(list);\n return this.lastVisibleEdges;\n }\n\n /**\n * The edges to draw, in drawing order: the drawable ones (in `view` when `culled`), by their\n * stack value, the document's order among equals.\n */\n drawnEdges(view: Rect | undefined, culled: boolean): readonly FlowEdge[] {\n this.sync();\n const shown = culled\n ? this.visibleEdges(view, true)\n : this.drawableEdges();\n const memo = this.drawnMemo;\n if (memo?.key[0] === shown && memo.key[1] === this.orderVersion) {\n return memo.value;\n }\n const ordered = drawingOrder(shown, (edge) => this.edgeValue(edge));\n const value = sameItems(ordered, this.lastDrawn)\n ? this.lastDrawn\n : Object.freeze(ordered);\n this.lastDrawn = value;\n this.drawnMemo = { key: [shown, this.orderVersion], value };\n return value;\n }\n\n /** The render layers (`render-layers`) of the shown nodes and the drawn edges. */\n layering(view: Rect | undefined, culled: boolean): Layering {\n this.sync();\n const drawn = this.drawnEdges(view, culled);\n const part = this.nodePart();\n const mode = this.source.options().zIndexMode ?? \"auto\";\n const memo = this.layeringMemo;\n if (\n memo?.key[0] === part &&\n memo.key[1] === drawn &&\n memo.key[2] === mode\n ) {\n return memo.value;\n }\n const edges = drawn.map((edge) => ({\n id: edge.id,\n value: this.edgeValue(edge),\n }));\n const thresholds =\n mode === \"basic\" || part.stacked.length === 0\n ? []\n : layerThresholds(part.lowest, edges);\n const key = thresholds.join(\",\");\n let levels = this.levelsMemo;\n if (levels?.key[0] !== part || levels.key[1] !== key) {\n levels = {\n key: [part, key],\n value: nodeLevels(part.stacked, thresholds),\n };\n this.levelsMemo = levels;\n }\n const value = layersOf(levels.value, edges);\n this.layeringMemo = { key: [part, drawn, mode], value };\n return value;\n }\n\n /**\n * The shown nodes of known size sharing area with `area` (`partial: false`: inside it), but\n * `nodeId`, in the document's order (`intersecting-nodes`).\n */\n intersecting(\n area: Rect,\n nodeId: string | undefined,\n partial: boolean,\n ): readonly FlowNode[] {\n this.sync();\n const indexes: number[] = [];\n for (const id of this.nodeGrid.query(area)) {\n if (id === nodeId) continue;\n const box = this.nodeEntries.get(id)?.box;\n if (!box) continue;\n if (!(partial ? sharesArea(box, area) : contains(area, box)))\n continue;\n const at = this.nodeIndex.get(id);\n if (at !== undefined) indexes.push(at);\n }\n indexes.sort((a, b) => a - b);\n return indexes.map((at) => this.nodes[at] as FlowNode);\n }\n\n /** The bounds of every node of known size: the shown ones, or the hidden ones too. */\n bounds(includeHidden: boolean): Rect | undefined {\n this.sync();\n if (includeHidden) {\n const rects: Rect[] = [];\n for (const entry of this.nodeEntries.values()) {\n if (entry.known) rects.push(entry.box);\n }\n return boundsOf(rects);\n }\n if (this.boundsMemo?.key !== this.shapeVersion) {\n const rects: Rect[] = [];\n for (const id of this.nodeGrid.ids()) {\n const box = this.nodeGrid.get(id);\n if (box) rects.push(box);\n }\n this.boundsMemo = {\n key: this.shapeVersion,\n value: boundsOf(rects),\n };\n }\n const value = this.boundsMemo.value;\n return value ? { ...value } : undefined;\n }\n\n /** Whether the shown nodes are sized and measured (counted as they change). */\n readiness(): Readiness {\n this.sync();\n return {\n shown: this.shownCount,\n sized: this.unsizedCount === 0,\n measured: this.unmeasuredCount === 0,\n };\n }\n\n // ---------------------------------------------------------------------------------------------\n // the cached lists\n // ---------------------------------------------------------------------------------------------\n\n /** Every shown node, in the document's order. */\n private shownNodes(): readonly FlowNode[] {\n if (this.shownMemo?.key !== this.nodes) {\n this.shownMemo = {\n key: this.nodes,\n value: Object.freeze(\n this.nodes.filter((node) => node.hidden !== true),\n ),\n };\n }\n return this.shownMemo.value;\n }\n\n /** Every drawable edge, in the document's order. */\n private drawableEdges(): readonly FlowEdge[] {\n const memo = this.drawableMemo;\n if (memo?.key[0] === this.edges && memo.key[1] === this.orderVersion) {\n return memo.value;\n }\n const value = Object.freeze(\n this.edges.filter(\n (edge) => this.edgeEntries.get(edge.id)?.drawable === true,\n ),\n );\n this.drawableMemo = { key: [this.edges, this.orderVersion], value };\n return value;\n }\n\n /** The shown nodes with their stack values and the lowest of them, per order version. */\n private nodePart() {\n this.sync();\n if (this.nodePartMemo?.key !== this.orderVersion) {\n const stacked = this.shownNodes().map((node) => ({\n id: node.id,\n value: this.nodeValue(node),\n }));\n this.nodePartMemo = {\n key: this.orderVersion,\n value: {\n stacked,\n lowest: stacked.reduce(\n (least, node) => Math.min(least, node.value),\n Number.POSITIVE_INFINITY,\n ),\n },\n };\n }\n return this.nodePartMemo.value;\n }\n\n // ---------------------------------------------------------------------------------------------\n // the sync\n // ---------------------------------------------------------------------------------------------\n\n private nodeById(nodeId: string): FlowNode | undefined {\n const at = this.nodeIndex.get(nodeId);\n return at === undefined ? undefined : this.nodes[at];\n }\n\n /** A node's measured size, when it has some (an empty one is not). */\n private measuredSize(nodeId: string) {\n const measured = this.source.measurements.size(nodeId);\n return measured && (measured.width > 0 || measured.height > 0)\n ? measured\n : undefined;\n }\n\n private sizeOf(node: FlowNode) {\n return nodeSize(node, this.measuredSize(node.id));\n }\n\n /** Brings the caches to the model's document, the measurements and the options. */\n private sync(): void {\n const options = this.source.options();\n if (options !== this.seenOptions) this.syncOptions(options);\n const { model, measurements } = this.source;\n const nodes = model.get(\"all-nodes\");\n const edges = model.get(\"all-edges\");\n const touched = measurements.takeTouched();\n if (\n !this.stale &&\n nodes === this.nodes &&\n edges === this.edges &&\n !touched\n ) {\n return;\n }\n let full = this.stale;\n this.stale = false;\n const dirty = new Set<string>();\n if (nodes !== this.nodes) {\n // the commits since the last sync only replaced these nodes: no need to compare all\n const replaced = full\n ? undefined\n : replacedSince(nodes, this.nodes);\n const changed = (before: FlowNode, after: FlowNode) => {\n dirty.add(after.id);\n if (stackChanged(before, after)) this.orderVersion++;\n if (before.parentId !== after.parentId) {\n this.unparent(after.id, before.parentId);\n this.parent(after.id, after.parentId);\n }\n };\n if (replaced) {\n for (const id of replaced) {\n const at = this.nodeIndex.get(id);\n const before =\n at === undefined ? undefined : this.nodes[at];\n const after = at === undefined ? undefined : nodes[at];\n if (!before || !after || before.id !== after.id) {\n full = true;\n break;\n }\n if (before !== after) changed(before, after);\n }\n } else if (full || nodes.length !== this.nodes.length) {\n full = true;\n } else {\n for (let i = 0; i < nodes.length; i++) {\n const before = this.nodes[i] as FlowNode;\n const after = nodes[i] as FlowNode;\n if (before === after) continue;\n if (before.id !== after.id) {\n full = true;\n break;\n }\n changed(before, after);\n }\n }\n this.nodes = nodes;\n }\n const dirtyEdges = new Set<string>();\n let fullEdges = full;\n if (full) {\n this.rebuildNodes();\n } else {\n if (touched) {\n for (const id of touched) {\n if (this.nodeIndex.has(id)) dirty.add(id);\n }\n }\n // a child stands in its parent: its box follows\n for (const id of dirty) {\n for (const child of this.children.get(id) ?? [])\n dirty.add(child);\n }\n for (const id of dirty) {\n this.updateNode(id);\n for (const edgeId of this.edgesAt.get(id) ?? []) {\n dirtyEdges.add(edgeId);\n }\n }\n }\n if (edges !== this.edges) {\n const replaced = fullEdges\n ? undefined\n : replacedSince(edges, this.edges);\n const changed = (before: FlowEdge, after: FlowEdge) => {\n dirtyEdges.add(after.id);\n if (\n before.source !== after.source ||\n before.target !== after.target\n ) {\n this.detach(after.id, before);\n this.attach(after.id, after);\n }\n };\n if (replaced) {\n for (const id of replaced) {\n const at = this.edgeIndex.get(id);\n const before =\n at === undefined ? undefined : this.edges[at];\n const after = at === undefined ? undefined : edges[at];\n if (!before || !after || before.id !== after.id) {\n fullEdges = true;\n break;\n }\n if (before !== after) changed(before, after);\n }\n } else if (!fullEdges && edges.length === this.edges.length) {\n for (let i = 0; i < edges.length; i++) {\n const before = this.edges[i] as FlowEdge;\n const after = edges[i] as FlowEdge;\n if (before === after) continue;\n if (before.id !== after.id) {\n fullEdges = true;\n break;\n }\n changed(before, after);\n }\n } else {\n fullEdges = true;\n }\n this.orderVersion++;\n this.edges = edges;\n }\n if (fullEdges) {\n this.rebuildEdges();\n } else {\n for (const id of dirtyEdges) this.updateEdge(id);\n }\n }\n\n private syncOptions(options: GeometryOptions): void {\n this.seenOptions = options;\n const origin = options.nodeOrigin;\n if (origin?.x !== this.origin?.x || origin?.y !== this.origin?.y) {\n this.origin = origin ? { x: origin.x, y: origin.y } : undefined;\n this.stale = true;\n }\n if (!sameRecord(options.pathOptions, this.pathOptions)) {\n this.pathOptions = options.pathOptions\n ? { ...options.pathOptions }\n : undefined;\n this.pathVersion++;\n }\n const stack = `${options.zIndexMode}|${options.elevateNodesOnSelect}|${options.elevateEdgesOnSelect}`;\n if (stack !== this.stackOptions) {\n this.stackOptions = stack;\n this.orderVersion++;\n }\n }\n\n private parent(nodeId: string, parentId: string | undefined): void {\n if (parentId === undefined) return;\n let set = this.children.get(parentId);\n if (!set) {\n set = new Set();\n this.children.set(parentId, set);\n }\n set.add(nodeId);\n }\n\n private unparent(nodeId: string, parentId: string | undefined): void {\n if (parentId === undefined) return;\n const set = this.children.get(parentId);\n set?.delete(nodeId);\n if (set?.size === 0) this.children.delete(parentId);\n }\n\n private attach(edgeId: string, edge: FlowEdge): void {\n for (const nodeId of [edge.source, edge.target]) {\n let set = this.edgesAt.get(nodeId);\n if (!set) {\n set = new Set();\n this.edgesAt.set(nodeId, set);\n }\n set.add(edgeId);\n }\n }\n\n private detach(edgeId: string, edge: FlowEdge): void {\n for (const nodeId of [edge.source, edge.target]) {\n const set = this.edgesAt.get(nodeId);\n set?.delete(edgeId);\n if (set?.size === 0) this.edgesAt.delete(nodeId);\n }\n }\n\n private rebuildNodes(): void {\n this.nodeIndex.clear();\n this.nodeEntries.clear();\n this.children.clear();\n this.nodeGrid.clear();\n this.unsized.clear();\n this.nodeValues.clear();\n this.shownCount = 0;\n this.unsizedCount = 0;\n this.unmeasuredCount = 0;\n this.nodes.forEach((node, i) => {\n this.nodeIndex.set(node.id, i);\n this.parent(node.id, node.parentId);\n });\n for (const node of this.nodes) this.updateNode(node.id);\n this.orderVersion++;\n this.shapeVersion++;\n }\n\n private rebuildEdges(): void {\n this.edgeIndex.clear();\n this.edgeEntries.clear();\n this.edgesAt.clear();\n this.edgeGrid.clear();\n this.edgeValues.clear();\n this.edges.forEach((edge, i) => {\n this.edgeIndex.set(edge.id, i);\n this.attach(edge.id, edge);\n });\n for (const edge of this.edges) this.updateEdge(edge.id);\n this.orderVersion++;\n this.edgeVersion++;\n }\n\n /** Recomputes a node's entry, files it in the grid, and counts it. */\n private updateNode(nodeId: string): void {\n const node = this.nodeById(nodeId);\n const before = this.nodeEntries.get(nodeId);\n if (before) {\n if (before.shown) {\n this.shownCount--;\n if (!before.known) this.unsizedCount--;\n if (!before.measured) this.unmeasuredCount--;\n }\n }\n if (!node) {\n this.shapeVersion++;\n this.nodeEntries.delete(nodeId);\n this.nodeGrid.delete(nodeId);\n this.unsized.delete(nodeId);\n return;\n }\n const measured = this.measuredSize(nodeId);\n const known = nodeSize(node, measured) !== undefined;\n const entry: NodeEntry = {\n node,\n box: Object.freeze(nodeRectOf(node, this.layout)),\n known,\n measured:\n (node.width ?? measured?.width) !== undefined &&\n (node.height ?? measured?.height) !== undefined,\n shown: node.hidden !== true,\n };\n this.nodeEntries.set(nodeId, entry);\n this.shapeVersion++;\n if (before && before.known !== entry.known) this.orderVersion++;\n if (entry.shown) {\n this.shownCount++;\n if (!entry.known) this.unsizedCount++;\n if (!entry.measured) this.unmeasuredCount++;\n }\n if (entry.shown && entry.known) this.nodeGrid.set(nodeId, entry.box);\n else this.nodeGrid.delete(nodeId);\n if (entry.shown && !entry.known) this.unsized.add(nodeId);\n else this.unsized.delete(nodeId);\n }\n\n /** Recomputes an edge's ends and files it in the grid when it is drawable. */\n private updateEdge(edgeId: string): void {\n const at = this.edgeIndex.get(edgeId);\n const edge = at === undefined ? undefined : this.edges[at];\n const before = this.edgeEntries.get(edgeId);\n if (!edge) {\n this.edgeVersion++;\n this.edgeEntries.delete(edgeId);\n this.edgeGrid.delete(edgeId);\n return;\n }\n const ends = edgeEnds(edge, {\n rect: (nodeId) => {\n const entry = this.nodeEntries.get(nodeId);\n return entry?.known ? entry.box : undefined;\n },\n // a measured handle, else one the node declares (used until it is measured)\n handle: (nodeId, type, handleId) =>\n this.measuredHandle(nodeId, type, handleId) ??\n this.declaredHandle(nodeId, type, handleId),\n side: (nodeId, type) => {\n const node = this.nodeById(nodeId);\n return type === \"source\"\n ? node?.sourcePosition\n : node?.targetPosition;\n },\n });\n const drawable =\n ends !== undefined &&\n edge.hidden !== true &&\n this.nodeById(edge.source)?.hidden !== true &&\n this.nodeById(edge.target)?.hidden !== true;\n this.edgeVersion++;\n this.edgeEntries.set(edgeId, {\n edge,\n ends,\n drawable,\n path: undefined,\n pathVersion: this.pathVersion,\n });\n if (before && before.drawable !== drawable) this.orderVersion++;\n if (drawable && ends) {\n const x = Math.min(ends.source.x, ends.target.x);\n const y = Math.min(ends.source.y, ends.target.y);\n this.edgeGrid.set(edgeId, {\n x,\n y,\n width: Math.max(ends.source.x, ends.target.x) - x,\n height: Math.max(ends.source.y, ends.target.y) - y,\n });\n } else {\n this.edgeGrid.delete(edgeId);\n }\n }\n\n private measuredHandle(\n nodeId: string,\n type: HandleType,\n handleId: string | undefined,\n ): FlowHandle | undefined {\n const found = matchHandle(\n this.source.measurements.handlesOf(nodeId),\n type,\n handleId,\n );\n if (!found?.bounds) return found;\n const rect = this.nodeEntries.get(nodeId)?.box;\n if (!rect) return found;\n return {\n ...found,\n center: {\n x: rect.x + found.bounds.x + found.bounds.width / 2,\n y: rect.y + found.bounds.y + found.bounds.height / 2,\n },\n };\n }\n\n private declaredHandle(\n nodeId: string,\n type: HandleType,\n handleId: string | undefined,\n ): EdgeEndHandle | undefined {\n const node = this.nodeById(nodeId);\n const entry = this.nodeEntries.get(nodeId);\n return node && entry?.known\n ? declaredHandleOf(node, entry.box, type, handleId)\n : undefined;\n }\n}\n","// What `set-interactive` switches (the Controls' lock): the whole flow (`interactive`) and, inside\n// it, each kind of gesture and key on its own. The engine holds the switches as its state and every\n// feature reads them through the host (`host.allows(kind)`) at the moment it would act, so a switch\n// turned off stops its gestures at once without installing anything again. Pan and zoom are never\n// switched off: they change the view, not the flow.\n\n/** A kind of gesture and key `set-interactive` turns on or off on its own. */\nexport type InteractionKind = \"drag\" | \"connect\" | \"select\" | \"reconnect\";\n\n/** The kinds, in a stable order. */\nexport const INTERACTION_KINDS: readonly InteractionKind[] = Object.freeze([\n \"drag\",\n \"connect\",\n \"select\",\n \"reconnect\",\n]);\n\n/**\n * The switches of `set-interactive`: `interactive` (every gesture and key that changes the flow)\n * and each kind (`drag`: dragging nodes and moving them with the arrows; `connect`: drawing edges;\n * `select`: taps, the selection box, Enter and Space; `reconnect`: moving an edge's ends).\n */\nexport interface Interactivity {\n readonly interactive: boolean;\n readonly drag: boolean;\n readonly connect: boolean;\n readonly select: boolean;\n readonly reconnect: boolean;\n}\n\n/** What `set-interactive` takes: the switches it changes (at least one), the others kept. */\nexport type InteractivityPayload = Partial<Interactivity>;\n","// What the engine measures (D8, D9): each registered node's rendered size, with the\n// `ResizeObserver` of the node's own window (`defaultView`), and each registered handle's box\n// relative to its node, in flow units; the same observer watches the root's size. Sizes are layout\n// sizes (`offsetWidth`, unaffected by the viewport's scale); a handle's box comes from the client\n// rects, divided by the zoom.\nimport type { Rect } from \"../geometry/types\";\nimport type { FlowHandle, HandleRegistration } from \"./adapter\";\nimport { viewOf } from \"./dom\";\n\n/** A measured size, in flow units. */\nexport interface Size {\n readonly width: number;\n readonly height: number;\n}\n\ninterface Observer {\n observe(target: Element): void;\n unobserve(target: Element): void;\n disconnect(): void;\n}\n\ntype ObserverConstructor = new (\n callback: (entries: readonly { readonly target: Element }[]) => void,\n) => Observer;\n\ninterface RegisteredHandle {\n readonly registration: HandleRegistration;\n /** its element; none once it went while its node stays in the flow (its last bounds kept) */\n readonly element: Element | undefined;\n bounds: Rect | undefined;\n}\n\n/** The key of a handle among all: its node, its type and its id. */\nexport function handleKey(\n nodeId: string,\n type: string,\n handleId: string | undefined,\n): string {\n return `${nodeId}\\u0000${type}\\u0000${handleId ?? \"\"}`;\n}\n\n/** The measured nodes and handles of one engine. */\nexport class Measurements {\n private readonly nodes = new Map<string, HTMLElement>();\n private readonly nodeOfElement = new Map<Element, string>();\n private readonly sizes = new Map<string, Size>();\n private readonly handles = new Map<string, RegisteredHandle>();\n private readonly handleOfElement = new Map<Element, string>();\n /** each node's handle keys, in registration order */\n private readonly handlesByNode = new Map<string, Set<string>>();\n /** the nodes whose element went while they stayed in the flow: their last measurements kept */\n private readonly retired = new Set<string>();\n private observer: Observer | undefined;\n /** the root, observed for its size */\n private root: Element | undefined;\n private observerView: Window | undefined;\n /**\n * the nodes whose size or handles changed since the engine last took them (`takeTouched`):\n * its geometry cache recomputes those and keeps the rest\n */\n private touched = new Set<string>();\n\n constructor(\n /** the current zoom: client rects are divided by it */\n private readonly zoom: () => number,\n /** something was measured: the nodes whose size or handles changed */\n private readonly measured: (nodeIds: readonly string[]) => void,\n /**\n * whether a node is still in the flow: a node whose element goes while it stays (culled by\n * `onlyRenderVisible`, hidden) keeps its last size and handles, so that it is not taken\n * for an unmeasured one (rendered again) and its edges keep their ends\n */\n private readonly inFlow: (nodeId: string) => boolean = () => false,\n /** the observer reported the root */\n private readonly rootResized: () => void = () => {},\n ) {}\n\n /** Observes the root's size (none: stops). */\n observeRoot(element: Element | undefined): void {\n if (this.root) this.observer?.unobserve(this.root);\n this.root = element;\n if (element) this.observerFor(element)?.observe(element);\n }\n\n /** Takes the nodes whose size or handles changed since the last call (none: nothing did). */\n takeTouched(): ReadonlySet<string> | undefined {\n if (this.touched.size === 0) return undefined;\n const touched = this.touched;\n this.touched = new Set();\n return touched;\n }\n\n /** A node's measured size, if it was measured. */\n size(nodeId: string): Size | undefined {\n return this.sizes.get(nodeId);\n }\n\n /** A node's registered element. */\n nodeElement(nodeId: string): HTMLElement | undefined {\n return this.nodes.get(nodeId);\n }\n\n registerNode(nodeId: string, element: HTMLElement | null): void {\n const previous = this.nodes.get(nodeId);\n if (previous === element) return;\n if (previous) {\n this.observer?.unobserve(previous);\n this.nodeOfElement.delete(previous);\n this.nodes.delete(nodeId);\n }\n if (!element) {\n if (this.inFlow(nodeId)) {\n this.retired.add(nodeId);\n return;\n }\n this.forget(nodeId);\n return;\n }\n this.retired.delete(nodeId);\n // React attaches a node's children before the node: a handle of it still without an\n // element was not rendered again (a node of another type now, its handles changed)\n for (const key of this.handlesByNode.get(nodeId) ?? []) {\n if (this.handles.get(key)?.element === undefined) {\n this.handles.delete(key);\n this.handlesByNode.get(nodeId)?.delete(key);\n this.touched.add(nodeId);\n }\n }\n this.nodes.set(nodeId, element);\n this.nodeOfElement.set(element, nodeId);\n const observer = this.observerFor(element);\n observer?.observe(element);\n // measured now too: an observer reports asynchronously, and one may be missing\n this.measure([nodeId]);\n }\n\n registerHandle(\n registration: HandleRegistration,\n element: Element | null,\n ): void {\n const key = handleKey(\n registration.nodeId,\n registration.type,\n registration.handleId,\n );\n const previous = this.handles.get(key);\n if (previous?.element) {\n if (previous.element !== element) {\n this.observer?.unobserve(previous.element);\n }\n this.handleOfElement.delete(previous.element);\n }\n if (\n !element &&\n previous &&\n !this.nodes.has(registration.nodeId) &&\n this.inFlow(registration.nodeId)\n ) {\n // its node's element went before it (React detaches a parent's ref first) and the node\n // stays in the flow: the handle keeps its last bounds, without an element\n this.handles.set(key, { ...previous, element: undefined });\n this.touched.add(registration.nodeId);\n return;\n }\n if (previous) {\n this.handles.delete(key);\n this.handlesByNode.get(registration.nodeId)?.delete(key);\n this.touched.add(registration.nodeId);\n }\n if (!element) {\n this.measured([registration.nodeId]);\n return;\n }\n this.handles.set(key, {\n registration: Object.freeze({ ...registration }),\n element,\n bounds: undefined,\n });\n this.handleOfElement.set(element, key);\n this.touched.add(registration.nodeId);\n const own =\n this.handlesByNode.get(registration.nodeId) ?? new Set<string>();\n own.add(key);\n this.handlesByNode.set(registration.nodeId, own);\n if (previous?.element !== element) {\n this.observerFor(element)?.observe(element);\n }\n this.measure([registration.nodeId]);\n }\n\n /** The handle an element is, if it was registered. */\n handleOf(\n element: Element,\n center: (handle: FlowHandle) => FlowHandle,\n ): FlowHandle | undefined {\n const key = this.handleOfElement.get(element);\n const entry = key === undefined ? undefined : this.handles.get(key);\n return entry ? center(this.view(entry)) : undefined;\n }\n\n /** A node's registered handles (their centres left for the engine to place). */\n handlesOf(nodeId: string): FlowHandle[] {\n const keys = this.handlesByNode.get(nodeId);\n if (!keys) return [];\n return [...keys].flatMap((key) => {\n const entry = this.handles.get(key);\n return entry ? [this.view(entry)] : [];\n });\n }\n\n /**\n * Every rendered handle (its centre left for the engine to place), in registration order: what\n * a connection may reach. A culled or hidden node's kept handles are not in it.\n */\n allHandles(): FlowHandle[] {\n return [...this.handles.values()]\n .filter((entry) => entry.element !== undefined)\n .map((entry) => this.view(entry));\n }\n\n /** Forgets the kept measurements of the nodes that left the flow while not rendered. */\n prune(): void {\n for (const nodeId of [...this.retired]) {\n if (!this.inFlow(nodeId)) this.forget(nodeId);\n }\n }\n\n /** Forgets a node's size and handles. */\n private forget(nodeId: string): void {\n this.retired.delete(nodeId);\n this.forgetHandles(nodeId);\n this.touched.add(nodeId);\n if (this.sizes.delete(nodeId)) this.measured([nodeId]);\n }\n\n private view(entry: RegisteredHandle): FlowHandle {\n const { registration, bounds } = entry;\n const connectable = registration.connectable !== false;\n return {\n nodeId: registration.nodeId,\n handleId: registration.handleId,\n type: registration.type,\n side: registration.side,\n connectable,\n connectableStart:\n connectable && registration.connectableStart !== false,\n connectableEnd:\n connectable && registration.connectableEnd !== false,\n center: undefined,\n bounds,\n };\n }\n\n /** Measures nodes again (their size and their handles). */\n measure(nodeIds: Iterable<string>): void {\n const changed: string[] = [];\n for (const nodeId of nodeIds) {\n const element = this.nodes.get(nodeId);\n if (!element) continue;\n let touched = false;\n const size = sizeOf(element, this.zoom());\n const before = this.sizes.get(nodeId);\n if (\n !before ||\n before.width !== size.width ||\n before.height !== size.height\n ) {\n this.sizes.set(nodeId, size);\n touched = true;\n }\n const nodeBox = element.getBoundingClientRect();\n const zoom = this.zoom() || 1;\n for (const key of this.handlesByNode.get(nodeId) ?? []) {\n const entry = this.handles.get(key);\n if (!entry?.element) continue;\n const box = entry.element.getBoundingClientRect();\n const bounds = {\n x: (box.left - nodeBox.left) / zoom,\n y: (box.top - nodeBox.top) / zoom,\n width: box.width / zoom,\n height: box.height / zoom,\n };\n const was = entry.bounds;\n if (\n !was ||\n was.x !== bounds.x ||\n was.y !== bounds.y ||\n was.width !== bounds.width ||\n was.height !== bounds.height\n ) {\n entry.bounds = bounds;\n touched = true;\n }\n }\n if (touched) {\n changed.push(nodeId);\n this.touched.add(nodeId);\n }\n }\n if (changed.length > 0) this.measured(changed);\n }\n\n /** Forgets a node's handles (the node left the flow). */\n private forgetHandles(nodeId: string): void {\n for (const key of this.handlesByNode.get(nodeId) ?? []) {\n const entry = this.handles.get(key);\n if (entry?.element) {\n this.observer?.unobserve(entry.element);\n this.handleOfElement.delete(entry.element);\n }\n this.handles.delete(key);\n }\n this.handlesByNode.delete(nodeId);\n }\n\n /** Measures every registered node again (after a zoom, handles' client rects scale). */\n measureAll(): void {\n this.measure([...this.nodes.keys()]);\n }\n\n destroy(): void {\n this.observer?.disconnect();\n this.observer = undefined;\n this.root = undefined;\n this.nodes.clear();\n this.nodeOfElement.clear();\n this.sizes.clear();\n this.handles.clear();\n this.handleOfElement.clear();\n this.handlesByNode.clear();\n this.retired.clear();\n this.touched.clear();\n }\n\n /** The observer of an element's window, made once (an element of another window gets none). */\n private observerFor(element: Element): Observer | undefined {\n const view = viewOf(element);\n if (!view) return undefined;\n if (this.observer && this.observerView === view) return this.observer;\n if (this.observer) return undefined;\n const Constructor = (\n view as Window & { ResizeObserver?: ObserverConstructor }\n ).ResizeObserver;\n if (typeof Constructor !== \"function\") return undefined;\n this.observerView = view;\n this.observer = new Constructor((entries) => {\n const nodeIds = new Set<string>();\n for (const { target } of entries) {\n if (target === this.root) this.rootResized();\n const nodeId =\n this.nodeOfElement.get(target) ?? this.handleNodeOf(target);\n if (nodeId !== undefined) nodeIds.add(nodeId);\n }\n this.measure(nodeIds);\n });\n return this.observer;\n }\n\n private handleNodeOf(element: Element): string | undefined {\n const key = this.handleOfElement.get(element);\n return key === undefined\n ? undefined\n : this.handles.get(key)?.registration.nodeId;\n }\n}\n\n/** An element's layout size: `offsetWidth` for HTML, the client rect divided by the zoom otherwise. */\nfunction sizeOf(element: Element, zoom: number): Size {\n const html = element as Partial<HTMLElement>;\n if (\n typeof html.offsetWidth === \"number\" &&\n typeof html.offsetHeight === \"number\"\n ) {\n return { width: html.offsetWidth, height: html.offsetHeight };\n }\n const box = element.getBoundingClientRect();\n return { width: box.width / (zoom || 1), height: box.height / (zoom || 1) };\n}\n","// Where a node's toolbar goes (NodeToolbar geometry): beside one side of the node (or of several\n// nodes' bounds) on the screen, outside the zoom, so it keeps its size whatever the zoom.\nimport type { Rect, Viewport } from \"../geometry/types\";\nimport type { NodeToolbarPayload, NodeToolbarPosition } from \"./verbs\";\n\n/** A toolbar's anchor for a node's absolute box (or several nodes' bounds). */\nexport function nodeToolbarPosition(\n rect: Rect,\n viewport: Viewport,\n payload: NodeToolbarPayload,\n): NodeToolbarPosition {\n const side = payload.side ?? \"top\";\n const align = payload.align ?? \"center\";\n const offset = payload.offset ?? 10;\n const { zoom } = viewport;\n const left = rect.x * zoom + viewport.x;\n const top = rect.y * zoom + viewport.y;\n const width = rect.width * zoom;\n const height = rect.height * zoom;\n const share = align === \"start\" ? 0 : align === \"end\" ? 1 : 0.5;\n switch (side) {\n case \"top\":\n return {\n x: left + width * share,\n y: top - offset,\n anchorX: share,\n anchorY: 1,\n };\n case \"bottom\":\n return {\n x: left + width * share,\n y: top + height + offset,\n anchorX: share,\n anchorY: 0,\n };\n case \"left\":\n return {\n x: left - offset,\n y: top + height * share,\n anchorX: 1,\n anchorY: share,\n };\n case \"right\":\n return {\n x: left + width + offset,\n y: top + height * share,\n anchorX: 0,\n anchorY: share,\n };\n }\n}\n","// The one place the core writes a style: the viewport's transform (D4), written to its element\n// directly so the framework never reconciles it, and the root's `touch-action: none`, without\n// which a browser takes touches for its own scroll and zoom and cancels every gesture (D10). Only\n// these structural properties; the core guard allows `.style` in this file alone.\nimport type { Viewport } from \"../geometry/types\";\n\n/** Writes the viewport's transform to its element. */\nexport function writeViewportTransform(\n element: HTMLElement | SVGElement,\n viewport: Viewport,\n): void {\n element.style.transformOrigin = \"0 0\";\n element.style.transform = `translate(${viewport.x}px, ${viewport.y}px) scale(${viewport.zoom})`;\n}\n\n/** Removes what {@link writeViewportTransform} wrote. */\nexport function clearViewportTransform(\n element: HTMLElement | SVGElement,\n): void {\n element.style.removeProperty(\"transform\");\n element.style.removeProperty(\"transform-origin\");\n}\n\n/** Keeps the browser's own touch panning and zooming off the root (the engine runs them). */\nexport function writeRootTouchAction(element: HTMLElement): void {\n element.style.setProperty(\"touch-action\", \"none\");\n}\n\n/** Removes what {@link writeRootTouchAction} wrote. */\nexport function clearRootTouchAction(element: HTMLElement): void {\n element.style.removeProperty(\"touch-action\");\n}\n","// An animated viewport change (a viewport action's `duration`): from one viewport to another over\n// a time, eased, one step per frame of the root's window (never the global one). The first frame\n// starts the clock, so the time runs from when the window first paints it. x, y and the zoom move\n// by the same eased share, so a zoom around a point keeps that point still all the way.\nimport type { Viewport } from \"../geometry/types\";\n\n/** How an animation's share of time becomes its share of the way (0 → 0, 1 → 1). */\nexport type ViewportEasing = (t: number) => number;\n\n/** The default easing: slow at both ends (a cubic ease in and out). */\nfunction smooth(t: number): number {\n return t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2;\n}\n\n/** What {@link animateViewport} takes. */\nexport interface ViewportAnimationOptions {\n /** the window whose frames it runs on (the root's `defaultView`) */\n readonly view: Window;\n readonly from: Viewport;\n readonly to: Viewport;\n /** in milliseconds, above 0 */\n readonly duration: number;\n /** default a smooth ease in and out */\n readonly easing?: ViewportEasing | undefined;\n /** sets one frame's viewport (the last one is `to`) */\n readonly step: (viewport: Viewport) => void;\n /** the last frame was set */\n readonly done: () => void;\n}\n\n/** Animates the viewport from `from` to `to`; returns its stop (the pending frame cancelled). */\nexport function animateViewport(options: ViewportAnimationOptions): () => void {\n const { view, from, to, duration, step, done } = options;\n const easing = options.easing ?? smooth;\n let start: number | undefined;\n let frame: number | undefined;\n let stopped = false;\n const tick = (time: number) => {\n frame = undefined;\n start ??= time;\n const t = duration > 0 ? (time - start) / duration : 1;\n if (t >= 1) {\n step(to);\n done();\n return;\n }\n const share = easing(Math.max(0, t));\n const at = (a: number, b: number) => a + (b - a) * share;\n step({\n x: at(from.x, to.x),\n y: at(from.y, to.y),\n zoom: at(from.zoom, to.zoom),\n });\n // a listener of this step may have stopped it (another action)\n if (!stopped) frame = view.requestAnimationFrame(tick);\n };\n frame = view.requestAnimationFrame(tick);\n return () => {\n stopped = true;\n if (frame !== undefined) view.cancelAnimationFrame(frame);\n frame = undefined;\n };\n}\n","// The flow engine (D4, D8-D13): one flow on screen. It owns the viewport (written to its element\n// directly), measures nodes, handles and the root with the root window's `ResizeObserver`, draws edges'\n// paths, and runs every gesture on Pointer Events with capture (pan, pinch, the features' drags),\n// the wheel and the keys, behind the same five verbs as the model; the installed features add\n// theirs. It changes the flow only by running the model's commands, so every middleware sees what\n// a drag, a connection or a key does. It never touches the global `document` or `window`: every\n// DOM access goes through the root element (its `ownerDocument`, its `defaultView`).\nimport {\n END_ATTRIBUTE,\n flag,\n ID_ATTRIBUTE,\n LEVEL_ATTRIBUTE,\n type MutablePartAttributes,\n NO_WHEEL_ATTRIBUTE,\n PART_ATTRIBUTE,\n type PartAttributes,\n resizeHandleAttributes,\n} from \"../attributes/part-attributes\";\nimport { fail, ok } from \"../commands/define\";\nimport type { CommandResult } from \"../commands/types\";\nimport type {\n AnyTypes,\n FlowEdge,\n FlowNode,\n FlowTypes,\n XY,\n} from \"../document/types\";\nimport type { OwnedBy } from \"../features/keys\";\nimport { requiresFeature } from \"../features/keys\";\nimport {\n type ComposedFeatureEngine,\n featureEngine,\n featuresOf,\n} from \"../features/registry\";\nimport type {\n EngineActionKeyOf,\n EngineGetKeyOf,\n EngineIsKeyOf,\n FeatureEngineHost,\n FeatureGesture,\n FeatureModel,\n FlowFeatures,\n} from \"../features/types\";\nimport { type PathOptions, pathOf } from \"../geometry/edge-geometry\";\nimport {\n type NodeLayout,\n nodeAbsolutePosition,\n nodeOriginOf,\n nodeSize,\n} from \"../geometry/node-layout\";\nimport { boundsOf, cornerInside, intersectionOf } from \"../geometry/rect\";\nimport type { EdgePath, Rect, Viewport } from \"../geometry/types\";\nimport {\n isFitPadding,\n type ViewportForBoundsOptions,\n viewportForBounds,\n} from \"../geometry/viewport-for-bounds\";\nimport {\n centeredOn,\n clampZoom,\n keptInExtent,\n type Size,\n toFlow,\n toScreen,\n viewRect,\n zoomAround,\n} from \"../geometry/viewport-math\";\nimport type { Layering, ZIndexMode } from \"../geometry/z-order\";\nimport type { FlowModel } from \"../model/create-flow-model\";\nimport type { QueryArgs } from \"../state/queries\";\nimport type {\n FlowEngineAdapter,\n FlowHandle,\n HandleRegistration,\n PressTarget,\n ViewChange,\n} from \"./adapter\";\nimport { type AutoPanOptions, autoPanOffset, autoPans } from \"./auto-pan\";\nimport { backgroundPattern } from \"./background-pattern\";\nimport { asElement, pressTargetOf, viewOf } from \"./dom\";\nimport { edgeToolbarPosition } from \"./edge-toolbar\";\nimport { EngineGeometry } from \"./engine-geometry\";\nimport type { FlowEngineEvent, FlowPointerInfo } from \"./events\";\nimport {\n INTERACTION_KINDS,\n type InteractionKind,\n type Interactivity,\n} from \"./interactivity\";\nimport { Measurements } from \"./measurements\";\nimport { nodeToolbarPosition } from \"./node-toolbar\";\nimport {\n clearRootTouchAction,\n clearViewportTransform,\n writeRootTouchAction,\n writeViewportTransform,\n} from \"./structural-style\";\nimport { TAP_TOLERANCE } from \"./tap\";\nimport type {\n BackgroundPatternPayload,\n EdgeToolbarPayload,\n EngineActionKey,\n EngineActionPayload,\n EngineActionResult,\n EngineGetKey,\n EngineGetPayload,\n EngineGetResult,\n EngineIsKey,\n EngineIsPayload,\n FitViewPayload,\n InternalNode,\n NodeToolbarPayload,\n ZoomStepPayload,\n} from \"./verbs\";\nimport { animateViewport, type ViewportEasing } from \"./viewport-animation\";\nimport { WHEEL_PINCH_RATE, WHEEL_RATE, WHEEL_REST } from \"./wheel-rate\";\n\n/** Which way the wheel pans with `panOnScroll`: both ways, or one axis only. */\nexport type PanOnScrollMode = \"free\" | \"horizontal\" | \"vertical\";\n\n/** Options of {@link createFlowEngine}. */\nexport interface FlowEngineOptions {\n /** the root element; an adapter may attach it later (`engine.adapter.attachRoot`) */\n root?: HTMLElement | undefined;\n /** the viewport it starts at; default `{ x: 0, y: 0, zoom: 1 }` */\n defaultViewport?: Viewport | undefined;\n /** the least zoom; default 0.5 */\n minZoom?: number | undefined;\n /** the greatest zoom; default 2 */\n maxZoom?: number | undefined;\n /** the flow rectangle the view stays inside; default none */\n translateExtent?: Rect | undefined;\n /**\n * a drag on the pane pans: `true` with the primary button (and a touch or a pen), or the mouse\n * buttons that pan (`[0]` primary, `[1]` middle, `[2]` right); default true\n */\n panOnDrag?: boolean | readonly number[] | undefined;\n /**\n * the key that, held, makes a primary drag pan from anywhere (nodes included) and start no\n * other gesture (`KeyboardEvent.key`, or `.code`); null for none; default `\" \"` (Space)\n */\n panActivationKey?: string | null | undefined;\n /** the wheel pans (Ctrl + wheel zooms); default false: the wheel zooms */\n panOnScroll?: boolean | undefined;\n /** which way the wheel pans with `panOnScroll`; default `\"free\"` */\n panOnScrollMode?: PanOnScrollMode | undefined;\n /** the factor of the wheel's pixels when it pans (`panOnScroll`); default 1 */\n panOnScrollSpeed?: number | undefined;\n /**\n * the key that, held, makes the wheel zoom while `panOnScroll` is on (`KeyboardEvent.key`;\n * `Meta`, `Control`, `Alt` and `Shift` read from the wheel event); null for none; default\n * `Meta` on Apple platforms and `Control` elsewhere (the root window's `navigator`)\n */\n zoomActivationKey?: string | null | undefined;\n /** the wheel zooms around the pointer; default true */\n zoomOnScroll?: boolean | undefined;\n /** a two-finger pinch (and a trackpad's) zooms; default true */\n zoomOnPinch?: boolean | undefined;\n /** a double click on the pane zooms in; default true */\n zoomOnDoubleClick?: boolean | undefined;\n /** the factor of `zoom-in` and `zoom-out`; default 1.2 */\n zoomStep?: number | undefined;\n /** fits the nodes once their sizes are known, again once measured (`fit-view`'s options); default false */\n fitView?: boolean | FitViewPayload | undefined;\n /** whether gestures and keys may change the flow (`set-interactive`); default true */\n interactive?: boolean | undefined;\n /** adapters render only the nodes and edges in view; default false */\n onlyRenderVisible?: boolean | undefined;\n /** the shape of the built-in edge paths */\n pathOptions?: PathOptions | undefined;\n /**\n * the viewport pans while a drag, a connection, a reconnection, a selection box or a resize\n * has its pointer near the root's edge (`{ speed, margin }` tunes it; `{ node, connect,\n * selection, resize }` turn it off for one gesture); default true\n */\n autoPan?: boolean | AutoPanOptions | undefined;\n /**\n * how far (in pixels) a press on the pane may move and still be a tap (a click: it clears the\n * selection, `pane-click`); default 3\n */\n paneClickDistance?: number | undefined;\n /**\n * how far (in pixels) a press on a node, an edge or a handle may move and still be a tap (it\n * selects, `node-click`; with click-to-connect a handle's drag starts past it); default 3\n */\n nodeClickDistance?: number | undefined;\n /**\n * the wheel over the flow never scrolls the page, even when neither `zoomOnScroll` nor\n * `panOnScroll` uses it (a `data-flow-no-wheel` element and the controls keep theirs);\n * default true\n */\n preventScrolling?: boolean | undefined;\n /** nodes take focus (with `keyboard()`; a node's `focusable: false` still wins); default true */\n nodesFocusable?: boolean | undefined;\n /** edges take focus (with `keyboard()`; an edge's `focusable: false` still wins); default true */\n edgesFocusable?: boolean | undefined;\n /** how an animated viewport action (its `duration`) eases; default a smooth ease in and out */\n easing?: ViewportEasing | undefined;\n /**\n * the point of a node's box its `position` stands at, as shares of its size (`{ x: 0.5, y: 0.5 }`:\n * its centre), for the nodes on the flow (a child's position is its box's top-left corner in its\n * parent's); default `{ x: 0, y: 0 }`: the top-left corner\n */\n nodeOrigin?: XY | undefined;\n /** the flow rectangle every node's box stays inside when dragged, moved by keys or resized */\n nodeExtent?: Rect | undefined;\n /** a selected node, and its children with it, is drawn above the others; default true */\n elevateNodesOnSelect?: boolean | undefined;\n /**\n * a selected edge is drawn above the other edges (in `\"auto\"`, above the nodes too); default\n * false in `\"basic\"`, true in `\"auto\"`\n */\n elevateEdgesOnSelect?: boolean | undefined;\n /**\n * how nodes and edges stack (`render-layers`): `\"basic\"` edges always below the nodes, `\"auto\"`\n * an edge may stand above nodes (a selected one, one of a child, a higher `zIndex`), `\"manual\"`\n * only the `zIndex` values; default `\"auto\"`\n */\n zIndexMode?: ZIndexMode | undefined;\n}\n\n/**\n * One flow on screen. Every member is one verb, as on the model, and bound: `run` a screen\n * action, `can` / `check` it, `get` a fact of the screen, `is` a yes/no question; `subscribe`\n * listens to what happens on screen (D12: the events an app announces); `destroy` releases it.\n * `adapter` is what only an adapter calls.\n */\nexport interface FlowEngine<\n T extends FlowTypes = AnyTypes,\n F extends FlowFeatures = readonly [],\n> {\n run<K extends EngineActionKeyOf<F>>(\n action: K,\n ...payload: QueryArgs<EngineActionPayload<K>>\n ): CommandResult<EngineActionResult<K>>;\n can<K extends EngineActionKeyOf<F>>(\n action: K,\n ...payload: QueryArgs<EngineActionPayload<K>>\n ): boolean;\n check<K extends EngineActionKeyOf<F>>(\n action: K,\n ...payload: QueryArgs<EngineActionPayload<K>>\n ): CommandResult<EngineActionResult<K>>;\n get<K extends EngineGetKeyOf<F>>(\n key: K,\n ...payload: QueryArgs<EngineGetPayload<K>>\n ): EngineGetResult<T, K>;\n is<K extends EngineIsKeyOf<F>>(\n key: K,\n ...payload: QueryArgs<EngineIsPayload<K>>\n ): boolean;\n /** listens to what happens on screen (a drag's drop, a connection, the viewport); returns its remover */\n subscribe(listener: (event: FlowEngineEvent) => void): () => void;\n /** releases every listener and element; no command runs afterwards */\n destroy(): void;\n /** what only an adapter calls */\n readonly adapter: FlowEngineAdapter;\n}\n\ntype ActionHandler = (\n payload: unknown,\n dryRun: boolean,\n) => CommandResult<unknown>;\n\n/** A press under way: its pointer, where it started, and the gesture that took it. */\ninterface Press {\n readonly pointerId: number;\n readonly start: XY;\n readonly target: PressTarget;\n readonly gesture: FeatureGesture | undefined;\n readonly pan: boolean;\n /** the mouse button pressed (0 for a touch or a pen) */\n readonly button: number;\n /** started by the pan activation key: it pans and never taps */\n readonly keyPan: boolean;\n /** its gesture is the one a tap started (click-to-connect): its release is the gesture's end */\n readonly follows: boolean;\n travel: number;\n /** a context menu opened during it (a long press, Ctrl + click): its release is no tap */\n menu: boolean;\n /** its pointer's last move: a press whose release was missed ends there */\n last: PointerEvent | undefined;\n}\n\n/** What the last press released: a tap (on what) or not, for a double click. */\ninterface Released {\n readonly target: PressTarget;\n readonly tap: boolean;\n}\n\n/** A tap's target as its event's: a node, an edge or the pane (anything else has none). */\ntype TapOn =\n | { readonly kind: \"node\"; readonly nodeId: string }\n | { readonly kind: \"edge\"; readonly edgeId: string }\n | { readonly kind: \"pane\" };\n\nfunction tapOn(target: PressTarget): TapOn | undefined {\n if (target.kind === \"node\" && target.nodeId !== undefined)\n return { kind: \"node\", nodeId: target.nodeId };\n if (target.kind === \"edge\" && target.edgeId !== undefined)\n return { kind: \"edge\", edgeId: target.edgeId };\n if (target.kind === \"pane\") return { kind: \"pane\" };\n return undefined;\n}\n\n/** A pinch under way: its two pointers and where they started. */\ninterface Pinch {\n readonly ids: readonly [number, number];\n /** the fingers' spread when it began */\n readonly distance: number;\n /** the zoom when it began */\n readonly zoom: number;\n /** the flow point under the fingers' middle when it began */\n readonly anchor: XY;\n}\n\nconst ZERO_SIZE: Size = { width: 0, height: 0 };\n\nconst TOP_LEFT: XY = { x: 0, y: 0 };\n\n/** the app's actions that place the view: they read the root's box again, not the turn's kept one */\nconst FRESH_BOX_ACTIONS: ReadonlySet<string> = new Set([\n \"fit-view\",\n \"center-on\",\n \"focus-node\",\n \"set-viewport\",\n \"zoom-in\",\n \"zoom-out\",\n \"zoom-to\",\n \"pan-by\",\n]);\n\n/** the app's reads that map points through the view: likewise */\nconst FRESH_BOX_READS: ReadonlySet<string> = new Set([\n \"screen-to-flow\",\n \"flow-to-screen\",\n]);\n\nfunction finite(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value);\n}\n\nfunction payloadRecord(payload: unknown): Record<string, unknown> {\n return payload !== null && typeof payload === \"object\"\n ? (payload as Record<string, unknown>)\n : {};\n}\n\nfunction pointOf(value: unknown): XY | undefined {\n const record = payloadRecord(value);\n return finite(record.x) && finite(record.y)\n ? { x: record.x, y: record.y }\n : undefined;\n}\n\nfunction sameViewport(a: Viewport, b: Viewport): boolean {\n return a.x === b.x && a.y === b.y && a.zoom === b.zoom;\n}\n\nfunction distance(a: XY, b: XY): number {\n return Math.hypot(b.x - a.x, b.y - a.y);\n}\n\n/** What typing goes into: a key pressed there never activates a pan or a zoom. */\nconst EDITABLE =\n 'input, textarea, select, [contenteditable]:not([contenteditable=\"false\"])';\n\n/** The keys a pointer or wheel event tells itself whether they are held. */\nconst MODIFIERS: Readonly<\n Record<string, \"metaKey\" | \"ctrlKey\" | \"altKey\" | \"shiftKey\">\n> = { Meta: \"metaKey\", Control: \"ctrlKey\", Alt: \"altKey\", Shift: \"shiftKey\" };\n\n/** A viewport action's `duration`, in milliseconds (0 when it leaves it out), or its failure. */\nfunction durationOf(payload: unknown): number | CommandResult<unknown> {\n const { duration } = payloadRecord(payload);\n if (duration === undefined) return 0;\n if (!finite(duration) || duration < 0) {\n return fail(\n \"invalid_payload\",\n \"duration must be a number of milliseconds, 0 or more\",\n \"/duration\",\n );\n }\n return duration;\n}\n\nclass Engine<T extends FlowTypes, F extends FlowFeatures> {\n readonly model: FlowModel;\n readonly adapter: FlowEngineAdapter;\n private options: FlowEngineOptions;\n private minZoom: number;\n private maxZoom: number;\n private readonly measurements: Measurements;\n /** the cached geometry: boxes, edge paths, the grids and the lists built from them */\n private readonly geometry: EngineGeometry;\n private readonly features: ComposedFeatureEngine;\n private readonly shared = new Map<string, unknown>();\n private readonly partOptions = new Map<\n string,\n Readonly<Record<string, unknown>>\n >();\n private readonly listeners = new Set<(event: FlowEngineEvent) => void>();\n private readonly adapterListeners = new Set<(change: ViewChange) => void>();\n private readonly actions: Record<\n Exclude<EngineActionKey, OwnedBy<\"engineRun\">>,\n ActionHandler\n >;\n private current: Viewport;\n private interactivity: Interactivity;\n /** the viewport is changing (a gesture or an animation): `viewport-change-start` was told */\n private moving: { readonly gesture: boolean } | undefined;\n /** a pointer press or a wheel is being handled: its viewport changes belong to one move */\n private handling = 0;\n /** the wheel's rest timer: the move it started ends when it fires */\n private wheelRest: { view: Window; id: number } | undefined;\n /** what the last primary press released (a double click needs two taps) */\n private released: Released | undefined;\n /** the root was sized and a fit on init done (`ready`, once) */\n private ready = false;\n private rootElement: HTMLElement | undefined;\n /**\n * the root's client box, read once per turn: cleared on the root window's next microtask, on\n * `setOptions`, when the root attaches or detaches, and when its observer reports it\n */\n private cachedRootBox: Rect | undefined;\n /** a microtask that clears `cachedRootBox` is queued */\n private rootBoxClearQueued = false;\n private viewportElement: HTMLElement | SVGElement | undefined;\n private removeRootListeners: (() => void) | undefined;\n private press: Press | undefined;\n /**\n * a gesture a tap started that goes on without a press (click-to-connect): the pointer's moves\n * move it, and the next primary press is its own\n */\n private following: FeatureGesture | undefined;\n private pinch: Pinch | undefined;\n private readonly pointers = new Map<number, XY>();\n private pendingFit: FitViewPayload | undefined;\n /**\n * the fit on init, made before every node was measured: redone once they are; the first move\n * of the view that is not a frame of its own animation (`animation`) drops it, and so does\n * stopping an animation\n */\n private refit:\n | { payload: FitViewPayload; animation: (() => void) | undefined }\n | undefined;\n /** the root's size as of the last measurement flush: its observer tells only a change */\n private rootSeen: Size | undefined;\n /** the root's size changed since the last measurement flush */\n private rootChanged = false;\n /** stops the viewport animation under way */\n private stopAnimation: (() => void) | undefined;\n /** the auto-pan's pending frame, and its window */\n private autoPanFrame: { view: Window; id: number } | undefined;\n /** the keys held now (`key` and `code`), from the root's document */\n private readonly heldKeys = new Set<string>();\n /** a non-primary pan moved: the context menu its release opens is kept out */\n private blockContextMenu = false;\n private revision = 0;\n private destroyed = false;\n\n constructor(model: FlowModel<T, F>, options: FlowEngineOptions) {\n this.model = model as unknown as FlowModel;\n this.options = options;\n this.minZoom = options.minZoom ?? 0.5;\n this.maxZoom = Math.max(this.minZoom, options.maxZoom ?? 2);\n const start = options.defaultViewport ?? { x: 0, y: 0, zoom: 1 };\n this.current = {\n x: start.x,\n y: start.y,\n zoom: clampZoom(start.zoom, this.minZoom, this.maxZoom),\n };\n this.interactivity = Object.freeze({\n interactive: options.interactive ?? true,\n drag: true,\n connect: true,\n select: true,\n reconnect: true,\n });\n this.pendingFit =\n options.fitView === true\n ? {}\n : options.fitView === false\n ? undefined\n : options.fitView;\n this.measurements = new Measurements(\n () => this.current.zoom,\n () => this.measured(),\n (nodeId) => this.geometry.node(nodeId) !== undefined,\n () => this.rootResized(),\n );\n this.geometry = new EngineGeometry({\n model: this.model,\n measurements: this.measurements,\n options: () => this.options,\n });\n // a node removed while it was not rendered (culled, hidden) has its kept sizes forgotten\n this.stopPrune = this.model.subscribe(() => this.measurements.prune());\n this.features = featureEngine(featuresOf(model), this.host());\n this.actions = {\n \"set-viewport\": (payload, dryRun) =>\n this.setViewportAction(payload, dryRun),\n \"pan-by\": (payload, dryRun) => {\n const by = pointOf(payload);\n if (!by)\n return fail(\"invalid_payload\", \"x and y must be numbers\");\n return this.apply(\n {\n ...this.current,\n x: this.current.x + by.x,\n y: this.current.y + by.y,\n },\n dryRun,\n );\n },\n \"zoom-in\": (payload, dryRun) => this.zoomStep(payload, dryRun, 1),\n \"zoom-out\": (payload, dryRun) => this.zoomStep(payload, dryRun, -1),\n \"zoom-to\": (payload, dryRun) => {\n const { zoom, around } = payloadRecord(payload);\n if (!finite(zoom) || zoom <= 0) {\n return fail(\n \"invalid_payload\",\n \"zoom must be a positive number\",\n \"/zoom\",\n );\n }\n const duration = durationOf(payload);\n if (typeof duration !== \"number\") return duration;\n return this.apply(\n zoomAround(\n this.current,\n clampZoom(zoom, this.minZoom, this.maxZoom),\n pointOf(around) ?? this.center(),\n ),\n dryRun,\n duration,\n );\n },\n \"fit-view\": (payload, dryRun) =>\n this.fitView(payloadRecord(payload) as FitViewPayload, dryRun),\n \"center-on\": (payload, dryRun) => {\n const at = pointOf(payload);\n const { zoom } = payloadRecord(payload);\n if (!at)\n return fail(\"invalid_payload\", \"x and y must be numbers\");\n if (zoom !== undefined && (!finite(zoom) || zoom <= 0)) {\n return fail(\n \"invalid_payload\",\n \"zoom must be a positive number\",\n \"/zoom\",\n );\n }\n const duration = durationOf(payload);\n if (typeof duration !== \"number\") return duration;\n return this.apply(\n centeredOn(\n at,\n clampZoom(\n zoom ?? this.current.zoom,\n this.minZoom,\n this.maxZoom,\n ),\n this.rootSize(),\n ),\n dryRun,\n duration,\n );\n },\n \"focus-node\": (payload, dryRun) => this.focusNode(payload, dryRun),\n \"set-interactive\": (payload, dryRun) =>\n this.setInteractive(payload, dryRun),\n \"cancel-gesture\": (_payload, dryRun) => {\n this.dropEnded();\n if (\n !this.press &&\n !this.pinch &&\n !this.following &&\n !this.stopAnimation\n ) {\n return fail(\n \"refused\",\n \"no gesture nor viewport animation is under way\",\n );\n }\n if (!dryRun) {\n this.cancelPress();\n this.cancelFollowing();\n this.endPinch();\n this.stopViewportAnimation();\n }\n return ok({});\n },\n };\n this.adapter = this.createAdapter();\n if (options.root) this.attachRoot(options.root);\n }\n\n // ---------------------------------------------------------------------------------------------\n // the verbs\n // ---------------------------------------------------------------------------------------------\n\n /**\n * `set-interactive`: the switches given change, the others stay; a switch turned off cancels\n * the gesture under way (a press, a connection waiting without one).\n */\n private setInteractive(\n payload: unknown,\n dryRun: boolean,\n ): CommandResult<unknown> {\n const record = payloadRecord(payload);\n const keys = [\"interactive\", ...INTERACTION_KINDS] as const;\n const given = keys.filter((key) => record[key] !== undefined);\n if (given.length === 0) {\n return fail(\n \"invalid_payload\",\n \"give at least one of interactive, drag, connect, select, reconnect\",\n );\n }\n for (const key of given) {\n if (typeof record[key] !== \"boolean\") {\n return fail(\n \"invalid_payload\",\n `${key} must be a boolean`,\n `/${key}`,\n );\n }\n }\n const next: Interactivity = Object.freeze({\n ...this.interactivity,\n ...Object.fromEntries(given.map((key) => [key, record[key]])),\n });\n if (dryRun) return ok(next);\n const before = this.interactivity;\n if (keys.some((key) => before[key] !== next[key])) {\n // the gestures a switch turned off stop: every one with `interactive`, else those of\n // that kind (a pan, a resize or another kind's gesture goes on)\n // (a reconnection needs `connect` too, so `connect` off stops one as well)\n const off = (kind: InteractionKind | undefined) =>\n (before.interactive && !next.interactive) ||\n (kind !== undefined && before[kind] && !next[kind]) ||\n (kind === \"reconnect\" && before.connect && !next.connect);\n if (off(this.press?.gesture?.kind)) this.cancelPress();\n if (off(this.following?.kind)) this.cancelFollowing();\n this.interactivity = next;\n this.notify({ gesture: true });\n }\n return ok(this.interactivity);\n }\n\n /** Whether gestures and keys of a kind may change the flow now. */\n private allows(kind: InteractionKind): boolean {\n return this.interactivity.interactive && this.interactivity[kind];\n }\n\n run(action: string, payload?: unknown): CommandResult<unknown> {\n return this.perform(action, payload, false);\n }\n\n can(action: string, payload?: unknown): boolean {\n return this.perform(action, payload, true).ok;\n }\n\n check(action: string, payload?: unknown): CommandResult<unknown> {\n return this.perform(action, payload, true);\n }\n\n private perform(\n action: string,\n payload: unknown,\n dryRun: boolean,\n ): CommandResult<unknown> {\n if (this.destroyed) return fail(\"refused\", \"the engine was destroyed\");\n // an app may have moved or resized the root since the turn's first read\n if (FRESH_BOX_ACTIONS.has(action)) this.cachedRootBox = undefined;\n const handler = Object.hasOwn(this.actions, action)\n ? this.actions[action as keyof typeof this.actions]\n : this.features.run.get(action);\n if (!handler) {\n const owner = featuresOf(this.model).missing(\"engineRun\", action);\n return owner !== undefined\n ? fail(\"not_found\", `\"${action}\" ${requiresFeature(owner)}`)\n : fail(\"unknown_command\", `unknown action \"${action}\"`);\n }\n return handler(payload ?? {}, dryRun);\n }\n\n get(key: string, payload?: unknown): unknown {\n const values = this.getters;\n if (FRESH_BOX_READS.has(key)) this.cachedRootBox = undefined;\n if (Object.hasOwn(values, key)) {\n return values[key as keyof typeof values](payload ?? {});\n }\n return this.features.get.get(key)?.(payload ?? {});\n }\n\n /** The core's `get` keys, made once (a read is hot: an adapter reads per node and edge). */\n private readonly getters = this.makeGetters();\n\n private makeGetters() {\n return {\n viewport: () => this.current,\n \"root-size\": () => this.rootSize(),\n \"edge-path-by\": (p) =>\n this.edgePath(String(payloadRecord(p).edgeId)),\n \"node-rect-by\": (p) =>\n this.nodeRect(String(payloadRecord(p).nodeId)),\n \"nodes-bounds\": (p) => {\n const { nodeIds } = payloadRecord(p);\n return this.boundsOf(\n Array.isArray(nodeIds) ? nodeIds : undefined,\n );\n },\n \"intersecting-nodes\": (p) => this.intersectingNodes(p),\n \"viewport-for-bounds\": (p) => this.viewportForBoundsRead(p),\n \"screen-to-flow\": (p) => {\n const point = pointOf(p);\n return point ? this.toFlow(point) : undefined;\n },\n \"flow-to-screen\": (p) => {\n const point = pointOf(p);\n return point ? this.toClient(point) : undefined;\n },\n \"visible-nodes\": () => this.visibleNodes(),\n \"visible-edges\": () => this.visibleEdges(),\n \"drawn-edges\": () => this.drawnEdges(),\n \"render-layers\": () => this.layering().layers,\n \"node-z-index-by\": (p) =>\n this.nodeZ(String(payloadRecord(p).nodeId)),\n \"handles-by\": (p) =>\n this.handlesOf(String(payloadRecord(p).nodeId)),\n \"internal-node-by\": (p) =>\n this.internalNode(String(payloadRecord(p).nodeId)),\n \"background-pattern\": (p) =>\n backgroundPattern(\n this.current,\n payloadRecord(p) as BackgroundPatternPayload,\n ),\n \"node-toolbar-by\": (p) => {\n const request = payloadRecord(p) as NodeToolbarPayload;\n const many = Array.isArray(request.nodeIds)\n ? request.nodeIds.filter(\n (nodeId): nodeId is string =>\n typeof nodeId === \"string\",\n )\n : [];\n const rect =\n many.length > 0\n ? this.boundsOf(many)\n : typeof request.nodeId === \"string\"\n ? this.knownRect(request.nodeId)\n : undefined;\n return rect\n ? nodeToolbarPosition(rect, this.current, request)\n : undefined;\n },\n \"edge-toolbar-by\": (p) => {\n const request = payloadRecord(\n p,\n ) as unknown as EdgeToolbarPayload;\n const path =\n typeof request.edgeId === \"string\"\n ? this.edgePath(request.edgeId)\n : undefined;\n return path\n ? edgeToolbarPosition(path, this.current, {\n ...request,\n point: pointOf(request.point),\n offset: pointOf(request.offset),\n })\n : undefined;\n },\n } satisfies {\n [G in Exclude<EngineGetKey, OwnedBy<\"engineGet\">>]: (\n payload: unknown,\n ) => unknown;\n };\n }\n\n is(key: string, payload?: unknown): boolean {\n const questions = this.questions;\n if (Object.hasOwn(questions, key)) {\n return questions[key as keyof typeof questions](payload ?? {});\n }\n return this.features.is.get(key)?.(payload ?? {}) ?? false;\n }\n\n /** The core's `is` keys, made once. */\n private readonly questions = this.makeQuestions();\n\n private makeQuestions() {\n return {\n interactive: () => this.interactivity.interactive,\n \"interactive-by\": (p) => {\n const { kind } = payloadRecord(p);\n return (\n typeof kind === \"string\" &&\n (INTERACTION_KINDS as readonly string[]).includes(kind) &&\n this.allows(kind as InteractionKind)\n );\n },\n ready: () => this.ready,\n panning: () =>\n this.pinch !== undefined ||\n (this.press?.pan === true && this.press.travel > 0),\n \"node-measured\": (p) => {\n const node = this.node(String(payloadRecord(p).nodeId));\n return node !== undefined && this.isMeasured(node);\n },\n } satisfies {\n [G in Exclude<EngineIsKey, OwnedBy<\"engineIs\">>]: (\n payload: unknown,\n ) => boolean;\n };\n }\n\n subscribe(listener: (event: FlowEngineEvent) => void): () => void {\n const wrapper = (event: FlowEngineEvent) => listener(event);\n this.listeners.add(wrapper);\n return () => {\n this.listeners.delete(wrapper);\n };\n }\n\n destroy(): void {\n if (this.destroyed) return;\n this.detachRoot();\n this.stopViewportAnimation();\n this.destroyed = true;\n this.features.destroy();\n if (this.viewportElement) clearViewportTransform(this.viewportElement);\n this.viewportElement = undefined;\n this.stopPrune();\n this.measurements.destroy();\n this.geometry.release();\n this.listeners.clear();\n this.adapterListeners.clear();\n this.shared.clear();\n }\n\n // ---------------------------------------------------------------------------------------------\n // the viewport\n // ---------------------------------------------------------------------------------------------\n\n /** A viewport kept to the zoom limits and the translate extent. */\n private kept(viewport: Viewport): Viewport {\n const zoom = clampZoom(viewport.zoom, this.minZoom, this.maxZoom);\n let next: Viewport = { x: viewport.x, y: viewport.y, zoom };\n const extent = this.options.translateExtent;\n const size = this.rootSize();\n if (extent && size.width > 0 && size.height > 0) {\n next = keptInExtent(next, size, extent);\n }\n return next;\n }\n\n /**\n * Sets the viewport: writes its transform, tells the adapters (`change`: what else changed with\n * it, told in the same notification) and the app.\n */\n private setViewport(\n viewport: Viewport,\n gesture: boolean,\n change: Partial<ViewChange> = {},\n ): Viewport {\n // a gesture (a pan, the wheel, a pinch, the minimap, auto-pan) takes the viewport over\n if (gesture) this.stopViewportAnimation();\n const next = this.kept(viewport);\n if (sameViewport(next, this.current)) return this.current;\n if (\n !this.stopAnimation ||\n this.refit?.animation !== this.stopAnimation\n ) {\n this.refit = undefined;\n }\n if (!this.moving) {\n this.moving = { gesture };\n this.emit({\n type: \"viewport-change-start\",\n viewport: this.current,\n gesture,\n });\n }\n this.current = Object.freeze(next);\n if (this.viewportElement) {\n writeViewportTransform(this.viewportElement, this.current);\n }\n this.notify({ ...change, viewport: true });\n this.emit({ type: \"viewport-change\", viewport: this.current, gesture });\n this.settle();\n return this.current;\n }\n\n /**\n * Ends the viewport's move (`viewport-change-end`) once nothing that moves it is under way: no\n * press, pinch, animation or resting wheel, and (unless `now`: an animation was stopped) no\n * press or wheel being handled.\n */\n private settle(now = false): void {\n const moving = this.moving;\n if (\n !moving ||\n (!now && this.handling > 0) ||\n this.press ||\n this.pinch ||\n this.stopAnimation ||\n this.wheelRest\n ) {\n return;\n }\n this.moving = undefined;\n this.emit({\n type: \"viewport-change-end\",\n viewport: this.current,\n gesture: moving.gesture,\n });\n }\n\n /** (Re)starts the wheel's rest timer: the move it started ends when the wheel rests. */\n private restWheel(): void {\n this.stopWheelRest();\n if (!this.moving) return;\n const view = viewOf(this.rootElement);\n if (!view || typeof view.setTimeout !== \"function\") {\n this.settle();\n return;\n }\n const id = view.setTimeout(() => {\n if (this.wheelRest?.id !== id) return;\n this.wheelRest = undefined;\n this.settle();\n }, WHEEL_REST);\n this.wheelRest = { view, id };\n }\n\n private stopWheelRest(): void {\n const rest = this.wheelRest;\n this.wheelRest = undefined;\n if (rest) rest.view.clearTimeout(rest.id);\n }\n\n /**\n * A viewport action's change: at once, or (`duration`, with a root whose window has frames)\n * animated to the viewport it returns; either way an animation under way stops.\n */\n private apply(\n viewport: Viewport,\n dryRun: boolean,\n duration = 0,\n ): CommandResult<unknown> {\n if (\n !finite(viewport.x) ||\n !finite(viewport.y) ||\n !finite(viewport.zoom) ||\n viewport.zoom <= 0\n ) {\n return fail(\n \"invalid_payload\",\n \"the viewport must be finite numbers\",\n );\n }\n if (dryRun) return ok(this.kept(viewport));\n this.stopViewportAnimation();\n const target = this.kept(viewport);\n const view = viewOf(this.rootElement);\n if (\n duration > 0 &&\n view &&\n typeof view.requestAnimationFrame === \"function\" &&\n !sameViewport(target, this.current)\n ) {\n const stop = animateViewport({\n view,\n from: this.current,\n to: target,\n duration,\n easing: this.options.easing,\n step: (next) => {\n this.setViewport(next, false);\n },\n done: () => {\n if (this.stopAnimation === stop) {\n this.stopAnimation = undefined;\n this.settle();\n }\n },\n });\n this.stopAnimation = stop;\n return ok(Object.freeze(target));\n }\n return ok(this.setViewport(viewport, false));\n }\n\n /** Stops the viewport animation under way, where it is. */\n private stopViewportAnimation(): void {\n const stop = this.stopAnimation;\n if (!stop) return;\n this.refit = undefined;\n this.stopAnimation = undefined;\n stop();\n this.settle(true);\n }\n\n private setViewportAction(\n payload: unknown,\n dryRun: boolean,\n ): CommandResult<unknown> {\n const record = payloadRecord(payload);\n for (const key of [\"x\", \"y\", \"zoom\"] as const) {\n if (record[key] !== undefined && !finite(record[key])) {\n return fail(\n \"invalid_payload\",\n `${key} must be a number`,\n `/${key}`,\n );\n }\n }\n const duration = durationOf(payload);\n if (typeof duration !== \"number\") return duration;\n return this.apply(\n {\n x: (record.x as number | undefined) ?? this.current.x,\n y: (record.y as number | undefined) ?? this.current.y,\n zoom: (record.zoom as number | undefined) ?? this.current.zoom,\n },\n dryRun,\n duration,\n );\n }\n\n private zoomStep(\n payload: unknown,\n dryRun: boolean,\n direction: 1 | -1,\n ): CommandResult<unknown> {\n const { step, around } = payloadRecord(payload) as ZoomStepPayload;\n const duration = durationOf(payload);\n if (typeof duration !== \"number\") return duration;\n const factor = step ?? this.options.zoomStep ?? 1.2;\n if (!finite(factor) || factor <= 1) {\n return fail(\n \"invalid_payload\",\n \"step must be a number above 1\",\n \"/step\",\n );\n }\n const zoom = clampZoom(\n direction > 0\n ? this.current.zoom * factor\n : this.current.zoom / factor,\n this.minZoom,\n this.maxZoom,\n );\n if (zoom === this.current.zoom) {\n return fail(\n \"refused\",\n direction > 0\n ? \"the zoom is at its greatest\"\n : \"the zoom is at its least\",\n );\n }\n return this.apply(\n zoomAround(this.current, zoom, pointOf(around) ?? this.center()),\n dryRun,\n duration,\n );\n }\n\n private fitView(\n payload: FitViewPayload,\n dryRun: boolean,\n ): CommandResult<unknown> {\n const duration = durationOf(payload);\n if (typeof duration !== \"number\") return duration;\n if (payload.padding !== undefined && !isFitPadding(payload.padding)) {\n return fail(\n \"invalid_payload\",\n 'padding must be a number, a \"<n>px\" string, or { top, right, bottom, left } of them',\n \"/padding\",\n );\n }\n const size = this.rootSize();\n if (size.width <= 0 || size.height <= 0) {\n return fail(\"refused\", \"the root has no size yet\");\n }\n const bounds = this.boundsOf(\n payload.nodeIds,\n payload.includeHidden === true,\n );\n if (!bounds) return fail(\"refused\", \"no node has a size yet\");\n return this.apply(\n this.framing(bounds, size, payload),\n dryRun,\n duration,\n );\n }\n\n /**\n * The viewport that frames `bounds` in the root (`viewportForBounds`): `fit-view`'s and\n * `viewport-for-bounds`'; its own zoom limits default to the engine's (which still bound it).\n */\n private framing(\n bounds: Rect,\n size: Size,\n options: ViewportForBoundsOptions,\n ): Viewport {\n return viewportForBounds(bounds, size.width, size.height, {\n padding: options.padding ?? 0.1,\n minZoom: options.minZoom ?? this.minZoom,\n maxZoom: options.maxZoom ?? this.maxZoom,\n });\n }\n\n /** `viewport-for-bounds`: the viewport `fit-view` would set for a flow rectangle. */\n private viewportForBoundsRead(payload: unknown): Viewport | undefined {\n const record = payloadRecord(payload);\n const bounds = payloadRecord(record.bounds);\n const size = this.rootSize();\n if (\n size.width <= 0 ||\n size.height <= 0 ||\n !finite(bounds.x) ||\n !finite(bounds.y) ||\n !finite(bounds.width) ||\n !finite(bounds.height) ||\n bounds.width < 0 ||\n bounds.height < 0\n ) {\n return undefined;\n }\n return Object.freeze(\n this.kept(\n this.framing(\n {\n x: bounds.x,\n y: bounds.y,\n width: bounds.width,\n height: bounds.height,\n },\n size,\n {\n padding: isFitPadding(record.padding)\n ? record.padding\n : undefined,\n minZoom: finite(record.minZoom)\n ? record.minZoom\n : undefined,\n maxZoom: finite(record.maxZoom)\n ? record.maxZoom\n : undefined,\n },\n ),\n ),\n );\n }\n\n private focusNode(\n payload: unknown,\n dryRun: boolean,\n ): CommandResult<unknown> {\n const nodeId = payloadRecord(payload).nodeId;\n if (typeof nodeId !== \"string\") {\n return fail(\n \"invalid_payload\",\n \"nodeId must be a string\",\n \"/nodeId\",\n );\n }\n if (!this.model.get(\"node-by\", { id: nodeId })) {\n return fail(\"not_found\", `no node \"${nodeId}\"`, \"/nodeId\");\n }\n const element = this.measurements.nodeElement(nodeId);\n if (!element)\n return fail(\n \"refused\",\n `node \"${nodeId}\" is not rendered`,\n \"/nodeId\",\n );\n if (dryRun) return ok({ nodeId });\n if (element.ownerDocument.activeElement !== element) {\n element.focus({ preventScroll: true });\n }\n this.reveal(nodeId);\n return ok({ nodeId });\n }\n\n /** Pans a node into view (its centre in the root's centre) when it is not wholly in view. */\n private reveal(nodeId: string): void {\n const rect = this.knownRect(nodeId);\n const size = this.rootSize();\n if (!rect || size.width <= 0) return;\n const view = viewRect(this.current, size);\n const inside =\n rect.x >= view.x &&\n rect.y >= view.y &&\n rect.x + rect.width <= view.x + view.width &&\n rect.y + rect.height <= view.y + view.height;\n if (!inside) {\n this.stopViewportAnimation();\n this.setViewport(\n centeredOn(\n { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 },\n this.current.zoom,\n size,\n ),\n false,\n );\n }\n }\n\n /**\n * The root's client box (its position on the page and its size), read once until the next\n * microtask: every read that needs the view asks for it, and a layout forced per read is what\n * an adapter's render pays (Vue patches a node between two reads). The app's own verbs that\n * place or map the view read it again (`FRESH_BOX_ACTIONS`, `FRESH_BOX_READS`). Cleared with\n * a promise, not the window's `queueMicrotask`, which an app's fake timers may hold.\n */\n private rootBox(): Rect {\n if (this.cachedRootBox) return this.cachedRootBox;\n const element = this.rootElement;\n if (!element) return { x: 0, y: 0, width: 0, height: 0 };\n const box = element.getBoundingClientRect();\n const rect = {\n x: box.left,\n y: box.top,\n width: box.width,\n height: box.height,\n };\n this.cachedRootBox = rect;\n if (!this.rootBoxClearQueued) {\n this.rootBoxClearQueued = true;\n void Promise.resolve().then(() => {\n this.rootBoxClearQueued = false;\n this.cachedRootBox = undefined;\n });\n }\n return rect;\n }\n\n private rootSize(): Size {\n const box = this.rootBox();\n return box.width > 0 || box.height > 0\n ? { width: box.width, height: box.height }\n : ZERO_SIZE;\n }\n\n private center(): XY {\n const size = this.rootSize();\n return { x: size.width / 2, y: size.height / 2 };\n }\n\n private toRoot(client: XY): XY {\n const box = this.rootBox();\n return { x: client.x - box.x, y: client.y - box.y };\n }\n\n private toFlow(client: XY): XY {\n return toFlow(this.current, this.toRoot(client));\n }\n\n private toClient(point: XY): XY {\n const box = this.rootBox();\n const screen = toScreen(this.current, point);\n return { x: screen.x + box.x, y: screen.y + box.y };\n }\n\n /** How far a press on the pane, or on anything else, may move and still be a tap. */\n private tapDistance(on: \"pane\" | \"node\"): number {\n const option =\n on === \"pane\"\n ? this.options.paneClickDistance\n : this.options.nodeClickDistance;\n return finite(option) && option >= 0 ? option : TAP_TOLERANCE;\n }\n\n /** The tap distance of a press on `target`. */\n private tapDistanceOf(target: PressTarget): number {\n return this.tapDistance(target.kind === \"pane\" ? \"pane\" : \"node\");\n }\n\n // ---------------------------------------------------------------------------------------------\n // nodes, handles and edges on screen\n // ---------------------------------------------------------------------------------------------\n\n /** A node of the document by id (the geometry's index: no payload or reader per call). */\n private node(nodeId: string): FlowNode | undefined {\n return this.geometry.node(nodeId);\n }\n\n /**\n * A node's size: the document's `width` / `height` where it gives them, the measured one\n * otherwise, its `initialWidth` / `initialHeight` until it is measured.\n */\n private sizeOf(node: FlowNode): Size | undefined {\n return nodeSize(node, this.measuredSize(node.id));\n }\n\n /** A node's measured size, when it has some (an empty one is not). */\n private measuredSize(nodeId: string): Size | undefined {\n const measured = this.measurements.size(nodeId);\n return measured && (measured.width > 0 || measured.height > 0)\n ? measured\n : undefined;\n }\n\n /** Whether a node's size is measured or given by the document (`node-measured`; not initial). */\n private isMeasured(node: FlowNode): boolean {\n const measured = this.measuredSize(node.id);\n return (\n (node.width ?? measured?.width) !== undefined &&\n (node.height ?? measured?.height) !== undefined\n );\n }\n\n /** What the pure node layout reads of this engine: its nodes, sizes and `nodeOrigin`. */\n private layoutNow(): NodeLayout {\n return {\n node: (nodeId) => this.node(nodeId),\n size: (node) => this.sizeOf(node),\n nodeOrigin: this.options.nodeOrigin,\n };\n }\n\n /**\n * The share of a node's size its position stands at: its `origin`, else the engine's\n * `nodeOrigin`, for a node on the flow; the top-left corner for a child (`nodeOriginOf`).\n */\n private originOf(node: FlowNode): XY {\n return nodeOriginOf(node, this.layoutNow());\n }\n\n /** A node's position in absolute flow coordinates: its parent's top-left corner plus its own. */\n private absolutePosition(node: FlowNode): XY {\n return nodeAbsolutePosition(node, this.layoutNow());\n }\n\n /** A node's absolute box (`nodeBox`: its position at its origin), its size zero until known. */\n private boxOf(node: FlowNode): Rect {\n return this.geometry.boxOf(node);\n }\n\n /** The top-left corner of a node's parent's box (0, 0 without one). */\n private parentCorner(node: FlowNode): XY {\n const parent =\n node.parentId === undefined ? undefined : this.node(node.parentId);\n return parent ? this.boxOf(parent) : TOP_LEFT;\n }\n\n /** A node's registered handles, placed. */\n private handlesOf(nodeId: string): readonly FlowHandle[] {\n return this.measurements\n .handlesOf(nodeId)\n .map((handle) => this.placed(handle));\n }\n\n /** A node as the engine knows it on screen (`internal-node-by`). */\n private internalNode(nodeId: string): InternalNode | undefined {\n const node = this.node(nodeId);\n if (!node) return undefined;\n const rect = this.boxOf(node);\n return {\n id: node.id,\n node,\n // the engine's own layout, as `node-rect-by` (each origin applied)\n absolutePosition: this.absolutePosition(node),\n rect,\n measured: this.isMeasured(node),\n zIndex: this.nodeZ(nodeId),\n handles: this.handlesOf(nodeId),\n };\n }\n\n /** A node's absolute box, its size zero until known. */\n private nodeRect(nodeId: string): Rect | undefined {\n return this.geometry.box(nodeId);\n }\n\n /** A node's absolute box, once its size is known. */\n private knownRect(nodeId: string): Rect | undefined {\n return this.geometry.knownRect(nodeId);\n }\n\n /**\n * The position (relative to its parent) that puts a node's box of `size` with its top-left\n * corner at the absolute flow point `corner`.\n */\n private positionFor(nodeId: string, corner: XY, size: Size): XY {\n const node = this.node(nodeId);\n if (!node) return corner;\n const parent = this.parentCorner(node);\n const origin = this.originOf(node);\n return {\n x: corner.x + origin.x * size.width - parent.x,\n y: corner.y + origin.y * size.height - parent.y,\n };\n }\n\n /**\n * The absolute rectangle a node's box stays inside: its parent's box (`extent: \"parent\"`,\n * with the measured sizes), its own rectangle `extent` (relative to its parent's top-left\n * corner for a child) and the engine's `nodeExtent`, together; none when nothing bounds it.\n */\n private extentOf(nodeId: string): Rect | undefined {\n const node = this.node(nodeId);\n if (!node) return undefined;\n const bounds: Rect[] = [];\n const parent =\n node.parentId === undefined ? undefined : this.node(node.parentId);\n const corner = parent ? this.boxOf(parent) : TOP_LEFT;\n if (parent && node.extent === \"parent\" && node.expandParent !== true) {\n const room = this.sizeOf(parent);\n bounds.push({\n x: corner.x,\n y: corner.y,\n width: room?.width ?? Number.POSITIVE_INFINITY,\n height: room?.height ?? Number.POSITIVE_INFINITY,\n });\n }\n const own = node.extent;\n if (typeof own === \"object\" && own !== null) {\n bounds.push({\n x: corner.x + own.x,\n y: corner.y + own.y,\n width: own.width,\n height: own.height,\n });\n }\n if (this.options.nodeExtent) bounds.push(this.options.nodeExtent);\n return intersectionOf(bounds);\n }\n\n /**\n * A node's position (relative to its parent) kept inside its extent (`extentOf`) with its\n * measured size; `size` overrides it (a resize under way).\n */\n private keepInExtent(nodeId: string, position: XY, size?: Size): XY {\n const node = this.node(nodeId);\n const bounds = this.extentOf(nodeId);\n if (!node || !bounds) return position;\n const own = size ?? this.sizeOf(node) ?? ZERO_SIZE;\n const parent = this.parentCorner(node);\n const origin = this.originOf(node);\n const corner = {\n x: parent.x + position.x - origin.x * own.width,\n y: parent.y + position.y - origin.y * own.height,\n };\n const kept = cornerInside(corner, own, bounds);\n return {\n x:\n kept.x === corner.x\n ? position.x\n : kept.x + origin.x * own.width - parent.x,\n y:\n kept.y === corner.y\n ? position.y\n : kept.y + origin.y * own.height - parent.y,\n };\n }\n\n /** A node's stack value by the `zIndexMode` (`nodeStackValue`). */\n private nodeValue(node: FlowNode): number {\n return this.geometry.nodeValue(node);\n }\n\n /**\n * A node's structural `z-index`: its stack value with a single render level, its rank among\n * the layers' (negative) otherwise; 0 for an unknown node.\n */\n private nodeZ(nodeId: string): number {\n const node = this.node(nodeId);\n if (node === undefined) return 0;\n return this.layering().zIndexes?.get(nodeId) ?? this.nodeValue(node);\n }\n\n /** The render layers (`render-layers`): recomputed when the flow, the options or what is drawn change. */\n private layering(): Layering {\n return this.geometry.layering(this.view(), this.culled());\n }\n\n /** Whether the adapters render only what is in view (`onlyRenderVisible`). */\n private culled(): boolean {\n return this.options.onlyRenderVisible ?? false;\n }\n\n private boundsOf(\n nodeIds: readonly unknown[] | undefined,\n includeHidden = false,\n ): Rect | undefined {\n if (!nodeIds) return this.geometry.bounds(includeHidden);\n const ids = nodeIds.filter(\n (id): id is string => typeof id === \"string\",\n );\n return boundsOf(\n ids.flatMap((id) => {\n const rect = this.knownRect(id);\n return rect ? [rect] : [];\n }),\n );\n }\n\n /**\n * `intersecting-nodes`: the shown nodes of known size whose box shares area with a node's box\n * or a rectangle (`partial: false`: lies inside it), the node itself left out.\n */\n private intersectingNodes(payload: unknown): readonly FlowNode[] {\n const record = payloadRecord(payload);\n const nodeId =\n typeof record.nodeId === \"string\" ? record.nodeId : undefined;\n const rect = payloadRecord(record.rect);\n const area =\n nodeId !== undefined\n ? this.knownRect(nodeId)\n : finite(rect.x) &&\n finite(rect.y) &&\n finite(rect.width) &&\n finite(rect.height) &&\n rect.width >= 0 &&\n rect.height >= 0\n ? {\n x: rect.x,\n y: rect.y,\n width: rect.width,\n height: rect.height,\n }\n : undefined;\n if (!area) return [];\n return this.geometry.intersecting(\n area,\n nodeId,\n record.partial !== false,\n );\n }\n\n /** A handle with its absolute centre (once it and its node are measured). */\n private placed(handle: FlowHandle): FlowHandle {\n return this.geometry.placed(handle);\n }\n\n private handles(): FlowHandle[] {\n return this.measurements\n .allHandles()\n .map((handle) => this.placed(handle));\n }\n\n private edgePath(edgeId: string): EdgePath | undefined {\n return this.geometry.edgePath(edgeId);\n }\n\n private view(): Rect | undefined {\n const size = this.rootSize();\n return size.width > 0 && size.height > 0\n ? viewRect(this.current, size)\n : undefined;\n }\n\n /** `visible-nodes`: the shown nodes in view and those of unknown size (none culled before the root has a size). */\n private visibleNodes(): readonly FlowNode[] {\n return this.geometry.visibleNodes(this.view(), this.culled());\n }\n\n /** `visible-edges`: the drawn edges whose ends' box is in view. */\n private visibleEdges(): readonly FlowEdge[] {\n return this.geometry.visibleEdges(this.view(), this.culled());\n }\n\n /**\n * The edges an adapter draws, in drawing order: those shown whose nodes are measured (with\n * `onlyRenderVisible`, those in view), by their stacking value, the document's order among\n * equals.\n */\n private drawnEdges(): readonly FlowEdge[] {\n return this.geometry.drawnEdges(this.view(), this.culled());\n }\n\n /**\n * Something was measured: the adapters hear it once per task (a mount registers many nodes and\n * handles in one commit), through the root window's microtask queue; without a root, now.\n */\n private measured(): void {\n if (this.measureQueued) return;\n const view = viewOf(this.rootElement);\n if (!view || typeof view.queueMicrotask !== \"function\") {\n this.flushMeasured();\n return;\n }\n this.measureQueued = true;\n view.queueMicrotask(() => {\n this.measureQueued = false;\n this.flushMeasured();\n });\n }\n\n private measureQueued = false;\n\n private readonly stopPrune: () => void;\n\n /** The observer reported the root: a new size is told as a measurement, with the viewport. */\n private rootResized(): void {\n this.cachedRootBox = undefined;\n const size = this.rootSize();\n const seen = this.rootSeen;\n // the same size (the report of `observe`, a move): nothing, so no resize loop either\n if (seen?.width === size.width && seen.height === size.height) return;\n this.rootSeen = size;\n this.rootChanged = true;\n this.measured();\n }\n\n private flushMeasured(): void {\n if (this.destroyed) return;\n const viewport = this.rootChanged;\n this.rootChanged = false;\n this.notify({ measured: true, viewport });\n if (!this.rootElement) return;\n // a fit on init counts initial sizes as known, and is redone once on the measured ones\n const { shown, sized: all, measured } = this.geometry.readiness();\n const fit = this.pendingFit;\n const refit = this.refit;\n if (fit && shown > 0 && all) {\n const result = this.fitView(fit, false);\n if (result.ok) {\n this.pendingFit = undefined;\n if (!measured) {\n this.refit = {\n payload: fit,\n animation: this.stopAnimation,\n };\n }\n }\n } else if (refit && measured) {\n // still pending: the view has not moved but for the fit's own animation\n this.refit = undefined;\n this.fitView(refit.payload, false);\n }\n // ready once: a sized root (and a pending fit done)\n const size = this.rootSize();\n this.rootSeen = size;\n if (\n !this.ready &&\n size.width > 0 &&\n size.height > 0 &&\n (this.pendingFit === undefined || shown === 0)\n ) {\n this.ready = true;\n // a reactive read of `is(\"ready\")` sees it\n this.notify({ measured: true });\n this.emit({ type: \"ready\" });\n }\n }\n\n // ---------------------------------------------------------------------------------------------\n // notifications\n // ---------------------------------------------------------------------------------------------\n\n private notify(change: Partial<ViewChange>): void {\n if (this.destroyed) return;\n this.revision += 1;\n const full: ViewChange = {\n viewport: change.viewport ?? false,\n measured: change.measured ?? false,\n gesture: change.gesture ?? false,\n };\n for (const listener of [...this.adapterListeners]) listener(full);\n }\n\n private emit(event: FlowEngineEvent): void {\n if (this.destroyed) return;\n for (const listener of [...this.listeners]) listener(event);\n }\n\n private host(): FeatureEngineHost {\n return {\n model: this.model as unknown as FeatureModel,\n shared: <V>(key: string, create: () => V): V => {\n if (!this.shared.has(key)) this.shared.set(key, create());\n return this.shared.get(key) as V;\n },\n root: () => this.rootElement,\n viewport: () => this.current,\n zoomLimits: () => ({ min: this.minZoom, max: this.maxZoom }),\n setViewport: (viewport) => this.setViewport(viewport, true),\n rootSize: () => this.rootSize(),\n toRoot: (client) => this.toRoot(client),\n toFlow: (client) => this.toFlow(client),\n nodeRect: (nodeId) => this.nodeRect(nodeId),\n measured: (nodeId) => this.knownRect(nodeId) !== undefined,\n handles: () => this.handles(),\n edgePath: (edgeId) => this.edgePath(edgeId),\n absolutePosition: (nodeId) => {\n const node = this.node(nodeId);\n return node ? this.absolutePosition(node) : undefined;\n },\n positionFor: (nodeId, corner, size) =>\n this.positionFor(nodeId, corner, size),\n extentOf: (nodeId) => this.extentOf(nodeId),\n keepInExtent: (nodeId, position, size) =>\n this.keepInExtent(nodeId, position, size),\n held: (key, event) => this.held(key, event),\n nodeElement: (nodeId) => this.measurements.nodeElement(nodeId),\n interactive: () => this.interactivity.interactive,\n allows: (kind) => this.allows(kind),\n tapDistance: (on) => this.tapDistance(on),\n focusable: (kind) =>\n (kind === \"node\"\n ? this.options.nodesFocusable\n : this.options.edgesFocusable) !== false,\n toClient: (point) => this.toClient(point),\n path: (type, ends) =>\n pathOf(type, ends, this.options.pathOptions ?? {}),\n partOptions: (part, id) =>\n this.partOptions.get(`${part}\\u0000${id}`),\n changed: () => this.notify({ gesture: true }),\n emit: (event) => this.emit(event),\n };\n }\n\n // ---------------------------------------------------------------------------------------------\n // the root's events\n // ---------------------------------------------------------------------------------------------\n\n private attachRoot(element: HTMLElement): void {\n if (this.rootElement === element) return;\n this.detachRoot();\n this.rootElement = element;\n this.cachedRootBox = undefined;\n // the browser must not take touches for its own scroll or zoom: they would cancel gestures\n writeRootTouchAction(element);\n const listeners: [string, EventListener, AddEventListenerOptions?][] = [\n [\"pointerdown\", (event) => this.pointerDown(event as PointerEvent)],\n [\"pointermove\", (event) => this.pointerMove(event as PointerEvent)],\n [\"pointerup\", (event) => this.pointerUp(event as PointerEvent)],\n [\n \"pointercancel\",\n (event) => this.pointerLost(event as PointerEvent),\n ],\n [\n \"lostpointercapture\",\n (event) => this.pointerLost(event as PointerEvent),\n ],\n [\n \"wheel\",\n (event) => this.wheel(event as WheelEvent),\n { passive: false },\n ],\n [\"dblclick\", (event) => this.doubleClick(event as MouseEvent)],\n [\"keydown\", (event) => this.keyDown(event as KeyboardEvent)],\n [\"focusin\", (event) => this.focusIn(event as FocusEvent)],\n [\"focusout\", (event) => this.focusOut(event as FocusEvent)],\n [\"contextmenu\", (event) => this.contextMenu(event as MouseEvent)],\n ];\n for (const [type, listener, options] of listeners) {\n element.addEventListener(type, listener, options);\n }\n // the activation keys are held anywhere in the page, not only with focus in the flow\n const doc = element.ownerDocument;\n const view = viewOf(element);\n const keyListeners: [EventTarget | undefined, string, EventListener][] =\n [\n [\n doc,\n \"keydown\",\n (event) => this.keyHeld(event as KeyboardEvent, true),\n ],\n [\n doc,\n \"keyup\",\n (event) => this.keyHeld(event as KeyboardEvent, false),\n ],\n [view, \"blur\", () => this.heldKeys.clear()],\n ];\n for (const [target, type, listener] of keyListeners) {\n target?.addEventListener(type, listener);\n }\n this.removeRootListeners = () => {\n for (const [type, listener, options] of listeners) {\n element.removeEventListener(type, listener, options);\n }\n for (const [target, type, listener] of keyListeners) {\n target?.removeEventListener(type, listener);\n }\n };\n this.features.attached(element);\n this.measurements.observeRoot(element);\n this.measurements.measureAll();\n this.measured();\n }\n\n private detachRoot(): void {\n if (!this.rootElement) return;\n this.cancelPress();\n this.cancelFollowing();\n this.endPinch();\n this.stopWheelRest();\n this.released = undefined;\n // the frames are the root window's: another root may be in another window\n this.stopViewportAnimation();\n this.stopAutoPan();\n this.heldKeys.clear();\n this.blockContextMenu = false;\n this.pointers.clear();\n this.features.detached();\n this.measurements.observeRoot(undefined);\n this.rootSeen = undefined;\n this.removeRootListeners?.();\n this.removeRootListeners = undefined;\n clearRootTouchAction(this.rootElement);\n this.rootElement = undefined;\n this.cachedRootBox = undefined;\n this.settle(true);\n }\n\n private target(eventTarget: EventTarget | null): PressTarget {\n const root = this.rootElement;\n if (!root) return { kind: \"other\", element: undefined };\n return pressTargetOf(root, eventTarget, (element) =>\n this.measurements.handleOf(element, (handle) =>\n this.placed(handle),\n ),\n );\n }\n\n private capture(pointerId: number): void {\n try {\n this.rootElement?.setPointerCapture?.(pointerId);\n } catch {\n // a pointer that is no longer active cannot be captured: its moves still bubble here\n }\n }\n\n private release(pointerId: number): void {\n try {\n if (this.rootElement?.hasPointerCapture?.(pointerId)) {\n this.rootElement.releasePointerCapture(pointerId);\n }\n } catch {\n // already released\n }\n }\n\n private pointerDown(event: PointerEvent): void {\n if (this.destroyed) return;\n // the viewport changes of a press (the minimap centres on it) are one move with its drag\n this.handling++;\n try {\n this.pressDown(event);\n } finally {\n this.handling--;\n this.settle();\n }\n }\n\n private pressDown(event: PointerEvent): void {\n this.dropEnded();\n // a double click counts this press's release only (a press that starts nothing has none)\n this.released = undefined;\n const client = { x: event.clientX, y: event.clientY };\n // only touch pointers pinch: the others are never tracked\n if (event.pointerType === \"touch\") {\n this.pointers.set(event.pointerId, client);\n }\n if (this.pinch) return;\n let press = this.press;\n // a press whose release was missed (outside the root, its capture refused) ends where its\n // pointer was last seen, as if released there\n if (\n press &&\n (press.pointerId === event.pointerId ||\n event.pointerType !== \"touch\")\n ) {\n this.press = undefined;\n this.stopAutoPan();\n this.release(press.pointerId);\n if (press.last) press.gesture?.end(press.last);\n else press.gesture?.cancel();\n this.released = undefined;\n press = undefined;\n }\n if (press) {\n // a second finger on a pan (or a press that did nothing yet) pinches\n if (\n event.pointerType === \"touch\" &&\n (this.options.zoomOnPinch ?? true) &&\n (press.pan ||\n press.gesture === undefined ||\n press.gesture.active?.() !== true) &&\n this.pointers.size === 2\n ) {\n this.startPinch(press.pointerId, event.pointerId);\n event.preventDefault();\n }\n return;\n }\n if (event.isPrimary === false) return;\n this.blockContextMenu = false;\n // a touch or a pen presses as the primary button\n const button = event.pointerType === \"mouse\" ? event.button : 0;\n // a mouse button that does not pan starts nothing (a feature's gestures are primary)\n if (button !== 0 && !this.pansWith(button)) return;\n const target = this.target(event.target);\n if (target.kind === \"other\") {\n this.pointers.delete(event.pointerId);\n return;\n }\n let gesture: FeatureGesture | undefined;\n let pan = false;\n const keyPan = button === 0 && this.panKeyHeld(event);\n const following = button === 0 && !keyPan ? this.following : undefined;\n if (following) {\n // the gesture a tap started takes the next press: its release is the gesture's end\n this.following = undefined;\n gesture = following;\n } else if (keyPan) {\n // the pan activation key: a pan from anywhere, and no other gesture\n gesture = this.panGesture(client);\n pan = true;\n } else if (button !== 0) {\n if (target.kind !== \"pane\") return;\n gesture = this.panGesture(client);\n pan = true;\n } else {\n gesture = this.features.pointerdown(event, target);\n if (!gesture && target.kind === \"pane\" && this.pansWith(0)) {\n gesture = this.panGesture(client);\n pan = true;\n }\n }\n this.press = {\n pointerId: event.pointerId,\n start: client,\n target,\n gesture,\n pan,\n button,\n keyPan,\n follows: following !== undefined,\n travel: 0,\n menu: false,\n last: undefined,\n };\n this.capture(event.pointerId);\n // the pane's presses select no text; a node's keep their default (focus)\n if (target.kind !== \"node\" && target.kind !== \"edge\")\n event.preventDefault();\n }\n\n /** Whether a press of a mouse button (0 for a touch or a pen) pans the pane (`panOnDrag`). */\n private pansWith(button: number): boolean {\n const option = this.options.panOnDrag ?? true;\n return typeof option === \"boolean\"\n ? option && button === 0\n : option.includes(button);\n }\n\n /** Whether `key` is held now: a modifier as `event` tells it, any other from the document's keys. */\n private held(\n key: string | null,\n event: MouseEvent | KeyboardEvent,\n ): boolean {\n if (key === null || key === \"\") return false;\n const modifier = MODIFIERS[key];\n return modifier !== undefined\n ? event[modifier]\n : this.heldKeys.has(key);\n }\n\n private panKeyHeld(event: MouseEvent): boolean {\n const key = this.options.panActivationKey;\n return this.held(key === undefined ? \" \" : key, event);\n }\n\n private zoomKeyHeld(event: MouseEvent): boolean {\n const key = this.options.zoomActivationKey;\n if (key !== undefined) return this.held(key, event);\n const agent = viewOf(this.rootElement)?.navigator;\n const platform = `${agent?.platform ?? \"\"} ${agent?.userAgent ?? \"\"}`;\n return this.held(\n /Mac|iPhone|iPad|iPod/.test(platform) ? \"Meta\" : \"Control\",\n event,\n );\n }\n\n /** A key went down or up in the root's document: the activation keys read it. */\n private keyHeld(event: KeyboardEvent, down: boolean): void {\n this.dropEnded();\n // a connection a tap started waits without a press, often with focus outside the root (the\n // handle's press kept it from moving): Escape anywhere in the page cancels it\n if (down && event.key === \"Escape\" && this.following && !this.press) {\n this.cancelFollowing();\n event.preventDefault();\n return;\n }\n if (down) {\n // typing in a field (a node's, the page's) holds no activation key\n if (asElement(event.target)?.closest?.(EDITABLE)) return;\n this.heldKeys.add(event.key);\n this.heldKeys.add(event.code);\n } else {\n this.heldKeys.delete(event.key);\n this.heldKeys.delete(event.code);\n }\n }\n\n /**\n * A middle or right button pan keeps the context menu out while it is pressed (macOS and Linux\n * open it on press, before any move), and a right-button pan that moved after its release\n * (Windows opens it on release).\n */\n private contextMenu(event: MouseEvent): void {\n if (this.destroyed) return;\n const press = this.press;\n const panning = press?.pan === true && press.button !== 0;\n const blocked = panning || this.blockContextMenu;\n this.blockContextMenu = false;\n if (blocked) {\n event.preventDefault();\n return;\n }\n // during a captured press (a long press, Ctrl + click) the menu targets the root: it is\n // the press's, whose release is then no tap\n if (press) press.menu = true;\n this.emitPointer(\n \"context-menu\",\n press?.target ?? this.target(event.target),\n event,\n );\n }\n\n private panGesture(start: XY): FeatureGesture {\n // a pan takes the viewport over from an animation, where it is\n this.stopViewportAnimation();\n const origin = this.current;\n let moved = false;\n return {\n move: (event) => {\n const first = !moved;\n moved = true;\n const before = this.current;\n // the panning state changed once, on the first move: told with the viewport's\n // change, in one notification\n this.setViewport(\n {\n x: origin.x + event.clientX - start.x,\n y: origin.y + event.clientY - start.y,\n zoom: origin.zoom,\n },\n true,\n first ? { gesture: true } : {},\n );\n if (first && this.current === before) {\n this.notify({ gesture: true });\n }\n },\n end: () => {\n if (moved) this.notify({ gesture: true });\n },\n cancel: () => {\n this.setViewport(origin, true);\n this.notify({ gesture: true });\n },\n active: () => (this.press?.travel ?? 0) > this.tapDistance(\"pane\"),\n };\n }\n\n private pointerMove(event: PointerEvent): void {\n if (this.destroyed) return;\n this.dropEnded();\n const client = { x: event.clientX, y: event.clientY };\n if (this.pointers.has(event.pointerId))\n this.pointers.set(event.pointerId, client);\n if (this.pinch) {\n if (this.pinch.ids.includes(event.pointerId)) this.movePinch();\n return;\n }\n const press = this.press;\n if (!press) {\n // a gesture a tap started follows the pointer without a press\n if (event.isPrimary !== false) this.following?.move(event);\n return;\n }\n if (press.pointerId !== event.pointerId) return;\n press.travel = Math.max(press.travel, distance(press.start, client));\n press.last = event;\n press.gesture?.move(event);\n this.autoPan();\n }\n\n /** The auto-pan offset of the press under way now (zero when it does not auto-pan). */\n private autoPanNow(): XY {\n const press = this.press;\n const gesture = press?.gesture;\n if (\n !press?.last ||\n press.pan ||\n !autoPans(this.options.autoPan, gesture?.autoPan) ||\n gesture?.active?.() !== true\n ) {\n return { x: 0, y: 0 };\n }\n return autoPanOffset(\n this.toRoot({ x: press.last.clientX, y: press.last.clientY }),\n this.rootSize(),\n this.options.autoPan,\n );\n }\n\n /** Starts the auto-pan loop when the press's pointer is near the edge (one loop per engine). */\n private autoPan(): void {\n if (this.autoPanFrame || this.destroyed) return;\n const offset = this.autoPanNow();\n if (offset.x === 0 && offset.y === 0) return;\n const view = viewOf(this.rootElement);\n if (!view || typeof view.requestAnimationFrame !== \"function\") return;\n const id = view.requestAnimationFrame(() => {\n this.autoPanFrame = undefined;\n this.autoPanStep();\n });\n this.autoPanFrame = { view, id };\n }\n\n /**\n * One auto-pan frame: the viewport pans, and the gesture moves again with its last pointer\n * event (the flow point under the still pointer changed). It stops at the translate extent and\n * when the pointer leaves the edge; the next move starts it again.\n */\n private autoPanStep(): void {\n const offset = this.autoPanNow();\n const last = this.press?.last;\n if (!last || (offset.x === 0 && offset.y === 0)) return;\n const before = this.current;\n const after = this.setViewport(\n {\n x: before.x + offset.x,\n y: before.y + offset.y,\n zoom: before.zoom,\n },\n true,\n );\n if (sameViewport(before, after)) return;\n this.press?.gesture?.move(last);\n this.autoPan();\n }\n\n private stopAutoPan(): void {\n const frame = this.autoPanFrame;\n this.autoPanFrame = undefined;\n if (frame) frame.view.cancelAnimationFrame(frame.id);\n }\n\n private pointerUp(event: PointerEvent): void {\n if (this.destroyed) return;\n this.pointers.delete(event.pointerId);\n if (this.pinch) {\n if (this.pinch.ids.includes(event.pointerId)) this.endPinch();\n return;\n }\n const press = this.press;\n if (!press || press.pointerId !== event.pointerId) return;\n this.press = undefined;\n this.stopAutoPan();\n this.release(event.pointerId);\n const active = press.gesture?.active?.() ?? false;\n press.gesture?.end(event);\n const within = press.travel <= this.tapDistanceOf(press.target);\n if (press.button !== 0) {\n // the context menu a moved right-button pan's release opens stays out\n this.blockContextMenu = press.pan && press.button === 2 && !within;\n this.settle();\n return;\n }\n // a tap: released within the tap distance, no gesture started, not a key pan nor the\n // release of a connection a tap began (click-to-connect)\n const tap =\n !press.keyPan && !press.follows && !press.menu && !active && within;\n this.released = { target: press.target, tap };\n if (tap) {\n if (this.interactivity.interactive) {\n const taken = this.features.tap(event, press.target);\n if (typeof taken === \"object\") {\n this.cancelFollowing();\n this.following = taken;\n }\n }\n this.emitPointer(\"click\", press.target, event);\n }\n this.settle();\n }\n\n /**\n * Tells the app a tap, a double click or a context menu on a node, an edge or the pane\n * (`node-click`, `edge-double-click`, `pane-context-menu`, …); several selected nodes, and the\n * rectangle around the selection (`nodes-selection`), take a context menu as the selection's\n * (`selection-context-menu`).\n */\n private emitPointer(\n what: \"click\" | \"double-click\" | \"context-menu\",\n target: PressTarget,\n event: MouseEvent,\n ): void {\n const client = { x: event.clientX, y: event.clientY };\n const info: FlowPointerInfo = {\n point: this.toFlow(client),\n client,\n event,\n };\n if (target.kind === \"nodes-selection\") {\n if (what === \"context-menu\") this.emitSelectionMenu(info);\n return;\n }\n const on = tapOn(target);\n if (!on) return;\n if (on.kind === \"pane\") {\n this.emit({ type: `pane-${what}`, ...info });\n return;\n }\n if (on.kind === \"edge\") {\n this.emit({ type: `edge-${what}`, edgeId: on.edgeId, ...info });\n return;\n }\n if (what === \"context-menu\") {\n const nodes =\n (this.model.get(\"selected-nodes\") as\n | readonly FlowNode[]\n | undefined) ?? [];\n if (\n nodes.length > 1 &&\n nodes.some((node) => node.id === on.nodeId)\n ) {\n this.emitSelectionMenu(info);\n return;\n }\n }\n this.emit({ type: `node-${what}`, nodeId: on.nodeId, ...info });\n }\n\n /** Tells the app a context menu on the selection (`selection-context-menu`). */\n private emitSelectionMenu(info: FlowPointerInfo): void {\n const ids = (key: \"selected-nodes\" | \"selected-edges\") =>\n (\n (this.model.get(key) as\n | readonly (FlowNode | FlowEdge)[]\n | undefined) ?? []\n ).map((item) => item.id);\n this.emit({\n type: \"selection-context-menu\",\n nodeIds: ids(\"selected-nodes\"),\n edgeIds: ids(\"selected-edges\"),\n ...info,\n });\n }\n\n private pointerLost(event: PointerEvent): void {\n if (this.destroyed) return;\n this.pointers.delete(event.pointerId);\n if (this.pinch?.ids.includes(event.pointerId)) {\n this.endPinch();\n return;\n }\n if (this.press?.pointerId === event.pointerId) {\n this.released = undefined;\n this.cancelPress();\n }\n }\n\n /**\n * Forgets a gesture going on without a press that ended by itself (a keyboard connection whose\n * handle lost focus or whose node went away): its `active()` answers false.\n */\n private dropEnded(): void {\n if (this.following?.active?.() === false) this.following = undefined;\n }\n\n /** Ends the gesture a tap started without committing. */\n private cancelFollowing(): void {\n const following = this.following;\n this.following = undefined;\n following?.cancel();\n }\n\n /** Ends the press under way without committing (its gesture cancelled). */\n private cancelPress(): void {\n const press = this.press;\n if (!press) return;\n this.press = undefined;\n this.stopAutoPan();\n this.release(press.pointerId);\n press.gesture?.cancel();\n this.settle();\n }\n\n private startPinch(first: number, second: number): void {\n const a = this.pointers.get(first);\n const b = this.pointers.get(second);\n if (!a || !b) return;\n // the press's gesture (a pan) gives way: the pinch pans and zooms from here\n const press = this.press;\n this.press = undefined;\n this.stopAutoPan();\n this.stopViewportAnimation();\n if (press && !press.pan) press.gesture?.cancel();\n const middle = this.toRoot({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 });\n this.pinch = {\n ids: [first, second],\n distance: Math.max(1, distance(a, b)),\n zoom: this.current.zoom,\n anchor: toFlow(this.current, middle),\n };\n this.capture(second);\n this.notify({ gesture: true });\n }\n\n private movePinch(): void {\n const pinch = this.pinch;\n if (!pinch) return;\n const a = this.pointers.get(pinch.ids[0]);\n const b = this.pointers.get(pinch.ids[1]);\n if (!a || !b) return;\n // the zoom grows with the fingers' spread since the pinch began\n const zoom = clampZoom(\n (pinch.zoom * distance(a, b)) / pinch.distance,\n this.minZoom,\n this.maxZoom,\n );\n const middle = this.toRoot({ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 });\n // the flow point first under the fingers' middle stays under it\n this.setViewport(\n {\n x: middle.x - pinch.anchor.x * zoom,\n y: middle.y - pinch.anchor.y * zoom,\n zoom,\n },\n true,\n );\n }\n\n private endPinch(): void {\n const pinch = this.pinch;\n if (!pinch) return;\n this.pinch = undefined;\n this.released = undefined;\n for (const id of pinch.ids) this.release(id);\n this.notify({ gesture: true });\n this.settle();\n }\n\n private wheel(event: WheelEvent): void {\n if (this.destroyed || !this.rootElement) return;\n const element = event.target as Element | null;\n if (element?.closest?.(`[${NO_WHEEL_ATTRIBUTE}]`)) return;\n // the wheel's viewport changes are one move, until it rests\n const before = this.moving;\n this.handling++;\n try {\n this.wheelOn(event);\n } finally {\n this.handling--;\n if (this.moving) this.restWheel();\n else if (before) this.settle();\n }\n }\n\n private wheelOn(event: WheelEvent): void {\n const target = this.target(event.target);\n if (this.features.wheel(event, target)) {\n event.preventDefault();\n return;\n }\n // a control, a toolbar or a panel keeps its wheel (a field scrolls)\n if (target.kind === \"other\") return;\n // the page never scrolls under the flow, whatever the wheel does there\n if (this.options.preventScrolling ?? true) event.preventDefault();\n const scale =\n event.deltaMode === 1\n ? 16\n : event.deltaMode === 2\n ? this.rootSize().height || 800\n : 1;\n const dx = event.deltaX * scale;\n const dy = event.deltaY * scale;\n const pinching = event.ctrlKey;\n const panOnScroll = this.options.panOnScroll ?? false;\n const point = this.toRoot({ x: event.clientX, y: event.clientY });\n // with panOnScroll, the zoom activation key held turns the wheel back into a zoom\n const zoomKey = panOnScroll && this.zoomKeyHeld(event);\n if (\n zoomKey ||\n (pinching ? (this.options.zoomOnPinch ?? true) : !panOnScroll)\n ) {\n if (!zoomKey && !pinching && !(this.options.zoomOnScroll ?? true))\n return;\n event.preventDefault();\n // a trackpad's pinch sends small deltas: it zooms faster per pixel than a wheel\n const zoom =\n this.current.zoom *\n Math.exp(-dy / (pinching ? WHEEL_PINCH_RATE : WHEEL_RATE));\n this.setViewport(\n zoomAround(\n this.current,\n clampZoom(zoom, this.minZoom, this.maxZoom),\n point,\n ),\n true,\n );\n return;\n }\n if (panOnScroll) {\n event.preventDefault();\n // Shift turns a wheel without a sideways delta sideways; the mode keeps one axis\n const mode = this.options.panOnScrollMode ?? \"free\";\n const sideways = event.shiftKey && dx === 0 && mode !== \"vertical\";\n const speed = this.options.panOnScrollSpeed ?? 1;\n const byX = mode === \"vertical\" ? 0 : sideways ? dy : dx;\n const byY = mode === \"horizontal\" || sideways ? 0 : dy;\n this.setViewport(\n {\n ...this.current,\n x: this.current.x - byX * speed,\n y: this.current.y - byY * speed,\n },\n true,\n );\n }\n }\n\n /**\n * A double click. With the pointer captured on the root, a browser's `dblclick` targets the\n * root: what it was on is the last press's target, and it counts (`*-double-click`) only when\n * that press was a tap (a double click ending a drag is none). A double click with no press\n * seen (a synthetic one) is read from its own target; one on a control is the control's.\n */\n private doubleClick(event: MouseEvent): void {\n if (this.destroyed) return;\n if (this.target(event.target).kind === \"other\") return;\n const released = this.released;\n const target = released?.target ?? this.target(event.target);\n const tap = released?.tap ?? true;\n if (!tap) return;\n this.emitPointer(\"double-click\", target, event);\n if (!(this.options.zoomOnDoubleClick ?? true)) return;\n if (target.kind !== \"pane\") return;\n const point = this.toRoot({ x: event.clientX, y: event.clientY });\n const zoom = clampZoom(\n this.current.zoom * 2,\n this.minZoom,\n this.maxZoom,\n );\n this.setViewport(zoomAround(this.current, zoom, point), true);\n }\n\n private keyDown(event: KeyboardEvent): void {\n if (this.destroyed) return;\n this.dropEnded();\n if (\n event.key === \"Escape\" &&\n (this.press || this.pinch || this.following)\n ) {\n this.cancelPress();\n this.cancelFollowing();\n this.endPinch();\n event.preventDefault();\n return;\n }\n // a gesture going on without a press (a keyboard connection) takes the keys first\n const following = this.following;\n if (following?.keydown) {\n const taken = following.keydown(event);\n if (\n this.following === following &&\n following.active?.() === false\n ) {\n this.following = undefined;\n }\n if (taken) {\n event.preventDefault();\n return;\n }\n }\n const target = this.target(event.target);\n if (target.kind === \"other\") return;\n const taken = this.features.keydown(event, target);\n if (typeof taken === \"object\") {\n this.cancelFollowing();\n this.following = taken;\n }\n if (taken) event.preventDefault();\n }\n\n /** the part that last took focus in the flow (its part name and id), for `refocus` */\n private lastFocus: { part: string; id: string | undefined } | undefined;\n\n private focusIn(event: FocusEvent): void {\n if (this.destroyed) return;\n const focused = asElement(event.target);\n const part = focused?.getAttribute(PART_ATTRIBUTE) ?? null;\n this.lastFocus =\n focused && part !== null\n ? {\n part,\n id: focused.getAttribute(ID_ATTRIBUTE) ?? undefined,\n }\n : undefined;\n const target = this.target(event.target);\n if (target.kind === \"node\" || target.kind === \"edge\")\n this.features.focus(target);\n }\n\n /**\n * Focus left a part: a blur (the part still in the document) forgets it, so a later remount\n * does not take focus back; a removal (an edge moving to another level's layer) keeps it. The\n * check waits a microtask, as a removal may tell `focusout` before the part leaves.\n */\n private focusOut(event: FocusEvent): void {\n const left = asElement(event.target);\n const last = this.lastFocus;\n if (!left || !last) return;\n const check = () => {\n if (this.lastFocus === last && left.isConnected)\n this.lastFocus = undefined;\n };\n const view = viewOf(left);\n if (view && typeof view.queueMicrotask === \"function\")\n view.queueMicrotask(check);\n else check();\n }\n\n /** `adapter.refocus`: a remounted part that had focus, focus lost since, takes it back. */\n private refocus(element: Element): void {\n const last = this.lastFocus;\n if (this.destroyed || !last || !element.isConnected) return;\n if (\n element.getAttribute(PART_ATTRIBUTE) !== last.part ||\n (element.getAttribute(ID_ATTRIBUTE) ?? undefined) !== last.id\n ) {\n return;\n }\n const owner = element.ownerDocument;\n const active = owner.activeElement;\n if (active !== null && active !== owner.body) return;\n const focusable = element as Partial<HTMLElement>;\n if (typeof focusable.focus === \"function\")\n focusable.focus({ preventScroll: true });\n }\n\n // ---------------------------------------------------------------------------------------------\n // the adapter\n // ---------------------------------------------------------------------------------------------\n\n private attributes(\n part: string,\n payload: Readonly<Record<string, unknown>>,\n ): PartAttributes {\n const into: MutablePartAttributes = { [PART_ATTRIBUTE]: part };\n const id = (key: string) =>\n typeof payload[key] === \"string\"\n ? (payload[key] as string)\n : undefined;\n switch (part) {\n case \"root\":\n into[\"data-interactive\"] = flag(this.interactivity.interactive);\n into[\"data-panning\"] = flag(this.is(\"panning\"));\n break;\n case \"node\":\n case \"minimap-node\":\n case \"toolbar\":\n case \"resizer\": {\n const nodeId = id(\"nodeId\");\n const node =\n nodeId === undefined ? undefined : this.node(nodeId);\n // an edge's toolbar stands for its edge\n into[ID_ATTRIBUTE] =\n nodeId ?? (part === \"toolbar\" ? id(\"edgeId\") : undefined);\n if (part !== \"resizer\" && part !== \"toolbar\") {\n into[\"data-selected\"] = flag(node?.selected === true);\n }\n if (part === \"node\") {\n into[\"data-hidden\"] = flag(node?.hidden === true);\n into[\"data-measured\"] = flag(\n node !== undefined && this.isMeasured(node),\n );\n }\n break;\n }\n case \"edge\":\n case \"edge-path\":\n case \"edge-label\": {\n const edgeId = id(\"edgeId\");\n const edge =\n edgeId === undefined\n ? undefined\n : this.geometry.edge(edgeId);\n into[ID_ATTRIBUTE] = edgeId;\n into[\"data-selected\"] = flag(edge?.selected === true);\n into[\"data-animated\"] = flag(edge?.animated === true);\n break;\n }\n case \"handle\": {\n into[ID_ATTRIBUTE] = id(\"handleId\");\n into[\"data-handle-type\"] = id(\"type\");\n into[\"data-side\"] = id(\"side\");\n const nodeId = id(\"nodeId\");\n const connectable =\n payload.connectable !== false &&\n nodeId !== undefined &&\n this.model.is(\"node-connectable\", { nodeId });\n into[\"data-connectable\"] = flag(connectable);\n into[\"data-connectable-start\"] = flag(\n connectable && payload.connectableStart !== false,\n );\n into[\"data-connectable-end\"] = flag(\n connectable && payload.connectableEnd !== false,\n );\n break;\n }\n case \"resize-handle\":\n Object.assign(\n into,\n resizeHandleAttributes(id(\"position\"), {\n direction: id(\"direction\"),\n variant: id(\"variant\"),\n }),\n );\n break;\n case \"edges-layer\":\n into[LEVEL_ATTRIBUTE] =\n typeof payload.level === \"number\" &&\n Number.isFinite(payload.level)\n ? String(payload.level)\n : undefined;\n break;\n case \"reconnect-anchor\":\n into[ID_ATTRIBUTE] = id(\"edgeId\");\n into[END_ATTRIBUTE] = id(\"end\");\n break;\n }\n this.features.attributes(part, payload, into);\n return Object.freeze(into);\n }\n\n private createAdapter(): FlowEngineAdapter {\n const engine = this;\n return Object.freeze({\n model: this.model,\n get settings() {\n return Object.freeze({\n onlyRenderVisible:\n engine.options.onlyRenderVisible ?? false,\n });\n },\n setOptions: (options) => {\n if (this.destroyed) return;\n const {\n root: _root,\n defaultViewport: _viewport,\n fitView: _fit,\n ...rest\n } = options;\n // new options may come with a new layout of the root (read it again)\n this.cachedRootBox = undefined;\n this.options = { ...this.options, ...rest };\n this.minZoom = this.options.minZoom ?? 0.5;\n this.maxZoom = Math.max(\n this.minZoom,\n this.options.maxZoom ?? 2,\n );\n if (\n rest.interactive !== undefined &&\n rest.interactive !== this.interactivity.interactive\n ) {\n this.run(\"set-interactive\", {\n interactive: rest.interactive,\n });\n }\n // the viewport kept to the new limits and extent\n this.setViewport(this.current, false);\n this.notify({ viewport: true, measured: true, gesture: true });\n },\n attachRoot: (element) => {\n if (!this.destroyed) this.attachRoot(element);\n },\n detachRoot: () => this.detachRoot(),\n attachViewport: (element) => {\n if (this.destroyed || this.viewportElement === element) return;\n if (this.viewportElement)\n clearViewportTransform(this.viewportElement);\n this.viewportElement = element ?? undefined;\n if (element) writeViewportTransform(element, this.current);\n },\n registerNode: (nodeId, element) => {\n if (!this.destroyed)\n this.measurements.registerNode(nodeId, element);\n },\n registerHandle: (handle: HandleRegistration, element) => {\n if (!this.destroyed)\n this.measurements.registerHandle(handle, element);\n },\n setPartOptions: (part, id, options) => {\n const key = `${part}\\u0000${id}`;\n if (options)\n this.partOptions.set(key, Object.freeze({ ...options }));\n else this.partOptions.delete(key);\n },\n attributes: ((\n part: string,\n payload?: Readonly<Record<string, unknown>>,\n ) =>\n this.attributes(\n part,\n payload ?? {},\n )) as FlowEngineAdapter[\"attributes\"],\n subscribe: (listener) => {\n const wrapper = (change: ViewChange) => listener(change);\n this.adapterListeners.add(wrapper);\n return () => {\n this.adapterListeners.delete(wrapper);\n };\n },\n getSnapshot: () => this.revision,\n refocus: (element) => this.refocus(element),\n } satisfies FlowEngineAdapter);\n }\n}\n\n/**\n * Creates the engine of one flow on screen, over its model\n * (`createFlowEngine<Types, typeof features>(model, options)`). Give it the root element now or\n * attach it later (`engine.adapter.attachRoot`, what an adapter does); call `destroy()` when the\n * flow leaves the screen.\n */\nexport function createFlowEngine<\n T extends FlowTypes = AnyTypes,\n const F extends FlowFeatures = readonly [],\n>(model: FlowModel<T, F>, options: FlowEngineOptions = {}): FlowEngine<T, F> {\n const engine = new Engine<T, F>(model, options);\n // the surface is exactly the verbs, `subscribe`, `destroy` and `adapter`, each bound\n return Object.freeze({\n run: engine.run.bind(engine),\n can: engine.can.bind(engine),\n check: engine.check.bind(engine),\n get: engine.get.bind(engine),\n is: engine.is.bind(engine),\n subscribe: engine.subscribe.bind(engine),\n destroy: engine.destroy.bind(engine),\n adapter: engine.adapter,\n }) as unknown as FlowEngine<T, F>;\n}\n","// The name each engine event has as a root callback in every adapter (#33), so the four adapters\n// cannot drift: React's `onNodeClick`, Svelte's `onnodeclick`, Vue's `@node-click`, Angular's\n// `(nodeClick)` all come from `NodeClick`. The names follow React Flow's callbacks where it has\n// one (`onMoveStart`, `onInit`, `onSelectionStart`, `onDelete`); `viewport-change` has its own\n// callback (`onViewportChange(viewport, gesture)`) and is not here, nor `minimap-click` (the\n// minimap part's own `onClick(event, point)`).\nimport type { FlowEngineEventType } from \"./events\";\n\n/** The engine events a root calls back, each with its callback's name (after `on`). */\nexport const ENGINE_EVENT_CALLBACKS = Object.freeze({\n \"viewport-change-start\": \"MoveStart\",\n \"viewport-change-end\": \"MoveEnd\",\n ready: \"Init\",\n \"node-click\": \"NodeClick\",\n \"node-double-click\": \"NodeDoubleClick\",\n \"node-context-menu\": \"NodeContextMenu\",\n \"edge-click\": \"EdgeClick\",\n \"edge-double-click\": \"EdgeDoubleClick\",\n \"edge-context-menu\": \"EdgeContextMenu\",\n \"pane-click\": \"PaneClick\",\n \"pane-double-click\": \"PaneDoubleClick\",\n \"pane-context-menu\": \"PaneContextMenu\",\n \"selection-context-menu\": \"SelectionContextMenu\",\n \"box-select-start\": \"SelectionStart\",\n \"box-select\": \"SelectionEnd\",\n \"drag-start\": \"NodeDragStart\",\n \"nodes-move\": \"NodesMove\",\n \"drag-cancel\": \"NodeDragCancel\",\n \"selection-drag-start\": \"SelectionDragStart\",\n \"selection-drag\": \"SelectionDrag\",\n \"selection-drag-end\": \"SelectionDragStop\",\n \"connect-start\": \"ConnectStart\",\n \"connect-target\": \"ConnectTarget\",\n connect: \"Connect\",\n \"connect-cancel\": \"ConnectCancel\",\n \"reconnect-start\": \"ReconnectStart\",\n reconnect: \"Reconnect\",\n \"reconnect-cancel\": \"ReconnectCancel\",\n \"resize-start\": \"ResizeStart\",\n resize: \"ResizeEnd\",\n \"resize-cancel\": \"ResizeCancel\",\n remove: \"Delete\",\n} as const satisfies Record<\n Exclude<FlowEngineEventType, \"viewport-change\" | \"minimap-click\">,\n string\n>);\n\n/** An engine event a root calls back. */\nexport type CallbackEventType = keyof typeof ENGINE_EVENT_CALLBACKS;\n\n/** A callback's name after `on` (`NodeClick`). */\nexport type EventCallbackName =\n (typeof ENGINE_EVENT_CALLBACKS)[CallbackEventType];\n","// Whether keys are held, for the adapters' `useKeyPress` (and its composable, rune and injection\n// function): one matcher in the core, so the four adapters agree on the combo syntax. It listens\n// to the target it is given (the root's window by default in the adapters), never to a global.\n\n/**\n * The keys `watchKeyPress` waits for: a combo, or several (any of them). A combo is key names\n * joined by `+`, all held at once: `\"Shift\"`, `\"Meta+s\"`, `\"Control+Shift+z\"`. A name is a\n * `KeyboardEvent.key` (`\"a\"`, `\"Shift\"`, `\"Delete\"`, `\" \"` for Space) or a `KeyboardEvent.code`\n * (`\"KeyA\"`, `\"Space\"`), compared without case.\n */\nexport type KeyPressKeys = string | readonly string[];\n\n/** What `watchKeyPress` listens to: a window, a document or an element. */\nexport interface KeyPressTarget {\n addEventListener(\n type: string,\n listener: (event: Event) => void,\n options?: boolean | AddEventListenerOptions,\n ): void;\n removeEventListener(\n type: string,\n listener: (event: Event) => void,\n options?: boolean | EventListenerOptions,\n ): void;\n}\n\n/** The combos of `keys`, each a list of lowercase key names. */\nfunction combosOf(keys: KeyPressKeys): string[][] {\n const list = typeof keys === \"string\" ? [keys] : [...keys];\n return list\n .map((combo) =>\n (combo === \"+\" ? [\"+\"] : combo.split(\"+\"))\n .map((name) => (name === \"\" ? \"\" : name.toLowerCase()))\n .filter((name) => name !== \"\"),\n )\n .filter((combo) => combo.length > 0);\n}\n\n/** The window a target belongs to (itself when it is one), for its `blur`. */\nfunction viewOf(target: KeyPressTarget): KeyPressTarget | undefined {\n const owner = target as {\n defaultView?: KeyPressTarget | null;\n ownerDocument?: { defaultView?: KeyPressTarget | null } | null;\n };\n if (owner.defaultView) return owner.defaultView;\n if (owner.ownerDocument)\n return owner.ownerDocument.defaultView ?? undefined;\n return target;\n}\n\n/**\n * Calls `onChange(pressed)` whenever one of the combos of `keys` starts or stops being held,\n * reading `keydown` and `keyup` on `target` (a window, a document or an element). The keys held\n * are forgotten when the target's window loses focus, and when Meta is released (its platform\n * swallows the other keys' `keyup` while it is held). Returns the function that stops listening.\n */\nexport function watchKeyPress(\n target: KeyPressTarget,\n keys: KeyPressKeys,\n onChange: (pressed: boolean) => void,\n): () => void {\n const combos = combosOf(keys);\n // each physical key held (its `code`, else its `key`) with the names it was pressed as: its\n // release forgets them, though its `key` changed meanwhile (Shift released before `!`)\n const held = new Map<string, readonly string[]>();\n let pressed = false;\n const update = () => {\n const names = new Set([...held.values()].flat());\n const now = combos.some((combo) =>\n combo.every((name) => names.has(name)),\n );\n if (now === pressed) return;\n pressed = now;\n onChange(now);\n };\n const physical = (event: KeyboardEvent) =>\n (event.code || event.key || \"\").toLowerCase();\n const down = (event: Event) => {\n const key = event as KeyboardEvent;\n held.set(\n physical(key),\n [key.key, key.code]\n .filter((name) => typeof name === \"string\" && name !== \"\")\n .map((name) => name.toLowerCase()),\n );\n update();\n };\n const up = (event: Event) => {\n const key = event as KeyboardEvent;\n if (key.key === \"Meta\") held.clear();\n else held.delete(physical(key));\n update();\n };\n const reset = () => {\n held.clear();\n update();\n };\n const view = viewOf(target);\n target.addEventListener(\"keydown\", down);\n target.addEventListener(\"keyup\", up);\n view?.addEventListener(\"blur\", reset);\n return () => {\n target.removeEventListener(\"keydown\", down);\n target.removeEventListener(\"keyup\", up);\n view?.removeEventListener(\"blur\", reset);\n };\n}\n","// The middle of an edge's two ends, and how far each lies from it: where a straight edge's label\n// goes, and the point an app's own path may centre a label or a turn on.\nimport type { XY } from \"../document/types\";\n\n/** The middle of two ends, and the distance across (x) and down (y) from it to either end. */\nexport interface EdgeCenter {\n /** the point halfway between the ends, in flow coordinates */\n readonly center: XY;\n /** half the distance between the ends across (x) and down (y), both positive */\n readonly offset: XY;\n}\n\n/** The point halfway between an edge's `source` and `target`, and how far each end lies from it. */\nexport function edgeCenter(source: XY, target: XY): EdgeCenter {\n return {\n center: {\n x: (source.x + target.x) / 2,\n y: (source.y + target.y) / 2,\n },\n offset: {\n x: Math.abs(target.x - source.x) / 2,\n y: Math.abs(target.y - source.y) / 2,\n },\n };\n}\n","// The geometry of a flow without an engine (a server render, the first client render): node boxes\n// from the sizes the document gives (`width` / `height`, else `initialWidth` / `initialHeight`),\n// edge ends at the declared `handles` (else the `sourcePosition` / `targetPosition` side), the\n// paths, the drawing order and the render layers. It runs the very functions the engine runs\n// before a node is measured, so the first render and the engine agree (no hydration jump). Pure:\n// no DOM and nothing of the engine.\nimport type {\n AnyTypes,\n FlowEdge,\n FlowNode,\n FlowTypes,\n XY,\n} from \"../document/types\";\nimport { edgeEnds, type PathOptions, pathOf } from \"./edge-geometry\";\nimport {\n declaredHandleOf,\n type NodeLayout,\n nodeRectOf,\n nodeSize,\n} from \"./node-layout\";\nimport type { EdgePath, Rect } from \"./types\";\nimport {\n drawingOrder,\n edgeStackValue,\n nodeStackValue,\n type RenderLayer,\n renderLayers,\n type ZIndexMode,\n} from \"./z-order\";\n\n/** The engine options the static geometry follows (give it the root's, so both agree). */\nexport interface StaticGeometryOptions {\n /** the point of a node's box its position stands at, as shares of its size; default top-left */\n readonly nodeOrigin?: XY | undefined;\n /** the shape of the built-in edge paths (an edge's own `pathOptions` go over them) */\n readonly pathOptions?: PathOptions | undefined;\n /** how stack values are worked out; default `\"auto\"` */\n readonly zIndexMode?: ZIndexMode | undefined;\n /** a selected node is raised; default true */\n readonly elevateNodesOnSelect?: boolean | undefined;\n /** a selected edge is raised; default false in `\"basic\"`, true in `\"auto\"` */\n readonly elevateEdgesOnSelect?: boolean | undefined;\n}\n\n/**\n * A flow's geometry from its document alone (frozen plain data, keyed by id), as the engine's reads\n * give it before anything is measured.\n */\nexport interface StaticGeometry {\n /** every node's box in absolute flow coordinates, its size 0 when unknown (`node-rect-by`) */\n readonly nodeRects: Readonly<Record<string, Rect>>;\n /** every node's structural `z-index` (`node-z-index-by`) */\n readonly nodeZIndexes: Readonly<Record<string, number>>;\n /** the path of each edge whose two nodes have a known size (`edge-path-by`); others are absent */\n readonly edgePaths: Readonly<Record<string, EdgePath>>;\n /** the ids of the edges to draw, in drawing order (`drawn-edges`, without `onlyRenderVisible`) */\n readonly drawnEdges: readonly string[];\n /** the levels to draw (`render-layers`) */\n readonly layers: readonly RenderLayer[];\n}\n\n/**\n * The geometry of a flow's document without an engine: what an adapter renders on the server and\n * in its first client render, before the engine measures anything.\n */\nexport function staticGeometry<T extends FlowTypes = AnyTypes>(\n flow: {\n readonly nodes: readonly FlowNode<T>[];\n readonly edges: readonly FlowEdge<T>[];\n },\n options: StaticGeometryOptions = {},\n): StaticGeometry {\n const nodes = flow.nodes as readonly FlowNode[];\n const edges = flow.edges as readonly FlowEdge[];\n const byId = new Map(nodes.map((node) => [node.id, node]));\n const nodeById = (nodeId: string) => byId.get(nodeId);\n const layout: NodeLayout = {\n node: nodeById,\n size: (node) => nodeSize(node),\n nodeOrigin: options.nodeOrigin,\n };\n const rects = new Map<string, Rect>();\n for (const node of nodes) {\n rects.set(node.id, Object.freeze(nodeRectOf(node, layout)));\n }\n const knownRect = (nodeId: string) => {\n const node = byId.get(nodeId);\n return node && nodeSize(node) ? rects.get(nodeId) : undefined;\n };\n const paths = new Map<string, EdgePath>();\n for (const edge of edges) {\n const ends = edgeEnds(edge, {\n rect: knownRect,\n handle: (nodeId, type, handleId) => {\n const node = byId.get(nodeId);\n const rect = rects.get(nodeId);\n return node && rect\n ? declaredHandleOf(node, rect, type, handleId)\n : undefined;\n },\n side: (nodeId, type) => {\n const node = byId.get(nodeId);\n return type === \"source\"\n ? node?.sourcePosition\n : node?.targetPosition;\n },\n });\n if (ends) {\n paths.set(\n edge.id,\n Object.freeze(\n pathOf(edge.type, ends, {\n ...options.pathOptions,\n ...edge.pathOptions,\n }),\n ),\n );\n }\n }\n const shownNodes = nodes.filter((node) => node.hidden !== true);\n const shown = (nodeId: string) => byId.get(nodeId)?.hidden !== true;\n const drawn = drawingOrder(\n edges.filter(\n (edge) =>\n edge.hidden !== true &&\n shown(edge.source) &&\n shown(edge.target) &&\n paths.has(edge.id),\n ),\n (edge) => edgeStackValue(edge, nodeById, options),\n );\n const values = new Map(\n nodes.map((node) => [node.id, nodeStackValue(node, nodeById, options)]),\n );\n const layering = renderLayers(\n shownNodes.map((node) => ({\n id: node.id,\n value: values.get(node.id) ?? 0,\n })),\n drawn.map((edge) => ({\n id: edge.id,\n value: edgeStackValue(edge, nodeById, options),\n })),\n options.zIndexMode ?? \"auto\",\n );\n return Object.freeze({\n nodeRects: Object.freeze(Object.fromEntries(rects)),\n nodeZIndexes: Object.freeze(\n Object.fromEntries(\n nodes.map((node) => [\n node.id,\n layering.zIndexes?.get(node.id) ?? values.get(node.id) ?? 0,\n ]),\n ),\n ),\n edgePaths: Object.freeze(Object.fromEntries(paths)),\n drawnEdges: Object.freeze(drawn.map((edge) => edge.id)),\n layers: layering.layers,\n });\n}\n","// `batch` (D6): several commands as one atomic step. They run in order on one draft, each through\n// the middleware chain; the first failure fails the whole batch (nothing applies), and a success\n// commits once, with one event listing every command it ran.\nimport { defineCommand, ok } from \"./define\";\n\nexport const batch = defineCommand({\n name: \"batch\",\n description:\n \"Runs several commands as one atomic step: in order, all or nothing, with one event. The first failure is the batch's result, its path pointing into `commands`.\",\n payloadSchema: {\n type: \"object\",\n properties: {\n commands: {\n type: \"array\",\n description:\n \"the commands, in order: each a `{ command, payload }`\",\n items: {\n type: \"object\",\n properties: {\n command: {\n type: \"string\",\n description: \"the command's name\",\n },\n payload: {\n type: \"object\",\n description: \"its payload\",\n },\n },\n required: [\"command\", \"payload\"],\n additionalProperties: false,\n },\n },\n },\n required: [\"commands\"],\n additionalProperties: false,\n },\n resultSchema: {\n type: \"object\",\n properties: {\n results: {\n type: \"array\",\n items: {},\n description: \"each command's value, in order\",\n },\n },\n required: [\"results\"],\n additionalProperties: false,\n },\n // transient when every command it runs may be (a multi-node drag's step)\n transient: true,\n reduce: ({ commands }, { runInBatch }) => {\n const results: unknown[] = [];\n for (const [i, entry] of commands.entries()) {\n const result = runInBatch(\n entry.command,\n entry.payload,\n `/commands/${i}`,\n );\n if (!result.ok) {\n return result;\n }\n results.push(result.value);\n }\n return ok({ results });\n },\n});\n","// The core's edge commands (D6). An edge joins two existing, connectable nodes, and no second edge\n// joins the same handles in the same direction; a middleware decides the app's own rules (D7:\n// `model.can(\"edge.add\", …)` is a connection's validity).\nimport {\n edgeFlagProperties,\n edgeSchema,\n zIndexSchema,\n} from \"../document/document-schema\";\nimport { edgeFlag } from \"../document/flags\";\nimport type { FlowEdge } from \"../document/types\";\nimport { cloneJson } from \"../state/clone-json\";\nimport { defineCommand, fail, invalid, ok } from \"./define\";\nimport { connectionProblem, findEdge, isFailure } from \"./rules\";\n\nconst edgeId = {\n type: \"string\",\n minLength: 1,\n description: \"the edge's id\",\n} as const;\n\nconst edgeIdResult = {\n type: \"object\",\n properties: { edgeId },\n required: [\"edgeId\"],\n additionalProperties: false,\n} as const;\n\nexport const edgeAdd = defineCommand({\n name: \"edge.add\",\n description:\n \"Adds an edge from a source node to a target node, optionally between two of their handles, with its type, data and flags (its id generated when missing). Refused when a node is not connectable, when an edge already joins the same handles, or when the id is taken.\",\n payloadSchema: edgeSchema,\n resultSchema: edgeIdResult,\n transient: false,\n reduce: (payload, { draft, features }) => {\n const missing = invalid(\n features.missingFields(\"edgeFields\", payload, \"\"),\n );\n if (missing) {\n return missing;\n }\n if (payload.id !== undefined && draft.edge(payload.id)) {\n return fail(\"refused\", `an edge \"${payload.id}\" exists`, \"/id\");\n }\n const problem = connectionProblem(draft, payload);\n if (problem) {\n return problem;\n }\n const { id = draft.nextEdgeId(), ...fields } = cloneJson(payload);\n const edge = { id, ...fields } as FlowEdge;\n const refused = features.checkEdge(draft, edge, \"\");\n if (refused) {\n return refused;\n }\n draft.putEdge(edge);\n return ok({ edgeId: id });\n },\n});\n\nexport const edgeRemove = defineCommand({\n name: \"edge.remove\",\n description: \"Removes an edge. Refused when it is not deletable.\",\n payloadSchema: {\n type: \"object\",\n properties: { edgeId },\n required: [\"edgeId\"],\n additionalProperties: false,\n },\n resultSchema: edgeIdResult,\n transient: false,\n reduce: ({ edgeId }, { draft }) => {\n const edge = findEdge(draft, edgeId, \"/edgeId\");\n if (isFailure(edge)) {\n return edge;\n }\n if (!edgeFlag(edge, \"deletable\")) {\n return fail(\n \"refused\",\n `edge \"${edgeId}\" is not deletable`,\n \"/edgeId\",\n );\n }\n draft.removeEdges(new Set([edgeId]));\n return ok({ edgeId });\n },\n});\n\nexport const edgeSetData = defineCommand({\n name: \"edge.set-data\",\n description:\n \"Merges a shallow patch into an edge's data: each top-level key given replaces the edge's own.\",\n payloadSchema: {\n type: \"object\",\n properties: {\n edgeId,\n data: {\n type: \"object\",\n description: \"the keys to set in the edge's data\",\n },\n },\n required: [\"edgeId\", \"data\"],\n additionalProperties: false,\n },\n resultSchema: edgeIdResult,\n transient: false,\n reduce: ({ edgeId, data }, { draft }) => {\n const edge = findEdge(draft, edgeId, \"/edgeId\");\n if (isFailure(edge)) {\n return edge;\n }\n draft.putEdge({ ...edge, data: { ...edge.data, ...cloneJson(data) } });\n return ok({ edgeId });\n },\n});\n\nexport const edgeSetFlags = defineCommand({\n name: \"edge.set-flags\",\n description:\n \"Sets some of an edge's flags (selectable, deletable, hidden, reconnectable, focusable, animated); the others stay. An edge made unselectable is deselected.\",\n payloadSchema: {\n type: \"object\",\n properties: { edgeId, ...edgeFlagProperties },\n required: [\"edgeId\"],\n additionalProperties: false,\n },\n resultSchema: edgeIdResult,\n transient: false,\n reduce: ({ edgeId, ...flags }, { draft, features }) => {\n const edge = findEdge(draft, edgeId, \"/edgeId\");\n if (isFailure(edge)) {\n return edge;\n }\n draft.putEdge({ ...edge, ...flags });\n features.flagsChanged(draft, \"edge\", edgeId);\n return ok({ edgeId });\n },\n});\n\nexport const edgeSetZIndex = defineCommand({\n name: \"edge.set-z-index\",\n description:\n \"Sets an edge's `zIndex`, its place in the edges' drawing order (null: the default, 0), in place.\",\n payloadSchema: {\n type: \"object\",\n properties: {\n edgeId,\n zIndex: {\n anyOf: [zIndexSchema, { type: \"null\" }],\n description:\n \"its place in its layer's stacking order (an integer); null: back to the default, 0\",\n },\n },\n required: [\"edgeId\", \"zIndex\"],\n additionalProperties: false,\n },\n resultSchema: edgeIdResult,\n transient: false,\n reduce: ({ edgeId, zIndex }, { draft }) => {\n const edge = findEdge(draft, edgeId, \"/edgeId\");\n if (isFailure(edge)) {\n return edge;\n }\n const { zIndex: _was, ...rest } = edge;\n draft.putEdge(\n (zIndex === null ? rest : { ...rest, zIndex }) as typeof edge,\n );\n return ok({ edgeId });\n },\n});\n","// The core's node commands (D6). Flags are enforced here, so no caller can bypass them: a node\n// that is not draggable does not move, one that is not deletable is not removed. Removing a node\n// removes its edges in the same step (and, with `subflows()`, its children).\nimport {\n nodeFlagProperties,\n nodeSchema,\n xySchema,\n zIndexSchema,\n} from \"../document/document-schema\";\nimport { nodeFlag } from \"../document/flags\";\nimport type { FlowNode } from \"../document/types\";\nimport { cloneJson } from \"../state/clone-json\";\nimport { defineCommand, fail, invalid, ok } from \"./define\";\nimport { findNode, isFailure, removalOf, removeAll } from \"./rules\";\n\nconst nodeId = {\n type: \"string\",\n minLength: 1,\n description: \"the node's id\",\n} as const;\n\nconst removedSchema = {\n type: \"object\",\n properties: {\n removedNodeIds: {\n type: \"array\",\n items: { type: \"string\" },\n description: \"the nodes removed, in drawing order\",\n },\n removedEdgeIds: {\n type: \"array\",\n items: { type: \"string\" },\n description:\n \"the edges removed: those that touched a removed node, and those removed themselves\",\n },\n },\n required: [\"removedNodeIds\", \"removedEdgeIds\"],\n additionalProperties: false,\n} as const;\n\nconst nodeIdResult = {\n type: \"object\",\n properties: { nodeId },\n required: [\"nodeId\"],\n additionalProperties: false,\n} as const;\n\nexport const nodeAdd = defineCommand({\n name: \"node.add\",\n description:\n \"Adds a node at the end of the drawing order: its type, position and data, optionally its id (generated when missing), size and flags. Refused when the id is taken.\",\n payloadSchema: nodeSchema,\n resultSchema: nodeIdResult,\n transient: false,\n reduce: (payload, { draft, features }) => {\n const missing = invalid(\n features.missingFields(\"nodeFields\", payload, \"\"),\n );\n if (missing) {\n return missing;\n }\n if (payload.id !== undefined && draft.node(payload.id)) {\n return fail(\"refused\", `a node \"${payload.id}\" exists`, \"/id\");\n }\n const { id = draft.nextNodeId(), ...fields } = cloneJson(payload);\n const node = { id, ...fields } as FlowNode;\n const refused = features.checkNode(draft, node, \"\");\n if (refused) {\n return refused;\n }\n draft.putNode({\n ...node,\n position: features.constrainPosition(draft, node, node.position),\n });\n features.nodeChanged(draft, id);\n return ok({ nodeId: id });\n },\n});\n\nexport const nodeRemove = defineCommand({\n name: \"node.remove\",\n description:\n \"Removes a node and every edge that starts or ends at it, in one step; with sub-flows, its children go too. Refused when the node (or a child) is not deletable.\",\n payloadSchema: {\n type: \"object\",\n properties: { nodeId },\n required: [\"nodeId\"],\n additionalProperties: false,\n },\n resultSchema: removedSchema,\n transient: false,\n reduce: ({ nodeId }, { draft, features }) => {\n const node = findNode(draft, nodeId, \"/nodeId\");\n if (isFailure(node)) {\n return node;\n }\n const ids = removalOf(draft, features, nodeId);\n for (const id of ids) {\n const removed = draft.node(id);\n if (removed && !nodeFlag(removed, \"deletable\")) {\n return fail(\n \"refused\",\n id === nodeId\n ? `node \"${id}\" is not deletable`\n : `node \"${nodeId}\" holds node \"${id}\", which is not deletable`,\n \"/nodeId\",\n );\n }\n }\n return ok(removeAll(draft, ids));\n },\n});\n\nexport const nodeMove = defineCommand({\n name: \"node.move\",\n description:\n 'Moves a node to a position (relative to its parent with sub-flows), kept inside its parent with `extent: \"parent\"` (a rectangle extent is kept by the gestures, not here). Refused when the node is not draggable. A drag runs it as transient steps, then once more for the drop.',\n payloadSchema: {\n type: \"object\",\n properties: {\n nodeId,\n position: {\n ...xySchema,\n description:\n \"its new top-left corner, in flow coordinates (relative to its parent with sub-flows)\",\n },\n },\n required: [\"nodeId\", \"position\"],\n additionalProperties: false,\n },\n resultSchema: {\n type: \"object\",\n properties: {\n nodeId,\n position: {\n ...xySchema,\n description:\n 'the position it got, kept inside its parent with `extent: \"parent\"`',\n },\n },\n required: [\"nodeId\", \"position\"],\n additionalProperties: false,\n },\n transient: true,\n reduce: ({ nodeId, position }, { draft, features }) => {\n const node = findNode(draft, nodeId, \"/nodeId\");\n if (isFailure(node)) {\n return node;\n }\n if (!nodeFlag(node, \"draggable\")) {\n return fail(\n \"refused\",\n `node \"${nodeId}\" is not draggable`,\n \"/nodeId\",\n );\n }\n const kept = features.constrainPosition(draft, node, {\n x: position.x,\n y: position.y,\n });\n draft.putNode({ ...node, position: kept });\n features.nodeChanged(draft, nodeId);\n // where it ended: a parent that grew to hold it may have shifted it\n return ok({ nodeId, position: draft.node(nodeId)?.position ?? kept });\n },\n});\n\nexport const nodeResize = defineCommand({\n name: \"node.resize\",\n description:\n 'Sets a node\\'s width and height, and optionally its position (a resize from a top or left edge moves it), kept inside its parent with `extent: \"parent\"` (a rectangle extent is kept by the gestures, not here). A resize gesture runs it as transient steps, then once more at the end.',\n payloadSchema: {\n type: \"object\",\n properties: {\n nodeId,\n width: { type: \"number\", minimum: 0, description: \"its new width\" },\n height: {\n type: \"number\",\n minimum: 0,\n description: \"its new height\",\n },\n position: {\n ...xySchema,\n description: \"its new top-left corner; none: it stays\",\n },\n },\n required: [\"nodeId\", \"width\", \"height\"],\n additionalProperties: false,\n },\n resultSchema: {\n type: \"object\",\n properties: {\n nodeId,\n width: { type: \"number\", description: \"its width\" },\n height: { type: \"number\", description: \"its height\" },\n position: {\n ...xySchema,\n description:\n 'the position it got, kept inside its parent with `extent: \"parent\"`',\n },\n },\n required: [\"nodeId\", \"width\", \"height\", \"position\"],\n additionalProperties: false,\n },\n transient: true,\n reduce: ({ nodeId, width, height, position }, { draft, features }) => {\n const node = findNode(draft, nodeId, \"/nodeId\");\n if (isFailure(node)) {\n return node;\n }\n const resized = { ...node, width, height };\n const kept = features.constrainPosition(\n draft,\n resized,\n position ? { x: position.x, y: position.y } : node.position,\n );\n draft.putNode({ ...resized, position: kept });\n features.nodeChanged(draft, nodeId);\n return ok({\n nodeId,\n width,\n height,\n position: draft.node(nodeId)?.position ?? kept,\n });\n },\n});\n\nexport const nodeSetData = defineCommand({\n name: \"node.set-data\",\n description:\n \"Merges a shallow patch into a node's data: each top-level key given replaces the node's own.\",\n payloadSchema: {\n type: \"object\",\n properties: {\n nodeId,\n data: {\n type: \"object\",\n description: \"the keys to set in the node's data\",\n },\n },\n required: [\"nodeId\", \"data\"],\n additionalProperties: false,\n },\n resultSchema: nodeIdResult,\n transient: false,\n reduce: ({ nodeId, data }, { draft }) => {\n const node = findNode(draft, nodeId, \"/nodeId\");\n if (isFailure(node)) {\n return node;\n }\n draft.putNode({ ...node, data: { ...node.data, ...cloneJson(data) } });\n return ok({ nodeId });\n },\n});\n\nexport const nodeSetFlags = defineCommand({\n name: \"node.set-flags\",\n description:\n \"Sets some of a node's flags (draggable, selectable, connectable, deletable, hidden, focusable); the others stay. A node made unselectable is deselected.\",\n payloadSchema: {\n type: \"object\",\n properties: { nodeId, ...nodeFlagProperties },\n required: [\"nodeId\"],\n additionalProperties: false,\n },\n resultSchema: nodeIdResult,\n transient: false,\n reduce: ({ nodeId, ...flags }, { draft, features }) => {\n const node = findNode(draft, nodeId, \"/nodeId\");\n if (isFailure(node)) {\n return node;\n }\n draft.putNode({ ...node, ...flags });\n features.flagsChanged(draft, \"node\", nodeId);\n return ok({ nodeId });\n },\n});\n\nexport const nodeSetZIndex = defineCommand({\n name: \"node.set-z-index\",\n description:\n \"Sets a node's `zIndex`, its place in the nodes' stacking order (null: the default, 0), in place: its edges and measurements stay.\",\n payloadSchema: {\n type: \"object\",\n properties: {\n nodeId,\n zIndex: {\n anyOf: [zIndexSchema, { type: \"null\" }],\n description:\n \"its place in its layer's stacking order (an integer); null: back to the default, 0\",\n },\n },\n required: [\"nodeId\", \"zIndex\"],\n additionalProperties: false,\n },\n resultSchema: nodeIdResult,\n transient: false,\n reduce: ({ nodeId, zIndex }, { draft }) => {\n const node = findNode(draft, nodeId, \"/nodeId\");\n if (isFailure(node)) {\n return node;\n }\n const { zIndex: _was, ...rest } = node;\n draft.putNode(\n (zIndex === null ? rest : { ...rest, zIndex }) as typeof node,\n );\n return ok({ nodeId });\n },\n});\n","import { batch } from \"./batch\";\nimport type { CommandDefinition } from \"./define\";\nimport {\n edgeAdd,\n edgeRemove,\n edgeSetData,\n edgeSetFlags,\n edgeSetZIndex,\n} from \"./edge\";\nimport {\n nodeAdd,\n nodeMove,\n nodeRemove,\n nodeResize,\n nodeSetData,\n nodeSetFlags,\n nodeSetZIndex,\n} from \"./node\";\nimport type { CommandName } from \"./types\";\n\n/**\n * The core's commands, in the order `model.get(\"commands\")` lists them (an installed feature's\n * follow, in install order). Each definition keeps its schemas' literal types (the type tests read\n * them); the list erases them to `CommandDefinition` once.\n */\nexport const CORE_COMMANDS: readonly CommandDefinition[] = [\n nodeAdd,\n nodeRemove,\n nodeMove,\n nodeResize,\n nodeSetData,\n nodeSetFlags,\n nodeSetZIndex,\n edgeAdd,\n edgeRemove,\n edgeSetData,\n edgeSetFlags,\n edgeSetZIndex,\n batch,\n] as const satisfies readonly {\n readonly name: CommandName;\n readonly transient: boolean;\n readonly reduce: (...args: never[]) => unknown;\n}[] as readonly unknown[] as readonly CommandDefinition[];\n","// The model's bus (Dockable's, fragiola/dockable, packages/core/src/state/model.ts, same author and\n// licence; adapted to a flow document and to the feature registry). A command is looked up (the\n// core's, then the installed features'), its payload validated against its schema, then it runs\n// through the middleware chain (outermost first) on a draft; a success commits once and emits one\n// event. A command issued from a middleware while another runs is queued and runs after it\n// (`queued`); one a listener runs commits at once, its event delivered after the current one. Nothing here throws on bad input; a reducer or a listener that throws is a\n// bug, rethrown once the chain unwound.\nimport { CORE_COMMANDS } from \"../commands/catalogue\";\nimport {\n type CommandDefinition,\n fail,\n invalid,\n type ReduceContext,\n} from \"../commands/define\";\nimport type {\n BatchStep,\n CommandContext,\n CommandContextGetKey,\n CommandEvent,\n CommandInfo,\n CommandListener,\n CommandName,\n CommandResult,\n Middleware,\n RunOptions,\n} from \"../commands/types\";\nimport type { IdSource } from \"../document/create-id\";\nimport type { FlowDocument } from \"../document/types\";\nimport { type FeatureName, requiresFeature } from \"../features/keys\";\nimport type { ComposedFeatures } from \"../features/registry\";\nimport { isObject, validate } from \"../schema/validator\";\nimport { cloneJson } from \"../state/clone-json\";\nimport {\n CORE_GET,\n CORE_IS,\n type QueryContext,\n stringOf,\n} from \"../state/core-queries\";\nimport { deepFreeze } from \"../state/deep-freeze\";\nimport { Draft, type IndexedDocument, readerOf } from \"../state/draft\";\n\n/** What the app adds to a dispatched command: never read from the untrusted input. */\nexport interface DispatchOptions {\n /** free-form information for middleware and listeners (`{ source: \"assistant\" }`) */\n meta?: Readonly<Record<string, unknown>> | undefined;\n}\n\n/** Where a command's errors point: into its payload, and at its transient flag. */\ninterface ErrorPaths {\n readonly payload: string;\n readonly transient: string;\n}\n\n/** One top-level execution: the draft it runs on, and what it collects (the steps of a batch). */\ninterface Execution {\n readonly draft: Draft;\n readonly dryRun: boolean;\n readonly options: RunOptions;\n readonly steps: BatchStep[];\n /** an exception a reducer threw: rethrown once the chain unwound */\n thrown: { error: unknown } | undefined;\n}\n\nfunction prefixed(\n result: CommandResult<unknown>,\n prefix: string,\n): CommandResult<unknown> {\n if (result.ok || prefix === \"\") {\n return result;\n }\n const { error } = result;\n return {\n ok: false,\n error: {\n ...error,\n ...(error.path !== undefined\n ? { path: `${prefix}${error.path}` }\n : {}),\n ...(error.issues\n ? {\n issues: error.issues.map((issue) => ({\n path: `${prefix}${issue.path}`,\n message: issue.message,\n })),\n }\n : {}),\n },\n };\n}\n\n/** The model's commands' descriptions: the core's, then each installed feature's. */\nfunction describe(\n definitions: ReadonlyMap<string, CommandDefinition>,\n owners: ReadonlyMap<string, FeatureName>,\n): readonly CommandInfo[] {\n return Object.freeze(\n [...definitions.values()].map((definition) => {\n const feature = owners.get(definition.name);\n return Object.freeze({\n name: definition.name,\n description: definition.description,\n payloadSchema: definition.payloadSchema,\n resultSchema: definition.resultSchema,\n transient: definition.transient,\n ...(feature === undefined ? {} : { feature }),\n });\n }),\n );\n}\n\n/** The bus behind a model (`createFlowModel`); its verbs are bound. */\nexport class FlowModelBus {\n private committed: IndexedDocument;\n private readonly ids: IdSource;\n private readonly features: ComposedFeatures;\n private readonly freeze: boolean;\n /** the fields `edge.add` fills in where its payload leaves them out (`defaultEdgeOptions`) */\n private readonly defaultEdge: Readonly<Record<string, unknown>> | undefined;\n private readonly definitions: ReadonlyMap<string, CommandDefinition>;\n private readonly infos: readonly CommandInfo[];\n private readonly middleware: Middleware[] = [];\n private readonly listeners = new Set<CommandListener>();\n private inFlight = 0;\n /** dry runs under way (`can`, `check`): a command a middleware issues then is refused */\n private dryRuns = 0;\n private readonly queue: (() => void)[] = [];\n private readonly events: CommandEvent[] = [];\n private delivering = false;\n /** the reads' context of the committed document, made once per commit (reads are hot) */\n private reads:\n | { readonly of: IndexedDocument; readonly context: QueryContext }\n | undefined;\n\n constructor(\n committed: IndexedDocument,\n ids: IdSource,\n features: ComposedFeatures,\n freeze: boolean,\n defaultEdge?: Readonly<Record<string, unknown>> | undefined,\n ) {\n this.defaultEdge = defaultEdge;\n this.committed = committed;\n this.ids = ids;\n this.features = features;\n this.freeze = freeze;\n const definitions = new Map<string, CommandDefinition>();\n const owners = new Map<string, FeatureName>();\n for (const definition of CORE_COMMANDS) {\n definitions.set(definition.name, definition);\n }\n for (const feature of features.list) {\n for (const definition of feature.commands ?? []) {\n definitions.set(definition.name, definition);\n owners.set(definition.name, feature.name);\n }\n }\n this.definitions = definitions;\n this.infos = describe(definitions, owners);\n // the bus can be passed around detached: `const { run } = model`\n this.run = this.run.bind(this);\n this.dispatch = this.dispatch.bind(this);\n this.can = this.can.bind(this);\n this.check = this.check.bind(this);\n this.get = this.get.bind(this);\n this.is = this.is.bind(this);\n this.use = this.use.bind(this);\n this.subscribe = this.subscribe.bind(this);\n }\n\n // ---------------------------------------------------------------------------------------------\n // reads\n // ---------------------------------------------------------------------------------------------\n\n private queryContext(): QueryContext {\n const reads = this.reads;\n if (reads?.of === this.committed) return reads.context;\n const context: QueryContext = {\n reader: readerOf(this.committed),\n features: this.features,\n commands: this.infos,\n defaultEdge: this.defaultEdge,\n };\n this.reads = { of: this.committed, context };\n return context;\n }\n\n get(key: string, payload?: unknown): unknown {\n const core = Object.hasOwn(CORE_GET, key) ? CORE_GET[key] : undefined;\n if (core) {\n return core(this.queryContext(), payload);\n }\n return this.features.get.get(key)?.(\n this.queryContext().reader,\n payload,\n );\n }\n\n is(key: string, payload?: unknown): boolean {\n const core = Object.hasOwn(CORE_IS, key) ? CORE_IS[key] : undefined;\n if (core) {\n return core(this.queryContext(), payload);\n }\n return (\n this.features.is.get(key)?.(this.queryContext().reader, payload) ??\n false\n );\n }\n\n // ---------------------------------------------------------------------------------------------\n // the bus\n // ---------------------------------------------------------------------------------------------\n\n use(middleware: Middleware): () => void {\n this.middleware.push(middleware);\n return () => {\n const at = this.middleware.indexOf(middleware);\n if (at >= 0) {\n this.middleware.splice(at, 1);\n }\n };\n }\n\n subscribe(listener: CommandListener): () => void {\n // a wrapper: the same function subscribed twice is two subscriptions\n const wrapper: CommandListener = (event) => listener(event);\n this.listeners.add(wrapper);\n return () => {\n this.listeners.delete(wrapper);\n };\n }\n\n run(\n command: string,\n payload?: unknown,\n options?: RunOptions,\n ): CommandResult<unknown> {\n return this.enqueueOrExecute(\n command,\n payload === undefined ? {} : payload,\n options,\n \"\",\n );\n }\n\n can(command: string, payload?: unknown, options?: RunOptions): boolean {\n return this.check(command, payload, options).ok;\n }\n\n check(\n command: string,\n payload?: unknown,\n options?: RunOptions,\n ): CommandResult<unknown> {\n return this.execute(\n command,\n payload === undefined ? {} : payload,\n options ?? {},\n true,\n \"\",\n );\n }\n\n dispatch(\n input: unknown,\n options: DispatchOptions = {},\n ): CommandResult<unknown> {\n if (!isObject(input)) {\n return fail(\n \"invalid_payload\",\n \"must be an object { command, payload }\",\n \"\",\n );\n }\n const { command, payload, transient } = input;\n if (typeof command !== \"string\") {\n return fail(\"invalid_payload\", \"must be a string\", \"/command\");\n }\n const unknown = this.unknownCommand(command, \"/command\");\n if (unknown) {\n return unknown;\n }\n if (!isObject(payload)) {\n return fail(\"invalid_payload\", \"must be an object\", \"/payload\");\n }\n if (transient !== undefined && typeof transient !== \"boolean\") {\n return fail(\"invalid_payload\", \"must be a boolean\", \"/transient\");\n }\n for (const key of Object.keys(input)) {\n if (key !== \"command\" && key !== \"payload\" && key !== \"transient\") {\n return fail(\"invalid_payload\", \"is not allowed\", `/${key}`);\n }\n }\n return this.enqueueOrExecute(\n command,\n payload,\n {\n ...(transient === undefined ? {} : { transient }),\n ...(options.meta === undefined ? {} : { meta: options.meta }),\n },\n \"/payload\",\n );\n }\n\n /** Why a name is not a command of this model: unknown, or its feature is not installed. */\n private unknownCommand(command: string, path?: string) {\n if (this.definitions.has(command)) {\n return undefined;\n }\n const owner = this.features.missing(\"commands\", command);\n return owner === undefined\n ? fail(\"unknown_command\", `unknown command \"${command}\"`, path)\n : fail(\"not_found\", `\"${command}\" ${requiresFeature(owner)}`, path);\n }\n\n private enqueueOrExecute(\n command: string,\n payload: unknown,\n options: RunOptions | undefined,\n prefix: string,\n ): CommandResult<unknown> {\n if (this.dryRuns > 0) {\n // issued from a middleware during `can` / `check`: a dry run causes nothing\n return fail(\n \"refused\",\n `\"${command}\" was issued during a dry run (\\`can\\`, \\`check\\`); it does not run`,\n );\n }\n if (this.inFlight > 0) {\n // issued from a middleware: runs once the current command committed\n this.queue.push(() => {\n this.execute(command, payload, options ?? {}, false, prefix);\n });\n return fail(\n \"queued\",\n `\"${command}\" was issued while another command was running; it runs after it`,\n );\n }\n try {\n return this.execute(command, payload, options ?? {}, false, prefix);\n } finally {\n // a throwing listener or reducer must not strand the commands a middleware queued\n this.drain();\n }\n }\n\n private drain() {\n while (this.inFlight === 0 && this.queue.length > 0) {\n this.queue.shift()?.();\n }\n }\n\n private execute(\n command: string,\n payload: unknown,\n options: RunOptions,\n dryRun: boolean,\n prefix: string,\n ): CommandResult<unknown> {\n // a dry run commits nothing, not even the ids it generated (nor asks the app's createId)\n const ids = dryRun ? this.ids.dryClone() : this.ids;\n const draft = new Draft(this.committed, ids);\n const execution: Execution = {\n draft,\n dryRun,\n options,\n steps: [],\n thrown: undefined,\n };\n if (dryRun) {\n this.dryRuns++;\n } else {\n this.inFlight++;\n }\n let ran: { result: CommandResult<unknown>; payload: unknown };\n try {\n ran = this.runChain(\n execution,\n command,\n payload,\n { payload: prefix, transient: \"/transient\" },\n false,\n );\n } finally {\n if (dryRun) {\n this.dryRuns--;\n } else {\n this.inFlight--;\n }\n }\n if (execution.thrown) {\n throw execution.thrown.error;\n }\n const { result } = ran;\n if (!result.ok || dryRun) {\n return result;\n }\n const before = this.committed.document;\n this.committed = draft.commit(this.freeze);\n this.emit({\n command: command as CommandName,\n payload: ran.payload,\n result: result.value,\n before,\n after: this.committed.document,\n transient: options.transient === true,\n meta: options.meta,\n ...(command === \"batch\" ? { commands: execution.steps } : {}),\n });\n return result;\n }\n\n /**\n * Looks up, validates and runs one command through the middleware chain on the execution's\n * draft. Returns its result, its errors placed at `at`, and the payload the reducer ran with (a\n * middleware may have rewritten it).\n */\n private runChain(\n execution: Execution,\n command: string,\n payload: unknown,\n at: ErrorPaths,\n inBatch: boolean,\n ): { result: CommandResult<unknown>; payload: unknown } {\n const { draft, dryRun, options } = execution;\n const definition = this.definitions.get(command);\n // the default edge fields go under what an `edge.add` gives, before anything sees it\n if (\n command === \"edge.add\" &&\n this.defaultEdge !== undefined &&\n isObject(payload)\n ) {\n payload = {\n ...this.defaultEdge,\n ...Object.fromEntries(\n Object.entries(payload).filter(\n ([, value]) => value !== undefined,\n ),\n ),\n };\n }\n if (!definition) {\n return {\n result:\n this.unknownCommand(command) ??\n fail(\"unknown_command\", command),\n payload,\n };\n }\n const failed = invalid(\n validate(definition.payloadSchema, payload, at.payload),\n );\n if (failed) {\n return { result: failed, payload };\n }\n if (options.transient === true && !definition.transient) {\n return {\n result: fail(\n \"invalid_payload\",\n `\"${command}\" cannot run as a transient step`,\n at.transient,\n ),\n payload,\n };\n }\n\n // the chain sees a frozen copy: a middleware rewrites by assigning a new payload (validated\n // again), never by writing into it, and nothing reaches back into the caller's object\n const validated = deepFreeze(cloneJson(payload));\n const context = {\n command: command as CommandName,\n payload: validated,\n dryRun,\n transient: options.transient === true,\n inBatch,\n meta: options.meta,\n state: this.committed.document as FlowDocument,\n get: (key: CommandContextGetKey, query?: unknown) => {\n const id = stringOf(query, \"id\");\n if (id === undefined) {\n return undefined;\n }\n return key === \"node-by\" ? draft.node(id) : draft.edge(id);\n },\n } as CommandContext;\n\n const reduceContext: ReduceContext = {\n draft,\n features: this.features,\n runInBatch: (subCommand, subPayload, path) => {\n const sub = this.runChain(\n execution,\n subCommand,\n subPayload,\n {\n payload: `${path}/payload`,\n transient: `${path}/command`,\n },\n true,\n );\n const { result } = sub;\n if (!result.ok) {\n const { error } = result;\n if (\n error.code === \"unknown_command\" ||\n (error.code === \"not_found\" &&\n !this.definitions.has(subCommand))\n ) {\n return fail(\n error.code,\n error.message,\n `${path}/command`,\n );\n }\n // an error with no place of its own (a veto) points at its step\n return error.path === undefined\n ? { ok: false, error: { ...error, path } }\n : result;\n }\n // a nested batch's own steps are listed; the batch itself is not one\n if (subCommand !== \"batch\") {\n execution.steps.push({\n command: subCommand as CommandName,\n payload: sub.payload,\n result: result.value,\n });\n }\n return result;\n },\n };\n\n let ranWith: unknown = validated;\n let reduced: CommandResult<unknown> | undefined;\n const core = (): CommandResult<unknown> => {\n if (context.payload !== validated) {\n const rewritten = invalid(\n validate(definition.payloadSchema, context.payload),\n \"rewritten by a middleware: \",\n );\n if (rewritten) {\n return rewritten;\n }\n ranWith = deepFreeze(cloneJson(context.payload));\n }\n try {\n reduced = definition.reduce(ranWith as never, reduceContext);\n } catch (thrown) {\n execution.thrown ??= { error: thrown };\n reduced = fail(\"refused\", \"the command failed\");\n }\n return reduced;\n };\n const chained = this.chain(context, core);\n // a middleware may veto a success, never turn a failure into one: the draft the failed\n // command may have half written is not committed (a batch stays all or nothing)\n const result = prefixed(\n chained.ok && reduced !== undefined && !reduced.ok\n ? reduced\n : chained,\n at.payload,\n );\n return { result, payload: ranWith };\n }\n\n private chain(\n context: CommandContext,\n core: () => CommandResult<unknown>,\n ): CommandResult<unknown> {\n const list = [...this.middleware];\n const at = (i: number): CommandResult<unknown> => {\n const middleware = list[i];\n if (!middleware) {\n return core();\n }\n let called = false;\n let nextResult: CommandResult<unknown> = fail(\n \"vetoed\",\n \"a middleware returned no result\",\n );\n const next = () => {\n if (!called) {\n called = true;\n nextResult = at(i + 1);\n }\n return nextResult;\n };\n let out: CommandResult<unknown> | undefined;\n try {\n out = middleware(context, next);\n } catch (thrown) {\n return fail(\n \"middleware_error\",\n thrown instanceof Error ? thrown.message : String(thrown),\n );\n }\n return out ?? nextResult;\n };\n return at(0);\n }\n\n private emit(event: CommandEvent) {\n this.events.push(event);\n if (this.delivering) {\n return;\n }\n this.delivering = true;\n let failure: { error: unknown } | undefined;\n try {\n for (\n let next = this.events.shift();\n next !== undefined;\n next = this.events.shift()\n ) {\n for (const listener of [...this.listeners]) {\n try {\n listener(next);\n } catch (thrown) {\n failure ??= { error: thrown };\n }\n }\n }\n } finally {\n this.delivering = false;\n }\n if (failure) {\n throw failure.error;\n }\n }\n}\n","// The flow model (D3, D13): the document and its rules, the single source of truth. An immutable\n// document that only commands change, usable in plain Node (no DOM). Its surface is exactly the\n// five verbs plus `use`, `subscribe` and `dispatch` (a guard test keeps it so); its keys are the\n// core's and the installed features' (`F`): a command or key of a feature that is not installed\n// does not compile, and at runtime is `not_found` (a command) or `undefined` / `false` (a key).\nimport type {\n CommandContext,\n CommandListener,\n CommandResult,\n PayloadOf,\n ResultOf,\n RunOptions,\n} from \"../commands/types\";\nimport { type CreateId, IdSource } from \"../document/create-id\";\nimport { edgeSchema } from \"../document/document-schema\";\nimport { FlowValidationError } from \"../document/flow-validation-error\";\nimport { loadDocument } from \"../document/load-document\";\nimport type {\n AnyTypes,\n FlowEdgeInput,\n FlowJson,\n FlowTypes,\n} from \"../document/types\";\nimport { composeFeatures, registerFeatures } from \"../features/registry\";\nimport type {\n CommandNameOf,\n FlowFeatures,\n ModelGetKeyOf,\n ModelIsKeyOf,\n} from \"../features/types\";\nimport { validate } from \"../schema/validator\";\nimport { cloneJson } from \"../state/clone-json\";\nimport { deepFreeze } from \"../state/deep-freeze\";\nimport type {\n ModelGetPayload,\n ModelGetResult,\n ModelIsPayload,\n NoPayload,\n QueryArgs,\n} from \"../state/queries\";\nimport { type DispatchOptions, FlowModelBus } from \"./flow-model-bus\";\n\nexport type { DispatchOptions } from \"./flow-model-bus\";\n\n/**\n * The arguments after a command's name: its payload (optional when it has no required field:\n * `model.run(\"selection.clear\")`) and the run options.\n */\nexport type CommandArgs<P> = NoPayload extends P\n ? [payload?: P, options?: RunOptions]\n : [payload: P, options?: RunOptions];\n\n/**\n * The flow model. Every member is one verb, and bound (`const { run } = model` works):\n *\n * - `run` changes the flow (a command, through the middleware chain); `dispatch` is `run` for\n * untrusted JSON;\n * - `can` answers whether `run` would succeed; `check` returns what it would return;\n * - `get` reads (`model.get(\"node-by\", { id })`); `is` asks a yes/no question\n * (`model.is(\"node-draggable\", { nodeId })`);\n * - `use` adds a middleware around every command; `subscribe` listens to every commit.\n *\n * `F` is the installed features; the default, any features, is what every model is assignable to.\n */\nexport interface FlowModel<\n T extends FlowTypes = AnyTypes,\n F extends FlowFeatures = FlowFeatures,\n> {\n /**\n * changes the flow: runs a command (typed) through the middleware chain; never throws on bad\n * input. A command of a feature that is not installed returns `not_found`\n */\n run<C extends CommandNameOf<F>>(\n command: C,\n ...args: CommandArgs<PayloadOf<T, C>>\n ): CommandResult<ResultOf<T, C>>;\n /**\n * `run` for a command given as untrusted JSON `{ command, payload, transient? }`, validated\n * first; `options.meta` (the app's, never the input's) reaches middleware and listeners\n */\n dispatch(input: unknown, options?: DispatchOptions): CommandResult<unknown>;\n /** whether `run` would succeed now (a dry run: nothing is committed or emitted) */\n can<C extends CommandNameOf<F>>(\n command: C,\n ...args: CommandArgs<PayloadOf<T, C>>\n ): boolean;\n /** what `run` would return (its value, or why it is refused), without committing or emitting */\n check<C extends CommandNameOf<F>>(\n command: C,\n ...args: CommandArgs<PayloadOf<T, C>>\n ): CommandResult<ResultOf<T, C>>;\n /** reads from the committed document: a node, the edges of a node, the JSON, the commands, … */\n get<K extends ModelGetKeyOf<F>>(\n key: K,\n ...payload: QueryArgs<ModelGetPayload<T, K>>\n ): ModelGetResult<T, K>;\n /** asks a yes/no question about the committed document */\n is<K extends ModelIsKeyOf<F>>(key: K, payload: ModelIsPayload<K>): boolean;\n /** adds a middleware around every command (the first added runs outermost); returns its remover */\n use(\n middleware: {\n // a method's parameters compare both ways: a model with features is a model\n middleware(\n ctx: CommandContext<T, F>,\n next: () => CommandResult<unknown>,\n ): CommandResult<unknown> | undefined;\n }[\"middleware\"],\n ): () => void;\n /** listens to every committed command (one event per commit); returns its remover */\n subscribe(listener: CommandListener<T>): () => void;\n}\n\n/**\n * The fields `edge.add` fills in when its payload leaves them out (the `defaultEdgeOptions` model\n * option): an edge's type, data, `zIndex` and flags, never its id or its ends.\n */\nexport type DefaultEdgeOptions<T extends FlowTypes = AnyTypes> = Partial<\n Omit<\n FlowEdgeInput<T>,\n \"id\" | \"source\" | \"target\" | \"sourceHandle\" | \"targetHandle\"\n >\n>;\n\n/** Options of {@link createFlowModel}. */\nexport interface FlowModelOptions<\n F extends FlowFeatures = readonly [],\n T extends FlowTypes = AnyTypes,\n> {\n /**\n * the opt-in features (`[selection(), subflows()]`), each from its own entry\n * (`@fragiola/flow/<feature>`): fixed for the model's life. Without them, a bare flow\n */\n features?: F | undefined;\n /** generates the id of a node or edge given without one; default `` `${kind}-${n}` `` */\n createId?: CreateId | undefined;\n /** freeze the document (default true) */\n freeze?: boolean | undefined;\n /**\n * the fields every `edge.add` fills in where its payload leaves them out, before the\n * middleware sees it (`{ type: \"smoothstep\" }`: a connection's new edges are smooth steps);\n * the document's edges are loaded as they are. An invalid one throws a `TypeError`\n */\n defaultEdgeOptions?: DefaultEdgeOptions<T> | undefined;\n}\n\nconst EMPTY_FLOW: FlowJson = { version: 1, nodes: [], edges: [] };\n\n/**\n * Creates a flow model from a JSON v1 document (an empty flow without one), with the features it\n * installs (`createFlowModel<Types, typeof features>(json, { features })`). The document is\n * validated: an invalid one throws a {@link FlowValidationError} listing every problem with its\n * JSON path. A feature installed twice, or missing one it requires, throws a `TypeError` naming\n * both.\n */\nexport function createFlowModel<\n T extends FlowTypes = AnyTypes,\n const F extends FlowFeatures = readonly [],\n>(json?: FlowJson<T>, options: FlowModelOptions<F, T> = {}): FlowModel<T, F> {\n const features = composeFeatures(options.features);\n const defaults = edgeDefaults(options.defaultEdgeOptions);\n const ids = new IdSource(options.createId);\n const freeze = options.freeze ?? true;\n const loaded = loadDocument(json ?? EMPTY_FLOW, ids, features, freeze);\n if (!loaded.ok) {\n throw new FlowValidationError(loaded.issues);\n }\n const bus = new FlowModelBus(\n loaded.indexed,\n ids,\n features,\n freeze,\n defaults,\n );\n // the verbs only, bound: the surface stays exact (the bus's internals are not reachable)\n const model = Object.freeze({\n run: bus.run,\n dispatch: bus.dispatch,\n can: bus.can,\n check: bus.check,\n get: bus.get,\n is: bus.is,\n use: bus.use,\n subscribe: bus.subscribe,\n }) as unknown as FlowModel<T, F>;\n registerFeatures(model, features);\n return model;\n}\n\n/** The default edge fields, checked against the edge schema once (a copy, frozen). */\nfunction edgeDefaults(\n defaults: object | undefined,\n): Readonly<Record<string, unknown>> | undefined {\n if (defaults === undefined) return undefined;\n const copy = cloneJson(defaults) as Record<string, unknown>;\n for (const key of [\n \"id\",\n \"source\",\n \"target\",\n \"sourceHandle\",\n \"targetHandle\",\n ]) {\n if (key in copy) {\n throw new TypeError(\n `defaultEdgeOptions cannot set \"${key}\": an edge's id and ends are its own`,\n );\n }\n }\n const issues = validate(\n edgeSchema,\n { source: \"a\", target: \"b\", ...copy },\n \"/defaultEdgeOptions\",\n );\n if (issues.length > 0) {\n throw new TypeError(\n `defaultEdgeOptions is not valid: ${issues.map((issue) => `${issue.path} ${issue.message}`).join(\"; \")}`,\n );\n }\n return deepFreeze(copy);\n}\n","// Whether two reads of the flow are the same value, for the adapters' hooks: a hook re-renders\n// (or a composable, rune or signal changes) only when what it selected changed, and every\n// adapter compares the same way.\n\n/** Whether a value is a plain record (`{ … }`): not an array, a class instance or null. */\nfunction plainRecord(\n value: unknown,\n): value is Readonly<Record<string, unknown>> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n return false;\n }\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n/**\n * Whether two values read from the model or the engine are the same: the same value\n * (`Object.is`), or arrays of the same values in order, or plain records with the same keys and\n * values, compared all the way down. Anything else (a DOM event, a class instance, a function)\n * is the same only when it is the very same.\n */\nexport function sameFlowValue(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (Array.isArray(a) && Array.isArray(b)) {\n return (\n a.length === b.length &&\n a.every((value, i) => sameFlowValue(value, b[i]))\n );\n }\n if (plainRecord(a) && plainRecord(b)) {\n const keys = Object.keys(a);\n return (\n keys.length === Object.keys(b).length &&\n keys.every(\n (key) => Object.hasOwn(b, key) && sameFlowValue(a[key], b[key]),\n )\n );\n }\n return false;\n}\n"],"mappings":";;;;;;;;;AAGA,SAAgB,KAAK,UAAU,0BAG7B;CACE,OAAO;EAAE,IAAI;EAAO,OAAO;GAAE,MAAM;GAAU;EAAQ;CAAE;AAC3D;;;ACLA,IAAa,sBAAb,cAAyC,MA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