@miadi/stateloom-canvas 0.1.4 → 0.1.6

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.
@@ -0,0 +1,394 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ /**
3
+ * The sequence design surface (Spec 81) — the third sibling of
4
+ * `<StateMachineCanvas>` and `<EntityRelationshipCanvas>`.
5
+ *
6
+ * Same contract: props in, callbacks out, no store, no socket. The host owns
7
+ * the definition and the viewport; the geometry is `sequenceLayout(def)`, which
8
+ * the host may compute once and pass in so that its own "centre on message 9"
9
+ * and this drawing agree to the pixel. Same gestures: wheel pans, ⌃/⌘ wheel
10
+ * zooms at the pointer, a drag anywhere pans (nothing on a sequence is dragged
11
+ * into place — the order IS the drawing), two fingers pinch. Same `--slc-*`
12
+ * variables, so a themed host has themed this board too.
13
+ *
14
+ * What is drawn, from the layout:
15
+ *
16
+ * - a header box per participant. An actor (a participant that names a system
17
+ * actor) has rounded ends; an object participant (it IS a machine's object)
18
+ * has its name underlined, as UML writes an instance.
19
+ * - a lifeline under each header.
20
+ * - one arrow per message, headed by its ref and label. The event it fires is a
21
+ * small chip after the label, the state it leaves the machine in follows as
22
+ * `→ State`. A reply is dashed, an optional message is tagged `opt`, and a
23
+ * message to oneself is a loop to the right.
24
+ * - each fragment as a frame below the main messages, headed
25
+ * `alt · after 11 · <label>`.
26
+ *
27
+ * Selection is by focus kind: `{ kind: "message", id: "9" }` or
28
+ * `{ kind: "participant", id: "Chart" }` — the same names `focus=` uses.
29
+ */
30
+ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, } from "react";
31
+ import { allMessages, fitToBoxes, panBy, sequenceLayout, textWidth, viewportTransform, zoomAt, } from "@miadi/stateloom-protocol";
32
+ import { themeStyle } from "./theme.js";
33
+ const WHEEL_LINE_HEIGHT = 16;
34
+ const WHEEL_PAGE_HEIGHT = 400;
35
+ /** Movement under this many screen pixels is a click, not a drag. */
36
+ const DRAG_THRESHOLD = 4;
37
+ const LABEL_SIZE = 11;
38
+ const CHIP_SIZE = 10;
39
+ const REF_SIZE = 10;
40
+ /** A self-message's loop: how far right it reaches and how tall it is. */
41
+ const LOOP_W = 30;
42
+ const LOOP_H = 14;
43
+ function wheelPixels(delta, mode) {
44
+ if (mode === 1)
45
+ return delta * WHEEL_LINE_HEIGHT;
46
+ if (mode === 2)
47
+ return delta * WHEEL_PAGE_HEIGHT;
48
+ return delta;
49
+ }
50
+ /** A filled arrowhead with its tip at (x, y), pointing along +dx. */
51
+ function arrowHead(x, y, dir, open) {
52
+ const back = x - dir * 9;
53
+ return open ? `M ${back} ${y - 4.5} L ${x} ${y} L ${back} ${y + 4.5}` : `M ${back} ${y - 4.5} L ${x} ${y} L ${back} ${y + 4.5} Z`;
54
+ }
55
+ function participantTitle(p) {
56
+ return [
57
+ p.actor ? `actor ${p.actor}` : p.object ? `object ${p.object}` : p.service ? `service ${p.service}` : "",
58
+ p.holds?.length ? `holds ${p.holds.join(", ")}` : "",
59
+ p.description ?? "",
60
+ p.notes?.trim() ? `Notes: ${p.notes}` : "",
61
+ ]
62
+ .filter(Boolean)
63
+ .join("\n");
64
+ }
65
+ function messageTitle(ref, m) {
66
+ return [
67
+ `${ref}. ${m.from} → ${m.to}: ${m.label}`,
68
+ m.event ? `fires ${m.event}${m.machine ? ` on ${m.machine}` : ""}` : "",
69
+ m.carries ? `carries ${m.carries}` : "",
70
+ m.state ? `then ${m.state}` : "",
71
+ m.optional ? "optional" : "",
72
+ m.reply ? "reply" : "",
73
+ m.description ?? "",
74
+ m.notes?.trim() ? `Notes: ${m.notes}` : "",
75
+ ]
76
+ .filter(Boolean)
77
+ .join("\n");
78
+ }
79
+ const text = (v) => (typeof v === "string" ? v : v === null || v === undefined ? "" : String(v));
80
+ const optional = (v) => text(v) || undefined;
81
+ function drawableMessage(m) {
82
+ const o = (m && typeof m === "object" ? m : {});
83
+ return {
84
+ from: text(o.from),
85
+ to: text(o.to),
86
+ label: text(o.label),
87
+ event: optional(o.event),
88
+ machine: optional(o.machine),
89
+ carries: optional(o.carries),
90
+ state: optional(o.state),
91
+ description: optional(o.description),
92
+ notes: optional(o.notes),
93
+ optional: o.optional === true || undefined,
94
+ reply: o.reply === true || undefined,
95
+ };
96
+ }
97
+ /**
98
+ * The sequence as this canvas draws it: every string a string, every list a
99
+ * list, nothing null — so a malformed document draws what it can instead of
100
+ * throwing. Positions are kept (a null message stays a row, an unnamed
101
+ * participant a column) so refs and the layout still line up. Read-only: the
102
+ * host's definition is never changed.
103
+ */
104
+ export function drawableSequence(def) {
105
+ const d = (def && typeof def === "object" ? def : {});
106
+ const list = (v) => (Array.isArray(v) ? v : []);
107
+ const settings = (d.settings && typeof d.settings === "object" ? d.settings : {});
108
+ return {
109
+ settings: { namespace: text(settings.namespace), name: text(settings.name), notes: optional(settings.notes) },
110
+ participants: list(d.participants).map((p) => {
111
+ const o = (p && typeof p === "object" ? p : {});
112
+ return {
113
+ name: text(o.name),
114
+ description: optional(o.description),
115
+ notes: optional(o.notes),
116
+ actor: optional(o.actor),
117
+ service: optional(o.service),
118
+ object: optional(o.object),
119
+ holds: Array.isArray(o.holds) ? o.holds.map(text) : typeof o.holds === "string" ? [o.holds] : undefined,
120
+ };
121
+ }),
122
+ messages: list(d.messages).map(drawableMessage),
123
+ ...(Array.isArray(d.fragments)
124
+ ? {
125
+ fragments: d.fragments.map((f) => {
126
+ const o = (f && typeof f === "object" ? f : {});
127
+ return {
128
+ kind: text(o.kind),
129
+ label: text(o.label),
130
+ after: typeof o.after === "number" && Number.isFinite(o.after) ? o.after : 0,
131
+ notes: optional(o.notes),
132
+ messages: list(o.messages).map(drawableMessage),
133
+ };
134
+ }),
135
+ }
136
+ : {}),
137
+ };
138
+ }
139
+ export function SequenceCanvas({ definition: given, layout: givenLayout, viewport, onViewportChange, selection = null, errorElements, warningElements, fitKey, onSelect, onClearSelection, onContextMenu, emptyHint, theme, className, style, svgId, }) {
140
+ const svgRef = useRef(null);
141
+ const viewportRef = useRef(viewport);
142
+ viewportRef.current = viewport;
143
+ const gestureRef = useRef(null);
144
+ const pointersRef = useRef(new Map());
145
+ const pinchRef = useRef(null);
146
+ // What is drawn: the document with every field read defensively — a
147
+ // hand-written or agent-written file is not always the shape the types say.
148
+ const definition = useMemo(() => drawableSequence(given), [given]);
149
+ const layout = useMemo(() => givenLayout ?? sequenceLayout(definition), [givenLayout, definition]);
150
+ // The words on each row, measured once drawn: an estimate places the event
151
+ // chip after the label, the measure puts it right after it. Keyed `ref:part`.
152
+ const textRefs = useRef(new Map());
153
+ const [measured, setMeasured] = useState({});
154
+ const measureRef = (key) => (el) => {
155
+ if (el)
156
+ textRefs.current.set(key, el);
157
+ else
158
+ textRefs.current.delete(key);
159
+ };
160
+ useLayoutEffect(() => {
161
+ const next = {};
162
+ let changed = false;
163
+ for (const [key, el] of textRefs.current) {
164
+ const w = typeof el.getComputedTextLength === "function" ? el.getComputedTextLength() : 0;
165
+ if (!w)
166
+ continue;
167
+ next[key] = w;
168
+ if (Math.abs((measured[key] ?? -1) - w) > 0.5)
169
+ changed = true;
170
+ }
171
+ if (changed)
172
+ setMeasured(next);
173
+ // Measured again whenever what is drawn changes.
174
+ // eslint-disable-next-line react-hooks/exhaustive-deps
175
+ }, [layout, definition]);
176
+ const messages = useMemo(() => new Map(allMessages(definition).map((m) => [m.ref, m.message])), [definition]);
177
+ const participants = useMemo(() => new Map(definition.participants.filter((p) => p.name).map((p) => [p.name, p])), [definition.participants]);
178
+ const toCanvasPoint = useCallback((clientX, clientY) => {
179
+ const rect = svgRef.current?.getBoundingClientRect();
180
+ return { x: clientX - (rect?.left ?? 0), y: clientY - (rect?.top ?? 0) };
181
+ }, []);
182
+ // Fit on demand, as the other boards do.
183
+ useEffect(() => {
184
+ if (fitKey === undefined)
185
+ return;
186
+ const rect = svgRef.current?.getBoundingClientRect();
187
+ if (!rect || layout.participants.length === 0)
188
+ return;
189
+ onViewportChange(fitToBoxes([{ x: 0, y: 0, width: layout.width, height: layout.height }], rect.width, rect.height, { padding: 16 }));
190
+ // eslint-disable-next-line react-hooks/exhaustive-deps
191
+ }, [fitKey]);
192
+ useEffect(() => {
193
+ const svg = svgRef.current;
194
+ if (!svg)
195
+ return;
196
+ const onWheel = (e) => {
197
+ e.preventDefault();
198
+ const vp = viewportRef.current;
199
+ const dx = wheelPixels(e.deltaX, e.deltaMode);
200
+ const dy = wheelPixels(e.deltaY, e.deltaMode);
201
+ if (e.ctrlKey || e.metaKey) {
202
+ onViewportChange(zoomAt(vp, Math.exp(-dy * 0.0025), toCanvasPoint(e.clientX, e.clientY)));
203
+ return;
204
+ }
205
+ const moveX = e.shiftKey ? -(dx || dy) : -dx;
206
+ const moveY = e.shiftKey ? 0 : -dy;
207
+ if (moveX !== 0 || moveY !== 0)
208
+ onViewportChange(panBy(vp, moveX, moveY));
209
+ };
210
+ svg.addEventListener("wheel", onWheel, { passive: false });
211
+ return () => svg.removeEventListener("wheel", onWheel);
212
+ }, [onViewportChange, toCanvasPoint]);
213
+ const pinchState = () => {
214
+ const pts = [...pointersRef.current.values()];
215
+ if (pts.length < 2)
216
+ return null;
217
+ const [a, b] = pts;
218
+ return { distance: Math.hypot(b.x - a.x, b.y - a.y) || 1, mid: { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 } };
219
+ };
220
+ const onPointerDown = (e, target) => {
221
+ if (e.button !== 0 && e.pointerType === "mouse")
222
+ return;
223
+ e.stopPropagation();
224
+ svgRef.current?.setPointerCapture(e.pointerId);
225
+ pointersRef.current.set(e.pointerId, toCanvasPoint(e.clientX, e.clientY));
226
+ if (pointersRef.current.size >= 2) {
227
+ gestureRef.current = null;
228
+ pinchRef.current = pinchState();
229
+ return;
230
+ }
231
+ gestureRef.current = {
232
+ pointerId: e.pointerId,
233
+ startX: e.clientX,
234
+ startY: e.clientY,
235
+ lastX: e.clientX,
236
+ lastY: e.clientY,
237
+ target,
238
+ moved: false,
239
+ };
240
+ };
241
+ const onPointerMove = (e) => {
242
+ if (pointersRef.current.has(e.pointerId))
243
+ pointersRef.current.set(e.pointerId, toCanvasPoint(e.clientX, e.clientY));
244
+ if (pinchRef.current) {
245
+ const next = pinchState();
246
+ if (!next)
247
+ return;
248
+ const prev = pinchRef.current;
249
+ const panned = panBy(viewportRef.current, next.mid.x - prev.mid.x, next.mid.y - prev.mid.y);
250
+ onViewportChange(zoomAt(panned, next.distance / prev.distance, next.mid));
251
+ pinchRef.current = next;
252
+ return;
253
+ }
254
+ const g = gestureRef.current;
255
+ if (!g || g.pointerId !== e.pointerId)
256
+ return;
257
+ if (!g.moved && Math.hypot(e.clientX - g.startX, e.clientY - g.startY) < DRAG_THRESHOLD)
258
+ return;
259
+ g.moved = true;
260
+ onViewportChange(panBy(viewportRef.current, e.clientX - g.lastX, e.clientY - g.lastY));
261
+ g.lastX = e.clientX;
262
+ g.lastY = e.clientY;
263
+ };
264
+ const onPointerUp = (e) => {
265
+ pointersRef.current.delete(e.pointerId);
266
+ if (pinchRef.current) {
267
+ if (pointersRef.current.size < 2)
268
+ pinchRef.current = null;
269
+ return;
270
+ }
271
+ const g = gestureRef.current;
272
+ if (!g || g.pointerId !== e.pointerId)
273
+ return;
274
+ gestureRef.current = null;
275
+ if (g.moved)
276
+ return;
277
+ if (g.target)
278
+ onSelect?.(g.target.kind, g.target.id);
279
+ else
280
+ onClearSelection?.();
281
+ };
282
+ const menu = (target) => (e) => {
283
+ if (!onContextMenu)
284
+ return;
285
+ e.preventDefault();
286
+ e.stopPropagation();
287
+ onContextMenu(e.clientX, e.clientY, target);
288
+ };
289
+ const errors = new Set(errorElements ?? []);
290
+ const warnings = new Set(warningElements ?? []);
291
+ const isSel = (kind, id) => selection?.kind === kind && selection.id === id;
292
+ const selectedMessage = selection?.kind === "message" ? messages.get(selection.id) : undefined;
293
+ return (_jsxs("div", { className: `slc-pane${className ? ` ${className}` : ""}`, style: { ...themeStyle(theme), ...style }, children: [_jsx("svg", { ref: svgRef, id: svgId, className: "slc-surface", onPointerDown: (e) => onPointerDown(e), onPointerMove: onPointerMove, onPointerUp: onPointerUp, onPointerCancel: onPointerUp, onContextMenu: menu({ kind: "canvas" }), children: _jsxs("g", { transform: viewportTransform(viewport), children: [layout.fragments.map((box) => {
294
+ const f = definition.fragments?.[box.index];
295
+ if (!f)
296
+ return null;
297
+ const heading = `${f.kind} · after ${f.after} · ${f.label}`;
298
+ const tabW = textWidth(heading, LABEL_SIZE) + 18;
299
+ const top = box.top;
300
+ return (_jsxs("g", { className: "slc-sqd-fragment", children: [f.notes?.trim() && _jsx("title", { children: `Notes: ${f.notes}` }), _jsx("rect", { x: box.left, y: top, width: box.width, height: box.height, rx: 3, className: "slc-sqd-frame" }), _jsx("path", { d: `M ${box.left} ${top + 22} L ${box.left} ${top} L ${box.left + tabW} ${top} L ${box.left + tabW} ${top + 15} L ${box.left + tabW - 7} ${top + 22} Z`, className: "slc-sqd-frame-tab" }), _jsxs("text", { x: box.left + 8, y: top + 15, className: "slc-sqd-frame-heading", children: [_jsx("tspan", { className: "slc-sqd-frame-kind", children: f.kind }), ` · after ${f.after} · ${f.label}`] }), f.notes?.trim() && (_jsx("rect", { x: box.left + tabW + 6, y: top + 7, width: 13, height: 5, rx: 1.5, className: "slc-note-mark" }))] }, `f${box.index}`));
301
+ }), layout.participants.map((box) => {
302
+ const selected = isSel("participant", box.name);
303
+ return (_jsxs("g", { onPointerDown: (e) => onPointerDown(e, { kind: "participant", id: box.name }), children: [_jsx("path", { d: `M ${box.x} ${layout.lifelineTop} V ${layout.lifelineBottom}`, className: "slc-sqd-hit" }), _jsx("path", { d: `M ${box.x} ${layout.lifelineTop} V ${layout.lifelineBottom}`, className: `slc-sqd-lifeline${selected ? " slc-sqd-lifeline--selected" : ""}` })] }, `l-${box.name}`));
304
+ }), layout.fragments.map((box) => {
305
+ const f = definition.fragments?.[box.index];
306
+ const anchor = f && f.after > 0 ? layout.rows.find((r) => r.fragment === null && r.index === f.after - 1) : undefined;
307
+ if (!anchor)
308
+ return null;
309
+ const x = box.left + 4;
310
+ return (_jsx("path", { d: `M ${Math.min(anchor.fromX, anchor.toX) - 14} ${anchor.y} H ${x} V ${box.top}`, className: "slc-sqd-branch" }, `fa${box.index}`));
311
+ }), layout.rows.map((row) => {
312
+ const m = messages.get(row.ref);
313
+ if (!m)
314
+ return null;
315
+ const focus = `message:${row.ref}`;
316
+ const selected = isSel("message", row.ref);
317
+ const error = errors.has(focus);
318
+ const warn = !error && warnings.has(focus);
319
+ const lineClass = [
320
+ "slc-sqd-line",
321
+ m.reply ? "slc-sqd-line--reply" : "",
322
+ m.optional ? "slc-sqd-line--optional" : "",
323
+ error ? "slc-sqd-line--error" : warn ? "slc-sqd-line--warn" : "",
324
+ selected ? "slc-sqd-line--selected" : "",
325
+ ]
326
+ .filter(Boolean)
327
+ .join(" ");
328
+ const headClass = `slc-sqd-head${m.reply ? " slc-sqd-head--open" : ""}${selected ? " slc-sqd-head--selected" : error ? " slc-sqd-head--error" : ""}`;
329
+ // The words, measured: ref, label, then the chips that follow it.
330
+ const refText = row.ref;
331
+ const refW = textWidth(refText, REF_SIZE) + 8;
332
+ const labelW = measured[`${row.ref}:label`] ?? textWidth(m.label ?? "", LABEL_SIZE);
333
+ const optW = m.optional ? textWidth("opt", CHIP_SIZE) + 8 : 0;
334
+ const chipW = m.event ? (measured[`${row.ref}:event`] ?? m.event.length * 6.1) + 12 : 0;
335
+ const stateText = m.state ? `→ ${m.state}` : "";
336
+ const stateW = m.state ? (measured[`${row.ref}:state`] ?? textWidth(stateText, LABEL_SIZE)) : 0;
337
+ const gap = 5;
338
+ const total = refW + gap + labelW + (optW ? gap + optW : 0) + (chipW ? gap + chipW : 0) + (stateW ? gap + stateW : 0);
339
+ let startX;
340
+ let baseline;
341
+ let geometry;
342
+ let hit;
343
+ if (row.self) {
344
+ const x = row.fromX;
345
+ const top = row.y - LOOP_H / 2 - 2;
346
+ const bottom = top + LOOP_H;
347
+ geometry = (_jsxs(_Fragment, { children: [_jsx("path", { d: `M ${x} ${top} H ${x + LOOP_W} V ${bottom} H ${x + 2}`, className: lineClass }), _jsx("path", { d: arrowHead(x + 1, bottom, -1, !!m.reply), className: headClass })] }));
348
+ startX = x + LOOP_W + 8;
349
+ baseline = row.y + 2;
350
+ hit = { x: x - 6, y: top - 8, w: LOOP_W + 14 + total, h: LOOP_H + 16 };
351
+ }
352
+ else {
353
+ const dir = row.toX >= row.fromX ? 1 : -1;
354
+ const lineEnd = row.toX - dir * 1;
355
+ geometry = (_jsxs(_Fragment, { children: [_jsx("path", { d: `M ${row.fromX} ${row.y} H ${lineEnd}`, className: lineClass }), _jsx("path", { d: arrowHead(lineEnd, row.y, dir, !!m.reply), className: headClass })] }));
356
+ const mid = (row.fromX + row.toX) / 2;
357
+ startX = mid - total / 2;
358
+ baseline = row.y - 6;
359
+ const left = Math.min(row.fromX, row.toX, startX);
360
+ const right = Math.max(row.fromX, row.toX, startX + total);
361
+ hit = { x: left - 4, y: row.y - 22, w: right - left + 8, h: 30 };
362
+ }
363
+ let cursor = startX;
364
+ const place = (w) => {
365
+ const at = cursor;
366
+ cursor += w + gap;
367
+ return at;
368
+ };
369
+ const refX = place(refW);
370
+ const labelX = place(labelW);
371
+ const optX = optW ? place(optW) : 0;
372
+ const chipX = chipW ? place(chipW) : 0;
373
+ const stateX = stateW ? place(stateW) : 0;
374
+ return (_jsxs("g", { className: "slc-sqd-message", onPointerDown: (e) => onPointerDown(e, { kind: "message", id: row.ref }), onContextMenu: menu({ kind: "message", id: row.ref }), children: [_jsx("title", { children: messageTitle(row.ref, m) }), _jsx("rect", { x: hit.x, y: hit.y, width: hit.w, height: hit.h, className: "slc-sqd-hitbox" }), selected && _jsx("rect", { x: hit.x, y: hit.y, width: hit.w, height: hit.h, rx: 4, className: "slc-sqd-selected-plate" }), geometry, _jsx("rect", { x: refX, y: baseline - 10, width: refW - 2, height: 13, rx: 6.5, className: `slc-sqd-ref-plate${selected ? " slc-sqd-ref-plate--selected" : ""}` }), _jsx("text", { x: refX + (refW - 2) / 2, y: baseline, textAnchor: "middle", className: "slc-sqd-ref", children: refText }), _jsx("text", { ref: measureRef(`${row.ref}:label`), x: labelX, y: baseline, className: `slc-sqd-label${selected ? " slc-sqd-label--selected" : ""}${error ? " slc-sqd-label--error" : ""}`, children: m.label }), optW > 0 && (_jsxs(_Fragment, { children: [_jsx("rect", { x: optX, y: baseline - 10, width: optW, height: 13, rx: 3, className: "slc-sqd-opt" }), _jsx("text", { x: optX + optW / 2, y: baseline - 0.5, textAnchor: "middle", className: "slc-sqd-opt-text", children: "opt" })] })), chipW > 0 && (_jsxs(_Fragment, { children: [_jsx("rect", { x: chipX, y: baseline - 10.5, width: chipW, height: 14, rx: 7, className: "slc-sqd-event" }), _jsx("text", { ref: measureRef(`${row.ref}:event`), x: chipX + chipW / 2, y: baseline - 0.5, textAnchor: "middle", className: "slc-sqd-event-text", children: m.event })] })), stateW > 0 && (_jsx("text", { ref: measureRef(`${row.ref}:state`), x: stateX, y: baseline, className: "slc-sqd-state", children: stateText })), m.notes?.trim() && (_jsx("rect", { x: cursor - gap + 3, y: baseline - 9, width: 5, height: 11, rx: 1.5, className: "slc-note-mark" }))] }, `m-${row.ref}`));
375
+ }), layout.participants.map((box) => {
376
+ const p = participants.get(box.name);
377
+ if (!p)
378
+ return null;
379
+ const focus = `participant:${box.name}`;
380
+ const selected = isSel("participant", box.name) || (!!selectedMessage && (selectedMessage.from === box.name || selectedMessage.to === box.name));
381
+ const cls = [
382
+ "slc-node",
383
+ "slc-sqd-header",
384
+ isSel("participant", box.name) ? "slc-node--selected" : selected ? "slc-sqd-header--involved" : "",
385
+ errors.has(focus) ? "slc-node--error" : "",
386
+ ]
387
+ .filter(Boolean)
388
+ .join(" ");
389
+ const kind = p.actor ? "actor" : p.object ? "object" : p.service ? "service" : "";
390
+ return (_jsxs("g", { className: "slc-node--static slc-sqd-participant", onPointerDown: (e) => onPointerDown(e, { kind: "participant", id: box.name }), onContextMenu: menu({ kind: "participant", id: box.name }), children: [participantTitle(p) && _jsx("title", { children: participantTitle(p) }), _jsx("rect", { x: box.left, y: box.top, width: box.width, height: box.height, rx: p.actor ? box.height / 2 : 4, className: cls }), p.notes?.trim() && (_jsx("rect", { x: box.left + box.width - 24, y: box.top - 5, width: 13, height: 5, rx: 1.5, className: "slc-note-mark" })), _jsx("text", { x: box.x, y: box.top + box.height / 2 + (kind ? 1 : 4), textAnchor: "middle", className: `slc-node-name slc-sqd-name${p.object ? " slc-sqd-name--object" : ""}`, children: box.name }), kind && (_jsxs("text", { x: box.x, y: box.top + box.height - 4, textAnchor: "middle", className: "slc-sqd-kind", children: [kind === "object" ? `:${p.object}` : kind === "service" ? "service" : "actor", p.holds?.length ? ` · holds ${p.holds.length}` : ""] }))] }, `p-${box.name}`));
391
+ })] }) }), layout.participants.length === 0 && emptyHint && _jsx("div", { className: "slc-erd-empty", children: emptyHint })] }));
392
+ }
393
+ export default SequenceCanvas;
394
+ //# sourceMappingURL=SequenceCanvas.js.map
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The words of the step on stage, and the buttons that move a tour (Spec 83).
3
+ *
4
+ * A card over the bottom of the board: who is presenting, the tour and the
5
+ * step's title, what the agent says, where the tour stands. The controls are
6
+ * the person's: back, play or pause, forward, the voice on or off, answer
7
+ * (the host opens a mark on what is lit), close. Nothing here plays anything;
8
+ * the buttons call the host, which holds the stage session.
9
+ */
10
+ import type { CSSProperties } from "react";
11
+ import type { TourStep } from "@miadi/stateloom-protocol";
12
+ import { type CanvasTheme } from "./theme.js";
13
+ export interface StageCaptionProps {
14
+ shown: {
15
+ step: TourStep;
16
+ index: number | null;
17
+ count: number | null;
18
+ title?: string;
19
+ origin?: string;
20
+ } | null;
21
+ playing?: boolean;
22
+ speaking?: boolean;
23
+ /** The canvas's voice is on. Absent: no voice button. */
24
+ voice?: boolean;
25
+ onToggleVoice?: () => void;
26
+ onPlay?: () => void;
27
+ onPause?: () => void;
28
+ onNext?: () => void;
29
+ onPrev?: () => void;
30
+ onGoto?: (index: number) => void;
31
+ onClose?: () => void;
32
+ /** Answer what is lit: the host opens a mark on it. Absent: no answer button. */
33
+ onAnswer?: () => void;
34
+ theme?: Partial<CanvasTheme>;
35
+ className?: string;
36
+ style?: CSSProperties;
37
+ }
38
+ export declare function StageCaption({ shown, playing, speaking, voice, onToggleVoice, onPlay, onPause, onNext, onPrev, onGoto, onClose, onAnswer, theme, className, style, }: StageCaptionProps): import("react").JSX.Element | null;
39
+ export default StageCaption;
@@ -0,0 +1,15 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { themeStyle } from "./theme.js";
3
+ import { CloseIcon, NextIcon, PauseIcon, PlayIcon, PrevIcon, SpeakerIcon, SpeakerOffIcon } from "./icons.js";
4
+ /** Past this many steps the dots give way to the count alone. */
5
+ const MAX_DOTS = 24;
6
+ export function StageCaption({ shown, playing = false, speaking = false, voice, onToggleVoice, onPlay, onPause, onNext, onPrev, onGoto, onClose, onAnswer, theme, className, style, }) {
7
+ if (!shown)
8
+ return null;
9
+ const { step, index, count, title, origin } = shown;
10
+ const inTour = index !== null && count !== null;
11
+ const heading = [title, step.title].filter(Boolean).join(" · ");
12
+ return (_jsxs("section", { className: `slc-stage-caption${className ? ` ${className}` : ""}`, style: { ...themeStyle(theme), ...style }, role: "region", "aria-label": "What the agent is showing", "aria-live": "polite", children: [_jsxs("header", { className: "slc-stage-caption-head", children: [origin && _jsx("span", { className: "slc-stage-caption-origin", children: origin }), heading && _jsx("span", { className: "slc-stage-caption-title", children: heading }), inTour && (_jsxs("span", { className: "slc-stage-caption-count", children: [index + 1, " / ", count] })), speaking && _jsx("span", { className: "slc-stage-caption-speaking", "aria-label": "speaking" }), onClose && (_jsx("button", { type: "button", className: "slc-stage-btn slc-stage-btn--quiet", onClick: onClose, "aria-label": "Close", title: "Close", children: _jsx(CloseIcon, {}) }))] }), _jsx("p", { className: "slc-stage-caption-say", children: step.say }), inTour && count <= MAX_DOTS && count > 1 && (_jsx("nav", { className: "slc-stage-dots", "aria-label": "Steps", children: Array.from({ length: count }, (_, i) => (_jsx("button", { type: "button", className: `slc-stage-dot${i === index ? " slc-stage-dot--current" : i < index ? " slc-stage-dot--seen" : ""}`, onClick: () => onGoto?.(i), "aria-label": `Step ${i + 1}`, "aria-current": i === index ? "step" : undefined }, i))) })), _jsxs("footer", { className: "slc-stage-caption-controls", children: [inTour && (_jsxs(_Fragment, { children: [_jsx("button", { type: "button", className: "slc-stage-btn", onClick: onPrev, disabled: index === 0, "aria-label": "Previous step", title: "Previous step", children: _jsx(PrevIcon, {}) }), playing ? (_jsx("button", { type: "button", className: "slc-stage-btn slc-stage-btn--main", onClick: onPause, "aria-label": "Pause", title: "Pause", children: _jsx(PauseIcon, {}) })) : (_jsx("button", { type: "button", className: "slc-stage-btn slc-stage-btn--main", onClick: onPlay, "aria-label": "Play", title: "Play", children: _jsx(PlayIcon, {}) })), _jsx("button", { type: "button", className: "slc-stage-btn", onClick: onNext, disabled: index === count - 1, "aria-label": "Next step", title: "Next step", children: _jsx(NextIcon, {}) })] })), _jsx("span", { className: "slc-stage-spacer" }), voice !== undefined && (_jsx("button", { type: "button", className: `slc-stage-btn${voice ? " slc-stage-btn--on" : ""}`, onClick: onToggleVoice, "aria-pressed": voice, title: voice ? "Voice on — the steps are read aloud" : "Voice off — the steps are read on screen", children: voice ? _jsx(SpeakerIcon, {}) : _jsx(SpeakerOffIcon, {}) })), onAnswer && (_jsx("button", { type: "button", className: "slc-stage-btn slc-stage-btn--answer", onClick: onAnswer, title: "Answer \u2014 mark what is lit and say something about it", children: "Answer" }))] })] }));
13
+ }
14
+ export default StageCaption;
15
+ //# sourceMappingURL=StageCaption.js.map
@@ -0,0 +1,54 @@
1
+ /**
2
+ * The stage's layer over a canvas (Spec 83) — any of the three boards, or any
3
+ * host's board that shares a viewport.
4
+ *
5
+ * It never reaches into the canvas under it. It is told the viewport and where
6
+ * the elements are (`machineElementBoxes`, `erdElementBoxes`,
7
+ * `sequenceElementBoxes` from the protocol), and from those alone it:
8
+ *
9
+ * - **lights** what an agent points at: the rest of the drawing dims behind a
10
+ * scrim with a hole around each spotlighted element, and each hole is ringed;
11
+ * - **frames** an area the agent names;
12
+ * - **pins** each mark at what it points at, numbered, coloured by whether it
13
+ * waits (open), was answered, or is done — a tap opens its thread;
14
+ * - **takes a mark** when the host turns marking on: a tap names the element
15
+ * under it, a drag names the elements inside the area drawn (and the area).
16
+ *
17
+ * Positioned over the canvas by the host (both in one `position: relative`
18
+ * box); it lets every pointer through to the canvas except on its pins and
19
+ * while marking.
20
+ */
21
+ import { type CSSProperties } from "react";
22
+ import { type Box, type ElementBox, type Mark, type Viewport } from "@miadi/stateloom-protocol";
23
+ import { type CanvasTheme } from "./theme.js";
24
+ /** What a person pointed at while marking, before they say anything about it. */
25
+ export interface MarkDraft {
26
+ elements: string[];
27
+ region?: Box;
28
+ }
29
+ export interface StageOverlayProps {
30
+ viewport: Viewport;
31
+ /** Where the drawn elements are, in the drawing's coordinates. */
32
+ boxes: readonly ElementBox[];
33
+ /** Elements to light; the rest dims. */
34
+ spotlight?: readonly string[];
35
+ /** An area to frame. */
36
+ region?: Box | null;
37
+ marks?: readonly Mark[];
38
+ selectedMark?: string | null;
39
+ onSelectMark?: (id: string) => void;
40
+ /** Resolved marks keep no pin. Default true. */
41
+ hideResolved?: boolean;
42
+ /** Take the next tap or drag as a mark. */
43
+ marking?: boolean;
44
+ onDraft?: (draft: MarkDraft) => void;
45
+ /** A mark being written: its elements ringed, its area framed. */
46
+ draft?: MarkDraft | null;
47
+ theme?: Partial<CanvasTheme>;
48
+ className?: string;
49
+ style?: CSSProperties;
50
+ }
51
+ /** Where a mark sits: its elements that are drawn here, else its area. */
52
+ export declare function markAnchor(mark: Pick<Mark, "elements" | "region">, boxes: readonly ElementBox[]): Box | null;
53
+ export declare function StageOverlay({ viewport, boxes, spotlight, region, marks, selectedMark, onSelectMark, hideResolved, marking, onDraft, draft, theme, className, style, }: StageOverlayProps): import("react").JSX.Element;
54
+ export default StageOverlay;
@@ -0,0 +1,121 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ /**
3
+ * The stage's layer over a canvas (Spec 83) — any of the three boards, or any
4
+ * host's board that shares a viewport.
5
+ *
6
+ * It never reaches into the canvas under it. It is told the viewport and where
7
+ * the elements are (`machineElementBoxes`, `erdElementBoxes`,
8
+ * `sequenceElementBoxes` from the protocol), and from those alone it:
9
+ *
10
+ * - **lights** what an agent points at: the rest of the drawing dims behind a
11
+ * scrim with a hole around each spotlighted element, and each hole is ringed;
12
+ * - **frames** an area the agent names;
13
+ * - **pins** each mark at what it points at, numbered, coloured by whether it
14
+ * waits (open), was answered, or is done — a tap opens its thread;
15
+ * - **takes a mark** when the host turns marking on: a tap names the element
16
+ * under it, a drag names the elements inside the area drawn (and the area).
17
+ *
18
+ * Positioned over the canvas by the host (both in one `position: relative`
19
+ * box); it lets every pointer through to the canvas except on its pins and
20
+ * while marking.
21
+ */
22
+ import { useId, useMemo, useRef, useState } from "react";
23
+ import { boxesOf, elementAt, elementsInRegion, padBox, screenToWorld, unionBox, viewportTransform, worldToScreen, } from "@miadi/stateloom-protocol";
24
+ import { themeStyle } from "./theme.js";
25
+ /** Below this many screen pixels a press is a tap, not an area. */
26
+ const DRAG_THRESHOLD = 6;
27
+ /** A tap on empty board marks a square this many screen pixels wide around it. */
28
+ const TAP_AREA = 56;
29
+ const HOLE_PAD = 8;
30
+ /** Where a mark sits: its elements that are drawn here, else its area. */
31
+ export function markAnchor(mark, boxes) {
32
+ const drawn = mark.elements?.length ? boxesOf(boxes, mark.elements) : [];
33
+ return unionBox(drawn) ?? mark.region ?? null;
34
+ }
35
+ function pinTone(mark) {
36
+ if (mark.status === "resolved")
37
+ return "resolved";
38
+ if (mark.author.role === "agent")
39
+ return mark.status === "answered" ? "answered" : "question";
40
+ return mark.status === "answered" ? "answered" : "open";
41
+ }
42
+ export function StageOverlay({ viewport, boxes, spotlight, region, marks, selectedMark = null, onSelectMark, hideResolved = true, marking = false, onDraft, draft = null, theme, className, style, }) {
43
+ const maskId = `slc-stage-mask-${useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;
44
+ const rootRef = useRef(null);
45
+ const press = useRef(null);
46
+ const [drag, setDrag] = useState(null);
47
+ const holes = useMemo(() => (spotlight?.length ? boxesOf(boxes, spotlight).map((b) => padBox(b, HOLE_PAD)) : []), [boxes, spotlight]);
48
+ const vt = viewportTransform(viewport);
49
+ const selected = marks?.find((m) => m.id === selectedMark) ?? null;
50
+ const ringed = useMemo(() => {
51
+ const out = [];
52
+ if (selected?.elements?.length)
53
+ out.push(...boxesOf(boxes, selected.elements));
54
+ if (draft?.elements.length)
55
+ out.push(...boxesOf(boxes, draft.elements));
56
+ return out.map((b) => padBox(b, 4));
57
+ }, [boxes, selected, draft]);
58
+ const framed = [selected?.region, draft?.region].filter((b) => !!b);
59
+ const pins = (marks ?? [])
60
+ .map((m, i) => ({ mark: m, n: i + 1 }))
61
+ .filter(({ mark }) => !(hideResolved && mark.status === "resolved" && mark.id !== selectedMark))
62
+ .map(({ mark, n }) => {
63
+ const at = markAnchor(mark, boxes);
64
+ if (!at)
65
+ return null;
66
+ const p = worldToScreen(viewport, { x: at.x + at.width, y: at.y });
67
+ return { mark, n, x: p.x, y: p.y };
68
+ })
69
+ .filter((p) => p !== null);
70
+ const local = (e) => {
71
+ const r = rootRef.current?.getBoundingClientRect();
72
+ return { x: e.clientX - (r?.left ?? 0), y: e.clientY - (r?.top ?? 0) };
73
+ };
74
+ const onDown = (e) => {
75
+ if (e.button !== 0 && e.pointerType === "mouse")
76
+ return;
77
+ e.currentTarget.setPointerCapture(e.pointerId);
78
+ const p = local(e);
79
+ press.current = { id: e.pointerId, x: p.x, y: p.y, moved: false };
80
+ };
81
+ const onMove = (e) => {
82
+ const s = press.current;
83
+ if (!s || s.id !== e.pointerId)
84
+ return;
85
+ const p = local(e);
86
+ if (!s.moved && Math.hypot(p.x - s.x, p.y - s.y) < DRAG_THRESHOLD)
87
+ return;
88
+ s.moved = true;
89
+ setDrag({ x: Math.min(s.x, p.x), y: Math.min(s.y, p.y), w: Math.abs(p.x - s.x), h: Math.abs(p.y - s.y) });
90
+ };
91
+ const onUp = (e) => {
92
+ const s = press.current;
93
+ if (!s || s.id !== e.pointerId)
94
+ return;
95
+ press.current = null;
96
+ setDrag(null);
97
+ const p = local(e);
98
+ if (s.moved) {
99
+ const a = screenToWorld(viewport, { x: Math.min(s.x, p.x), y: Math.min(s.y, p.y) });
100
+ const b = screenToWorld(viewport, { x: Math.max(s.x, p.x), y: Math.max(s.y, p.y) });
101
+ const area = { x: a.x, y: a.y, width: Math.max(1, b.x - a.x), height: Math.max(1, b.y - a.y) };
102
+ onDraft?.({ elements: elementsInRegion(boxes, area), region: area });
103
+ return;
104
+ }
105
+ const w = screenToWorld(viewport, p);
106
+ const hit = elementAt(boxes, w.x, w.y);
107
+ if (hit)
108
+ return onDraft?.({ elements: [hit] });
109
+ const half = TAP_AREA / 2 / (viewport.scale || 1);
110
+ onDraft?.({ elements: [], region: { x: w.x - half, y: w.y - half, width: half * 2, height: half * 2 } });
111
+ };
112
+ return (_jsxs("div", { ref: rootRef, className: `slc-stage${marking ? " slc-stage--marking" : ""}${className ? ` ${className}` : ""}`, style: { ...themeStyle(theme), ...style }, children: [_jsxs("svg", { className: "slc-stage-svg", "aria-hidden": "true", children: [holes.length > 0 && (_jsxs(_Fragment, { children: [_jsx("defs", { children: _jsxs("mask", { id: maskId, maskUnits: "userSpaceOnUse", x: "0", y: "0", width: "100%", height: "100%", children: [_jsx("rect", { x: "0", y: "0", width: "100%", height: "100%", fill: "white" }), _jsx("g", { transform: vt, children: holes.map((b, i) => (_jsx("rect", { x: b.x, y: b.y, width: b.width, height: b.height, rx: 10, fill: "black" }, i))) })] }) }), _jsx("rect", { x: "0", y: "0", width: "100%", height: "100%", className: "slc-stage-scrim", mask: `url(#${maskId})` }), _jsx("g", { transform: vt, children: holes.map((b, i) => (_jsx("rect", { x: b.x, y: b.y, width: b.width, height: b.height, rx: 10, className: "slc-stage-ring", vectorEffect: "non-scaling-stroke" }, i))) })] })), _jsxs("g", { transform: vt, children: [region && (_jsx("rect", { x: region.x, y: region.y, width: region.width, height: region.height, rx: 6, className: "slc-stage-region", vectorEffect: "non-scaling-stroke" })), ringed.map((b, i) => (_jsx("rect", { x: b.x, y: b.y, width: b.width, height: b.height, rx: 8, className: "slc-stage-mark-ring", vectorEffect: "non-scaling-stroke" }, `r${i}`))), framed.map((b, i) => (_jsx("rect", { x: b.x, y: b.y, width: b.width, height: b.height, rx: 4, className: "slc-stage-mark-area", vectorEffect: "non-scaling-stroke" }, `f${i}`)))] }), drag && _jsx("rect", { x: drag.x, y: drag.y, width: drag.w, height: drag.h, rx: 4, className: "slc-stage-drag" })] }), pins.map(({ mark, n, x, y }) => (_jsxs("button", { type: "button", className: `slc-stage-pin slc-stage-pin--${pinTone(mark)}${mark.id === selectedMark ? " slc-stage-pin--selected" : ""}`, style: { left: x, top: y }, title: `${mark.author.name}: ${mark.text}${mark.replies?.length ? ` (${mark.replies.length} repl${mark.replies.length === 1 ? "y" : "ies"})` : ""}`, "aria-label": `Mark ${n}, ${mark.status}: ${mark.text}`, onPointerDown: (e) => e.stopPropagation(), onClick: (e) => {
113
+ e.stopPropagation();
114
+ onSelectMark?.(mark.id);
115
+ }, children: [n, (mark.replies?.length ?? 0) > 0 && _jsx("span", { className: "slc-stage-pin-count", children: mark.replies.length })] }, mark.id))), marking && (_jsx("div", { className: "slc-stage-catch", onPointerDown: onDown, onPointerMove: onMove, onPointerUp: onUp, onPointerCancel: () => {
116
+ press.current = null;
117
+ setDrag(null);
118
+ } }))] }));
119
+ }
120
+ export default StageOverlay;
121
+ //# sourceMappingURL=StageOverlay.js.map