@miadi/stateloom-canvas 0.1.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 +91 -0
- package/dist/StateMachineCanvas.d.ts +103 -0
- package/dist/StateMachineCanvas.js +932 -0
- package/dist/drill.d.ts +32 -0
- package/dist/drill.js +70 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.js +21 -0
- package/dist/styles.css +404 -0
- package/dist/theme.d.ts +61 -0
- package/dist/theme.js +59 -0
- package/package.json +61 -0
|
@@ -0,0 +1,932 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
3
|
+
/**
|
|
4
|
+
* The design surface, as a component anyone can mount.
|
|
5
|
+
*
|
|
6
|
+
* This is the smcraft designer's canvas with its store taken out. Everything
|
|
7
|
+
* it knows arrives as props — the definition, where the boxes sit, which way
|
|
8
|
+
* the view is pointed — and everything it wants arrives back as a callback.
|
|
9
|
+
* Nothing here reaches for a zustand store, a Next.js route, a stylesheet
|
|
10
|
+
* framework, or a socket, which is the whole reason a second application can
|
|
11
|
+
* mount the same board and get the same navigation.
|
|
12
|
+
*
|
|
13
|
+
* What it still owns, because none of it is application state:
|
|
14
|
+
*
|
|
15
|
+
* · the gesture layer — wheel, ⌃wheel, middle-drag, Space+drag, one-finger
|
|
16
|
+
* pan, two-finger pinch, held-press menu — with the pointer bookkeeping
|
|
17
|
+
* that keeps a second finger from being read as a rival drag;
|
|
18
|
+
* · the drawing — edges routed so they leave a box through the gap that is
|
|
19
|
+
* actually there, labels settled so two chips never print through each
|
|
20
|
+
* other, both from `@miadi/stateloom-protocol`;
|
|
21
|
+
* · the enter/exit animation of nodes and edges as a definition changes.
|
|
22
|
+
*
|
|
23
|
+
* Colour is CSS, never an attribute (see theme.ts): a host re-skins the whole
|
|
24
|
+
* board by declaring `--slc-*` variables, and the same component is at home on
|
|
25
|
+
* slate and on warm coal.
|
|
26
|
+
*/
|
|
27
|
+
import { forwardRef, useCallback, useEffect, useId, useImperativeHandle, useMemo, useRef, useState, } from "react";
|
|
28
|
+
import { GLYPH_SIZE, IDENTITY_VIEWPORT, SELF_LOOP_BULGE, VIEWPORT_LIMITS, eventGlyph, fitToBoxes, glyphAt, guardText, panBy, placeLabels, routeEdges, viewportTransform, zoomAt, zoomTo, } from "@miadi/stateloom-protocol";
|
|
29
|
+
import { childStatesAt, definedEvents, livePath } from "./drill.js";
|
|
30
|
+
import { themeStyle } from "./theme.js";
|
|
31
|
+
/** Wheel notches arrive in three units; normalise them to pixels. */
|
|
32
|
+
const WHEEL_LINE_HEIGHT = 16;
|
|
33
|
+
const WHEEL_PAGE_HEIGHT = 400;
|
|
34
|
+
/** How long a finger must rest in place before the press becomes a menu. */
|
|
35
|
+
const LONG_PRESS_MS = 500;
|
|
36
|
+
/**
|
|
37
|
+
* How far a finger may wander and still count as resting. It doubles as the
|
|
38
|
+
* line between a pan and a tap: a fingertip never lands perfectly still, and a
|
|
39
|
+
* one-pixel tremor must not swallow the tap that clears the selection.
|
|
40
|
+
*/
|
|
41
|
+
const TOUCH_SLOP_PX = 8;
|
|
42
|
+
/** Screen-space cuff added around a box so a fingertip (~9mm) can find it. */
|
|
43
|
+
const TOUCH_TARGET_PAD_PX = 10;
|
|
44
|
+
/** Screen-space width of the invisible ribbon that catches a tap on an edge. */
|
|
45
|
+
const TOUCH_EDGE_STROKE_PX = 28;
|
|
46
|
+
const FALLBACK_BOX = { x: 100, y: 100, width: 160, height: 60 };
|
|
47
|
+
function wheelPixels(delta, mode) {
|
|
48
|
+
if (mode === 1)
|
|
49
|
+
return delta * WHEEL_LINE_HEIGHT;
|
|
50
|
+
if (mode === 2)
|
|
51
|
+
return delta * WHEEL_PAGE_HEIGHT;
|
|
52
|
+
return delta;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Space is a pan modifier on the canvas and a plain space bar everywhere else —
|
|
56
|
+
* a name being typed in a panel, or a focused button waiting to be pressed,
|
|
57
|
+
* must never make the board slide.
|
|
58
|
+
*/
|
|
59
|
+
function isTypingTarget(node) {
|
|
60
|
+
const el = node;
|
|
61
|
+
if (!el || typeof el.tagName !== "string")
|
|
62
|
+
return false;
|
|
63
|
+
if (el.isContentEditable)
|
|
64
|
+
return true;
|
|
65
|
+
return ["INPUT", "TEXTAREA", "SELECT", "BUTTON", "OPTION"].includes(el.tagName);
|
|
66
|
+
}
|
|
67
|
+
function isComposite(state) {
|
|
68
|
+
return (state.states?.length ?? 0) > 0 || (state.parallel?.states.length ?? 0) > 0;
|
|
69
|
+
}
|
|
70
|
+
function childCount(state) {
|
|
71
|
+
return (state.states?.length ?? 0) + (state.parallel?.states.length ?? 0);
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* The trigger mark on an event chip: a check for a confirmation, chevrons for
|
|
75
|
+
* an advance, two bars for a pause. Six chips reading `advance_context` are six
|
|
76
|
+
* identical words until something in front of them differs.
|
|
77
|
+
*
|
|
78
|
+
* Drawn from the protocol's glyph data in a 24-unit box, scaled where it
|
|
79
|
+
* stands — the same paths a headless renderer writes, so a picture taken of
|
|
80
|
+
* the board carries the marks the board showed.
|
|
81
|
+
*/
|
|
82
|
+
function TriggerGlyph({ mark, x, y, selected }) {
|
|
83
|
+
return (_jsxs("g", { transform: `translate(${x} ${y}) scale(${GLYPH_SIZE / 24})`, strokeWidth: mark.strokeWidth, className: `slc-glyph${selected ? " slc-glyph--selected" : ""}`, children: [(mark.circles ?? []).map((c, i) => (_jsx("circle", { cx: c.cx, cy: c.cy, r: c.r, className: c.filled ? "slc-glyph-dot" : undefined }, `c${i}`))), mark.paths.map((d, i) => (_jsx("path", { d: d }, `p${i}`)))] }));
|
|
84
|
+
}
|
|
85
|
+
// ─── Component ───────────────────────────────────────────────────────────────
|
|
86
|
+
const NO_SELECTION = { kind: null, id: null };
|
|
87
|
+
export const StateMachineCanvas = forwardRef(function StateMachineCanvas(props, ref) {
|
|
88
|
+
const { definition, positions, path = [], rootLabel, viewport, onViewportChange, selection = NO_SELECTION, activeStates, errorElements, drawMode = "select", drawSource = null, readOnly = false, showBreadcrumb = true, showHud = true, fitKey, onSelect, onClearSelection, onStateMove, onNavigateInto, onNavigateTo, onContextMenu, onCreateTransition, onCancelDraw, onDeleteState, onUndo, onRedo, hudExtras, emptyHint, theme, className, style, svgId, pinchOwner = "canvas", } = props;
|
|
89
|
+
const svgRef = useRef(null);
|
|
90
|
+
const markerId = useId().replace(/:/g, "");
|
|
91
|
+
// Every handler that reads "the viewport right now" reads it here, not from
|
|
92
|
+
// the closure: a wheel event and a pointer move can both land inside the
|
|
93
|
+
// frame that produced the last render, and either one working from a stale
|
|
94
|
+
// transform makes the board jump.
|
|
95
|
+
const viewportRef = useRef(viewport);
|
|
96
|
+
viewportRef.current = viewport;
|
|
97
|
+
const [drag, setDrag] = useState(null);
|
|
98
|
+
// The same truth as `drag`, readable by a handler that may run before the
|
|
99
|
+
// render carrying it — a second finger, or a lift, can arrive inside the
|
|
100
|
+
// frame the press started in, and must still know which pointer owns the box.
|
|
101
|
+
const dragRef = useRef(null);
|
|
102
|
+
const applyDrag = useCallback((next) => {
|
|
103
|
+
dragRef.current = next;
|
|
104
|
+
setDrag(next);
|
|
105
|
+
}, []);
|
|
106
|
+
const [eventPicker, setEventPicker] = useState(null);
|
|
107
|
+
// Navigation. `spaceHeld` / `panning` drive the cursor (they must re-render);
|
|
108
|
+
// the refs carry the same truth into native listeners and pointer handlers
|
|
109
|
+
// that would otherwise close over a stale value.
|
|
110
|
+
const spaceRef = useRef(false);
|
|
111
|
+
const [spaceHeld, setSpaceHeld] = useState(false);
|
|
112
|
+
const panRef = useRef(null);
|
|
113
|
+
const [panning, setPanning] = useState(false);
|
|
114
|
+
// A pan that actually moved must not end as a click that clears the selection.
|
|
115
|
+
const panMovedRef = useRef(false);
|
|
116
|
+
// Who holds each live pointer, keyed by id, so it can be released again. A
|
|
117
|
+
// map rather than a single slot: with two fingers down, one box can be
|
|
118
|
+
// holding the first while the surface holds the second, and releasing the
|
|
119
|
+
// wrong one strands the gesture.
|
|
120
|
+
const capturesRef = useRef(new Map());
|
|
121
|
+
// Touch. Every finger currently on the canvas, in the order it landed — the
|
|
122
|
+
// map is what makes a *second* finger legible as a pinch rather than as a
|
|
123
|
+
// second, competing drag.
|
|
124
|
+
const pointersRef = useRef(new Map());
|
|
125
|
+
const pinchRef = useRef(null);
|
|
126
|
+
const [pinching, setPinching] = useState(false);
|
|
127
|
+
const longPressRef = useRef(null);
|
|
128
|
+
// A press that became a menu must not also read as a click: a host shell
|
|
129
|
+
// hides its menu on any click that reaches it, closing it on the way back up.
|
|
130
|
+
const suppressClickRef = useRef(false);
|
|
131
|
+
// Coarse pointer: hit areas grow for a fingertip, and only then, so a mouse
|
|
132
|
+
// keeps the precision the visual design was drawn for. Resolved in an effect
|
|
133
|
+
// (never during render) so the server's HTML and the first client paint agree.
|
|
134
|
+
const [coarsePointer, setCoarsePointer] = useState(false);
|
|
135
|
+
// While the view is being steered — dragged by a finger, pinched, or panned
|
|
136
|
+
// with the middle button — the board underneath stops answering the pointer,
|
|
137
|
+
// so a box never fights the gesture that is moving the whole world.
|
|
138
|
+
const navigating = panning || pinching;
|
|
139
|
+
const root = definition.state;
|
|
140
|
+
const crumbs = useMemo(() => {
|
|
141
|
+
const live = livePath(root, path);
|
|
142
|
+
return [rootLabel ?? root?.name ?? "Root", ...live];
|
|
143
|
+
}, [root, path, rootLabel]);
|
|
144
|
+
const currentChildren = useMemo(() => (root ? childStatesAt(root, path) : []), [root, path]);
|
|
145
|
+
const currentParent = crumbs[crumbs.length - 1];
|
|
146
|
+
const allEvents = useMemo(() => definedEvents(definition), [definition]);
|
|
147
|
+
const activeSet = useMemo(() => new Set(activeStates ?? []), [activeStates]);
|
|
148
|
+
const errorSet = useMemo(() => new Set(errorElements ?? []), [errorElements]);
|
|
149
|
+
/** Pointer position relative to the canvas element — the space zoom anchors in. */
|
|
150
|
+
const toCanvasPoint = useCallback((clientX, clientY) => {
|
|
151
|
+
const rect = svgRef.current?.getBoundingClientRect();
|
|
152
|
+
return { x: clientX - (rect?.left ?? 0), y: clientY - (rect?.top ?? 0) };
|
|
153
|
+
}, []);
|
|
154
|
+
/** Hand the pointer back to whoever was holding it, and forget the holder. */
|
|
155
|
+
const releaseCapture = useCallback((pointerId) => {
|
|
156
|
+
const held = capturesRef.current.get(pointerId);
|
|
157
|
+
capturesRef.current.delete(pointerId);
|
|
158
|
+
if (held?.hasPointerCapture?.(pointerId))
|
|
159
|
+
held.releasePointerCapture?.(pointerId);
|
|
160
|
+
}, []);
|
|
161
|
+
/** Disarm the pending menu — for one pointer, or for whichever is armed. */
|
|
162
|
+
const cancelLongPress = useCallback((pointerId) => {
|
|
163
|
+
const held = longPressRef.current;
|
|
164
|
+
if (!held)
|
|
165
|
+
return;
|
|
166
|
+
if (pointerId !== undefined && held.pointerId !== pointerId)
|
|
167
|
+
return;
|
|
168
|
+
clearTimeout(held.timer);
|
|
169
|
+
longPressRef.current = null;
|
|
170
|
+
}, []);
|
|
171
|
+
/**
|
|
172
|
+
* Arm the hold that stands in for a right-click. The finger keeps whatever
|
|
173
|
+
* it already started — a drag, a pan — until the timer fires; only then does
|
|
174
|
+
* the gesture let go, so the board cannot slide out from under the menu.
|
|
175
|
+
*/
|
|
176
|
+
const armLongPress = useCallback((e, target) => {
|
|
177
|
+
if (e.pointerType !== "touch" || !onContextMenu)
|
|
178
|
+
return;
|
|
179
|
+
cancelLongPress();
|
|
180
|
+
const { pointerId, clientX: x, clientY: y } = e;
|
|
181
|
+
const timer = setTimeout(() => {
|
|
182
|
+
longPressRef.current = null;
|
|
183
|
+
applyDrag(null);
|
|
184
|
+
panRef.current = null;
|
|
185
|
+
setPanning(false);
|
|
186
|
+
// The capture stays where it is: the finger now steers nothing, but the
|
|
187
|
+
// element holding it is still guaranteed to receive the eventual lift.
|
|
188
|
+
suppressClickRef.current = true;
|
|
189
|
+
navigator.vibrate?.(10);
|
|
190
|
+
onContextMenu(x, y, target);
|
|
191
|
+
}, LONG_PRESS_MS);
|
|
192
|
+
longPressRef.current = { pointerId, x, y, target, timer };
|
|
193
|
+
}, [cancelLongPress, onContextMenu, applyDrag]);
|
|
194
|
+
// A fingertip asks for room a cursor does not. Detected once, watched for
|
|
195
|
+
// change (a tablet docking to a mouse flips this), and never read in render
|
|
196
|
+
// before the effect has run — so hydration matches the server's `false`.
|
|
197
|
+
useEffect(() => {
|
|
198
|
+
if (typeof window === "undefined" || !window.matchMedia)
|
|
199
|
+
return;
|
|
200
|
+
const mq = window.matchMedia("(pointer: coarse)");
|
|
201
|
+
const apply = () => setCoarsePointer(mq.matches);
|
|
202
|
+
apply();
|
|
203
|
+
mq.addEventListener("change", apply);
|
|
204
|
+
return () => mq.removeEventListener("change", apply);
|
|
205
|
+
}, []);
|
|
206
|
+
// Safety net. Pointer capture makes the canvas's own `pointerup` reliable, but
|
|
207
|
+
// a gesture torn away by the OS — a call arriving, the app backgrounded — can
|
|
208
|
+
// still leave a finger recorded that is no longer on the glass. A stale entry
|
|
209
|
+
// would make the *next* single touch look like the second half of a pinch, so
|
|
210
|
+
// every pointer that ends anywhere is forgotten here too.
|
|
211
|
+
useEffect(() => {
|
|
212
|
+
const forget = (e) => {
|
|
213
|
+
pointersRef.current.delete(e.pointerId);
|
|
214
|
+
};
|
|
215
|
+
window.addEventListener("pointerup", forget);
|
|
216
|
+
window.addEventListener("pointercancel", forget);
|
|
217
|
+
return () => {
|
|
218
|
+
window.removeEventListener("pointerup", forget);
|
|
219
|
+
window.removeEventListener("pointercancel", forget);
|
|
220
|
+
};
|
|
221
|
+
}, []);
|
|
222
|
+
// Unmounting mid-hold must not leave a timer alive to open a menu over a
|
|
223
|
+
// canvas that no longer exists.
|
|
224
|
+
useEffect(() => () => cancelLongPress(), [cancelLongPress]);
|
|
225
|
+
// Live-animation tracking. The prev* refs are read/written ONLY inside the
|
|
226
|
+
// commit effect (never during render). The rendered classes are driven by
|
|
227
|
+
// state (enteringNames / enteringEdges), so the render stays a pure function
|
|
228
|
+
// of props+state. `exitingNodes` holds nodes that vanished from the current
|
|
229
|
+
// drill level so they outlive React's unmount and animate out.
|
|
230
|
+
const prevNamesRef = useRef(new Set());
|
|
231
|
+
const prevNodeDataRef = useRef(new Map());
|
|
232
|
+
const prevParentRef = useRef(currentParent);
|
|
233
|
+
const prevEdgeKeysRef = useRef(new Set());
|
|
234
|
+
const [enteringNames, setEnteringNames] = useState(new Set());
|
|
235
|
+
const [enteringEdges, setEnteringEdges] = useState(new Set());
|
|
236
|
+
const [exitingNodes, setExitingNodes] = useState(new Map());
|
|
237
|
+
// Touch hit areas. Both live in world units — everything inside the navigated
|
|
238
|
+
// group does — so each is a screen-pixel budget divided by the scale: the cuff
|
|
239
|
+
// around a box and the ribbon along an edge stay the same size *in the hand*
|
|
240
|
+
// whether the board is zoomed in or pushed away. Zero for a mouse, which means
|
|
241
|
+
// the extra geometry is never rendered at all and the cursor keeps hitting
|
|
242
|
+
// exactly what it is pointed at.
|
|
243
|
+
const touchPad = coarsePointer ? TOUCH_TARGET_PAD_PX / viewport.scale : 0;
|
|
244
|
+
const touchEdgeStroke = coarsePointer ? TOUCH_EDGE_STROKE_PX / viewport.scale : 0;
|
|
245
|
+
const getPos = useCallback((name) => positions[name] ?? FALLBACK_BOX, [positions]);
|
|
246
|
+
// Keyboard shortcuts. Undo, redo and delete belong to the host — the canvas
|
|
247
|
+
// only says that they were asked for.
|
|
248
|
+
useEffect(() => {
|
|
249
|
+
const handler = (e) => {
|
|
250
|
+
if ((e.ctrlKey || e.metaKey) && e.key === "z" && onUndo) {
|
|
251
|
+
e.preventDefault();
|
|
252
|
+
onUndo();
|
|
253
|
+
}
|
|
254
|
+
if ((e.ctrlKey || e.metaKey) && (e.key === "y" || (e.shiftKey && e.key === "z")) && onRedo) {
|
|
255
|
+
e.preventDefault();
|
|
256
|
+
onRedo();
|
|
257
|
+
}
|
|
258
|
+
if (e.key === "Escape") {
|
|
259
|
+
setEventPicker(null);
|
|
260
|
+
onCancelDraw?.();
|
|
261
|
+
}
|
|
262
|
+
if (e.key === "Delete" && selection.kind === "state" && selection.id && onDeleteState) {
|
|
263
|
+
onDeleteState(selection.id);
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
window.addEventListener("keydown", handler);
|
|
267
|
+
return () => window.removeEventListener("keydown", handler);
|
|
268
|
+
}, [onUndo, onRedo, onCancelDraw, onDeleteState, selection]);
|
|
269
|
+
/** Begin sliding the whole board with one pointer. Shared by mouse and finger. */
|
|
270
|
+
const beginPan = useCallback((e) => {
|
|
271
|
+
const vp = viewportRef.current;
|
|
272
|
+
panRef.current = {
|
|
273
|
+
pointerId: e.pointerId,
|
|
274
|
+
startX: e.clientX,
|
|
275
|
+
startY: e.clientY,
|
|
276
|
+
origX: vp.x,
|
|
277
|
+
origY: vp.y,
|
|
278
|
+
};
|
|
279
|
+
panMovedRef.current = false;
|
|
280
|
+
setPanning(true);
|
|
281
|
+
const svg = svgRef.current;
|
|
282
|
+
if (!svg)
|
|
283
|
+
return;
|
|
284
|
+
capturesRef.current.set(e.pointerId, svg);
|
|
285
|
+
svg.setPointerCapture(e.pointerId);
|
|
286
|
+
}, []);
|
|
287
|
+
/**
|
|
288
|
+
* Promote whatever is happening to a two-finger gesture. Everything the
|
|
289
|
+
* single pointer had claimed — a box mid-drag, a pan mid-slide, a hold on its
|
|
290
|
+
* way to a menu — is given up here: with both fingers on the glass the user
|
|
291
|
+
* is steering the view, not editing the machine.
|
|
292
|
+
*/
|
|
293
|
+
const beginPinch = useCallback(() => {
|
|
294
|
+
const live = [...pointersRef.current.entries()];
|
|
295
|
+
if (live.length < 2)
|
|
296
|
+
return;
|
|
297
|
+
const [[idA, a], [idB, b]] = live;
|
|
298
|
+
cancelLongPress();
|
|
299
|
+
applyDrag(null);
|
|
300
|
+
panRef.current = null;
|
|
301
|
+
// Fingers landing on the same pixel would divide by zero; a floor of one
|
|
302
|
+
// pixel makes the first frame a no-op instead of an infinity.
|
|
303
|
+
const startDist = Math.max(1, Math.hypot(b.x - a.x, b.y - a.y));
|
|
304
|
+
const mid = toCanvasPoint((a.x + b.x) / 2, (a.y + b.y) / 2);
|
|
305
|
+
pinchRef.current = {
|
|
306
|
+
a: idA,
|
|
307
|
+
b: idB,
|
|
308
|
+
startDist,
|
|
309
|
+
startMidX: mid.x,
|
|
310
|
+
startMidY: mid.y,
|
|
311
|
+
start: viewportRef.current,
|
|
312
|
+
};
|
|
313
|
+
// A pinch has plainly travelled; its lift is never a tap on empty space.
|
|
314
|
+
panMovedRef.current = true;
|
|
315
|
+
setPinching(true);
|
|
316
|
+
// A finger that arrived while the capture phase was swallowing the event was
|
|
317
|
+
// never captured by anyone. Take it on the surface so the gesture survives it
|
|
318
|
+
// sliding off the canvas; fingers already held by a box keep that holder,
|
|
319
|
+
// since their moves bubble here regardless.
|
|
320
|
+
const svg = svgRef.current;
|
|
321
|
+
if (!svg)
|
|
322
|
+
return;
|
|
323
|
+
for (const id of [idA, idB]) {
|
|
324
|
+
if (capturesRef.current.has(id))
|
|
325
|
+
continue;
|
|
326
|
+
try {
|
|
327
|
+
svg.setPointerCapture(id);
|
|
328
|
+
capturesRef.current.set(id, svg);
|
|
329
|
+
}
|
|
330
|
+
catch {
|
|
331
|
+
// The pointer ended between the event and this line. Nothing to hold.
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
}, [cancelLongPress, toCanvasPoint, applyDrag]);
|
|
335
|
+
/**
|
|
336
|
+
* Runs before any box or the surface sees the press, so it can count fingers
|
|
337
|
+
* that a node's `stopPropagation` would otherwise hide. Bookkeeping only —
|
|
338
|
+
* except for the one decision that has to be made this early: a second finger
|
|
339
|
+
* turns the gesture into a pinch, and nothing below may start a rival one.
|
|
340
|
+
*/
|
|
341
|
+
const handlePointerDownCapture = useCallback((e) => {
|
|
342
|
+
// The click that closes out the previous gesture has been and gone (or was
|
|
343
|
+
// never sent, as on iOS after a hold). Either way, stop swallowing.
|
|
344
|
+
suppressClickRef.current = false;
|
|
345
|
+
if (e.pointerType !== "touch")
|
|
346
|
+
return;
|
|
347
|
+
setCoarsePointer(true);
|
|
348
|
+
pointersRef.current.set(e.pointerId, { x: e.clientX, y: e.clientY });
|
|
349
|
+
const count = pointersRef.current.size;
|
|
350
|
+
if (count < 2)
|
|
351
|
+
return;
|
|
352
|
+
e.stopPropagation();
|
|
353
|
+
if (count === 2)
|
|
354
|
+
beginPinch();
|
|
355
|
+
// A third finger is noise: recorded so its lift is accounted for, but the
|
|
356
|
+
// pinch keeps the two fingers it started with.
|
|
357
|
+
}, [beginPinch]);
|
|
358
|
+
const handleNodePointerDown = useCallback((e, name) => {
|
|
359
|
+
// Middle button, or space held: this gesture belongs to the surface. Let
|
|
360
|
+
// it bubble un-stopped so the pan handler below picks it up.
|
|
361
|
+
if (e.button !== 0 || spaceRef.current)
|
|
362
|
+
return;
|
|
363
|
+
e.stopPropagation();
|
|
364
|
+
// A finger on a box may still be asking for the menu rather than a drag.
|
|
365
|
+
// Arm the hold either way; travel past the slop disarms it.
|
|
366
|
+
armLongPress(e, { kind: "state", id: name });
|
|
367
|
+
if (!readOnly && drawMode === "transition") {
|
|
368
|
+
if (!drawSource) {
|
|
369
|
+
onSelect?.("state", name);
|
|
370
|
+
}
|
|
371
|
+
else if (drawSource !== name) {
|
|
372
|
+
setEventPicker({ stateName: drawSource, targetName: name, x: e.clientX, y: e.clientY });
|
|
373
|
+
}
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
onSelect?.("state", name);
|
|
377
|
+
if (readOnly || !onStateMove)
|
|
378
|
+
return;
|
|
379
|
+
const pos = getPos(name);
|
|
380
|
+
applyDrag({
|
|
381
|
+
name,
|
|
382
|
+
pointerId: e.pointerId,
|
|
383
|
+
startX: e.clientX,
|
|
384
|
+
startY: e.clientY,
|
|
385
|
+
origX: pos.x,
|
|
386
|
+
origY: pos.y,
|
|
387
|
+
});
|
|
388
|
+
// Capture on the node's own group, so the gesture survives the pointer
|
|
389
|
+
// outrunning the box or leaving the canvas. It must be *this* element and
|
|
390
|
+
// not the surface: a capture retargets the click and dblclick that follow,
|
|
391
|
+
// and retargeting them to the <svg> would read as a click on empty space —
|
|
392
|
+
// clearing the selection the press just made, and stealing the
|
|
393
|
+
// double-click that drills into a composite.
|
|
394
|
+
const node = e.currentTarget;
|
|
395
|
+
capturesRef.current.set(e.pointerId, node);
|
|
396
|
+
node.setPointerCapture?.(e.pointerId);
|
|
397
|
+
}, [onSelect, getPos, drawMode, drawSource, armLongPress, applyDrag, readOnly, onStateMove]);
|
|
398
|
+
const handleSurfacePointerDown = useCallback((e) => {
|
|
399
|
+
if (e.pointerType === "touch") {
|
|
400
|
+
// A phone has no middle button and no space bar, so the plainest gesture
|
|
401
|
+
// has to be the one that moves the board: one finger on bare canvas pans.
|
|
402
|
+
// No `preventDefault` — the click and double-click synthesised from this
|
|
403
|
+
// touch are what still clear the selection and drill into a composite.
|
|
404
|
+
armLongPress(e, { kind: "canvas" });
|
|
405
|
+
beginPan(e);
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
const wantsPan = e.button === 1 || (e.button === 0 && spaceRef.current);
|
|
409
|
+
if (!wantsPan)
|
|
410
|
+
return;
|
|
411
|
+
// Suppresses the compatibility mouse events, and with them Chrome's
|
|
412
|
+
// middle-click autoscroll.
|
|
413
|
+
e.preventDefault();
|
|
414
|
+
beginPan(e);
|
|
415
|
+
}, [armLongPress, beginPan]);
|
|
416
|
+
const handleSurfacePointerMove = useCallback((e) => {
|
|
417
|
+
if (pointersRef.current.has(e.pointerId)) {
|
|
418
|
+
pointersRef.current.set(e.pointerId, { x: e.clientX, y: e.clientY });
|
|
419
|
+
}
|
|
420
|
+
// A hold that wanders is a drag changing its mind.
|
|
421
|
+
const hold = longPressRef.current;
|
|
422
|
+
if (hold && hold.pointerId === e.pointerId) {
|
|
423
|
+
if (Math.hypot(e.clientX - hold.x, e.clientY - hold.y) > TOUCH_SLOP_PX) {
|
|
424
|
+
cancelLongPress(e.pointerId);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
const pinch = pinchRef.current;
|
|
428
|
+
if (pinch) {
|
|
429
|
+
if (e.pointerId !== pinch.a && e.pointerId !== pinch.b)
|
|
430
|
+
return;
|
|
431
|
+
const a = pointersRef.current.get(pinch.a);
|
|
432
|
+
const b = pointersRef.current.get(pinch.b);
|
|
433
|
+
if (!a || !b)
|
|
434
|
+
return;
|
|
435
|
+
// Two fingers say two things at once, and the viewport has room for
|
|
436
|
+
// both. The spread says how much to magnify: scale is the starting
|
|
437
|
+
// scale times how much further apart the fingers are now. The midpoint
|
|
438
|
+
// says where: `zoomTo` re-anchors the board so the world point that sat
|
|
439
|
+
// under the *starting* midpoint is still under it after the rescale —
|
|
440
|
+
// the same invariant Ctrl+wheel uses, with the midpoint standing in for
|
|
441
|
+
// the cursor. Whatever the midpoint itself has travelled since is then
|
|
442
|
+
// a plain screen-space slide, which is exactly a pan. Both are measured
|
|
443
|
+
// from the gesture's opening frame, never from the previous move, so
|
|
444
|
+
// rounding cannot accumulate under a long pinch.
|
|
445
|
+
const dist = Math.hypot(b.x - a.x, b.y - a.y);
|
|
446
|
+
const mid = toCanvasPoint((a.x + b.x) / 2, (a.y + b.y) / 2);
|
|
447
|
+
const zoomed = zoomTo(pinch.start, pinch.start.scale * (dist / pinch.startDist), {
|
|
448
|
+
x: pinch.startMidX,
|
|
449
|
+
y: pinch.startMidY,
|
|
450
|
+
});
|
|
451
|
+
onViewportChange(panBy(zoomed, mid.x - pinch.startMidX, mid.y - pinch.startMidY));
|
|
452
|
+
return;
|
|
453
|
+
}
|
|
454
|
+
const pan = panRef.current;
|
|
455
|
+
if (pan) {
|
|
456
|
+
if (pan.pointerId !== e.pointerId)
|
|
457
|
+
return;
|
|
458
|
+
const dx = e.clientX - pan.startX;
|
|
459
|
+
const dy = e.clientY - pan.startY;
|
|
460
|
+
// A mouse that moved at all was dragged. A fingertip is never that
|
|
461
|
+
// still, so a touch has to clear the slop before its lift stops
|
|
462
|
+
// counting as a tap.
|
|
463
|
+
const slop = e.pointerType === "touch" ? TOUCH_SLOP_PX : 0;
|
|
464
|
+
if (Math.abs(dx) > slop || Math.abs(dy) > slop)
|
|
465
|
+
panMovedRef.current = true;
|
|
466
|
+
onViewportChange({
|
|
467
|
+
x: pan.origX + dx,
|
|
468
|
+
y: pan.origY + dy,
|
|
469
|
+
scale: viewportRef.current.scale,
|
|
470
|
+
});
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
if (!drag || drag.pointerId !== e.pointerId || !onStateMove)
|
|
474
|
+
return;
|
|
475
|
+
// The pointer moves in screen pixels; the box lives in world units. At
|
|
476
|
+
// scale k a screen pixel is 1/k world units, which is what keeps a
|
|
477
|
+
// dragged state pinned under the cursor at any zoom. Pan cancels out of a
|
|
478
|
+
// delta, so only the scale appears here.
|
|
479
|
+
const scale = viewportRef.current.scale;
|
|
480
|
+
const dx = (e.clientX - drag.startX) / scale;
|
|
481
|
+
const dy = (e.clientY - drag.startY) / scale;
|
|
482
|
+
const pos = getPos(drag.name);
|
|
483
|
+
onStateMove(drag.name, {
|
|
484
|
+
...pos,
|
|
485
|
+
x: Math.max(0, drag.origX + dx),
|
|
486
|
+
y: Math.max(0, drag.origY + dy),
|
|
487
|
+
});
|
|
488
|
+
}, [drag, getPos, onStateMove, onViewportChange, cancelLongPress, toCanvasPoint]);
|
|
489
|
+
const handleSurfacePointerUp = useCallback((e) => {
|
|
490
|
+
pointersRef.current.delete(e.pointerId);
|
|
491
|
+
cancelLongPress(e.pointerId);
|
|
492
|
+
releaseCapture(e.pointerId);
|
|
493
|
+
const pinch = pinchRef.current;
|
|
494
|
+
if (pinch && (pinch.a === e.pointerId || pinch.b === e.pointerId)) {
|
|
495
|
+
pinchRef.current = null;
|
|
496
|
+
setPinching(false);
|
|
497
|
+
// One finger lifting out of a pinch leaves the other still on the glass,
|
|
498
|
+
// and a hand that is still touching the board expects it to keep
|
|
499
|
+
// following. Re-open a pan from where that finger is *now*, against the
|
|
500
|
+
// viewport the pinch just left behind — measuring from where it first
|
|
501
|
+
// landed would snap the board across the screen.
|
|
502
|
+
const survivorId = pinch.a === e.pointerId ? pinch.b : pinch.a;
|
|
503
|
+
const survivor = pointersRef.current.get(survivorId);
|
|
504
|
+
if (survivor) {
|
|
505
|
+
const vp = viewportRef.current;
|
|
506
|
+
panRef.current = {
|
|
507
|
+
pointerId: survivorId,
|
|
508
|
+
startX: survivor.x,
|
|
509
|
+
startY: survivor.y,
|
|
510
|
+
origX: vp.x,
|
|
511
|
+
origY: vp.y,
|
|
512
|
+
};
|
|
513
|
+
panMovedRef.current = true;
|
|
514
|
+
setPanning(true);
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
if (panRef.current?.pointerId === e.pointerId)
|
|
518
|
+
panRef.current = null;
|
|
519
|
+
if (dragRef.current?.pointerId === e.pointerId)
|
|
520
|
+
applyDrag(null);
|
|
521
|
+
// Sweep. Whether the view is being steered is asked of the refs, not of
|
|
522
|
+
// which pointer just ended — a finger the OS reclaimed, or one whose lift
|
|
523
|
+
// never reached us, would otherwise leave the board inert for good, every
|
|
524
|
+
// box deaf to the pointer with nothing left to explain why.
|
|
525
|
+
if (!panRef.current)
|
|
526
|
+
setPanning(false);
|
|
527
|
+
if (!pinchRef.current)
|
|
528
|
+
setPinching(false);
|
|
529
|
+
}, [cancelLongPress, releaseCapture, applyDrag]);
|
|
530
|
+
// Wheel: pan by default, zoom under Ctrl/⌘ (which is also how a browser
|
|
531
|
+
// delivers a trackpad pinch). Registered natively with `passive: false` —
|
|
532
|
+
// React's own wheel listener is passive, so `preventDefault` there cannot stop
|
|
533
|
+
// the page from zooming out from under the canvas.
|
|
534
|
+
useEffect(() => {
|
|
535
|
+
const svg = svgRef.current;
|
|
536
|
+
if (!svg)
|
|
537
|
+
return;
|
|
538
|
+
const onWheel = (e) => {
|
|
539
|
+
e.preventDefault();
|
|
540
|
+
const vp = viewportRef.current;
|
|
541
|
+
const dx = wheelPixels(e.deltaX, e.deltaMode);
|
|
542
|
+
const dy = wheelPixels(e.deltaY, e.deltaMode);
|
|
543
|
+
if (e.ctrlKey || e.metaKey) {
|
|
544
|
+
const anchor = toCanvasPoint(e.clientX, e.clientY);
|
|
545
|
+
const next = zoomAt(vp, Math.exp(-dy * 0.0025), anchor);
|
|
546
|
+
if (next !== vp)
|
|
547
|
+
onViewportChange(next);
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
// Shift turns the wheel sideways; a trackpad already reports deltaX.
|
|
551
|
+
const moveX = e.shiftKey ? -(dx || dy) : -dx;
|
|
552
|
+
const moveY = e.shiftKey ? 0 : -dy;
|
|
553
|
+
if (moveX === 0 && moveY === 0)
|
|
554
|
+
return;
|
|
555
|
+
onViewportChange(panBy(vp, moveX, moveY));
|
|
556
|
+
};
|
|
557
|
+
svg.addEventListener("wheel", onWheel, { passive: false });
|
|
558
|
+
return () => svg.removeEventListener("wheel", onWheel);
|
|
559
|
+
}, [onViewportChange, toCanvasPoint]);
|
|
560
|
+
// Space arms the pan grip. Held down it must not scroll the page, and it must
|
|
561
|
+
// stay inert while the user is typing into a panel.
|
|
562
|
+
useEffect(() => {
|
|
563
|
+
const down = (e) => {
|
|
564
|
+
if (e.code !== "Space" || e.repeat)
|
|
565
|
+
return;
|
|
566
|
+
if (isTypingTarget(e.target) || isTypingTarget(document.activeElement))
|
|
567
|
+
return;
|
|
568
|
+
e.preventDefault();
|
|
569
|
+
spaceRef.current = true;
|
|
570
|
+
setSpaceHeld(true);
|
|
571
|
+
};
|
|
572
|
+
const up = (e) => {
|
|
573
|
+
if (e.code !== "Space")
|
|
574
|
+
return;
|
|
575
|
+
spaceRef.current = false;
|
|
576
|
+
setSpaceHeld(false);
|
|
577
|
+
};
|
|
578
|
+
// Losing the window mid-hold would otherwise leave the grip stuck on.
|
|
579
|
+
const release = () => {
|
|
580
|
+
spaceRef.current = false;
|
|
581
|
+
setSpaceHeld(false);
|
|
582
|
+
};
|
|
583
|
+
window.addEventListener("keydown", down);
|
|
584
|
+
window.addEventListener("keyup", up);
|
|
585
|
+
window.addEventListener("blur", release);
|
|
586
|
+
return () => {
|
|
587
|
+
window.removeEventListener("keydown", down);
|
|
588
|
+
window.removeEventListener("keyup", up);
|
|
589
|
+
window.removeEventListener("blur", release);
|
|
590
|
+
};
|
|
591
|
+
}, []);
|
|
592
|
+
/** Zoom from the buttons: anchored at the middle of the canvas. */
|
|
593
|
+
const zoomFromCentre = useCallback((factor) => {
|
|
594
|
+
const rect = svgRef.current?.getBoundingClientRect();
|
|
595
|
+
const anchor = { x: (rect?.width ?? 0) / 2, y: (rect?.height ?? 0) / 2 };
|
|
596
|
+
const vp = viewportRef.current;
|
|
597
|
+
const next = zoomAt(vp, factor, anchor);
|
|
598
|
+
if (next !== vp)
|
|
599
|
+
onViewportChange(next);
|
|
600
|
+
}, [onViewportChange]);
|
|
601
|
+
const resetZoom = useCallback(() => {
|
|
602
|
+
const rect = svgRef.current?.getBoundingClientRect();
|
|
603
|
+
const anchor = { x: (rect?.width ?? 0) / 2, y: (rect?.height ?? 0) / 2 };
|
|
604
|
+
onViewportChange(zoomTo(viewportRef.current, 1, anchor));
|
|
605
|
+
}, [onViewportChange]);
|
|
606
|
+
/** Frame every box of the current drill level — the answer to "where did it go". */
|
|
607
|
+
const fitToView = useCallback(() => {
|
|
608
|
+
const rect = svgRef.current?.getBoundingClientRect();
|
|
609
|
+
if (!rect)
|
|
610
|
+
return;
|
|
611
|
+
const boxes = currentChildren.map((s) => getPos(s.name));
|
|
612
|
+
onViewportChange(boxes.length ? fitToBoxes(boxes, rect.width, rect.height) : { ...IDENTITY_VIEWPORT });
|
|
613
|
+
}, [currentChildren, getPos, onViewportChange]);
|
|
614
|
+
useImperativeHandle(ref, () => ({
|
|
615
|
+
fit: fitToView,
|
|
616
|
+
zoomIn: () => zoomFromCentre(1.25),
|
|
617
|
+
zoomOut: () => zoomFromCentre(1 / 1.25),
|
|
618
|
+
resetZoom,
|
|
619
|
+
element: () => svgRef.current,
|
|
620
|
+
}), [fitToView, zoomFromCentre, resetZoom]);
|
|
621
|
+
// A board the host says is new gets framed once. Waiting a frame lets the
|
|
622
|
+
// pane finish laying out, so `getBoundingClientRect` is not measuring zero.
|
|
623
|
+
const fitRef = useRef(fitToView);
|
|
624
|
+
fitRef.current = fitToView;
|
|
625
|
+
useEffect(() => {
|
|
626
|
+
if (fitKey === undefined)
|
|
627
|
+
return;
|
|
628
|
+
const raf = requestAnimationFrame(() => fitRef.current());
|
|
629
|
+
return () => cancelAnimationFrame(raf);
|
|
630
|
+
}, [fitKey]);
|
|
631
|
+
const handleContextMenu = useCallback((e, stateName) => {
|
|
632
|
+
if (!onContextMenu)
|
|
633
|
+
return;
|
|
634
|
+
e.preventDefault();
|
|
635
|
+
e.stopPropagation();
|
|
636
|
+
onContextMenu(e.clientX, e.clientY, stateName ? { kind: "state", id: stateName } : { kind: "canvas" });
|
|
637
|
+
}, [onContextMenu]);
|
|
638
|
+
const handleEventPick = (eventId) => {
|
|
639
|
+
if (!eventPicker)
|
|
640
|
+
return;
|
|
641
|
+
onCreateTransition?.(eventPicker.stateName, eventPicker.targetName, eventId);
|
|
642
|
+
setEventPicker(null);
|
|
643
|
+
onCancelDraw?.();
|
|
644
|
+
};
|
|
645
|
+
// Collect transitions for arrows (within current navigation level). Memoized
|
|
646
|
+
// so its identity is stable across renders (drag/selection) — the commit
|
|
647
|
+
// effect below lists it as a dependency.
|
|
648
|
+
const arrows = useMemo(() => {
|
|
649
|
+
const childNames = new Set(currentChildren.map((s) => s.name));
|
|
650
|
+
const result = [];
|
|
651
|
+
for (const state of currentChildren) {
|
|
652
|
+
for (const [i, t] of (state.transitions ?? []).entries()) {
|
|
653
|
+
if (t.nextState && childNames.has(t.nextState)) {
|
|
654
|
+
result.push({
|
|
655
|
+
from: state.name,
|
|
656
|
+
to: t.nextState,
|
|
657
|
+
event: t.event,
|
|
658
|
+
stateName: state.name,
|
|
659
|
+
index: i,
|
|
660
|
+
condition: t.condition,
|
|
661
|
+
});
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
return result;
|
|
666
|
+
}, [currentChildren]);
|
|
667
|
+
/**
|
|
668
|
+
* The drawable form of those transitions: a routed curve each, and a settled
|
|
669
|
+
* spot for each event chip.
|
|
670
|
+
*
|
|
671
|
+
* Both halves are level-wide on purpose. Every edge used to leave the
|
|
672
|
+
* bottom-centre of its source and enter the top-centre of its target, so the
|
|
673
|
+
* three transitions out of `draft` and the three `advance_context` edges
|
|
674
|
+
* coming back ran as one rope, and their chips — pinned to midpoints a few
|
|
675
|
+
* pixels apart — printed through each other.
|
|
676
|
+
*
|
|
677
|
+
* `routeEdges` hands every edge its own spot on each box it touches and sends
|
|
678
|
+
* it through the gap that is actually there (an edge to a state above leaves
|
|
679
|
+
* the top, not the bottom). `placeLabels` then nudges any chip that still has
|
|
680
|
+
* a neighbour. The curve and the walker the chip rides come from the same
|
|
681
|
+
* control points, so a label can never be settled against a line other than
|
|
682
|
+
* the one drawn.
|
|
683
|
+
*
|
|
684
|
+
* Recomputed while a box is being dragged, which is what makes the arrows and
|
|
685
|
+
* their labels re-settle under the hand instead of after it.
|
|
686
|
+
*/
|
|
687
|
+
const edges = useMemo(() => {
|
|
688
|
+
const curves = routeEdges(arrows, getPos);
|
|
689
|
+
const spots = placeLabels(arrows.map((arrow, i) => {
|
|
690
|
+
const box = getPos(arrow.from);
|
|
691
|
+
return {
|
|
692
|
+
id: `${arrow.stateName}:${arrow.index}`,
|
|
693
|
+
event: arrow.event,
|
|
694
|
+
condition: arrow.condition,
|
|
695
|
+
glyph: true,
|
|
696
|
+
// A self-loop's arc is a short bulge with no room to carry a word on
|
|
697
|
+
// it; its chip sits just beyond the bulge instead.
|
|
698
|
+
at: arrow.from === arrow.to
|
|
699
|
+
? () => ({
|
|
700
|
+
x: box.x + box.width + SELF_LOOP_BULGE + 30,
|
|
701
|
+
y: box.y + box.height / 2 + 4,
|
|
702
|
+
})
|
|
703
|
+
: curves[i].at,
|
|
704
|
+
};
|
|
705
|
+
}), currentChildren.map((s) => getPos(s.name)));
|
|
706
|
+
const byId = new Map(spots.map((spot) => [spot.label.id, spot]));
|
|
707
|
+
return arrows.flatMap((arrow, i) => {
|
|
708
|
+
const id = `${arrow.stateName}:${arrow.index}`;
|
|
709
|
+
const spot = byId.get(id);
|
|
710
|
+
return spot ? [{ arrow, id, curve: curves[i], spot }] : [];
|
|
711
|
+
});
|
|
712
|
+
}, [arrows, currentChildren, getPos]);
|
|
713
|
+
// After each commit, diff the freshly-rendered nodes/edges against the
|
|
714
|
+
// previous render (held in refs, touched only here). Newly-present names/edges
|
|
715
|
+
// are flagged as "entering" (drives slc-node-enter / slc-edge-enter on the NEXT
|
|
716
|
+
// render's fresh element); names that vanished from the current drill level are
|
|
717
|
+
// captured with their last def + position into `exitingNodes` so they animate
|
|
718
|
+
// out. Drill-level changes are NOT add/remove: the new level just blooms in and
|
|
719
|
+
// stale exit nodes are cleared.
|
|
720
|
+
useEffect(() => {
|
|
721
|
+
const currentNames = new Set(currentChildren.map((s) => s.name));
|
|
722
|
+
const currentEdgeKeys = new Set(arrows.map((a) => `${a.stateName}:${a.index}`));
|
|
723
|
+
const sameLevel = prevParentRef.current === currentParent;
|
|
724
|
+
const newNames = [...currentNames].filter((n) => !prevNamesRef.current.has(n));
|
|
725
|
+
if (newNames.length) {
|
|
726
|
+
setEnteringNames((prev) => {
|
|
727
|
+
const next = new Set(prev);
|
|
728
|
+
newNames.forEach((n) => next.add(n));
|
|
729
|
+
return next;
|
|
730
|
+
});
|
|
731
|
+
}
|
|
732
|
+
const newEdges = [...currentEdgeKeys].filter((k) => !prevEdgeKeysRef.current.has(k));
|
|
733
|
+
if (newEdges.length) {
|
|
734
|
+
setEnteringEdges((prev) => {
|
|
735
|
+
const next = new Set(prev);
|
|
736
|
+
newEdges.forEach((k) => next.add(k));
|
|
737
|
+
return next;
|
|
738
|
+
});
|
|
739
|
+
}
|
|
740
|
+
// Prune enter markers for nodes/edges that no longer exist (keeps the sets
|
|
741
|
+
// bounded to what is currently on-canvas).
|
|
742
|
+
setEnteringNames((prev) => {
|
|
743
|
+
let changed = false;
|
|
744
|
+
const next = new Set(prev);
|
|
745
|
+
prev.forEach((n) => {
|
|
746
|
+
if (!currentNames.has(n)) {
|
|
747
|
+
next.delete(n);
|
|
748
|
+
changed = true;
|
|
749
|
+
}
|
|
750
|
+
});
|
|
751
|
+
return changed ? next : prev;
|
|
752
|
+
});
|
|
753
|
+
setEnteringEdges((prev) => {
|
|
754
|
+
let changed = false;
|
|
755
|
+
const next = new Set(prev);
|
|
756
|
+
prev.forEach((k) => {
|
|
757
|
+
if (!currentEdgeKeys.has(k)) {
|
|
758
|
+
next.delete(k);
|
|
759
|
+
changed = true;
|
|
760
|
+
}
|
|
761
|
+
});
|
|
762
|
+
return changed ? next : prev;
|
|
763
|
+
});
|
|
764
|
+
if (sameLevel) {
|
|
765
|
+
setExitingNodes((prev) => {
|
|
766
|
+
const next = new Map(prev);
|
|
767
|
+
let changed = false;
|
|
768
|
+
prevNodeDataRef.current.forEach((data, name) => {
|
|
769
|
+
if (!currentNames.has(name) && !next.has(name)) {
|
|
770
|
+
next.set(name, data);
|
|
771
|
+
changed = true;
|
|
772
|
+
}
|
|
773
|
+
});
|
|
774
|
+
// A node that reappeared must never linger in the exiting layer.
|
|
775
|
+
currentNames.forEach((name) => {
|
|
776
|
+
if (next.delete(name))
|
|
777
|
+
changed = true;
|
|
778
|
+
});
|
|
779
|
+
return changed ? next : prev;
|
|
780
|
+
});
|
|
781
|
+
}
|
|
782
|
+
else {
|
|
783
|
+
setExitingNodes((prev) => (prev.size ? new Map() : prev));
|
|
784
|
+
}
|
|
785
|
+
prevNamesRef.current = currentNames;
|
|
786
|
+
prevNodeDataRef.current = new Map(currentChildren.map((s) => [s.name, { state: s, pos: getPos(s.name) }]));
|
|
787
|
+
prevEdgeKeysRef.current = currentEdgeKeys;
|
|
788
|
+
prevParentRef.current = currentParent;
|
|
789
|
+
}, [currentChildren, currentParent, arrows, getPos]);
|
|
790
|
+
const paneStyle = { ...themeStyle(theme), ...style };
|
|
791
|
+
const hudScale = coarsePointer ? " slc-hud--coarse" : "";
|
|
792
|
+
return (
|
|
793
|
+
// The canvas *pane*, not just the SVG. Two things hang off this element.
|
|
794
|
+
//
|
|
795
|
+
// `data-pinch-owner` is what a host's own chrome pinch reads to disqualify
|
|
796
|
+
// itself: a finger anywhere in here — the board, the breadcrumb, the zoom
|
|
797
|
+
// HUD — means this gesture is about the machine, never about the chrome.
|
|
798
|
+
//
|
|
799
|
+
// `touch-action: none` extends the SVG's own refusal to the overlays sitting
|
|
800
|
+
// on top of it. The SVG had it; the HUD and the breadcrumb did not, so a
|
|
801
|
+
// pinch that happened to open with a finger on the zoom bar was still a
|
|
802
|
+
// browser page zoom. Nothing in this pane scrolls, so denying everything
|
|
803
|
+
// costs nothing.
|
|
804
|
+
_jsxs("div", { className: `slc-pane${className ? ` ${className}` : ""}`, style: paneStyle, "data-pinch-owner": pinchOwner, children: [showBreadcrumb && crumbs.length > 1 && (_jsx("div", { className: "slc-crumbs", children: crumbs.map((name, i) => (_jsxs("span", { className: "slc-crumb-item", children: [i > 0 && _jsx("span", { className: "slc-crumb-sep", children: "\u203A" }), _jsx("button", { type: "button", className: `slc-crumb${i === crumbs.length - 1 ? " slc-crumb--current" : ""}`, onClick: () => onNavigateTo?.(i), children: name })] }, `${name}-${i}`))) })), _jsxs("svg", { ref: svgRef,
|
|
805
|
+
// Named so an export can find the board without a ref threaded through
|
|
806
|
+
// the host's toolbar — the picture it writes is this element, serialized.
|
|
807
|
+
id: svgId, className: "slc-surface", style: {
|
|
808
|
+
cursor: panning ? "grabbing" : spaceHeld ? "grab" : undefined,
|
|
809
|
+
// The browser's own gestures are all suppressed here, so every one of
|
|
810
|
+
// them has to be answered below: one finger pans, two pinch, and a
|
|
811
|
+
// held finger opens the menu.
|
|
812
|
+
touchAction: "none",
|
|
813
|
+
// On a touch device a resting finger would otherwise raise the system
|
|
814
|
+
// selection callout on top of our own held-press menu.
|
|
815
|
+
...(coarsePointer
|
|
816
|
+
? {
|
|
817
|
+
WebkitUserSelect: "none",
|
|
818
|
+
userSelect: "none",
|
|
819
|
+
WebkitTouchCallout: "none",
|
|
820
|
+
}
|
|
821
|
+
: {}),
|
|
822
|
+
}, onPointerDownCapture: handlePointerDownCapture, onPointerDown: handleSurfacePointerDown, onPointerMove: handleSurfacePointerMove, onPointerUp: handleSurfacePointerUp, onPointerCancel: handleSurfacePointerUp,
|
|
823
|
+
// Middle-click on Linux/Windows would otherwise paste or autoscroll.
|
|
824
|
+
onAuxClick: (e) => e.preventDefault(), onClick: (e) => {
|
|
825
|
+
// A hold that opened the menu still ends in a click on most touch
|
|
826
|
+
// browsers. It must not reach the host shell, which closes the menu on
|
|
827
|
+
// any click that arrives — the menu would flash and vanish on the lift.
|
|
828
|
+
if (suppressClickRef.current) {
|
|
829
|
+
suppressClickRef.current = false;
|
|
830
|
+
e.stopPropagation();
|
|
831
|
+
return;
|
|
832
|
+
}
|
|
833
|
+
// A pan that travelled is not a click on empty space.
|
|
834
|
+
if (panMovedRef.current) {
|
|
835
|
+
panMovedRef.current = false;
|
|
836
|
+
return;
|
|
837
|
+
}
|
|
838
|
+
if (e.target?.tagName === "svg") {
|
|
839
|
+
onClearSelection?.();
|
|
840
|
+
setEventPicker(null);
|
|
841
|
+
}
|
|
842
|
+
}, onContextMenu: (e) => handleContextMenu(e), children: [_jsxs("defs", { children: [_jsx("marker", { id: `slc-arrow-${markerId}`, markerWidth: "10", markerHeight: "7", refX: "10", refY: "3.5", orient: "auto", children: _jsx("polygon", { points: "0 0, 10 3.5, 0 7", className: "slc-arrowhead" }) }), _jsx("marker", { id: `slc-arrow-sel-${markerId}`, markerWidth: "10", markerHeight: "7", refX: "10", refY: "3.5", orient: "auto", children: _jsx("polygon", { points: "0 0, 10 3.5, 0 7", className: "slc-arrowhead slc-arrowhead--selected" }) })] }), drawMode === "transition" && drawSource && (_jsxs("text", { x: "50%", y: "30", textAnchor: "middle", className: "slc-draw-hint", children: ["Click target state to create transition from \"", drawSource, "\""] })), _jsxs("g", { transform: viewportTransform(viewport), style: navigating ? { pointerEvents: "none" } : undefined, children: [edges.map(({ arrow, id: edgeId, curve, spot }) => {
|
|
843
|
+
const isSelected = selection.kind === "transition" && selection.id === edgeId;
|
|
844
|
+
// A new edge (flagged in the commit effect) draws itself on.
|
|
845
|
+
const edgeEntering = enteringEdges.has(edgeId);
|
|
846
|
+
// A chip that had to move is drawn back to its own curve with a hair
|
|
847
|
+
// line, so a displaced label still says which transition it names.
|
|
848
|
+
const anchor = curve.at(0.5);
|
|
849
|
+
const strayed = Math.hypot(anchor.x - spot.cx, anchor.y - spot.cy) > 4;
|
|
850
|
+
return (_jsxs("g", { children: [coarsePointer && (_jsx("path", { d: curve.path, fill: "none", stroke: "transparent", strokeWidth: touchEdgeStroke, strokeLinecap: "round", pointerEvents: "stroke", onClick: (e) => {
|
|
851
|
+
e.stopPropagation();
|
|
852
|
+
onSelect?.("transition", edgeId);
|
|
853
|
+
} })), _jsx("path", { d: curve.path, pathLength: 1, markerEnd: `url(#slc-arrow${isSelected ? "-sel" : ""}-${markerId})`, className: `slc-edge${isSelected ? " slc-edge--selected" : ""}${edgeEntering ? " slc-edge-enter" : ""}`, onClick: (e) => {
|
|
854
|
+
e.stopPropagation();
|
|
855
|
+
onSelect?.("transition", edgeId);
|
|
856
|
+
} }), _jsxs("g", { className: "slc-chip", onClick: (e) => {
|
|
857
|
+
e.stopPropagation();
|
|
858
|
+
onSelect?.("transition", edgeId);
|
|
859
|
+
}, children: [strayed && (_jsx("line", { x1: anchor.x, y1: anchor.y, x2: spot.cx, y2: spot.cy - 5, className: `slc-chip-leader${isSelected ? " slc-chip-leader--selected" : ""}` })), coarsePointer && (_jsx("rect", { x: spot.x - touchPad, y: spot.y - touchPad, width: spot.width + touchPad * 2, height: spot.height + touchPad * 2, fill: "transparent", pointerEvents: "all" })), _jsx("rect", { x: spot.x, y: spot.y, width: spot.width, height: spot.height, rx: 4, className: `slc-chip-plate${isSelected ? " slc-chip-plate--selected" : ""}` }), _jsx(TriggerGlyph, { mark: eventGlyph(arrow.event), x: glyphAt(spot).x, y: glyphAt(spot).y, selected: isSelected }), _jsx("text", { x: spot.cx, y: spot.cy - 5, textAnchor: "middle", className: `slc-chip-text${isSelected ? " slc-chip-text--selected" : ""}`, children: arrow.event }), arrow.condition && (
|
|
860
|
+
// Elided to the width the chip was measured for. A guard is
|
|
861
|
+
// prose and can run to a paragraph; the whole of it is on the
|
|
862
|
+
// tooltip here, and in the host's properties panel.
|
|
863
|
+
_jsxs("text", { x: spot.cx, y: spot.cy + 7, textAnchor: "middle", className: "slc-chip-guard", children: [_jsx("title", { children: arrow.condition }), guardText(arrow.condition)] }))] })] }, `arrow-${edgeId}`));
|
|
864
|
+
}), currentChildren.map((state) => {
|
|
865
|
+
const pos = getPos(state.name);
|
|
866
|
+
const isSelected = selection.kind === "state" && selection.id === state.name;
|
|
867
|
+
const isFinal = state.kind === "final";
|
|
868
|
+
const isHistory = state.kind === "history";
|
|
869
|
+
const composite = isComposite(state);
|
|
870
|
+
const isDrawSource = drawSource === state.name;
|
|
871
|
+
const errored = errorSet.has(state.name);
|
|
872
|
+
const hasEntry = (state.onEntry?.actions?.length ?? 0) > 0;
|
|
873
|
+
const hasExit = (state.onExit?.actions?.length ?? 0) > 0;
|
|
874
|
+
const isActive = activeSet.has(state.name);
|
|
875
|
+
// A node first seen this session (flagged in the commit effect)
|
|
876
|
+
// carries slc-node-enter; the bloom only fires on the freshly-mounted
|
|
877
|
+
// element, so the marker staying set for existing nodes is inert.
|
|
878
|
+
const entering = enteringNames.has(state.name);
|
|
879
|
+
const cursor = spaceHeld
|
|
880
|
+
? undefined // the surface owns the cursor while the pan grip is armed
|
|
881
|
+
: drawMode === "transition" && !readOnly
|
|
882
|
+
? "slc-node--drawing"
|
|
883
|
+
: composite
|
|
884
|
+
? "slc-node--drillable"
|
|
885
|
+
: readOnly || !onStateMove
|
|
886
|
+
? "slc-node--static"
|
|
887
|
+
: "slc-node--draggable";
|
|
888
|
+
return (_jsxs("g", { className: cursor, onPointerDown: (e) => handleNodePointerDown(e, state.name), onDoubleClick: (e) => {
|
|
889
|
+
e.stopPropagation();
|
|
890
|
+
if (composite)
|
|
891
|
+
onNavigateInto?.(state.name);
|
|
892
|
+
}, onContextMenu: (e) => handleContextMenu(e, state.name), children: [coarsePointer && (_jsx("rect", { x: pos.x - touchPad, y: pos.y - touchPad, width: pos.width + touchPad * 2, height: pos.height + touchPad * 2, rx: 12, fill: "transparent", pointerEvents: "all" })), _jsxs("g", { className: entering ? "slc-node-enter" : undefined, children: [_jsx("rect", { x: pos.x, y: pos.y, width: pos.width, height: pos.height, rx: isHistory ? 30 : isFinal ? 4 : 8, strokeDasharray: isFinal ? "6 3" : composite ? "4 2" : undefined, className: [
|
|
893
|
+
"slc-node",
|
|
894
|
+
isFinal ? "slc-node--final" : composite ? "slc-node--composite" : "",
|
|
895
|
+
isDrawSource ? "slc-node--source" : "",
|
|
896
|
+
errored ? "slc-node--error" : "",
|
|
897
|
+
isSelected ? "slc-node--selected" : "",
|
|
898
|
+
isActive ? "slc-node--active" : "",
|
|
899
|
+
]
|
|
900
|
+
.filter(Boolean)
|
|
901
|
+
.join(" ") }), _jsx("text", { x: pos.x + pos.width / 2, y: pos.y + (hasEntry || hasExit ? pos.height / 2 : pos.height / 2 + 5), textAnchor: "middle", className: "slc-node-name", children: state.name }), state.kind && state.kind !== "normal" && (_jsx("text", { x: pos.x + pos.width - 8, y: pos.y + 14, textAnchor: "end", className: "slc-node-kind", children: state.kind })), hasEntry && (_jsx("text", { x: pos.x + 6, y: pos.y + pos.height - 6, className: "slc-node-entry", children: "\u25B8entry" })), hasExit && (_jsx("text", { x: pos.x + pos.width - 6, y: pos.y + pos.height - 6, textAnchor: "end", className: "slc-node-exit", children: "exit\u25C2" })), errored && (_jsx("text", { x: pos.x + 6, y: pos.y + 14, className: "slc-node-warn", children: "\u26A0" })), composite && (_jsxs("text", { x: pos.x + pos.width / 2, y: pos.y + pos.height - 6, textAnchor: "middle", className: "slc-node-drill", children: ["\u25BC ", childCount(state), " children \u2014 ", coarsePointer ? "double-tap" : "double-click", " to enter"] }))] })] }, state.name));
|
|
902
|
+
}), Array.from(exitingNodes.entries()).map(([name, { state, pos }]) => {
|
|
903
|
+
const exFinal = state.kind === "final";
|
|
904
|
+
const exComposite = isComposite(state);
|
|
905
|
+
return (_jsxs("g", { className: "slc-node-exit-group", onAnimationEnd: (e) => {
|
|
906
|
+
if (e.animationName !== "slc-node-out")
|
|
907
|
+
return;
|
|
908
|
+
setExitingNodes((prev) => {
|
|
909
|
+
if (!prev.has(name))
|
|
910
|
+
return prev;
|
|
911
|
+
const next = new Map(prev);
|
|
912
|
+
next.delete(name);
|
|
913
|
+
return next;
|
|
914
|
+
});
|
|
915
|
+
}, children: [_jsx("rect", { x: pos.x, y: pos.y, width: pos.width, height: pos.height, rx: state.kind === "history" ? 30 : exFinal ? 4 : 8, strokeDasharray: exFinal ? "6 3" : exComposite ? "4 2" : undefined, className: `slc-node${exFinal ? " slc-node--final" : exComposite ? " slc-node--composite" : ""}` }), _jsx("text", { x: pos.x + pos.width / 2, y: pos.y + pos.height / 2 + 5, textAnchor: "middle", className: "slc-node-name", children: name })] }, `exit-${name}`));
|
|
916
|
+
})] }), currentChildren.length === 0 && (_jsx("text", { x: "50%", y: "50%", textAnchor: "middle", className: "slc-empty", children: emptyHint ?? "This level has no states." }))] }), showHud && (_jsxs("div", { className: `slc-hud${hudScale}`, children: [_jsx("button", { type: "button", className: "slc-hud-btn", title: "Zoom out (Ctrl + wheel down, or pinch in)", disabled: viewport.scale <= VIEWPORT_LIMITS.min, onClick: () => zoomFromCentre(1 / 1.25), children: "\u2212" }), _jsxs("button", { type: "button", className: "slc-hud-btn slc-hud-btn--scale", title: "Reset zoom to 100%", onClick: resetZoom, children: [Math.round(viewport.scale * 100), "%"] }), _jsx("button", { type: "button", className: "slc-hud-btn", title: "Zoom in (Ctrl + wheel up, or pinch out)", disabled: viewport.scale >= VIEWPORT_LIMITS.max, onClick: () => zoomFromCentre(1.25), children: "\uFF0B" }), _jsx("span", { className: "slc-hud-sep", children: "|" }), _jsx("button", { type: "button", className: "slc-hud-btn", title: "Fit the whole machine in view", onClick: fitToView, children: "\u2922 Fit" }), hudExtras && (_jsxs(_Fragment, { children: [_jsx("span", { className: "slc-hud-sep", children: "|" }), hudExtras] })), _jsx("span", { className: "slc-hud-sep", children: "|" }), _jsx("span", { className: "slc-hud-hint", title: coarsePointer
|
|
917
|
+
? "Drag to pan · pinch with two fingers to zoom · press and hold for the menu · double-tap a composite to enter it"
|
|
918
|
+
: "Wheel scrolls · Shift+wheel scrolls sideways · Ctrl+wheel zooms at the cursor · middle-drag or Space+drag pans", children: pinching
|
|
919
|
+
? "pinching"
|
|
920
|
+
: panning
|
|
921
|
+
? "panning"
|
|
922
|
+
: coarsePointer
|
|
923
|
+
? "drag · pinch · hold"
|
|
924
|
+
: spaceHeld
|
|
925
|
+
? "space to pan"
|
|
926
|
+
: "wheel · ⌃wheel · space" })] })), eventPicker && (_jsxs("div", { className: "slc-picker", style: { left: eventPicker.x, top: eventPicker.y - 80 }, onClick: (e) => e.stopPropagation(), children: [_jsxs("div", { className: "slc-picker-title", children: [eventPicker.stateName, " \u2192 ", eventPicker.targetName] }), _jsx("div", { className: "slc-picker-sub", children: "Select event:" }), allEvents.length === 0 ? (_jsx("div", { className: "slc-picker-empty", children: "No events defined. Add events first." })) : (allEvents.map((eventId) => (_jsx("button", { type: "button", className: "slc-picker-item", onClick: () => handleEventPick(eventId), children: eventId }, eventId)))), _jsx("button", { type: "button", className: "slc-picker-cancel", onClick: () => {
|
|
927
|
+
setEventPicker(null);
|
|
928
|
+
onCancelDraw?.();
|
|
929
|
+
}, children: "Cancel" })] }))] }));
|
|
930
|
+
});
|
|
931
|
+
export default StateMachineCanvas;
|
|
932
|
+
//# sourceMappingURL=StateMachineCanvas.js.map
|