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