@markdy/renderer-dom 1.1.7 → 1.3.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 (4) hide show
  1. package/README.md +58 -110
  2. package/dist/index.d.ts +178 -50
  3. package/dist/index.js +2574 -717
  4. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  // src/diagram.ts
2
2
  import {
3
3
  compressMarkdyToUrlHash,
4
- parseAndCompile,
4
+ parseAndCompile as parseAndCompile2,
5
5
  resolvePlayer,
6
- resolveTheme
6
+ resolveTheme as resolveTheme2
7
7
  } from "@markdy/core";
8
8
 
9
9
  // src/geometry/rect.ts
@@ -224,14 +224,53 @@ function overlapCount(rect, obstacles) {
224
224
  for (const o of obstacles) if (rectsOverlap(rect, o)) hits++;
225
225
  return hits;
226
226
  }
227
- function placeFlowLabel(points, textWidth, obstacles, bounds) {
227
+ function wrapFlowLabelText(text, maxAvailableWidth) {
228
+ const CHAR_WIDTH = 6.6;
229
+ const PAD = 8;
230
+ const singleLineWidth = text.length * CHAR_WIDTH + PAD;
231
+ if (singleLineWidth <= maxAvailableWidth || text.length <= 18 || !text.includes(" ")) {
232
+ return [text];
233
+ }
234
+ const words = text.trim().split(/\s+/);
235
+ if (words.length <= 1) return [text];
236
+ let bestSplit = 1;
237
+ let bestBalanceScore = Number.POSITIVE_INFINITY;
238
+ for (let i = 1; i < words.length; i++) {
239
+ const line12 = words.slice(0, i).join(" ");
240
+ const line22 = words.slice(i).join(" ");
241
+ const w12 = line12.length * CHAR_WIDTH + PAD;
242
+ const w22 = line22.length * CHAR_WIDTH + PAD;
243
+ const maxW = Math.max(w12, w22);
244
+ const diff = Math.abs(w12 - w22);
245
+ const penalty = maxW > maxAvailableWidth ? 1e3 + (maxW - maxAvailableWidth) * 10 : 0;
246
+ const score = penalty + diff + maxW * 0.1;
247
+ if (score < bestBalanceScore) {
248
+ bestBalanceScore = score;
249
+ bestSplit = i;
250
+ }
251
+ }
252
+ const line1 = words.slice(0, bestSplit).join(" ");
253
+ const line2 = words.slice(bestSplit).join(" ");
254
+ const w1 = line1.length * CHAR_WIDTH + PAD;
255
+ const w2 = line2.length * CHAR_WIDTH + PAD;
256
+ if (Math.max(w1, w2) > maxAvailableWidth && words.length >= 4) {
257
+ const third = Math.ceil(words.length / 3);
258
+ const l1 = words.slice(0, third).join(" ");
259
+ const l2 = words.slice(third, third * 2).join(" ");
260
+ const l3 = words.slice(third * 2).join(" ");
261
+ const max3W = Math.max(l1.length, l2.length, l3.length) * CHAR_WIDTH + PAD;
262
+ if (max3W < Math.max(w1, w2)) {
263
+ return [l1, l2, l3];
264
+ }
265
+ }
266
+ return [line1, line2];
267
+ }
268
+ function placeFlowLabel(points, textWidth, obstacles, bounds, boxHeight = LABEL_BOX_HEIGHT) {
228
269
  const halfW = textWidth / 2 + 5;
229
- const halfH = LABEL_BOX_HEIGHT / 2 + 1;
270
+ const halfH = boxHeight / 2 + 1;
230
271
  const pad = 12;
231
272
  let bestPlacement = null;
232
273
  let bestScore = Number.POSITIVE_INFINITY;
233
- const stepX = Math.max(18, halfW + 6);
234
- const stepY = Math.max(18, halfH + 6);
235
274
  for (let i = 0; i < points.length - 1; i++) {
236
275
  const a = points[i];
237
276
  const b = points[i + 1];
@@ -239,16 +278,43 @@ function placeFlowLabel(points, textWidth, obstacles, bounds) {
239
278
  if (segLen < 1) continue;
240
279
  const mid = { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 };
241
280
  const horizontal = Math.abs(a.x - b.x) >= Math.abs(a.y - b.y);
242
- const offsets = [0];
243
- for (let k = 1; k <= 8; k++) {
244
- offsets.push(-k * (horizontal ? stepX : stepY), k * (horizontal ? stepX : stepY));
281
+ const candidates = [
282
+ { x: mid.x, y: mid.y, penalty: 0 }
283
+ ];
284
+ for (let k = 1; k <= 4; k++) {
285
+ const stepLong = k * 16;
286
+ if (horizontal) {
287
+ candidates.push(
288
+ { x: mid.x - stepLong, y: mid.y, penalty: k * 4 },
289
+ { x: mid.x + stepLong, y: mid.y, penalty: k * 4 }
290
+ );
291
+ } else {
292
+ candidates.push(
293
+ { x: mid.x, y: mid.y - stepLong, penalty: k * 4 },
294
+ { x: mid.x, y: mid.y + stepLong, penalty: k * 4 }
295
+ );
296
+ }
245
297
  }
246
- for (const off of offsets) {
247
- const cx = clamp(horizontal ? mid.x + off : mid.x, pad + halfW, bounds.width - pad - halfW);
248
- const cy = clamp(horizontal ? mid.y : mid.y + off, pad + halfH, bounds.height - pad - halfH);
298
+ const perpSteps = [halfH + 8, halfH + 22, halfH + 38, halfH + 56];
299
+ perpSteps.forEach((stepPerp, k) => {
300
+ if (horizontal) {
301
+ candidates.push(
302
+ { x: mid.x, y: mid.y - stepPerp, penalty: 20 + k * 8 },
303
+ { x: mid.x, y: mid.y + stepPerp, penalty: 24 + k * 8 }
304
+ );
305
+ } else {
306
+ candidates.push(
307
+ { x: mid.x - stepPerp, y: mid.y, penalty: 20 + k * 8 },
308
+ { x: mid.x + stepPerp, y: mid.y, penalty: 24 + k * 8 }
309
+ );
310
+ }
311
+ });
312
+ for (const cand of candidates) {
313
+ const cx = clamp(cand.x, pad + halfW, bounds.width - pad - halfW);
314
+ const cy = clamp(cand.y, pad + halfH, bounds.height - pad - halfH);
249
315
  const rect = { x1: cx - halfW, y1: cy - halfH, x2: cx + halfW, y2: cy + halfH };
250
316
  const hits = overlapCount(rect, obstacles);
251
- const score = hits * 1e5 + (horizontal ? 0 : 40) + Math.abs(off) * 2 - Math.min(100, segLen) * 0.1;
317
+ const score = hits * 1e5 + (horizontal ? 0 : 40) + cand.penalty - Math.min(100, segLen) * 0.1;
252
318
  if (score < bestScore) {
253
319
  bestScore = score;
254
320
  bestPlacement = { x: round1(cx), y: round1(cy), rect };
@@ -437,8 +503,9 @@ function routeOrthogonal(sourceRect, targetRect, obstacles, bounds, lane = 0) {
437
503
  sY = clamp(sourceCenter.y + dirSign * 12, sourceRect.y1 + 10, sourceRect.y2 - 10);
438
504
  tY = clamp(targetCenter.y - dirSign * 12, targetRect.y1 + 10, targetRect.y2 - 10);
439
505
  } else {
440
- sY = clamp(sourceCenter.y + (lane > 0 ? lane % 2 === 1 ? 4 : -4 : 0), sourceRect.y1 + 10, sourceRect.y2 - 10);
441
- tY = clamp(targetCenter.y + (lane > 0 ? lane % 2 === 1 ? 4 : -4 : 0), targetRect.y1 + 10, targetRect.y2 - 10);
506
+ const fwdShift = lane > 0 ? lane % 2 === 1 ? -10 : -18 : 0;
507
+ sY = clamp(sourceCenter.y + fwdShift, sourceRect.y1 + 10, sourceRect.y2 - 10);
508
+ tY = clamp(targetCenter.y + fwdShift, targetRect.y1 + 10, targetRect.y2 - 10);
442
509
  }
443
510
  const sPort = { x: sourceRect.x2, y: sY };
444
511
  const tPort = { x: targetRect.x1, y: tY };
@@ -502,6 +569,10 @@ function routeOrthogonal(sourceRect, targetRect, obstacles, bounds, lane = 0) {
502
569
  const dirSign = Math.sign(dy);
503
570
  sY = clamp(sourceCenter.y + dirSign * 12, sourceRect.y1 + 10, sourceRect.y2 - 10);
504
571
  tY = clamp(targetCenter.y - dirSign * 12, targetRect.y1 + 10, targetRect.y2 - 10);
572
+ } else {
573
+ const retShift = lane > 0 ? lane % 2 === 1 ? 10 : 18 : 10;
574
+ sY = clamp(sourceCenter.y + retShift, sourceRect.y1 + 10, sourceRect.y2 - 10);
575
+ tY = clamp(targetCenter.y + retShift, targetRect.y1 + 10, targetRect.y2 - 10);
505
576
  }
506
577
  const sPortL = { x: sourceRect.x1, y: sY };
507
578
  const tPortR = { x: targetRect.x2, y: tY };
@@ -763,14 +834,30 @@ function updateEdgeLayerTheme(svg, edgeRuntimeMap, theme, sceneId) {
763
834
  const color = theme.edges[runtime.kind];
764
835
  runtime.color = color;
765
836
  runtime.path.setAttribute("stroke", color);
837
+ runtime.path.removeAttribute("filter");
766
838
  if (runtime.kind !== "dependency") {
767
839
  runtime.path.style.filter = `drop-shadow(0 0 4px ${translucentColor(color, "44")})`;
840
+ } else {
841
+ runtime.path.style.filter = "";
768
842
  }
769
843
  runtime.dot.setAttribute("fill", color);
770
844
  runtime.dot.style.filter = `drop-shadow(0 0 6px ${color}) drop-shadow(0 0 12px ${color}88)`;
771
845
  if (runtime.labelPlate) {
772
- runtime.labelPlate.setAttribute("fill", theme.canvas ?? theme.surface ?? "#ffffff");
773
- runtime.labelPlate.setAttribute("stroke", translucentColor(color, "28"));
846
+ if (theme.name === "doodle") {
847
+ runtime.labelPlate.setAttribute("fill", "#ffffff");
848
+ runtime.labelPlate.setAttribute("stroke", "#18181b");
849
+ runtime.labelPlate.setAttribute("stroke-width", "1.5");
850
+ runtime.labelPlate.setAttribute("rx", "7");
851
+ runtime.labelPlate.setAttribute("ry", "7");
852
+ runtime.labelPlate.style.filter = "drop-shadow(2px 2px 0 #18181b)";
853
+ } else {
854
+ runtime.labelPlate.setAttribute("fill", theme.canvas ?? theme.surface ?? "#ffffff");
855
+ runtime.labelPlate.setAttribute("stroke", translucentColor(color, "28"));
856
+ runtime.labelPlate.setAttribute("stroke-width", "1");
857
+ runtime.labelPlate.setAttribute("rx", "5");
858
+ runtime.labelPlate.setAttribute("ry", "5");
859
+ runtime.labelPlate.style.filter = isDark ? `drop-shadow(0 4px 12px ${translucentColor(color, "18")})` : "drop-shadow(0 2px 6px rgba(15, 23, 42, 0.08))";
860
+ }
774
861
  }
775
862
  if (runtime.label) {
776
863
  runtime.label.setAttribute("fill", computeEdgeLabelColor(color, isDark));
@@ -778,7 +865,7 @@ function updateEdgeLayerTheme(svg, edgeRuntimeMap, theme, sceneId) {
778
865
  }
779
866
  }
780
867
  function isDarkTheme(theme) {
781
- if (theme.name === "paper" || theme.name === "editorial" || theme.name === "sketchy") {
868
+ if (theme.name === "paper" || theme.name === "editorial" || theme.name === "sketchy" || theme.name === "ink" || theme.name === "doodle") {
782
869
  return false;
783
870
  }
784
871
  const canvas = (theme.canvas || theme.surface || "").trim();
@@ -806,12 +893,17 @@ function createEdgeRuntime(svg, from, to, kind, label, theme, sceneId, routeObst
806
893
  const points = isSelfLoop ? dedupePoints(selfLoopPath(from, bounds)) : dedupePoints(routeEdgePoints(from, to, routeObstacles, bounds, lane));
807
894
  const d = toPathD(points, 14, existingPaths);
808
895
  const len = polylineLength(points);
896
+ const edgeId = `${from.id}_${to.id}`;
809
897
  const group = document.createElementNS("http://www.w3.org/2000/svg", "g");
898
+ group.setAttribute("data-edge-id", edgeId);
899
+ group.setAttribute("data-edge", edgeId);
900
+ group.setAttribute("id", `edge-${edgeId}`);
810
901
  group.setAttribute("data-edge-kind", kind);
811
902
  group.setAttribute("class", `markdy-edge markdy-edge--${kind}`);
812
903
  group.style.opacity = "0";
813
904
  const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
814
905
  path.setAttribute("d", d);
906
+ path.setAttribute("data-edge-path", edgeId);
815
907
  path.setAttribute("fill", "none");
816
908
  path.setAttribute("stroke", color);
817
909
  path.setAttribute("stroke-width", kind === "dependency" ? "1.5" : "2");
@@ -826,52 +918,95 @@ function createEdgeRuntime(svg, from, to, kind, label, theme, sceneId, routeObst
826
918
  path.style.filter = `drop-shadow(0 0 4px ${translucentColor(color, "44")})`;
827
919
  }
828
920
  const dot = document.createElementNS("http://www.w3.org/2000/svg", "circle");
829
- dot.setAttribute("r", "4");
921
+ dot.setAttribute("r", "4.5");
830
922
  dot.setAttribute("fill", color);
831
923
  dot.setAttribute("class", "markdy-edge-dot");
832
924
  dot.style.opacity = "0";
833
- dot.style.filter = `drop-shadow(0 0 6px ${color}) drop-shadow(0 0 12px ${color}88)`;
925
+ dot.style.filter = `drop-shadow(0 0 4px ${color}) drop-shadow(0 0 10px ${color}bb) drop-shadow(0 0 18px ${color}66)`;
834
926
  group.append(path, dot);
835
927
  let labelEl;
836
928
  let labelRect;
837
929
  if (label) {
838
930
  const isDark = isDarkTheme(theme);
839
931
  const labelColor = computeEdgeLabelColor(color, isDark);
840
- const textWidth = Math.max(36, label.length * 6.6 + 8);
841
- const placement = placeFlowLabel(points, textWidth, labelObstacles, bounds);
932
+ let longestSegLen = 0;
933
+ for (let i = 0; i < points.length - 1; i++) {
934
+ longestSegLen = Math.max(longestSegLen, Math.hypot(points[i + 1].x - points[i].x, points[i + 1].y - points[i].y));
935
+ }
936
+ const maxAvailW = Math.max(48, longestSegLen - 24);
937
+ const lines = wrapFlowLabelText(label, maxAvailW);
938
+ const maxChars = Math.max(...lines.map((l) => l.length));
939
+ const textWidth = Math.max(36, maxChars * 6.6 + 8);
940
+ const lineHeight = 13;
941
+ const boxHeight = lines.length === 1 ? 18 : lines.length * lineHeight + 6;
942
+ const placement = placeFlowLabel(points, textWidth, labelObstacles, bounds, boxHeight);
842
943
  labelRect = placement.rect;
944
+ labelObstacles.push(inflateRect(labelRect, 4));
843
945
  const plate = document.createElementNS("http://www.w3.org/2000/svg", "rect");
844
946
  const padX = 6;
845
947
  const halfW = textWidth / 2;
846
948
  plate.setAttribute("class", "markdy-edge-plate");
847
949
  plate.setAttribute("x", String(placement.x - halfW - padX));
848
- plate.setAttribute("y", String(placement.y - 9));
950
+ plate.setAttribute("y", String(placement.y - boxHeight / 2));
849
951
  plate.setAttribute("width", String(textWidth + padX * 2));
850
- plate.setAttribute("height", "18");
851
- plate.setAttribute("rx", "4");
852
- plate.setAttribute("ry", "4");
853
- plate.setAttribute("fill", theme.canvas ?? theme.surface ?? "#ffffff");
854
- plate.setAttribute("fill-opacity", "0.85");
855
- plate.setAttribute("stroke", translucentColor(color, "28"));
856
- plate.setAttribute("stroke-width", "0.85");
857
- plate.style.opacity = "0";
858
- plate.style.filter = "none";
952
+ plate.setAttribute("height", String(boxHeight));
953
+ if (theme.name === "doodle") {
954
+ plate.setAttribute("rx", "7");
955
+ plate.setAttribute("ry", "7");
956
+ plate.setAttribute("fill", "#ffffff");
957
+ plate.setAttribute("fill-opacity", "1");
958
+ plate.setAttribute("stroke", "#18181b");
959
+ plate.setAttribute("stroke-width", "1.5");
960
+ plate.style.opacity = "0";
961
+ plate.style.filter = "drop-shadow(2px 2px 0 #18181b)";
962
+ } else if (theme.name === "ink") {
963
+ plate.setAttribute("rx", "4");
964
+ plate.setAttribute("ry", "4");
965
+ plate.setAttribute("fill", "#ffffff");
966
+ plate.setAttribute("fill-opacity", "0.98");
967
+ plate.setAttribute("stroke", "#1d4ed8");
968
+ plate.setAttribute("stroke-width", "1");
969
+ plate.style.opacity = "0";
970
+ plate.style.filter = "drop-shadow(1.5px 1.5px 0 rgba(29, 78, 216, 0.14))";
971
+ } else {
972
+ plate.setAttribute("rx", "5");
973
+ plate.setAttribute("ry", "5");
974
+ plate.setAttribute("fill", theme.canvas ?? theme.surface ?? "#ffffff");
975
+ plate.setAttribute("fill-opacity", isDark ? "0.88" : "0.94");
976
+ plate.setAttribute("stroke", translucentColor(color, isDark ? "55" : "33"));
977
+ plate.setAttribute("stroke-width", "1");
978
+ plate.style.opacity = "0";
979
+ plate.style.filter = isDark ? "drop-shadow(0 2px 8px rgba(0, 0, 0, 0.45))" : "drop-shadow(0 1px 4px rgba(0, 0, 0, 0.12))";
980
+ }
859
981
  group.appendChild(plate);
860
- labelEl = document.createElementNS("http://www.w3.org/2000/svg", "text");
861
- labelEl.setAttribute("class", "markdy-edge-label");
862
- labelEl.setAttribute("x", String(placement.x));
863
- labelEl.setAttribute("y", String(placement.y + 0.5));
864
- labelEl.setAttribute("text-anchor", "middle");
865
- labelEl.setAttribute("dominant-baseline", "middle");
866
- labelEl.setAttribute("font-size", "10.5");
867
- labelEl.setAttribute("font-weight", "500");
868
- labelEl.setAttribute("letter-spacing", "0.02em");
869
- labelEl.setAttribute("font-family", "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace");
870
- labelEl.setAttribute("fill", labelColor);
871
- labelEl.textContent = label;
872
- labelEl.style.opacity = "0";
873
- group.appendChild(labelEl);
874
- labelEl.__plate = plate;
982
+ const textEl = document.createElementNS("http://www.w3.org/2000/svg", "text");
983
+ labelEl = textEl;
984
+ textEl.setAttribute("class", "markdy-edge-label");
985
+ textEl.setAttribute("x", String(placement.x));
986
+ textEl.setAttribute("text-anchor", "middle");
987
+ textEl.setAttribute("font-size", "10.5");
988
+ textEl.setAttribute("font-weight", "500");
989
+ textEl.setAttribute("letter-spacing", "0.02em");
990
+ textEl.setAttribute("font-family", "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace");
991
+ textEl.setAttribute("fill", labelColor);
992
+ if (lines.length === 1) {
993
+ textEl.setAttribute("y", String(placement.y + 0.5));
994
+ textEl.setAttribute("dominant-baseline", "middle");
995
+ textEl.textContent = lines[0];
996
+ } else {
997
+ const startY = placement.y - (lines.length - 1) * lineHeight / 2 + 3.5;
998
+ lines.forEach((lineText, idx) => {
999
+ const tspan = document.createElementNS("http://www.w3.org/2000/svg", "tspan");
1000
+ tspan.setAttribute("x", String(placement.x));
1001
+ tspan.setAttribute("y", String(startY + idx * lineHeight));
1002
+ tspan.setAttribute("text-anchor", "middle");
1003
+ tspan.textContent = idx < lines.length - 1 ? `${lineText} ` : lineText;
1004
+ textEl.appendChild(tspan);
1005
+ });
1006
+ }
1007
+ textEl.style.opacity = "0";
1008
+ group.appendChild(textEl);
1009
+ textEl.__plate = plate;
875
1010
  }
876
1011
  svg.appendChild(group);
877
1012
  return {
@@ -1097,6 +1232,7 @@ function buildCueAnimations(cues, nodeEls, nodes, theme, scene, titleEl, bounds,
1097
1232
  { duration: 420, delay: 0, fill: "forwards", easing: "ease-out" }
1098
1233
  )
1099
1234
  );
1235
+ const shownNodeSet = /* @__PURE__ */ new Set();
1100
1236
  for (const cue of cues) {
1101
1237
  const startMs = cue.start * 1e3;
1102
1238
  const durMs = cue.duration * 1e3;
@@ -1105,12 +1241,22 @@ function buildCueAnimations(cues, nodeEls, nodes, theme, scene, titleEl, bounds,
1105
1241
  const el = nodeEls.get(id);
1106
1242
  const delay = startMs + (typeof cue.params.stagger === "number" ? cue.params.stagger * 1e3 * idx : 0);
1107
1243
  if (el) {
1108
- anims.push(
1109
- el.animate(
1110
- [{ opacity: 0, transform: "translateY(10px) scale(0.98)" }, { opacity: 1, transform: "translateY(0) scale(1)" }],
1111
- { duration: durMs, delay, fill: "forwards", easing: "cubic-bezier(0.16, 1, 0.3, 1)" }
1112
- )
1113
- );
1244
+ if (!shownNodeSet.has(id)) {
1245
+ shownNodeSet.add(id);
1246
+ anims.push(
1247
+ el.animate(
1248
+ [{ opacity: 0, transform: "translateY(10px) scale(0.98)" }, { opacity: 1, transform: "translateY(0) scale(1)" }],
1249
+ { duration: durMs, delay, fill: "forwards", easing: "cubic-bezier(0.16, 1, 0.3, 1)" }
1250
+ )
1251
+ );
1252
+ } else {
1253
+ anims.push(
1254
+ el.animate(
1255
+ [{ transform: "scale(1)" }, { transform: "scale(1.03)" }, { transform: "scale(1)" }],
1256
+ { duration: durMs, delay, fill: "none", easing: "ease-in-out" }
1257
+ )
1258
+ );
1259
+ }
1114
1260
  return;
1115
1261
  }
1116
1262
  const runtime = edgeRuntimes.get(id);
@@ -1230,6 +1376,20 @@ function buildCueAnimations(cues, nodeEls, nodes, theme, scene, titleEl, bounds,
1230
1376
  if (edgeId) edgeRuntimes.set(edgeId, runtime);
1231
1377
  }
1232
1378
  anims.push(...animateEdgeReveal(runtime, startMs, durMs));
1379
+ for (const id of [seg.from, seg.to]) {
1380
+ if (!shownNodeSet.has(id)) {
1381
+ shownNodeSet.add(id);
1382
+ const el = nodeEls.get(id);
1383
+ if (el) {
1384
+ anims.push(
1385
+ el.animate(
1386
+ [{ opacity: 0, transform: "translateY(8px) scale(0.98)" }, { opacity: 1, transform: "translateY(0) scale(1)" }],
1387
+ { duration: 320, delay: startMs, fill: "forwards", easing: "cubic-bezier(0.16, 1, 0.3, 1)" }
1388
+ )
1389
+ );
1390
+ }
1391
+ }
1392
+ }
1233
1393
  const toEl = nodeEls.get(seg.to);
1234
1394
  if (toEl) {
1235
1395
  anims.push(
@@ -1798,14 +1958,14 @@ function ensureGroupStyles(doc) {
1798
1958
  .markdy-group-boundary {
1799
1959
  position: absolute;
1800
1960
  box-sizing: border-box;
1801
- border: 1px solid var(--md-group-border, color-mix(in srgb, var(--md-border) 45%, transparent));
1961
+ border: 1px dashed var(--md-group-border, color-mix(in srgb, var(--md-border) 50%, transparent));
1802
1962
  border-radius: 16px;
1803
- background: color-mix(in srgb, var(--md-surface-raised) 32%, transparent);
1963
+ background: color-mix(in srgb, var(--md-surface-raised) 28%, transparent);
1804
1964
  box-shadow:
1805
- 0 4px 20px -4px var(--md-shadow, rgba(0, 0, 0, 0.25)),
1806
- inset 0 1px 0 rgba(255, 255, 255, 0.06);
1807
- backdrop-filter: blur(8px);
1808
- -webkit-backdrop-filter: blur(8px);
1965
+ 0 8px 32px -8px var(--md-shadow, rgba(0, 0, 0, 0.25)),
1966
+ inset 0 1px 0 rgba(255, 255, 255, 0.12);
1967
+ backdrop-filter: blur(10px);
1968
+ -webkit-backdrop-filter: blur(10px);
1809
1969
  pointer-events: none;
1810
1970
  z-index: 40;
1811
1971
  }
@@ -1813,19 +1973,51 @@ function ensureGroupStyles(doc) {
1813
1973
  position: absolute;
1814
1974
  left: 14px;
1815
1975
  top: 10px;
1816
- padding: 4px 10px;
1817
- font-size: 10.5px;
1818
- font-weight: 600;
1819
- letter-spacing: 0.08em;
1976
+ padding: 3px 10px;
1977
+ font-size: 10px;
1978
+ font-weight: 700;
1979
+ letter-spacing: 0.1em;
1820
1980
  text-transform: uppercase;
1821
1981
  color: var(--md-text);
1822
- background: color-mix(in srgb, var(--md-surface-raised) 85%, transparent);
1823
- border: 1px solid var(--md-group-border, color-mix(in srgb, var(--md-border) 50%, transparent));
1982
+ background: color-mix(in srgb, var(--md-surface-raised) 90%, transparent);
1983
+ border: 1px solid var(--md-group-border, color-mix(in srgb, var(--md-border) 60%, transparent));
1824
1984
  border-radius: 6px;
1825
- font-family: var(--md-font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);
1826
- backdrop-filter: blur(6px);
1827
- -webkit-backdrop-filter: blur(6px);
1828
- box-shadow: 0 1px 4px rgba(0, 0, 0, 0.12);
1985
+ font-family: var(--md-font-mono, ui-monospace, SFMono-Regular, Menlo, Monaco, monospace);
1986
+ backdrop-filter: blur(8px);
1987
+ -webkit-backdrop-filter: blur(8px);
1988
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.16);
1989
+ display: inline-flex;
1990
+ align-items: center;
1991
+ gap: 6px;
1992
+ }
1993
+ .markdy-scene-root[data-markdy-theme="doodle"] .markdy-group-boundary {
1994
+ border: 2px dashed #18181b;
1995
+ border-radius: 20px 24px 18px 22px / 22px 18px 24px 20px;
1996
+ background: rgba(254, 240, 138, 0.08);
1997
+ box-shadow: 3px 3px 0 rgba(24, 24, 27, 0.08);
1998
+ }
1999
+ .markdy-scene-root[data-markdy-theme="doodle"] .markdy-group-boundary__label {
2000
+ border: 1.5px solid #18181b;
2001
+ border-radius: 6px;
2002
+ box-shadow: 2px 2px 0 #18181b;
2003
+ background: #fef08a;
2004
+ color: #18181b;
2005
+ font-weight: 800;
2006
+ transform: rotate(-0.8deg);
2007
+ }
2008
+ .markdy-scene-root[data-markdy-theme="ink"] .markdy-group-boundary {
2009
+ border: 1.5px dashed #1d4ed8;
2010
+ border-radius: 8px;
2011
+ background: rgba(239, 246, 255, 0.45);
2012
+ box-shadow: 2px 2px 0 rgba(29, 78, 216, 0.08);
2013
+ }
2014
+ .markdy-scene-root[data-markdy-theme="ink"] .markdy-group-boundary__label {
2015
+ border: 1.25px solid #1d4ed8;
2016
+ border-radius: 4px;
2017
+ box-shadow: 1.5px 1.5px 0 rgba(29, 78, 216, 0.12);
2018
+ background: #ffffff;
2019
+ color: #1e3a8a;
2020
+ font-weight: 600;
1829
2021
  }
1830
2022
  `;
1831
2023
  doc.head.appendChild(style);
@@ -1856,6 +2048,7 @@ function mountGroupBoundaries(layer, boundaries, theme) {
1856
2048
  }
1857
2049
 
1858
2050
  // src/nodes.ts
2051
+ import { resolveVectorSymbol } from "@markdy/core";
1859
2052
  var STYLE_ID3 = "markdy-diagram-node-styles";
1860
2053
  function ensureNodeStyles(doc) {
1861
2054
  if (doc.getElementById(STYLE_ID3)) return;
@@ -1908,7 +2101,7 @@ function ensureNodeStyles(doc) {
1908
2101
  .markdy-node__type { display: none; }
1909
2102
  .markdy-node__body {
1910
2103
  height: 100%;
1911
- padding: 0 14px;
2104
+ padding: 0 16px;
1912
2105
  display: flex;
1913
2106
  align-items: center;
1914
2107
  gap: 12px;
@@ -1917,36 +2110,30 @@ function ensureNodeStyles(doc) {
1917
2110
  }
1918
2111
  .markdy-node__icon {
1919
2112
  flex: 0 0 auto;
1920
- width: 34px;
1921
- height: 34px;
1922
- border-radius: 9px;
2113
+ width: 28px;
2114
+ height: 28px;
1923
2115
  display: flex;
1924
2116
  align-items: center;
1925
2117
  justify-content: center;
1926
2118
  color: var(--md-role-color, var(--md-accent));
1927
- background:
1928
- linear-gradient(180deg,
1929
- color-mix(in srgb, var(--md-role-color, var(--md-accent)) 24%, transparent),
1930
- color-mix(in srgb, var(--md-role-color, var(--md-accent)) 10%, transparent));
1931
- box-shadow:
1932
- inset 0 0 0 1px color-mix(in srgb, var(--md-role-color, var(--md-accent)) 38%, transparent),
1933
- inset 0 1px 0 rgba(255, 255, 255, 0.18);
2119
+ background: transparent;
2120
+ box-shadow: none;
1934
2121
  }
1935
2122
  .markdy-node__icon svg {
1936
- width: 18px;
1937
- height: 18px;
2123
+ width: 26px;
2124
+ height: 26px;
1938
2125
  display: block;
1939
2126
  stroke: currentColor;
1940
2127
  }
1941
2128
  .markdy-node__icon[data-media="image"] {
1942
- background: color-mix(in srgb, var(--md-surface-raised) 68%, #ffffff 32%);
1943
- box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--md-border) 60%, transparent);
1944
- padding: 3px;
2129
+ background: transparent;
2130
+ box-shadow: none;
2131
+ padding: 0;
1945
2132
  overflow: hidden;
1946
2133
  }
1947
2134
  .markdy-node__icon img {
1948
- width: 100%;
1949
- height: 100%;
2135
+ width: 26px;
2136
+ height: 26px;
1950
2137
  object-fit: contain;
1951
2138
  border-radius: 6px;
1952
2139
  display: block;
@@ -1954,12 +2141,16 @@ function ensureNodeStyles(doc) {
1954
2141
  .markdy-node__icon[data-fit="cover"] img {
1955
2142
  object-fit: cover;
1956
2143
  }
1957
- .markdy-node[data-icon="decision"] .markdy-node__icon,
1958
- .markdy-node[data-icon="flow"] .markdy-node__icon {
1959
- border-radius: 999px;
2144
+ .markdy-node__content {
2145
+ flex: 1 1 auto;
2146
+ min-width: 0;
2147
+ display: flex;
2148
+ flex-direction: column;
2149
+ justify-content: center;
2150
+ gap: 3px;
1960
2151
  }
1961
2152
  .markdy-node__label {
1962
- flex: 1 1 auto;
2153
+ flex: 0 1 auto;
1963
2154
  min-width: 0;
1964
2155
  padding: 0;
1965
2156
  font-size: 13.5px;
@@ -1969,13 +2160,30 @@ function ensureNodeStyles(doc) {
1969
2160
  color: var(--md-text);
1970
2161
  display: -webkit-box;
1971
2162
  -webkit-box-orient: vertical;
1972
- -webkit-line-clamp: 3;
1973
- line-clamp: 3;
2163
+ -webkit-line-clamp: 2;
2164
+ line-clamp: 2;
1974
2165
  overflow: hidden;
1975
2166
  overflow-wrap: anywhere;
1976
2167
  word-break: break-word;
1977
2168
  text-wrap: pretty;
1978
2169
  }
2170
+ .markdy-node__tech {
2171
+ align-self: flex-start;
2172
+ font-family: var(--md-font-mono, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace);
2173
+ font-size: 10px;
2174
+ font-weight: 500;
2175
+ line-height: 1.2;
2176
+ color: var(--md-text-muted, #94a3b8);
2177
+ background: color-mix(in srgb, var(--md-text, #ffffff) 6%, transparent);
2178
+ border: 1px solid color-mix(in srgb, var(--md-border, #475569) 55%, transparent);
2179
+ padding: 1.5px 6px;
2180
+ border-radius: 4px;
2181
+ letter-spacing: 0.01em;
2182
+ white-space: nowrap;
2183
+ overflow: hidden;
2184
+ text-overflow: ellipsis;
2185
+ max-width: 100%;
2186
+ }
1979
2187
  .markdy-node__value {
1980
2188
  flex: 0 0 auto;
1981
2189
  font-size: 16px;
@@ -1983,6 +2191,14 @@ function ensureNodeStyles(doc) {
1983
2191
  color: var(--md-ink, var(--md-text));
1984
2192
  font-variant-numeric: tabular-nums;
1985
2193
  }
2194
+ .markdy-node[data-visible="1"]:hover {
2195
+ transform: translateY(-2px);
2196
+ box-shadow:
2197
+ 0 3px 8px color-mix(in srgb, var(--md-shadow, rgba(2, 6, 23, 0.35)) 45%, transparent),
2198
+ 0 16px 32px -8px var(--md-shadow, rgba(2, 6, 23, 0.5)),
2199
+ inset 0 0 0 1px var(--md-hairline, color-mix(in srgb, var(--md-border) 60%, transparent)),
2200
+ inset 0 1px 0 rgba(255, 255, 255, 0.2);
2201
+ }
1986
2202
  .markdy-node[data-role="client"] { border-radius: 14px 14px 10px 10px; }
1987
2203
  .markdy-node[data-role="data"] { border-radius: 12px 12px 16px 16px; }
1988
2204
  .markdy-scene-title {
@@ -2020,6 +2236,10 @@ function ensureNodeStyles(doc) {
2020
2236
  .markdy-scene-root[data-markdy-theme="terminal"] .markdy-node[data-shape="diamond"][data-focal="1"],
2021
2237
  .markdy-scene-root[data-markdy-theme="sketchy"] .markdy-node[data-shape="diamond"],
2022
2238
  .markdy-scene-root[data-markdy-theme="sketchy"] .markdy-node[data-shape="diamond"][data-focal="1"],
2239
+ .markdy-scene-root[data-markdy-theme="ink"] .markdy-node[data-shape="diamond"],
2240
+ .markdy-scene-root[data-markdy-theme="ink"] .markdy-node[data-shape="diamond"][data-focal="1"],
2241
+ .markdy-scene-root[data-markdy-theme="doodle"] .markdy-node[data-shape="diamond"],
2242
+ .markdy-scene-root[data-markdy-theme="doodle"] .markdy-node[data-shape="diamond"][data-focal="1"],
2023
2243
  .markdy-scene-root[data-markdy-theme="nebula"] .markdy-node[data-shape="diamond"],
2024
2244
  .markdy-scene-root[data-markdy-theme="nebula"] .markdy-node[data-shape="diamond"][data-focal="1"] {
2025
2245
  border: none;
@@ -2196,6 +2416,97 @@ function ensureNodeStyles(doc) {
2196
2416
  background: rgba(235, 108, 54, 0.06);
2197
2417
  box-shadow: 3px 3px 0 rgba(235, 108, 54, 0.12);
2198
2418
  }
2419
+ .markdy-scene-root[data-markdy-theme="ink"] .markdy-node {
2420
+ background: #ffffff;
2421
+ border: 1.5px solid #1d4ed8;
2422
+ box-shadow:
2423
+ 3px 3px 0 rgba(29, 78, 216, 0.12),
2424
+ 0 4px 16px -2px rgba(29, 78, 216, 0.08),
2425
+ inset 0 1px 0 rgba(255, 255, 255, 0.9);
2426
+ border-radius: var(--md-radius-md, 6px);
2427
+ }
2428
+ .markdy-scene-root[data-markdy-theme="ink"] .markdy-node[data-visible="1"]:hover {
2429
+ transform: translate(-1px, -1px);
2430
+ box-shadow:
2431
+ 4px 4px 0 rgba(29, 78, 216, 0.18),
2432
+ 0 8px 24px -4px rgba(29, 78, 216, 0.14),
2433
+ inset 0 1px 0 rgba(255, 255, 255, 0.9);
2434
+ }
2435
+ .markdy-scene-root[data-markdy-theme="ink"] .markdy-node__icon {
2436
+ background: color-mix(in srgb, var(--md-role-color, var(--md-accent)) 10%, #ffffff);
2437
+ border: 1px solid color-mix(in srgb, var(--md-role-color, var(--md-accent)) 30%, transparent);
2438
+ border-radius: 6px;
2439
+ width: 30px;
2440
+ height: 30px;
2441
+ }
2442
+ .markdy-scene-root[data-markdy-theme="ink"] .markdy-node__tech {
2443
+ background: #eff6ff;
2444
+ color: #1e3a8a;
2445
+ border: 1px solid #bfdbfe;
2446
+ border-radius: 4px;
2447
+ font-weight: 600;
2448
+ }
2449
+ .markdy-scene-root[data-markdy-theme="ink"] .markdy-node[data-shape="diamond"] {
2450
+ filter: drop-shadow(0 0 1px #1d4ed8) drop-shadow(3px 3px 0 rgba(29, 78, 216, 0.12));
2451
+ }
2452
+ .markdy-scene-root[data-markdy-theme="ink"] .markdy-node[data-focal="1"] {
2453
+ border-color: #1d4ed8;
2454
+ background: linear-gradient(180deg, #ffffff 0%, #f0f7ff 100%);
2455
+ box-shadow:
2456
+ 3px 3px 0 rgba(29, 78, 216, 0.25),
2457
+ 0 8px 24px -4px rgba(29, 78, 216, 0.18),
2458
+ inset 0 1px 0 #ffffff;
2459
+ }
2460
+ .markdy-scene-root[data-markdy-theme="ink"] .markdy-node[data-focal="1"] .markdy-node__icon {
2461
+ background: rgba(29, 78, 216, 0.12);
2462
+ border-color: rgba(29, 78, 216, 0.40);
2463
+ }
2464
+ .markdy-scene-root[data-markdy-theme="ink"] .markdy-node[data-shape="diamond"][data-focal="1"] {
2465
+ filter: drop-shadow(0 0 1.5px #1d4ed8) drop-shadow(3px 3px 0 rgba(29, 78, 216, 0.25)) drop-shadow(0 6px 20px rgba(29, 78, 216, 0.16));
2466
+ }
2467
+ .markdy-scene-root[data-markdy-theme="doodle"] .markdy-node {
2468
+ background: #ffffff;
2469
+ border: 2px solid #18181b;
2470
+ border-radius: 255px 15px 225px 15px/15px 225px 15px 255px;
2471
+ box-shadow: 4px 4px 0 #18181b, 0 8px 16px -4px rgba(24, 24, 27, 0.08);
2472
+ }
2473
+ .markdy-scene-root[data-markdy-theme="doodle"] .markdy-node[data-visible="1"]:hover {
2474
+ transform: translate(-1.5px, -1.5px) rotate(-0.6deg);
2475
+ box-shadow: 5.5px 5.5px 0 #18181b, 0 10px 20px -4px rgba(24, 24, 27, 0.12);
2476
+ }
2477
+ .markdy-scene-root[data-markdy-theme="doodle"] .markdy-node__icon {
2478
+ background: color-mix(in srgb, var(--md-role-color, var(--md-accent)) 16%, #ffffff);
2479
+ border: 1.75px solid #18181b;
2480
+ border-radius: 50% 45% 55% 48% / 48% 55% 45% 50%;
2481
+ width: 30px;
2482
+ height: 30px;
2483
+ box-shadow: 1.5px 1.5px 0 #18181b;
2484
+ }
2485
+ .markdy-scene-root[data-markdy-theme="doodle"] .markdy-node__tech {
2486
+ background: #fef08a;
2487
+ color: #18181b;
2488
+ border: 1.5px solid #18181b;
2489
+ border-radius: 4px 8px 5px 7px;
2490
+ font-weight: 800;
2491
+ box-shadow: 2px 2px 0 #18181b;
2492
+ transform: rotate(-1.2deg);
2493
+ }
2494
+ .markdy-scene-root[data-markdy-theme="doodle"] .markdy-node[data-shape="diamond"] {
2495
+ filter: drop-shadow(0 0 1px #18181b) drop-shadow(4px 4px 0 #18181b);
2496
+ }
2497
+ .markdy-scene-root[data-markdy-theme="doodle"] .markdy-node[data-focal="1"] {
2498
+ border: 2.25px solid #18181b;
2499
+ background: linear-gradient(135deg, #ffffff 0%, #fff1f2 100%);
2500
+ box-shadow: 4.5px 4.5px 0 #f43f5e, 0 0 0 2px #18181b;
2501
+ }
2502
+ .markdy-scene-root[data-markdy-theme="doodle"] .markdy-node[data-focal="1"] .markdy-node__icon {
2503
+ background: #f43f5e;
2504
+ color: #ffffff;
2505
+ border-color: #18181b;
2506
+ }
2507
+ .markdy-scene-root[data-markdy-theme="doodle"] .markdy-node[data-shape="diamond"][data-focal="1"] {
2508
+ filter: drop-shadow(0 0 1.5px #18181b) drop-shadow(4.5px 4.5px 0 #f43f5e);
2509
+ }
2199
2510
  .markdy-scene-root[data-markdy-theme="nebula"] .markdy-node[data-shape="diamond"] {
2200
2511
  filter: drop-shadow(0 0 1px var(--md-hairline)) drop-shadow(0 0 18px -4px color-mix(in srgb, var(--md-role-color, var(--md-accent)) 60%, transparent));
2201
2512
  }
@@ -2415,6 +2726,7 @@ var ICON_REGISTRY = Object.freeze(ICONS);
2415
2726
  function iconKeyForNode(node) {
2416
2727
  const override = typeof node.props?.icon === "string" ? node.props.icon.toLowerCase() : void 0;
2417
2728
  if (override && ICONS[override]) return override;
2729
+ if (override && resolveVectorSymbol(override)) return override;
2418
2730
  if (node.kind === "api_gateway" || node.kind === "gateway" || node.kind === "load_balancer" || node.kind === "ingress") return "gateway";
2419
2731
  if (node.kind === "db" || node.kind === "database" || node.kind === "sql" || node.kind === "nosql" || node.kind === "warehouse") return "database";
2420
2732
  if (node.kind === "bucket" || node.kind === "object_store" || node.kind === "blob" || node.kind === "volume" || node.kind === "disk") return "storage";
@@ -2490,6 +2802,21 @@ function createNodeMediaEl(doc, node, assets) {
2490
2802
  wrap.appendChild(img);
2491
2803
  return wrap;
2492
2804
  }
2805
+ const symbolKey = typeof node.props?.icon === "string" ? node.props.icon : typeof node.props?.symbol === "string" ? node.props.symbol : void 0;
2806
+ const vectorSymbol = symbolKey ? resolveVectorSymbol(symbolKey) : null;
2807
+ if (vectorSymbol) {
2808
+ wrap.dataset.vectorSymbol = vectorSymbol.name;
2809
+ const svg = doc.createElementNS("http://www.w3.org/2000/svg", "svg");
2810
+ svg.setAttribute("viewBox", vectorSymbol.viewBox);
2811
+ svg.setAttribute("width", "26");
2812
+ svg.setAttribute("height", "26");
2813
+ if (vectorSymbol.brandColor) {
2814
+ svg.style.color = vectorSymbol.brandColor;
2815
+ }
2816
+ svg.innerHTML = vectorSymbol.svgPaths;
2817
+ wrap.appendChild(svg);
2818
+ return wrap;
2819
+ }
2493
2820
  appendGlyph(doc, wrap, ICONS[iconKeyForNode(node)] ?? ICONS.service);
2494
2821
  return wrap;
2495
2822
  }
@@ -2511,7 +2838,10 @@ function createNodeEl(node, theme, assets) {
2511
2838
  const el = document.createElement("div");
2512
2839
  el.className = "markdy-node markdy-scene-node";
2513
2840
  el.dataset.node = node.id;
2514
- el.dataset.role = node.role;
2841
+ el.dataset.nodeId = node.id;
2842
+ el.setAttribute("data-node-id", node.id);
2843
+ el.setAttribute("data-node", node.id);
2844
+ el.id = `node-${node.id}`;
2515
2845
  el.style.left = `${node.x}px`;
2516
2846
  el.style.top = `${node.y}px`;
2517
2847
  el.style.setProperty("--md-node-w", `${node.width}px`);
@@ -2533,11 +2863,21 @@ function createNodeEl(node, theme, assets) {
2533
2863
  el.setAttribute("aria-label", el.title);
2534
2864
  const body = document.createElement("div");
2535
2865
  body.className = "markdy-node__body";
2866
+ if (node.shape !== "diamond") body.append(createNodeMediaEl(document, node, assets));
2867
+ const content = document.createElement("div");
2868
+ content.className = "markdy-node__content";
2536
2869
  const label = document.createElement("div");
2537
2870
  label.className = "markdy-node__label";
2538
2871
  label.textContent = node.label;
2539
- if (node.shape !== "diamond") body.append(createNodeMediaEl(document, node, assets));
2540
- body.append(label);
2872
+ content.appendChild(label);
2873
+ const tech = node.props?.tech ?? node.props?.sub;
2874
+ if (tech !== void 0 && tech !== null && String(tech).trim().length > 0) {
2875
+ const techEl = document.createElement("div");
2876
+ techEl.className = "markdy-node__tech";
2877
+ techEl.textContent = String(tech);
2878
+ content.appendChild(techEl);
2879
+ }
2880
+ body.append(content);
2541
2881
  const value = node.props?.value ?? node.props?.metric;
2542
2882
  if (value !== void 0 && value !== null) {
2543
2883
  const valueEl = document.createElement("div");
@@ -2658,10 +2998,11 @@ function mountSequenceLayer(layer, nodes, messages, activations, theme, bounds)
2658
2998
  cap.setAttribute("opacity", "0.85");
2659
2999
  svg.appendChild(cap);
2660
3000
  }
2661
- for (const activation of activations) {
3001
+ activations.forEach((activation, index) => {
2662
3002
  const x = centerX(activation.participant);
2663
3003
  const bar = doc.createElementNS("http://www.w3.org/2000/svg", "rect");
2664
3004
  bar.classList.add("markdy-sequence-activation");
3005
+ bar.setAttribute("data-activation-index", String(index));
2665
3006
  bar.setAttribute("x", String(x - 6));
2666
3007
  bar.setAttribute("y", String(activation.y));
2667
3008
  bar.setAttribute("width", "12");
@@ -2671,7 +3012,7 @@ function mountSequenceLayer(layer, nodes, messages, activations, theme, bounds)
2671
3012
  bar.setAttribute("opacity", "0");
2672
3013
  bar.style.filter = `drop-shadow(0 0 6px ${theme.accent}66)`;
2673
3014
  svg.appendChild(bar);
2674
- }
3015
+ });
2675
3016
  const animations = [];
2676
3017
  for (const message of messages) {
2677
3018
  const fromX = centerX(message.from);
@@ -2679,6 +3020,7 @@ function mountSequenceLayer(layer, nodes, messages, activations, theme, bounds)
2679
3020
  const group = doc.createElementNS("http://www.w3.org/2000/svg", "g");
2680
3021
  group.classList.add("markdy-sequence-message");
2681
3022
  group.setAttribute("data-message", message.id);
3023
+ group.setAttribute("data-message-id", message.id);
2682
3024
  group.style.opacity = "0";
2683
3025
  const line = doc.createElementNS("http://www.w3.org/2000/svg", "line");
2684
3026
  line.setAttribute("x1", String(fromX));
@@ -2712,16 +3054,39 @@ function mountSequenceLayer(layer, nodes, messages, activations, theme, bounds)
2712
3054
  group.appendChild(plate);
2713
3055
  group.appendChild(createText(doc, midX, message.y - 14.5, message.label, theme));
2714
3056
  }
3057
+ const pulse = doc.createElementNS("http://www.w3.org/2000/svg", "circle");
3058
+ pulse.setAttribute("r", "4");
3059
+ pulse.setAttribute("fill", theme.edges[message.kind] || theme.accent);
3060
+ pulse.classList.add("markdy-sequence-pulse");
3061
+ pulse.style.opacity = "0";
3062
+ pulse.style.filter = `drop-shadow(0 0 6px ${theme.edges[message.kind] || theme.accent})`;
3063
+ group.appendChild(pulse);
2715
3064
  svg.appendChild(group);
3065
+ const durMs = Math.max(160, message.duration * 1e3);
3066
+ const startMs = message.start * 1e3;
2716
3067
  animations.push(
2717
3068
  group.animate(
2718
3069
  [{ opacity: 0 }, { opacity: 1 }],
2719
3070
  {
2720
- duration: Math.max(160, message.duration * 1e3),
2721
- delay: message.start * 1e3,
3071
+ duration: 120,
3072
+ delay: startMs,
2722
3073
  fill: "forwards",
2723
3074
  easing: "ease-out"
2724
3075
  }
3076
+ ),
3077
+ pulse.animate(
3078
+ [
3079
+ { transform: `translate(${fromX}px, ${message.y}px)`, opacity: 0 },
3080
+ { transform: `translate(${fromX}px, ${message.y}px)`, opacity: 1, offset: 0.1 },
3081
+ { transform: `translate(${toX}px, ${message.y}px)`, opacity: 1, offset: 0.9 },
3082
+ { transform: `translate(${toX}px, ${message.y}px)`, opacity: 0 }
3083
+ ],
3084
+ {
3085
+ duration: durMs,
3086
+ delay: startMs,
3087
+ fill: "forwards",
3088
+ easing: "cubic-bezier(0.2, 0.85, 0.4, 1)"
3089
+ }
2725
3090
  )
2726
3091
  );
2727
3092
  }
@@ -2866,47 +3231,45 @@ function ensureSceneStyles(doc) {
2866
3231
  .markdy-scene-root::before {
2867
3232
  z-index: 0;
2868
3233
  background:
2869
- linear-gradient(var(--md-grid-minor) 1px, transparent 1px) 0 0 / 32px 32px,
2870
- linear-gradient(90deg, var(--md-grid-minor) 1px, transparent 1px) 0 0 / 32px 32px,
2871
- linear-gradient(var(--md-grid-major) 1px, transparent 1px) 0 0 / 160px 160px,
2872
- linear-gradient(90deg, var(--md-grid-major) 1px, transparent 1px) 0 0 / 160px 160px;
2873
- mask-image: radial-gradient(ellipse at 50% 42%, #000 55%, transparent 100%);
2874
- opacity: 0.5;
3234
+ radial-gradient(circle at 50% 50%, var(--md-grid-minor) 1.2px, transparent 1.2px) 0 0 / 24px 24px,
3235
+ linear-gradient(var(--md-grid-major) 1px, transparent 1px) 0 0 / 120px 120px,
3236
+ linear-gradient(90deg, var(--md-grid-major) 1px, transparent 1px) 0 0 / 120px 120px;
3237
+ mask-image: radial-gradient(ellipse at 50% 48%, #000 65%, transparent 100%);
3238
+ opacity: 0.55;
2875
3239
  }
2876
3240
  .markdy-scene-root::after {
2877
3241
  z-index: 1;
2878
3242
  background:
2879
- radial-gradient(ellipse at 50% -8%, color-mix(in srgb, var(--md-accent) 10%, transparent), transparent 46%),
2880
- linear-gradient(180deg, transparent 0%, rgba(2, 6, 23, 0.05) 62%, var(--md-vignette) 100%);
2881
- opacity: 0.62;
3243
+ radial-gradient(ellipse at 50% -12%, color-mix(in srgb, var(--md-accent) 14%, transparent), transparent 50%),
3244
+ linear-gradient(180deg, transparent 0%, rgba(2, 6, 23, 0.04) 55%, var(--md-vignette) 100%);
3245
+ opacity: 0.68;
2882
3246
  }
2883
3247
  .markdy-scene-content { z-index: 2; }
2884
3248
  .markdy-scene-root[data-markdy-theme="nebula"]::before {
2885
3249
  background:
2886
- radial-gradient(circle at 18% 18%, color-mix(in srgb, var(--md-soft) 16%, transparent), transparent 32%),
2887
- radial-gradient(circle at 84% 72%, color-mix(in srgb, var(--md-accent) 18%, transparent), transparent 36%),
2888
- linear-gradient(var(--md-grid-minor) 1px, transparent 1px) 0 0 / 32px 32px,
2889
- linear-gradient(90deg, var(--md-grid-minor) 1px, transparent 1px) 0 0 / 32px 32px;
2890
- mask-image: none;
2891
- opacity: 0.9;
3250
+ radial-gradient(circle at 18% 18%, color-mix(in srgb, var(--md-soft) 20%, transparent), transparent 36%),
3251
+ radial-gradient(circle at 84% 72%, color-mix(in srgb, var(--md-accent) 22%, transparent), transparent 40%),
3252
+ radial-gradient(circle at 50% 50%, var(--md-grid-minor) 1.5px, transparent 1.5px) 0 0 / 28px 28px;
3253
+ mask-image: radial-gradient(ellipse at 50% 50%, #000 70%, transparent 100%);
3254
+ opacity: 0.95;
2892
3255
  }
2893
3256
  .markdy-scene-root[data-markdy-theme="nebula"]::after {
2894
3257
  background:
2895
- radial-gradient(ellipse at 50% 42%, color-mix(in srgb, var(--md-accent) 12%, transparent), transparent 56%),
3258
+ radial-gradient(ellipse at 50% 42%, color-mix(in srgb, var(--md-accent) 16%, transparent), transparent 56%),
2896
3259
  linear-gradient(180deg, transparent 0%, var(--md-vignette) 100%);
2897
- opacity: 0.8;
3260
+ opacity: 0.85;
2898
3261
  }
2899
3262
  .markdy-scene-root[data-markdy-theme="terminal"]::before {
2900
3263
  background:
2901
- radial-gradient(circle at 50% 50%, rgba(255, 255, 255, 0.06) 1px, transparent 1px) 0 0 / 22px 22px;
3264
+ radial-gradient(circle at 50% 50%, rgba(255, 255, 255, 0.08) 1px, transparent 1px) 0 0 / 20px 20px;
2902
3265
  mask-image: none;
2903
- opacity: 0.4;
3266
+ opacity: 0.45;
2904
3267
  }
2905
3268
  .markdy-scene-root[data-markdy-theme="terminal"]::after {
2906
3269
  background:
2907
- radial-gradient(ellipse at 50% 0%, rgba(255, 90, 54, 0.08), transparent 50%),
2908
- linear-gradient(180deg, transparent, rgba(0, 0, 0, 0.5) 100%);
2909
- opacity: 0.7;
3270
+ radial-gradient(ellipse at 50% 0%, rgba(255, 90, 54, 0.1), transparent 52%),
3271
+ linear-gradient(180deg, transparent, rgba(0, 0, 0, 0.55) 100%);
3272
+ opacity: 0.75;
2910
3273
  }
2911
3274
  .markdy-scene-root[data-markdy-theme="sketchy"]::before {
2912
3275
  background: none;
@@ -2916,18 +3279,45 @@ function ensureSceneStyles(doc) {
2916
3279
  background: none;
2917
3280
  opacity: 0;
2918
3281
  }
3282
+ .markdy-scene-root[data-markdy-theme="ink"]::before {
3283
+ background:
3284
+ radial-gradient(circle at 50% 50%, color-mix(in srgb, var(--md-accent) 9%, transparent) 1px, transparent 1px) 0 0 / 20px 20px,
3285
+ linear-gradient(color-mix(in srgb, var(--md-accent) 6%, transparent) 1px, transparent 1px) 0 0 / 20px 20px,
3286
+ linear-gradient(90deg, color-mix(in srgb, var(--md-accent) 6%, transparent) 1px, transparent 1px) 0 0 / 20px 20px;
3287
+ mask-image: radial-gradient(ellipse at 50% 50%, #000 75%, transparent 100%);
3288
+ opacity: 0.75;
3289
+ }
3290
+ .markdy-scene-root[data-markdy-theme="ink"]::after {
3291
+ background:
3292
+ radial-gradient(ellipse at 50% -10%, color-mix(in srgb, var(--md-accent) 12%, transparent), transparent 50%),
3293
+ radial-gradient(ellipse at 100% 100%, rgba(30, 58, 138, 0.05), transparent 40%),
3294
+ linear-gradient(180deg, transparent 0%, rgba(219, 234, 254, 0.25) 80%, var(--md-vignette) 100%);
3295
+ opacity: 0.85;
3296
+ }
3297
+ .markdy-scene-root[data-markdy-theme="doodle"]::before {
3298
+ background:
3299
+ radial-gradient(circle at 50% 50%, rgba(24, 24, 27, 0.06) 1.5px, transparent 1.5px) 0 0 / 20px 20px;
3300
+ mask-image: none;
3301
+ opacity: 0.7;
3302
+ }
3303
+ .markdy-scene-root[data-markdy-theme="doodle"]::after {
3304
+ background:
3305
+ radial-gradient(ellipse at 85% 15%, rgba(244, 63, 94, 0.05), transparent 45%),
3306
+ radial-gradient(ellipse at 15% 85%, rgba(37, 99, 235, 0.05), transparent 45%);
3307
+ opacity: 0.6;
3308
+ }
2919
3309
  @keyframes markdy-star-twinkle {
2920
3310
  from { opacity: 0.24; transform: scale(0.85); }
2921
3311
  to { opacity: 0.9; transform: scale(1.15); }
2922
3312
  }
2923
3313
  @keyframes markdy-flow-dash {
2924
- to { stroke-dashoffset: -24; }
3314
+ to { stroke-dashoffset: -32; }
2925
3315
  }
2926
3316
  .markdy-edge {
2927
3317
  transition: opacity 0.2s ease;
2928
3318
  }
2929
3319
  .markdy-edge-path--flowing {
2930
- animation: markdy-flow-dash 1.2s linear infinite;
3320
+ animation: markdy-flow-dash 1.1s linear infinite;
2931
3321
  }
2932
3322
  .markdy-edge-path {
2933
3323
  transition: stroke 0.2s ease, stroke-width 0.2s ease, filter 0.2s ease;
@@ -2987,6 +3377,24 @@ function ensureSceneStyles(doc) {
2987
3377
  transform: translateY(8px);
2988
3378
  will-change: opacity, transform;
2989
3379
  }
3380
+ .markdy-scene-root[data-markdy-theme="ink"] .markdy-beat-caption {
3381
+ background: rgba(255, 255, 255, 0.96);
3382
+ border: 1.5px solid #1d4ed8;
3383
+ color: #1e3a8a;
3384
+ box-shadow:
3385
+ 2.5px 2.5px 0 rgba(29, 78, 216, 0.16),
3386
+ 0 10px 24px -6px rgba(29, 78, 216, 0.12);
3387
+ font-weight: 600;
3388
+ }
3389
+ .markdy-scene-root[data-markdy-theme="doodle"] .markdy-beat-caption {
3390
+ background: #ffffff;
3391
+ border: 2px solid #18181b;
3392
+ color: #18181b;
3393
+ border-radius: 255px 15px 225px 15px/15px 225px 15px 255px;
3394
+ box-shadow: 4px 4px 0 #18181b, 0 8px 20px -4px rgba(24, 24, 27, 0.12);
3395
+ font-weight: 800;
3396
+ padding: 10px 20px;
3397
+ }
2990
3398
  .markdy-diagram-root {
2991
3399
  position: relative;
2992
3400
  display: flex;
@@ -3639,6 +4047,11 @@ function applyThemeToScene(scene, theme) {
3639
4047
  }
3640
4048
 
3641
4049
  // src/export/svg-exporter.ts
4050
+ import {
4051
+ parseAndCompile,
4052
+ resolveTheme,
4053
+ resolveVectorSymbol as resolveVectorSymbol2
4054
+ } from "@markdy/core";
3642
4055
  function copyRenderedStyles(source, clone) {
3643
4056
  if (typeof window === "undefined" || typeof window.getComputedStyle !== "function") return;
3644
4057
  const sourceElements = [source, ...Array.from(source.querySelectorAll("*"))];
@@ -3659,11 +4072,6 @@ function normalizeExportViewport(scene) {
3659
4072
  viewportTransform.style.willChange = "auto";
3660
4073
  });
3661
4074
  }
3662
- function getDiagramSceneElement(containerEl) {
3663
- const sceneEl = containerEl.classList?.contains("markdy-scene-root") ? containerEl : containerEl.querySelector(".markdy-scene-root") || containerEl.querySelector("svg") || (containerEl.tagName?.toLowerCase() === "svg" ? containerEl : null);
3664
- if (!sceneEl) throw new Error("No Markdy scene element found in container");
3665
- return sceneEl;
3666
- }
3667
4075
  function prepareHtmlSceneForExport(sceneEl, options = {}) {
3668
4076
  const clonedScene = sceneEl.cloneNode(true);
3669
4077
  copyRenderedStyles(sceneEl, clonedScene);
@@ -3689,98 +4097,1505 @@ function prepareHtmlSceneForExport(sceneEl, options = {}) {
3689
4097
  }
3690
4098
  return { sceneEl, clonedScene, width, height, scaledWidth, scaledHeight };
3691
4099
  }
3692
- function exportDiagramAsVectorSvg(containerEl, options = {}) {
3693
- const sceneEl = getDiagramSceneElement(containerEl);
3694
- if (sceneEl.tagName?.toLowerCase() === "svg") {
3695
- const clonedSvg = sceneEl.cloneNode(true);
3696
- if (!clonedSvg.getAttribute("xmlns")) {
3697
- clonedSvg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
4100
+ function escapeXml(str) {
4101
+ if (str === null || str === void 0) return "";
4102
+ return String(str).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
4103
+ }
4104
+ function dedupePoints2(points) {
4105
+ const out = [];
4106
+ for (const p of points) {
4107
+ const last = out[out.length - 1];
4108
+ if (!last || Math.abs(last.x - p.x) > 0.01 || Math.abs(last.y - p.y) > 0.01) out.push(p);
4109
+ }
4110
+ return out.length >= 2 ? out : points;
4111
+ }
4112
+ function circleBoundaryRoute2(from, to) {
4113
+ const fromCenter = { x: from.x + from.width / 2, y: from.y + from.height / 2 };
4114
+ const toCenter = { x: to.x + to.width / 2, y: to.y + to.height / 2 };
4115
+ const dx = toCenter.x - fromCenter.x;
4116
+ const dy = toCenter.y - fromCenter.y;
4117
+ const distance = Math.hypot(dx, dy) || 1;
4118
+ const ux = dx / distance;
4119
+ const uy = dy / distance;
4120
+ const fromRadius = Math.min(from.width, from.height) / 2;
4121
+ const toRadius = Math.min(to.width, to.height) / 2;
4122
+ return dedupePoints2([
4123
+ { x: fromCenter.x + ux * fromRadius, y: fromCenter.y + uy * fromRadius },
4124
+ { x: toCenter.x - ux * toRadius, y: toCenter.y - uy * toRadius }
4125
+ ]);
4126
+ }
4127
+ function snapPortToNodeShape2(node, port, neighbor, isSource) {
4128
+ if (!node.shape || node.shape === "card" || node.shape === "rounded" || node.shape === "terminal" || node.shape === "container") {
4129
+ return port;
4130
+ }
4131
+ const cx = node.x + node.width / 2;
4132
+ const cy = node.y + node.height / 2;
4133
+ const hw = node.width / 2;
4134
+ const hh = node.height / 2;
4135
+ if (node.shape === "diamond") {
4136
+ const isVert = Math.abs(port.x - neighbor.x) < 0.01;
4137
+ const isHoriz = Math.abs(port.y - neighbor.y) < 0.01;
4138
+ if (isVert) {
4139
+ const goingDown = isSource ? neighbor.y > port.y : port.y > neighbor.y;
4140
+ const boundaryY = goingDown ? cy + hh * (1 - Math.min(1, Math.abs(port.x - cx) / hw)) : cy - hh * (1 - Math.min(1, Math.abs(port.x - cx) / hw));
4141
+ return { x: port.x, y: Math.round(boundaryY * 10) / 10 };
4142
+ }
4143
+ if (isHoriz) {
4144
+ const goingRight = isSource ? neighbor.x > port.x : port.x > neighbor.x;
4145
+ const boundaryX = goingRight ? cx + hw * (1 - Math.min(1, Math.abs(port.y - cy) / hh)) : cx - hw * (1 - Math.min(1, Math.abs(port.y - cy) / hh));
4146
+ return { x: Math.round(boundaryX * 10) / 10, y: port.y };
3698
4147
  }
3699
- const serializer2 = new XMLSerializer();
3700
- return `<?xml version="1.0" encoding="UTF-8" standalone="no"?>
3701
- ${serializer2.serializeToString(clonedSvg)}`;
3702
4148
  }
3703
- const { clonedScene, scaledWidth, scaledHeight } = prepareHtmlSceneForExport(sceneEl, options);
3704
- const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
3705
- svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
3706
- svg.setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
3707
- svg.setAttribute("width", String(scaledWidth));
3708
- svg.setAttribute("height", String(scaledHeight));
3709
- svg.setAttribute("viewBox", `0 0 ${scaledWidth} ${scaledHeight}`);
3710
- if (options.includeThemeStyles !== false) {
3711
- const styleEl = document.createElementNS("http://www.w3.org/2000/svg", "style");
3712
- let combinedStyles = `
3713
- foreignObject { width: 100%; height: 100%; }
3714
- .markdy-node { transition: opacity 0.3s ease; }
3715
- `;
3716
- if (typeof document !== "undefined") {
3717
- const styles = document.querySelectorAll("style[id^='markdy-']");
3718
- for (let i = 0; i < styles.length; i++) {
3719
- combinedStyles += styles[i].textContent + "\n";
3720
- }
4149
+ if (node.shape === "circle") {
4150
+ const r = Math.min(node.width, node.height) / 2;
4151
+ const isVert = Math.abs(port.x - neighbor.x) < 0.01;
4152
+ const isHoriz = Math.abs(port.y - neighbor.y) < 0.01;
4153
+ if (isVert) {
4154
+ const goingDown = isSource ? neighbor.y > port.y : port.y > neighbor.y;
4155
+ return { x: cx, y: goingDown ? cy + r : cy - r };
4156
+ }
4157
+ if (isHoriz) {
4158
+ const goingRight = isSource ? neighbor.x > port.x : port.x > neighbor.x;
4159
+ return { x: goingRight ? cx + r : cx - r, y: cy };
3721
4160
  }
3722
- styleEl.textContent = combinedStyles;
3723
- svg.appendChild(styleEl);
3724
4161
  }
3725
- const foreignObject = document.createElementNS("http://www.w3.org/2000/svg", "foreignObject");
3726
- foreignObject.setAttribute("width", "100%");
3727
- foreignObject.setAttribute("height", "100%");
3728
- foreignObject.appendChild(clonedScene);
3729
- svg.appendChild(foreignObject);
3730
- const serializer = new XMLSerializer();
3731
- return `<?xml version="1.0" encoding="UTF-8" standalone="no"?>
3732
- ` + serializer.serializeToString(svg);
4162
+ if (node.shape === "pill") {
4163
+ const r = node.height / 2;
4164
+ const isVert = Math.abs(port.x - neighbor.x) < 0.01;
4165
+ const isHoriz = Math.abs(port.y - neighbor.y) < 0.01;
4166
+ if (isHoriz) {
4167
+ const goingRight = isSource ? neighbor.x > port.x : port.x > neighbor.x;
4168
+ return { x: goingRight ? node.x + node.width : node.x, y: cy };
4169
+ }
4170
+ if (isVert) {
4171
+ const goingDown = isSource ? neighbor.y > port.y : port.y > neighbor.y;
4172
+ const clampedX = Math.max(node.x + r, Math.min(node.x + node.width - r, port.x));
4173
+ return { x: clampedX, y: goingDown ? node.y + node.height : node.y };
4174
+ }
4175
+ }
4176
+ return port;
3733
4177
  }
3734
-
3735
- // src/diagram.ts
3736
- var NORMAL_PLAYBACK_RATE = 4 / 5;
3737
- var MIN_VIEWPORT_ZOOM = 0.5;
3738
- var MAX_VIEWPORT_ZOOM = 3;
3739
- var VIEWPORT_ZOOM_STEP = 15e-4;
3740
- var DRAG_CLICK_THRESHOLD_PX = 4;
3741
- var BEAT_NAV_EPSILON_S = 0.05;
3742
- var MARKDY_PLAYGROUND_URL = "https://markdy.com/playground/";
3743
- function encodeCodeForPlaygroundHash(code) {
3744
- return encodeURIComponent(btoa(encodeURIComponent(code)));
4178
+ function snapRouteEndpointsToShapes2(points, from, to) {
4179
+ if (points.length < 2) return points;
4180
+ const out = [...points];
4181
+ out[0] = snapPortToNodeShape2(from, out[0], out[1], true);
4182
+ out[out.length - 1] = snapPortToNodeShape2(to, out[out.length - 1], out[out.length - 2], false);
4183
+ return dedupePoints2(out);
3745
4184
  }
3746
- function createBeatCaptionLayer(doc, beats) {
3747
- const layer = doc.createElement("div");
3748
- layer.className = "markdy-beat-caption-layer";
3749
- for (const beat of beats) {
3750
- if (!beat.label) continue;
3751
- const caption = doc.createElement("div");
3752
- caption.className = "markdy-beat-caption";
3753
- caption.textContent = beat.label;
3754
- caption.dataset.beat = beat.name;
3755
- layer.appendChild(caption);
3756
- }
3757
- return layer;
4185
+ function routeEdgePoints2(from, to, routeObstacles, bounds, lane) {
4186
+ if (from.shape === "circle" && to.shape === "circle") return circleBoundaryRoute2(from, to);
4187
+ const raw = routeOrthogonal(boxRect(from), boxRect(to), routeObstacles, bounds, lane);
4188
+ return snapRouteEndpointsToShapes2(raw, from, to);
3758
4189
  }
3759
- function buildBeatCaptionAnimations(beats, layer) {
3760
- const anims = [];
3761
- const captions = Array.from(layer.querySelectorAll(".markdy-beat-caption"));
3762
- for (const beat of beats) {
3763
- if (!beat.label) continue;
3764
- const caption = captions.find((item) => item.dataset.beat === beat.name);
3765
- if (!caption) continue;
3766
- const startMs = beat.start * 1e3;
3767
- const durMs = Math.max((beat.end - beat.start) * 1e3, 650);
3768
- anims.push(
3769
- caption.animate(
3770
- [
3771
- { opacity: 0, transform: "translateY(8px)" },
3772
- { opacity: 1, transform: "translateY(0)", offset: 0.16 },
3773
- { opacity: 1, transform: "translateY(0)", offset: 0.82 },
3774
- { opacity: 0, transform: "translateY(-4px)" }
3775
- ],
3776
- { duration: durMs, delay: startMs, fill: "forwards", easing: "ease-out" }
3777
- )
3778
- );
4190
+ function isDarkTheme2(theme) {
4191
+ if (theme.name === "paper" || theme.name === "editorial" || theme.name === "sketchy" || theme.name === "ink" || theme.name === "doodle") {
4192
+ return false;
3779
4193
  }
3780
- return anims;
3781
- }
3782
- function createDiagram(opts) {
3783
- const {
4194
+ const canvas = (theme.canvas || theme.surface || "").trim();
4195
+ if (canvas.startsWith("#")) {
4196
+ const hex = canvas.slice(1);
4197
+ const r = parseInt(hex.length === 3 ? hex[0] + hex[0] : hex.slice(0, 2), 16) || 0;
4198
+ const g = parseInt(hex.length === 3 ? hex[1] + hex[1] : hex.slice(2, 4), 16) || 0;
4199
+ const b = parseInt(hex.length === 3 ? hex[2] + hex[2] : hex.slice(4, 6), 16) || 0;
4200
+ const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
4201
+ return luminance < 0.5;
4202
+ }
4203
+ return true;
4204
+ }
4205
+ function computeEdgeLabelColor2(edgeColor, isDark) {
4206
+ return isDark ? "#f8fafc" : "#0f172a";
4207
+ }
4208
+ var EDGE_STYLES2 = {
4209
+ request: { dash: "", marker: "arrow" },
4210
+ response: { dash: "6 4", marker: "arrow-open" },
4211
+ event: { dash: "2 6", marker: "dot" },
4212
+ dependency: { dash: "4 4", marker: "none" }
4213
+ };
4214
+ function wrapNodeLabel(label, maxWidthPx, fontSize = 13.5) {
4215
+ if (!label) return [];
4216
+ const avgCharWidth = fontSize * 0.52;
4217
+ const maxChars = Math.max(10, Math.floor(maxWidthPx / avgCharWidth));
4218
+ if (label.length <= maxChars) return [label];
4219
+ const words = label.trim().split(/\s+/);
4220
+ if (words.length <= 1) return [label];
4221
+ const lines = [];
4222
+ let current = "";
4223
+ for (const word of words) {
4224
+ if (!current) {
4225
+ current = word;
4226
+ } else if ((current + " " + word).length <= maxChars) {
4227
+ current += " " + word;
4228
+ } else {
4229
+ lines.push(current);
4230
+ current = word;
4231
+ if (lines.length === 2) break;
4232
+ }
4233
+ }
4234
+ if (current && lines.length < 3) {
4235
+ lines.push(current);
4236
+ }
4237
+ return lines;
4238
+ }
4239
+ function renderPureVectorSvg(plan, options = {}) {
4240
+ const width = plan.meta.width;
4241
+ const height = plan.meta.height;
4242
+ const theme = plan.theme || resolveTheme(plan.meta?.theme || "paper");
4243
+ const isDark = isDarkTheme2(theme);
4244
+ const canvasBg = options.transparentBackground ? "none" : theme.canvas || (isDark ? "#0b0f19" : "#f6f8fc");
4245
+ const surface = theme.surface || (isDark ? "#141c2e" : "#ffffff");
4246
+ const surfaceRaised = theme.surfaceRaised || (isDark ? "#1e293b" : "#f1f5f9");
4247
+ const border = theme.border || (isDark ? "#334155" : "#cbd5e1");
4248
+ const textColor = theme.text || (isDark ? "#f8fafc" : "#0f172a");
4249
+ const textMuted = theme.textMuted || (isDark ? "#94a3b8" : "#64748b");
4250
+ const accent = theme.accent || "#2563eb";
4251
+ const bounds = { width, height };
4252
+ const routeObstacles = [
4253
+ ...plan.nodes.map((n) => inflateRect(boxRect(n), 12)),
4254
+ ...(plan.groupBoundaries ?? []).map((gb) => boxRect(gb))
4255
+ ];
4256
+ const labelObstacles = plan.nodes.map((n) => inflateRect(boxRect(n), 6));
4257
+ const existingPaths = [];
4258
+ let svg = `<?xml version="1.0" encoding="UTF-8" standalone="no"?>
4259
+ <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 ${width} ${height}" width="${width}" height="${height}">
4260
+ <defs>
4261
+ <!-- Embedded Typography & Anti-Aliasing -->
4262
+ <style>
4263
+ text {
4264
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Inter, Roboto, "Helvetica Neue", Arial, sans-serif;
4265
+ text-rendering: geometricPrecision;
4266
+ -webkit-font-smoothing: antialiased;
4267
+ }
4268
+ .markdy-svg-text {
4269
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Inter, Roboto, "Helvetica Neue", Arial, sans-serif;
4270
+ text-rendering: geometricPrecision;
4271
+ -webkit-font-smoothing: antialiased;
4272
+ }
4273
+ .markdy-svg-mono {
4274
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
4275
+ text-rendering: geometricPrecision;
4276
+ -webkit-font-smoothing: antialiased;
4277
+ }
4278
+ </style>
4279
+
4280
+ <!-- Drop Shadow Filter -->
4281
+ <filter id="markdy-node-shadow" x="-10%" y="-10%" width="130%" height="130%">
4282
+ <feDropShadow dx="0" dy="4" stdDeviation="6" flood-color="#020617" flood-opacity="${isDark ? "0.45" : "0.12"}"/>
4283
+ <feDropShadow dx="0" dy="1" stdDeviation="2" flood-color="#020617" flood-opacity="${isDark ? "0.25" : "0.08"}"/>
4284
+ </filter>
4285
+
4286
+ <!-- Grid Patterns -->
4287
+ <pattern id="markdy-grid-minor" width="32" height="32" patternUnits="userSpaceOnUse">
4288
+ <path d="M 32 0 L 0 0 0 32" fill="none" stroke="${theme.gridMinor || (isDark ? "#334155" : "#e2e8f0")}" stroke-width="1" stroke-opacity="0.5"/>
4289
+ </pattern>
4290
+ <pattern id="markdy-grid-major" width="160" height="160" patternUnits="userSpaceOnUse">
4291
+ <path d="M 160 0 L 0 0 0 160" fill="none" stroke="${theme.gridMajor || (isDark ? "#475569" : "#cbd5e1")}" stroke-width="1.2" stroke-opacity="0.6"/>
4292
+ </pattern>
4293
+
4294
+ <!-- Arrowhead Markers -->
4295
+ <marker id="arrow-request" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto">
4296
+ <path d="M 1.5 1.6 L 9 5 L 1.5 8.4 L 3.4 5 Z" fill="${theme.edges?.request || accent}"/>
4297
+ </marker>
4298
+ <marker id="arrow-response" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto">
4299
+ <path d="M 1.5 1.6 L 9 5 L 1.5 8.4" fill="none" stroke="${theme.edges?.response || textMuted}" stroke-width="1.4"/>
4300
+ </marker>
4301
+ <marker id="arrow-event" viewBox="0 0 10 10" refX="5" refY="5" markerWidth="6" markerHeight="6" orient="auto">
4302
+ <circle cx="5" cy="5" r="3" fill="${theme.edges?.event || accent}"/>
4303
+ </marker>
4304
+ </defs>
4305
+
4306
+ <!-- Background -->
4307
+ ${options.transparentBackground ? "" : `
4308
+ <rect width="100%" height="100%" fill="${canvasBg}"/>
4309
+ <rect width="100%" height="100%" fill="url(#markdy-grid-minor)"/>
4310
+ <rect width="100%" height="100%" fill="url(#markdy-grid-major)"/>
4311
+ `}
4312
+ `;
4313
+ if (plan.title) {
4314
+ svg += `
4315
+ <!-- Diagram Title -->
4316
+ <g class="markdy-title-layer">
4317
+ <text x="48" y="44" class="markdy-svg-text" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Inter, Roboto, sans-serif" font-size="22" font-weight="700" fill="${textColor}" dominant-baseline="central" letter-spacing="-0.02em">${escapeXml(plan.title)}</text>
4318
+ </g>
4319
+ `;
4320
+ }
4321
+ const cameraTransformAttr = options.cameraTransform && options.cameraTransform !== "none" ? ` transform="${escapeXml(options.cameraTransform)}"` : "";
4322
+ svg += ` <!-- Main Scene Content -->
4323
+ <g class="markdy-camera-layer"${cameraTransformAttr}>
4324
+ `;
4325
+ if (plan.groupBoundaries && plan.groupBoundaries.length > 0) {
4326
+ svg += ` <!-- Group Boundaries -->
4327
+ <g class="markdy-groups-layer">
4328
+ `;
4329
+ for (const gb of plan.groupBoundaries) {
4330
+ svg += ` <g id="group-${escapeXml(gb.id)}" transform="translate(${gb.x}, ${gb.y})">
4331
+ <rect width="${gb.width}" height="${gb.height}" rx="16" fill="${surfaceRaised}" fill-opacity="${isDark ? "0.28" : "0.45"}" stroke="${border}" stroke-width="1.2" stroke-dasharray="5 5"/>
4332
+ `;
4333
+ if (gb.label) {
4334
+ const labelText = gb.label.toUpperCase();
4335
+ const labelW = Math.max(54, labelText.length * 6.8 + 20);
4336
+ svg += ` <rect x="14" y="10" width="${labelW}" height="20" rx="6" fill="${surfaceRaised}" fill-opacity="0.95" stroke="${border}" stroke-width="1"/>
4337
+ <text x="${14 + labelW / 2}" y="20" class="markdy-svg-mono" font-family="ui-monospace, SFMono-Regular, Menlo, Monaco, monospace" font-size="10" font-weight="700" letter-spacing="0.1em" fill="${textColor}" text-anchor="middle" dominant-baseline="central">${escapeXml(labelText)}</text>
4338
+ `;
4339
+ }
4340
+ svg += ` </g>
4341
+ `;
4342
+ }
4343
+ svg += ` </g>
4344
+ `;
4345
+ }
4346
+ if (plan.treeBuses && plan.treeBuses.length > 0) {
4347
+ svg += ` <!-- Tree Buses -->
4348
+ <g class="markdy-tree-layer">
4349
+ `;
4350
+ const busStroke = theme.edges?.dependency ?? theme.border ?? "#64748b";
4351
+ for (const bus of plan.treeBuses) {
4352
+ for (const childX of bus.childXs) {
4353
+ let d;
4354
+ if (Math.abs(childX - bus.parentX) < 1) {
4355
+ d = toPathD([
4356
+ { x: bus.parentX, y: bus.parentY },
4357
+ { x: childX, y: bus.childY }
4358
+ ], 12);
4359
+ } else {
4360
+ d = toPathD([
4361
+ { x: bus.parentX, y: bus.parentY },
4362
+ { x: bus.parentX, y: bus.branchY },
4363
+ { x: childX, y: bus.branchY },
4364
+ { x: childX, y: bus.childY }
4365
+ ], 12);
4366
+ }
4367
+ svg += ` <path d="${d}" fill="none" stroke="${busStroke}" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
4368
+ `;
4369
+ }
4370
+ }
4371
+ svg += ` </g>
4372
+ `;
4373
+ }
4374
+ if (plan.diagramType === "sequence") {
4375
+ svg += ` <!-- Sequence Layer -->
4376
+ <g class="markdy-sequence-layer">
4377
+ `;
4378
+ const nodeById = new Map(plan.nodes.map((node) => [node.id, node]));
4379
+ const centerX = (id) => {
4380
+ const node = nodeById.get(id);
4381
+ return node ? node.x + node.width / 2 : 0;
4382
+ };
4383
+ const lifelineStroke = theme.edges?.dependency ?? theme.rule ?? theme.border ?? "#64748b";
4384
+ for (const node of plan.nodes) {
4385
+ const x = centerX(node.id);
4386
+ const y1 = node.y + node.height;
4387
+ const y2 = Math.max(y1 + 40, height - 36);
4388
+ svg += ` <line class="markdy-sequence-lifeline" x1="${x}" y1="${y1}" x2="${x}" y2="${y2}" stroke="${lifelineStroke}" stroke-width="1.5" stroke-dasharray="5 5" opacity="0.85"/>
4389
+ `;
4390
+ svg += ` <circle class="markdy-sequence-lifeline-cap" cx="${x}" cy="${y2}" r="2.5" fill="${lifelineStroke}" opacity="0.85"/>
4391
+ `;
4392
+ }
4393
+ if (plan.sequenceActivations) {
4394
+ plan.sequenceActivations.forEach((activation, idx) => {
4395
+ const x = centerX(activation.participant);
4396
+ const actState = options.sequenceActivationStates?.get(idx);
4397
+ const actOpacity = actState !== void 0 ? actState.opacity : options.sequenceActivationStates ? 0 : 0.9;
4398
+ if (actOpacity > 1e-3) {
4399
+ const opacityAttr = actOpacity < 0.999 ? `opacity="${actOpacity}"` : "";
4400
+ svg += ` <rect class="markdy-sequence-activation" x="${x - 6}" y="${activation.y}" width="12" height="${activation.height}" rx="4" fill="${accent}" ${opacityAttr}/>
4401
+ `;
4402
+ }
4403
+ });
4404
+ }
4405
+ if (plan.sequenceMessages) {
4406
+ for (const msg of plan.sequenceMessages) {
4407
+ const fromX = centerX(msg.from);
4408
+ const toX = centerX(msg.to);
4409
+ const msgColor = theme.edges?.[msg.kind] || accent;
4410
+ const markerAttr = msg.kind === "response" ? 'marker-end="url(#arrow-response)"' : 'marker-end="url(#arrow-request)"';
4411
+ const dashAttr = msg.kind === "response" ? 'stroke-dasharray="6 4"' : msg.kind === "event" ? 'stroke-dasharray="2 6"' : "";
4412
+ const msgState = options.sequenceMessageStates?.get(msg.id);
4413
+ const msgOpacity = msgState !== void 0 ? msgState.opacity : 1;
4414
+ if (msgOpacity <= 1e-3) continue;
4415
+ const opacityAttr = msgOpacity < 0.999 ? `opacity="${msgOpacity}"` : "";
4416
+ svg += ` <g class="markdy-sequence-message" data-message="${escapeXml(msg.id)}" ${opacityAttr}>
4417
+ <line x1="${fromX}" y1="${msg.y}" x2="${toX}" y2="${msg.y}" stroke="${msgColor}" stroke-width="2" stroke-linecap="round" ${dashAttr} ${markerAttr}/>
4418
+ `;
4419
+ if (msg.label) {
4420
+ const midX = (fromX + toX) / 2;
4421
+ const msgPlateW = msg.label.length * 6.8 + 16;
4422
+ const plateFill = theme.labelPlate ?? theme.surface ?? (isDark ? "#1e293b" : "#ffffff");
4423
+ const plateStroke = theme.hairline ?? theme.border ?? (isDark ? "#334155" : "#cbd5e1");
4424
+ svg += ` <rect x="${midX - msgPlateW / 2}" y="${msg.y - 12}" width="${msgPlateW}" height="24" rx="6" fill="${plateFill}" fill-opacity="0.96" stroke="${plateStroke}" stroke-width="1"/>
4425
+ <text x="${midX}" y="${msg.y}" class="markdy-svg-mono" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-size="11" font-weight="500" fill="${textColor}" text-anchor="middle" dominant-baseline="central">${escapeXml(msg.label)}</text>
4426
+ `;
4427
+ }
4428
+ svg += ` </g>
4429
+ `;
4430
+ }
4431
+ }
4432
+ svg += ` </g>
4433
+ `;
4434
+ }
4435
+ if (plan.diagramType !== "sequence" && plan.edges && plan.edges.length > 0) {
4436
+ svg += ` <!-- Edge Connections -->
4437
+ <g class="markdy-edges-layer">
4438
+ `;
4439
+ const nodeMap = new Map(plan.nodes.map((n) => [n.id, n]));
4440
+ const laneByPair = /* @__PURE__ */ new Map();
4441
+ plan.edges.forEach((edge, index) => {
4442
+ const from = nodeMap.get(edge.from);
4443
+ const to = nodeMap.get(edge.to);
4444
+ if (!from || !to) return;
4445
+ const edgeState = edge.id ? options.edgeStates?.get(edge.id) : void 0;
4446
+ const edgeOpacity = edgeState ? edgeState.opacity : 1;
4447
+ if (edgeOpacity <= 1e-3) return;
4448
+ const color = theme.edges?.[edge.kind] || accent;
4449
+ const style = EDGE_STYLES2[edge.kind] || EDGE_STYLES2.request;
4450
+ const isSelfLoop = from.id === to.id;
4451
+ const lane = nextEdgeLane(laneByPair, from, to);
4452
+ const points = isSelfLoop ? dedupePoints2(selfLoopPath(from, bounds)) : dedupePoints2(routeEdgePoints2(from, to, routeObstacles, bounds, lane));
4453
+ const d = toPathD(points, 14, existingPaths);
4454
+ existingPaths.push(points);
4455
+ const markerAttr = style.marker === "arrow" ? 'marker-end="url(#arrow-request)"' : style.marker === "arrow-open" ? 'marker-end="url(#arrow-response)"' : style.marker === "dot" ? 'marker-end="url(#arrow-event)"' : "";
4456
+ const dashAttr = style.dash ? `stroke-dasharray="${style.dash}"` : "";
4457
+ const dashOffsetAttr = edgeState?.strokeDashoffset && edgeState.strokeDashoffset !== "0px" && edgeState.strokeDashoffset !== "0" ? `stroke-dashoffset="${escapeXml(edgeState.strokeDashoffset)}"` : "";
4458
+ const opacityAttr = edgeOpacity < 0.999 ? `opacity="${edgeOpacity}"` : "";
4459
+ svg += ` <g id="edge-${escapeXml(edge.id || `flow_${index}`)}" class="markdy-edge" ${opacityAttr}>
4460
+ <path d="${d}" fill="none" stroke="${color}" stroke-width="${edge.kind === "dependency" ? "1.5" : "2"}" stroke-linecap="round" stroke-linejoin="round" ${dashAttr} ${dashOffsetAttr} ${markerAttr}/>
4461
+ `;
4462
+ if (edge.label) {
4463
+ let longestSegLen = 0;
4464
+ for (let i = 0; i < points.length - 1; i++) {
4465
+ longestSegLen = Math.max(longestSegLen, Math.hypot(points[i + 1].x - points[i].x, points[i + 1].y - points[i].y));
4466
+ }
4467
+ const maxAvailW = Math.max(48, longestSegLen - 24);
4468
+ const lines = wrapFlowLabelText(edge.label, maxAvailW);
4469
+ const maxChars = Math.max(...lines.map((l) => l.length));
4470
+ const textWidth = Math.max(36, maxChars * 6.6 + 8);
4471
+ const lineHeight = 13;
4472
+ const boxHeight = lines.length === 1 ? 18 : lines.length * lineHeight + 6;
4473
+ const placement = placeFlowLabel(points, textWidth, labelObstacles, bounds, boxHeight);
4474
+ labelObstacles.push(inflateRect(placement.rect, 4));
4475
+ const padX = 6;
4476
+ const halfW = textWidth / 2;
4477
+ const labelX = placement.x - halfW - padX;
4478
+ const labelY = placement.y - boxHeight / 2;
4479
+ const labelColor = computeEdgeLabelColor2(color, isDark);
4480
+ svg += ` <!-- Edge Label -->
4481
+ <rect x="${labelX}" y="${labelY}" width="${textWidth + padX * 2}" height="${boxHeight}" rx="4" fill="${canvasBg}" stroke="${border}" stroke-width="1"/>
4482
+ `;
4483
+ if (lines.length === 1) {
4484
+ svg += ` <text x="${placement.x}" y="${placement.y}" class="markdy-svg-mono" font-family="ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace" font-size="10.5" font-weight="500" fill="${labelColor}" text-anchor="middle" dominant-baseline="central">${escapeXml(lines[0])}</text>
4485
+ `;
4486
+ } else {
4487
+ lines.forEach((lineText, idx) => {
4488
+ const lineY = placement.y - (lines.length - 1) * lineHeight / 2 + idx * lineHeight;
4489
+ svg += ` <text x="${placement.x}" y="${lineY}" class="markdy-svg-mono" font-family="ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace" font-size="10.5" font-weight="500" fill="${labelColor}" text-anchor="middle" dominant-baseline="central">${escapeXml(lineText)}</text>
4490
+ `;
4491
+ });
4492
+ }
4493
+ }
4494
+ svg += ` </g>
4495
+ `;
4496
+ });
4497
+ svg += ` </g>
4498
+ `;
4499
+ }
4500
+ svg += ` <!-- Node Cards -->
4501
+ <g class="markdy-nodes-layer">
4502
+ `;
4503
+ for (const node of plan.nodes) {
4504
+ const nodeState = options.nodeStates?.get(node.id);
4505
+ const nodeOpacity = nodeState ? nodeState.opacity : 1;
4506
+ if (nodeOpacity <= 1e-3) continue;
4507
+ const roleColor = theme.roles && theme.roles[node.role] || accent;
4508
+ const iconKey = iconKeyForNode(node);
4509
+ const glyphSpec = ICON_REGISTRY[iconKey] || ICON_REGISTRY.service;
4510
+ const isDiamond = node.shape === "diamond";
4511
+ const isCircle = node.shape === "circle";
4512
+ const isPill = node.shape === "pill";
4513
+ const transformStr = nodeState?.transform && nodeState.transform !== "none" ? `translate(${node.x}, ${node.y}) ${nodeState.transform}` : `translate(${node.x}, ${node.y})`;
4514
+ const opacityAttr = nodeOpacity < 0.999 ? `opacity="${nodeOpacity}"` : "";
4515
+ svg += ` <g id="node-${escapeXml(node.id)}" transform="${escapeXml(transformStr)}" ${opacityAttr}>
4516
+ `;
4517
+ if (isDiamond) {
4518
+ const hw = node.width / 2;
4519
+ const hh = node.height / 2;
4520
+ svg += ` <polygon points="${hw},0 ${node.width},${hh} ${hw},${node.height} 0,${hh}" fill="${surface}" stroke="${border}" stroke-width="1" filter="url(#markdy-node-shadow)"/>
4521
+ `;
4522
+ } else if (isCircle) {
4523
+ const r = Math.min(node.width, node.height) / 2;
4524
+ svg += ` <circle cx="${node.width / 2}" cy="${node.height / 2}" r="${r}" fill="${surface}" stroke="${border}" stroke-width="1" filter="url(#markdy-node-shadow)"/>
4525
+ `;
4526
+ } else if (isPill) {
4527
+ svg += ` <rect width="${node.width}" height="${node.height}" rx="${node.height / 2}" fill="${surface}" stroke="${border}" stroke-width="1" filter="url(#markdy-node-shadow)"/>
4528
+ `;
4529
+ } else {
4530
+ const rx = node.shape === "terminal" ? "8" : node.shape === "rounded" ? "16" : "12";
4531
+ svg += ` <rect width="${node.width}" height="${node.height}" rx="${rx}" fill="${surface}" stroke="${border}" stroke-width="1" filter="url(#markdy-node-shadow)"/>
4532
+ <rect x="0.5" y="0.5" width="${node.width - 1}" height="${node.height - 1}" rx="${parseFloat(rx) - 0.5}" fill="none" stroke="rgba(255,255,255,0.12)" stroke-width="1"/>
4533
+ `;
4534
+ }
4535
+ const hasTech = Boolean(node.props?.tech || node.props?.sub);
4536
+ const techText = String(node.props?.tech || node.props?.sub || "");
4537
+ const value = node.props?.value ?? node.props?.metric;
4538
+ const valText = value !== void 0 && value !== null ? String(value) : "";
4539
+ const valWidth = valText ? valText.length * 9.5 + 16 : 0;
4540
+ const iconSize = 26;
4541
+ if (isDiamond) {
4542
+ const availTextWidth = Math.max(40, node.width * 0.65);
4543
+ const lines = wrapNodeLabel(node.label, availTextWidth, 12.5);
4544
+ const centerX = node.width / 2;
4545
+ if (hasTech) {
4546
+ const labelCenterY = node.height / 2 - 8;
4547
+ if (lines.length === 1) {
4548
+ svg += ` <text x="${centerX}" y="${labelCenterY}" class="markdy-svg-text" font-size="12.5" font-weight="600" fill="${textColor}" text-anchor="middle" dominant-baseline="central">${escapeXml(lines[0])}</text>
4549
+ `;
4550
+ } else {
4551
+ const startY = labelCenterY - (lines.length - 1) * 14 / 2;
4552
+ lines.forEach((l, idx) => {
4553
+ svg += ` <text x="${centerX}" y="${startY + idx * 14}" class="markdy-svg-text" font-size="12" font-weight="600" fill="${textColor}" text-anchor="middle" dominant-baseline="central">${escapeXml(l)}</text>
4554
+ `;
4555
+ });
4556
+ }
4557
+ const techBadgeW = Math.min(availTextWidth, techText.length * 6.2 + 12);
4558
+ const techBadgeY = node.height / 2 + 5;
4559
+ svg += ` <rect x="${centerX - techBadgeW / 2}" y="${techBadgeY}" width="${techBadgeW}" height="15" rx="4" fill="${textColor}" fill-opacity="${isDark ? "0.08" : "0.05"}" stroke="${border}" stroke-width="0.75"/>
4560
+ <text x="${centerX}" y="${techBadgeY + 7.5}" class="markdy-svg-mono" font-size="9" font-weight="500" fill="${textMuted}" text-anchor="middle" dominant-baseline="central">${escapeXml(techText)}</text>
4561
+ `;
4562
+ } else {
4563
+ if (lines.length === 1) {
4564
+ svg += ` <text x="${centerX}" y="${node.height / 2}" class="markdy-svg-text" font-size="13" font-weight="600" fill="${textColor}" text-anchor="middle" dominant-baseline="central">${escapeXml(lines[0])}</text>
4565
+ `;
4566
+ } else {
4567
+ const startY = node.height / 2 - (lines.length - 1) * 15 / 2;
4568
+ lines.forEach((l, idx) => {
4569
+ svg += ` <text x="${centerX}" y="${startY + idx * 15}" class="markdy-svg-text" font-size="12.5" font-weight="600" fill="${textColor}" text-anchor="middle" dominant-baseline="central">${escapeXml(l)}</text>
4570
+ `;
4571
+ });
4572
+ }
4573
+ }
4574
+ } else if (isCircle) {
4575
+ const centerX = node.width / 2;
4576
+ const availTextWidth = Math.max(40, node.width * 0.72);
4577
+ const lines = wrapNodeLabel(node.label, availTextWidth, 11.5);
4578
+ const circleIconSize = 20;
4579
+ const iconX = (node.width - circleIconSize) / 2;
4580
+ const iconY = node.height / 2 - 20;
4581
+ const circleSymbolKey = typeof node.props?.icon === "string" ? node.props.icon : typeof node.props?.symbol === "string" ? node.props.symbol : void 0;
4582
+ const circleVectorSymbol = circleSymbolKey ? resolveVectorSymbol2(circleSymbolKey) : null;
4583
+ const rawImage = node.props?.image ?? node.props?.logo;
4584
+ if (typeof rawImage === "string" && rawImage.length > 0) {
4585
+ svg += ` <!-- Centered Custom Image -->
4586
+ <image href="${escapeXml(rawImage)}" x="${iconX}" y="${iconY}" width="${circleIconSize}" height="${circleIconSize}" preserveAspectRatio="xMidYMid meet"/>
4587
+ `;
4588
+ } else if (circleVectorSymbol) {
4589
+ const symColor = circleVectorSymbol.brandColor || roleColor;
4590
+ svg += ` <!-- Centered Vector Symbol: ${escapeXml(circleVectorSymbol.name)} -->
4591
+ <g transform="translate(${iconX}, ${iconY}) scale(${circleIconSize / 24})" fill="currentColor" color="${symColor}">
4592
+ ${circleVectorSymbol.svgPaths}
4593
+ </g>
4594
+ `;
4595
+ } else {
4596
+ svg += ` <!-- Centered Icon Glyph -->
4597
+ <g transform="translate(${iconX}, ${iconY}) scale(${circleIconSize / 24})" fill="none" stroke="${roleColor}" stroke-width="1.85" stroke-linecap="round" stroke-linejoin="round">
4598
+ `;
4599
+ if (glyphSpec) {
4600
+ for (const [tag, attrs] of glyphSpec) {
4601
+ const attrStr = Object.entries(attrs).map(([k, v]) => `${k}="${escapeXml(v)}"`).join(" ");
4602
+ svg += ` <${tag} ${attrStr} />
4603
+ `;
4604
+ }
4605
+ }
4606
+ svg += ` </g>
4607
+ `;
4608
+ }
4609
+ const textCenterY = node.height / 2 + 10;
4610
+ if (lines.length === 1) {
4611
+ svg += ` <text x="${centerX}" y="${textCenterY}" class="markdy-svg-text" font-size="11.5" font-weight="600" fill="${textColor}" text-anchor="middle" dominant-baseline="central">${escapeXml(lines[0])}</text>
4612
+ `;
4613
+ } else {
4614
+ const startY = textCenterY - (lines.length - 1) * 13 / 2;
4615
+ lines.forEach((l, idx) => {
4616
+ svg += ` <text x="${centerX}" y="${startY + idx * 13}" class="markdy-svg-text" font-size="11" font-weight="600" fill="${textColor}" text-anchor="middle" dominant-baseline="central">${escapeXml(l)}</text>
4617
+ `;
4618
+ });
4619
+ }
4620
+ } else {
4621
+ const iconX = 16;
4622
+ const iconY = (node.height - iconSize) / 2;
4623
+ const cardSymbolKey = typeof node.props?.icon === "string" ? node.props.icon : typeof node.props?.symbol === "string" ? node.props.symbol : void 0;
4624
+ const cardVectorSymbol = cardSymbolKey ? resolveVectorSymbol2(cardSymbolKey) : null;
4625
+ const rawImage = node.props?.image ?? node.props?.logo;
4626
+ if (typeof rawImage === "string" && rawImage.length > 0) {
4627
+ svg += ` <!-- Node Custom Image -->
4628
+ <image href="${escapeXml(rawImage)}" x="${iconX}" y="${iconY}" width="${iconSize}" height="${iconSize}" preserveAspectRatio="xMidYMid meet"/>
4629
+ `;
4630
+ } else if (cardVectorSymbol) {
4631
+ const symColor = cardVectorSymbol.brandColor || roleColor;
4632
+ svg += ` <!-- Native Vector Symbol: ${escapeXml(cardVectorSymbol.name)} -->
4633
+ <g transform="translate(${iconX}, ${iconY}) scale(${iconSize / 24})" fill="currentColor" color="${symColor}">
4634
+ ${cardVectorSymbol.svgPaths}
4635
+ </g>
4636
+ `;
4637
+ } else {
4638
+ svg += ` <!-- Frameless Icon Glyph -->
4639
+ <g transform="translate(${iconX}, ${iconY}) scale(${iconSize / 24})" fill="none" stroke="${roleColor}" stroke-width="1.85" stroke-linecap="round" stroke-linejoin="round">
4640
+ `;
4641
+ if (glyphSpec) {
4642
+ for (const [tag, attrs] of glyphSpec) {
4643
+ const attrStr = Object.entries(attrs).map(([k, v]) => `${k}="${escapeXml(v)}"`).join(" ");
4644
+ svg += ` <${tag} ${attrStr} />
4645
+ `;
4646
+ }
4647
+ }
4648
+ svg += ` </g>
4649
+ `;
4650
+ }
4651
+ const textStartX = 54;
4652
+ const availTextWidth = node.width - textStartX - (valWidth > 0 ? valWidth + 14 : 14);
4653
+ const lines = wrapNodeLabel(node.label, availTextWidth, 13.5);
4654
+ if (hasTech) {
4655
+ const labelCenterY = Math.round(node.height / 2 - 8);
4656
+ if (lines.length === 1) {
4657
+ svg += ` <!-- Label -->
4658
+ <text x="${textStartX}" y="${labelCenterY}" class="markdy-svg-text" font-size="13" font-weight="600" letter-spacing="-0.01em" fill="${textColor}" dominant-baseline="central">${escapeXml(lines[0])}</text>
4659
+ `;
4660
+ } else {
4661
+ const startY = Math.round(labelCenterY - (lines.length - 1) * 14 / 2);
4662
+ svg += ` <!-- Label -->
4663
+ <text class="markdy-svg-text" font-size="12.5" font-weight="600" letter-spacing="-0.01em" fill="${textColor}">
4664
+ `;
4665
+ lines.forEach((l, idx) => {
4666
+ svg += ` <tspan x="${textStartX}" y="${startY + idx * 14}" dominant-baseline="central">${escapeXml(l)}</tspan>
4667
+ `;
4668
+ });
4669
+ svg += ` </text>
4670
+ `;
4671
+ }
4672
+ const techBadgeW = Math.min(availTextWidth, techText.length * 6.2 + 12);
4673
+ const techBadgeY = Math.round(node.height / 2 + 5);
4674
+ svg += ` <!-- Tech Badge -->
4675
+ <rect x="${textStartX}" y="${techBadgeY}" width="${techBadgeW}" height="16" rx="4" fill="${textColor}" fill-opacity="${isDark ? "0.08" : "0.05"}" stroke="${border}" stroke-width="0.75"/>
4676
+ <text x="${textStartX + 6}" y="${techBadgeY + 8}" class="markdy-svg-mono" font-size="9.5" font-weight="500" fill="${textMuted}" dominant-baseline="central">${escapeXml(techText)}</text>
4677
+ `;
4678
+ } else {
4679
+ if (lines.length === 1) {
4680
+ svg += ` <!-- Label -->
4681
+ <text x="${textStartX}" y="${Math.round(node.height / 2)}" class="markdy-svg-text" font-size="13.5" font-weight="600" letter-spacing="-0.01em" fill="${textColor}" dominant-baseline="central">${escapeXml(lines[0])}</text>
4682
+ `;
4683
+ } else if (lines.length === 2) {
4684
+ const startY = Math.round(node.height / 2 - 8);
4685
+ svg += ` <!-- Label -->
4686
+ <text x="${textStartX}" y="${startY}" class="markdy-svg-text" font-size="13.5" font-weight="600" letter-spacing="-0.01em" fill="${textColor}" dominant-baseline="central">${escapeXml(lines[0])}</text>
4687
+ <text x="${textStartX}" y="${startY + 16}" class="markdy-svg-text" font-size="13.5" font-weight="600" letter-spacing="-0.01em" fill="${textColor}" dominant-baseline="central">${escapeXml(lines[1])}</text>
4688
+ `;
4689
+ } else {
4690
+ const startY = Math.round(node.height / 2 - 15);
4691
+ svg += ` <!-- Label -->
4692
+ <text x="${textStartX}" y="${startY}" class="markdy-svg-text" font-size="13.5" font-weight="600" letter-spacing="-0.01em" fill="${textColor}" dominant-baseline="central">${escapeXml(lines[0])}</text>
4693
+ <text x="${textStartX}" y="${startY + 15}" class="markdy-svg-text" font-size="13.5" font-weight="600" letter-spacing="-0.01em" fill="${textColor}" dominant-baseline="central">${escapeXml(lines[1])}</text>
4694
+ <text x="${textStartX}" y="${startY + 30}" class="markdy-svg-text" font-size="13.5" font-weight="600" letter-spacing="-0.01em" fill="${textColor}" dominant-baseline="central">${escapeXml(lines[2])}</text>
4695
+ `;
4696
+ }
4697
+ }
4698
+ }
4699
+ if (valText) {
4700
+ svg += ` <!-- Metric Value -->
4701
+ <text x="${node.width - 16}" y="${Math.round(node.height / 2)}" class="markdy-svg-text" font-size="15" font-weight="700" fill="${textColor}" text-anchor="end" dominant-baseline="central">${escapeXml(valText)}</text>
4702
+ `;
4703
+ }
4704
+ svg += ` </g>
4705
+ `;
4706
+ }
4707
+ svg += ` </g>
4708
+ `;
4709
+ if (options.flowDots && options.flowDots.length > 0) {
4710
+ svg += ` <!-- Flow Particles -->
4711
+ <g class="markdy-flow-particles">
4712
+ `;
4713
+ for (const dot of options.flowDots) {
4714
+ if (dot.opacity > 1e-3) {
4715
+ svg += ` <circle cx="${dot.x}" cy="${dot.y}" r="${dot.r}" fill="${dot.fill}" opacity="${dot.opacity}"/>
4716
+ `;
4717
+ }
4718
+ }
4719
+ svg += ` </g>
4720
+ `;
4721
+ }
4722
+ svg += ` </g>
4723
+ `;
4724
+ if (options.activeCaption && options.activeCaption.opacity > 0.01 && options.activeCaption.text) {
4725
+ const capX = width / 2;
4726
+ const capY = height - 32;
4727
+ const capW = options.activeCaption.text.length * 7.5 + 28;
4728
+ svg += ` <!-- Live Beat Caption -->
4729
+ <g class="markdy-live-caption" opacity="${options.activeCaption.opacity}">
4730
+ `;
4731
+ svg += ` <rect x="${capX - capW / 2}" y="${capY - 13}" width="${capW}" height="26" rx="13" fill="${surfaceRaised}" stroke="${border}" stroke-width="1" filter="url(#markdy-node-shadow)"/>
4732
+ `;
4733
+ svg += ` <text x="${capX}" y="${capY}" class="markdy-svg-text" font-size="12" font-weight="600" fill="${textColor}" text-anchor="middle" dominant-baseline="central">${escapeXml(options.activeCaption.text)}</text>
4734
+ `;
4735
+ svg += ` </g>
4736
+ `;
4737
+ }
4738
+ svg += `
4739
+ <!-- Watermark -->
4740
+ <g class="markdy-watermark" transform="translate(${width - 120}, ${height - 18})">
4741
+ <text class="markdy-svg-text" font-family="-apple-system, BlinkMacSystemFont, 'Segoe UI', Inter, sans-serif" font-size="10" font-weight="500" fill="${textMuted}" opacity="0.7" dominant-baseline="central">Powered by Markdy</text>
4742
+ </g>
4743
+ </svg>`;
4744
+ return svg;
4745
+ }
4746
+ function exportLiveSceneAsPureVectorSvg(containerEl, options = {}) {
4747
+ const sceneEl = containerEl.classList?.contains("markdy-scene-root") ? containerEl : containerEl.querySelector(".markdy-scene-root") || containerEl;
4748
+ const rootEl = containerEl.classList?.contains("markdy-diagram-root") ? containerEl : containerEl.closest?.(".markdy-diagram-root") || containerEl;
4749
+ const storedPlan = rootEl.__markdyPlan || sceneEl.__markdyPlan || containerEl.__markdyPlan;
4750
+ const storedCode = rootEl.__markdyCode || sceneEl.__markdyCode || containerEl.__markdyCode;
4751
+ let plan = storedPlan ?? null;
4752
+ if (!plan && storedCode && typeof storedCode === "string") {
4753
+ try {
4754
+ plan = parseAndCompile(storedCode).plan;
4755
+ } catch {
4756
+ plan = null;
4757
+ }
4758
+ }
4759
+ if (plan) {
4760
+ const nodeStates = /* @__PURE__ */ new Map();
4761
+ const edgeStates = /* @__PURE__ */ new Map();
4762
+ const sequenceMessageStates = /* @__PURE__ */ new Map();
4763
+ const sequenceActivationStates = /* @__PURE__ */ new Map();
4764
+ const flowDots = [];
4765
+ let activeCaption;
4766
+ let cameraTransform;
4767
+ if (typeof window !== "undefined" && typeof window.getComputedStyle === "function") {
4768
+ const cameraEl = sceneEl.querySelector(".markdy-camera-layer");
4769
+ if (cameraEl) {
4770
+ const comp = window.getComputedStyle(cameraEl);
4771
+ if (comp.transform && comp.transform !== "none") {
4772
+ cameraTransform = comp.transform;
4773
+ }
4774
+ }
4775
+ for (const node of plan.nodes) {
4776
+ const nodeEl = sceneEl.querySelector(`[data-node="${node.id}"], [data-node-id="${node.id}"], #node-${node.id}`);
4777
+ if (nodeEl) {
4778
+ const comp = window.getComputedStyle(nodeEl);
4779
+ const opacity = comp.display === "none" || comp.visibility === "hidden" ? 0 : parseFloat(comp.opacity || "1");
4780
+ nodeStates.set(node.id, {
4781
+ opacity: isNaN(opacity) ? 1 : opacity,
4782
+ transform: comp.transform && comp.transform !== "none" ? comp.transform : void 0
4783
+ });
4784
+ }
4785
+ }
4786
+ for (const edge of plan.edges) {
4787
+ const edgeId = edge.id;
4788
+ if (edgeId) {
4789
+ const edgeEl = sceneEl.querySelector(`[data-edge-id="${edgeId}"], [data-edge="${edgeId}"], #edge-${edgeId}`);
4790
+ if (edgeEl) {
4791
+ const comp = window.getComputedStyle(edgeEl);
4792
+ const opacity = comp.display === "none" || comp.visibility === "hidden" ? 0 : parseFloat(comp.opacity || "1");
4793
+ const pathEl = edgeEl.querySelector(".markdy-edge-path");
4794
+ const pathComp = pathEl ? window.getComputedStyle(pathEl) : comp;
4795
+ edgeStates.set(edgeId, {
4796
+ opacity: isNaN(opacity) ? 1 : opacity,
4797
+ strokeDashoffset: pathComp.strokeDashoffset && pathComp.strokeDashoffset !== "0px" ? pathComp.strokeDashoffset : void 0
4798
+ });
4799
+ }
4800
+ }
4801
+ }
4802
+ const seqMsgEls = sceneEl.querySelectorAll(".markdy-sequence-message, [data-message], [data-message-id]");
4803
+ seqMsgEls.forEach((msgEl) => {
4804
+ const msgId = msgEl.getAttribute("data-message") || msgEl.getAttribute("data-message-id");
4805
+ if (msgId) {
4806
+ const comp = window.getComputedStyle(msgEl);
4807
+ const opacity = comp.display === "none" || comp.visibility === "hidden" ? 0 : parseFloat(comp.opacity || "1");
4808
+ sequenceMessageStates.set(msgId, {
4809
+ opacity: isNaN(opacity) ? 1 : opacity
4810
+ });
4811
+ }
4812
+ });
4813
+ const seqActEls = sceneEl.querySelectorAll(".markdy-sequence-activation");
4814
+ seqActEls.forEach((actEl, idx) => {
4815
+ const indexAttr = actEl.getAttribute("data-activation-index");
4816
+ const actIndex = indexAttr ? parseInt(indexAttr, 10) : idx;
4817
+ const comp = window.getComputedStyle(actEl);
4818
+ const opacity = comp.display === "none" || comp.visibility === "hidden" ? 0 : parseFloat(comp.opacity || "1");
4819
+ sequenceActivationStates.set(actIndex, {
4820
+ opacity: isNaN(opacity) ? 0 : opacity
4821
+ });
4822
+ });
4823
+ const dotEls = sceneEl.querySelectorAll(".markdy-edge-dot, .markdy-sequence-pulse");
4824
+ dotEls.forEach((dotEl) => {
4825
+ const comp = window.getComputedStyle(dotEl);
4826
+ const opacity = comp.display === "none" || comp.visibility === "hidden" ? 0 : parseFloat(comp.opacity || "0");
4827
+ if (opacity > 0.01) {
4828
+ const transform = comp.transform;
4829
+ let tx = 0;
4830
+ let ty = 0;
4831
+ if (transform && transform !== "none") {
4832
+ const matrixMatch = transform.match(/matrix\(([^)]+)\)/);
4833
+ if (matrixMatch) {
4834
+ const parts = matrixMatch[1].split(",").map(Number);
4835
+ tx = parts[4] || 0;
4836
+ ty = parts[5] || 0;
4837
+ } else {
4838
+ const translateMatch = transform.match(/translate\(([^,]+)px,\s*([^)]+)px\)/);
4839
+ if (translateMatch) {
4840
+ tx = parseFloat(translateMatch[1]) || 0;
4841
+ ty = parseFloat(translateMatch[2]) || 0;
4842
+ }
4843
+ }
4844
+ }
4845
+ const cx = parseFloat(dotEl.getAttribute("cx") || "0") + tx;
4846
+ const cy = parseFloat(dotEl.getAttribute("cy") || "0") + ty;
4847
+ const r = parseFloat(dotEl.getAttribute("r") || "4.5");
4848
+ const fill = comp.fill || dotEl.getAttribute("fill") || "#38bdf8";
4849
+ flowDots.push({ x: cx, y: cy, r, fill, opacity });
4850
+ }
4851
+ });
4852
+ const capEls = sceneEl.querySelectorAll(".markdy-beat-caption");
4853
+ for (const capEl of Array.from(capEls)) {
4854
+ const comp = window.getComputedStyle(capEl);
4855
+ const opacity = comp.display === "none" || comp.visibility === "hidden" ? 0 : parseFloat(comp.opacity || "0");
4856
+ if (opacity > 0.05 && capEl.textContent) {
4857
+ activeCaption = {
4858
+ text: capEl.textContent.trim(),
4859
+ opacity
4860
+ };
4861
+ break;
4862
+ }
4863
+ }
4864
+ return renderPureVectorSvg(plan, {
4865
+ ...options,
4866
+ nodeStates,
4867
+ edgeStates,
4868
+ sequenceMessageStates,
4869
+ sequenceActivationStates,
4870
+ flowDots,
4871
+ activeCaption,
4872
+ cameraTransform
4873
+ });
4874
+ }
4875
+ return renderPureVectorSvg(plan, {
4876
+ ...options,
4877
+ nodeStates,
4878
+ edgeStates,
4879
+ cameraTransform
4880
+ });
4881
+ }
4882
+ return exportDiagramAsVectorSvg(containerEl, { ...options, mode: "pure" });
4883
+ }
4884
+ function exportDiagramAsVectorSvg(target, options = {}) {
4885
+ if (typeof target === "string") {
4886
+ const { plan } = parseAndCompile(target);
4887
+ return renderPureVectorSvg(plan, options);
4888
+ }
4889
+ if (typeof target === "object" && target !== null && "meta" in target && "nodes" in target) {
4890
+ return renderPureVectorSvg(target, options);
4891
+ }
4892
+ if (typeof HTMLElement !== "undefined" && target instanceof HTMLElement) {
4893
+ const rootEl = target.classList?.contains("markdy-diagram-root") ? target : target.closest?.(".markdy-diagram-root") || target;
4894
+ const storedCode = rootEl.__markdyCode || target.__markdyCode;
4895
+ if (storedCode && typeof storedCode === "string") {
4896
+ const { plan } = parseAndCompile(storedCode);
4897
+ return renderPureVectorSvg(plan, options);
4898
+ }
4899
+ const storedPlan = rootEl.__markdyPlan || target.__markdyPlan;
4900
+ if (storedPlan && typeof storedPlan === "object" && "meta" in storedPlan) {
4901
+ return renderPureVectorSvg(storedPlan, options);
4902
+ }
4903
+ if (target.tagName?.toLowerCase() === "svg") {
4904
+ const clonedSvg = target.cloneNode(true);
4905
+ if (!clonedSvg.getAttribute("xmlns")) {
4906
+ clonedSvg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
4907
+ }
4908
+ const serializer = new XMLSerializer();
4909
+ return `<?xml version="1.0" encoding="UTF-8" standalone="no"?>
4910
+ ${serializer.serializeToString(clonedSvg)}`;
4911
+ }
4912
+ }
4913
+ const sceneEl = typeof HTMLElement !== "undefined" && target instanceof HTMLElement ? target.querySelector(".markdy-scene-root") || target : null;
4914
+ if (sceneEl) {
4915
+ const { clonedScene, scaledWidth, scaledHeight } = prepareHtmlSceneForExport(sceneEl, options);
4916
+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
4917
+ svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
4918
+ svg.setAttribute("width", String(scaledWidth));
4919
+ svg.setAttribute("height", String(scaledHeight));
4920
+ svg.setAttribute("viewBox", `0 0 ${scaledWidth} ${scaledHeight}`);
4921
+ const foreignObject = document.createElementNS("http://www.w3.org/2000/svg", "foreignObject");
4922
+ foreignObject.setAttribute("width", "100%");
4923
+ foreignObject.setAttribute("height", "100%");
4924
+ foreignObject.appendChild(clonedScene);
4925
+ svg.appendChild(foreignObject);
4926
+ const serializer = new XMLSerializer();
4927
+ return `<?xml version="1.0" encoding="UTF-8" standalone="no"?>
4928
+ ` + serializer.serializeToString(svg);
4929
+ }
4930
+ throw new Error("Could not export diagram: invalid target or missing Markdy script.");
4931
+ }
4932
+
4933
+ // src/export/inline-resources.ts
4934
+ var TRANSPARENT_PIXEL_DATA_URI = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
4935
+ var RESOURCE_FETCH_TIMEOUT_MS = 3e3;
4936
+ var dataUriCache = /* @__PURE__ */ new Map();
4937
+ function shouldInlineUrl(url) {
4938
+ const trimmed = url.trim();
4939
+ return !!trimmed && !trimmed.startsWith("data:") && !trimmed.startsWith("blob:") && !trimmed.startsWith("#");
4940
+ }
4941
+ async function toDataUri(url) {
4942
+ if (dataUriCache.has(url)) return dataUriCache.get(url);
4943
+ const request = (async () => {
4944
+ const controller = new AbortController();
4945
+ const timeout = setTimeout(() => controller.abort(), RESOURCE_FETCH_TIMEOUT_MS);
4946
+ try {
4947
+ const resp = await fetch(url, { mode: "cors", credentials: "same-origin", signal: controller.signal });
4948
+ if (!resp.ok) return null;
4949
+ const arrayBuffer = await resp.arrayBuffer();
4950
+ const mimeType = resp.headers.get("Content-Type") || "application/octet-stream";
4951
+ const base64 = btoa(
4952
+ new Uint8Array(arrayBuffer).reduce((data, byte) => data + String.fromCharCode(byte), "")
4953
+ );
4954
+ return `data:${mimeType};base64,${base64}`;
4955
+ } catch {
4956
+ return null;
4957
+ } finally {
4958
+ clearTimeout(timeout);
4959
+ }
4960
+ })();
4961
+ dataUriCache.set(url, request);
4962
+ return request;
4963
+ }
4964
+ async function inlineCssUrls(cssValue) {
4965
+ const urlPattern = /url\(["']?([^"')]+)["']?\)/g;
4966
+ const matches = [];
4967
+ let m;
4968
+ while ((m = urlPattern.exec(cssValue)) !== null) {
4969
+ const src = m[1];
4970
+ if (shouldInlineUrl(src)) {
4971
+ matches.push({ full: m[0], src });
4972
+ }
4973
+ }
4974
+ let result = cssValue;
4975
+ await Promise.all(
4976
+ matches.map(async ({ full, src }) => {
4977
+ try {
4978
+ const absoluteSrc = new URL(src, document.baseURI).href;
4979
+ const dataUri = await toDataUri(absoluteSrc);
4980
+ result = result.split(full).join(dataUri ? `url("${dataUri}")` : "none");
4981
+ } catch {
4982
+ result = result.split(full).join("none");
4983
+ }
4984
+ })
4985
+ );
4986
+ return result;
4987
+ }
4988
+ async function inlineExternalResources(root) {
4989
+ const tasks = [];
4990
+ root.querySelectorAll("img").forEach((img) => {
4991
+ const src = img.getAttribute("src");
4992
+ if (src && shouldInlineUrl(src)) {
4993
+ tasks.push(
4994
+ Promise.resolve().then(() => toDataUri(new URL(src, document.baseURI).href)).then((dataUri) => {
4995
+ img.setAttribute("src", dataUri || TRANSPARENT_PIXEL_DATA_URI);
4996
+ })
4997
+ );
4998
+ }
4999
+ });
5000
+ const allEls = [root, ...Array.from(root.querySelectorAll("*"))];
5001
+ allEls.forEach((el) => {
5002
+ const style = el.getAttribute("style");
5003
+ if (style && style.includes("url(")) {
5004
+ tasks.push(
5005
+ inlineCssUrls(style).then((inlined) => {
5006
+ if (inlined !== style) el.setAttribute("style", inlined);
5007
+ })
5008
+ );
5009
+ }
5010
+ });
5011
+ await Promise.all(tasks);
5012
+ }
5013
+ async function inlineSerializedSvgResources(svgXml) {
5014
+ const doc = new DOMParser().parseFromString(svgXml, "image/svg+xml");
5015
+ if (doc.querySelector("parsererror")) return svgXml;
5016
+ await inlineExternalResources(doc.documentElement);
5017
+ const serializer = new XMLSerializer();
5018
+ const serializedSvg = serializer.serializeToString(doc.documentElement);
5019
+ return `<?xml version="1.0" encoding="UTF-8" standalone="no"?>
5020
+ ${serializedSvg}`;
5021
+ }
5022
+
5023
+ // src/export/png-exporter.ts
5024
+ async function exportDiagramAsPng(containerEl, options = {}) {
5025
+ const canvas = await rasterizeDiagramToCanvas(containerEl, options, options.pixelRatio || 2);
5026
+ return new Promise((resolve, reject) => {
5027
+ canvas.toBlob((b) => {
5028
+ if (b) resolve(b);
5029
+ else reject(new Error("Canvas toBlob failed for PNG export"));
5030
+ }, "image/png");
5031
+ });
5032
+ }
5033
+ async function rasterizeDiagramToCanvas(containerEl, options = {}, pixelRatio = 1) {
5034
+ const pixelRatioForSvg = pixelRatio || 1;
5035
+ const svgXml = exportLiveSceneAsPureVectorSvg(containerEl, options);
5036
+ const inlinedSvgXml = await inlineSerializedSvgResources(svgXml);
5037
+ const blob = new Blob([inlinedSvgXml], { type: "image/svg+xml;charset=utf-8" });
5038
+ const url = URL.createObjectURL(blob);
5039
+ const img = new Image();
5040
+ await new Promise((resolve, reject) => {
5041
+ img.onload = () => resolve();
5042
+ img.onerror = () => {
5043
+ URL.revokeObjectURL(url);
5044
+ reject(new Error("Failed to rasterize SVG into Image for canvas export"));
5045
+ };
5046
+ img.src = url;
5047
+ });
5048
+ const width = img.naturalWidth || (containerEl.clientWidth || 800);
5049
+ const height = img.naturalHeight || (containerEl.clientHeight || 400);
5050
+ const canvas = document.createElement("canvas");
5051
+ canvas.width = Math.max(1, Math.round(width * pixelRatioForSvg));
5052
+ canvas.height = Math.max(1, Math.round(height * pixelRatioForSvg));
5053
+ const ctx = canvas.getContext("2d");
5054
+ if (!ctx) {
5055
+ URL.revokeObjectURL(url);
5056
+ throw new Error("Could not get 2D canvas context for export");
5057
+ }
5058
+ ctx.scale(pixelRatioForSvg, pixelRatioForSvg);
5059
+ ctx.drawImage(img, 0, 0, width, height);
5060
+ URL.revokeObjectURL(url);
5061
+ return canvas;
5062
+ }
5063
+
5064
+ // src/export/gif-encoder.ts
5065
+ var GIF_HEADER = "GIF89a";
5066
+ var TRANSPARENT_COLOR_INDEX = 255;
5067
+ function buildAdaptivePalette(frames, maxColors = 254) {
5068
+ const histogram = /* @__PURE__ */ new Map();
5069
+ const stepFrame = Math.max(1, Math.floor(frames.length / 8));
5070
+ for (let f = 0; f < frames.length; f += stepFrame) {
5071
+ const data = frames[f].imageData.data;
5072
+ const len = data.length;
5073
+ for (let i = 0; i < len; i += 8) {
5074
+ const a = data[i + 3];
5075
+ if (a < 16) continue;
5076
+ const r = data[i];
5077
+ const g = data[i + 1];
5078
+ const b = data[i + 2];
5079
+ const key = r << 16 | g << 8 | b;
5080
+ histogram.set(key, (histogram.get(key) || 0) + 1);
5081
+ }
5082
+ }
5083
+ const entries = Array.from(histogram.entries());
5084
+ let paletteColors = [];
5085
+ if (entries.length <= maxColors) {
5086
+ paletteColors = entries.map(([key]) => [
5087
+ key >> 16 & 255,
5088
+ key >> 8 & 255,
5089
+ key & 255
5090
+ ]);
5091
+ } else {
5092
+ entries.sort((a, b) => b[1] - a[1]);
5093
+ const topCount = Math.min(128, Math.floor(maxColors * 0.6));
5094
+ for (let i = 0; i < topCount; i++) {
5095
+ const key = entries[i][0];
5096
+ paletteColors.push([
5097
+ key >> 16 & 255,
5098
+ key >> 8 & 255,
5099
+ key & 255
5100
+ ]);
5101
+ }
5102
+ const buckets = /* @__PURE__ */ new Map();
5103
+ for (let i = topCount; i < entries.length; i++) {
5104
+ const [key, count] = entries[i];
5105
+ const r = key >> 16 & 255;
5106
+ const g = key >> 8 & 255;
5107
+ const b = key & 255;
5108
+ const bKey = r >> 3 << 10 | g >> 3 << 5 | b >> 3;
5109
+ let buck = buckets.get(bKey);
5110
+ if (!buck) {
5111
+ buck = { rSum: 0, gSum: 0, bSum: 0, count: 0 };
5112
+ buckets.set(bKey, buck);
5113
+ }
5114
+ buck.rSum += r * count;
5115
+ buck.gSum += g * count;
5116
+ buck.bSum += b * count;
5117
+ buck.count += count;
5118
+ }
5119
+ const bucketList = Array.from(buckets.values()).sort((a, b) => b.count - a.count);
5120
+ const remainSlots = maxColors - paletteColors.length;
5121
+ for (let i = 0; i < Math.min(remainSlots, bucketList.length); i++) {
5122
+ const b = bucketList[i];
5123
+ paletteColors.push([
5124
+ Math.round(b.rSum / b.count),
5125
+ Math.round(b.gSum / b.count),
5126
+ Math.round(b.bSum / b.count)
5127
+ ]);
5128
+ }
5129
+ }
5130
+ if (paletteColors.length === 0) {
5131
+ paletteColors.push([255, 255, 255]);
5132
+ }
5133
+ const globalPalette = new Uint8Array(256 * 3);
5134
+ for (let i = 0; i < paletteColors.length; i++) {
5135
+ globalPalette[i * 3] = paletteColors[i][0];
5136
+ globalPalette[i * 3 + 1] = paletteColors[i][1];
5137
+ globalPalette[i * 3 + 2] = paletteColors[i][2];
5138
+ }
5139
+ for (let i = paletteColors.length; i < 255; i++) {
5140
+ globalPalette[i * 3] = 0;
5141
+ globalPalette[i * 3 + 1] = 0;
5142
+ globalPalette[i * 3 + 2] = 0;
5143
+ }
5144
+ globalPalette[255 * 3] = 0;
5145
+ globalPalette[255 * 3 + 1] = 0;
5146
+ globalPalette[255 * 3 + 2] = 0;
5147
+ const lookupCache = new Uint8Array(32768);
5148
+ const colorCount = paletteColors.length;
5149
+ for (let r5 = 0; r5 < 32; r5++) {
5150
+ const r = r5 << 3 | r5 >> 2;
5151
+ for (let g5 = 0; g5 < 32; g5++) {
5152
+ const g = g5 << 3 | g5 >> 2;
5153
+ for (let b5 = 0; b5 < 32; b5++) {
5154
+ const b = b5 << 3 | b5 >> 2;
5155
+ let bestIdx = 0;
5156
+ let bestDist = Infinity;
5157
+ for (let i = 0; i < colorCount; i++) {
5158
+ const pr = globalPalette[i * 3];
5159
+ const pg = globalPalette[i * 3 + 1];
5160
+ const pb = globalPalette[i * 3 + 2];
5161
+ const dist = (r - pr) ** 2 * 2 + (g - pg) ** 2 * 4 + (b - pb) ** 2 * 1;
5162
+ if (dist < bestDist) {
5163
+ bestDist = dist;
5164
+ bestIdx = i;
5165
+ if (dist === 0) break;
5166
+ }
5167
+ }
5168
+ const cacheKey = r5 << 10 | g5 << 5 | b5;
5169
+ lookupCache[cacheKey] = bestIdx;
5170
+ }
5171
+ }
5172
+ }
5173
+ return {
5174
+ palette: globalPalette,
5175
+ quantize(imageData) {
5176
+ const { width, height, data } = imageData;
5177
+ const pixelCount = width * height;
5178
+ const out = new Uint8Array(pixelCount);
5179
+ for (let i = 0; i < pixelCount; i++) {
5180
+ const idx = i * 4;
5181
+ const a = data[idx + 3];
5182
+ if (a < 16) {
5183
+ out[i] = 255;
5184
+ continue;
5185
+ }
5186
+ const r = data[idx];
5187
+ const g = data[idx + 1];
5188
+ const b = data[idx + 2];
5189
+ const cacheKey = r >> 3 << 10 | g >> 3 << 5 | b >> 3;
5190
+ out[i] = lookupCache[cacheKey];
5191
+ }
5192
+ return out;
5193
+ }
5194
+ };
5195
+ }
5196
+ var BITS = 12;
5197
+ var HSIZE = 5003;
5198
+ var MASKS = [
5199
+ 0,
5200
+ 1,
5201
+ 3,
5202
+ 7,
5203
+ 15,
5204
+ 31,
5205
+ 63,
5206
+ 127,
5207
+ 255,
5208
+ 511,
5209
+ 1023,
5210
+ 2047,
5211
+ 4095,
5212
+ 8191,
5213
+ 16383,
5214
+ 32767,
5215
+ 65535
5216
+ ];
5217
+ function lzwCompress(pixels, minCodeSize = 8) {
5218
+ const out = [];
5219
+ const accum = new Uint8Array(256);
5220
+ const htab = new Int32Array(HSIZE);
5221
+ const codetab = new Int32Array(HSIZE);
5222
+ htab.fill(-1);
5223
+ codetab.fill(0);
5224
+ const init_bits = minCodeSize + 1;
5225
+ const g_init_bits = init_bits;
5226
+ let clear_flg = false;
5227
+ let n_bits = g_init_bits;
5228
+ let maxcode = (1 << n_bits) - 1;
5229
+ const ClearCode = 1 << minCodeSize;
5230
+ const EOFCode = ClearCode + 1;
5231
+ let free_ent = ClearCode + 2;
5232
+ let a_count = 0;
5233
+ let cur_accum = 0;
5234
+ let cur_bits = 0;
5235
+ let ent = pixels[0] ?? 0;
5236
+ let hshift = 0;
5237
+ for (let fcode = HSIZE; fcode < 65536; fcode *= 2) {
5238
+ ++hshift;
5239
+ }
5240
+ hshift = 8 - hshift;
5241
+ out.push(minCodeSize);
5242
+ output(ClearCode);
5243
+ for (let idx = 1; idx < pixels.length; idx++) {
5244
+ next_block: {
5245
+ const c = pixels[idx];
5246
+ const fcode = (c << BITS) + ent;
5247
+ let i = c << hshift ^ ent;
5248
+ if (htab[i] === fcode) {
5249
+ ent = codetab[i];
5250
+ break next_block;
5251
+ }
5252
+ const disp = i === 0 ? 1 : HSIZE - i;
5253
+ while (htab[i] >= 0) {
5254
+ i -= disp;
5255
+ if (i < 0) i += HSIZE;
5256
+ if (htab[i] === fcode) {
5257
+ ent = codetab[i];
5258
+ break next_block;
5259
+ }
5260
+ }
5261
+ output(ent);
5262
+ ent = c;
5263
+ if (free_ent < 1 << BITS) {
5264
+ codetab[i] = free_ent++;
5265
+ htab[i] = fcode;
5266
+ } else {
5267
+ htab.fill(-1);
5268
+ free_ent = ClearCode + 2;
5269
+ clear_flg = true;
5270
+ output(ClearCode);
5271
+ }
5272
+ }
5273
+ }
5274
+ output(ent);
5275
+ output(EOFCode);
5276
+ out.push(0);
5277
+ return new Uint8Array(out);
5278
+ function output(code) {
5279
+ cur_accum &= MASKS[cur_bits];
5280
+ if (cur_bits > 0) cur_accum |= code << cur_bits;
5281
+ else cur_accum = code;
5282
+ cur_bits += n_bits;
5283
+ while (cur_bits >= 8) {
5284
+ accum[a_count++] = cur_accum & 255;
5285
+ if (a_count >= 254) {
5286
+ out.push(a_count);
5287
+ for (let j = 0; j < a_count; j++) out.push(accum[j]);
5288
+ a_count = 0;
5289
+ }
5290
+ cur_accum >>= 8;
5291
+ cur_bits -= 8;
5292
+ }
5293
+ if (free_ent > maxcode || clear_flg) {
5294
+ if (clear_flg) {
5295
+ n_bits = g_init_bits;
5296
+ maxcode = (1 << n_bits) - 1;
5297
+ clear_flg = false;
5298
+ } else {
5299
+ ++n_bits;
5300
+ maxcode = n_bits === BITS ? 1 << n_bits : (1 << n_bits) - 1;
5301
+ }
5302
+ }
5303
+ if (code === EOFCode) {
5304
+ while (cur_bits > 0) {
5305
+ accum[a_count++] = cur_accum & 255;
5306
+ if (a_count >= 254) {
5307
+ out.push(a_count);
5308
+ for (let j = 0; j < a_count; j++) out.push(accum[j]);
5309
+ a_count = 0;
5310
+ }
5311
+ cur_accum >>= 8;
5312
+ cur_bits -= 8;
5313
+ }
5314
+ if (a_count > 0) {
5315
+ out.push(a_count);
5316
+ for (let j = 0; j < a_count; j++) out.push(accum[j]);
5317
+ a_count = 0;
5318
+ }
5319
+ }
5320
+ }
5321
+ }
5322
+ function encodeGifSequence(frames, options = {}) {
5323
+ if (frames.length === 0) {
5324
+ throw new Error("Cannot encode GIF without frames");
5325
+ }
5326
+ const { width, height } = frames[0].imageData;
5327
+ const enableDiff = options.diff !== false;
5328
+ const quantizer = buildAdaptivePalette(frames);
5329
+ const buffer = [];
5330
+ const pushString = (str) => {
5331
+ for (let i = 0; i < str.length; i++) buffer.push(str.charCodeAt(i));
5332
+ };
5333
+ const pushU16 = (val) => {
5334
+ buffer.push(val & 255, val >> 8 & 255);
5335
+ };
5336
+ pushString(GIF_HEADER);
5337
+ pushU16(width);
5338
+ pushU16(height);
5339
+ buffer.push(247);
5340
+ buffer.push(0);
5341
+ buffer.push(0);
5342
+ for (let i = 0; i < quantizer.palette.length; i++) {
5343
+ buffer.push(quantizer.palette[i]);
5344
+ }
5345
+ if (options.loop !== false) {
5346
+ buffer.push(33, 255, 11);
5347
+ pushString("NETSCAPE2.0");
5348
+ buffer.push(3, 1, 0, 0, 0);
5349
+ }
5350
+ let prevQuantized = null;
5351
+ for (let frameIdx = 0; frameIdx < frames.length; frameIdx++) {
5352
+ const frame = frames[frameIdx];
5353
+ const currQuantized = quantizer.quantize(frame.imageData);
5354
+ const delayHundredths = Math.max(2, Math.round(frame.delayMs / 10));
5355
+ if (!enableDiff || prevQuantized === null || frameIdx === 0) {
5356
+ const compressedWithHeader = lzwCompress(currQuantized);
5357
+ buffer.push(33, 249, 4, 4);
5358
+ pushU16(delayHundredths);
5359
+ buffer.push(0, 0);
5360
+ buffer.push(44);
5361
+ pushU16(0);
5362
+ pushU16(0);
5363
+ pushU16(width);
5364
+ pushU16(height);
5365
+ buffer.push(0);
5366
+ for (let i = 0; i < compressedWithHeader.length; i++) {
5367
+ buffer.push(compressedWithHeader[i]);
5368
+ }
5369
+ prevQuantized = currQuantized;
5370
+ } else {
5371
+ let minX = width;
5372
+ let minY = height;
5373
+ let maxX = -1;
5374
+ let maxY = -1;
5375
+ for (let y = 0; y < height; y++) {
5376
+ const rowOffset = y * width;
5377
+ for (let x = 0; x < width; x++) {
5378
+ if (currQuantized[rowOffset + x] !== prevQuantized[rowOffset + x]) {
5379
+ if (x < minX) minX = x;
5380
+ if (x > maxX) maxX = x;
5381
+ if (y < minY) minY = y;
5382
+ if (y > maxY) maxY = y;
5383
+ }
5384
+ }
5385
+ }
5386
+ if (maxX < minX || maxY < minY) {
5387
+ continue;
5388
+ }
5389
+ const diffW = maxX - minX + 1;
5390
+ const diffH = maxY - minY + 1;
5391
+ const diffData = new Uint8Array(diffW * diffH);
5392
+ for (let dy = 0; dy < diffH; dy++) {
5393
+ const gy = minY + dy;
5394
+ const gRowOffset = gy * width;
5395
+ const dRowOffset = dy * diffW;
5396
+ for (let dx = 0; dx < diffW; dx++) {
5397
+ const gx = minX + dx;
5398
+ const currCol = currQuantized[gRowOffset + gx];
5399
+ const prevCol = prevQuantized[gRowOffset + gx];
5400
+ diffData[dRowOffset + dx] = currCol === prevCol ? TRANSPARENT_COLOR_INDEX : currCol;
5401
+ }
5402
+ }
5403
+ const compressedWithHeader = lzwCompress(diffData);
5404
+ buffer.push(33, 249, 4, 5);
5405
+ pushU16(delayHundredths);
5406
+ buffer.push(TRANSPARENT_COLOR_INDEX, 0);
5407
+ buffer.push(44);
5408
+ pushU16(minX);
5409
+ pushU16(minY);
5410
+ pushU16(diffW);
5411
+ pushU16(diffH);
5412
+ buffer.push(0);
5413
+ for (let i = 0; i < compressedWithHeader.length; i++) {
5414
+ buffer.push(compressedWithHeader[i]);
5415
+ }
5416
+ prevQuantized = currQuantized;
5417
+ }
5418
+ }
5419
+ buffer.push(59);
5420
+ return new Uint8Array(buffer);
5421
+ }
5422
+
5423
+ // src/export/gif-exporter.ts
5424
+ var nextFrame = () => new Promise((resolve) => {
5425
+ let settled = false;
5426
+ const finish = () => {
5427
+ if (settled) return;
5428
+ settled = true;
5429
+ resolve();
5430
+ };
5431
+ const fallback = setTimeout(finish, 80);
5432
+ requestAnimationFrame(() => requestAnimationFrame(() => {
5433
+ clearTimeout(fallback);
5434
+ finish();
5435
+ }));
5436
+ });
5437
+ var DEFAULT_GIF_PIXEL_RATIO = 2;
5438
+ var DEFAULT_GIF_FPS = 20;
5439
+ var MAX_GIF_FRAMES = 96;
5440
+ async function rasterizeFrame(container, pixelRatio, options) {
5441
+ const canvas = await rasterizeDiagramToCanvas(container, options, pixelRatio);
5442
+ const context = canvas.getContext("2d");
5443
+ if (!context) throw new Error("Could not create GIF canvas context");
5444
+ return context.getImageData(0, 0, canvas.width, canvas.height);
5445
+ }
5446
+ async function exportDiagramAsGif(container, timeline, options = {}) {
5447
+ const requestedFps = Math.min(30, Math.max(1, Math.round(options.fps ?? DEFAULT_GIF_FPS)));
5448
+ const rawDuration = timeline.duration();
5449
+ const duration = Math.max(Number.isFinite(rawDuration) ? rawDuration : 1, 0.1);
5450
+ const fps = Math.min(requestedFps, Math.max(6, Math.round(MAX_GIF_FRAMES / duration)));
5451
+ const frameCount = Math.max(1, Math.ceil(duration * fps));
5452
+ const delayMs = Math.max(20, Math.round(1e3 / fps));
5453
+ const pixelRatio = options.pixelRatio ?? DEFAULT_GIF_PIXEL_RATIO;
5454
+ const holdEndMs = Math.max(delayMs, options.holdEndMs ?? 1400);
5455
+ const priorTime = timeline.currentTime();
5456
+ const wasPlaying = timeline.isPlaying();
5457
+ timeline.pause();
5458
+ try {
5459
+ const frames = [];
5460
+ const totalFrames = frameCount + 1;
5461
+ for (let frame = 0; frame < frameCount; frame++) {
5462
+ timeline.seek(Math.min(duration, frame / fps));
5463
+ await nextFrame();
5464
+ const imageData = await rasterizeFrame(container, pixelRatio, options);
5465
+ frames.push({
5466
+ imageData,
5467
+ delayMs
5468
+ });
5469
+ options.onProgress?.(frames.length / totalFrames, frames.length, totalFrames);
5470
+ }
5471
+ timeline.seek(duration);
5472
+ await nextFrame();
5473
+ const finalImageData = await rasterizeFrame(container, pixelRatio, options);
5474
+ frames.push({
5475
+ imageData: finalImageData,
5476
+ delayMs: holdEndMs
5477
+ });
5478
+ options.onProgress?.(1, totalFrames, totalFrames);
5479
+ const encoded = encodeGifSequence(frames, {
5480
+ dither: options.dither ?? false,
5481
+ loop: options.loop ?? true,
5482
+ diff: options.diff ?? true
5483
+ });
5484
+ const bytes = new Uint8Array(encoded.byteLength);
5485
+ bytes.set(encoded);
5486
+ return new Blob([bytes], { type: "image/gif" });
5487
+ } finally {
5488
+ timeline.seek(priorTime);
5489
+ if (wasPlaying) timeline.play();
5490
+ }
5491
+ }
5492
+
5493
+ // src/diagram.ts
5494
+ var NORMAL_PLAYBACK_RATE = 4 / 5;
5495
+ var MIN_VIEWPORT_ZOOM = 0.5;
5496
+ var MAX_VIEWPORT_ZOOM = 3;
5497
+ var VIEWPORT_ZOOM_STEP = 15e-4;
5498
+ var DRAG_CLICK_THRESHOLD_PX = 4;
5499
+ var BEAT_NAV_EPSILON_S = 0.05;
5500
+ var MARKDY_PLAYGROUND_URL = "https://markdy.com/playground/";
5501
+ function encodeCodeForPlaygroundHash(code) {
5502
+ return encodeURIComponent(btoa(encodeURIComponent(code)));
5503
+ }
5504
+ function createBeatCaptionLayer(doc, beats) {
5505
+ const layer = doc.createElement("div");
5506
+ layer.className = "markdy-beat-caption-layer";
5507
+ for (const beat of beats) {
5508
+ if (!beat.label) continue;
5509
+ const caption = doc.createElement("div");
5510
+ caption.className = "markdy-beat-caption";
5511
+ caption.textContent = beat.label;
5512
+ caption.dataset.beat = beat.name;
5513
+ layer.appendChild(caption);
5514
+ }
5515
+ return layer;
5516
+ }
5517
+ function buildBeatCaptionAnimations(beats, layer) {
5518
+ const anims = [];
5519
+ const captions = Array.from(layer.querySelectorAll(".markdy-beat-caption"));
5520
+ for (const beat of beats) {
5521
+ if (!beat.label) continue;
5522
+ const caption = captions.find((item) => item.dataset.beat === beat.name);
5523
+ if (!caption) continue;
5524
+ const startMs = beat.start * 1e3;
5525
+ const durMs = Math.max((beat.end - beat.start) * 1e3, 650);
5526
+ anims.push(
5527
+ caption.animate(
5528
+ [
5529
+ { opacity: 0, transform: "translateY(8px)" },
5530
+ { opacity: 1, transform: "translateY(0)", offset: 0.16 },
5531
+ { opacity: 1, transform: "translateY(0)", offset: 0.82 },
5532
+ { opacity: 0, transform: "translateY(-4px)" }
5533
+ ],
5534
+ { duration: durMs, delay: startMs, fill: "forwards", easing: "ease-out" }
5535
+ )
5536
+ );
5537
+ }
5538
+ return anims;
5539
+ }
5540
+ function isDarkBgColor(colorStr) {
5541
+ if (!colorStr || colorStr === "transparent" || colorStr === "rgba(0, 0, 0, 0)") return null;
5542
+ const match = colorStr.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/i);
5543
+ if (!match) return null;
5544
+ const r = parseInt(match[1], 10);
5545
+ const g = parseInt(match[2], 10);
5546
+ const b = parseInt(match[3], 10);
5547
+ const luma = 0.2126 * r + 0.7152 * g + 0.0722 * b;
5548
+ return luma < 128;
5549
+ }
5550
+ function checkElementTheme(el) {
5551
+ const themeAttr = el.getAttribute("data-theme") || el.dataset.theme || el.getAttribute("data-mode") || el.getAttribute("data-bs-theme") || el.getAttribute("data-color-mode") || el.getAttribute("data-color-scheme");
5552
+ if (themeAttr) {
5553
+ const lower = themeAttr.toLowerCase();
5554
+ if (lower.includes("dark")) return "nebula";
5555
+ if (lower.includes("light")) return "paper";
5556
+ }
5557
+ const cls = el.className;
5558
+ if (typeof cls === "string" && cls.length > 0) {
5559
+ if (/\b(dark|dark-mode|dark-theme|theme-dark|vscode-dark)\b/i.test(cls)) return "nebula";
5560
+ if (/\b(light|light-mode|light-theme|theme-light|vscode-light)\b/i.test(cls)) return "paper";
5561
+ }
5562
+ return null;
5563
+ }
5564
+ function detectHostTheme(container) {
5565
+ if (typeof document === "undefined") return "nebula";
5566
+ let current = container ?? null;
5567
+ while (current) {
5568
+ const check = checkElementTheme(current);
5569
+ if (check) return check;
5570
+ current = current.parentElement;
5571
+ }
5572
+ const docRoot = document.documentElement;
5573
+ const rootCheck = checkElementTheme(docRoot);
5574
+ if (rootCheck) return rootCheck;
5575
+ if (document.body) {
5576
+ const bodyCheck = checkElementTheme(document.body);
5577
+ if (bodyCheck) return bodyCheck;
5578
+ }
5579
+ if (typeof window !== "undefined" && typeof window.getComputedStyle === "function") {
5580
+ let bgEl = container ?? document.body ?? null;
5581
+ while (bgEl) {
5582
+ try {
5583
+ const bg = window.getComputedStyle(bgEl).backgroundColor;
5584
+ const isDark = isDarkBgColor(bg);
5585
+ if (isDark === true) return "nebula";
5586
+ if (isDark === false) return "paper";
5587
+ } catch {
5588
+ }
5589
+ bgEl = bgEl.parentElement;
5590
+ }
5591
+ }
5592
+ if (typeof window !== "undefined" && window.matchMedia?.("(prefers-color-scheme: dark)").matches) {
5593
+ return "nebula";
5594
+ }
5595
+ return "paper";
5596
+ }
5597
+ function createDiagram(opts) {
5598
+ const {
3784
5599
  container,
3785
5600
  code,
3786
5601
  assets,
@@ -3800,10 +5615,18 @@ function createDiagram(opts) {
3800
5615
  onPlayStateChange,
3801
5616
  onEnded
3802
5617
  } = opts;
3803
- const { ast, plan } = parseAndCompile(code);
5618
+ const { ast, plan } = parseAndCompile2(code);
3804
5619
  for (const w of ast.diagnostics) {
3805
5620
  if (w.severity === "warning") onWarning(w);
3806
5621
  }
5622
+ const hasExplicitTheme = Boolean(ast.meta.explicitTheme === true && ast.meta.theme !== "auto");
5623
+ if (!hasExplicitTheme) {
5624
+ const detected = detectHostTheme(container);
5625
+ plan.theme = resolveTheme2(detected);
5626
+ }
5627
+ let hostThemeObserver = null;
5628
+ let mediaQueryListener = null;
5629
+ let colorSchemeQuery = null;
3807
5630
  const hostProgress = sceneBoundaryProgress === false || sceneBoundaryProgress === void 0 && progressBar === false ? "none" : void 0;
3808
5631
  const hostProgressColor = progressColor ?? progressBarColor ?? (typeof sceneBoundaryProgress === "string" && sceneBoundaryProgress !== "true" && sceneBoundaryProgress !== "false" ? sceneBoundaryProgress : typeof progressBar === "string" && progressBar !== "true" && progressBar !== "false" ? progressBar : void 0);
3809
5632
  const player = resolvePlayer(plan.meta.player, {
@@ -3838,6 +5661,7 @@ function createDiagram(opts) {
3838
5661
  resetView: resetViewButton,
3839
5662
  fullscreen: fullscreenButton,
3840
5663
  svg: svgButton,
5664
+ gif: gifButton,
3841
5665
  share: shareButton,
3842
5666
  code: codeButton,
3843
5667
  theme: themeButton
@@ -3852,6 +5676,8 @@ function createDiagram(opts) {
3852
5676
  const totalDurationMs = plan.duration * 1e3;
3853
5677
  const durationSeconds = plan.duration;
3854
5678
  container.classList.add("markdy-diagram-root");
5679
+ container.__markdyCode = code;
5680
+ container.__markdyPlan = plan;
3855
5681
  applyThemeVariables(container, plan.theme);
3856
5682
  Object.assign(container.style, {
3857
5683
  position: "relative",
@@ -4222,6 +6048,7 @@ function createDiagram(opts) {
4222
6048
  resetView: '<svg class="markdy-icon" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="3"/></svg>',
4223
6049
  fullscreen: '<svg class="markdy-icon" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"/></svg>',
4224
6050
  svg: '<svg class="markdy-icon" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>',
6051
+ gif: '<svg class="markdy-icon" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="20" rx="3"/><circle cx="7" cy="7" r="1.5" fill="currentColor"/><circle cx="17" cy="7" r="1.5" fill="currentColor"/><circle cx="7" cy="17" r="1.5" fill="currentColor"/><circle cx="17" cy="17" r="1.5" fill="currentColor"/><path d="M10 10l5 2-5 2z" fill="currentColor"/></svg>',
4225
6052
  share: '<svg class="markdy-icon" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>',
4226
6053
  code: '<svg class="markdy-icon" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>',
4227
6054
  theme: '<svg class="markdy-icon" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="M12 3v18"/><path d="M12 3a9 9 0 0 1 0 18z" fill="currentColor"/></svg>',
@@ -4424,7 +6251,7 @@ function createDiagram(opts) {
4424
6251
  diagram.seek(target);
4425
6252
  },
4426
6253
  setTheme(theme) {
4427
- const newTheme = typeof theme === "string" ? resolveTheme(theme) : theme;
6254
+ const newTheme = typeof theme === "string" ? resolveTheme2(theme) : theme;
4428
6255
  plan.theme = newTheme;
4429
6256
  applyThemeVariables(container, newTheme);
4430
6257
  applyThemeToScene(scene, newTheme);
@@ -4523,8 +6350,42 @@ function createDiagram(opts) {
4523
6350
  }
4524
6351
  if (totalDurationMs > 0) updateProgressBar(sceneMs / totalDurationMs);
4525
6352
  },
6353
+ exportSvg(options) {
6354
+ const resumeAt = sceneMs;
6355
+ const wasPlaying = isPlaying;
6356
+ try {
6357
+ diagram.pause();
6358
+ diagram.seek(durationSeconds);
6359
+ return exportDiagramAsVectorSvg(container, options);
6360
+ } finally {
6361
+ diagram.seek(resumeAt / 1e3);
6362
+ if (wasPlaying) diagram.play();
6363
+ }
6364
+ },
6365
+ async exportPng(options) {
6366
+ const resumeAt = sceneMs;
6367
+ const wasPlaying = isPlaying;
6368
+ try {
6369
+ diagram.pause();
6370
+ diagram.seek(durationSeconds);
6371
+ return await exportDiagramAsPng(container, options);
6372
+ } finally {
6373
+ diagram.seek(resumeAt / 1e3);
6374
+ if (wasPlaying) diagram.play();
6375
+ }
6376
+ },
6377
+ async exportGif(options) {
6378
+ return await exportDiagramAsGif(container, diagram, options);
6379
+ },
4526
6380
  destroy() {
4527
6381
  diagram.pause();
6382
+ hostThemeObserver?.disconnect();
6383
+ hostThemeObserver = null;
6384
+ if (colorSchemeQuery && mediaQueryListener) {
6385
+ colorSchemeQuery.removeEventListener?.("change", mediaQueryListener);
6386
+ mediaQueryListener = null;
6387
+ colorSchemeQuery = null;
6388
+ }
4528
6389
  if (keyboardShortcuts && typeof window !== "undefined") {
4529
6390
  window.removeEventListener("keydown", handleKeyDown);
4530
6391
  }
@@ -4541,6 +6402,43 @@ function createDiagram(opts) {
4541
6402
  if (viewport.parentNode === container) container.removeChild(viewport);
4542
6403
  }
4543
6404
  };
6405
+ if (!hasExplicitTheme && typeof document !== "undefined") {
6406
+ const syncWithHost = () => {
6407
+ const nextTheme = detectHostTheme(container);
6408
+ diagram.setTheme(nextTheme);
6409
+ };
6410
+ const attributeFilter = [
6411
+ "data-theme",
6412
+ "data-mode",
6413
+ "data-bs-theme",
6414
+ "data-color-mode",
6415
+ "data-color-scheme",
6416
+ "class",
6417
+ "style"
6418
+ ];
6419
+ hostThemeObserver = new MutationObserver(syncWithHost);
6420
+ hostThemeObserver.observe(document.documentElement, {
6421
+ attributes: true,
6422
+ attributeFilter
6423
+ });
6424
+ if (document.body) {
6425
+ hostThemeObserver.observe(document.body, {
6426
+ attributes: true,
6427
+ attributeFilter
6428
+ });
6429
+ }
6430
+ if (container && container.parentElement && container !== document.body) {
6431
+ hostThemeObserver.observe(container.parentElement, {
6432
+ attributes: true,
6433
+ attributeFilter
6434
+ });
6435
+ }
6436
+ if (typeof window !== "undefined" && window.matchMedia) {
6437
+ colorSchemeQuery = window.matchMedia("(prefers-color-scheme: dark)");
6438
+ mediaQueryListener = syncWithHost;
6439
+ colorSchemeQuery.addEventListener?.("change", mediaQueryListener);
6440
+ }
6441
+ }
4544
6442
  function togglePlayback() {
4545
6443
  if (isPlaying) diagram.pause();
4546
6444
  else {
@@ -4664,6 +6562,39 @@ function createDiagram(opts) {
4664
6562
  });
4665
6563
  toolbar.appendChild(button);
4666
6564
  }
6565
+ function mountGifControl(toolbar) {
6566
+ if (!gifButton) return;
6567
+ const button = makeControlButton("GIF", "Export diagram as animated GIF", ICONS2.gif);
6568
+ button.className = "markdy-control-gif";
6569
+ let exporting = false;
6570
+ button.addEventListener("click", async () => {
6571
+ if (exporting) return;
6572
+ exporting = true;
6573
+ flashControlLabel(button, "Recording...");
6574
+ button.setAttribute("disabled", "true");
6575
+ try {
6576
+ const blob = await diagram.exportGif();
6577
+ const name = (plan.title || "markdy-diagram").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
6578
+ const url = URL.createObjectURL(blob);
6579
+ const link = document.createElement("a");
6580
+ link.href = url;
6581
+ link.download = `${name || "markdy-diagram"}.gif`;
6582
+ link.style.display = "none";
6583
+ document.body.appendChild(link);
6584
+ link.click();
6585
+ document.body.removeChild(link);
6586
+ URL.revokeObjectURL(url);
6587
+ flashControlLabel(button, "Saved");
6588
+ } catch (error) {
6589
+ onWarning({ severity: "warning", message: `GIF export failed: ${String(error)}`, line: 0 });
6590
+ flashControlLabel(button, "Failed");
6591
+ } finally {
6592
+ exporting = false;
6593
+ button.removeAttribute("disabled");
6594
+ }
6595
+ });
6596
+ toolbar.appendChild(button);
6597
+ }
4667
6598
  function mountShareControl(toolbar) {
4668
6599
  if (!shareButton) return;
4669
6600
  const button = makeControlButton("Share", "Copy a share link for this diagram", ICONS2.share);
@@ -4687,7 +6618,7 @@ function createDiagram(opts) {
4687
6618
  button.className = "markdy-control-theme";
4688
6619
  button.addEventListener("click", () => {
4689
6620
  const darkThemes = ["midnight", "blueprint", "graphite", "nebula", "terminal"];
4690
- const lightThemes = ["paper", "editorial", "sketchy"];
6621
+ const lightThemes = ["paper", "editorial", "sketchy", "ink", "doodle"];
4691
6622
  const currentName = plan.theme.name || "paper";
4692
6623
  const isDark = darkThemes.includes(currentName);
4693
6624
  const targetThemes = isDark ? lightThemes : darkThemes;
@@ -5039,513 +6970,59 @@ function createDiagram(opts) {
5039
6970
  mountSpeedControls(speedGroup);
5040
6971
  toolsGroup.appendChild(speedGroup);
5041
6972
  }
5042
- if (fitViewButton || resetViewButton || fullscreenButton) {
5043
- if (toolsGroup.children.length > 0) {
5044
- const divider = document.createElement("div");
5045
- divider.className = "markdy-control-divider";
5046
- toolsGroup.appendChild(divider);
5047
- }
5048
- mountFitControl(toolsGroup);
5049
- mountResetViewControl(toolsGroup);
5050
- mountFullscreenControl(toolsGroup);
5051
- }
5052
- if (svgButton || shareButton || codeButton || themeButton) {
5053
- if (toolsGroup.children.length > 0) {
5054
- const divider = document.createElement("div");
5055
- divider.className = "markdy-control-divider";
5056
- toolsGroup.appendChild(divider);
5057
- }
5058
- mountThemeControl(toolsGroup);
5059
- mountSvgControl(toolsGroup);
5060
- mountShareControl(toolsGroup);
5061
- mountCodeControl(toolsGroup);
5062
- }
5063
- if (toolsGroup.children.length > 0) toolbar.appendChild(toolsGroup);
5064
- ensureFooter().insertBefore(toolbar, badge);
5065
- syncControls();
5066
- }
5067
- viewport.style.cursor = interactiveViewport ? "grab" : "pointer";
5068
- if (interactiveViewport) {
5069
- viewport.style.touchAction = "none";
5070
- if (allowZoom) viewport.addEventListener("wheel", handleViewportWheel, { passive: false });
5071
- if (allowPan) {
5072
- viewport.addEventListener("pointerdown", handleViewportPointerDown);
5073
- viewport.addEventListener("pointermove", handleViewportPointerMove);
5074
- viewport.addEventListener("pointerup", handleViewportPointerEnd);
5075
- viewport.addEventListener("pointercancel", handleViewportPointerEnd);
5076
- }
5077
- if (doubleClickToReset) viewport.addEventListener("dblclick", handleViewportDoubleClick);
5078
- }
5079
- if (showControls) mountControls();
5080
- if (clickToPlay) {
5081
- viewport.addEventListener("click", () => {
5082
- if (suppressNextClick) {
5083
- suppressNextClick = false;
5084
- return;
5085
- }
5086
- togglePlayback();
5087
- });
5088
- }
5089
- if (keyboardShortcuts && typeof window !== "undefined") {
5090
- window.addEventListener("keydown", handleKeyDown);
5091
- }
5092
- if (autoplay) diagram.play();
5093
- return diagram;
5094
- }
5095
-
5096
- // src/export/gif-encoder.ts
5097
- var GIF_HEADER = "GIF89a";
5098
- var PALETTE_RGB332 = (() => {
5099
- const palette = new Uint8Array(256 * 3);
5100
- for (let i = 0; i < 256; i++) {
5101
- const r = Math.round((i >> 5 & 7) * 255 / 7);
5102
- const g = Math.round((i >> 2 & 7) * 255 / 7);
5103
- const b = Math.round((i & 3) * 255 / 3);
5104
- palette[i * 3] = r;
5105
- palette[i * 3 + 1] = g;
5106
- palette[i * 3 + 2] = b;
5107
- }
5108
- return palette;
5109
- })();
5110
- function clamp2(value, min = 0, max = 255) {
5111
- return value < min ? min : value > max ? max : value;
5112
- }
5113
- function nearestColorIndex(r, g, b) {
5114
- return (clamp2(r) & 224 | (clamp2(g) & 224) >> 3 | (clamp2(b) & 192) >> 6) & 255;
5115
- }
5116
- function quantizeFrame(imageData, dither) {
5117
- const { width, height, data } = imageData;
5118
- const pixelCount = width * height;
5119
- const out = new Uint8Array(pixelCount);
5120
- if (!dither) {
5121
- for (let i = 0; i < pixelCount; i++) {
5122
- const idx = i * 4;
5123
- out[i] = (data[idx] & 224 | (data[idx + 1] & 224) >> 3 | (data[idx + 2] & 192) >> 6) & 255;
5124
- }
5125
- return out;
5126
- }
5127
- const errR = new Float32Array(pixelCount);
5128
- const errG = new Float32Array(pixelCount);
5129
- const errB = new Float32Array(pixelCount);
5130
- for (let i = 0; i < pixelCount; i++) {
5131
- const idx = i * 4;
5132
- errR[i] = data[idx];
5133
- errG[i] = data[idx + 1];
5134
- errB[i] = data[idx + 2];
5135
- }
5136
- for (let y = 0; y < height; y++) {
5137
- for (let x = 0; x < width; x++) {
5138
- const idx = y * width + x;
5139
- const r = clamp2(Math.round(errR[idx]));
5140
- const g = clamp2(Math.round(errG[idx]));
5141
- const b = clamp2(Math.round(errB[idx]));
5142
- const colorIdx = nearestColorIndex(r, g, b);
5143
- out[idx] = colorIdx;
5144
- const pr = PALETTE_RGB332[colorIdx * 3];
5145
- const pg = PALETTE_RGB332[colorIdx * 3 + 1];
5146
- const pb = PALETTE_RGB332[colorIdx * 3 + 2];
5147
- const dr = errR[idx] - pr;
5148
- const dg = errG[idx] - pg;
5149
- const db = errB[idx] - pb;
5150
- if (x + 1 < width) {
5151
- errR[idx + 1] += dr * 7 / 16;
5152
- errG[idx + 1] += dg * 7 / 16;
5153
- errB[idx + 1] += db * 7 / 16;
5154
- }
5155
- if (y + 1 < height) {
5156
- if (x > 0) {
5157
- errR[idx + width - 1] += dr * 3 / 16;
5158
- errG[idx + width - 1] += dg * 3 / 16;
5159
- errB[idx + width - 1] += db * 3 / 16;
5160
- }
5161
- errR[idx + width] += dr * 5 / 16;
5162
- errG[idx + width] += dg * 5 / 16;
5163
- errB[idx + width] += db * 5 / 16;
5164
- if (x + 1 < width) {
5165
- errR[idx + width + 1] += dr * 1 / 16;
5166
- errG[idx + width + 1] += dg * 1 / 16;
5167
- errB[idx + width + 1] += db * 1 / 16;
5168
- }
5169
- }
5170
- }
5171
- }
5172
- return out;
5173
- }
5174
- function lzwCompress(pixels, minCodeSize = 8) {
5175
- const clearCode = 1 << minCodeSize;
5176
- const endCode = clearCode + 1;
5177
- let codeSize = minCodeSize + 1;
5178
- let nextCode = endCode + 1;
5179
- let dict = /* @__PURE__ */ new Map();
5180
- for (let i = 0; i < clearCode; i++) {
5181
- dict.set(String(i), i);
5182
- }
5183
- const codes = [clearCode];
5184
- let prefix = String(pixels[0] ?? 0);
5185
- for (let i = 1; i < pixels.length; i++) {
5186
- const suffix = String(pixels[i]);
5187
- const combo = `${prefix},${suffix}`;
5188
- if (dict.has(combo)) {
5189
- prefix = combo;
5190
- continue;
5191
- }
5192
- codes.push(dict.get(prefix));
5193
- dict.set(combo, nextCode++);
5194
- prefix = suffix;
5195
- if (nextCode === 1 << codeSize && codeSize < 12) {
5196
- codeSize++;
5197
- }
5198
- if (nextCode >= 4096) {
5199
- codes.push(clearCode);
5200
- dict = /* @__PURE__ */ new Map();
5201
- for (let j = 0; j < clearCode; j++) dict.set(String(j), j);
5202
- codeSize = minCodeSize + 1;
5203
- nextCode = endCode + 1;
5204
- }
5205
- }
5206
- codes.push(dict.get(prefix));
5207
- codes.push(endCode);
5208
- const bytes = [];
5209
- let bitBuffer = 0;
5210
- let bitCount = 0;
5211
- codeSize = minCodeSize + 1;
5212
- nextCode = endCode + 1;
5213
- for (const code of codes) {
5214
- bitBuffer |= code << bitCount;
5215
- bitCount += codeSize;
5216
- while (bitCount >= 8) {
5217
- bytes.push(bitBuffer & 255);
5218
- bitBuffer >>= 8;
5219
- bitCount -= 8;
5220
- }
5221
- if (code === clearCode) {
5222
- codeSize = minCodeSize + 1;
5223
- nextCode = endCode + 1;
5224
- } else if (code !== endCode) {
5225
- nextCode++;
5226
- if (nextCode === 1 << codeSize && codeSize < 12) {
5227
- codeSize++;
5228
- }
5229
- }
5230
- }
5231
- if (bitCount > 0) {
5232
- bytes.push(bitBuffer & 255);
5233
- }
5234
- return new Uint8Array(bytes);
5235
- }
5236
- function encodeGifSequence(frames, options = {}) {
5237
- if (frames.length === 0) {
5238
- throw new Error("Cannot encode GIF without frames");
5239
- }
5240
- const { width, height } = frames[0].imageData;
5241
- const dither = options.dither ?? true;
5242
- const buffer = [];
5243
- const pushString = (str) => {
5244
- for (let i = 0; i < str.length; i++) buffer.push(str.charCodeAt(i));
5245
- };
5246
- const pushU16 = (val) => {
5247
- buffer.push(val & 255, val >> 8 & 255);
5248
- };
5249
- pushString(GIF_HEADER);
5250
- pushU16(width);
5251
- pushU16(height);
5252
- buffer.push(247);
5253
- buffer.push(0);
5254
- buffer.push(0);
5255
- for (let i = 0; i < PALETTE_RGB332.length; i++) {
5256
- buffer.push(PALETTE_RGB332[i]);
5257
- }
5258
- if (options.loop !== false) {
5259
- buffer.push(33, 255, 11);
5260
- pushString("NETSCAPE2.0");
5261
- buffer.push(3, 1, 0, 0, 0);
5262
- }
5263
- for (const frame of frames) {
5264
- const quantized = quantizeFrame(frame.imageData, dither);
5265
- const compressed = lzwCompress(quantized);
5266
- const delayHundredths = Math.max(2, Math.round(frame.delayMs / 10));
5267
- buffer.push(33, 249, 4, 4);
5268
- pushU16(delayHundredths);
5269
- buffer.push(0, 0);
5270
- buffer.push(44);
5271
- pushU16(0);
5272
- pushU16(0);
5273
- pushU16(width);
5274
- pushU16(height);
5275
- buffer.push(0);
5276
- buffer.push(8);
5277
- for (let offset = 0; offset < compressed.length; offset += 255) {
5278
- const chunk = compressed.slice(offset, offset + 255);
5279
- buffer.push(chunk.length, ...chunk);
5280
- }
5281
- buffer.push(0);
5282
- }
5283
- buffer.push(59);
5284
- return new Uint8Array(buffer);
5285
- }
5286
-
5287
- // src/export/inline-resources.ts
5288
- var TRANSPARENT_PIXEL_DATA_URI = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
5289
- var RESOURCE_FETCH_TIMEOUT_MS = 3e3;
5290
- var dataUriCache = /* @__PURE__ */ new Map();
5291
- function shouldInlineUrl(url) {
5292
- const trimmed = url.trim();
5293
- return !!trimmed && !trimmed.startsWith("data:") && !trimmed.startsWith("blob:") && !trimmed.startsWith("#");
5294
- }
5295
- async function toDataUri(url) {
5296
- if (dataUriCache.has(url)) return dataUriCache.get(url);
5297
- const request = (async () => {
5298
- const controller = new AbortController();
5299
- const timeout = setTimeout(() => controller.abort(), RESOURCE_FETCH_TIMEOUT_MS);
5300
- try {
5301
- const resp = await fetch(url, { mode: "cors", credentials: "same-origin", signal: controller.signal });
5302
- if (!resp.ok) return null;
5303
- const arrayBuffer = await resp.arrayBuffer();
5304
- const mimeType = resp.headers.get("Content-Type") || "application/octet-stream";
5305
- const base64 = btoa(
5306
- new Uint8Array(arrayBuffer).reduce((data, byte) => data + String.fromCharCode(byte), "")
5307
- );
5308
- return `data:${mimeType};base64,${base64}`;
5309
- } catch {
5310
- return null;
5311
- } finally {
5312
- clearTimeout(timeout);
5313
- }
5314
- })();
5315
- dataUriCache.set(url, request);
5316
- return request;
5317
- }
5318
- async function inlineCssUrls(cssValue) {
5319
- const urlPattern = /url\(["']?([^"')]+)["']?\)/g;
5320
- const matches = [];
5321
- let m;
5322
- while ((m = urlPattern.exec(cssValue)) !== null) {
5323
- const src = m[1];
5324
- if (shouldInlineUrl(src)) {
5325
- matches.push({ full: m[0], src });
5326
- }
5327
- }
5328
- let result = cssValue;
5329
- await Promise.all(
5330
- matches.map(async ({ full, src }) => {
5331
- try {
5332
- const absoluteSrc = new URL(src, document.baseURI).href;
5333
- const dataUri = await toDataUri(absoluteSrc);
5334
- result = result.split(full).join(dataUri ? `url("${dataUri}")` : "none");
5335
- } catch {
5336
- result = result.split(full).join("none");
6973
+ if (fitViewButton || resetViewButton || fullscreenButton) {
6974
+ if (toolsGroup.children.length > 0) {
6975
+ const divider = document.createElement("div");
6976
+ divider.className = "markdy-control-divider";
6977
+ toolsGroup.appendChild(divider);
5337
6978
  }
5338
- })
5339
- );
5340
- return result;
5341
- }
5342
- async function inlineExternalResources(root) {
5343
- const tasks = [];
5344
- root.querySelectorAll("img").forEach((img) => {
5345
- const src = img.getAttribute("src");
5346
- if (src && shouldInlineUrl(src)) {
5347
- tasks.push(
5348
- Promise.resolve().then(() => toDataUri(new URL(src, document.baseURI).href)).then((dataUri) => {
5349
- img.setAttribute("src", dataUri || TRANSPARENT_PIXEL_DATA_URI);
5350
- })
5351
- );
5352
- }
5353
- });
5354
- const allEls = [root, ...Array.from(root.querySelectorAll("*"))];
5355
- allEls.forEach((el) => {
5356
- const style = el.getAttribute("style");
5357
- if (style && style.includes("url(")) {
5358
- tasks.push(
5359
- inlineCssUrls(style).then((inlined) => {
5360
- if (inlined !== style) el.setAttribute("style", inlined);
5361
- })
5362
- );
6979
+ mountFitControl(toolsGroup);
6980
+ mountResetViewControl(toolsGroup);
6981
+ mountFullscreenControl(toolsGroup);
5363
6982
  }
5364
- });
5365
- await Promise.all(tasks);
5366
- }
5367
- async function inlineSerializedSvgResources(svgXml) {
5368
- const doc = new DOMParser().parseFromString(svgXml, "image/svg+xml");
5369
- if (doc.querySelector("parsererror")) return svgXml;
5370
- await inlineExternalResources(doc.documentElement);
5371
- const serializer = new XMLSerializer();
5372
- const serializedSvg = serializer.serializeToString(doc.documentElement);
5373
- return `<?xml version="1.0" encoding="UTF-8" standalone="no"?>
5374
- ${serializedSvg}`;
5375
- }
5376
-
5377
- // src/export/png-exporter.ts
5378
- function cssColorComponentToByte(value) {
5379
- const trimmed = value.trim();
5380
- const numeric = trimmed.endsWith("%") ? Number.parseFloat(trimmed) / 100 : Number.parseFloat(trimmed);
5381
- if (!Number.isFinite(numeric)) return 0;
5382
- return Math.round(Math.min(1, Math.max(0, numeric)) * 255);
5383
- }
5384
- function cssAlphaToNumber(value) {
5385
- if (!value) return 1;
5386
- const trimmed = value.trim();
5387
- const numeric = trimmed.endsWith("%") ? Number.parseFloat(trimmed) / 100 : Number.parseFloat(trimmed);
5388
- if (!Number.isFinite(numeric)) return 1;
5389
- return Math.min(1, Math.max(0, numeric));
5390
- }
5391
- function normalizeCssColorFunctions(cssValue) {
5392
- return cssValue.replace(/color\(\s*[-a-z0-9]+\s+([^)]*)\)/gi, (_match, rawComponents) => {
5393
- const [rawChannels, rawAlpha] = String(rawComponents).split("/");
5394
- const channels = rawChannels.trim().split(/\s+/);
5395
- if (channels.length < 3) return "rgba(0, 0, 0, 0)";
5396
- const red = cssColorComponentToByte(channels[0]);
5397
- const green = cssColorComponentToByte(channels[1]);
5398
- const blue = cssColorComponentToByte(channels[2]);
5399
- const alpha = cssAlphaToNumber(rawAlpha);
5400
- return alpha >= 1 ? `rgb(${red}, ${green}, ${blue})` : `rgba(${red}, ${green}, ${blue}, ${alpha})`;
5401
- });
5402
- }
5403
- function sanitizeHtml2CanvasStyles(root) {
5404
- [root, ...Array.from(root.querySelectorAll("*"))].forEach((element) => {
5405
- const style = element.getAttribute("style");
5406
- if (style?.includes("color(")) {
5407
- element.setAttribute("style", normalizeCssColorFunctions(style));
6983
+ if (svgButton || gifButton || shareButton || codeButton || themeButton) {
6984
+ if (toolsGroup.children.length > 0) {
6985
+ const divider = document.createElement("div");
6986
+ divider.className = "markdy-control-divider";
6987
+ toolsGroup.appendChild(divider);
6988
+ }
6989
+ mountThemeControl(toolsGroup);
6990
+ mountSvgControl(toolsGroup);
6991
+ mountGifControl(toolsGroup);
6992
+ mountShareControl(toolsGroup);
6993
+ mountCodeControl(toolsGroup);
5408
6994
  }
5409
- });
5410
- }
5411
- async function exportDiagramAsPng(containerEl, options = {}) {
5412
- const canvas = await rasterizeDiagramToCanvas(containerEl, options, options.pixelRatio || 2);
5413
- return new Promise((resolve, reject) => {
5414
- canvas.toBlob((b) => {
5415
- if (b) resolve(b);
5416
- else reject(new Error("Canvas toBlob failed for PNG export"));
5417
- }, "image/png");
5418
- });
5419
- }
5420
- async function rasterizeDiagramToCanvas(containerEl, options = {}, pixelRatio = 1) {
5421
- const sceneEl = getDiagramSceneElement(containerEl);
5422
- if (sceneEl.tagName?.toLowerCase() !== "svg") {
5423
- const { clonedScene, scaledWidth, scaledHeight } = prepareHtmlSceneForExport(sceneEl, options);
5424
- await inlineExternalResources(clonedScene);
5425
- sanitizeHtml2CanvasStyles(clonedScene);
5426
- const host = document.createElement("div");
5427
- Object.assign(host.style, {
5428
- position: "fixed",
5429
- left: "-100000px",
5430
- top: "0",
5431
- width: `${scaledWidth}px`,
5432
- height: `${scaledHeight}px`,
5433
- overflow: "hidden",
5434
- pointerEvents: "none",
5435
- zIndex: "-1"
5436
- });
5437
- host.setAttribute("aria-hidden", "true");
5438
- host.appendChild(clonedScene);
5439
- document.body.appendChild(host);
5440
- try {
5441
- await document.fonts?.ready;
5442
- const html2canvasModule = await import("html2canvas");
5443
- const html2canvas = html2canvasModule.default ?? html2canvasModule;
5444
- return await html2canvas(clonedScene, {
5445
- allowTaint: false,
5446
- backgroundColor: options.transparentBackground ? null : void 0,
5447
- height: scaledHeight,
5448
- imageTimeout: 3e3,
5449
- logging: false,
5450
- onclone: (clonedDocument, clonedElement) => {
5451
- clonedDocument.querySelectorAll("style, link[rel='stylesheet']").forEach((styleNode) => styleNode.remove());
5452
- sanitizeHtml2CanvasStyles(clonedElement);
5453
- },
5454
- scale: pixelRatio,
5455
- useCORS: true,
5456
- width: scaledWidth
5457
- });
5458
- } finally {
5459
- host.remove();
6995
+ if (toolsGroup.children.length > 0) toolbar.appendChild(toolsGroup);
6996
+ ensureFooter().insertBefore(toolbar, badge);
6997
+ syncControls();
6998
+ }
6999
+ viewport.style.cursor = interactiveViewport ? "grab" : "pointer";
7000
+ if (interactiveViewport) {
7001
+ viewport.style.touchAction = "none";
7002
+ if (allowZoom) viewport.addEventListener("wheel", handleViewportWheel, { passive: false });
7003
+ if (allowPan) {
7004
+ viewport.addEventListener("pointerdown", handleViewportPointerDown);
7005
+ viewport.addEventListener("pointermove", handleViewportPointerMove);
7006
+ viewport.addEventListener("pointerup", handleViewportPointerEnd);
7007
+ viewport.addEventListener("pointercancel", handleViewportPointerEnd);
5460
7008
  }
7009
+ if (doubleClickToReset) viewport.addEventListener("dblclick", handleViewportDoubleClick);
5461
7010
  }
5462
- const pixelRatioForSvg = pixelRatio || 1;
5463
- const clonedContainer = containerEl.cloneNode(true);
5464
- await inlineExternalResources(clonedContainer);
5465
- const svgXml = await inlineSerializedSvgResources(exportDiagramAsVectorSvg(clonedContainer, options));
5466
- const blob = new Blob([svgXml], { type: "image/svg+xml;charset=utf-8" });
5467
- const url = URL.createObjectURL(blob);
5468
- const img = new Image();
5469
- await new Promise((resolve, reject) => {
5470
- img.onload = () => resolve();
5471
- img.onerror = () => {
5472
- URL.revokeObjectURL(url);
5473
- reject(new Error("Failed to rasterize SVG into Image for PNG export"));
5474
- };
5475
- img.src = url;
5476
- });
5477
- const width = img.naturalWidth || 800;
5478
- const height = img.naturalHeight || 400;
5479
- const canvas = document.createElement("canvas");
5480
- canvas.width = width * pixelRatioForSvg;
5481
- canvas.height = height * pixelRatioForSvg;
5482
- const ctx = canvas.getContext("2d");
5483
- if (!ctx) {
5484
- URL.revokeObjectURL(url);
5485
- throw new Error("Could not get 2D canvas context for PNG export");
7011
+ if (showControls) mountControls();
7012
+ if (clickToPlay) {
7013
+ viewport.addEventListener("click", () => {
7014
+ if (suppressNextClick) {
7015
+ suppressNextClick = false;
7016
+ return;
7017
+ }
7018
+ togglePlayback();
7019
+ });
5486
7020
  }
5487
- ctx.scale(pixelRatioForSvg, pixelRatioForSvg);
5488
- ctx.drawImage(img, 0, 0, width, height);
5489
- URL.revokeObjectURL(url);
5490
- return canvas;
5491
- }
5492
-
5493
- // src/export/gif-exporter.ts
5494
- var nextFrame = () => new Promise((resolve) => {
5495
- let settled = false;
5496
- const finish = () => {
5497
- if (settled) return;
5498
- settled = true;
5499
- resolve();
5500
- };
5501
- const fallback = setTimeout(finish, 80);
5502
- requestAnimationFrame(() => requestAnimationFrame(() => {
5503
- clearTimeout(fallback);
5504
- finish();
5505
- }));
5506
- });
5507
- var DEFAULT_GIF_PIXEL_RATIO = 0.3;
5508
- var MAX_GIF_FRAMES = 24;
5509
- async function rasterizeFrame(container, pixelRatio, options) {
5510
- const canvas = await rasterizeDiagramToCanvas(container, options, pixelRatio);
5511
- const context = canvas.getContext("2d");
5512
- if (!context) throw new Error("Could not create GIF canvas context");
5513
- return context.getImageData(0, 0, canvas.width, canvas.height);
5514
- }
5515
- async function exportDiagramAsGif(container, timeline, options = {}) {
5516
- const requestedFps = Math.min(24, Math.max(1, Math.round(options.fps ?? 12)));
5517
- const duration = timeline.duration();
5518
- const fps = Math.min(requestedFps, MAX_GIF_FRAMES / Math.max(duration, 1e-3));
5519
- const frameCount = Math.max(1, Math.ceil(duration * fps));
5520
- const delayMs = Math.max(20, Math.round(1e3 / fps));
5521
- const pixelRatio = options.pixelRatio ?? DEFAULT_GIF_PIXEL_RATIO;
5522
- const priorTime = timeline.currentTime();
5523
- const wasPlaying = timeline.isPlaying();
5524
- timeline.pause();
5525
- try {
5526
- const frames = [];
5527
- timeline.seek(duration);
5528
- await nextFrame();
5529
- frames.push({ imageData: await rasterizeFrame(container, pixelRatio, options), delayMs: Math.max(delayMs, 800) });
5530
- for (let frame = 0; frame < frameCount; frame++) {
5531
- timeline.seek(Math.min(duration, frame / fps));
5532
- await nextFrame();
5533
- frames.push({
5534
- imageData: await rasterizeFrame(container, pixelRatio, options),
5535
- delayMs
5536
- });
5537
- }
5538
- timeline.seek(duration);
5539
- await nextFrame();
5540
- frames.push({ imageData: await rasterizeFrame(container, pixelRatio, options), delayMs: Math.max(delayMs, 800) });
5541
- const encoded = encodeGifSequence(frames, { dither: true, loop: options.loop ?? true });
5542
- const bytes = new Uint8Array(encoded.byteLength);
5543
- bytes.set(encoded);
5544
- return new Blob([bytes.buffer], { type: "image/gif" });
5545
- } finally {
5546
- timeline.seek(priorTime);
5547
- if (wasPlaying) timeline.play();
7021
+ if (keyboardShortcuts && typeof window !== "undefined") {
7022
+ window.addEventListener("keydown", handleKeyDown);
5548
7023
  }
7024
+ if (autoplay) diagram.play();
7025
+ return diagram;
5549
7026
  }
5550
7027
 
5551
7028
  // src/presentation-controller.ts
@@ -5628,12 +7105,392 @@ var DiagramPresentationController = class {
5628
7105
  }
5629
7106
  }
5630
7107
  };
7108
+
7109
+ // src/impact.ts
7110
+ function extractAllDiagramEdges(ast) {
7111
+ const result = [];
7112
+ const seen = /* @__PURE__ */ new Set();
7113
+ const add = (from, to, op, label) => {
7114
+ const key = `${from}->${to}`;
7115
+ if (!seen.has(key)) {
7116
+ seen.add(key);
7117
+ result.push({ from, to, op, label });
7118
+ }
7119
+ };
7120
+ for (const edge of ast.edges || []) {
7121
+ add(edge.from, edge.to, edge.kind, edge.label);
7122
+ }
7123
+ for (const beat of ast.beats || []) {
7124
+ for (const cue of beat.cues || []) {
7125
+ if (cue.kind === "flow") {
7126
+ for (const segment of cue.segments) {
7127
+ add(segment.from, segment.to, segment.op, segment.label);
7128
+ }
7129
+ } else if (cue.kind === "parallel") {
7130
+ for (const childCue of cue.cues) {
7131
+ if (childCue.kind === "flow") {
7132
+ for (const segment of childCue.segments) {
7133
+ add(segment.from, segment.to, segment.op, segment.label);
7134
+ }
7135
+ }
7136
+ }
7137
+ }
7138
+ }
7139
+ }
7140
+ return result;
7141
+ }
7142
+ function calculateBlastRadius(nodeId, ast, maxDepth = 10) {
7143
+ const upstreamNodeIds = /* @__PURE__ */ new Set();
7144
+ const downstreamNodeIds = /* @__PURE__ */ new Set();
7145
+ const connectedEdgeKeys = /* @__PURE__ */ new Set();
7146
+ const edges = extractAllDiagramEdges(ast);
7147
+ const forwardQueue = [{ id: nodeId, depth: 0 }];
7148
+ const visitedForward = /* @__PURE__ */ new Set([nodeId]);
7149
+ while (forwardQueue.length > 0) {
7150
+ const { id, depth } = forwardQueue.shift();
7151
+ if (depth >= maxDepth) continue;
7152
+ for (const edge of edges) {
7153
+ if (edge.from === id) {
7154
+ connectedEdgeKeys.add(`${edge.from}->${edge.to}`);
7155
+ if (!visitedForward.has(edge.to)) {
7156
+ visitedForward.add(edge.to);
7157
+ downstreamNodeIds.add(edge.to);
7158
+ forwardQueue.push({ id: edge.to, depth: depth + 1 });
7159
+ }
7160
+ }
7161
+ }
7162
+ }
7163
+ const backwardQueue = [{ id: nodeId, depth: 0 }];
7164
+ const visitedBackward = /* @__PURE__ */ new Set([nodeId]);
7165
+ while (backwardQueue.length > 0) {
7166
+ const { id, depth } = backwardQueue.shift();
7167
+ if (depth >= maxDepth) continue;
7168
+ for (const edge of edges) {
7169
+ if (edge.to === id) {
7170
+ connectedEdgeKeys.add(`${edge.from}->${edge.to}`);
7171
+ if (!visitedBackward.has(edge.from)) {
7172
+ visitedBackward.add(edge.from);
7173
+ upstreamNodeIds.add(edge.from);
7174
+ backwardQueue.push({ id: edge.from, depth: depth + 1 });
7175
+ }
7176
+ }
7177
+ }
7178
+ }
7179
+ const allImpactedNodeIds = /* @__PURE__ */ new Set([nodeId, ...upstreamNodeIds, ...downstreamNodeIds]);
7180
+ return {
7181
+ rootNodeId: nodeId,
7182
+ upstreamNodeIds,
7183
+ downstreamNodeIds,
7184
+ allImpactedNodeIds,
7185
+ connectedEdgeKeys
7186
+ };
7187
+ }
7188
+ function findShortestRoute(fromId, toId, ast) {
7189
+ if (fromId === toId) return [fromId];
7190
+ const edges = extractAllDiagramEdges(ast);
7191
+ const queue = [{ current: fromId, path: [fromId] }];
7192
+ const visited = /* @__PURE__ */ new Set([fromId]);
7193
+ while (queue.length > 0) {
7194
+ const { current, path } = queue.shift();
7195
+ for (const edge of edges) {
7196
+ if (edge.from === current) {
7197
+ if (edge.to === toId) {
7198
+ return [...path, toId];
7199
+ }
7200
+ if (!visited.has(edge.to)) {
7201
+ visited.add(edge.to);
7202
+ queue.push({ current: edge.to, path: [...path, edge.to] });
7203
+ }
7204
+ }
7205
+ }
7206
+ }
7207
+ return null;
7208
+ }
7209
+ function applyImpactHighlight(container, impact) {
7210
+ const nodeElements = container.querySelectorAll("[data-node-id]");
7211
+ nodeElements.forEach((el) => {
7212
+ const id = el.getAttribute("data-node-id");
7213
+ if (!id) return;
7214
+ if (id === impact.rootNodeId) {
7215
+ el.style.opacity = "1";
7216
+ el.style.filter = "drop-shadow(0 0 12px rgba(56, 189, 248, 0.8))";
7217
+ } else if (impact.upstreamNodeIds.has(id)) {
7218
+ el.style.opacity = "1";
7219
+ el.style.filter = "drop-shadow(0 0 8px rgba(167, 139, 250, 0.6))";
7220
+ } else if (impact.downstreamNodeIds.has(id)) {
7221
+ el.style.opacity = "1";
7222
+ el.style.filter = "drop-shadow(0 0 8px rgba(52, 211, 153, 0.6))";
7223
+ } else {
7224
+ el.style.opacity = "0.2";
7225
+ el.style.filter = "grayscale(80%)";
7226
+ }
7227
+ });
7228
+ const edgeElements = container.querySelectorAll("[data-edge-key]");
7229
+ edgeElements.forEach((el) => {
7230
+ const key = el.getAttribute("data-edge-key");
7231
+ if (!key) return;
7232
+ if (impact.connectedEdgeKeys.has(key)) {
7233
+ el.style.opacity = "1";
7234
+ el.style.stroke = "#38bdf8";
7235
+ } else {
7236
+ el.style.opacity = "0.15";
7237
+ }
7238
+ });
7239
+ }
7240
+ function clearImpactHighlight(container) {
7241
+ const nodeElements = container.querySelectorAll("[data-node-id]");
7242
+ nodeElements.forEach((el) => {
7243
+ el.style.opacity = "";
7244
+ el.style.filter = "";
7245
+ });
7246
+ const edgeElements = container.querySelectorAll("[data-edge-key]");
7247
+ edgeElements.forEach((el) => {
7248
+ el.style.opacity = "";
7249
+ el.style.stroke = "";
7250
+ });
7251
+ }
7252
+
7253
+ // src/export/share-card.ts
7254
+ var THEME_CARD_STYLES = {
7255
+ midnight: {
7256
+ bg: "#070d18",
7257
+ cardBg: "#0e1a2c",
7258
+ text: "#f4f7fb",
7259
+ muted: "#93a4bb",
7260
+ border: "#28384f",
7261
+ accent: "#38bdf8"
7262
+ },
7263
+ paper: {
7264
+ bg: "#f6f8fc",
7265
+ cardBg: "#ffffff",
7266
+ text: "#0f1c2e",
7267
+ muted: "#475569",
7268
+ border: "#cbd5e1",
7269
+ accent: "#0284c7"
7270
+ },
7271
+ blueprint: {
7272
+ bg: "#0a1a3a",
7273
+ cardBg: "#10214a",
7274
+ text: "#eaf1ff",
7275
+ muted: "#9fb6e0",
7276
+ border: "#2c477f",
7277
+ accent: "#5ba3ff"
7278
+ },
7279
+ graphite: {
7280
+ bg: "#111317",
7281
+ cardBg: "#191c22",
7282
+ text: "#eef1f5",
7283
+ muted: "#9aa3b1",
7284
+ border: "#343a45",
7285
+ accent: "#2dd4bf"
7286
+ },
7287
+ editorial: {
7288
+ bg: "#fafafa",
7289
+ cardBg: "#ffffff",
7290
+ text: "#0f172a",
7291
+ muted: "#475569",
7292
+ border: "#e2e8f0",
7293
+ accent: "#047857"
7294
+ },
7295
+ nebula: {
7296
+ bg: "#090b1a",
7297
+ cardBg: "#111735",
7298
+ text: "#eef2ff",
7299
+ muted: "#a5b4fc",
7300
+ border: "rgba(167, 139, 250, 0.28)",
7301
+ accent: "#c4b5fd"
7302
+ },
7303
+ terminal: {
7304
+ bg: "#0a0a0a",
7305
+ cardBg: "#141414",
7306
+ text: "#f5f5f5",
7307
+ muted: "#888888",
7308
+ border: "#2b2b2b",
7309
+ accent: "#4ade80"
7310
+ }
7311
+ };
7312
+ function escapeXml2(str) {
7313
+ return str.replace(/[<>&"']/g, (c) => {
7314
+ switch (c) {
7315
+ case "<":
7316
+ return "&lt;";
7317
+ case ">":
7318
+ return "&gt;";
7319
+ case "&":
7320
+ return "&amp;";
7321
+ case '"':
7322
+ return "&quot;";
7323
+ case "'":
7324
+ return "&apos;";
7325
+ default:
7326
+ return c;
7327
+ }
7328
+ });
7329
+ }
7330
+ function renderShareCardSvg(diagramSvgXml, options = {}) {
7331
+ const themeKey = options.theme || "midnight";
7332
+ const colors = THEME_CARD_STYLES[themeKey] || THEME_CARD_STYLES.midnight;
7333
+ const title = options.title || "Architecture System Map";
7334
+ const variant = options.variant || "standard";
7335
+ let badgeText = "MARKDY SYSTEM MAP";
7336
+ let badgeColor = colors.accent;
7337
+ let telemetryLine = "";
7338
+ if (variant === "route") {
7339
+ const routeOpt = options;
7340
+ badgeText = "ROUTE PATHFINDER";
7341
+ badgeColor = "#38bdf8";
7342
+ const hops = routeOpt.hops ?? 2;
7343
+ const protocol = routeOpt.protocol ? ` \u2022 ${escapeXml2(routeOpt.protocol)}` : "";
7344
+ telemetryLine = `Active Route: ${escapeXml2(routeOpt.from || "Origin")} \u2192 ${escapeXml2(routeOpt.to || "Destination")} \u2022 ${hops} hops${protocol}`;
7345
+ } else if (variant === "reach") {
7346
+ const reachOpt = options;
7347
+ badgeText = "BLAST RADIUS LENS";
7348
+ badgeColor = reachOpt.direction === "upstream" ? "#a78bfa" : "#22c55e";
7349
+ const dir = reachOpt.direction ? reachOpt.direction.toUpperCase() : "DOWNSTREAM";
7350
+ const count = reachOpt.impactedNodeCount ?? 3;
7351
+ const depth = reachOpt.maxDepth ?? 2;
7352
+ telemetryLine = `Root: ${escapeXml2(reachOpt.rootId || "Origin")} \u2022 Direction: ${dir} \u2022 ${count} Impacted Nodes \u2022 Depth: ${depth}`;
7353
+ }
7354
+ const vbMatch = diagramSvgXml.match(/viewBox="([^"]+)"/);
7355
+ let vbWidth = 1e3;
7356
+ let vbHeight = 500;
7357
+ if (vbMatch) {
7358
+ const parts = vbMatch[1].split(/\s+/).map(Number);
7359
+ if (parts.length === 4 && parts[2] > 0 && parts[3] > 0) {
7360
+ vbWidth = parts[2];
7361
+ vbHeight = parts[3];
7362
+ }
7363
+ }
7364
+ const canvasW = 1200;
7365
+ const canvasH = 630;
7366
+ const availW = 1120;
7367
+ const availH = 460;
7368
+ const scale = Math.min(availW / vbWidth, availH / vbHeight, 1.2);
7369
+ const targetW = vbWidth * scale;
7370
+ const targetH = vbHeight * scale;
7371
+ const targetX = (canvasW - targetW) / 2;
7372
+ const targetY = 110 + (availH - targetH) / 2;
7373
+ const cleanedInnerSvg = diagramSvgXml.replace(/^<\?xml[^>]*\?>/i, "").replace(/^<!DOCTYPE[^>]*>/i, "").trim();
7374
+ const innerContent = cleanedInnerSvg.replace(/^<svg[^>]*>/i, "").replace(/<\/svg>\s*$/i, "");
7375
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 630" width="1200" height="630">
7376
+ <defs>
7377
+ <style>
7378
+ .card-title { font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 22px; font-weight: 700; fill: ${colors.text}; }
7379
+ .card-badge { font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 11px; font-weight: 700; letter-spacing: 0.14em; fill: ${badgeColor}; }
7380
+ .card-telemetry { font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 13px; font-weight: 500; fill: ${colors.muted}; }
7381
+ .card-footer { font-family: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; font-weight: 600; fill: ${colors.muted}; }
7382
+ </style>
7383
+ <pattern id="cardGrid" width="30" height="30" patternUnits="userSpaceOnUse">
7384
+ <path d="M 30 0 L 0 0 0 30" fill="none" stroke="${colors.border}" stroke-width="0.75" stroke-opacity="0.35"/>
7385
+ </pattern>
7386
+ <filter id="cardGlow" x="-20%" y="-20%" width="140%" height="140%">
7387
+ <feDropShadow dx="0" dy="16" stdDeviation="28" flood-color="#000000" flood-opacity="0.45"/>
7388
+ </filter>
7389
+ </defs>
7390
+
7391
+ <!-- Background Canvas -->
7392
+ <rect width="1200" height="630" fill="${colors.bg}"/>
7393
+ <rect width="1200" height="630" fill="url(#cardGrid)"/>
7394
+
7395
+ <!-- Main Card Container Panel -->
7396
+ <rect x="30" y="30" width="1140" height="570" rx="16" fill="${colors.cardBg}" stroke="${colors.border}" stroke-width="1.5" filter="url(#cardGlow)"/>
7397
+
7398
+ <!-- Card Header -->
7399
+ <g transform="translate(60, 72)">
7400
+ <!-- Badge Capsule -->
7401
+ <rect x="0" y="0" width="${badgeText.length * 8.5 + 24}" height="24" rx="12" fill="${colors.border}" fill-opacity="0.5"/>
7402
+ <text x="12" y="16" class="card-badge">${escapeXml2(badgeText)}</text>
7403
+
7404
+ <!-- Title -->
7405
+ <text x="${badgeText.length * 8.5 + 40}" y="18" class="card-title">${escapeXml2(title)}</text>
7406
+ </g>
7407
+
7408
+ <!-- Telemetry Bar (if present) -->
7409
+ ${telemetryLine ? `
7410
+ <g transform="translate(60, 110)">
7411
+ <text x="0" y="0" class="card-telemetry">${telemetryLine}</text>
7412
+ </g>` : ""}
7413
+
7414
+ <!-- Embedded Scaled Diagram -->
7415
+ <g transform="translate(${targetX}, ${targetY})">
7416
+ <svg width="${targetW}" height="${targetH}" viewBox="0 0 ${vbWidth} ${vbHeight}">
7417
+ ${innerContent}
7418
+ </svg>
7419
+ </g>
7420
+
7421
+ <!-- Card Footer -->
7422
+ <g transform="translate(60, 574)">
7423
+ <circle cx="6" cy="-4" r="4" fill="${colors.accent}"/>
7424
+ <text x="18" y="0" class="card-footer">markdy.com \u2022 Deterministic Vector Verification</text>
7425
+ </g>
7426
+ </svg>`;
7427
+ }
7428
+ async function exportDiagramAsShareCard(containerEl, options = {}) {
7429
+ const pixelRatio = options.pixelRatio || 2;
7430
+ const rawSvg = exportLiveSceneAsPureVectorSvg(containerEl, options);
7431
+ const cardSvg = renderShareCardSvg(rawSvg, options);
7432
+ const inlinedSvg = await inlineSerializedSvgResources(cardSvg);
7433
+ const blob = new Blob([inlinedSvg], { type: "image/svg+xml;charset=utf-8" });
7434
+ const url = URL.createObjectURL(blob);
7435
+ const img = new Image();
7436
+ await new Promise((resolve, reject) => {
7437
+ img.onload = () => resolve();
7438
+ img.onerror = () => {
7439
+ URL.revokeObjectURL(url);
7440
+ reject(new Error("Failed to load Share Card SVG for rasterization"));
7441
+ };
7442
+ img.src = url;
7443
+ });
7444
+ const canvas = document.createElement("canvas");
7445
+ canvas.width = 1200 * pixelRatio;
7446
+ canvas.height = 630 * pixelRatio;
7447
+ const ctx = canvas.getContext("2d");
7448
+ if (!ctx) {
7449
+ URL.revokeObjectURL(url);
7450
+ throw new Error("Could not get 2D canvas context for Share Card export");
7451
+ }
7452
+ ctx.scale(pixelRatio, pixelRatio);
7453
+ ctx.drawImage(img, 0, 0, 1200, 630);
7454
+ URL.revokeObjectURL(url);
7455
+ return new Promise((resolve, reject) => {
7456
+ canvas.toBlob((b) => {
7457
+ if (b) resolve(b);
7458
+ else reject(new Error("Canvas toBlob failed for Share Card PNG"));
7459
+ }, "image/png");
7460
+ });
7461
+ }
7462
+ async function exportRouteShareCard(containerEl, route, options = {}) {
7463
+ return exportDiagramAsShareCard(containerEl, {
7464
+ ...options,
7465
+ ...route,
7466
+ variant: "route"
7467
+ });
7468
+ }
7469
+ async function exportReachShareCard(containerEl, reach, options = {}) {
7470
+ return exportDiagramAsShareCard(containerEl, {
7471
+ ...options,
7472
+ ...reach,
7473
+ variant: "reach"
7474
+ });
7475
+ }
5631
7476
  export {
5632
7477
  DiagramPresentationController,
5633
7478
  ICON_REGISTRY,
7479
+ applyImpactHighlight,
7480
+ calculateBlastRadius,
7481
+ clearImpactHighlight,
5634
7482
  createDiagram,
7483
+ detectHostTheme,
5635
7484
  encodeGifSequence,
5636
7485
  exportDiagramAsGif,
5637
7486
  exportDiagramAsPng,
5638
- exportDiagramAsVectorSvg
7487
+ exportDiagramAsShareCard,
7488
+ exportDiagramAsVectorSvg,
7489
+ exportLiveSceneAsPureVectorSvg,
7490
+ exportReachShareCard,
7491
+ exportRouteShareCard,
7492
+ findShortestRoute,
7493
+ iconKeyForNode,
7494
+ renderPureVectorSvg,
7495
+ renderShareCardSvg
5639
7496
  };