@pauloricca/spagbol 0.0.0-stage → 0.1.1

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.
Files changed (159) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +338 -2
  3. package/dist/controls.css +122 -0
  4. package/dist/core/controller.d.ts +89 -0
  5. package/dist/core/controller.d.ts.map +1 -0
  6. package/dist/core/controller.js +732 -0
  7. package/dist/core/controller.js.map +1 -0
  8. package/dist/core/graph.d.ts +30 -0
  9. package/dist/core/graph.d.ts.map +1 -0
  10. package/dist/core/graph.js +318 -0
  11. package/dist/core/graph.js.map +1 -0
  12. package/dist/core/grouping.d.ts +10 -0
  13. package/dist/core/grouping.d.ts.map +1 -0
  14. package/dist/core/grouping.js +130 -0
  15. package/dist/core/grouping.js.map +1 -0
  16. package/dist/core/groups.d.ts +40 -0
  17. package/dist/core/groups.d.ts.map +1 -0
  18. package/dist/core/groups.js +164 -0
  19. package/dist/core/groups.js.map +1 -0
  20. package/dist/core/index.d.ts +8 -0
  21. package/dist/core/index.d.ts.map +1 -0
  22. package/dist/core/index.js +8 -0
  23. package/dist/core/index.js.map +1 -0
  24. package/dist/core/model.d.ts +182 -0
  25. package/dist/core/model.d.ts.map +1 -0
  26. package/dist/core/model.js +149 -0
  27. package/dist/core/model.js.map +1 -0
  28. package/dist/core/observations.d.ts +10 -0
  29. package/dist/core/observations.d.ts.map +1 -0
  30. package/dist/core/observations.js +36 -0
  31. package/dist/core/observations.js.map +1 -0
  32. package/dist/core/serialization.d.ts +9 -0
  33. package/dist/core/serialization.d.ts.map +1 -0
  34. package/dist/core/serialization.js +148 -0
  35. package/dist/core/serialization.js.map +1 -0
  36. package/dist/index.d.ts +4 -0
  37. package/dist/index.d.ts.map +1 -0
  38. package/dist/index.js +4 -0
  39. package/dist/index.js.map +1 -0
  40. package/dist/link-controls.css +123 -0
  41. package/dist/react/Controls.d.ts +18 -0
  42. package/dist/react/Controls.d.ts.map +1 -0
  43. package/dist/react/Controls.js +301 -0
  44. package/dist/react/Controls.js.map +1 -0
  45. package/dist/react/SpagbolCanvas.d.ts +38 -0
  46. package/dist/react/SpagbolCanvas.d.ts.map +1 -0
  47. package/dist/react/SpagbolCanvas.js +1248 -0
  48. package/dist/react/SpagbolCanvas.js.map +1 -0
  49. package/dist/react/SpagbolCanvasControls.d.ts +36 -0
  50. package/dist/react/SpagbolCanvasControls.d.ts.map +1 -0
  51. package/dist/react/SpagbolCanvasControls.js +113 -0
  52. package/dist/react/SpagbolCanvasControls.js.map +1 -0
  53. package/dist/react/SpagbolCanvasFlow.d.ts +14 -0
  54. package/dist/react/SpagbolCanvasFlow.d.ts.map +1 -0
  55. package/dist/react/SpagbolCanvasFlow.js +6 -0
  56. package/dist/react/SpagbolCanvasFlow.js.map +1 -0
  57. package/dist/react/SpagbolCanvasLinkControls.d.ts +16 -0
  58. package/dist/react/SpagbolCanvasLinkControls.d.ts.map +1 -0
  59. package/dist/react/SpagbolCanvasLinkControls.js +7 -0
  60. package/dist/react/SpagbolCanvasLinkControls.js.map +1 -0
  61. package/dist/react/SpagbolCanvasMenu.d.ts +12 -0
  62. package/dist/react/SpagbolCanvasMenu.d.ts.map +1 -0
  63. package/dist/react/SpagbolCanvasMenu.js +65 -0
  64. package/dist/react/SpagbolCanvasMenu.js.map +1 -0
  65. package/dist/react/SpagbolControlNumber.d.ts +25 -0
  66. package/dist/react/SpagbolControlNumber.d.ts.map +1 -0
  67. package/dist/react/SpagbolControlNumber.js +209 -0
  68. package/dist/react/SpagbolControlNumber.js.map +1 -0
  69. package/dist/react/SpagbolControlNumberLink.d.ts +6 -0
  70. package/dist/react/SpagbolControlNumberLink.d.ts.map +1 -0
  71. package/dist/react/SpagbolControlNumberLink.js +159 -0
  72. package/dist/react/SpagbolControlNumberLink.js.map +1 -0
  73. package/dist/react/SpagbolControlZoom.d.ts +11 -0
  74. package/dist/react/SpagbolControlZoom.d.ts.map +1 -0
  75. package/dist/react/SpagbolControlZoom.js +24 -0
  76. package/dist/react/SpagbolControlZoom.js.map +1 -0
  77. package/dist/react/SpagbolNodeFrame.d.ts +35 -0
  78. package/dist/react/SpagbolNodeFrame.d.ts.map +1 -0
  79. package/dist/react/SpagbolNodeFrame.js +171 -0
  80. package/dist/react/SpagbolNodeFrame.js.map +1 -0
  81. package/dist/react/SpagbolNodeFrameTypePicker.d.ts +9 -0
  82. package/dist/react/SpagbolNodeFrameTypePicker.d.ts.map +1 -0
  83. package/dist/react/SpagbolNodeFrameTypePicker.js +68 -0
  84. package/dist/react/SpagbolNodeFrameTypePicker.js.map +1 -0
  85. package/dist/react/SpagbolNodeGroupPort.d.ts +15 -0
  86. package/dist/react/SpagbolNodeGroupPort.d.ts.map +1 -0
  87. package/dist/react/SpagbolNodeGroupPort.js +62 -0
  88. package/dist/react/SpagbolNodeGroupPort.js.map +1 -0
  89. package/dist/react/SpagbolNodeGroupPortAdd.d.ts +5 -0
  90. package/dist/react/SpagbolNodeGroupPortAdd.d.ts.map +1 -0
  91. package/dist/react/SpagbolNodeGroupPortAdd.js +27 -0
  92. package/dist/react/SpagbolNodeGroupPortAdd.js.map +1 -0
  93. package/dist/react/context.d.ts +84 -0
  94. package/dist/react/context.d.ts.map +1 -0
  95. package/dist/react/context.js +43 -0
  96. package/dist/react/context.js.map +1 -0
  97. package/dist/react/duplicateDrag.d.ts +19 -0
  98. package/dist/react/duplicateDrag.d.ts.map +1 -0
  99. package/dist/react/duplicateDrag.js +71 -0
  100. package/dist/react/duplicateDrag.js.map +1 -0
  101. package/dist/react/flowPresentation.d.ts +11 -0
  102. package/dist/react/flowPresentation.d.ts.map +1 -0
  103. package/dist/react/flowPresentation.js +50 -0
  104. package/dist/react/flowPresentation.js.map +1 -0
  105. package/dist/react/geometry.d.ts +13 -0
  106. package/dist/react/geometry.d.ts.map +1 -0
  107. package/dist/react/geometry.js +43 -0
  108. package/dist/react/geometry.js.map +1 -0
  109. package/dist/react/index.d.ts +11 -0
  110. package/dist/react/index.d.ts.map +1 -0
  111. package/dist/react/index.js +11 -0
  112. package/dist/react/index.js.map +1 -0
  113. package/dist/react/nodeDrag.d.ts +7 -0
  114. package/dist/react/nodeDrag.d.ts.map +1 -0
  115. package/dist/react/nodeDrag.js +27 -0
  116. package/dist/react/nodeDrag.js.map +1 -0
  117. package/dist/react/portState.d.ts +10 -0
  118. package/dist/react/portState.d.ts.map +1 -0
  119. package/dist/react/portState.js +35 -0
  120. package/dist/react/portState.js.map +1 -0
  121. package/dist/react/viewport.d.ts +24 -0
  122. package/dist/react/viewport.d.ts.map +1 -0
  123. package/dist/react/viewport.js +55 -0
  124. package/dist/react/viewport.js.map +1 -0
  125. package/dist/styles.css +748 -0
  126. package/package.json +58 -4
  127. package/src/core/controller.ts +844 -0
  128. package/src/core/graph.ts +451 -0
  129. package/src/core/grouping.ts +159 -0
  130. package/src/core/groups.ts +125 -0
  131. package/src/core/index.ts +7 -0
  132. package/src/core/model.ts +304 -0
  133. package/src/core/observations.ts +31 -0
  134. package/src/core/serialization.ts +184 -0
  135. package/src/index.ts +9 -0
  136. package/src/react/Controls.tsx +355 -0
  137. package/src/react/SpagbolCanvas.tsx +1893 -0
  138. package/src/react/SpagbolCanvasControls.tsx +255 -0
  139. package/src/react/SpagbolCanvasFlow.tsx +38 -0
  140. package/src/react/SpagbolCanvasLinkControls.tsx +21 -0
  141. package/src/react/SpagbolCanvasMenu.tsx +121 -0
  142. package/src/react/SpagbolControlNumber.tsx +297 -0
  143. package/src/react/SpagbolControlNumberLink.tsx +209 -0
  144. package/src/react/SpagbolControlZoom.tsx +102 -0
  145. package/src/react/SpagbolNodeFrame.tsx +330 -0
  146. package/src/react/SpagbolNodeFrameTypePicker.tsx +51 -0
  147. package/src/react/SpagbolNodeGroupPort.tsx +111 -0
  148. package/src/react/SpagbolNodeGroupPortAdd.tsx +48 -0
  149. package/src/react/context.tsx +146 -0
  150. package/src/react/controls.css +122 -0
  151. package/src/react/duplicateDrag.ts +97 -0
  152. package/src/react/flowPresentation.ts +56 -0
  153. package/src/react/geometry.ts +53 -0
  154. package/src/react/index.ts +61 -0
  155. package/src/react/link-controls.css +123 -0
  156. package/src/react/nodeDrag.ts +33 -0
  157. package/src/react/portState.ts +24 -0
  158. package/src/react/styles.css +748 -0
  159. package/src/react/viewport.ts +90 -0
@@ -0,0 +1,1248 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { previewNodePositions, applyNodePositions } from "./nodeDrag.js";
3
+ import { createPortal } from "react-dom";
4
+ import { SpagbolCanvasLinkControls } from "./SpagbolCanvasLinkControls.js";
5
+ import { SpagbolCanvasFlow } from "./SpagbolCanvasFlow.js";
6
+ import { BaseEdge, ConnectionLineType, EdgeLabelRenderer, Handle, Position, ReactFlow, ReactFlowProvider, SelectionMode, ViewportPortal, useReactFlow, useStore, useStoreApi, useUpdateNodeInternals, useNodeId, useNodesInitialized, useViewport, } from "@xyflow/react";
7
+ import { memo, useCallback, useEffect, useId, useMemo, useRef, useState, } from "react";
8
+ import { areaMembers, groupPanelLayout, spagbolGroupKinds, copyFragment, createId, portsFor, readFragment, } from "../core/index.js";
9
+ import { GraphContext, useEditorSnapshot, useEditorSelector, useSpagbol, } from "./context.js";
10
+ import { SpagbolNodeFrame, SpagbolNodePanel, useNodeViewProps } from "./SpagbolNodeFrame.js";
11
+ import { SpagbolControlNumber } from "./SpagbolControlNumber.js";
12
+ import { SpagbolCanvasControls, } from "./SpagbolCanvasControls.js";
13
+ import { rememberMeasurements, reuseFlowPresentations, stationaryReconnectEdge, } from "./flowPresentation.js";
14
+ import { duplicateDragPresentation, } from "./duplicateDrag.js";
15
+ import { translateExtentForVisibleContent, clampViewportToTranslateExtent, infiniteCanvasExtent, } from "./viewport.js";
16
+ import { anchorFlowId, areaFlowId, linkPath, nodeFlowId, parseHandle, sourceHandle, targetHandle, } from "./geometry.js";
17
+ const emptyFlowNodes = [];
18
+ const emptyViews = Object.freeze({});
19
+ const emptyPresentations = Object.freeze({});
20
+ const defaultFeatures = { compact: true, nestedGraphs: true, panels: true, areas: true, linkProperties: true };
21
+ export function SpagbolCanvas(props) {
22
+ const margin = props.panBounds === false ? undefined : props.panBounds?.emptyScreenRatio;
23
+ if (margin !== undefined && (!Number.isFinite(margin) || margin < 0))
24
+ throw new Error("Pan margin must be a finite, nonnegative screen proportion.");
25
+ const features = useMemo(() => ({ ...defaultFeatures, ...props.features }), [props.features]);
26
+ if (features.panels && !features.nestedGraphs)
27
+ throw new Error("Projected panels require the nestedGraphs feature.");
28
+ return (_jsx(ReactFlowProvider, { children: _jsx(SpagbolCanvasInner, { ...props, features: features }) }));
29
+ }
30
+ const SpagbolNodeRenderer = memo(function SpagbolNodeRenderer({ data, selected }) {
31
+ const node = data.node;
32
+ const { views, features, editor } = useSpagbol();
33
+ const updateInternals = useUpdateNodeInternals();
34
+ const flowId = useNodeId();
35
+ const portKey = portsFor(node, editor.nodes)
36
+ .map((port) => `${port.direction}:${port.id}`)
37
+ .join("|");
38
+ useEffect(() => {
39
+ if (data.projected || !flowId)
40
+ return;
41
+ const frame = requestAnimationFrame(() => updateInternals(flowId));
42
+ return () => cancelAnimationFrame(frame);
43
+ }, [flowId, portKey, data.projected, updateInternals]);
44
+ const baseProps = useNodeViewProps(node, selected, data.projected === true);
45
+ const props = {
46
+ ...baseProps,
47
+ readOnly: baseProps.readOnly || data.stationaryOriginal === true,
48
+ };
49
+ const view = views[node.kind];
50
+ const Renderer = data.projected ? view?.projected : view?.render;
51
+ const Body = view?.body;
52
+ const content = Renderer ? (_jsx(Renderer, { ...props })) : (_jsxs(SpagbolNodeFrame, { ...props, children: [features.panels && node.graph && groupPanelLayout(node) ? (_jsx(SpagbolNodePanel, { group: node })) : null, Body ? _jsx(Body, { ...props }) : null] }));
53
+ return data.stationaryOriginal ? (_jsx("div", { className: "spagbol-canvas-duplicate-origin", inert: true, children: content })) : (content);
54
+ }, (previous, next) => previous.selected === next.selected && previous.data.node === next.data.node && previous.data.projected === next.data.projected && previous.data.stationaryOriginal === next.data.stationaryOriginal);
55
+ const SpagbolCanvasLinkAnchor = memo(function SpagbolCanvasLinkAnchor({ data }) {
56
+ const { editor, connecting } = useSpagbol();
57
+ return (_jsx("div", { className: "spagbol-canvas-link-anchor", children: (editor.policy.linkProperties ?? []).map((property) => (_jsx(Handle, { id: `property:${property}`, type: "target", position: Position.Left, className: "spagbol-property-port", isConnectable: editor.editing && connecting, style: { opacity: 0 }, "aria-label": `Link ${property}` }, property))) }));
58
+ }, (before, after) => before.data.linkId === after.data.linkId);
59
+ function SpagbolCanvasArea({ data, selected }) {
60
+ const area = data.area;
61
+ const { editor, zoom, areaDuplicate } = useSpagbol();
62
+ const [titleEditing, setTitleEditing] = useState(false);
63
+ const [titleDraft, setTitleDraft] = useState(area.title);
64
+ const drag = useRef(null);
65
+ function start(event, resize = false) {
66
+ if (!editor.editing || event.button !== 0)
67
+ return;
68
+ event.preventDefault();
69
+ event.stopPropagation();
70
+ editor.select({ areaIds: [area.id] });
71
+ editor.beginGesture(resize ? "Resize area" : event.altKey ? "Duplicate area" : "Move area");
72
+ if (!resize && event.altKey)
73
+ areaDuplicate?.(area.id, "start", { x: 0, y: 0 }, event.metaKey || event.ctrlKey || event.shiftKey);
74
+ drag.current = {
75
+ pointer: event.pointerId,
76
+ start: { x: event.clientX, y: event.clientY },
77
+ position: { ...area.position },
78
+ size: { ...area.size },
79
+ resize,
80
+ duplicate: !resize && event.altKey, offset: { x: 0, y: 0 }, moved: false, title: !!event.target.closest(".spagbol-canvas-area-title"),
81
+ };
82
+ event.currentTarget.setPointerCapture(event.pointerId);
83
+ }
84
+ function move(event) {
85
+ const current = drag.current;
86
+ if (!current || current.pointer !== event.pointerId)
87
+ return;
88
+ event.stopPropagation();
89
+ const x = (event.clientX - current.start.x) / zoom, y = (event.clientY - current.start.y) / zoom;
90
+ current.offset = { x, y };
91
+ current.moved ||= Math.abs(x) + Math.abs(y) > 3 / zoom;
92
+ if (current.duplicate) {
93
+ areaDuplicate?.(area.id, "move", { x, y });
94
+ return;
95
+ }
96
+ if (current.resize) {
97
+ const members = areaMembers(editor.graph, area.id);
98
+ const minWidth = area.locked
99
+ ? Math.max(140, ...editor.graph.nodes
100
+ .filter((node) => members.nodeIds.has(node.id))
101
+ .map((node) => node.position.x - area.position.x + (node.size?.width ?? 220)))
102
+ : 140;
103
+ const minHeight = area.locked
104
+ ? Math.max(80, ...editor.graph.nodes
105
+ .filter((node) => members.nodeIds.has(node.id))
106
+ .map((node) => node.position.y -
107
+ area.position.y +
108
+ (node.size?.height ?? 120)))
109
+ : 80;
110
+ editor.updateArea(area.id, {
111
+ size: {
112
+ width: Math.max(minWidth, current.size.width + x),
113
+ height: Math.max(minHeight, current.size.height + y),
114
+ },
115
+ });
116
+ }
117
+ else
118
+ editor.moveArea(area.id, {
119
+ x: current.position.x + x,
120
+ y: current.position.y + y,
121
+ });
122
+ }
123
+ function end(event, cancel = false) {
124
+ const current = drag.current;
125
+ if (current?.pointer !== event.pointerId)
126
+ return;
127
+ drag.current = null;
128
+ if (event.currentTarget.hasPointerCapture(event.pointerId))
129
+ event.currentTarget.releasePointerCapture(event.pointerId);
130
+ if (current.duplicate)
131
+ areaDuplicate?.(area.id, cancel || !current.moved ? 'cancel' : 'end', current.offset);
132
+ else {
133
+ if (cancel)
134
+ editor.cancelGesture();
135
+ else
136
+ editor.commitGesture();
137
+ if (!cancel && !current.moved && current.title) {
138
+ setTitleDraft(area.title);
139
+ setTitleEditing(true);
140
+ }
141
+ }
142
+ }
143
+ const pointerHandlers = {
144
+ onPointerMove: move,
145
+ onPointerUp: (event) => end(event),
146
+ onPointerCancel: (event) => end(event, true),
147
+ onLostPointerCapture: (event) => end(event, true),
148
+ };
149
+ return (_jsxs("div", { inert: data.stationaryOriginal === true, className: `spagbol-canvas-area${selected ? " spagbol-canvas-area-selected" : ""}${area.collapsed ? " spagbol-canvas-area-collapsed" : ""}`, style: {
150
+ width: area.size.width,
151
+ height: area.collapsed
152
+ ? 34 + (area.controlHeight ?? 0)
153
+ : area.size.height,
154
+ }, children: [_jsxs("div", { className: "spagbol-canvas-area-header nodrag nopan", onPointerDown: (event) => start(event), ...pointerHandlers, children: [titleEditing ? _jsx("input", { autoFocus: true, className: "spagbol-canvas-area-title-input nodrag nopan", "aria-label": "Area title", value: titleDraft, onFocus: event => event.currentTarget.select(), onChange: event => setTitleDraft(event.currentTarget.value), onPointerDown: event => event.stopPropagation(), onBlur: () => { editor.updateArea(area.id, { title: titleDraft.trim() || 'Area' }); setTitleEditing(false); }, onKeyDown: event => { event.stopPropagation(); if (event.key === 'Enter')
155
+ event.currentTarget.blur(); if (event.key === 'Escape') {
156
+ setTitleDraft(area.title);
157
+ setTitleEditing(false);
158
+ } } }) : _jsx("span", { className: "spagbol-canvas-area-title", onDoubleClick: event => { event.stopPropagation(); if (editor.editing) {
159
+ setTitleDraft(area.title);
160
+ setTitleEditing(true);
161
+ } }, children: area.title }), _jsxs("div", { className: "spagbol-canvas-area-actions", onPointerDown: (event) => event.stopPropagation(), children: [_jsx("button", { title: area.locked ? "Unlock membership" : "Lock membership", "aria-label": area.locked ? "Unlock membership" : "Lock membership", disabled: !editor.editing, onClick: () => editor.lockArea(area.id, !area.locked), children: area.locked ? "●" : "○" }), _jsx("button", { title: area.collapsed ? "Expand area" : "Collapse area", "aria-label": area.collapsed ? "Expand area" : "Collapse area", disabled: !editor.editing, onClick: () => editor.updateArea(area.id, { collapsed: !area.collapsed }), children: area.collapsed ? "+" : "−" })] })] }), !area.collapsed && area.controlHeight ? (_jsx("div", { className: "spagbol-canvas-area-divider", style: { top: 34 + area.controlHeight } })) : null, !area.collapsed && editor.editing && (_jsx("button", { className: "spagbol-canvas-area-resize nodrag nopan", "aria-label": "Resize area", onPointerDown: (event) => start(event, true), ...pointerHandlers })), _jsx(Handle, { id: "collapsed:in", type: "target", position: Position.Left, isConnectable: false, className: "spagbol-canvas-area-pin", style: { top: 17 } }), _jsx(Handle, { id: "collapsed:out", type: "source", position: Position.Right, isConnectable: false, className: "spagbol-canvas-area-pin", style: { top: 17 } })] }));
162
+ }
163
+ const SpagbolCanvasLink = memo(function SpagbolCanvasLink(props) {
164
+ const { editor, diagnostics, linkOverlay, connecting } = useSpagbol();
165
+ const flow = useReactFlow();
166
+ const viewport = useViewport();
167
+ const [controlsVisible, setControlsVisible] = useState(false);
168
+ const selectedLinkId = useEditorSelector(editor, snapshot => snapshot.selection.linkIds.length === 1 ? snapshot.selection.linkIds[0] : undefined);
169
+ const showControls = props.selected && selectedLinkId === props.id && editor.editing && !connecting && !props.data?.virtual;
170
+ useEffect(() => {
171
+ if (!showControls) {
172
+ setControlsVisible(false);
173
+ return;
174
+ }
175
+ const timer = window.setTimeout(() => setControlsVisible(true), 260);
176
+ return () => window.clearTimeout(timer);
177
+ }, [showControls]);
178
+ const link = props.data.link;
179
+ const [path, x, y] = linkPath({ x: props.sourceX, y: props.sourceY }, { x: props.targetX, y: props.targetY }, props.data?.feedback, link.target.type === "port" && link.source.nodeId === link.target.nodeId);
180
+ const mode = editor.modes.get(link.mode);
181
+ const errors = diagnostics.filter((item) => item.linkId === link.id);
182
+ const selected = props.selected;
183
+ const className = `spagbol-canvas-link${selected || props.data?.emphasized ? " spagbol-canvas-link-emphasized" : ""}${props.data?.dimmed ? " spagbol-canvas-link-dimmed" : ""}${props.data?.disabled ? " spagbol-canvas-link-disabled" : ""}${props.data?.control ? " spagbol-canvas-link-control" : ""}${props.data?.virtual ? " spagbol-canvas-link-virtual" : ""}${errors.length ? " spagbol-canvas-link-error" : ""}`;
184
+ return (_jsxs(_Fragment, { children: [_jsx("path", { d: path, className: "spagbol-canvas-link-underlay", fill: "none", style: { strokeWidth: selected || props.data?.emphasized ? 7 : 5 } }), _jsx(BaseEdge, { id: props.id, path: path, interactionWidth: link.source.nodeId ===
185
+ (link.target.type === "port" ? link.target.nodeId : null)
186
+ ? 38
187
+ : 22, className: `${className}${props.data?.preview ? " spagbol-canvas-link-preview" : ""}`, style: { stroke: mode?.color ?? "var(--spagbol-muted)" } }), _jsx("path", { d: path, className: "spagbol-canvas-link-hit", "data-spagbol-link": link.id, fill: "none", pointerEvents: "none" }), showControls && controlsVisible && linkOverlay && createPortal(_jsx(SpagbolCanvasLinkControls, { style: { left: flow.flowToScreenPosition({ x, y }).x, top: flow.flowToScreenPosition({ x, y: !(props.data?.feedback || props.source === props.target) && Math.hypot(props.targetX - props.sourceX, props.targetY - props.sourceY) < 144 ? y - 52 : y }).y, transform: `translate(-50%, -50%) scale(${viewport.zoom})` }, weight: link.weight, mode: link.mode, enabled: link.enabled !== false, modes: editor.modes.list().filter(mode => !editor.policy.modes || editor.policy.modes.includes(mode.id)), onWeightChange: weight => editor.updateLink(link.id, { weight }), onModeChange: mode => editor.updateLink(link.id, { mode }), onEnabledChange: enabled => editor.updateLink(link.id, { enabled }) }), linkOverlay), errors.length > 0 && (_jsx(EdgeLabelRenderer, { children: _jsx("div", { className: "spagbol-canvas-link-diagnostic", role: "status", style: {
188
+ transform: `translate(-50%, -50%) translate(${x}px,${y + 18}px)`,
189
+ }, title: errors.map((error) => error.message).join("\n"), children: "!" }) }))] }));
190
+ }, (before, after) => {
191
+ if (before.id !== after.id || before.selected !== after.selected || before.source !== after.source || before.target !== after.target || before.sourceX !== after.sourceX || before.sourceY !== after.sourceY || before.targetX !== after.targetX || before.targetY !== after.targetY)
192
+ return false;
193
+ const keys = Object.keys(before.data ?? {});
194
+ return keys.length === Object.keys(after.data ?? {}).length && keys.every(key => before.data?.[key] === after.data?.[key]);
195
+ });
196
+ const nodeTypes = {
197
+ spagbolNode: SpagbolNodeRenderer,
198
+ spagbolArea: SpagbolCanvasArea,
199
+ spagbolAnchor: SpagbolCanvasLinkAnchor,
200
+ };
201
+ const edgeTypes = { spagbolLink: SpagbolCanvasLink };
202
+ function SpagbolCanvasInner({ editor, views = emptyViews, features = defaultFeatures, linkPresentation = emptyPresentations, ...props }) {
203
+ const snapshot = useEditorSnapshot(editor);
204
+ const graph = editor.graph;
205
+ const root = useRef(null);
206
+ const [linkOverlay, setLinkOverlay] = useState(null);
207
+ const instanceId = useId();
208
+ const flow = useReactFlow();
209
+ const flowStore = useStoreApi();
210
+ const nodesInitialized = useNodesInitialized();
211
+ // Only cable-property anchors need live native geometry. Subscribing to every
212
+ // position change otherwise causes redundant full-canvas renders during drags.
213
+ const flowNodes = useStore((state) => features.linkProperties ? state.nodes : emptyFlowNodes);
214
+ // Measurements are canvas state, not saved graph data. Retaining them keeps
215
+ // React Flow from hiding/reinitializing every node on each drag preview frame.
216
+ const measuredSizes = useRef(new Map());
217
+ const [measurementRevision, setMeasurementRevision] = useState(0);
218
+ const [zoom, setZoom] = useState(props.defaultViewport?.zoom ?? 1);
219
+ const [settledViewport, setSettledViewport] = useState(props.defaultViewport ?? { x: 0, y: 0, zoom: 1 });
220
+ const [editorSize, setEditorSize] = useState({ width: 0, height: 0 });
221
+ const viewportMoving = useRef(false);
222
+ useEffect(() => {
223
+ const element = root.current;
224
+ if (!element)
225
+ return;
226
+ const update = () => {
227
+ const bounds = element.getBoundingClientRect();
228
+ setEditorSize((previous) => previous.width === bounds.width && previous.height === bounds.height
229
+ ? previous
230
+ : { width: bounds.width, height: bounds.height });
231
+ };
232
+ update();
233
+ const observer = new ResizeObserver(update);
234
+ observer.observe(element);
235
+ return () => observer.disconnect();
236
+ }, []);
237
+ const [connecting, setConnecting] = useState(false);
238
+ const [revealedNodeId, setRevealedNodeId] = useState(null);
239
+ const [activeMode, setActiveMode] = useState(editor.policy.modes?.[0] ?? editor.modes.list()[0]?.id ?? "set");
240
+ const [picker, setPicker] = useState(null);
241
+ const [search, setSearch] = useState("");
242
+ const [error, setError] = useState(null);
243
+ const [drawing, setDrawing] = useState(null);
244
+ const connection = useRef(null);
245
+ const connectionDone = useRef(false);
246
+ const reconnecting = useRef(null);
247
+ const reconnectDuplicate = useRef(false);
248
+ const [reconnectOriginal, setReconnectOriginal] = useState(null);
249
+ const duplicate = useRef(null);
250
+ const [duplicatePreview, setDuplicatePreview] = useState(null);
251
+ const cancelledNodeDrag = useRef(false);
252
+ // Position previews belong to the canvas, not the persistent document. A drag
253
+ // commits once, avoiding whole-document edits/validation on every pointer move.
254
+ const nodeDrag = useRef(null);
255
+ const [positionRevision, setPositionRevision] = useState(0);
256
+ const clearNodeDrag = () => {
257
+ nodeDrag.current = null;
258
+ // Force a controlled refresh on cancellation, even though the saved position
259
+ // never changed: React Flow currently holds the transient pointer position.
260
+ setPositionRevision(value => value + 1);
261
+ };
262
+ useEffect(() => {
263
+ if (!snapshot.gesture && nodeDrag.current) {
264
+ cancelledNodeDrag.current = true;
265
+ clearNodeDrag();
266
+ }
267
+ if (!snapshot.gesture && duplicate.current) {
268
+ cancelledNodeDrag.current = true;
269
+ duplicate.current = null;
270
+ setDuplicatePreview(null);
271
+ }
272
+ }, [snapshot.gesture]);
273
+ const duplicatePresentation = useMemo(() => duplicatePreview
274
+ ? duplicateDragPresentation(graph, duplicatePreview)
275
+ : null, [graph, duplicatePreview]);
276
+ const baseRenderGraph = duplicatePresentation?.graph ?? graph;
277
+ const renderGraph = useMemo(() => props.virtualLinks?.length ? { ...baseRenderGraph, links: [...baseRenderGraph.links, ...props.virtualLinks] } : baseRenderGraph, [baseRenderGraph, props.virtualLinks]);
278
+ const targets = useRef(new Map());
279
+ const coreDiagnostics = useMemo(() => editor.diagnostics(), [editor, snapshot.document]);
280
+ const diagnosticKey = JSON.stringify([coreDiagnostics, props.diagnostics ?? []]);
281
+ const diagnostics = useMemo(() => [...coreDiagnostics, ...(props.diagnostics ?? [])].filter((item) => item.path.length === snapshot.path.length &&
282
+ item.path.every((id, index) => id === snapshot.path[index])), [diagnosticKey, snapshot.path]);
283
+ const registerTarget = useCallback((key, element) => {
284
+ if (element)
285
+ targets.current.set(key, element);
286
+ else
287
+ targets.current.delete(key);
288
+ props.onRenderTarget?.(key, element);
289
+ }, [props.onRenderTarget]);
290
+ useEffect(() => () => {
291
+ for (const key of targets.current.keys())
292
+ props.onRenderTarget?.(key, null);
293
+ targets.current.clear();
294
+ }, [props.onRenderTarget]);
295
+ useEffect(() => {
296
+ setPicker(null);
297
+ setError(null);
298
+ }, [snapshot.path.join("/")]);
299
+ const areaDuplicate = useCallback((id, phase, offset, external = false) => {
300
+ if (phase === 'start') {
301
+ const area = editor.graph.areas.find(area => area.id === id);
302
+ if (!area)
303
+ return;
304
+ cancelledNodeDrag.current = false;
305
+ const fragment = copyFragment(editor.graph, [], [id]);
306
+ duplicate.current = { namespace: createId('preview'), fragment, nodeId: '', origin: area.position, positions: new Map(fragment.nodes.map(node => [node.id, node.position])), areaPositions: new Map(fragment.areas.map(area => [area.id, area.position])), external };
307
+ setDuplicatePreview(duplicate.current);
308
+ return;
309
+ }
310
+ const current = duplicate.current;
311
+ if (!current)
312
+ return;
313
+ if (phase === 'move') {
314
+ duplicate.current = { ...current,
315
+ positions: new Map(current.fragment.nodes.map(node => [node.id, { x: node.position.x + offset.x, y: node.position.y + offset.y }])),
316
+ areaPositions: new Map(current.fragment.areas.map(area => [area.id, { x: area.position.x + offset.x, y: area.position.y + offset.y }])),
317
+ };
318
+ setDuplicatePreview(duplicate.current);
319
+ return;
320
+ }
321
+ duplicate.current = null;
322
+ setDuplicatePreview(null);
323
+ if (phase === 'cancel')
324
+ editor.cancelGesture();
325
+ else {
326
+ editor.paste(current.fragment, offset, current.external);
327
+ editor.commitGesture();
328
+ }
329
+ }, [editor]);
330
+ const context = useMemo(() => ({
331
+ editor,
332
+ views,
333
+ nodeKinds: props.nodeKinds,
334
+ changeNodeKind: props.onChangeNodeKind,
335
+ features,
336
+ diagnostics,
337
+ zoom,
338
+ connecting,
339
+ instanceId,
340
+ areaDuplicate,
341
+ registerTarget,
342
+ linkOverlay,
343
+ }), [
344
+ editor,
345
+ views,
346
+ features,
347
+ diagnostics,
348
+ zoom,
349
+ connecting,
350
+ instanceId,
351
+ registerTarget,
352
+ linkOverlay,
353
+ areaDuplicate,
354
+ props.nodeKinds,
355
+ props.onChangeNodeKind,
356
+ ]);
357
+ const attempt = useCallback((action) => {
358
+ try {
359
+ action();
360
+ setError(null);
361
+ }
362
+ catch (cause) {
363
+ setError(cause instanceof Error ? cause.message : String(cause));
364
+ }
365
+ }, []);
366
+ const collapsed = useMemo(() => {
367
+ const nodes = new Map(), projected = new Set(), hiddenAreas = new Set();
368
+ if (features.areas)
369
+ for (const area of renderGraph.areas.filter((area) => area.collapsed)) {
370
+ const members = areaMembers(renderGraph, area.id);
371
+ for (const id of members.nodeIds) {
372
+ const node = renderGraph.nodes.find((node) => node.id === id);
373
+ if (node &&
374
+ (area.controlHeight ?? 0) > 0 &&
375
+ node.position.y >= area.position.y + 34 &&
376
+ node.position.y < area.position.y + 34 + (area.controlHeight ?? 0))
377
+ projected.add(id);
378
+ else
379
+ nodes.set(id, area);
380
+ }
381
+ for (const id of members.areaIds)
382
+ hiddenAreas.add(id);
383
+ }
384
+ return { nodes, projected, hiddenAreas };
385
+ }, [renderGraph, features.areas]);
386
+ const modelNodes = useMemo(() => [
387
+ ...(features.areas
388
+ ? renderGraph.areas.map((area) => ({
389
+ id: areaFlowId(area.id),
390
+ type: "spagbolArea",
391
+ position: area.position,
392
+ selected: snapshot.selection.areaIds.includes(area.id),
393
+ hidden: collapsed.hiddenAreas.has(area.id),
394
+ draggable: false,
395
+ selectable: false,
396
+ connectable: false,
397
+ deletable: false,
398
+ zIndex: -1,
399
+ data: { area, stationaryOriginal: duplicatePresentation?.originalAreas.has(area.id) },
400
+ measured: measuredSizes.current.get(areaFlowId(area.id)),
401
+ style: {
402
+ width: area.size.width,
403
+ height: area.collapsed
404
+ ? 34 + (area.controlHeight ?? 0)
405
+ : area.size.height,
406
+ },
407
+ }))
408
+ : []),
409
+ ...renderGraph.nodes.map((node) => ({
410
+ id: nodeFlowId(node.id),
411
+ type: "spagbolNode",
412
+ position: nodeDrag.current?.get(node.id) ?? node.position,
413
+ selected: snapshot.selection.nodeIds.includes(node.id),
414
+ hidden: collapsed.nodes.has(node.id),
415
+ draggable: editor.editing && views[node.kind]?.draggable !== false &&
416
+ !collapsed.projected.has(node.id) &&
417
+ !duplicatePresentation?.originalNodes.has(node.id),
418
+ selectable: editor.editing && views[node.kind]?.selectable !== false &&
419
+ !collapsed.projected.has(node.id) &&
420
+ !duplicatePresentation?.originalNodes.has(node.id),
421
+ connectable: editor.editing &&
422
+ !collapsed.projected.has(node.id) &&
423
+ !duplicatePresentation?.originalNodes.has(node.id),
424
+ focusable: !duplicatePresentation?.originalNodes.has(node.id),
425
+ deletable: false,
426
+ dragHandle: ".spagbol-canvas-drag-handle",
427
+ data: {
428
+ positionRevision,
429
+ node: duplicatePresentation?.originalNodes.get(node.id) ?? node,
430
+ projected: collapsed.projected.has(node.id),
431
+ stationaryOriginal: duplicatePresentation?.originalNodes.has(node.id),
432
+ },
433
+ measured: measuredSizes.current.get(nodeFlowId(node.id)) ??
434
+ (duplicatePresentation?.originalNodes.has(node.id)
435
+ ? measuredSizes.current.get(nodeFlowId(duplicatePresentation.originalNodes.get(node.id).id))
436
+ : undefined),
437
+ className: duplicatePresentation?.previewNodeIds.has(node.id)
438
+ ? "spagbol-canvas-duplicate-preview"
439
+ : undefined,
440
+ style: {
441
+ width: views[node.kind]?.autoWidth && !node.size?.width ? "max-content" : (node.size?.width ?? Math.max(220, (groupPanelLayout(node)?.size.width ?? 0) + 2)) * (node.scale ?? 1),
442
+ ...(node.size?.height ? { height: node.size.height * (node.scale ?? 1) } : {}),
443
+ },
444
+ zIndex: connecting && revealedNodeId === node.id ? 5 : snapshot.selection.nodeIds.includes(node.id) ? 3 : 1,
445
+ })),
446
+ ], [
447
+ renderGraph,
448
+ positionRevision,
449
+ duplicatePresentation,
450
+ snapshot.selection,
451
+ snapshot.mode,
452
+ editor,
453
+ features.areas,
454
+ collapsed,
455
+ measurementRevision,
456
+ connecting,
457
+ revealedNodeId,
458
+ ]);
459
+ // React Flow publishes handle measurements. Only measured geometry participates
460
+ // in anchor derivation, so updating invisible anchors cannot form a render loop.
461
+ const measurementKey = flowNodes
462
+ .filter((node) => node.id.startsWith("node:") || node.id.startsWith("area:"))
463
+ .map((node) => {
464
+ const internal = flow.getInternalNode(node.id);
465
+ return JSON.stringify([
466
+ node.id,
467
+ node.position,
468
+ node.measured,
469
+ internal?.internals.handleBounds,
470
+ ]);
471
+ })
472
+ .join("|");
473
+ const panExtent = useMemo(() => {
474
+ if (props.panBounds === false)
475
+ return infiniteCanvasExtent;
476
+ // Use saved content, not temporary duplication nodes or invisible link anchors.
477
+ const items = graph.nodes.map((node) => {
478
+ const internal = flow.getInternalNode(nodeFlowId(node.id));
479
+ return {
480
+ position: node.position,
481
+ hidden: collapsed.nodes.has(node.id),
482
+ size: {
483
+ width: internal?.measured?.width ?? node.size?.width ?? 220,
484
+ height: internal?.measured?.height ?? node.size?.height ?? 96,
485
+ },
486
+ };
487
+ });
488
+ if (features.areas)
489
+ items.push(...graph.areas.map((area) => ({
490
+ position: area.position,
491
+ hidden: collapsed.hiddenAreas.has(area.id),
492
+ size: {
493
+ width: area.size.width,
494
+ height: area.collapsed
495
+ ? 34 + (area.controlHeight ?? 0)
496
+ : area.size.height,
497
+ },
498
+ })));
499
+ return translateExtentForVisibleContent(items, settledViewport, editorSize, props.panBounds?.emptyScreenRatio ?? 0.7);
500
+ }, [
501
+ graph,
502
+ features.areas,
503
+ collapsed,
504
+ flow,
505
+ measurementKey,
506
+ measurementRevision,
507
+ settledViewport.zoom,
508
+ editorSize,
509
+ props.panBounds,
510
+ ]);
511
+ useEffect(() => {
512
+ if (props.panBounds === false ||
513
+ !flow.viewportInitialized ||
514
+ !nodesInitialized ||
515
+ viewportMoving.current ||
516
+ snapshot.gesture)
517
+ return;
518
+ const current = flow.getViewport();
519
+ const clamped = clampViewportToTranslateExtent(current, panExtent, editorSize);
520
+ if (Math.abs(current.x - clamped.x) < 0.0001 &&
521
+ Math.abs(current.y - clamped.y) < 0.0001 &&
522
+ current.zoom === clamped.zoom)
523
+ return;
524
+ setSettledViewport((previous) => previous.x === clamped.x &&
525
+ previous.y === clamped.y &&
526
+ previous.zoom === clamped.zoom
527
+ ? previous
528
+ : clamped);
529
+ void flow.setViewport(clamped);
530
+ }, [
531
+ panExtent,
532
+ editorSize,
533
+ flow,
534
+ settledViewport,
535
+ nodesInitialized,
536
+ snapshot.gesture,
537
+ props.panBounds,
538
+ ]);
539
+ const anchors = useMemo(() => {
540
+ if (!features.linkProperties || snapshot.mode !== "edit")
541
+ return [];
542
+ function endpoint(point, direction) {
543
+ const area = collapsed.nodes.get(point.nodeId);
544
+ if (area)
545
+ return {
546
+ x: area.position.x + (direction === "output" ? area.size.width : 0),
547
+ y: area.position.y + 17,
548
+ };
549
+ const internal = flow.getInternalNode(nodeFlowId(point.nodeId));
550
+ const handle = internal?.internals.handleBounds?.[direction === "output" ? "source" : "target"]?.find((handle) => handle.id ===
551
+ (direction === "output"
552
+ ? sourceHandle(point.portId)
553
+ : targetHandle(point.portId)));
554
+ if (internal && handle)
555
+ return {
556
+ x: internal.internals.positionAbsolute.x + handle.x + handle.width / 2,
557
+ y: internal.internals.positionAbsolute.y +
558
+ handle.y +
559
+ handle.height / 2,
560
+ };
561
+ const node = renderGraph.nodes.find((node) => node.id === point.nodeId);
562
+ return {
563
+ x: (node?.position.x ?? 0) +
564
+ (direction === "output" ? (node?.size?.width ?? 220) : 0),
565
+ y: (node?.position.y ?? 0) + 56,
566
+ };
567
+ }
568
+ const cache = new Map();
569
+ function midpoint(link, visited = new Set()) {
570
+ const cached = cache.get(link.id);
571
+ if (cached)
572
+ return cached;
573
+ if (visited.has(link.id))
574
+ return { x: 0, y: 0 };
575
+ const next = new Set([...visited, link.id]);
576
+ // Keep the target reference narrowed across callback boundaries.
577
+ const reference = link.target.type === "link" ? link.target.linkId : undefined;
578
+ const parent = reference
579
+ ? renderGraph.links.find((candidate) => candidate.id === reference)
580
+ : undefined;
581
+ const destination = link.target.type === "port"
582
+ ? endpoint(link.target, "input")
583
+ : parent
584
+ ? midpoint(parent, next)
585
+ : { x: 0, y: 0 };
586
+ const [, x, y] = linkPath(endpoint(link.source, "output"), destination, linkPresentation[duplicatePresentation?.previewLinks.get(link.id) ?? link.id]?.feedback, link.target.type === "port" &&
587
+ link.source.nodeId === link.target.nodeId);
588
+ const result = { x, y };
589
+ cache.set(link.id, result);
590
+ return result;
591
+ }
592
+ const targeted = new Set(renderGraph.links.flatMap(link => link.target.type === 'link' ? [link.target.linkId] : []));
593
+ return renderGraph.links.filter(link => connecting || targeted.has(link.id)).map((link) => ({
594
+ id: anchorFlowId(link.id),
595
+ type: "spagbolAnchor",
596
+ position: midpoint(link),
597
+ data: { linkId: link.id },
598
+ measured: { width: 1, height: 1 },
599
+ draggable: false,
600
+ selectable: false,
601
+ deletable: false,
602
+ focusable: false,
603
+ zIndex: 4,
604
+ style: { width: 1, height: 1 },
605
+ }));
606
+ }, [
607
+ renderGraph,
608
+ duplicatePresentation,
609
+ features.linkProperties,
610
+ connecting,
611
+ snapshot.mode,
612
+ collapsed,
613
+ linkPresentation,
614
+ measurementKey,
615
+ flow,
616
+ ]);
617
+ const nodePresentations = useRef([]);
618
+ const displayNodes = useMemo(() => { const result = reuseFlowPresentations(nodePresentations.current, [...modelNodes, ...anchors]); nodePresentations.current = result; return result; }, [modelNodes, anchors]);
619
+ const graphLinks = useMemo(() => snapshot.mode === "controls"
620
+ ? []
621
+ : renderGraph.links.flatMap((link) => {
622
+ if (link.target.type === "link" && !features.linkProperties)
623
+ return [];
624
+ const sourceArea = collapsed.nodes.get(link.source.nodeId);
625
+ const targetArea = link.target.type === "port"
626
+ ? collapsed.nodes.get(link.target.nodeId)
627
+ : undefined;
628
+ if (sourceArea && sourceArea.id === targetArea?.id)
629
+ return [];
630
+ const sourceNode = renderGraph.nodes.find((node) => node.id === link.source.nodeId);
631
+ const targetNodeId = link.target.type === "port" ? link.target.nodeId : undefined;
632
+ const targetNode = renderGraph.nodes.find((node) => node.id === targetNodeId);
633
+ const preview = duplicatePresentation?.previewLinks.has(link.id) ?? false;
634
+ const presentation = props.virtualLinks?.some(item => item.id === link.id) ? { virtual: true } :
635
+ linkPresentation[duplicatePresentation?.previewLinks.get(link.id) ?? link.id];
636
+ const related = snapshot.selection.nodeIds.includes(link.source.nodeId) ||
637
+ (!!targetNodeId &&
638
+ snapshot.selection.nodeIds.includes(targetNodeId));
639
+ const selected = !duplicatePreview && snapshot.selection.linkIds.includes(link.id);
640
+ return [
641
+ {
642
+ id: link.id,
643
+ type: "spagbolLink",
644
+ source: sourceArea
645
+ ? areaFlowId(sourceArea.id)
646
+ : nodeFlowId(link.source.nodeId),
647
+ sourceHandle: sourceArea
648
+ ? "collapsed:out"
649
+ : sourceHandle(link.source.portId),
650
+ target: targetArea
651
+ ? areaFlowId(targetArea.id)
652
+ : link.target.type === "port"
653
+ ? nodeFlowId(link.target.nodeId)
654
+ : anchorFlowId(link.target.linkId),
655
+ targetHandle: targetArea
656
+ ? "collapsed:in"
657
+ : link.target.type === "port"
658
+ ? targetHandle(link.target.portId)
659
+ : `property:${link.target.property}`,
660
+ selected,
661
+ reconnectable: selected &&
662
+ editor.editing &&
663
+ !presentation?.virtual &&
664
+ !sourceArea &&
665
+ !targetArea,
666
+ selectable: editor.editing && !presentation?.virtual && !duplicatePreview,
667
+ deletable: false,
668
+ zIndex: selected ? 10 : 0,
669
+ data: {
670
+ link,
671
+ preview,
672
+ ...presentation,
673
+ emphasized: related || preview,
674
+ dimmed: !duplicatePreview &&
675
+ (snapshot.selection.nodeIds.length > 0 ||
676
+ snapshot.selection.linkIds.length > 0) &&
677
+ !selected &&
678
+ !related,
679
+ disabled: link.enabled === false ||
680
+ sourceNode?.enabled === false ||
681
+ targetNode?.enabled === false,
682
+ },
683
+ },
684
+ ];
685
+ }), [
686
+ renderGraph,
687
+ duplicatePresentation,
688
+ duplicatePreview,
689
+ snapshot.mode,
690
+ snapshot.selection,
691
+ features.linkProperties,
692
+ collapsed,
693
+ linkPresentation,
694
+ editor,
695
+ ]);
696
+ const rawDisplayLinks = useMemo(() => reconnectOriginal && snapshot.mode === "edit"
697
+ ? [...graphLinks, reconnectOriginal]
698
+ : graphLinks, [graphLinks, reconnectOriginal, snapshot.mode]);
699
+ const linkPresentations = useRef([]);
700
+ const displayLinks = useMemo(() => {
701
+ const result = reuseFlowPresentations(linkPresentations.current, rawDisplayLinks);
702
+ linkPresentations.current = result;
703
+ return result;
704
+ }, [rawDisplayLinks]);
705
+ function modelConnection(value) {
706
+ const source = parseHandle(value.sourceHandle), target = parseHandle(value.targetHandle);
707
+ if (!source ||
708
+ source.direction !== "output" ||
709
+ !value.source.startsWith("node:"))
710
+ return;
711
+ if (value.target.startsWith("anchor:") &&
712
+ value.targetHandle?.startsWith("property:"))
713
+ return {
714
+ source: { nodeId: value.source.slice(5), portId: source.id },
715
+ target: {
716
+ type: "link",
717
+ linkId: value.target.slice(7),
718
+ property: value.targetHandle.slice(9),
719
+ },
720
+ };
721
+ if (!target ||
722
+ target.direction !== "input" ||
723
+ !value.target.startsWith("node:"))
724
+ return;
725
+ return {
726
+ source: { nodeId: value.source.slice(5), portId: source.id },
727
+ target: {
728
+ type: "port",
729
+ nodeId: value.target.slice(5),
730
+ portId: target.id,
731
+ },
732
+ };
733
+ }
734
+ function onNodesChange(changes) {
735
+ const remeasured = rememberMeasurements(measuredSizes.current, changes);
736
+ if (remeasured)
737
+ setMeasurementRevision((value) => value + 1);
738
+ const selected = new Set(editor.getSnapshot().selection.nodeIds);
739
+ let selectionChanged = false;
740
+ for (const change of changes)
741
+ if (change.type === "select" &&
742
+ change.id.startsWith("node:") &&
743
+ graph.nodes.some((node) => nodeFlowId(node.id) === change.id)) {
744
+ const id = change.id.slice(5);
745
+ if (change.selected)
746
+ selected.add(id);
747
+ else
748
+ selected.delete(id);
749
+ selectionChanged = true;
750
+ }
751
+ if (selectionChanged)
752
+ editor.select({
753
+ nodeIds: [...selected],
754
+ linkIds: editor.getSnapshot().selection.linkIds,
755
+ });
756
+ const positions = changes.filter((change) => change.type === "position" &&
757
+ change.position &&
758
+ change.id.startsWith("node:"));
759
+ if (positions.length && duplicate.current) {
760
+ const next = {
761
+ ...duplicate.current,
762
+ positions: new Map(duplicate.current.positions),
763
+ };
764
+ let changed = false;
765
+ for (const change of positions)
766
+ if (change.type === "position" &&
767
+ change.position &&
768
+ next.positions.has(change.id.slice(5))) {
769
+ const previous = next.positions.get(change.id.slice(5));
770
+ if (previous?.x !== change.position.x ||
771
+ previous?.y !== change.position.y) {
772
+ next.positions.set(change.id.slice(5), { ...change.position });
773
+ changed = true;
774
+ }
775
+ }
776
+ if (!changed)
777
+ return;
778
+ duplicate.current = next;
779
+ setDuplicatePreview(next);
780
+ return;
781
+ }
782
+ if (cancelledNodeDrag.current)
783
+ return;
784
+ if (positions.length && nodeDrag.current) {
785
+ const next = previewNodePositions(nodeDrag.current, positions);
786
+ if (next !== nodeDrag.current)
787
+ nodeDrag.current = next;
788
+ return;
789
+ }
790
+ if (positions.length)
791
+ editor.edit("Move nodes", "layout", (graph) => {
792
+ for (const change of positions)
793
+ if (change.type === "position" && change.position) {
794
+ const node = graph.nodes.find((node) => nodeFlowId(node.id) === change.id);
795
+ if (node)
796
+ node.position = { ...change.position };
797
+ }
798
+ });
799
+ }
800
+ function onEdgesChange(changes) {
801
+ const selected = new Set(editor.getSnapshot().selection.linkIds);
802
+ let changed = false;
803
+ for (const change of changes)
804
+ if (change.type === "select") {
805
+ if (change.selected)
806
+ selected.add(change.id);
807
+ else
808
+ selected.delete(change.id);
809
+ changed = true;
810
+ }
811
+ if (changed)
812
+ editor.select({
813
+ nodeIds: editor.getSnapshot().selection.nodeIds,
814
+ linkIds: [...selected],
815
+ });
816
+ }
817
+ function openPicker(client, extra = {}) {
818
+ if (!editor.editing)
819
+ return;
820
+ const bounds = root.current?.getBoundingClientRect();
821
+ setSearch("");
822
+ setPicker({
823
+ point: flow.screenToFlowPosition(client),
824
+ screen: {
825
+ x: Math.min(client.x - (bounds?.left ?? 0), Math.max(8, (bounds?.width ?? 400) - 260)),
826
+ y: Math.min(client.y - (bounds?.top ?? 0), Math.max(8, (bounds?.height ?? 500) - 320)),
827
+ },
828
+ ...extra,
829
+ });
830
+ }
831
+ function chooseNode(kind) {
832
+ if (!picker)
833
+ return;
834
+ attempt(() => {
835
+ if (kind === 'spagbol.area') {
836
+ editor.addArea(picker.point);
837
+ setPicker(null);
838
+ return;
839
+ }
840
+ const definition = editor.nodes.get(kind);
841
+ if (picker.linkId) {
842
+ const prototype = editor.nodes.create(kind, picker.point);
843
+ const ports = portsFor(prototype, editor.nodes), input = ports.find((port) => port.direction === "input" && port.connectable !== false), output = ports.find((port) => port.direction === "output" && port.connectable !== false);
844
+ if (!input || !output)
845
+ throw new Error("Choose a node with an input and an output to insert it into a link.");
846
+ editor.insertNode(picker.linkId, kind, picker.point, input.id, output.id);
847
+ }
848
+ else {
849
+ editor.beginGesture(picker.origin ? "Create connected node" : "Create node");
850
+ try {
851
+ const id = editor.addNode(kind, picker.point);
852
+ if (picker.origin) {
853
+ const node = editor.graph.nodes.find((node) => node.id === id);
854
+ const opposite = picker.origin.direction === "output" ? "input" : "output";
855
+ const port = definition
856
+ .ports(node)
857
+ .find((port) => port.direction === opposite && port.connectable !== false);
858
+ if (!port)
859
+ throw new Error(`This node has no connectable ${opposite}.`);
860
+ if (opposite === "input")
861
+ editor.connect({ nodeId: picker.origin.nodeId, portId: picker.origin.portId }, { type: "port", nodeId: id, portId: port.id }, activeMode);
862
+ else
863
+ editor.connect({ nodeId: id, portId: port.id }, {
864
+ type: "port",
865
+ nodeId: picker.origin.nodeId,
866
+ portId: picker.origin.portId,
867
+ }, activeMode);
868
+ }
869
+ editor.commitGesture();
870
+ }
871
+ catch (cause) {
872
+ editor.cancelGesture();
873
+ throw cause;
874
+ }
875
+ }
876
+ setPicker(null);
877
+ });
878
+ }
879
+ function linkAt(point, source, mode, replacingId) {
880
+ if (!features.linkProperties ||
881
+ !(editor.policy.linkProperties ?? []).includes("weight"))
882
+ return;
883
+ let best;
884
+ for (const path of root.current?.querySelectorAll("[data-spagbol-link]") ?? []) {
885
+ const id = path.dataset.spagbolLink;
886
+ if (!id ||
887
+ editor.canConnect(source, { type: "link", linkId: id, property: "weight" }, mode, replacingId))
888
+ continue;
889
+ const matrix = path.getScreenCTM();
890
+ if (!matrix)
891
+ continue;
892
+ const local = new DOMPoint(point.x, point.y).matrixTransform(matrix.inverse());
893
+ const length = path.getTotalLength();
894
+ let distance = Infinity;
895
+ for (let i = 0; i <= 48; i++) {
896
+ const p = path.getPointAtLength((length * i) / 48);
897
+ distance = Math.min(distance, Math.hypot(p.x - local.x, p.y - local.y) * zoom);
898
+ }
899
+ if (distance < 14 && (!best || distance < best.distance))
900
+ best = { id, distance };
901
+ }
902
+ return best?.id;
903
+ }
904
+ async function paste() {
905
+ let fragment;
906
+ try {
907
+ const text = await navigator.clipboard?.readText();
908
+ if (text)
909
+ fragment = readFragment(text);
910
+ }
911
+ catch {
912
+ /* Fall back to this controller's clipboard. */
913
+ }
914
+ attempt(() => editor.paste(fragment));
915
+ }
916
+ function keyDown(event) {
917
+ const target = event.target;
918
+ if (target.closest('input,textarea,select,[contenteditable="true"],[role="spinbutton"]'))
919
+ return;
920
+ const command = event.metaKey || event.ctrlKey, key = event.key.toLowerCase();
921
+ if (key === "escape") {
922
+ if (duplicate.current || nodeDrag.current)
923
+ cancelledNodeDrag.current = true;
924
+ if (nodeDrag.current)
925
+ clearNodeDrag();
926
+ duplicate.current = null;
927
+ setDuplicatePreview(null);
928
+ editor.cancelGesture();
929
+ flowStore.getState().cancelConnection();
930
+ setPicker(null);
931
+ setDrawing(null);
932
+ setConnecting(false);
933
+ connection.current = null;
934
+ connectionDone.current = true;
935
+ setReconnectOriginal(null);
936
+ return;
937
+ }
938
+ if (command && key === "z") {
939
+ event.preventDefault();
940
+ event.shiftKey ? editor.redo() : editor.undo();
941
+ return;
942
+ }
943
+ if (command && key === "y") {
944
+ event.preventDefault();
945
+ editor.redo();
946
+ return;
947
+ }
948
+ if (!editor.editing)
949
+ return;
950
+ if (command && key === "c") {
951
+ event.preventDefault();
952
+ const fragment = editor.copy();
953
+ void navigator.clipboard
954
+ ?.writeText(JSON.stringify(fragment))
955
+ .catch(() => undefined);
956
+ return;
957
+ }
958
+ if (command && key === "v") {
959
+ event.preventDefault();
960
+ void paste();
961
+ return;
962
+ }
963
+ if (command && key === "d") {
964
+ event.preventDefault();
965
+ attempt(() => editor.duplicate());
966
+ return;
967
+ }
968
+ if (command && key === "a") {
969
+ event.preventDefault();
970
+ editor.select({ nodeIds: graph.nodes.filter(node => views[node.kind]?.selectable !== false).map((node) => node.id) });
971
+ return;
972
+ }
973
+ if (command && key === "0") {
974
+ event.preventDefault();
975
+ void flow.zoomTo(1);
976
+ return;
977
+ }
978
+ if (key === "delete" || key === "backspace") {
979
+ event.preventDefault();
980
+ editor.deleteSelection(command);
981
+ return;
982
+ }
983
+ if (!command && key === "x") {
984
+ editor.edit("Toggle enabled", "values", (graph) => {
985
+ const nodes = graph.nodes.filter((node) => snapshot.selection.nodeIds.includes(node.id));
986
+ if (nodes.length) {
987
+ const enabled = nodes.every((node) => node.enabled === false);
988
+ for (const node of nodes)
989
+ node.enabled = enabled;
990
+ }
991
+ else {
992
+ const links = graph.links.filter((link) => snapshot.selection.linkIds.includes(link.id));
993
+ const enabled = links.every((link) => link.enabled === false);
994
+ for (const link of links)
995
+ link.enabled = enabled;
996
+ }
997
+ });
998
+ return;
999
+ }
1000
+ const mode = editor.modes
1001
+ .list()
1002
+ .find((mode) => mode.shortcut === key &&
1003
+ (!editor.policy.modes || editor.policy.modes.includes(mode.id)));
1004
+ if (mode && !command) {
1005
+ setActiveMode(mode.id);
1006
+ if (!connecting)
1007
+ editor.edit("Change link mode", "values", (graph) => {
1008
+ for (const link of graph.links)
1009
+ if (snapshot.selection.linkIds.includes(link.id))
1010
+ link.mode = mode.id;
1011
+ });
1012
+ }
1013
+ }
1014
+ function pointFromEvent(event) {
1015
+ if ("clientX" in event)
1016
+ return { x: event.clientX, y: event.clientY };
1017
+ const touch = event.changedTouches[0];
1018
+ return touch ? { x: touch.clientX, y: touch.clientY } : undefined;
1019
+ }
1020
+ const availableNodes = [...editor.nodes.list().filter(definition => !props.nodeKinds || props.nodeKinds.includes(definition.kind)), ...(features.areas && !picker?.origin && !picker?.linkId ? [{ kind: 'spagbol.area', label: 'Area', createData: () => ({}), ports: () => [] }] : [])]
1021
+ .filter(definition => snapshot.path.length > 0 || ![spagbolGroupKinds.inputs, spagbolGroupKinds.outputs].includes(definition.kind))
1022
+ .filter((definition) => `${definition.label} ${definition.category ?? ""} ${definition.keywords?.join(" ") ?? ""}`
1023
+ .toLowerCase()
1024
+ .includes(search.toLowerCase()));
1025
+ return (_jsx(GraphContext.Provider, { value: context, children: _jsxs("div", { ref: root, className: `spagbol-canvas ${props.className ?? ""}`, style: {
1026
+ ...props.style,
1027
+ "--spagbol-title-scale": zoom < 0.3 ? 1.75 : zoom < 0.5 ? 1.3 : 1,
1028
+ "--spagbol-canvas-height": `${editorSize.height}px`,
1029
+ }, tabIndex: 0, "aria-label": props.ariaLabel ?? "Graph editor", onKeyDown: keyDown, onDoubleClick: (event) => {
1030
+ if (event.target.classList.contains("react-flow__pane")) {
1031
+ event.preventDefault();
1032
+ openPicker({ x: event.clientX, y: event.clientY });
1033
+ }
1034
+ }, onPointerDownCapture: (event) => {
1035
+ const pane = event.target.classList.contains("react-flow__pane");
1036
+ if (pane)
1037
+ root.current?.focus({ preventScroll: true });
1038
+ if (pane &&
1039
+ features.areas &&
1040
+ editor.editing &&
1041
+ (event.metaKey || event.ctrlKey) &&
1042
+ event.button === 0) {
1043
+ event.preventDefault();
1044
+ event.stopPropagation();
1045
+ const point = flow.screenToFlowPosition({
1046
+ x: event.clientX,
1047
+ y: event.clientY,
1048
+ });
1049
+ setDrawing({ start: point, end: point, pointer: event.pointerId });
1050
+ event.currentTarget.setPointerCapture(event.pointerId);
1051
+ }
1052
+ }, onPointerMove: (event) => {
1053
+ if (drawing?.pointer === event.pointerId)
1054
+ setDrawing({
1055
+ ...drawing,
1056
+ end: flow.screenToFlowPosition({
1057
+ x: event.clientX,
1058
+ y: event.clientY,
1059
+ }),
1060
+ });
1061
+ }, onPointerUp: (event) => {
1062
+ if (drawing?.pointer !== event.pointerId)
1063
+ return;
1064
+ const position = {
1065
+ x: Math.min(drawing.start.x, drawing.end.x),
1066
+ y: Math.min(drawing.start.y, drawing.end.y),
1067
+ }, size = {
1068
+ width: Math.abs(drawing.start.x - drawing.end.x),
1069
+ height: Math.abs(drawing.start.y - drawing.end.y),
1070
+ };
1071
+ if (size.width >= 40 && size.height >= 40)
1072
+ editor.addArea(position, size);
1073
+ setDrawing(null);
1074
+ if (event.currentTarget.hasPointerCapture(event.pointerId))
1075
+ event.currentTarget.releasePointerCapture(event.pointerId);
1076
+ }, onPointerCancel: () => {
1077
+ if (duplicate.current || nodeDrag.current)
1078
+ cancelledNodeDrag.current = true;
1079
+ if (nodeDrag.current)
1080
+ clearNodeDrag();
1081
+ duplicate.current = null;
1082
+ setDuplicatePreview(null);
1083
+ setDrawing(null);
1084
+ editor.cancelGesture();
1085
+ }, children: [props.background && (_jsx("div", { className: "spagbol-canvas-background", children: props.background })), _jsx(SpagbolCanvasFlow, { nodes: displayNodes, onlyRenderVisibleElements: true, edges: displayLinks, nodeTypes: nodeTypes, edgeTypes: edgeTypes, onNodesChange: onNodesChange, onEdgesChange: onEdgesChange, onNodeMouseEnter: (_, node) => { if (connecting && node.data.node?.compact && !node.data.stationaryOriginal)
1086
+ setRevealedNodeId(node.data.node.id); }, onNodeMouseLeave: (_, node) => setRevealedNodeId(id => id === node.data.node?.id ? null : id), onNodeDoubleClick: (event, flowNode) => {
1087
+ const node = flowNode.data.node;
1088
+ if (node?.graph && features.nestedGraphs && !event.target.closest('.spagbol-node-frame-header')) {
1089
+ event.preventDefault();
1090
+ editor.enter(node.id);
1091
+ }
1092
+ }, onPaneClick: () => {
1093
+ editor.select({});
1094
+ setPicker(null);
1095
+ }, onNodeDragStart: (event, node) => {
1096
+ if (!node.data.node)
1097
+ return;
1098
+ cancelledNodeDrag.current = false;
1099
+ editor.beginGesture(event.altKey ? "Duplicate nodes" : "Move nodes");
1100
+ if (!event.altKey)
1101
+ nodeDrag.current = new Map();
1102
+ if (event.altKey) {
1103
+ const selection = editor.getSnapshot().selection;
1104
+ const ids = selection.nodeIds.includes(node.data.node.id)
1105
+ ? selection.nodeIds
1106
+ : [node.data.node.id];
1107
+ duplicate.current = {
1108
+ namespace: createId("duplicate-preview"),
1109
+ fragment: copyFragment(graph, ids),
1110
+ origin: { ...node.position },
1111
+ nodeId: node.data.node.id,
1112
+ positions: new Map(graph.nodes
1113
+ .filter((node) => ids.includes(node.id))
1114
+ .map((node) => [node.id, { ...node.position }])),
1115
+ external: event.ctrlKey || event.metaKey || event.shiftKey,
1116
+ };
1117
+ setDuplicatePreview(duplicate.current);
1118
+ }
1119
+ }, onNodeDragStop: (_event, node) => {
1120
+ const positions = nodeDrag.current;
1121
+ if (positions)
1122
+ clearNodeDrag();
1123
+ const current = duplicate.current;
1124
+ duplicate.current = null;
1125
+ setDuplicatePreview(null);
1126
+ if (cancelledNodeDrag.current) {
1127
+ cancelledNodeDrag.current = false;
1128
+ editor.cancelGesture();
1129
+ editor.select(editor.getSnapshot().selection);
1130
+ return;
1131
+ }
1132
+ if (current) {
1133
+ const position = current.positions.get(current.nodeId) ?? node.position;
1134
+ const delta = {
1135
+ x: position.x - current.origin.x,
1136
+ y: position.y - current.origin.y,
1137
+ };
1138
+ try {
1139
+ editor.paste(current.fragment, delta, current.external);
1140
+ }
1141
+ catch (cause) {
1142
+ editor.cancelGesture();
1143
+ setError(cause instanceof Error ? cause.message : String(cause));
1144
+ return;
1145
+ }
1146
+ }
1147
+ if (positions?.size)
1148
+ editor.edit("Move nodes", "layout", graph => applyNodePositions(graph, positions));
1149
+ editor.commitGesture();
1150
+ }, onConnectStart: (_event, params) => {
1151
+ setRevealedNodeId(params.nodeId?.startsWith("node:") ? params.nodeId.slice(5) : null);
1152
+ connection.current = params;
1153
+ connectionDone.current = false;
1154
+ setConnecting(true);
1155
+ }, onConnect: (value) => {
1156
+ connectionDone.current = true;
1157
+ const next = modelConnection(value);
1158
+ if (next)
1159
+ attempt(() => {
1160
+ editor.connect(next.source, next.target, activeMode);
1161
+ });
1162
+ }, onConnectEnd: (event, state) => {
1163
+ const origin = connection.current;
1164
+ connection.current = null;
1165
+ setConnecting(false);
1166
+ if (connectionDone.current ||
1167
+ reconnecting.current ||
1168
+ !origin ||
1169
+ state.toHandle)
1170
+ return;
1171
+ const point = pointFromEvent(event), port = parseHandle(origin.handleId);
1172
+ if (!point || !port || !origin.nodeId?.startsWith("node:"))
1173
+ return;
1174
+ const source = { nodeId: origin.nodeId.slice(5), portId: port.id };
1175
+ const hit = port.direction === "output"
1176
+ ? linkAt(point, source, activeMode)
1177
+ : undefined;
1178
+ if (hit)
1179
+ attempt(() => {
1180
+ editor.connect(source, { type: "link", linkId: hit, property: "weight" }, activeMode);
1181
+ });
1182
+ else if ("metaKey" in event && (event.metaKey || event.ctrlKey))
1183
+ openPicker(point, {
1184
+ origin: { ...source, direction: port.direction },
1185
+ });
1186
+ }, reconnectRadius: 12, onReconnectStart: (event, edge) => {
1187
+ reconnecting.current = edge.id;
1188
+ reconnectDuplicate.current =
1189
+ event.ctrlKey || event.metaKey || event.altKey;
1190
+ setReconnectOriginal(reconnectDuplicate.current ? stationaryReconnectEdge(edge) : null);
1191
+ connectionDone.current = false;
1192
+ setConnecting(true);
1193
+ }, onReconnect: (edge, value) => {
1194
+ connectionDone.current = true;
1195
+ const next = modelConnection(value);
1196
+ if (next)
1197
+ attempt(() => {
1198
+ editor.reconnect(edge.id, next.source, next.target, reconnectDuplicate.current);
1199
+ });
1200
+ }, onReconnectEnd: (event, edge, handleType, state) => {
1201
+ if (!connectionDone.current &&
1202
+ !state.toHandle &&
1203
+ handleType === "source") {
1204
+ const point = pointFromEvent(event), link = edge.data?.link;
1205
+ if (point && link) {
1206
+ const hit = linkAt(point, link.source, link.mode, edge.id);
1207
+ if (hit)
1208
+ attempt(() => {
1209
+ editor.reconnect(edge.id, link.source, { type: "link", linkId: hit, property: "weight" }, event.ctrlKey || event.metaKey || event.altKey);
1210
+ });
1211
+ }
1212
+ }
1213
+ reconnecting.current = null;
1214
+ setReconnectOriginal(null);
1215
+ setConnecting(false);
1216
+ }, isValidConnection: (value) => {
1217
+ const next = modelConnection(value);
1218
+ const old = reconnecting.current &&
1219
+ graph.links.find((link) => link.id === reconnecting.current);
1220
+ return (!!next &&
1221
+ !editor.canConnect(next.source, next.target, old ? old.mode : activeMode, reconnecting.current ?? undefined));
1222
+ }, onEdgeDoubleClick: (event, edge) => {
1223
+ event.preventDefault();
1224
+ if (edge.data?.virtual)
1225
+ return;
1226
+ openPicker({ x: event.clientX, y: event.clientY }, { linkId: edge.id });
1227
+ }, connectionLineType: ConnectionLineType.Bezier, connectionLineStyle: {
1228
+ stroke: editor.modes.get(activeMode)?.color,
1229
+ strokeWidth: 2,
1230
+ }, defaultViewport: props.defaultViewport, onInit: instance => props.onInit?.(instance), onMoveStart: () => {
1231
+ viewportMoving.current = true;
1232
+ }, onMove: (_, viewport) => setZoom(viewport.zoom), onMoveEnd: (_, viewport) => {
1233
+ viewportMoving.current = false;
1234
+ setSettledViewport(viewport);
1235
+ props.onViewportChange?.(viewport);
1236
+ }, translateExtent: panExtent, fitView: !props.defaultViewport, fitViewOptions: { padding: 0.18 }, minZoom: 0.05, maxZoom: 3, panOnScroll: true, selectionOnDrag: true, selectionMode: SelectionMode.Partial, panOnDrag: [1, 2], zoomOnScroll: false, zoomOnPinch: true, zoomOnDoubleClick: false, deleteKeyCode: null, multiSelectionKeyCode: ["Meta", "Shift"], nodesDraggable: editor.editing, nodesConnectable: editor.editing, elementsSelectable: editor.editing, autoPanOnConnect: true, autoPanOnNodeDrag: true, proOptions: { hideAttribution: true }, children: drawing && (_jsx(ViewportPortal, { children: _jsx("div", { className: "spagbol-canvas-area-draft", style: {
1237
+ transform: `translate(${Math.min(drawing.start.x, drawing.end.x)}px, ${Math.min(drawing.start.y, drawing.end.y)}px)`,
1238
+ width: Math.abs(drawing.start.x - drawing.end.x),
1239
+ height: Math.abs(drawing.start.y - drawing.end.y),
1240
+ } }) })) }), _jsx("div", { ref: setLinkOverlay, className: "spagbol-canvas-link-overlay" }), (props.toolbar ?? true) === true ? (props.controls === false ? null : (_jsx(SpagbolCanvasControls, { ...props.controls }))) : (props.toolbar), picker && (_jsxs("div", { className: "spagbol-canvas-picker nodrag nopan", role: "dialog", "aria-label": "Add node", style: { left: picker.screen.x, top: picker.screen.y }, onPointerDown: (event) => event.stopPropagation(), children: [_jsxs("div", { className: "spagbol-canvas-picker-heading", children: [picker.linkId ? "insert a node" : "add a node", _jsx("button", { "aria-label": "Cancel node creation", onClick: () => setPicker(null), children: "\u00D7" })] }), _jsx("input", { autoFocus: true, "aria-label": "Search node types", placeholder: "Search nodes\u2026", value: search, onChange: (event) => setSearch(event.target.value), onKeyDown: (event) => {
1241
+ event.stopPropagation();
1242
+ if (event.key === "Escape")
1243
+ setPicker(null);
1244
+ if (event.key === "Enter" && availableNodes[0])
1245
+ chooseNode(availableNodes[0].kind);
1246
+ } }), _jsxs("div", { className: "spagbol-canvas-picker-list", children: [availableNodes.map((definition) => (_jsxs("button", { onClick: () => chooseNode(definition.kind), children: [_jsx("span", { children: definition.label }), _jsx("small", { children: definition.category })] }, definition.kind))), !availableNodes.length && _jsx("p", { children: "No matching nodes." })] })] })), error && (_jsxs("div", { className: "spagbol-canvas-error", role: "alert", children: [error, _jsx("button", { "aria-label": "Dismiss error", onClick: () => setError(null), children: "\u00D7" })] })), props.overlay && (_jsx("div", { className: "spagbol-canvas-overlay", children: props.overlay }))] }) }));
1247
+ }
1248
+ //# sourceMappingURL=SpagbolCanvas.js.map