@tdacorp/hyle-sdk 0.12.0 → 0.17.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 (43) hide show
  1. package/README.md +46 -12
  2. package/dist/check-routes-bin.js +31 -18
  3. package/dist/{chunk-S7PCCEHP.js → chunk-6VOHFFA5.js} +4 -3
  4. package/dist/{chunk-ZQFYH4FX.js → chunk-DMK4XQLU.js} +497 -327
  5. package/dist/{chunk-N7ZQUAGM.js → chunk-MGSUQBDW.js} +19 -7
  6. package/dist/{chunk-R5EMI4HQ.js → chunk-PJMJMP66.js} +3 -1
  7. package/dist/comments.cjs +6 -4
  8. package/dist/comments.js +6 -5
  9. package/dist/{diagram-viewer-DYX6R63Y.js → diagram-viewer-FJPED4SN.js} +46 -26
  10. package/dist/{embed-jCaSI31t.d.cts → embed-BmdwA2G9.d.cts} +51 -5
  11. package/dist/{embed-DL5QIZRJ.d.ts → embed-DNTZ2UXv.d.ts} +51 -5
  12. package/dist/index.cjs +19 -7
  13. package/dist/index.d.cts +15 -8
  14. package/dist/index.d.ts +15 -8
  15. package/dist/index.js +1 -1
  16. package/dist/labels-nmukKYgL.d.cts +37 -0
  17. package/dist/labels-nmukKYgL.d.ts +37 -0
  18. package/dist/mermaid-diagram.cjs +59 -30
  19. package/dist/mermaid-diagram.d.cts +4 -37
  20. package/dist/mermaid-diagram.d.ts +4 -37
  21. package/dist/mermaid-diagram.js +7 -5
  22. package/dist/mermaid-image.cjs +1382 -0
  23. package/dist/mermaid-image.d.cts +29 -0
  24. package/dist/mermaid-image.d.ts +29 -0
  25. package/dist/mermaid-image.js +94 -0
  26. package/dist/next.cjs +1235 -789
  27. package/dist/next.d.cts +149 -24
  28. package/dist/next.d.ts +149 -24
  29. package/dist/next.js +887 -612
  30. package/dist/react.cjs +336 -196
  31. package/dist/react.d.cts +39 -7
  32. package/dist/react.d.ts +39 -7
  33. package/dist/react.js +1 -1
  34. package/dist/{resolve-DvmuBlpO.d.ts → resolve-Ae7UFjsQ.d.ts} +5 -5
  35. package/dist/{resolve-f6IJ6SL9.d.cts → resolve-euZ4-aC9.d.cts} +5 -5
  36. package/dist/styles.css +11 -22
  37. package/dist/{types-5D6ZD0Wi.d.cts → types-Czt887Iv.d.cts} +32 -3
  38. package/dist/{types-5D6ZD0Wi.d.ts → types-Czt887Iv.d.ts} +32 -3
  39. package/dist/use-cache.cjs +1 -1
  40. package/dist/use-cache.d.cts +2 -2
  41. package/dist/use-cache.d.ts +2 -2
  42. package/dist/use-cache.js +2 -2
  43. package/package.json +1 -1
@@ -0,0 +1,1382 @@
1
+ "use strict";
2
+ "use client";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __esm = (fn, res) => function __init() {
8
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
9
+ };
10
+ var __export = (target, all) => {
11
+ for (var name in all)
12
+ __defProp(target, name, { get: all[name], enumerable: true });
13
+ };
14
+ var __copyProps = (to, from, except, desc) => {
15
+ if (from && typeof from === "object" || typeof from === "function") {
16
+ for (let key of __getOwnPropNames(from))
17
+ if (!__hasOwnProp.call(to, key) && key !== except)
18
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
19
+ }
20
+ return to;
21
+ };
22
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
23
+
24
+ // src/react/viewer/labels.ts
25
+ var VIEWER_LABELS_EN, fill;
26
+ var init_labels = __esm({
27
+ "src/react/viewer/labels.ts"() {
28
+ "use strict";
29
+ VIEWER_LABELS_EN = {
30
+ expand: "Expand diagram",
31
+ expandHint: "Expand",
32
+ viewer: "Diagram viewer",
33
+ close: "Close",
34
+ zoomIn: "Zoom in",
35
+ zoomOut: "Zoom out",
36
+ fit: "Fit to window",
37
+ actual: "Actual size",
38
+ search: "Find in diagram",
39
+ searchPlaceholder: "Find",
40
+ noMatch: "No match",
41
+ matchOf: "{n} of {total}",
42
+ copySource: "Copy diagram source",
43
+ downloadSvg: "Download SVG",
44
+ downloadPng: "Download PNG",
45
+ copyImage: "Copy as image",
46
+ pngScale: "PNG scale",
47
+ fullscreen: "Fullscreen",
48
+ exitFullscreen: "Exit fullscreen",
49
+ copied: "Copied",
50
+ saved: "Saved",
51
+ unavailable: "Not available here",
52
+ hint: "Scroll to zoom, drag to pan, click a node to trace its paths, press / to search",
53
+ legendSelected: "Selected",
54
+ legendUpstream: "Upstream",
55
+ legendDownstream: "Downstream",
56
+ outgoing: "outgoing",
57
+ tracing: "{label}: {up} upstream, {down} downstream",
58
+ map: "Overview map"
59
+ };
60
+ fill = (template, values) => template.replace(/\{(\w+)\}/g, (m, k) => k in values ? String(values[k]) : m);
61
+ }
62
+ });
63
+
64
+ // src/react/viewer/extract.ts
65
+ function translateOf(el) {
66
+ const m = /translate\(\s*(-?[\d.e+-]+)[\s,]*(-?[\d.e+-]+)?\s*\)/i.exec(el.getAttribute("transform") ?? "");
67
+ return m ? [Number(m[1]), Number(m[2] ?? 0)] : [0, 0];
68
+ }
69
+ function shapeRect(el, ox, oy) {
70
+ switch (tag(el)) {
71
+ case "rect": {
72
+ const w = num(el, "width");
73
+ const h = num(el, "height");
74
+ return w > 0 && h > 0 ? { x: ox + num(el, "x"), y: oy + num(el, "y"), w, h } : void 0;
75
+ }
76
+ case "circle":
77
+ case "ellipse": {
78
+ const rx = num(el, tag(el) === "circle" ? "r" : "rx");
79
+ const ry = num(el, tag(el) === "circle" ? "r" : "ry");
80
+ 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;
81
+ }
82
+ case "polygon":
83
+ case "path": {
84
+ const n = numbers(el.getAttribute(tag(el) === "polygon" ? "points" : "d") ?? "");
85
+ const xs = n.filter((_, i) => i % 2 === 0);
86
+ const ys = n.filter((_, i) => i % 2 === 1);
87
+ if (xs.length < 2 || ys.length < 2) return void 0;
88
+ const x0 = Math.min(...xs);
89
+ const y0 = Math.min(...ys);
90
+ return { x: ox + x0, y: oy + y0, w: Math.max(...xs) - x0, h: Math.max(...ys) - y0 };
91
+ }
92
+ default:
93
+ return void 0;
94
+ }
95
+ }
96
+ function nodeBox(node, cx, cy) {
97
+ const found = [];
98
+ const visit = (el, ox, oy) => {
99
+ for (const child of kids(el)) {
100
+ const t = tokens(child);
101
+ if (t.includes("label") || tag(child) === "foreignobject" || tag(child) === "text") continue;
102
+ const [dx, dy] = translateOf(child);
103
+ const r = SHAPES.has(tag(child)) ? shapeRect(child, ox + dx, oy + dy) : void 0;
104
+ if (r) found.push(r);
105
+ else visit(child, ox + dx, oy + dy);
106
+ }
107
+ };
108
+ visit(node, 0, 0);
109
+ if (!found.length) return { x: cx - 40, y: cy - 20, w: 80, h: 40 };
110
+ const x0 = Math.min(...found.map((r) => r.x));
111
+ const y0 = Math.min(...found.map((r) => r.y));
112
+ 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 };
113
+ }
114
+ function nearest(nodes, x, y) {
115
+ let best;
116
+ let d = GEOMETRY_SLACK;
117
+ for (const n of nodes) {
118
+ const nd = dist(n.box, x, y);
119
+ if (nd < d) d = nd, best = n.key;
120
+ }
121
+ return best;
122
+ }
123
+ function endsFromId(id, keys) {
124
+ const mid = /^L_(.+)_\d+$/.exec(id)?.[1];
125
+ if (!mid) return void 0;
126
+ for (let i = mid.indexOf("_"); i !== -1; i = mid.indexOf("_", i + 1)) {
127
+ const a = mid.slice(0, i);
128
+ const b = mid.slice(i + 1);
129
+ if (keys.has(a) && keys.has(b)) return [a, b];
130
+ }
131
+ return void 0;
132
+ }
133
+ function extractGraph(root, idPrefix = "") {
134
+ const rawNodes = [];
135
+ const paths = [];
136
+ const labels = [];
137
+ const visit = (el, ox, oy, parent) => {
138
+ for (const child of kids(el)) {
139
+ const t = tokens(child);
140
+ const [dx, dy] = translateOf(child);
141
+ const raw = child.getAttribute("id") ?? "";
142
+ const id = idPrefix && raw.startsWith(idPrefix) ? raw.slice(idPrefix.length) : raw;
143
+ if (tag(child) === "g" && t.includes("node") && !t.includes("cluster") && id) {
144
+ const box = nodeBox(child, ox + dx, oy + dy);
145
+ rawNodes.push({ el: child, key: nodeKey(id), label: clean(child.textContent), box });
146
+ continue;
147
+ }
148
+ if (tag(child) === "path" && parent.includes("edgePaths")) {
149
+ paths.push({ el: child, id, d: child.getAttribute("d") ?? "", start: child.getAttribute("marker-start") ?? "", end: child.getAttribute("marker-end") ?? "" });
150
+ continue;
151
+ }
152
+ if (tag(child) === "g" && parent.includes("edgeLabels")) {
153
+ labels.push(child);
154
+ continue;
155
+ }
156
+ visit(child, ox + dx, oy + dy, [...t.filter((c) => c === "edgePaths" || c === "edgeLabels")]);
157
+ }
158
+ };
159
+ visit(root, 0, 0, []);
160
+ const keys = new Set(rawNodes.map((n) => n.key));
161
+ const edges = [];
162
+ const sameCount = labels.length === paths.length;
163
+ paths.forEach((p, i) => {
164
+ const loop = /^(.+)-cyclic-special-(1|mid|2)$/.exec(p.id);
165
+ if (loop && keys.has(loop[1])) {
166
+ if (loop[2] === "1") edges.push({ el: p.el, from: loop[1], to: loop[1], label: clean(labels[i]?.textContent ?? null) });
167
+ return;
168
+ }
169
+ let ends = endsFromId(p.id, keys);
170
+ if (!ends) {
171
+ const n = numbers(p.d);
172
+ if (n.length < 4) return;
173
+ const a = nearest(rawNodes, n[0], n[1]);
174
+ const b = nearest(rawNodes, n[n.length - 2], n[n.length - 1]);
175
+ if (a === void 0 || b === void 0) return;
176
+ ends = p.start && !p.end ? [b, a] : [a, b];
177
+ }
178
+ const labelEl = sameCount ? labels[i] : void 0;
179
+ edges.push({ el: p.el, from: ends[0], to: ends[1], label: clean(labelEl?.textContent ?? null), ...labelEl ? { labelEl } : {} });
180
+ });
181
+ return { nodes: rawNodes, edges };
182
+ }
183
+ var tokens, tag, kids, num, clean, numbers, SHAPES, nodeKey, dist, GEOMETRY_SLACK;
184
+ var init_extract = __esm({
185
+ "src/react/viewer/extract.ts"() {
186
+ "use strict";
187
+ tokens = (el) => (el.getAttribute("class") ?? "").split(/\s+/).filter(Boolean);
188
+ tag = (el) => el.tagName.toLowerCase();
189
+ kids = (el) => Array.from(el.children);
190
+ num = (el, name) => Number.parseFloat(el.getAttribute(name) ?? "") || 0;
191
+ clean = (s) => (s ?? "").replace(/\s+/g, " ").trim();
192
+ numbers = (s) => (s.match(/-?\d*\.?\d+(?:e-?\d+)?/gi) ?? []).map(Number);
193
+ SHAPES = /* @__PURE__ */ new Set(["rect", "polygon", "circle", "ellipse", "path"]);
194
+ nodeKey = (id) => /^(?:flowchart|state|classId|entity|node)-(.+)-\d+$/.exec(id)?.[1] ?? id;
195
+ 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)));
196
+ GEOMETRY_SLACK = 28;
197
+ }
198
+ });
199
+
200
+ // src/react/viewer/graph.ts
201
+ function buildGraph(nodes, edges) {
202
+ const byKey = /* @__PURE__ */ new Map();
203
+ nodes.forEach((n, i) => byKey.has(n.key) || byKey.set(n.key, i));
204
+ const out = /* @__PURE__ */ new Map();
205
+ const inn = /* @__PURE__ */ new Map();
206
+ edges.forEach((e, i) => {
207
+ out.set(e.from, [...out.get(e.from) ?? [], i]);
208
+ inn.set(e.to, [...inn.get(e.to) ?? [], i]);
209
+ });
210
+ return { nodes, edges, byKey, out, inn };
211
+ }
212
+ function walk(g, start, next, far) {
213
+ const nodes = /* @__PURE__ */ new Set();
214
+ const edges = /* @__PURE__ */ new Set();
215
+ const queue = [start];
216
+ const seen = /* @__PURE__ */ new Set([start]);
217
+ for (let head = 0; head < queue.length; head++) {
218
+ for (const i of next.get(queue[head]) ?? []) {
219
+ edges.add(i);
220
+ const other = far(g.edges[i]);
221
+ nodes.add(other);
222
+ if (!seen.has(other)) seen.add(other), queue.push(other);
223
+ }
224
+ }
225
+ return { nodes, edges };
226
+ }
227
+ function trace(g, key) {
228
+ const up = walk(g, key, g.inn, (e) => e.from);
229
+ const down = walk(g, key, g.out, (e) => e.to);
230
+ return { up: up.nodes, down: down.nodes, upEdges: up.edges, downEdges: down.edges };
231
+ }
232
+ function neighbourhood(g, key) {
233
+ const edges = /* @__PURE__ */ new Set([...g.out.get(key) ?? [], ...g.inn.get(key) ?? []]);
234
+ const nodes = /* @__PURE__ */ new Set([key]);
235
+ for (const i of edges) nodes.add(g.edges[i].from), nodes.add(g.edges[i].to);
236
+ return { nodes, edges };
237
+ }
238
+ function pickNeighbour(g, key, dir) {
239
+ const from = g.byKey.get(key);
240
+ if (from === void 0) return void 0;
241
+ const [cx, cy] = centre(g.nodes[from].box);
242
+ const [vx, vy] = VEC[dir];
243
+ const best = (keys, cone) => {
244
+ let pick;
245
+ let cost = Infinity;
246
+ for (const k of keys) {
247
+ const i = g.byKey.get(k);
248
+ if (i === void 0 || k === key) continue;
249
+ const [x, y] = centre(g.nodes[i].box);
250
+ const along = (x - cx) * vx + (y - cy) * vy;
251
+ const across = Math.abs((x - cx) * vy - (y - cy) * vx);
252
+ if (along <= 0 || across > along * cone) continue;
253
+ const c = along + across * 2;
254
+ if (c < cost) cost = c, pick = k;
255
+ }
256
+ return pick;
257
+ };
258
+ const adjacent = /* @__PURE__ */ new Set();
259
+ for (const i of [...g.out.get(key) ?? [], ...g.inn.get(key) ?? []]) adjacent.add(g.edges[i].from), adjacent.add(g.edges[i].to);
260
+ return best(adjacent, CONE) ?? best(adjacent, Infinity) ?? best(g.byKey.keys(), CONE);
261
+ }
262
+ function searchNodes(nodes, query) {
263
+ const q = query.trim().toLowerCase();
264
+ if (!q) return [];
265
+ 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);
266
+ }
267
+ function describeNode(g, key, labels) {
268
+ const node = g.nodes[g.byKey.get(key) ?? -1];
269
+ if (!node) return key;
270
+ const out = g.out.get(key) ?? [];
271
+ if (!out.length) return node.label;
272
+ const targets = out.slice(0, MAX_TARGETS).map((i) => {
273
+ const e = g.edges[i];
274
+ return e.label || g.nodes[g.byKey.get(e.to) ?? -1]?.label || e.to;
275
+ });
276
+ const more = out.length > MAX_TARGETS ? ", ..." : "";
277
+ return `${node.label}, ${out.length} ${labels.outgoing}: ${targets.join(", ")}${more}`;
278
+ }
279
+ var VEC, centre, CONE, MAX_TARGETS, traceSummary;
280
+ var init_graph = __esm({
281
+ "src/react/viewer/graph.ts"() {
282
+ "use strict";
283
+ init_labels();
284
+ VEC = { up: [0, -1], down: [0, 1], left: [-1, 0], right: [1, 0] };
285
+ centre = (b) => [b.x + b.w / 2, b.y + b.h / 2];
286
+ CONE = 2;
287
+ MAX_TARGETS = 6;
288
+ traceSummary = (labels, label, t) => fill(labels.tracing, { label, up: t.up.size, down: t.down.size });
289
+ }
290
+ });
291
+
292
+ // src/react/viewer/scope-svg.ts
293
+ function scopeSvg(svg, oldId, newId) {
294
+ if (!/^[\w-]+$/.test(oldId) || !/^[\w-]+$/.test(newId)) throw new Error("unsafe svg id");
295
+ const token = new RegExp(`(?<![\\w-])${escapeRe(oldId)}(?![A-Za-z0-9-])`, "g");
296
+ const rooted = svg.replace(SEGMENT, (segment) => segment.replace(token, newId));
297
+ const fresh = /* @__PURE__ */ new Map();
298
+ for (const segment of rooted.match(SEGMENT) ?? []) {
299
+ if (!isTag(segment)) continue;
300
+ for (const m of segment.matchAll(/\sid="([^"]*)"/g)) if (!m[1].startsWith(`${newId}_`) && m[1] !== newId) fresh.set(m[1], `${newId}_${m[1]}`);
301
+ }
302
+ if (!fresh.size) return rooted;
303
+ const to = (id) => fresh.get(id) ?? id;
304
+ return rooted.replace(
305
+ SEGMENT,
306
+ (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(" ")}"`)
307
+ );
308
+ }
309
+ function svgSize(svg) {
310
+ const vb = /^\s*<svg\b[^>]*?\sviewBox="([^"]*)"/i.exec(svg)?.[1];
311
+ const n = vb?.split(/[\s,]+/).map(Number);
312
+ const w = n?.[2];
313
+ const h = n?.[3];
314
+ return w && h && w > 0 && h > 0 && Number.isFinite(w) && Number.isFinite(h) ? { w, h } : void 0;
315
+ }
316
+ function standaloneSvg(svg) {
317
+ const size = svgSize(svg);
318
+ const open = /^\s*<svg\b[^>]*>/i.exec(svg)?.[0];
319
+ if (!size || !open) return svg;
320
+ let tagText = open.replace(/\s(?:width|height)="[^"]*"/gi, "");
321
+ if (!/\sxmlns="/i.test(tagText)) tagText = tagText.replace(/^\s*<svg/i, '<svg xmlns="http://www.w3.org/2000/svg"');
322
+ tagText = tagText.replace(/^(\s*<svg)/i, `$1 width="${size.w}" height="${size.h}"`);
323
+ return svg.replace(open, tagText);
324
+ }
325
+ var SEGMENT, escapeRe, isTag;
326
+ var init_scope_svg = __esm({
327
+ "src/react/viewer/scope-svg.ts"() {
328
+ "use strict";
329
+ SEGMENT = /<style\b[^>]*>[\s\S]*?<\/style>|<[^<>]+>/gi;
330
+ escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
331
+ isTag = (segment) => !/^<style\b/i.test(segment);
332
+ }
333
+ });
334
+
335
+ // src/react/viewer/svg-css.ts
336
+ var SVG_CSS;
337
+ var init_svg_css = __esm({
338
+ "src/react/viewer/svg-css.ts"() {
339
+ "use strict";
340
+ SVG_CSS = `
341
+ svg{display:block;position:static!important;width:100%;height:100%;max-width:none!important}
342
+ .hv-n{cursor:pointer;outline:none}
343
+ .hv-n,.hv-e{transition:opacity .15s}
344
+ @media (prefers-reduced-motion:reduce){.hv-n,.hv-e{transition:none}}
345
+ :host(.hv-plain) .hv-n,:host(.hv-plain) .hv-e{transition:none}
346
+ :host(.hv-active) .hv-n:not(.hv-on),:host(.hv-active) .hv-e:not(.hv-on){opacity:var(--hv-dim)}
347
+ .hv-n:focus-visible :is(rect,polygon,circle,ellipse,path){stroke:var(--hv-focus)!important;stroke-width:calc(3px / var(--hv-k,1))!important}
348
+ .hv-n.hv-nb :is(rect,polygon,circle,ellipse,path){stroke:var(--hv-accent)!important;stroke-width:calc(2px / var(--hv-k,1))!important}
349
+ .hv-n.hv-up :is(rect,polygon,circle,ellipse,path){stroke:var(--hv-up)!important;stroke-width:calc(2.5px / var(--hv-k,1))!important}
350
+ .hv-n.hv-down :is(rect,polygon,circle,ellipse,path){stroke:var(--hv-down)!important;stroke-width:calc(2.5px / var(--hv-k,1))!important}
351
+ .hv-n.hv-sel :is(rect,polygon,circle,ellipse,path){stroke:var(--hv-accent)!important;stroke-width:calc(3.5px / var(--hv-k,1))!important}
352
+ .hv-n.hv-hit :is(rect,polygon,circle,ellipse,path){stroke:var(--hv-accent)!important;stroke-width:calc(3px / var(--hv-k,1))!important}
353
+ .hv-n.hv-cur :is(rect,polygon,circle,ellipse,path){stroke-width:calc(5px / var(--hv-k,1))!important}
354
+ text.hv-hit,text.hv-hit tspan{fill:var(--hv-accent)!important;font-weight:700}
355
+ text.hv-cur{text-decoration:underline}
356
+ path.hv-nb{stroke:var(--hv-accent)!important;stroke-width:calc(2.5px / var(--hv-k,1))!important}
357
+ path.hv-up{stroke:var(--hv-up)!important;stroke-width:calc(2.5px / var(--hv-k,1))!important}
358
+ path.hv-down{stroke:var(--hv-down)!important;stroke-width:calc(2.5px / var(--hv-k,1))!important}
359
+ path.hv-flow{stroke-dasharray:calc(7px / var(--hv-k,1)) calc(6px / var(--hv-k,1))!important;animation:hv-dash .9s linear infinite}
360
+ @keyframes hv-dash{to{stroke-dashoffset:calc(-26px / var(--hv-k,1))}}
361
+ @media (prefers-reduced-motion:reduce){path.hv-flow{animation:none}}
362
+ `;
363
+ }
364
+ });
365
+
366
+ // src/react/viewer/view-math.ts
367
+ function zoomAt(v, px, py, k, min = MIN_K) {
368
+ const next = clamp(k, min, MAX_K);
369
+ const r = next / v.k;
370
+ return { k: next, x: px - (px - v.x) * r, y: py - (py - v.y) * r };
371
+ }
372
+ function fitRect(r, vw, vh, pad = 32, maxK = FIT_MAX_K) {
373
+ 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));
374
+ return { k, x: (vw - r.w * k) / 2 - r.x * k, y: (vh - r.h * k) / 2 - r.y * k };
375
+ }
376
+ function keepVisible(v, c, vw, vh, margin = 80) {
377
+ const axis = (pos, start, size, extent) => {
378
+ const m = Math.min(margin, extent / 2, size * v.k);
379
+ const lo = m - (start + size) * v.k;
380
+ const hi = extent - m - start * v.k;
381
+ return lo > hi ? pos : clamp(pos, lo, hi);
382
+ };
383
+ return { k: v.k, x: axis(v.x, c.x, c.w, vw), y: axis(v.y, c.y, c.h, vh) };
384
+ }
385
+ function wheelFactor(deltaY, deltaMode, ctrl) {
386
+ const px = deltaMode === 1 ? deltaY * 16 : deltaMode === 2 ? deltaY * 400 : deltaY;
387
+ return Math.exp(-clamp(px, -120, 120) * (ctrl ? 0.01 : 16e-4));
388
+ }
389
+ function pinchView(start, a0, b0, a1, b1, min = MIN_K) {
390
+ const d0 = Math.hypot(a0.x - b0.x, a0.y - b0.y) || 1;
391
+ const d1 = Math.hypot(a1.x - b1.x, a1.y - b1.y);
392
+ const k = clamp(start.k * (d1 / d0), min, MAX_K);
393
+ const c0 = { x: (a0.x + b0.x) / 2, y: (a0.y + b0.y) / 2 };
394
+ const c1 = { x: (a1.x + b1.x) / 2, y: (a1.y + b1.y) / 2 };
395
+ const wx = (c0.x - start.x) / start.k;
396
+ const wy = (c0.y - start.y) / start.k;
397
+ return { k, x: c1.x - wx * k, y: c1.y - wy * k };
398
+ }
399
+ function releaseVelocity(samples, now) {
400
+ const recent = samples.filter((s) => now - s.t <= 100);
401
+ const first = recent[0];
402
+ const last = recent[recent.length - 1];
403
+ if (!first || !last || last === first || now - last.t > 60) return { x: 0, y: 0 };
404
+ const dt = last.t - first.t || 1;
405
+ return { x: (last.x - first.x) / dt, y: (last.y - first.y) / dt };
406
+ }
407
+ function stepInertia(vel, dt) {
408
+ const decay = Math.exp(-dt / INERTIA_TAU);
409
+ const travel = INERTIA_TAU * (1 - decay);
410
+ const next = { x: vel.x * decay, y: vel.y * decay };
411
+ return { dx: vel.x * travel, dy: vel.y * travel, vel: next, done: Math.hypot(next.x, next.y) < STOP_SPEED };
412
+ }
413
+ function lerpView(a, b, t) {
414
+ 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 };
415
+ }
416
+ function unionRect(rects) {
417
+ if (!rects.length) return void 0;
418
+ const x0 = Math.min(...rects.map((r) => r.x));
419
+ const y0 = Math.min(...rects.map((r) => r.y));
420
+ const x1 = Math.max(...rects.map((r) => r.x + r.w));
421
+ const y1 = Math.max(...rects.map((r) => r.y + r.h));
422
+ return { x: x0, y: y0, w: x1 - x0, h: y1 - y0 };
423
+ }
424
+ function revealRect(v, r, vw, vh, pad = 48) {
425
+ const shift = (pos, start, size, extent) => {
426
+ const lo = pos + start * v.k;
427
+ const hi = lo + size * v.k;
428
+ if (hi - lo > extent - 2 * pad) return pos + (extent - (lo + hi)) / 2;
429
+ if (lo < pad) return pos + pad - lo;
430
+ if (hi > extent - pad) return pos + extent - pad - hi;
431
+ return pos;
432
+ };
433
+ return { k: v.k, x: shift(v.x, r.x, r.w, vw), y: shift(v.y, r.y, r.h, vh) };
434
+ }
435
+ var MIN_K, MAX_K, FIT_MIN_K, FIT_MAX_K, INERTIA_TAU, STOP_SPEED, clamp, easeOutCubic, MINIMAP_MIN_NODES, showMinimap, centerOn;
436
+ var init_view_math = __esm({
437
+ "src/react/viewer/view-math.ts"() {
438
+ "use strict";
439
+ MIN_K = 0.2;
440
+ MAX_K = 10;
441
+ FIT_MIN_K = 0.02;
442
+ FIT_MAX_K = 3;
443
+ INERTIA_TAU = 325;
444
+ STOP_SPEED = 0.02;
445
+ clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
446
+ easeOutCubic = (t) => 1 - (1 - clamp(t, 0, 1)) ** 3;
447
+ MINIMAP_MIN_NODES = 12;
448
+ showMinimap = (nodeCount) => nodeCount >= MINIMAP_MIN_NODES;
449
+ centerOn = (v, wx, wy, vw, vh) => ({ k: v.k, x: vw / 2 - wx * v.k, y: vh / 2 - wy * v.k });
450
+ }
451
+ });
452
+
453
+ // src/react/viewer/controller.ts
454
+ var TAP_SLOP, DOUBLE_TAP_MS, DOUBLE_TAP_DIST, TWEEN_MS, FOCUS_MAX_K, KEY_PAN, KEY_ZOOM, FADE_MAX_NODES, FLOW_MAX_EDGES, HIT, STATE_CLASSES, reduced, DiagramController;
455
+ var init_controller = __esm({
456
+ "src/react/viewer/controller.ts"() {
457
+ "use strict";
458
+ init_extract();
459
+ init_graph();
460
+ init_scope_svg();
461
+ init_svg_css();
462
+ init_view_math();
463
+ TAP_SLOP = 5;
464
+ DOUBLE_TAP_MS = 350;
465
+ DOUBLE_TAP_DIST = 32;
466
+ TWEEN_MS = 380;
467
+ FOCUS_MAX_K = 2.5;
468
+ KEY_PAN = 64;
469
+ KEY_ZOOM = 1.25;
470
+ FADE_MAX_NODES = 150;
471
+ FLOW_MAX_EDGES = 120;
472
+ HIT = ["hv-hit", "hv-cur"];
473
+ STATE_CLASSES = ["hv-on", "hv-sel", "hv-up", "hv-down", "hv-nb", "hv-flow"];
474
+ reduced = () => globalThis.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false;
475
+ DiagramController = class {
476
+ constructor(o) {
477
+ this.o = o;
478
+ const { viewport: vp, stage, minimap } = o;
479
+ const root = this.root = stage.shadowRoot ?? stage.attachShadow({ mode: "open" });
480
+ const on = (el, type, fn, opts) => {
481
+ el.addEventListener(type, fn, opts);
482
+ this.off.push(() => el.removeEventListener(type, fn, opts));
483
+ };
484
+ on(vp, "wheel", (e) => this.onWheel(e), { passive: false });
485
+ on(vp, "pointerdown", (e) => this.onDown(e));
486
+ on(vp, "pointermove", (e) => this.onMove(e));
487
+ on(vp, "pointerup", (e) => this.onUp(e));
488
+ on(vp, "pointercancel", (e) => this.onUp(e, true));
489
+ on(root, "pointerover", (e) => e.pointerType === "mouse" && !this.pointers.size && this.mouseOver(this.keyAt(e.target)));
490
+ on(root, "pointerout", (e) => e.pointerType === "mouse" && !this.pointers.size && this.mouseOver(this.keyAt(e.relatedTarget)));
491
+ on(root, "focusin", (e) => this.onFocusIn(e));
492
+ on(root, "focusout", () => this.focusLeft());
493
+ on(minimap, "pointerdown", (e) => this.onMiniDown(e));
494
+ on(minimap, "pointermove", (e) => this.miniDrag && this.miniTo(e));
495
+ on(minimap, "pointerup", () => this.miniDrag = false);
496
+ on(minimap, "pointercancel", () => this.miniDrag = false);
497
+ this.ro = new ResizeObserver(() => this.measure());
498
+ this.ro.observe(vp);
499
+ this.measure();
500
+ }
501
+ o;
502
+ view = { x: 0, y: 0, k: 1 };
503
+ content = { x: 0, y: 0, w: 1, h: 1 };
504
+ vw = 0;
505
+ vh = 0;
506
+ needFit = true;
507
+ /** The lowest zoom: 0.2x, or lower when the diagram needs it to fit at all. */
508
+ minK = MIN_K;
509
+ dirty = false;
510
+ kWritten = 0;
511
+ frame = 0;
512
+ anim;
513
+ svg;
514
+ graph;
515
+ nodes = [];
516
+ edges = [];
517
+ nodeIndex = /* @__PURE__ */ new Map();
518
+ touched = [];
519
+ hits = [];
520
+ hitEls = [];
521
+ query = "";
522
+ cursor = -1;
523
+ pinned = null;
524
+ hot = null;
525
+ mouseKey = null;
526
+ focusKey = null;
527
+ roving;
528
+ pointers = /* @__PURE__ */ new Map();
529
+ start;
530
+ pinch;
531
+ tap;
532
+ lastTap;
533
+ dragging = false;
534
+ samples = [];
535
+ ro;
536
+ root;
537
+ miniDrag = false;
538
+ miniColors = { node: "#888", edge: "#555", view: "#0af", bg: "transparent" };
539
+ off = [];
540
+ destroy() {
541
+ this.anim?.stop();
542
+ cancelAnimationFrame(this.frame);
543
+ this.ro?.disconnect();
544
+ for (const f of this.off) f();
545
+ }
546
+ // ---- mounting -----------------------------------------------------------------------------------------------------------------------
547
+ /** Shows `markup` in the stage's shadow root and attaches to its SVG. A new SVG (theme change) keeps the view and a still-valid pin. */
548
+ show(markup, idPrefix) {
549
+ this.root.innerHTML = `<style>${SVG_CSS}</style>${markup}`;
550
+ const svg = this.root.querySelector("svg");
551
+ if (svg) this.mount(svg, markup, idPrefix);
552
+ }
553
+ mount(svg, markup, idPrefix) {
554
+ const size = svgSize(markup) ?? { w: svg.getBoundingClientRect().width || 600, h: svg.getBoundingClientRect().height || 400 };
555
+ const first = this.svg === void 0;
556
+ this.svg = svg;
557
+ this.content = { x: 0, y: 0, w: size.w, h: size.h };
558
+ this.o.stage.style.width = `${size.w}px`;
559
+ this.o.stage.style.height = `${size.h}px`;
560
+ this.touched = [];
561
+ this.hitEls = [];
562
+ this.hits = [];
563
+ this.roving = void 0;
564
+ this.indexGraph(svg, idPrefix);
565
+ if (first || this.needFit) this.needFit = true;
566
+ this.measure();
567
+ if (this.pinned && !this.graph?.byKey.has(this.pinned)) this.pinned = null;
568
+ this.paint();
569
+ const again = this.focusKey === null ? void 0 : this.graph?.byKey.get(this.focusKey);
570
+ if (again !== void 0) this.nodes[again]?.el?.focus({ preventScroll: true });
571
+ if (this.query) this.search(this.query, false);
572
+ this.readMiniColors();
573
+ this.emit();
574
+ this.request();
575
+ }
576
+ indexGraph(svg, idPrefix) {
577
+ let ex;
578
+ try {
579
+ ex = extractGraph(svg, idPrefix);
580
+ } catch {
581
+ ex = { nodes: [], edges: [] };
582
+ }
583
+ this.nodes = ex.nodes.map((n) => ({ el: n.el, key: n.key, box: n.box }));
584
+ this.edges = ex.edges.map((e) => ({ el: e.el, ...e.labelEl ? { labelEl: e.labelEl } : {} }));
585
+ this.nodeIndex = new Map(this.nodes.map((n, i) => [n.el, i]));
586
+ this.graph = this.nodes.length ? buildGraph(ex.nodes, ex.edges) : void 0;
587
+ const labels = this.o.labels();
588
+ this.nodes.forEach((n, i) => {
589
+ n.el.classList.add("hv-n");
590
+ n.el.setAttribute("tabindex", i === 0 ? "0" : "-1");
591
+ n.el.setAttribute("role", "button");
592
+ n.el.setAttribute("aria-label", describeNode(this.graph, n.key, labels));
593
+ n.el.setAttribute("aria-pressed", "false");
594
+ });
595
+ if (this.nodes[0]) this.roving = this.nodes[0].el;
596
+ for (const e of this.edges) e.el.classList.add("hv-e"), e.labelEl?.classList.add("hv-e");
597
+ this.o.stage.classList.toggle("hv-plain", this.nodes.length > FADE_MAX_NODES);
598
+ }
599
+ // ---- view ---------------------------------------------------------------------------------------------------------------------------
600
+ measure() {
601
+ const r = this.o.viewport.getBoundingClientRect();
602
+ this.vw = r.width;
603
+ this.vh = r.height;
604
+ if (this.vw > 0 && this.vh > 0) this.minK = Math.min(MIN_K, this.fitView(this.content).k);
605
+ if (this.needFit && this.vw > 0 && this.vh > 0) {
606
+ this.needFit = false;
607
+ this.view = this.fitView(this.content);
608
+ this.request();
609
+ }
610
+ }
611
+ fitView(r, maxK) {
612
+ return fitRect(r, this.vw, this.vh, Math.min(48, this.vw / 8), maxK);
613
+ }
614
+ request() {
615
+ if (this.dirty) return;
616
+ this.dirty = true;
617
+ this.frame = requestAnimationFrame(() => {
618
+ this.dirty = false;
619
+ const { x, y, k } = this.view;
620
+ this.o.stage.style.transform = `translate(${x}px, ${y}px) scale(${k})`;
621
+ this.o.zoomOutput.textContent = `${Math.round(k * 100)}%`;
622
+ this.syncK();
623
+ this.drawMinimap();
624
+ });
625
+ }
626
+ /** Publishes the zoom to CSS as --hv-k, but only while something is highlighted (a new value restyles the highlighted strokes). */
627
+ syncK() {
628
+ if (!this.touched.length && !this.hitEls.length) return;
629
+ const k = Math.round(this.view.k * 100) / 100;
630
+ if (k === this.kWritten) return;
631
+ this.kWritten = k;
632
+ this.o.stage.style.setProperty("--hv-k", String(k));
633
+ }
634
+ set(v) {
635
+ this.view = keepVisible(v, this.content, this.vw, this.vh);
636
+ this.request();
637
+ }
638
+ stopAnim() {
639
+ this.anim?.stop();
640
+ this.anim = void 0;
641
+ }
642
+ /** Moves to `target`: instantly under reduced motion, otherwise an eased tween that any input cancels. */
643
+ go(target) {
644
+ this.stopAnim();
645
+ const goal = keepVisible(target, this.content, this.vw, this.vh);
646
+ if (reduced()) return this.set(goal);
647
+ const from = this.view;
648
+ const t0 = performance.now();
649
+ let id = 0;
650
+ const tick = (now) => {
651
+ const t = (now - t0) / TWEEN_MS;
652
+ this.view = t >= 1 ? goal : lerpView(from, goal, easeOutCubic(t));
653
+ this.request();
654
+ if (t < 1) id = requestAnimationFrame(tick);
655
+ else this.anim = void 0;
656
+ };
657
+ id = requestAnimationFrame(tick);
658
+ this.anim = { stop: () => cancelAnimationFrame(id) };
659
+ }
660
+ zoomBy(factor) {
661
+ this.go(zoomAt(this.view, this.vw / 2, this.vh / 2, this.view.k * factor, this.minK));
662
+ }
663
+ fit() {
664
+ this.go(this.fitView(this.content));
665
+ }
666
+ actual() {
667
+ this.go(zoomAt(this.view, this.vw / 2, this.vh / 2, 1));
668
+ }
669
+ /** The current zoom, for tests and the live region. */
670
+ scale() {
671
+ return this.view.k;
672
+ }
673
+ local(e) {
674
+ const r = this.o.viewport.getBoundingClientRect();
675
+ return { x: e.clientX - r.left, y: e.clientY - r.top };
676
+ }
677
+ onWheel(e) {
678
+ e.preventDefault();
679
+ this.stopAnim();
680
+ const p = this.local(e);
681
+ this.set(zoomAt(this.view, p.x, p.y, this.view.k * wheelFactor(e.deltaY, e.deltaMode, e.ctrlKey), this.minK));
682
+ }
683
+ // ---- pointers -----------------------------------------------------------------------------------------------------------------------
684
+ onDown(e) {
685
+ if (e.pointerType === "mouse" && e.button !== 0) return;
686
+ this.stopAnim();
687
+ const at = this.local(e);
688
+ this.pointers.set(e.pointerId, at);
689
+ if (this.pointers.size === 1) {
690
+ const target = e.composedPath()[0];
691
+ const key = this.keyAt(target);
692
+ this.tap = { at, key, moved: false, link: Boolean(target.closest?.("a")), id: e.pointerId };
693
+ this.start = { view: this.view, at };
694
+ this.dragging = false;
695
+ this.samples = [{ t: e.timeStamp, ...at }];
696
+ } else if (this.pointers.size === 2) {
697
+ const [a, b] = [...this.pointers.values()];
698
+ this.pinch = { view: this.view, a, b };
699
+ this.tap = void 0;
700
+ this.dragging = true;
701
+ for (const id of this.pointers.keys()) this.capture(id);
702
+ }
703
+ }
704
+ onMove(e) {
705
+ if (!this.pointers.has(e.pointerId)) return;
706
+ const at = this.local(e);
707
+ this.pointers.set(e.pointerId, at);
708
+ if (this.pinch && this.pointers.size >= 2) {
709
+ const [a, b] = [...this.pointers.values()];
710
+ this.set(pinchView(this.pinch.view, this.pinch.a, this.pinch.b, a, b, this.minK));
711
+ return;
712
+ }
713
+ if (!this.start) return;
714
+ if (!this.dragging && this.tap && Math.hypot(at.x - this.tap.at.x, at.y - this.tap.at.y) > TAP_SLOP) {
715
+ this.dragging = true;
716
+ this.tap.moved = true;
717
+ this.capture(this.tap.id);
718
+ this.o.viewport.classList.add("hv-grabbing");
719
+ }
720
+ if (this.dragging) this.dragTo(at, e.timeStamp);
721
+ }
722
+ capture(id) {
723
+ try {
724
+ this.o.viewport.setPointerCapture(id);
725
+ } catch {
726
+ }
727
+ }
728
+ dragTo(at, t) {
729
+ const s = this.start;
730
+ this.set({ k: s.view.k, x: s.view.x + at.x - s.at.x, y: s.view.y + at.y - s.at.y });
731
+ this.samples.push({ t, ...at });
732
+ if (this.samples.length > 12) this.samples.shift();
733
+ }
734
+ onUp(e, cancelled = false) {
735
+ if (!this.pointers.delete(e.pointerId)) return;
736
+ try {
737
+ this.o.viewport.releasePointerCapture(e.pointerId);
738
+ } catch {
739
+ }
740
+ if (this.pinch) {
741
+ this.pinch = void 0;
742
+ const rest = [...this.pointers.values()][0];
743
+ this.start = rest ? { view: this.view, at: rest } : void 0;
744
+ this.tap = rest ? { at: rest, key: null, moved: true, link: false, id: -1 } : void 0;
745
+ this.dragging = Boolean(rest);
746
+ this.samples = [];
747
+ if (!rest) this.o.viewport.classList.remove("hv-grabbing");
748
+ return;
749
+ }
750
+ if (this.pointers.size > 0) return;
751
+ this.o.viewport.classList.remove("hv-grabbing");
752
+ const tap = this.tap;
753
+ this.tap = void 0;
754
+ this.start = void 0;
755
+ if (cancelled) return void (this.dragging = false);
756
+ if (tap && !tap.moved) this.onTap(tap.at, tap.key, e.timeStamp, tap.link);
757
+ else if (this.dragging && !reduced()) this.glide(releaseVelocity(this.samples, e.timeStamp));
758
+ this.dragging = false;
759
+ }
760
+ glide(v0) {
761
+ if (Math.hypot(v0.x, v0.y) < 0.1) return;
762
+ let vel = v0;
763
+ let last = performance.now();
764
+ let id = 0;
765
+ const tick = (now) => {
766
+ const dt = Math.min(now - last, 50);
767
+ last = now;
768
+ const s = stepInertia(vel, dt);
769
+ vel = s.vel;
770
+ this.set({ k: this.view.k, x: this.view.x + s.dx, y: this.view.y + s.dy });
771
+ if (s.done) this.anim = void 0;
772
+ else id = requestAnimationFrame(tick);
773
+ };
774
+ id = requestAnimationFrame(tick);
775
+ this.anim = { stop: () => cancelAnimationFrame(id) };
776
+ }
777
+ onTap(at, key, t, link) {
778
+ const prev = this.lastTap;
779
+ const isDouble = prev && t - prev.t < DOUBLE_TAP_MS && Math.hypot(at.x - prev.at.x, at.y - prev.at.y) < DOUBLE_TAP_DIST;
780
+ this.lastTap = isDouble ? void 0 : { t, at };
781
+ if (isDouble) {
782
+ if (key) this.focusNode(key);
783
+ else this.go(zoomAt(this.view, at.x, at.y, this.view.k * 2, this.minK));
784
+ return;
785
+ }
786
+ if (key && link) return;
787
+ if (key) {
788
+ this.nodes[this.graph.byKey.get(key)]?.el?.focus?.({ preventScroll: true });
789
+ this.pin(this.pinned === key ? null : key);
790
+ } else {
791
+ this.pin(null);
792
+ this.o.viewport.focus({ preventScroll: true });
793
+ }
794
+ }
795
+ keyAt(target) {
796
+ const node = target?.closest?.(".hv-n");
797
+ const i = node ? this.nodeIndex.get(node) : void 0;
798
+ return i === void 0 ? null : this.nodes[i].key;
799
+ }
800
+ // ---- node interaction ---------------------------------------------------------------------------------------------------------------
801
+ /** Hover highlight follows the mouse when it is over a node, otherwise the keyboard-focused node. */
802
+ mouseOver(key) {
803
+ this.mouseKey = key;
804
+ this.refreshHot();
805
+ }
806
+ refreshHot() {
807
+ const key = this.mouseKey ?? this.focusKey;
808
+ if (key === this.hot) return;
809
+ this.hot = key;
810
+ if (!this.pinned) this.paint();
811
+ }
812
+ onFocusIn(e) {
813
+ const key = this.keyAt(e.target);
814
+ if (key === null) return;
815
+ const el = e.target.closest(".hv-n");
816
+ if (this.roving && this.roving !== el) this.roving.setAttribute("tabindex", "-1");
817
+ el.setAttribute("tabindex", "0");
818
+ this.roving = el;
819
+ this.focusKey = key;
820
+ this.refreshHot();
821
+ }
822
+ focusLeft() {
823
+ queueMicrotask(() => {
824
+ if (this.root.activeElement) return;
825
+ this.focusKey = null;
826
+ this.refreshHot();
827
+ });
828
+ }
829
+ pin(key) {
830
+ if (key === this.pinned) return;
831
+ this.pinned = key;
832
+ this.paint();
833
+ if (key && this.graph) this.o.announce(traceSummary(this.o.labels(), this.graph.nodes[this.graph.byKey.get(key)].label, trace(this.graph, key)));
834
+ this.emit();
835
+ }
836
+ /** Recomputes which elements are highlighted. Only changed elements are touched; dimming is one class on the stage. */
837
+ paint() {
838
+ for (const el of this.touched) el.classList.remove(...STATE_CLASSES);
839
+ this.touched = [];
840
+ const g = this.graph;
841
+ const mark = (el, ...cls) => {
842
+ if (!el) return;
843
+ el.classList.add("hv-on", ...cls);
844
+ this.touched.push(el);
845
+ };
846
+ const at = (key) => this.nodes[g.byKey.get(key)];
847
+ let active = false;
848
+ if (g && this.pinned) {
849
+ active = true;
850
+ const t = trace(g, this.pinned);
851
+ for (const k of t.up) mark(at(k)?.el, "hv-up");
852
+ for (const k of t.down) mark(at(k)?.el, "hv-down");
853
+ mark(at(this.pinned)?.el, "hv-sel");
854
+ const flow = t.upEdges.size + t.downEdges.size <= FLOW_MAX_EDGES ? ["hv-flow"] : [];
855
+ for (const i of t.upEdges) mark(this.edges[i]?.el, "hv-up", ...flow), mark(this.edges[i]?.labelEl, "hv-up");
856
+ for (const i of t.downEdges) mark(this.edges[i]?.el, "hv-down", ...flow), mark(this.edges[i]?.labelEl, "hv-down");
857
+ } else if (g && this.hot) {
858
+ active = true;
859
+ const n = neighbourhood(g, this.hot);
860
+ for (const k of n.nodes) mark(at(k)?.el, k === this.hot ? "hv-sel" : "hv-nb");
861
+ for (const i of n.edges) mark(this.edges[i]?.el, "hv-nb"), mark(this.edges[i]?.labelEl, "hv-nb");
862
+ } else if (this.query && this.hitEls.length) {
863
+ active = true;
864
+ for (const el of this.hitEls) mark(el);
865
+ }
866
+ this.o.stage.classList.toggle("hv-active", active);
867
+ this.syncK();
868
+ for (const n of this.nodes) n.el.setAttribute("aria-pressed", String(n.key === this.pinned));
869
+ }
870
+ /** Zooms to a node and its direct neighbours. */
871
+ focusNode(key) {
872
+ const k = key ?? this.pinned ?? this.hot ?? this.nodes[0]?.key;
873
+ if (!k || !this.graph) return;
874
+ const rects = [...neighbourhood(this.graph, k).nodes].map((x) => this.graph.nodes[this.graph.byKey.get(x)].box);
875
+ const box = unionRect(rects);
876
+ if (box) this.go(this.fitView(box, FOCUS_MAX_K));
877
+ }
878
+ /** Arrow-key traversal from the focused node. Returns false when the key was not used. */
879
+ traverse(dir) {
880
+ const el = this.root.activeElement?.closest?.(".hv-n") ?? null;
881
+ const key = el && this.stageHas(el) ? this.keyAt(el) : null;
882
+ if (key === null || !this.graph) return false;
883
+ const next = pickNeighbour(this.graph, key, dir);
884
+ const target = next === void 0 ? void 0 : this.nodes[this.graph.byKey.get(next)];
885
+ if (target) {
886
+ target.el.focus({ preventScroll: true });
887
+ this.go(revealRect(this.view, target.box, this.vw, this.vh));
888
+ }
889
+ return true;
890
+ }
891
+ stageHas(el) {
892
+ return this.root.contains(el);
893
+ }
894
+ /** Keyboard commands of the viewer. Returns true when the key was handled (the caller then prevents the default). */
895
+ key(e) {
896
+ if (e.altKey || e.ctrlKey || e.metaKey) return false;
897
+ const arrows = { ArrowUp: "up", ArrowDown: "down", ArrowLeft: "left", ArrowRight: "right" };
898
+ const dir = arrows[e.key];
899
+ if (dir) {
900
+ if (this.traverse(dir)) return true;
901
+ const step = KEY_PAN * (e.shiftKey ? 4 : 1);
902
+ this.stopAnim();
903
+ 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) });
904
+ return true;
905
+ }
906
+ const onNode = this.keyAt(this.root.activeElement);
907
+ switch (e.key) {
908
+ case "+":
909
+ case "=":
910
+ return this.zoomBy(KEY_ZOOM), true;
911
+ case "-":
912
+ case "_":
913
+ return this.zoomBy(1 / KEY_ZOOM), true;
914
+ case "0":
915
+ case "Home":
916
+ return this.fit(), true;
917
+ case "1":
918
+ return this.actual(), true;
919
+ case "f":
920
+ case "F":
921
+ return this.focusNode(onNode), true;
922
+ case "Enter":
923
+ case " ":
924
+ if (onNode === null) return false;
925
+ return this.pin(this.pinned === onNode ? null : onNode), true;
926
+ default:
927
+ return false;
928
+ }
929
+ }
930
+ // ---- search -------------------------------------------------------------------------------------------------------------------------
931
+ /** Highlights matches of `query`; graph nodes when the diagram has them, otherwise every SVG text element. Returns the match count. */
932
+ search(query, jump = true) {
933
+ for (const el of this.hitEls) el.classList.remove(...HIT);
934
+ this.query = query.trim();
935
+ this.hits = [];
936
+ this.hitEls = [];
937
+ this.cursor = -1;
938
+ if (this.query && this.graph) {
939
+ const keys = new Set(searchNodes(this.graph.nodes, this.query));
940
+ 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 }));
941
+ } else if (this.query && this.svg) {
942
+ const q = this.query.toLowerCase();
943
+ this.hits = Array.from(this.svg.querySelectorAll("text")).filter((t) => (t.textContent ?? "").toLowerCase().includes(q)).map((el) => ({ el, box: () => this.worldRect(el) }));
944
+ }
945
+ this.hitEls = this.hits.map((h) => h.el);
946
+ for (const el of this.hitEls) el.classList.add("hv-hit");
947
+ this.paint();
948
+ if (this.hits.length && jump) this.step(1);
949
+ else this.emit();
950
+ return this.hits.length;
951
+ }
952
+ /** Moves to the next (or previous) match and brings it into view. */
953
+ step(by) {
954
+ if (!this.hits.length) return;
955
+ this.hits[this.cursor]?.el.classList.remove("hv-cur");
956
+ this.cursor = (this.cursor + by + this.hits.length) % this.hits.length;
957
+ const hit = this.hits[this.cursor];
958
+ hit.el.classList.add("hv-cur");
959
+ this.go(this.fitView(hit.box(), FOCUS_MAX_K));
960
+ this.emit();
961
+ }
962
+ worldRect(el) {
963
+ const r = el.getBoundingClientRect();
964
+ const s = this.o.stage.getBoundingClientRect();
965
+ const k = this.view.k;
966
+ return { x: (r.left - s.left) / k, y: (r.top - s.top) / k, w: r.width / k, h: r.height / k };
967
+ }
968
+ // ---- minimap ------------------------------------------------------------------------------------------------------------------------
969
+ readMiniColors() {
970
+ const cs = getComputedStyle(this.o.minimap);
971
+ this.miniColors = { node: cs.color, edge: cs.borderLeftColor, view: cs.accentColor, bg: cs.backgroundColor };
972
+ }
973
+ miniScale() {
974
+ const c = this.o.minimap;
975
+ const s = Math.min(c.width / this.content.w, c.height / this.content.h);
976
+ return { s, ox: (c.width - this.content.w * s) / 2, oy: (c.height - this.content.h * s) / 2 };
977
+ }
978
+ drawMinimap() {
979
+ const c = this.o.minimap;
980
+ if (c.hidden || !c.width) return;
981
+ const ctx = c.getContext("2d");
982
+ if (!ctx) return;
983
+ const { s, ox, oy } = this.miniScale();
984
+ ctx.clearRect(0, 0, c.width, c.height);
985
+ ctx.fillStyle = this.miniColors.node;
986
+ ctx.globalAlpha = 0.55;
987
+ 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));
988
+ ctx.globalAlpha = 1;
989
+ const v = this.view;
990
+ ctx.strokeStyle = this.miniColors.view;
991
+ ctx.lineWidth = Math.max(1.5, c.width / 120);
992
+ ctx.strokeRect(ox + -v.x / v.k * s, oy + -v.y / v.k * s, this.vw / v.k * s, this.vh / v.k * s);
993
+ }
994
+ miniTo(e) {
995
+ const c = this.o.minimap;
996
+ const r = c.getBoundingClientRect();
997
+ const { s, ox, oy } = this.miniScale();
998
+ const px = (e.clientX - r.left) / r.width * c.width;
999
+ const py = (e.clientY - r.top) / r.height * c.height;
1000
+ this.stopAnim();
1001
+ this.set(centerOn(this.view, (px - ox) / s, (py - oy) / s, this.vw, this.vh));
1002
+ }
1003
+ onMiniDown(e) {
1004
+ e.stopPropagation();
1005
+ this.miniDrag = true;
1006
+ try {
1007
+ this.o.minimap.setPointerCapture(e.pointerId);
1008
+ } catch {
1009
+ }
1010
+ this.miniTo(e);
1011
+ }
1012
+ // ---- state out ----------------------------------------------------------------------------------------------------------------------
1013
+ emit() {
1014
+ this.o.onUi({ graph: Boolean(this.graph), minimap: showMinimap(this.nodes.length), pinned: this.pinned, matches: this.hits.length, current: this.cursor });
1015
+ }
1016
+ /** The node count and pinned key, for assertions. */
1017
+ inspect() {
1018
+ return { nodes: this.nodes.length, edges: this.edges.length, pinned: this.pinned, k: this.view.k };
1019
+ }
1020
+ };
1021
+ }
1022
+ });
1023
+
1024
+ // src/react/viewer/export.ts
1025
+ function pngSize(w, h, scale) {
1026
+ const limit = Math.min(1, MAX_SIDE / (w * scale), MAX_SIDE / (h * scale), Math.sqrt(MAX_PIXELS / (w * h * scale * scale)));
1027
+ return { w: Math.max(1, Math.floor(w * scale * limit)), h: Math.max(1, Math.floor(h * scale * limit)) };
1028
+ }
1029
+ function downloadBlob(blob, name) {
1030
+ const url = URL.createObjectURL(blob);
1031
+ const a = document.createElement("a");
1032
+ a.href = url;
1033
+ a.download = name;
1034
+ a.rel = "noopener";
1035
+ document.body.append(a);
1036
+ a.click();
1037
+ a.remove();
1038
+ setTimeout(() => URL.revokeObjectURL(url), 1e4);
1039
+ }
1040
+ function serializeSvg(markup) {
1041
+ const svg = new DOMParser().parseFromString(markup, "text/html").body.querySelector("svg");
1042
+ return standaloneSvg(svg ? new XMLSerializer().serializeToString(svg) : markup);
1043
+ }
1044
+ async function pngBlob(markup, scale, background) {
1045
+ const size = svgSize(markup);
1046
+ if (!size) throw new Error("no size");
1047
+ const { w, h } = pngSize(size.w, size.h, scale);
1048
+ const img = new Image();
1049
+ img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(serializeSvg(markup))}`;
1050
+ await img.decode();
1051
+ const canvas = document.createElement("canvas");
1052
+ canvas.width = w;
1053
+ canvas.height = h;
1054
+ const ctx = canvas.getContext("2d");
1055
+ if (!ctx) throw new Error("no canvas");
1056
+ ctx.fillStyle = background;
1057
+ ctx.fillRect(0, 0, w, h);
1058
+ ctx.drawImage(img, 0, 0, w, h);
1059
+ return await new Promise((resolve, reject) => canvas.toBlob((b) => b ? resolve(b) : reject(new Error("png")), "image/png"));
1060
+ }
1061
+ var MAX_SIDE, MAX_PIXELS, fileName, svgBlob;
1062
+ var init_export = __esm({
1063
+ "src/react/viewer/export.ts"() {
1064
+ "use strict";
1065
+ init_scope_svg();
1066
+ MAX_SIDE = 16384;
1067
+ MAX_PIXELS = 36e6;
1068
+ fileName = (title, ext) => `${title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "diagram"}.${ext}`;
1069
+ svgBlob = (markup) => new Blob([serializeSvg(markup)], { type: "image/svg+xml;charset=utf-8" });
1070
+ }
1071
+ });
1072
+
1073
+ // src/react/viewer/diagram-viewer.tsx
1074
+ var diagram_viewer_exports = {};
1075
+ __export(diagram_viewer_exports, {
1076
+ DiagramViewer: () => DiagramViewer
1077
+ });
1078
+ function DiagramViewer({ svg, svgId, source, title, labels, onClose }) {
1079
+ const dialog = (0, import_react.useRef)(null);
1080
+ const shell = (0, import_react.useRef)(null);
1081
+ const viewport = (0, import_react.useRef)(null);
1082
+ const stage = (0, import_react.useRef)(null);
1083
+ const minimap = (0, import_react.useRef)(null);
1084
+ const zoom = (0, import_react.useRef)(null);
1085
+ const finder = (0, import_react.useRef)(null);
1086
+ const ctl = (0, import_react.useRef)(null);
1087
+ const labelsRef = (0, import_react.useRef)(labels);
1088
+ labelsRef.current = labels;
1089
+ const ownId = (0, import_react.useRef)(`hyle-viewer-${++sequence}`);
1090
+ const helpId = (0, import_react.useId)();
1091
+ const toastTimer = (0, import_react.useRef)(void 0);
1092
+ const downOnBackdrop = (0, import_react.useRef)(false);
1093
+ const [ui, setUi] = (0, import_react.useState)({ graph: false, minimap: false, pinned: null, matches: 0, current: -1 });
1094
+ const [toast, setToast] = (0, import_react.useState)("");
1095
+ const [finding, setFinding] = (0, import_react.useState)(false);
1096
+ const [query, setQuery] = (0, import_react.useState)("");
1097
+ const [scale, setScale] = (0, import_react.useState)("2");
1098
+ const [fullscreen, setFullscreen] = (0, import_react.useState)(false);
1099
+ const scoped = (0, import_react.useMemo)(() => scopeSvg(svg, svgId, ownId.current), [svg, svgId]);
1100
+ const say = (message) => {
1101
+ clearTimeout(toastTimer.current);
1102
+ setToast(message);
1103
+ toastTimer.current = setTimeout(() => setToast(""), TOAST_MS);
1104
+ };
1105
+ (0, import_react.useLayoutEffect)(() => {
1106
+ const c = new DiagramController({
1107
+ viewport: viewport.current,
1108
+ stage: stage.current,
1109
+ minimap: minimap.current,
1110
+ zoomOutput: zoom.current,
1111
+ labels: () => labelsRef.current,
1112
+ onUi: setUi,
1113
+ announce: say
1114
+ });
1115
+ ctl.current = c;
1116
+ return () => {
1117
+ c.destroy();
1118
+ ctl.current = null;
1119
+ };
1120
+ }, []);
1121
+ (0, import_react.useLayoutEffect)(() => ctl.current?.show(scoped, `${ownId.current}_`), [scoped]);
1122
+ (0, import_react.useEffect)(() => {
1123
+ const d = dialog.current;
1124
+ if (!d.open) d.showModal();
1125
+ if (locks++ === 0) document.documentElement.classList.add(LOCK_CLASS);
1126
+ viewport.current?.focus({ preventScroll: true });
1127
+ const sync = () => setFullscreen(document.fullscreenElement === shell.current);
1128
+ document.addEventListener("fullscreenchange", sync);
1129
+ return () => {
1130
+ document.removeEventListener("fullscreenchange", sync);
1131
+ clearTimeout(toastTimer.current);
1132
+ if (--locks === 0) document.documentElement.classList.remove(LOCK_CLASS);
1133
+ if (document.fullscreenElement && d.contains(document.fullscreenElement)) void document.exitFullscreen().catch(() => {
1134
+ });
1135
+ };
1136
+ }, []);
1137
+ (0, import_react.useEffect)(() => {
1138
+ if (finding) finder.current?.focus();
1139
+ }, [finding]);
1140
+ const closeFind = () => {
1141
+ setFinding(false);
1142
+ setQuery("");
1143
+ ctl.current?.search("");
1144
+ viewport.current?.focus({ preventScroll: true });
1145
+ };
1146
+ const onKeyDown = (e) => {
1147
+ const target = e.target;
1148
+ if (e.key === "/" || (e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "f") {
1149
+ if (target === finder.current && e.key === "/") return;
1150
+ e.preventDefault();
1151
+ setFinding(true);
1152
+ finder.current?.focus();
1153
+ return;
1154
+ }
1155
+ if (target.closest(".hv-bar")) return;
1156
+ if (ctl.current?.key(e.nativeEvent)) e.preventDefault();
1157
+ };
1158
+ const onFindKey = (e) => {
1159
+ if (e.key === "Escape") {
1160
+ e.preventDefault();
1161
+ e.stopPropagation();
1162
+ closeFind();
1163
+ } else if (e.key === "Enter") {
1164
+ e.preventDefault();
1165
+ ctl.current?.step(e.shiftKey ? -1 : 1);
1166
+ }
1167
+ };
1168
+ const run = (job) => {
1169
+ job().then((m) => say(m || labels.saved), () => say(labels.unavailable));
1170
+ };
1171
+ const background = () => getComputedStyle(dialog.current).backgroundColor;
1172
+ const png = () => pngBlob(svg, Number(scale), background());
1173
+ const canCopyImage = typeof ClipboardItem !== "undefined" && Boolean(navigator.clipboard?.write);
1174
+ const canFullscreen = typeof document !== "undefined" && document.fullscreenEnabled;
1175
+ const status = !query.trim() ? "" : ui.matches === 0 ? labels.noMatch : fill(labels.matchOf, { n: Math.max(ui.current, 0) + 1, total: ui.matches });
1176
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1177
+ "dialog",
1178
+ {
1179
+ ref: dialog,
1180
+ className: "hyle-viewer",
1181
+ "aria-label": `${labels.viewer}: ${title}`,
1182
+ onClose,
1183
+ onPointerDown: (e) => downOnBackdrop.current = e.target === dialog.current,
1184
+ onClick: (e) => e.target === dialog.current && downOnBackdrop.current && dialog.current?.close(),
1185
+ onKeyDown,
1186
+ children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "hv-shell", ref: shell, children: [
1187
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "hv-bar", role: "toolbar", "aria-label": labels.viewer, children: [
1188
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "hv-title", children: title }),
1189
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("output", { className: "hv-zoom", ref: zoom, "aria-label": "zoom", children: "100%" }),
1190
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { className: "hv-group", children: [
1191
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { type: "button", className: "hv-btn", "aria-label": labels.zoomOut, title: labels.zoomOut, onClick: () => ctl.current?.zoomBy(0.8), children: "\u2212" }),
1192
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { type: "button", className: "hv-btn", "aria-label": labels.zoomIn, title: labels.zoomIn, onClick: () => ctl.current?.zoomBy(1.25), children: "+" }),
1193
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { type: "button", className: "hv-btn", "aria-label": labels.fit, title: labels.fit, onClick: () => ctl.current?.fit(), children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Glyph, { d: ICONS.fit }) }),
1194
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { type: "button", className: "hv-btn hv-txt", "aria-label": labels.actual, title: labels.actual, onClick: () => ctl.current?.actual(), children: "100%" })
1195
+ ] }),
1196
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { className: "hv-group hv-find", children: [
1197
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { type: "button", className: "hv-btn", "aria-label": labels.search, title: `${labels.search} (/)`, "aria-pressed": finding, onClick: () => finding ? closeFind() : setFinding(true), children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Glyph, { d: ICONS.search }) }),
1198
+ finding ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
1199
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
1200
+ "input",
1201
+ {
1202
+ ref: finder,
1203
+ className: "hv-input",
1204
+ type: "search",
1205
+ enterKeyHint: "search",
1206
+ autoComplete: "off",
1207
+ spellCheck: false,
1208
+ "aria-label": labels.search,
1209
+ placeholder: labels.searchPlaceholder,
1210
+ value: query,
1211
+ onChange: (e) => (setQuery(e.target.value), ctl.current?.search(e.target.value)),
1212
+ onKeyDown: onFindKey
1213
+ }
1214
+ ),
1215
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("output", { className: "hv-count", "aria-live": "polite", children: status })
1216
+ ] }) : null
1217
+ ] }),
1218
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { className: "hv-group hv-export", children: [
1219
+ /* @__PURE__ */ (0, import_jsx_runtime.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" }),
1220
+ /* @__PURE__ */ (0, import_jsx_runtime.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" }),
1221
+ /* @__PURE__ */ (0, import_jsx_runtime.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" }),
1222
+ /* @__PURE__ */ (0, import_jsx_runtime.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__ */ (0, import_jsx_runtime.jsx)("option", { value: s, children: `${s}\xD7` }, s)) }),
1223
+ canCopyImage ? /* @__PURE__ */ (0, import_jsx_runtime.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
1224
+ ] }),
1225
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { className: "hv-group hv-end", children: [
1226
+ canFullscreen ? /* @__PURE__ */ (0, import_jsx_runtime.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__ */ (0, import_jsx_runtime.jsx)(Glyph, { d: fullscreen ? ICONS.exit : ICONS.full }) }) : null,
1227
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", { type: "button", className: "hv-btn", "aria-label": labels.close, title: `${labels.close} (Esc)`, onClick: () => dialog.current?.close(), children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Glyph, { d: ICONS.close }) })
1228
+ ] })
1229
+ ] }),
1230
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "hv-view", ref: viewport, tabIndex: -1, role: "group", "aria-label": title, "aria-describedby": helpId, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "hv-stage", ref: stage }) }),
1231
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("canvas", { className: "hv-mini", ref: minimap, width: 176, height: 120, hidden: !ui.minimap, "aria-hidden": "true" }),
1232
+ /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "hv-foot", children: [
1233
+ ui.pinned ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("ul", { className: "hv-legend", "aria-hidden": "true", children: [
1234
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("li", { className: "hv-sel", children: labels.legendSelected }),
1235
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("li", { className: "hv-up", children: labels.legendUpstream }),
1236
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("li", { className: "hv-down", children: labels.legendDownstream })
1237
+ ] }) : null,
1238
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", { className: "hv-hint", id: helpId, children: labels.hint }),
1239
+ /* @__PURE__ */ (0, import_jsx_runtime.jsx)("output", { className: "hv-toast", role: "status", children: toast })
1240
+ ] })
1241
+ ] })
1242
+ }
1243
+ );
1244
+ }
1245
+ var import_react, import_jsx_runtime, sequence, locks, LOCK_CLASS, SCALES, TOAST_MS, Glyph, ICONS;
1246
+ var init_diagram_viewer = __esm({
1247
+ "src/react/viewer/diagram-viewer.tsx"() {
1248
+ "use strict";
1249
+ import_react = require("react");
1250
+ init_controller();
1251
+ init_export();
1252
+ init_labels();
1253
+ init_scope_svg();
1254
+ import_jsx_runtime = require("react/jsx-runtime");
1255
+ sequence = 0;
1256
+ locks = 0;
1257
+ LOCK_CLASS = "hyle-viewer-lock";
1258
+ SCALES = ["1", "2", "4"];
1259
+ TOAST_MS = 4e3;
1260
+ Glyph = ({ d }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("svg", { className: "hv-ic", viewBox: "0 0 16 16", "aria-hidden": "true", children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)("path", { d }) });
1261
+ ICONS = {
1262
+ close: "m4 4 8 8M12 4l-8 8",
1263
+ fit: "M2.5 6V2.5H6M10 2.5h3.5V6M13.5 10v3.5H10M6 13.5H2.5V10",
1264
+ 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",
1265
+ full: "M2.5 6V2.5H6M10 2.5h3.5V6M13.5 10v3.5H10M6 13.5H2.5V10",
1266
+ exit: "M6 2.5V6H2.5M13.5 6H10V2.5M10 13.5V10h3.5M2.5 10H6v3.5"
1267
+ };
1268
+ }
1269
+ });
1270
+
1271
+ // src/react/mermaid-image.tsx
1272
+ var mermaid_image_exports = {};
1273
+ __export(mermaid_image_exports, {
1274
+ MermaidImage: () => MermaidImage,
1275
+ isSafeStoredSvg: () => isSafeStoredSvg
1276
+ });
1277
+ module.exports = __toCommonJS(mermaid_image_exports);
1278
+ var import_react2 = require("react");
1279
+
1280
+ // src/react/mermaid-config.ts
1281
+ var MAX_MERMAID_SOURCE = 1024 * 1024;
1282
+ function luminance(css) {
1283
+ const m = /^(rgba?)\(([^)]*)\)$|^color\(srgb ([^)]*)\)$/.exec(css.trim());
1284
+ if (!m) return void 0;
1285
+ const parts = (m[2] ?? m[3] ?? "").split(/[\s,/]+/).filter(Boolean).map(Number);
1286
+ const [r, g, b] = parts.map((v) => m[3] ? v : v / 255);
1287
+ const alpha = parts[3] ?? 1;
1288
+ if (r === void 0 || g === void 0 || b === void 0 || [r, g, b, alpha].some(Number.isNaN) || alpha < 0.5) return void 0;
1289
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
1290
+ }
1291
+ function pickMermaidTheme(background, prefersDark) {
1292
+ const l = luminance(background);
1293
+ return (l === void 0 ? prefersDark : l < 0.5) ? "dark" : "default";
1294
+ }
1295
+
1296
+ // src/react/mermaid-image.tsx
1297
+ var import_mermaid_diagram = require("./mermaid-diagram.cjs");
1298
+ init_labels();
1299
+ var import_jsx_runtime2 = require("react/jsx-runtime");
1300
+ var FORBIDDEN_IN_SVG = /<script|<foreignObject|\son\w+\s*=|javascript:/i;
1301
+ var BAD_CSS = /\\|@(?!keyframes\b)|expression|-moz-binding|behavior|-webkit-image-set|(?:src|image|image-set|cross-fade|element|paint)\(|url\((?!\s*['"]?\s*#)/i;
1302
+ function isSafeStoredSvg(svg) {
1303
+ if (FORBIDDEN_IN_SVG.test(svg)) return false;
1304
+ for (const m of svg.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>|\s[\w:-]+="([^"]*)"/g)) if (BAD_CSS.test(m[1] ?? m[2] ?? "")) return false;
1305
+ return true;
1306
+ }
1307
+ function MermaidImage({ source, title, errorText, loadingText, sourceLabel, light, dark, labels = VIEWER_LABELS_EN }) {
1308
+ const figure = (0, import_react2.useRef)(null);
1309
+ const img = (0, import_react2.useRef)(null);
1310
+ const trigger = (0, import_react2.useRef)(null);
1311
+ const [theme, setTheme] = (0, import_react2.useState)(null);
1312
+ const [pending, setPending] = (0, import_react2.useState)(false);
1313
+ const [failed, setFailed] = (0, import_react2.useState)(false);
1314
+ const [view, setView] = (0, import_react2.useState)(null);
1315
+ const [Viewer, setViewer] = (0, import_react2.useState)(null);
1316
+ (0, import_react2.useEffect)(() => {
1317
+ const scheme = window.matchMedia("(prefers-color-scheme: dark)");
1318
+ const update = () => figure.current && setTheme(pickMermaidTheme(getComputedStyle(figure.current).backgroundColor, scheme.matches));
1319
+ update();
1320
+ const observer = new MutationObserver(update);
1321
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ["data-act", "data-theme", "class"] });
1322
+ scheme.addEventListener("change", update);
1323
+ return () => {
1324
+ observer.disconnect();
1325
+ scheme.removeEventListener("change", update);
1326
+ };
1327
+ }, []);
1328
+ (0, import_react2.useEffect)(() => {
1329
+ const el = img.current;
1330
+ if (!el?.complete) setPending(true);
1331
+ else if (el.naturalWidth === 0) setFailed(true);
1332
+ }, []);
1333
+ if (failed) return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_mermaid_diagram.MermaidDiagram, { source, title, errorText, loadingText, labels });
1334
+ const active = theme === "dark" ? dark : light;
1335
+ const expand = async (e) => {
1336
+ if (e.target.closest("a")) return;
1337
+ try {
1338
+ const response = await fetch(active.src);
1339
+ const svg = response.ok ? await response.text() : "";
1340
+ const id = /^\s*<svg\b[^>]*?\sid="([\w-]+)"/.exec(svg)?.[1];
1341
+ if (!id || !isSafeStoredSvg(svg)) return;
1342
+ const { DiagramViewer: DiagramViewer2 } = await Promise.resolve().then(() => (init_diagram_viewer(), diagram_viewer_exports));
1343
+ setViewer(() => DiagramViewer2);
1344
+ setView({ svg, id });
1345
+ } catch {
1346
+ }
1347
+ };
1348
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("figure", { ref: figure, className: "hyle-mermaid", "data-slot-component": "Mermaid", children: [
1349
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("button", { ref: trigger, type: "button", className: "hyle-mermaid-open", "aria-label": labels.expand, "aria-haspopup": "dialog", onClick: expand, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("span", { className: "hyle-mermaid-frame", style: { aspectRatio: `${active.width} / ${active.height}`, maxWidth: active.width }, children: [
1350
+ pending ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "hyle-mermaid-loader", role: "status", "aria-busy": "true", children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "sr-only", children: loadingText }) }) : null,
1351
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("picture", { children: [
1352
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("source", { srcSet: dark.src, media: theme === null ? "(prefers-color-scheme: dark)" : theme === "dark" ? "all" : "not all" }),
1353
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("img", { ref: img, src: light.src, alt: title, width: light.width, height: light.height, decoding: "async", loading: "lazy", onLoad: () => setPending(false), onError: () => setFailed(true) })
1354
+ ] }),
1355
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { className: "hyle-mermaid-hint", "aria-hidden": "true", children: labels.expandHint })
1356
+ ] }) }),
1357
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("details", { className: "hyle-mermaid-source", children: [
1358
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("summary", { children: sourceLabel }),
1359
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("pre", { tabIndex: 0, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("code", { className: "language-mermaid", children: source }) })
1360
+ ] }),
1361
+ view && Viewer ? /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
1362
+ Viewer,
1363
+ {
1364
+ svg: view.svg,
1365
+ svgId: view.id,
1366
+ source,
1367
+ title,
1368
+ labels,
1369
+ onClose: () => {
1370
+ setView(null);
1371
+ trigger.current?.focus({ preventScroll: true });
1372
+ }
1373
+ }
1374
+ ) : null,
1375
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("figcaption", { className: "sr-only", children: title })
1376
+ ] });
1377
+ }
1378
+ // Annotate the CommonJS export names for ESM import in node:
1379
+ 0 && (module.exports = {
1380
+ MermaidImage,
1381
+ isSafeStoredSvg
1382
+ });