@tdacorp/hyle-sdk 0.3.0 → 0.5.0

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