@tdacorp/hyle-sdk 0.3.0 → 0.5.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.
Files changed (37) hide show
  1. package/README.md +92 -3
  2. package/bin/hyle-sdk-check-routes.mjs +3 -0
  3. package/dist/check-routes-bin.js +389 -0
  4. package/dist/chunk-4OB77ZOD.js +455 -0
  5. package/dist/chunk-BUJFMR3M.js +38 -0
  6. package/dist/{chunk-7VCMJUPC.js → chunk-OW6S7IZX.js} +1 -1
  7. package/dist/{chunk-EARQBSMF.js → chunk-SO6H2UGL.js} +102 -4
  8. package/dist/diagram-viewer-DYX6R63Y.js +1132 -0
  9. package/dist/index.cjs +191 -20
  10. package/dist/index.d.cts +95 -3
  11. package/dist/index.d.ts +95 -3
  12. package/dist/index.js +13 -1
  13. package/dist/mermaid-diagram.cjs +1267 -16
  14. package/dist/mermaid-diagram.d.cts +39 -1
  15. package/dist/mermaid-diagram.d.ts +39 -1
  16. package/dist/mermaid-diagram.js +35 -5
  17. package/dist/next.cjs +266 -26
  18. package/dist/next.d.cts +51 -5
  19. package/dist/next.d.ts +51 -5
  20. package/dist/next.js +131 -5
  21. package/dist/react.cjs +102 -4
  22. package/dist/react.d.cts +44 -4
  23. package/dist/react.d.ts +44 -4
  24. package/dist/react.js +1 -1
  25. package/dist/{resolve-fMx2W8RR.d.ts → resolve-1rQntRBh.d.ts} +1 -1
  26. package/dist/{resolve-B_p0p4Zn.d.cts → resolve-36-Ng1H0.d.cts} +1 -1
  27. package/dist/styles.css +76 -0
  28. package/dist/{types-CBvLhUPr.d.ts → types-BoyBWF2F.d.ts} +1 -1
  29. package/dist/{types-DjXf6iPo.d.cts → types-CwBCPh6K.d.cts} +20 -1
  30. package/dist/{types-DjXf6iPo.d.ts → types-CwBCPh6K.d.ts} +20 -1
  31. package/dist/{types-D0qoLh4E.d.cts → types-DnPzhrFx.d.cts} +1 -1
  32. package/dist/use-cache.cjs +34 -20
  33. package/dist/use-cache.d.cts +2 -2
  34. package/dist/use-cache.d.ts +2 -2
  35. package/dist/use-cache.js +2 -2
  36. package/package.json +5 -1
  37. package/dist/chunk-HFUJRNFP.js +0 -290
@@ -0,0 +1,1132 @@
1
+ import {
2
+ fill
3
+ } from "./chunk-BUJFMR3M.js";
4
+
5
+ // src/react/viewer/diagram-viewer.tsx
6
+ import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
7
+
8
+ // src/react/viewer/extract.ts
9
+ var tokens = (el) => (el.getAttribute("class") ?? "").split(/\s+/).filter(Boolean);
10
+ var tag = (el) => el.tagName.toLowerCase();
11
+ var kids = (el) => Array.from(el.children);
12
+ var num = (el, name) => Number.parseFloat(el.getAttribute(name) ?? "") || 0;
13
+ var clean = (s) => (s ?? "").replace(/\s+/g, " ").trim();
14
+ var numbers = (s) => (s.match(/-?\d*\.?\d+(?:e-?\d+)?/gi) ?? []).map(Number);
15
+ function translateOf(el) {
16
+ const m = /translate\(\s*(-?[\d.e+-]+)[\s,]*(-?[\d.e+-]+)?\s*\)/i.exec(el.getAttribute("transform") ?? "");
17
+ return m ? [Number(m[1]), Number(m[2] ?? 0)] : [0, 0];
18
+ }
19
+ var SHAPES = /* @__PURE__ */ new Set(["rect", "polygon", "circle", "ellipse", "path"]);
20
+ function shapeRect(el, ox, oy) {
21
+ switch (tag(el)) {
22
+ case "rect": {
23
+ const w = num(el, "width");
24
+ const h = num(el, "height");
25
+ return w > 0 && h > 0 ? { x: ox + num(el, "x"), y: oy + num(el, "y"), w, h } : void 0;
26
+ }
27
+ case "circle":
28
+ case "ellipse": {
29
+ const rx = num(el, tag(el) === "circle" ? "r" : "rx");
30
+ const ry = num(el, tag(el) === "circle" ? "r" : "ry");
31
+ return rx > 0 && ry > 0 ? { x: ox + num(el, "cx") - rx, y: oy + num(el, "cy") - ry, w: 2 * rx, h: 2 * ry } : void 0;
32
+ }
33
+ case "polygon":
34
+ case "path": {
35
+ const n = numbers(el.getAttribute(tag(el) === "polygon" ? "points" : "d") ?? "");
36
+ const xs = n.filter((_, i) => i % 2 === 0);
37
+ const ys = n.filter((_, i) => i % 2 === 1);
38
+ if (xs.length < 2 || ys.length < 2) return void 0;
39
+ const x0 = Math.min(...xs);
40
+ const y0 = Math.min(...ys);
41
+ return { x: ox + x0, y: oy + y0, w: Math.max(...xs) - x0, h: Math.max(...ys) - y0 };
42
+ }
43
+ default:
44
+ return void 0;
45
+ }
46
+ }
47
+ function nodeBox(node, cx, cy) {
48
+ const found = [];
49
+ const visit = (el, ox, oy) => {
50
+ for (const child of kids(el)) {
51
+ const t = tokens(child);
52
+ if (t.includes("label") || tag(child) === "foreignobject" || tag(child) === "text") continue;
53
+ const [dx, dy] = translateOf(child);
54
+ const r = SHAPES.has(tag(child)) ? shapeRect(child, ox + dx, oy + dy) : void 0;
55
+ if (r) found.push(r);
56
+ else visit(child, ox + dx, oy + dy);
57
+ }
58
+ };
59
+ visit(node, 0, 0);
60
+ if (!found.length) return { x: cx - 40, y: cy - 20, w: 80, h: 40 };
61
+ const x0 = Math.min(...found.map((r) => r.x));
62
+ const y0 = Math.min(...found.map((r) => r.y));
63
+ return { x: cx + x0, y: cy + y0, w: Math.max(...found.map((r) => r.x + r.w)) - x0, h: Math.max(...found.map((r) => r.y + r.h)) - y0 };
64
+ }
65
+ var nodeKey = (id) => /^(?:flowchart|state|classId|entity|node)-(.+)-\d+$/.exec(id)?.[1] ?? id;
66
+ var dist = (r, x, y) => Math.hypot(Math.max(r.x - x, 0, x - (r.x + r.w)), Math.max(r.y - y, 0, y - (r.y + r.h)));
67
+ var GEOMETRY_SLACK = 28;
68
+ function nearest(nodes, x, y) {
69
+ let best;
70
+ let d = GEOMETRY_SLACK;
71
+ for (const n of nodes) {
72
+ const nd = dist(n.box, x, y);
73
+ if (nd < d) d = nd, best = n.key;
74
+ }
75
+ return best;
76
+ }
77
+ function endsFromId(id, keys) {
78
+ const mid = /^L_(.+)_\d+$/.exec(id)?.[1];
79
+ if (!mid) return void 0;
80
+ for (let i = mid.indexOf("_"); i !== -1; i = mid.indexOf("_", i + 1)) {
81
+ const a = mid.slice(0, i);
82
+ const b = mid.slice(i + 1);
83
+ if (keys.has(a) && keys.has(b)) return [a, b];
84
+ }
85
+ return void 0;
86
+ }
87
+ function extractGraph(root, idPrefix = "") {
88
+ const rawNodes = [];
89
+ const paths = [];
90
+ const labels = [];
91
+ const visit = (el, ox, oy, parent) => {
92
+ for (const child of kids(el)) {
93
+ const t = tokens(child);
94
+ const [dx, dy] = translateOf(child);
95
+ const raw = child.getAttribute("id") ?? "";
96
+ const id = idPrefix && raw.startsWith(idPrefix) ? raw.slice(idPrefix.length) : raw;
97
+ if (tag(child) === "g" && t.includes("node") && !t.includes("cluster") && id) {
98
+ const box = nodeBox(child, ox + dx, oy + dy);
99
+ rawNodes.push({ el: child, key: nodeKey(id), label: clean(child.textContent), box });
100
+ continue;
101
+ }
102
+ if (tag(child) === "path" && parent.includes("edgePaths")) {
103
+ paths.push({ el: child, id, d: child.getAttribute("d") ?? "", start: child.getAttribute("marker-start") ?? "", end: child.getAttribute("marker-end") ?? "" });
104
+ continue;
105
+ }
106
+ if (tag(child) === "g" && parent.includes("edgeLabels")) {
107
+ labels.push(child);
108
+ continue;
109
+ }
110
+ visit(child, ox + dx, oy + dy, [...t.filter((c) => c === "edgePaths" || c === "edgeLabels")]);
111
+ }
112
+ };
113
+ visit(root, 0, 0, []);
114
+ const keys = new Set(rawNodes.map((n) => n.key));
115
+ const edges = [];
116
+ const sameCount = labels.length === paths.length;
117
+ paths.forEach((p, i) => {
118
+ const loop = /^(.+)-cyclic-special-(1|mid|2)$/.exec(p.id);
119
+ if (loop && keys.has(loop[1])) {
120
+ if (loop[2] === "1") edges.push({ el: p.el, from: loop[1], to: loop[1], label: clean(labels[i]?.textContent ?? null) });
121
+ return;
122
+ }
123
+ let ends = endsFromId(p.id, keys);
124
+ if (!ends) {
125
+ const n = numbers(p.d);
126
+ if (n.length < 4) return;
127
+ const a = nearest(rawNodes, n[0], n[1]);
128
+ const b = nearest(rawNodes, n[n.length - 2], n[n.length - 1]);
129
+ if (a === void 0 || b === void 0) return;
130
+ ends = p.start && !p.end ? [b, a] : [a, b];
131
+ }
132
+ const labelEl = sameCount ? labels[i] : void 0;
133
+ edges.push({ el: p.el, from: ends[0], to: ends[1], label: clean(labelEl?.textContent ?? null), ...labelEl ? { labelEl } : {} });
134
+ });
135
+ return { nodes: rawNodes, edges };
136
+ }
137
+
138
+ // src/react/viewer/graph.ts
139
+ function buildGraph(nodes, edges) {
140
+ const byKey = /* @__PURE__ */ new Map();
141
+ nodes.forEach((n, i) => byKey.has(n.key) || byKey.set(n.key, i));
142
+ const out = /* @__PURE__ */ new Map();
143
+ const inn = /* @__PURE__ */ new Map();
144
+ edges.forEach((e, i) => {
145
+ out.set(e.from, [...out.get(e.from) ?? [], i]);
146
+ inn.set(e.to, [...inn.get(e.to) ?? [], i]);
147
+ });
148
+ return { nodes, edges, byKey, out, inn };
149
+ }
150
+ function walk(g, start, next, far) {
151
+ const nodes = /* @__PURE__ */ new Set();
152
+ const edges = /* @__PURE__ */ new Set();
153
+ const queue = [start];
154
+ const seen = /* @__PURE__ */ new Set([start]);
155
+ for (let head = 0; head < queue.length; head++) {
156
+ for (const i of next.get(queue[head]) ?? []) {
157
+ edges.add(i);
158
+ const other = far(g.edges[i]);
159
+ nodes.add(other);
160
+ if (!seen.has(other)) seen.add(other), queue.push(other);
161
+ }
162
+ }
163
+ return { nodes, edges };
164
+ }
165
+ function trace(g, key) {
166
+ const up = walk(g, key, g.inn, (e) => e.from);
167
+ const down = walk(g, key, g.out, (e) => e.to);
168
+ return { up: up.nodes, down: down.nodes, upEdges: up.edges, downEdges: down.edges };
169
+ }
170
+ function neighbourhood(g, key) {
171
+ const edges = /* @__PURE__ */ new Set([...g.out.get(key) ?? [], ...g.inn.get(key) ?? []]);
172
+ const nodes = /* @__PURE__ */ new Set([key]);
173
+ for (const i of edges) nodes.add(g.edges[i].from), nodes.add(g.edges[i].to);
174
+ return { nodes, edges };
175
+ }
176
+ var VEC = { up: [0, -1], down: [0, 1], left: [-1, 0], right: [1, 0] };
177
+ var centre = (b) => [b.x + b.w / 2, b.y + b.h / 2];
178
+ var CONE = 2;
179
+ function pickNeighbour(g, key, dir) {
180
+ const from = g.byKey.get(key);
181
+ if (from === void 0) return void 0;
182
+ const [cx, cy] = centre(g.nodes[from].box);
183
+ const [vx, vy] = VEC[dir];
184
+ const best = (keys, cone) => {
185
+ let pick;
186
+ let cost = Infinity;
187
+ for (const k of keys) {
188
+ const i = g.byKey.get(k);
189
+ if (i === void 0 || k === key) continue;
190
+ const [x, y] = centre(g.nodes[i].box);
191
+ const along = (x - cx) * vx + (y - cy) * vy;
192
+ const across = Math.abs((x - cx) * vy - (y - cy) * vx);
193
+ if (along <= 0 || across > along * cone) continue;
194
+ const c = along + across * 2;
195
+ if (c < cost) cost = c, pick = k;
196
+ }
197
+ return pick;
198
+ };
199
+ const adjacent = /* @__PURE__ */ new Set();
200
+ for (const i of [...g.out.get(key) ?? [], ...g.inn.get(key) ?? []]) adjacent.add(g.edges[i].from), adjacent.add(g.edges[i].to);
201
+ return best(adjacent, CONE) ?? best(adjacent, Infinity) ?? best(g.byKey.keys(), CONE);
202
+ }
203
+ function searchNodes(nodes, query) {
204
+ const q = query.trim().toLowerCase();
205
+ if (!q) return [];
206
+ return nodes.filter((n) => n.label.toLowerCase().includes(q) || n.key.toLowerCase().includes(q)).sort((a, b) => a.box.y - b.box.y || a.box.x - b.box.x).map((n) => n.key);
207
+ }
208
+ var MAX_TARGETS = 6;
209
+ function describeNode(g, key, labels) {
210
+ const node = g.nodes[g.byKey.get(key) ?? -1];
211
+ if (!node) return key;
212
+ const out = g.out.get(key) ?? [];
213
+ if (!out.length) return node.label;
214
+ const targets = out.slice(0, MAX_TARGETS).map((i) => {
215
+ const e = g.edges[i];
216
+ return e.label || g.nodes[g.byKey.get(e.to) ?? -1]?.label || e.to;
217
+ });
218
+ const more = out.length > MAX_TARGETS ? ", ..." : "";
219
+ return `${node.label}, ${out.length} ${labels.outgoing}: ${targets.join(", ")}${more}`;
220
+ }
221
+ var traceSummary = (labels, label, t) => fill(labels.tracing, { label, up: t.up.size, down: t.down.size });
222
+
223
+ // src/react/viewer/scope-svg.ts
224
+ var SEGMENT = /<style\b[^>]*>[\s\S]*?<\/style>|<[^<>]+>/gi;
225
+ var escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
226
+ var isTag = (segment) => !/^<style\b/i.test(segment);
227
+ function scopeSvg(svg, oldId, newId) {
228
+ if (!/^[\w-]+$/.test(oldId) || !/^[\w-]+$/.test(newId)) throw new Error("unsafe svg id");
229
+ const token = new RegExp(`(?<![\\w-])${escapeRe(oldId)}(?![A-Za-z0-9-])`, "g");
230
+ const rooted = svg.replace(SEGMENT, (segment) => segment.replace(token, newId));
231
+ const fresh = /* @__PURE__ */ new Map();
232
+ for (const segment of rooted.match(SEGMENT) ?? []) {
233
+ if (!isTag(segment)) continue;
234
+ for (const m of segment.matchAll(/\sid="([^"]*)"/g)) if (!m[1].startsWith(`${newId}_`) && m[1] !== newId) fresh.set(m[1], `${newId}_${m[1]}`);
235
+ }
236
+ if (!fresh.size) return rooted;
237
+ const to = (id) => fresh.get(id) ?? id;
238
+ return rooted.replace(
239
+ SEGMENT,
240
+ (segment) => !isTag(segment) ? segment : segment.replace(/(\sid=")([^"]*)"/g, (_, a, id) => `${a}${to(id)}"`).replace(/url\(#([^)"'\s]+)\)/g, (_, id) => `url(#${to(id)})`).replace(/(\s(?:xlink:)?href=")#([^"]*)"/g, (_, a, id) => `${a}#${to(id)}"`).replace(/(\saria-(?:labelledby|describedby)=")([^"]*)"/g, (_, a, ids) => `${a}${ids.split(/\s+/).map(to).join(" ")}"`)
241
+ );
242
+ }
243
+ function svgSize(svg) {
244
+ const vb = /^\s*<svg\b[^>]*?\sviewBox="([^"]*)"/i.exec(svg)?.[1];
245
+ const n = vb?.split(/[\s,]+/).map(Number);
246
+ const w = n?.[2];
247
+ const h = n?.[3];
248
+ return w && h && w > 0 && h > 0 && Number.isFinite(w) && Number.isFinite(h) ? { w, h } : void 0;
249
+ }
250
+ function standaloneSvg(svg) {
251
+ const size = svgSize(svg);
252
+ const open = /^\s*<svg\b[^>]*>/i.exec(svg)?.[0];
253
+ if (!size || !open) return svg;
254
+ let tagText = open.replace(/\s(?:width|height)="[^"]*"/gi, "");
255
+ if (!/\sxmlns="/i.test(tagText)) tagText = tagText.replace(/^\s*<svg/i, '<svg xmlns="http://www.w3.org/2000/svg"');
256
+ tagText = tagText.replace(/^(\s*<svg)/i, `$1 width="${size.w}" height="${size.h}"`);
257
+ return svg.replace(open, tagText);
258
+ }
259
+
260
+ // src/react/viewer/view-math.ts
261
+ var MIN_K = 0.2;
262
+ var MAX_K = 10;
263
+ var FIT_MIN_K = 0.02;
264
+ var FIT_MAX_K = 3;
265
+ var INERTIA_TAU = 325;
266
+ var STOP_SPEED = 0.02;
267
+ var clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
268
+ function zoomAt(v, px, py, k, min = MIN_K) {
269
+ const next = clamp(k, min, MAX_K);
270
+ const r = next / v.k;
271
+ return { k: next, x: px - (px - v.x) * r, y: py - (py - v.y) * r };
272
+ }
273
+ function fitRect(r, vw, vh, pad = 32, maxK = FIT_MAX_K) {
274
+ const k = clamp(Math.min(Math.max(1, vw - 2 * pad) / Math.max(r.w, 1), Math.max(1, vh - 2 * pad) / Math.max(r.h, 1)), FIT_MIN_K, Math.min(maxK, MAX_K));
275
+ return { k, x: (vw - r.w * k) / 2 - r.x * k, y: (vh - r.h * k) / 2 - r.y * k };
276
+ }
277
+ function keepVisible(v, c, vw, vh, margin = 80) {
278
+ const axis = (pos, start, size, extent) => {
279
+ const m = Math.min(margin, extent / 2, size * v.k);
280
+ const lo = m - (start + size) * v.k;
281
+ const hi = extent - m - start * v.k;
282
+ return lo > hi ? pos : clamp(pos, lo, hi);
283
+ };
284
+ return { k: v.k, x: axis(v.x, c.x, c.w, vw), y: axis(v.y, c.y, c.h, vh) };
285
+ }
286
+ function wheelFactor(deltaY, deltaMode, ctrl) {
287
+ const px = deltaMode === 1 ? deltaY * 16 : deltaMode === 2 ? deltaY * 400 : deltaY;
288
+ return Math.exp(-clamp(px, -120, 120) * (ctrl ? 0.01 : 16e-4));
289
+ }
290
+ function pinchView(start, a0, b0, a1, b1, min = MIN_K) {
291
+ const d0 = Math.hypot(a0.x - b0.x, a0.y - b0.y) || 1;
292
+ const d1 = Math.hypot(a1.x - b1.x, a1.y - b1.y);
293
+ const k = clamp(start.k * (d1 / d0), min, MAX_K);
294
+ const c0 = { x: (a0.x + b0.x) / 2, y: (a0.y + b0.y) / 2 };
295
+ const c1 = { x: (a1.x + b1.x) / 2, y: (a1.y + b1.y) / 2 };
296
+ const wx = (c0.x - start.x) / start.k;
297
+ const wy = (c0.y - start.y) / start.k;
298
+ return { k, x: c1.x - wx * k, y: c1.y - wy * k };
299
+ }
300
+ function releaseVelocity(samples, now) {
301
+ const recent = samples.filter((s) => now - s.t <= 100);
302
+ const first = recent[0];
303
+ const last = recent[recent.length - 1];
304
+ if (!first || !last || last === first || now - last.t > 60) return { x: 0, y: 0 };
305
+ const dt = last.t - first.t || 1;
306
+ return { x: (last.x - first.x) / dt, y: (last.y - first.y) / dt };
307
+ }
308
+ function stepInertia(vel, dt) {
309
+ const decay = Math.exp(-dt / INERTIA_TAU);
310
+ const travel = INERTIA_TAU * (1 - decay);
311
+ const next = { x: vel.x * decay, y: vel.y * decay };
312
+ return { dx: vel.x * travel, dy: vel.y * travel, vel: next, done: Math.hypot(next.x, next.y) < STOP_SPEED };
313
+ }
314
+ var easeOutCubic = (t) => 1 - (1 - clamp(t, 0, 1)) ** 3;
315
+ function lerpView(a, b, t) {
316
+ return { k: a.k * (b.k / a.k) ** t, x: a.x + (b.x - a.x) * t, y: a.y + (b.y - a.y) * t };
317
+ }
318
+ function unionRect(rects) {
319
+ if (!rects.length) return void 0;
320
+ const x0 = Math.min(...rects.map((r) => r.x));
321
+ const y0 = Math.min(...rects.map((r) => r.y));
322
+ const x1 = Math.max(...rects.map((r) => r.x + r.w));
323
+ const y1 = Math.max(...rects.map((r) => r.y + r.h));
324
+ return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 };
325
+ }
326
+ function revealRect(v, r, vw, vh, pad = 48) {
327
+ const shift = (pos, start, size, extent) => {
328
+ const lo = pos + start * v.k;
329
+ const hi = lo + size * v.k;
330
+ if (hi - lo > extent - 2 * pad) return pos + (extent - (lo + hi)) / 2;
331
+ if (lo < pad) return pos + pad - lo;
332
+ if (hi > extent - pad) return pos + extent - pad - hi;
333
+ return pos;
334
+ };
335
+ return { k: v.k, x: shift(v.x, r.x, r.w, vw), y: shift(v.y, r.y, r.h, vh) };
336
+ }
337
+ var MINIMAP_MIN_NODES = 12;
338
+ var showMinimap = (nodeCount) => nodeCount >= MINIMAP_MIN_NODES;
339
+ var centerOn = (v, wx, wy, vw, vh) => ({ k: v.k, x: vw / 2 - wx * v.k, y: vh / 2 - wy * v.k });
340
+
341
+ // src/react/viewer/controller.ts
342
+ var TAP_SLOP = 5;
343
+ var DOUBLE_TAP_MS = 350;
344
+ var DOUBLE_TAP_DIST = 32;
345
+ var TWEEN_MS = 380;
346
+ var FOCUS_MAX_K = 2.5;
347
+ var KEY_PAN = 64;
348
+ var KEY_ZOOM = 1.25;
349
+ var FADE_MAX_NODES = 150;
350
+ var FLOW_MAX_EDGES = 120;
351
+ var HIT = ["hv-hit", "hv-cur"];
352
+ var STATE_CLASSES = ["hv-on", "hv-sel", "hv-up", "hv-down", "hv-nb", "hv-flow"];
353
+ var reduced = () => globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false;
354
+ var DiagramController = class {
355
+ constructor(o) {
356
+ this.o = o;
357
+ const { viewport: vp, stage, minimap } = o;
358
+ const on = (el, type, fn, opts) => {
359
+ el.addEventListener(type, fn, opts);
360
+ this.off.push(() => el.removeEventListener(type, fn, opts));
361
+ };
362
+ on(vp, "wheel", (e) => this.onWheel(e), { passive: false });
363
+ on(vp, "pointerdown", (e) => this.onDown(e));
364
+ on(vp, "pointermove", (e) => this.onMove(e));
365
+ on(vp, "pointerup", (e) => this.onUp(e));
366
+ on(vp, "pointercancel", (e) => this.onUp(e, true));
367
+ on(stage, "pointerover", (e) => e.pointerType === "mouse" && !this.pointers.size && this.mouseOver(this.keyAt(e.target)));
368
+ on(stage, "pointerout", (e) => e.pointerType === "mouse" && !this.pointers.size && this.mouseOver(this.keyAt(e.relatedTarget)));
369
+ on(stage, "focusin", (e) => this.onFocusIn(e));
370
+ on(stage, "focusout", () => this.focusLeft());
371
+ on(minimap, "pointerdown", (e) => this.onMiniDown(e));
372
+ on(minimap, "pointermove", (e) => this.miniDrag && this.miniTo(e));
373
+ on(minimap, "pointerup", () => this.miniDrag = false);
374
+ on(minimap, "pointercancel", () => this.miniDrag = false);
375
+ this.ro = new ResizeObserver(() => this.measure());
376
+ this.ro.observe(vp);
377
+ this.watcher = new MutationObserver(() => {
378
+ const now = stage.querySelector("svg");
379
+ if (now && now !== this.svg && this.source) this.mount(now, this.source.markup, this.source.idPrefix);
380
+ });
381
+ this.watcher.observe(stage, { childList: true });
382
+ this.measure();
383
+ }
384
+ o;
385
+ view = { x: 0, y: 0, k: 1 };
386
+ content = { x: 0, y: 0, w: 1, h: 1 };
387
+ vw = 0;
388
+ vh = 0;
389
+ needFit = true;
390
+ /** The lowest zoom: 0.2x, or lower when the diagram needs it to fit at all. */
391
+ minK = MIN_K;
392
+ dirty = false;
393
+ kWritten = 0;
394
+ frame = 0;
395
+ anim;
396
+ svg;
397
+ graph;
398
+ nodes = [];
399
+ edges = [];
400
+ nodeIndex = /* @__PURE__ */ new Map();
401
+ touched = [];
402
+ hits = [];
403
+ hitEls = [];
404
+ query = "";
405
+ cursor = -1;
406
+ pinned = null;
407
+ hot = null;
408
+ mouseKey = null;
409
+ focusKey = null;
410
+ roving;
411
+ pointers = /* @__PURE__ */ new Map();
412
+ start;
413
+ pinch;
414
+ tap;
415
+ lastTap;
416
+ dragging = false;
417
+ samples = [];
418
+ ro;
419
+ watcher;
420
+ source;
421
+ miniDrag = false;
422
+ miniColors = { node: "#888", edge: "#555", view: "#0af", bg: "transparent" };
423
+ off = [];
424
+ destroy() {
425
+ this.anim?.stop();
426
+ cancelAnimationFrame(this.frame);
427
+ this.ro?.disconnect();
428
+ this.watcher?.disconnect();
429
+ for (const f of this.off) f();
430
+ }
431
+ // ---- mounting -----------------------------------------------------------------------------------------------------------------------
432
+ /** (Re)attaches to the SVG now in the stage. A re-mount (theme change) keeps the view and a still-valid pin. */
433
+ mount(svg, markup, idPrefix) {
434
+ const size = svgSize(markup) ?? { w: svg.getBoundingClientRect().width || 600, h: svg.getBoundingClientRect().height || 400 };
435
+ const first = this.svg === void 0;
436
+ this.svg = svg;
437
+ this.source = { markup, idPrefix };
438
+ this.content = { x: 0, y: 0, w: size.w, h: size.h };
439
+ this.o.stage.style.width = `${size.w}px`;
440
+ this.o.stage.style.height = `${size.h}px`;
441
+ this.touched = [];
442
+ this.hitEls = [];
443
+ this.hits = [];
444
+ this.roving = void 0;
445
+ this.indexGraph(svg, idPrefix);
446
+ if (first || this.needFit) this.needFit = true;
447
+ this.measure();
448
+ if (this.pinned && !this.graph?.byKey.has(this.pinned)) this.pinned = null;
449
+ this.paint();
450
+ const again = this.focusKey === null ? void 0 : this.graph?.byKey.get(this.focusKey);
451
+ if (again !== void 0) this.nodes[again]?.el?.focus({ preventScroll: true });
452
+ if (this.query) this.search(this.query, false);
453
+ this.readMiniColors();
454
+ this.emit();
455
+ this.request();
456
+ }
457
+ indexGraph(svg, idPrefix) {
458
+ let ex;
459
+ try {
460
+ ex = extractGraph(svg, idPrefix);
461
+ } catch {
462
+ ex = { nodes: [], edges: [] };
463
+ }
464
+ this.nodes = ex.nodes.map((n) => ({ el: n.el, key: n.key, box: n.box }));
465
+ this.edges = ex.edges.map((e) => ({ el: e.el, ...e.labelEl ? { labelEl: e.labelEl } : {} }));
466
+ this.nodeIndex = new Map(this.nodes.map((n, i) => [n.el, i]));
467
+ this.graph = this.nodes.length ? buildGraph(ex.nodes, ex.edges) : void 0;
468
+ const labels = this.o.labels();
469
+ this.nodes.forEach((n, i) => {
470
+ n.el.classList.add("hv-n");
471
+ n.el.setAttribute("tabindex", i === 0 ? "0" : "-1");
472
+ n.el.setAttribute("role", "button");
473
+ n.el.setAttribute("aria-label", describeNode(this.graph, n.key, labels));
474
+ n.el.setAttribute("aria-pressed", "false");
475
+ });
476
+ if (this.nodes[0]) this.roving = this.nodes[0].el;
477
+ for (const e of this.edges) e.el.classList.add("hv-e"), e.labelEl?.classList.add("hv-e");
478
+ this.o.stage.classList.toggle("hv-plain", this.nodes.length > FADE_MAX_NODES);
479
+ }
480
+ // ---- view ---------------------------------------------------------------------------------------------------------------------------
481
+ measure() {
482
+ const r = this.o.viewport.getBoundingClientRect();
483
+ this.vw = r.width;
484
+ this.vh = r.height;
485
+ if (this.vw > 0 && this.vh > 0) this.minK = Math.min(MIN_K, this.fitView(this.content).k);
486
+ if (this.needFit && this.vw > 0 && this.vh > 0) {
487
+ this.needFit = false;
488
+ this.view = this.fitView(this.content);
489
+ this.request();
490
+ }
491
+ }
492
+ fitView(r, maxK) {
493
+ return fitRect(r, this.vw, this.vh, Math.min(48, this.vw / 8), maxK);
494
+ }
495
+ request() {
496
+ if (this.dirty) return;
497
+ this.dirty = true;
498
+ this.frame = requestAnimationFrame(() => {
499
+ this.dirty = false;
500
+ const { x, y, k } = this.view;
501
+ this.o.stage.style.transform = `translate(${x}px, ${y}px) scale(${k})`;
502
+ this.o.zoomOutput.textContent = `${Math.round(k * 100)}%`;
503
+ this.syncK();
504
+ this.drawMinimap();
505
+ });
506
+ }
507
+ /** Publishes the zoom to CSS as --hv-k, but only while something is highlighted (a new value restyles the highlighted strokes). */
508
+ syncK() {
509
+ if (!this.touched.length && !this.hitEls.length) return;
510
+ const k = Math.round(this.view.k * 100) / 100;
511
+ if (k === this.kWritten) return;
512
+ this.kWritten = k;
513
+ this.o.stage.style.setProperty("--hv-k", String(k));
514
+ }
515
+ set(v) {
516
+ this.view = keepVisible(v, this.content, this.vw, this.vh);
517
+ this.request();
518
+ }
519
+ stopAnim() {
520
+ this.anim?.stop();
521
+ this.anim = void 0;
522
+ }
523
+ /** Moves to `target`: instantly under reduced motion, otherwise an eased tween that any input cancels. */
524
+ go(target) {
525
+ this.stopAnim();
526
+ const goal = keepVisible(target, this.content, this.vw, this.vh);
527
+ if (reduced()) return this.set(goal);
528
+ const from = this.view;
529
+ const t0 = performance.now();
530
+ let id = 0;
531
+ const tick = (now) => {
532
+ const t = (now - t0) / TWEEN_MS;
533
+ this.view = t >= 1 ? goal : lerpView(from, goal, easeOutCubic(t));
534
+ this.request();
535
+ if (t < 1) id = requestAnimationFrame(tick);
536
+ else this.anim = void 0;
537
+ };
538
+ id = requestAnimationFrame(tick);
539
+ this.anim = { stop: () => cancelAnimationFrame(id) };
540
+ }
541
+ zoomBy(factor) {
542
+ this.go(zoomAt(this.view, this.vw / 2, this.vh / 2, this.view.k * factor, this.minK));
543
+ }
544
+ fit() {
545
+ this.go(this.fitView(this.content));
546
+ }
547
+ actual() {
548
+ this.go(zoomAt(this.view, this.vw / 2, this.vh / 2, 1));
549
+ }
550
+ /** The current zoom, for tests and the live region. */
551
+ scale() {
552
+ return this.view.k;
553
+ }
554
+ local(e) {
555
+ const r = this.o.viewport.getBoundingClientRect();
556
+ return { x: e.clientX - r.left, y: e.clientY - r.top };
557
+ }
558
+ onWheel(e) {
559
+ e.preventDefault();
560
+ this.stopAnim();
561
+ const p = this.local(e);
562
+ this.set(zoomAt(this.view, p.x, p.y, this.view.k * wheelFactor(e.deltaY, e.deltaMode, e.ctrlKey), this.minK));
563
+ }
564
+ // ---- pointers -----------------------------------------------------------------------------------------------------------------------
565
+ onDown(e) {
566
+ if (e.pointerType === "mouse" && e.button !== 0) return;
567
+ this.stopAnim();
568
+ const at = this.local(e);
569
+ this.pointers.set(e.pointerId, at);
570
+ if (this.pointers.size === 1) {
571
+ const key = this.keyAt(e.target);
572
+ this.tap = { at, key, moved: false, link: Boolean(e.target.closest?.("a")), id: e.pointerId };
573
+ this.start = { view: this.view, at };
574
+ this.dragging = false;
575
+ this.samples = [{ t: e.timeStamp, ...at }];
576
+ } else if (this.pointers.size === 2) {
577
+ const [a, b] = [...this.pointers.values()];
578
+ this.pinch = { view: this.view, a, b };
579
+ this.tap = void 0;
580
+ this.dragging = true;
581
+ for (const id of this.pointers.keys()) this.capture(id);
582
+ }
583
+ }
584
+ onMove(e) {
585
+ if (!this.pointers.has(e.pointerId)) return;
586
+ const at = this.local(e);
587
+ this.pointers.set(e.pointerId, at);
588
+ if (this.pinch && this.pointers.size >= 2) {
589
+ const [a, b] = [...this.pointers.values()];
590
+ this.set(pinchView(this.pinch.view, this.pinch.a, this.pinch.b, a, b, this.minK));
591
+ return;
592
+ }
593
+ if (!this.start) return;
594
+ if (!this.dragging && this.tap && Math.hypot(at.x - this.tap.at.x, at.y - this.tap.at.y) > TAP_SLOP) {
595
+ this.dragging = true;
596
+ this.tap.moved = true;
597
+ this.capture(this.tap.id);
598
+ this.o.viewport.classList.add("hv-grabbing");
599
+ }
600
+ if (this.dragging) this.dragTo(at, e.timeStamp);
601
+ }
602
+ capture(id) {
603
+ try {
604
+ this.o.viewport.setPointerCapture(id);
605
+ } catch {
606
+ }
607
+ }
608
+ dragTo(at, t) {
609
+ const s = this.start;
610
+ this.set({ k: s.view.k, x: s.view.x + at.x - s.at.x, y: s.view.y + at.y - s.at.y });
611
+ this.samples.push({ t, ...at });
612
+ if (this.samples.length > 12) this.samples.shift();
613
+ }
614
+ onUp(e, cancelled = false) {
615
+ if (!this.pointers.delete(e.pointerId)) return;
616
+ try {
617
+ this.o.viewport.releasePointerCapture(e.pointerId);
618
+ } catch {
619
+ }
620
+ if (this.pinch) {
621
+ this.pinch = void 0;
622
+ const rest = [...this.pointers.values()][0];
623
+ this.start = rest ? { view: this.view, at: rest } : void 0;
624
+ this.tap = rest ? { at: rest, key: null, moved: true, link: false, id: -1 } : void 0;
625
+ this.dragging = Boolean(rest);
626
+ this.samples = [];
627
+ if (!rest) this.o.viewport.classList.remove("hv-grabbing");
628
+ return;
629
+ }
630
+ if (this.pointers.size > 0) return;
631
+ this.o.viewport.classList.remove("hv-grabbing");
632
+ const tap = this.tap;
633
+ this.tap = void 0;
634
+ this.start = void 0;
635
+ if (cancelled) return void (this.dragging = false);
636
+ if (tap && !tap.moved) this.onTap(tap.at, tap.key, e.timeStamp, tap.link);
637
+ else if (this.dragging && !reduced()) this.glide(releaseVelocity(this.samples, e.timeStamp));
638
+ this.dragging = false;
639
+ }
640
+ glide(v0) {
641
+ if (Math.hypot(v0.x, v0.y) < 0.1) return;
642
+ let vel = v0;
643
+ let last = performance.now();
644
+ let id = 0;
645
+ const tick = (now) => {
646
+ const dt = Math.min(now - last, 50);
647
+ last = now;
648
+ const s = stepInertia(vel, dt);
649
+ vel = s.vel;
650
+ this.set({ k: this.view.k, x: this.view.x + s.dx, y: this.view.y + s.dy });
651
+ if (s.done) this.anim = void 0;
652
+ else id = requestAnimationFrame(tick);
653
+ };
654
+ id = requestAnimationFrame(tick);
655
+ this.anim = { stop: () => cancelAnimationFrame(id) };
656
+ }
657
+ onTap(at, key, t, link) {
658
+ const prev = this.lastTap;
659
+ const isDouble = prev && t - prev.t < DOUBLE_TAP_MS && Math.hypot(at.x - prev.at.x, at.y - prev.at.y) < DOUBLE_TAP_DIST;
660
+ this.lastTap = isDouble ? void 0 : { t, at };
661
+ if (isDouble) {
662
+ if (key) this.focusNode(key);
663
+ else this.go(zoomAt(this.view, at.x, at.y, this.view.k * 2, this.minK));
664
+ return;
665
+ }
666
+ if (key && link) return;
667
+ if (key) {
668
+ this.nodes[this.graph.byKey.get(key)]?.el?.focus?.({ preventScroll: true });
669
+ this.pin(this.pinned === key ? null : key);
670
+ } else {
671
+ this.pin(null);
672
+ this.o.viewport.focus({ preventScroll: true });
673
+ }
674
+ }
675
+ keyAt(target) {
676
+ const node = target?.closest?.(".hv-n");
677
+ const i = node ? this.nodeIndex.get(node) : void 0;
678
+ return i === void 0 ? null : this.nodes[i].key;
679
+ }
680
+ // ---- node interaction ---------------------------------------------------------------------------------------------------------------
681
+ /** Hover highlight follows the mouse when it is over a node, otherwise the keyboard-focused node. */
682
+ mouseOver(key) {
683
+ this.mouseKey = key;
684
+ this.refreshHot();
685
+ }
686
+ refreshHot() {
687
+ const key = this.mouseKey ?? this.focusKey;
688
+ if (key === this.hot) return;
689
+ this.hot = key;
690
+ if (!this.pinned) this.paint();
691
+ }
692
+ onFocusIn(e) {
693
+ const key = this.keyAt(e.target);
694
+ if (key === null) return;
695
+ const el = e.target.closest(".hv-n");
696
+ if (this.roving && this.roving !== el) this.roving.setAttribute("tabindex", "-1");
697
+ el.setAttribute("tabindex", "0");
698
+ this.roving = el;
699
+ this.focusKey = key;
700
+ this.refreshHot();
701
+ }
702
+ focusLeft() {
703
+ queueMicrotask(() => {
704
+ if (this.o.stage.contains(document.activeElement)) return;
705
+ this.focusKey = null;
706
+ this.refreshHot();
707
+ });
708
+ }
709
+ pin(key) {
710
+ if (key === this.pinned) return;
711
+ this.pinned = key;
712
+ this.paint();
713
+ if (key && this.graph) this.o.announce(traceSummary(this.o.labels(), this.graph.nodes[this.graph.byKey.get(key)].label, trace(this.graph, key)));
714
+ this.emit();
715
+ }
716
+ /** Recomputes which elements are highlighted. Only changed elements are touched; dimming is one class on the stage. */
717
+ paint() {
718
+ for (const el of this.touched) el.classList.remove(...STATE_CLASSES);
719
+ this.touched = [];
720
+ const g = this.graph;
721
+ const mark = (el, ...cls) => {
722
+ if (!el) return;
723
+ el.classList.add("hv-on", ...cls);
724
+ this.touched.push(el);
725
+ };
726
+ const at = (key) => this.nodes[g.byKey.get(key)];
727
+ let active = false;
728
+ if (g && this.pinned) {
729
+ active = true;
730
+ const t = trace(g, this.pinned);
731
+ for (const k of t.up) mark(at(k)?.el, "hv-up");
732
+ for (const k of t.down) mark(at(k)?.el, "hv-down");
733
+ mark(at(this.pinned)?.el, "hv-sel");
734
+ const flow = t.upEdges.size + t.downEdges.size <= FLOW_MAX_EDGES ? ["hv-flow"] : [];
735
+ for (const i of t.upEdges) mark(this.edges[i]?.el, "hv-up", ...flow), mark(this.edges[i]?.labelEl, "hv-up");
736
+ for (const i of t.downEdges) mark(this.edges[i]?.el, "hv-down", ...flow), mark(this.edges[i]?.labelEl, "hv-down");
737
+ } else if (g && this.hot) {
738
+ active = true;
739
+ const n = neighbourhood(g, this.hot);
740
+ for (const k of n.nodes) mark(at(k)?.el, k === this.hot ? "hv-sel" : "hv-nb");
741
+ for (const i of n.edges) mark(this.edges[i]?.el, "hv-nb"), mark(this.edges[i]?.labelEl, "hv-nb");
742
+ } else if (this.query && this.hitEls.length) {
743
+ active = true;
744
+ for (const el of this.hitEls) mark(el);
745
+ }
746
+ this.o.stage.classList.toggle("hv-active", active);
747
+ this.syncK();
748
+ for (const n of this.nodes) n.el.setAttribute("aria-pressed", String(n.key === this.pinned));
749
+ }
750
+ /** Zooms to a node and its direct neighbours. */
751
+ focusNode(key) {
752
+ const k = key ?? this.pinned ?? this.hot ?? this.nodes[0]?.key;
753
+ if (!k || !this.graph) return;
754
+ const rects = [...neighbourhood(this.graph, k).nodes].map((x) => this.graph.nodes[this.graph.byKey.get(x)].box);
755
+ const box = unionRect(rects);
756
+ if (box) this.go(this.fitView(box, FOCUS_MAX_K));
757
+ }
758
+ /** Arrow-key traversal from the focused node. Returns false when the key was not used. */
759
+ traverse(dir) {
760
+ const el = document.activeElement?.closest?.(".hv-n") ?? null;
761
+ const key = el && this.stageHas(el) ? this.keyAt(el) : null;
762
+ if (key === null || !this.graph) return false;
763
+ const next = pickNeighbour(this.graph, key, dir);
764
+ const target = next === void 0 ? void 0 : this.nodes[this.graph.byKey.get(next)];
765
+ if (target) {
766
+ target.el.focus({ preventScroll: true });
767
+ this.go(revealRect(this.view, target.box, this.vw, this.vh));
768
+ }
769
+ return true;
770
+ }
771
+ stageHas(el) {
772
+ return this.o.stage.contains(el);
773
+ }
774
+ /** Keyboard commands of the viewer. Returns true when the key was handled (the caller then prevents the default). */
775
+ key(e) {
776
+ if (e.altKey || e.ctrlKey || e.metaKey) return false;
777
+ const arrows = { ArrowUp: "up", ArrowDown: "down", ArrowLeft: "left", ArrowRight: "right" };
778
+ const dir = arrows[e.key];
779
+ if (dir) {
780
+ if (this.traverse(dir)) return true;
781
+ const step = KEY_PAN * (e.shiftKey ? 4 : 1);
782
+ this.stopAnim();
783
+ this.set({ ...this.view, x: this.view.x + (dir === "left" ? step : dir === "right" ? -step : 0), y: this.view.y + (dir === "up" ? step : dir === "down" ? -step : 0) });
784
+ return true;
785
+ }
786
+ const onNode = this.keyAt(document.activeElement);
787
+ switch (e.key) {
788
+ case "+":
789
+ case "=":
790
+ return this.zoomBy(KEY_ZOOM), true;
791
+ case "-":
792
+ case "_":
793
+ return this.zoomBy(1 / KEY_ZOOM), true;
794
+ case "0":
795
+ case "Home":
796
+ return this.fit(), true;
797
+ case "1":
798
+ return this.actual(), true;
799
+ case "f":
800
+ case "F":
801
+ return this.focusNode(onNode), true;
802
+ case "Enter":
803
+ case " ":
804
+ if (onNode === null) return false;
805
+ return this.pin(this.pinned === onNode ? null : onNode), true;
806
+ default:
807
+ return false;
808
+ }
809
+ }
810
+ // ---- search -------------------------------------------------------------------------------------------------------------------------
811
+ /** Highlights matches of `query`; graph nodes when the diagram has them, otherwise every SVG text element. Returns the match count. */
812
+ search(query, jump = true) {
813
+ for (const el of this.hitEls) el.classList.remove(...HIT);
814
+ this.query = query.trim();
815
+ this.hits = [];
816
+ this.hitEls = [];
817
+ this.cursor = -1;
818
+ if (this.query && this.graph) {
819
+ const keys = new Set(searchNodes(this.graph.nodes, this.query));
820
+ this.hits = this.nodes.filter((n) => keys.has(n.key)).sort((a, b) => a.box.y - b.box.y || a.box.x - b.box.x).map((n) => ({ el: n.el, box: () => n.box }));
821
+ } else if (this.query && this.svg) {
822
+ const q = this.query.toLowerCase();
823
+ this.hits = Array.from(this.svg.querySelectorAll("text")).filter((t) => (t.textContent ?? "").toLowerCase().includes(q)).map((el) => ({ el, box: () => this.worldRect(el) }));
824
+ }
825
+ this.hitEls = this.hits.map((h) => h.el);
826
+ for (const el of this.hitEls) el.classList.add("hv-hit");
827
+ this.paint();
828
+ if (this.hits.length && jump) this.step(1);
829
+ else this.emit();
830
+ return this.hits.length;
831
+ }
832
+ /** Moves to the next (or previous) match and brings it into view. */
833
+ step(by) {
834
+ if (!this.hits.length) return;
835
+ this.hits[this.cursor]?.el.classList.remove("hv-cur");
836
+ this.cursor = (this.cursor + by + this.hits.length) % this.hits.length;
837
+ const hit = this.hits[this.cursor];
838
+ hit.el.classList.add("hv-cur");
839
+ this.go(this.fitView(hit.box(), FOCUS_MAX_K));
840
+ this.emit();
841
+ }
842
+ worldRect(el) {
843
+ const r = el.getBoundingClientRect();
844
+ const s = this.o.stage.getBoundingClientRect();
845
+ const k = this.view.k;
846
+ return { x: (r.left - s.left) / k, y: (r.top - s.top) / k, w: r.width / k, h: r.height / k };
847
+ }
848
+ // ---- minimap ------------------------------------------------------------------------------------------------------------------------
849
+ readMiniColors() {
850
+ const cs = getComputedStyle(this.o.minimap);
851
+ this.miniColors = { node: cs.color, edge: cs.borderLeftColor, view: cs.accentColor, bg: cs.backgroundColor };
852
+ }
853
+ miniScale() {
854
+ const c = this.o.minimap;
855
+ const s = Math.min(c.width / this.content.w, c.height / this.content.h);
856
+ return { s, ox: (c.width - this.content.w * s) / 2, oy: (c.height - this.content.h * s) / 2 };
857
+ }
858
+ drawMinimap() {
859
+ const c = this.o.minimap;
860
+ if (c.hidden || !c.width) return;
861
+ const ctx = c.getContext("2d");
862
+ if (!ctx) return;
863
+ const { s, ox, oy } = this.miniScale();
864
+ ctx.clearRect(0, 0, c.width, c.height);
865
+ ctx.fillStyle = this.miniColors.node;
866
+ ctx.globalAlpha = 0.55;
867
+ for (const n of this.nodes) ctx.fillRect(ox + n.box.x * s, oy + n.box.y * s, Math.max(n.box.w * s, 1.5), Math.max(n.box.h * s, 1.5));
868
+ ctx.globalAlpha = 1;
869
+ const v = this.view;
870
+ ctx.strokeStyle = this.miniColors.view;
871
+ ctx.lineWidth = Math.max(1.5, c.width / 120);
872
+ ctx.strokeRect(ox + -v.x / v.k * s, oy + -v.y / v.k * s, this.vw / v.k * s, this.vh / v.k * s);
873
+ }
874
+ miniTo(e) {
875
+ const c = this.o.minimap;
876
+ const r = c.getBoundingClientRect();
877
+ const { s, ox, oy } = this.miniScale();
878
+ const px = (e.clientX - r.left) / r.width * c.width;
879
+ const py = (e.clientY - r.top) / r.height * c.height;
880
+ this.stopAnim();
881
+ this.set(centerOn(this.view, (px - ox) / s, (py - oy) / s, this.vw, this.vh));
882
+ }
883
+ onMiniDown(e) {
884
+ e.stopPropagation();
885
+ this.miniDrag = true;
886
+ try {
887
+ this.o.minimap.setPointerCapture(e.pointerId);
888
+ } catch {
889
+ }
890
+ this.miniTo(e);
891
+ }
892
+ // ---- state out ----------------------------------------------------------------------------------------------------------------------
893
+ emit() {
894
+ this.o.onUi({ graph: Boolean(this.graph), minimap: showMinimap(this.nodes.length), pinned: this.pinned, matches: this.hits.length, current: this.cursor });
895
+ }
896
+ /** The node count and pinned key, for assertions. */
897
+ inspect() {
898
+ return { nodes: this.nodes.length, edges: this.edges.length, pinned: this.pinned, k: this.view.k };
899
+ }
900
+ };
901
+
902
+ // src/react/viewer/export.ts
903
+ var MAX_SIDE = 16384;
904
+ var MAX_PIXELS = 36e6;
905
+ function pngSize(w, h, scale) {
906
+ const limit = Math.min(1, MAX_SIDE / (w * scale), MAX_SIDE / (h * scale), Math.sqrt(MAX_PIXELS / (w * h * scale * scale)));
907
+ return { w: Math.max(1, Math.floor(w * scale * limit)), h: Math.max(1, Math.floor(h * scale * limit)) };
908
+ }
909
+ var fileName = (title, ext) => `${title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "diagram"}.${ext}`;
910
+ function downloadBlob(blob, name) {
911
+ const url = URL.createObjectURL(blob);
912
+ const a = document.createElement("a");
913
+ a.href = url;
914
+ a.download = name;
915
+ a.rel = "noopener";
916
+ document.body.append(a);
917
+ a.click();
918
+ a.remove();
919
+ setTimeout(() => URL.revokeObjectURL(url), 1e4);
920
+ }
921
+ function serializeSvg(markup) {
922
+ const svg = new DOMParser().parseFromString(markup, "text/html").body.querySelector("svg");
923
+ return standaloneSvg(svg ? new XMLSerializer().serializeToString(svg) : markup);
924
+ }
925
+ var svgBlob = (markup) => new Blob([serializeSvg(markup)], { type: "image/svg+xml;charset=utf-8" });
926
+ async function pngBlob(markup, scale, background) {
927
+ const size = svgSize(markup);
928
+ if (!size) throw new Error("no size");
929
+ const { w, h } = pngSize(size.w, size.h, scale);
930
+ const img = new Image();
931
+ img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(serializeSvg(markup))}`;
932
+ await img.decode();
933
+ const canvas = document.createElement("canvas");
934
+ canvas.width = w;
935
+ canvas.height = h;
936
+ const ctx = canvas.getContext("2d");
937
+ if (!ctx) throw new Error("no canvas");
938
+ ctx.fillStyle = background;
939
+ ctx.fillRect(0, 0, w, h);
940
+ ctx.drawImage(img, 0, 0, w, h);
941
+ return await new Promise((resolve, reject) => canvas.toBlob((b) => b ? resolve(b) : reject(new Error("png")), "image/png"));
942
+ }
943
+
944
+ // src/react/viewer/diagram-viewer.tsx
945
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
946
+ var sequence = 0;
947
+ var locks = 0;
948
+ var LOCK_CLASS = "hyle-viewer-lock";
949
+ var SCALES = ["1", "2", "4"];
950
+ var TOAST_MS = 4e3;
951
+ var Glyph = ({ d }) => /* @__PURE__ */ jsx("svg", { className: "hv-ic", viewBox: "0 0 16 16", "aria-hidden": "true", children: /* @__PURE__ */ jsx("path", { d }) });
952
+ var ICONS = {
953
+ close: "m4 4 8 8M12 4l-8 8",
954
+ fit: "M2.5 6V2.5H6M10 2.5h3.5V6M13.5 10v3.5H10M6 13.5H2.5V10",
955
+ search: "M7 12.2A5.2 5.2 0 1 0 7 1.8a5.2 5.2 0 0 0 0 10.4zM11 11l3.2 3.2",
956
+ full: "M2.5 6V2.5H6M10 2.5h3.5V6M13.5 10v3.5H10M6 13.5H2.5V10",
957
+ exit: "M6 2.5V6H2.5M13.5 6H10V2.5M10 13.5V10h3.5M2.5 10H6v3.5"
958
+ };
959
+ function DiagramViewer({ svg, svgId, source, title, labels, onClose }) {
960
+ const dialog = useRef(null);
961
+ const shell = useRef(null);
962
+ const viewport = useRef(null);
963
+ const stage = useRef(null);
964
+ const minimap = useRef(null);
965
+ const zoom = useRef(null);
966
+ const finder = useRef(null);
967
+ const ctl = useRef(null);
968
+ const labelsRef = useRef(labels);
969
+ labelsRef.current = labels;
970
+ const ownId = useRef(`hyle-viewer-${++sequence}`);
971
+ const helpId = useId();
972
+ const toastTimer = useRef(void 0);
973
+ const downOnBackdrop = useRef(false);
974
+ const [ui, setUi] = useState({ graph: false, minimap: false, pinned: null, matches: 0, current: -1 });
975
+ const [toast, setToast] = useState("");
976
+ const [finding, setFinding] = useState(false);
977
+ const [query, setQuery] = useState("");
978
+ const [scale, setScale] = useState("2");
979
+ const [fullscreen, setFullscreen] = useState(false);
980
+ const scoped = useMemo(() => scopeSvg(svg, svgId, ownId.current), [svg, svgId]);
981
+ const html = useMemo(() => ({ __html: scoped }), [scoped]);
982
+ const say = (message) => {
983
+ clearTimeout(toastTimer.current);
984
+ setToast(message);
985
+ toastTimer.current = setTimeout(() => setToast(""), TOAST_MS);
986
+ };
987
+ useLayoutEffect(() => {
988
+ const c = new DiagramController({
989
+ viewport: viewport.current,
990
+ stage: stage.current,
991
+ minimap: minimap.current,
992
+ zoomOutput: zoom.current,
993
+ labels: () => labelsRef.current,
994
+ onUi: setUi,
995
+ announce: say
996
+ });
997
+ ctl.current = c;
998
+ return () => {
999
+ c.destroy();
1000
+ ctl.current = null;
1001
+ };
1002
+ }, []);
1003
+ useLayoutEffect(() => {
1004
+ const el = stage.current?.querySelector("svg");
1005
+ if (el) ctl.current?.mount(el, scoped, `${ownId.current}_`);
1006
+ }, [scoped]);
1007
+ useEffect(() => {
1008
+ const d = dialog.current;
1009
+ if (!d.open) d.showModal();
1010
+ if (locks++ === 0) document.documentElement.classList.add(LOCK_CLASS);
1011
+ viewport.current?.focus({ preventScroll: true });
1012
+ const sync = () => setFullscreen(document.fullscreenElement === shell.current);
1013
+ document.addEventListener("fullscreenchange", sync);
1014
+ return () => {
1015
+ document.removeEventListener("fullscreenchange", sync);
1016
+ clearTimeout(toastTimer.current);
1017
+ if (--locks === 0) document.documentElement.classList.remove(LOCK_CLASS);
1018
+ if (document.fullscreenElement && d.contains(document.fullscreenElement)) void document.exitFullscreen().catch(() => {
1019
+ });
1020
+ };
1021
+ }, []);
1022
+ useEffect(() => {
1023
+ if (finding) finder.current?.focus();
1024
+ }, [finding]);
1025
+ const closeFind = () => {
1026
+ setFinding(false);
1027
+ setQuery("");
1028
+ ctl.current?.search("");
1029
+ viewport.current?.focus({ preventScroll: true });
1030
+ };
1031
+ const onKeyDown = (e) => {
1032
+ const target = e.target;
1033
+ if (e.key === "/" || (e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "f") {
1034
+ if (target === finder.current && e.key === "/") return;
1035
+ e.preventDefault();
1036
+ setFinding(true);
1037
+ finder.current?.focus();
1038
+ return;
1039
+ }
1040
+ if (target.closest(".hv-bar")) return;
1041
+ if (ctl.current?.key(e.nativeEvent)) e.preventDefault();
1042
+ };
1043
+ const onFindKey = (e) => {
1044
+ if (e.key === "Escape") {
1045
+ e.preventDefault();
1046
+ e.stopPropagation();
1047
+ closeFind();
1048
+ } else if (e.key === "Enter") {
1049
+ e.preventDefault();
1050
+ ctl.current?.step(e.shiftKey ? -1 : 1);
1051
+ }
1052
+ };
1053
+ const run = (job) => {
1054
+ job().then((m) => say(m || labels.saved), () => say(labels.unavailable));
1055
+ };
1056
+ const background = () => getComputedStyle(dialog.current).backgroundColor;
1057
+ const png = () => pngBlob(svg, Number(scale), background());
1058
+ const canCopyImage = typeof ClipboardItem !== "undefined" && Boolean(navigator.clipboard?.write);
1059
+ const canFullscreen = typeof document !== "undefined" && document.fullscreenEnabled;
1060
+ const status = !query.trim() ? "" : ui.matches === 0 ? labels.noMatch : fill(labels.matchOf, { n: Math.max(ui.current, 0) + 1, total: ui.matches });
1061
+ return /* @__PURE__ */ jsx(
1062
+ "dialog",
1063
+ {
1064
+ ref: dialog,
1065
+ className: "hyle-viewer",
1066
+ "aria-label": `${labels.viewer}: ${title}`,
1067
+ onClose,
1068
+ onPointerDown: (e) => downOnBackdrop.current = e.target === dialog.current,
1069
+ onClick: (e) => e.target === dialog.current && downOnBackdrop.current && dialog.current?.close(),
1070
+ onKeyDown,
1071
+ children: /* @__PURE__ */ jsxs("div", { className: "hv-shell", ref: shell, children: [
1072
+ /* @__PURE__ */ jsxs("div", { className: "hv-bar", role: "toolbar", "aria-label": labels.viewer, children: [
1073
+ /* @__PURE__ */ jsx("span", { className: "hv-title", children: title }),
1074
+ /* @__PURE__ */ jsx("output", { className: "hv-zoom", ref: zoom, "aria-label": "zoom", children: "100%" }),
1075
+ /* @__PURE__ */ jsxs("span", { className: "hv-group", children: [
1076
+ /* @__PURE__ */ jsx("button", { type: "button", className: "hv-btn", "aria-label": labels.zoomOut, title: labels.zoomOut, onClick: () => ctl.current?.zoomBy(0.8), children: "\u2212" }),
1077
+ /* @__PURE__ */ jsx("button", { type: "button", className: "hv-btn", "aria-label": labels.zoomIn, title: labels.zoomIn, onClick: () => ctl.current?.zoomBy(1.25), children: "+" }),
1078
+ /* @__PURE__ */ jsx("button", { type: "button", className: "hv-btn", "aria-label": labels.fit, title: labels.fit, onClick: () => ctl.current?.fit(), children: /* @__PURE__ */ jsx(Glyph, { d: ICONS.fit }) }),
1079
+ /* @__PURE__ */ jsx("button", { type: "button", className: "hv-btn hv-txt", "aria-label": labels.actual, title: labels.actual, onClick: () => ctl.current?.actual(), children: "100%" })
1080
+ ] }),
1081
+ /* @__PURE__ */ jsxs("span", { className: "hv-group hv-find", children: [
1082
+ /* @__PURE__ */ jsx("button", { type: "button", className: "hv-btn", "aria-label": labels.search, title: `${labels.search} (/)`, "aria-pressed": finding, onClick: () => finding ? closeFind() : setFinding(true), children: /* @__PURE__ */ jsx(Glyph, { d: ICONS.search }) }),
1083
+ finding ? /* @__PURE__ */ jsxs(Fragment, { children: [
1084
+ /* @__PURE__ */ jsx(
1085
+ "input",
1086
+ {
1087
+ ref: finder,
1088
+ className: "hv-input",
1089
+ type: "search",
1090
+ enterKeyHint: "search",
1091
+ autoComplete: "off",
1092
+ spellCheck: false,
1093
+ "aria-label": labels.search,
1094
+ placeholder: labels.searchPlaceholder,
1095
+ value: query,
1096
+ onChange: (e) => (setQuery(e.target.value), ctl.current?.search(e.target.value)),
1097
+ onKeyDown: onFindKey
1098
+ }
1099
+ ),
1100
+ /* @__PURE__ */ jsx("output", { className: "hv-count", "aria-live": "polite", children: status })
1101
+ ] }) : null
1102
+ ] }),
1103
+ /* @__PURE__ */ jsxs("span", { className: "hv-group hv-export", children: [
1104
+ /* @__PURE__ */ jsx("button", { type: "button", className: "hv-btn hv-txt", "aria-label": labels.copySource, title: labels.copySource, onClick: () => run(() => navigator.clipboard.writeText(source).then(() => labels.copied)), children: "MMD" }),
1105
+ /* @__PURE__ */ jsx("button", { type: "button", className: "hv-btn hv-txt", "aria-label": labels.downloadSvg, title: labels.downloadSvg, onClick: () => run(async () => downloadBlob(svgBlob(svg), fileName(title, "svg"))), children: "SVG" }),
1106
+ /* @__PURE__ */ jsx("button", { type: "button", className: "hv-btn hv-txt", "aria-label": labels.downloadPng, title: labels.downloadPng, onClick: () => run(async () => downloadBlob(await png(), fileName(title, "png"))), children: "PNG" }),
1107
+ /* @__PURE__ */ jsx("select", { className: "hv-select", "aria-label": labels.pngScale, title: labels.pngScale, value: scale, onChange: (e) => setScale(e.target.value), children: SCALES.map((s) => /* @__PURE__ */ jsx("option", { value: s, children: `${s}\xD7` }, s)) }),
1108
+ canCopyImage ? /* @__PURE__ */ jsx("button", { type: "button", className: "hv-btn hv-txt", "aria-label": labels.copyImage, title: labels.copyImage, onClick: () => run(() => navigator.clipboard.write([new ClipboardItem({ "image/png": png() })]).then(() => labels.copied)), children: "IMG" }) : null
1109
+ ] }),
1110
+ /* @__PURE__ */ jsxs("span", { className: "hv-group hv-end", children: [
1111
+ canFullscreen ? /* @__PURE__ */ jsx("button", { type: "button", className: "hv-btn", "aria-label": fullscreen ? labels.exitFullscreen : labels.fullscreen, title: fullscreen ? labels.exitFullscreen : labels.fullscreen, "aria-pressed": fullscreen, onClick: () => fullscreen ? void document.exitFullscreen() : void shell.current?.requestFullscreen().catch(() => say(labels.unavailable)), children: /* @__PURE__ */ jsx(Glyph, { d: fullscreen ? ICONS.exit : ICONS.full }) }) : null,
1112
+ /* @__PURE__ */ jsx("button", { type: "button", className: "hv-btn", "aria-label": labels.close, title: `${labels.close} (Esc)`, onClick: () => dialog.current?.close(), children: /* @__PURE__ */ jsx(Glyph, { d: ICONS.close }) })
1113
+ ] })
1114
+ ] }),
1115
+ /* @__PURE__ */ jsx("div", { className: "hv-view", ref: viewport, tabIndex: -1, role: "group", "aria-label": title, "aria-describedby": helpId, children: /* @__PURE__ */ jsx("div", { className: "hv-stage", ref: stage, dangerouslySetInnerHTML: html }) }),
1116
+ /* @__PURE__ */ jsx("canvas", { className: "hv-mini", ref: minimap, width: 176, height: 120, hidden: !ui.minimap, "aria-hidden": "true" }),
1117
+ /* @__PURE__ */ jsxs("div", { className: "hv-foot", children: [
1118
+ ui.pinned ? /* @__PURE__ */ jsxs("ul", { className: "hv-legend", "aria-hidden": "true", children: [
1119
+ /* @__PURE__ */ jsx("li", { className: "hv-sel", children: labels.legendSelected }),
1120
+ /* @__PURE__ */ jsx("li", { className: "hv-up", children: labels.legendUpstream }),
1121
+ /* @__PURE__ */ jsx("li", { className: "hv-down", children: labels.legendDownstream })
1122
+ ] }) : null,
1123
+ /* @__PURE__ */ jsx("p", { className: "hv-hint", id: helpId, children: labels.hint }),
1124
+ /* @__PURE__ */ jsx("output", { className: "hv-toast", role: "status", children: toast })
1125
+ ] })
1126
+ ] })
1127
+ }
1128
+ );
1129
+ }
1130
+ export {
1131
+ DiagramViewer
1132
+ };