@markdy/renderer-dom 1.1.7 → 1.2.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.
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,44 @@ 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
+ }
297
+ }
298
+ const perpStep = halfH + 8;
299
+ for (let k = 1; k <= 3; k++) {
300
+ const stepPerp = k * perpStep;
301
+ if (horizontal) {
302
+ candidates.push(
303
+ { x: mid.x, y: mid.y - stepPerp, penalty: 20 + k * 6 },
304
+ { x: mid.x, y: mid.y + stepPerp, penalty: 24 + k * 6 }
305
+ );
306
+ } else {
307
+ candidates.push(
308
+ { x: mid.x - stepPerp, y: mid.y, penalty: 20 + k * 6 },
309
+ { x: mid.x + stepPerp, y: mid.y, penalty: 24 + k * 6 }
310
+ );
311
+ }
245
312
  }
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);
313
+ for (const cand of candidates) {
314
+ const cx = clamp(cand.x, pad + halfW, bounds.width - pad - halfW);
315
+ const cy = clamp(cand.y, pad + halfH, bounds.height - pad - halfH);
249
316
  const rect = { x1: cx - halfW, y1: cy - halfH, x2: cx + halfW, y2: cy + halfH };
250
317
  const hits = overlapCount(rect, obstacles);
251
- const score = hits * 1e5 + (horizontal ? 0 : 40) + Math.abs(off) * 2 - Math.min(100, segLen) * 0.1;
318
+ const score = hits * 1e5 + (horizontal ? 0 : 40) + cand.penalty - Math.min(100, segLen) * 0.1;
252
319
  if (score < bestScore) {
253
320
  bestScore = score;
254
321
  bestPlacement = { x: round1(cx), y: round1(cy), rect };
@@ -763,14 +830,30 @@ function updateEdgeLayerTheme(svg, edgeRuntimeMap, theme, sceneId) {
763
830
  const color = theme.edges[runtime.kind];
764
831
  runtime.color = color;
765
832
  runtime.path.setAttribute("stroke", color);
833
+ runtime.path.removeAttribute("filter");
766
834
  if (runtime.kind !== "dependency") {
767
835
  runtime.path.style.filter = `drop-shadow(0 0 4px ${translucentColor(color, "44")})`;
836
+ } else {
837
+ runtime.path.style.filter = "";
768
838
  }
769
839
  runtime.dot.setAttribute("fill", color);
770
840
  runtime.dot.style.filter = `drop-shadow(0 0 6px ${color}) drop-shadow(0 0 12px ${color}88)`;
771
841
  if (runtime.labelPlate) {
772
- runtime.labelPlate.setAttribute("fill", theme.canvas ?? theme.surface ?? "#ffffff");
773
- runtime.labelPlate.setAttribute("stroke", translucentColor(color, "28"));
842
+ if (theme.name === "doodle") {
843
+ runtime.labelPlate.setAttribute("fill", "#ffffff");
844
+ runtime.labelPlate.setAttribute("stroke", "#18181b");
845
+ runtime.labelPlate.setAttribute("stroke-width", "1.5");
846
+ runtime.labelPlate.setAttribute("rx", "7");
847
+ runtime.labelPlate.setAttribute("ry", "7");
848
+ runtime.labelPlate.style.filter = "drop-shadow(2px 2px 0 #18181b)";
849
+ } else {
850
+ runtime.labelPlate.setAttribute("fill", theme.canvas ?? theme.surface ?? "#ffffff");
851
+ runtime.labelPlate.setAttribute("stroke", translucentColor(color, "28"));
852
+ runtime.labelPlate.setAttribute("stroke-width", "1");
853
+ runtime.labelPlate.setAttribute("rx", "5");
854
+ runtime.labelPlate.setAttribute("ry", "5");
855
+ runtime.labelPlate.style.filter = isDark ? `drop-shadow(0 4px 12px ${translucentColor(color, "18")})` : "drop-shadow(0 2px 6px rgba(15, 23, 42, 0.08))";
856
+ }
774
857
  }
775
858
  if (runtime.label) {
776
859
  runtime.label.setAttribute("fill", computeEdgeLabelColor(color, isDark));
@@ -778,7 +861,7 @@ function updateEdgeLayerTheme(svg, edgeRuntimeMap, theme, sceneId) {
778
861
  }
779
862
  }
780
863
  function isDarkTheme(theme) {
781
- if (theme.name === "paper" || theme.name === "editorial" || theme.name === "sketchy") {
864
+ if (theme.name === "paper" || theme.name === "editorial" || theme.name === "sketchy" || theme.name === "ink" || theme.name === "doodle") {
782
865
  return false;
783
866
  }
784
867
  const canvas = (theme.canvas || theme.surface || "").trim();
@@ -806,12 +889,17 @@ function createEdgeRuntime(svg, from, to, kind, label, theme, sceneId, routeObst
806
889
  const points = isSelfLoop ? dedupePoints(selfLoopPath(from, bounds)) : dedupePoints(routeEdgePoints(from, to, routeObstacles, bounds, lane));
807
890
  const d = toPathD(points, 14, existingPaths);
808
891
  const len = polylineLength(points);
892
+ const edgeId = `${from.id}_${to.id}`;
809
893
  const group = document.createElementNS("http://www.w3.org/2000/svg", "g");
894
+ group.setAttribute("data-edge-id", edgeId);
895
+ group.setAttribute("data-edge", edgeId);
896
+ group.setAttribute("id", `edge-${edgeId}`);
810
897
  group.setAttribute("data-edge-kind", kind);
811
898
  group.setAttribute("class", `markdy-edge markdy-edge--${kind}`);
812
899
  group.style.opacity = "0";
813
900
  const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
814
901
  path.setAttribute("d", d);
902
+ path.setAttribute("data-edge-path", edgeId);
815
903
  path.setAttribute("fill", "none");
816
904
  path.setAttribute("stroke", color);
817
905
  path.setAttribute("stroke-width", kind === "dependency" ? "1.5" : "2");
@@ -826,52 +914,94 @@ function createEdgeRuntime(svg, from, to, kind, label, theme, sceneId, routeObst
826
914
  path.style.filter = `drop-shadow(0 0 4px ${translucentColor(color, "44")})`;
827
915
  }
828
916
  const dot = document.createElementNS("http://www.w3.org/2000/svg", "circle");
829
- dot.setAttribute("r", "4");
917
+ dot.setAttribute("r", "4.5");
830
918
  dot.setAttribute("fill", color);
831
919
  dot.setAttribute("class", "markdy-edge-dot");
832
920
  dot.style.opacity = "0";
833
- dot.style.filter = `drop-shadow(0 0 6px ${color}) drop-shadow(0 0 12px ${color}88)`;
921
+ dot.style.filter = `drop-shadow(0 0 4px ${color}) drop-shadow(0 0 10px ${color}bb) drop-shadow(0 0 18px ${color}66)`;
834
922
  group.append(path, dot);
835
923
  let labelEl;
836
924
  let labelRect;
837
925
  if (label) {
838
926
  const isDark = isDarkTheme(theme);
839
927
  const labelColor = computeEdgeLabelColor(color, isDark);
840
- const textWidth = Math.max(36, label.length * 6.6 + 8);
841
- const placement = placeFlowLabel(points, textWidth, labelObstacles, bounds);
928
+ let longestSegLen = 0;
929
+ for (let i = 0; i < points.length - 1; i++) {
930
+ longestSegLen = Math.max(longestSegLen, Math.hypot(points[i + 1].x - points[i].x, points[i + 1].y - points[i].y));
931
+ }
932
+ const maxAvailW = Math.max(48, longestSegLen - 24);
933
+ const lines = wrapFlowLabelText(label, maxAvailW);
934
+ const maxChars = Math.max(...lines.map((l) => l.length));
935
+ const textWidth = Math.max(36, maxChars * 6.6 + 8);
936
+ const lineHeight = 13;
937
+ const boxHeight = lines.length === 1 ? 18 : lines.length * lineHeight + 6;
938
+ const placement = placeFlowLabel(points, textWidth, labelObstacles, bounds, boxHeight);
842
939
  labelRect = placement.rect;
843
940
  const plate = document.createElementNS("http://www.w3.org/2000/svg", "rect");
844
941
  const padX = 6;
845
942
  const halfW = textWidth / 2;
846
943
  plate.setAttribute("class", "markdy-edge-plate");
847
944
  plate.setAttribute("x", String(placement.x - halfW - padX));
848
- plate.setAttribute("y", String(placement.y - 9));
945
+ plate.setAttribute("y", String(placement.y - boxHeight / 2));
849
946
  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";
947
+ plate.setAttribute("height", String(boxHeight));
948
+ if (theme.name === "doodle") {
949
+ plate.setAttribute("rx", "7");
950
+ plate.setAttribute("ry", "7");
951
+ plate.setAttribute("fill", "#ffffff");
952
+ plate.setAttribute("fill-opacity", "1");
953
+ plate.setAttribute("stroke", "#18181b");
954
+ plate.setAttribute("stroke-width", "1.5");
955
+ plate.style.opacity = "0";
956
+ plate.style.filter = "drop-shadow(2px 2px 0 #18181b)";
957
+ } else if (theme.name === "ink") {
958
+ plate.setAttribute("rx", "4");
959
+ plate.setAttribute("ry", "4");
960
+ plate.setAttribute("fill", "#ffffff");
961
+ plate.setAttribute("fill-opacity", "0.98");
962
+ plate.setAttribute("stroke", "#1d4ed8");
963
+ plate.setAttribute("stroke-width", "1");
964
+ plate.style.opacity = "0";
965
+ plate.style.filter = "drop-shadow(1.5px 1.5px 0 rgba(29, 78, 216, 0.14))";
966
+ } else {
967
+ plate.setAttribute("rx", "5");
968
+ plate.setAttribute("ry", "5");
969
+ plate.setAttribute("fill", theme.canvas ?? theme.surface ?? "#ffffff");
970
+ plate.setAttribute("fill-opacity", isDark ? "0.88" : "0.94");
971
+ plate.setAttribute("stroke", translucentColor(color, isDark ? "55" : "33"));
972
+ plate.setAttribute("stroke-width", "1");
973
+ plate.style.opacity = "0";
974
+ 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))";
975
+ }
859
976
  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;
977
+ const textEl = document.createElementNS("http://www.w3.org/2000/svg", "text");
978
+ labelEl = textEl;
979
+ textEl.setAttribute("class", "markdy-edge-label");
980
+ textEl.setAttribute("x", String(placement.x));
981
+ textEl.setAttribute("text-anchor", "middle");
982
+ textEl.setAttribute("font-size", "10.5");
983
+ textEl.setAttribute("font-weight", "500");
984
+ textEl.setAttribute("letter-spacing", "0.02em");
985
+ textEl.setAttribute("font-family", "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace");
986
+ textEl.setAttribute("fill", labelColor);
987
+ if (lines.length === 1) {
988
+ textEl.setAttribute("y", String(placement.y + 0.5));
989
+ textEl.setAttribute("dominant-baseline", "middle");
990
+ textEl.textContent = lines[0];
991
+ } else {
992
+ const startY = placement.y - (lines.length - 1) * lineHeight / 2 + 3.5;
993
+ lines.forEach((lineText, idx) => {
994
+ const tspan = document.createElementNS("http://www.w3.org/2000/svg", "tspan");
995
+ tspan.setAttribute("x", String(placement.x));
996
+ tspan.setAttribute("y", String(startY + idx * lineHeight));
997
+ tspan.setAttribute("text-anchor", "middle");
998
+ tspan.textContent = idx < lines.length - 1 ? `${lineText} ` : lineText;
999
+ textEl.appendChild(tspan);
1000
+ });
1001
+ }
1002
+ textEl.style.opacity = "0";
1003
+ group.appendChild(textEl);
1004
+ textEl.__plate = plate;
875
1005
  }
876
1006
  svg.appendChild(group);
877
1007
  return {
@@ -1798,14 +1928,14 @@ function ensureGroupStyles(doc) {
1798
1928
  .markdy-group-boundary {
1799
1929
  position: absolute;
1800
1930
  box-sizing: border-box;
1801
- border: 1px solid var(--md-group-border, color-mix(in srgb, var(--md-border) 45%, transparent));
1931
+ border: 1px dashed var(--md-group-border, color-mix(in srgb, var(--md-border) 50%, transparent));
1802
1932
  border-radius: 16px;
1803
- background: color-mix(in srgb, var(--md-surface-raised) 32%, transparent);
1933
+ background: color-mix(in srgb, var(--md-surface-raised) 28%, transparent);
1804
1934
  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);
1935
+ 0 8px 32px -8px var(--md-shadow, rgba(0, 0, 0, 0.25)),
1936
+ inset 0 1px 0 rgba(255, 255, 255, 0.12);
1937
+ backdrop-filter: blur(10px);
1938
+ -webkit-backdrop-filter: blur(10px);
1809
1939
  pointer-events: none;
1810
1940
  z-index: 40;
1811
1941
  }
@@ -1813,19 +1943,51 @@ function ensureGroupStyles(doc) {
1813
1943
  position: absolute;
1814
1944
  left: 14px;
1815
1945
  top: 10px;
1816
- padding: 4px 10px;
1817
- font-size: 10.5px;
1818
- font-weight: 600;
1819
- letter-spacing: 0.08em;
1946
+ padding: 3px 10px;
1947
+ font-size: 10px;
1948
+ font-weight: 700;
1949
+ letter-spacing: 0.1em;
1820
1950
  text-transform: uppercase;
1821
1951
  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));
1952
+ background: color-mix(in srgb, var(--md-surface-raised) 90%, transparent);
1953
+ border: 1px solid var(--md-group-border, color-mix(in srgb, var(--md-border) 60%, transparent));
1824
1954
  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);
1955
+ font-family: var(--md-font-mono, ui-monospace, SFMono-Regular, Menlo, Monaco, monospace);
1956
+ backdrop-filter: blur(8px);
1957
+ -webkit-backdrop-filter: blur(8px);
1958
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.16);
1959
+ display: inline-flex;
1960
+ align-items: center;
1961
+ gap: 6px;
1962
+ }
1963
+ .markdy-scene-root[data-markdy-theme="doodle"] .markdy-group-boundary {
1964
+ border: 2px dashed #18181b;
1965
+ border-radius: 20px 24px 18px 22px / 22px 18px 24px 20px;
1966
+ background: rgba(254, 240, 138, 0.08);
1967
+ box-shadow: 3px 3px 0 rgba(24, 24, 27, 0.08);
1968
+ }
1969
+ .markdy-scene-root[data-markdy-theme="doodle"] .markdy-group-boundary__label {
1970
+ border: 1.5px solid #18181b;
1971
+ border-radius: 6px;
1972
+ box-shadow: 2px 2px 0 #18181b;
1973
+ background: #fef08a;
1974
+ color: #18181b;
1975
+ font-weight: 800;
1976
+ transform: rotate(-0.8deg);
1977
+ }
1978
+ .markdy-scene-root[data-markdy-theme="ink"] .markdy-group-boundary {
1979
+ border: 1.5px dashed #1d4ed8;
1980
+ border-radius: 8px;
1981
+ background: rgba(239, 246, 255, 0.45);
1982
+ box-shadow: 2px 2px 0 rgba(29, 78, 216, 0.08);
1983
+ }
1984
+ .markdy-scene-root[data-markdy-theme="ink"] .markdy-group-boundary__label {
1985
+ border: 1.25px solid #1d4ed8;
1986
+ border-radius: 4px;
1987
+ box-shadow: 1.5px 1.5px 0 rgba(29, 78, 216, 0.12);
1988
+ background: #ffffff;
1989
+ color: #1e3a8a;
1990
+ font-weight: 600;
1829
1991
  }
1830
1992
  `;
1831
1993
  doc.head.appendChild(style);
@@ -1908,7 +2070,7 @@ function ensureNodeStyles(doc) {
1908
2070
  .markdy-node__type { display: none; }
1909
2071
  .markdy-node__body {
1910
2072
  height: 100%;
1911
- padding: 0 14px;
2073
+ padding: 0 16px;
1912
2074
  display: flex;
1913
2075
  align-items: center;
1914
2076
  gap: 12px;
@@ -1917,36 +2079,30 @@ function ensureNodeStyles(doc) {
1917
2079
  }
1918
2080
  .markdy-node__icon {
1919
2081
  flex: 0 0 auto;
1920
- width: 34px;
1921
- height: 34px;
1922
- border-radius: 9px;
2082
+ width: 28px;
2083
+ height: 28px;
1923
2084
  display: flex;
1924
2085
  align-items: center;
1925
2086
  justify-content: center;
1926
2087
  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);
2088
+ background: transparent;
2089
+ box-shadow: none;
1934
2090
  }
1935
2091
  .markdy-node__icon svg {
1936
- width: 18px;
1937
- height: 18px;
2092
+ width: 26px;
2093
+ height: 26px;
1938
2094
  display: block;
1939
2095
  stroke: currentColor;
1940
2096
  }
1941
2097
  .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;
2098
+ background: transparent;
2099
+ box-shadow: none;
2100
+ padding: 0;
1945
2101
  overflow: hidden;
1946
2102
  }
1947
2103
  .markdy-node__icon img {
1948
- width: 100%;
1949
- height: 100%;
2104
+ width: 26px;
2105
+ height: 26px;
1950
2106
  object-fit: contain;
1951
2107
  border-radius: 6px;
1952
2108
  display: block;
@@ -1954,12 +2110,16 @@ function ensureNodeStyles(doc) {
1954
2110
  .markdy-node__icon[data-fit="cover"] img {
1955
2111
  object-fit: cover;
1956
2112
  }
1957
- .markdy-node[data-icon="decision"] .markdy-node__icon,
1958
- .markdy-node[data-icon="flow"] .markdy-node__icon {
1959
- border-radius: 999px;
2113
+ .markdy-node__content {
2114
+ flex: 1 1 auto;
2115
+ min-width: 0;
2116
+ display: flex;
2117
+ flex-direction: column;
2118
+ justify-content: center;
2119
+ gap: 3px;
1960
2120
  }
1961
2121
  .markdy-node__label {
1962
- flex: 1 1 auto;
2122
+ flex: 0 1 auto;
1963
2123
  min-width: 0;
1964
2124
  padding: 0;
1965
2125
  font-size: 13.5px;
@@ -1969,13 +2129,30 @@ function ensureNodeStyles(doc) {
1969
2129
  color: var(--md-text);
1970
2130
  display: -webkit-box;
1971
2131
  -webkit-box-orient: vertical;
1972
- -webkit-line-clamp: 3;
1973
- line-clamp: 3;
2132
+ -webkit-line-clamp: 2;
2133
+ line-clamp: 2;
1974
2134
  overflow: hidden;
1975
2135
  overflow-wrap: anywhere;
1976
2136
  word-break: break-word;
1977
2137
  text-wrap: pretty;
1978
2138
  }
2139
+ .markdy-node__tech {
2140
+ align-self: flex-start;
2141
+ font-family: var(--md-font-mono, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace);
2142
+ font-size: 10px;
2143
+ font-weight: 500;
2144
+ line-height: 1.2;
2145
+ color: var(--md-text-muted, #94a3b8);
2146
+ background: color-mix(in srgb, var(--md-text, #ffffff) 6%, transparent);
2147
+ border: 1px solid color-mix(in srgb, var(--md-border, #475569) 55%, transparent);
2148
+ padding: 1.5px 6px;
2149
+ border-radius: 4px;
2150
+ letter-spacing: 0.01em;
2151
+ white-space: nowrap;
2152
+ overflow: hidden;
2153
+ text-overflow: ellipsis;
2154
+ max-width: 100%;
2155
+ }
1979
2156
  .markdy-node__value {
1980
2157
  flex: 0 0 auto;
1981
2158
  font-size: 16px;
@@ -1983,6 +2160,14 @@ function ensureNodeStyles(doc) {
1983
2160
  color: var(--md-ink, var(--md-text));
1984
2161
  font-variant-numeric: tabular-nums;
1985
2162
  }
2163
+ .markdy-node[data-visible="1"]:hover {
2164
+ transform: translateY(-2px);
2165
+ box-shadow:
2166
+ 0 3px 8px color-mix(in srgb, var(--md-shadow, rgba(2, 6, 23, 0.35)) 45%, transparent),
2167
+ 0 16px 32px -8px var(--md-shadow, rgba(2, 6, 23, 0.5)),
2168
+ inset 0 0 0 1px var(--md-hairline, color-mix(in srgb, var(--md-border) 60%, transparent)),
2169
+ inset 0 1px 0 rgba(255, 255, 255, 0.2);
2170
+ }
1986
2171
  .markdy-node[data-role="client"] { border-radius: 14px 14px 10px 10px; }
1987
2172
  .markdy-node[data-role="data"] { border-radius: 12px 12px 16px 16px; }
1988
2173
  .markdy-scene-title {
@@ -2020,6 +2205,10 @@ function ensureNodeStyles(doc) {
2020
2205
  .markdy-scene-root[data-markdy-theme="terminal"] .markdy-node[data-shape="diamond"][data-focal="1"],
2021
2206
  .markdy-scene-root[data-markdy-theme="sketchy"] .markdy-node[data-shape="diamond"],
2022
2207
  .markdy-scene-root[data-markdy-theme="sketchy"] .markdy-node[data-shape="diamond"][data-focal="1"],
2208
+ .markdy-scene-root[data-markdy-theme="ink"] .markdy-node[data-shape="diamond"],
2209
+ .markdy-scene-root[data-markdy-theme="ink"] .markdy-node[data-shape="diamond"][data-focal="1"],
2210
+ .markdy-scene-root[data-markdy-theme="doodle"] .markdy-node[data-shape="diamond"],
2211
+ .markdy-scene-root[data-markdy-theme="doodle"] .markdy-node[data-shape="diamond"][data-focal="1"],
2023
2212
  .markdy-scene-root[data-markdy-theme="nebula"] .markdy-node[data-shape="diamond"],
2024
2213
  .markdy-scene-root[data-markdy-theme="nebula"] .markdy-node[data-shape="diamond"][data-focal="1"] {
2025
2214
  border: none;
@@ -2196,6 +2385,97 @@ function ensureNodeStyles(doc) {
2196
2385
  background: rgba(235, 108, 54, 0.06);
2197
2386
  box-shadow: 3px 3px 0 rgba(235, 108, 54, 0.12);
2198
2387
  }
2388
+ .markdy-scene-root[data-markdy-theme="ink"] .markdy-node {
2389
+ background: #ffffff;
2390
+ border: 1.5px solid #1d4ed8;
2391
+ box-shadow:
2392
+ 3px 3px 0 rgba(29, 78, 216, 0.12),
2393
+ 0 4px 16px -2px rgba(29, 78, 216, 0.08),
2394
+ inset 0 1px 0 rgba(255, 255, 255, 0.9);
2395
+ border-radius: var(--md-radius-md, 6px);
2396
+ }
2397
+ .markdy-scene-root[data-markdy-theme="ink"] .markdy-node[data-visible="1"]:hover {
2398
+ transform: translate(-1px, -1px);
2399
+ box-shadow:
2400
+ 4px 4px 0 rgba(29, 78, 216, 0.18),
2401
+ 0 8px 24px -4px rgba(29, 78, 216, 0.14),
2402
+ inset 0 1px 0 rgba(255, 255, 255, 0.9);
2403
+ }
2404
+ .markdy-scene-root[data-markdy-theme="ink"] .markdy-node__icon {
2405
+ background: color-mix(in srgb, var(--md-role-color, var(--md-accent)) 10%, #ffffff);
2406
+ border: 1px solid color-mix(in srgb, var(--md-role-color, var(--md-accent)) 30%, transparent);
2407
+ border-radius: 6px;
2408
+ width: 30px;
2409
+ height: 30px;
2410
+ }
2411
+ .markdy-scene-root[data-markdy-theme="ink"] .markdy-node__tech {
2412
+ background: #eff6ff;
2413
+ color: #1e3a8a;
2414
+ border: 1px solid #bfdbfe;
2415
+ border-radius: 4px;
2416
+ font-weight: 600;
2417
+ }
2418
+ .markdy-scene-root[data-markdy-theme="ink"] .markdy-node[data-shape="diamond"] {
2419
+ filter: drop-shadow(0 0 1px #1d4ed8) drop-shadow(3px 3px 0 rgba(29, 78, 216, 0.12));
2420
+ }
2421
+ .markdy-scene-root[data-markdy-theme="ink"] .markdy-node[data-focal="1"] {
2422
+ border-color: #1d4ed8;
2423
+ background: linear-gradient(180deg, #ffffff 0%, #f0f7ff 100%);
2424
+ box-shadow:
2425
+ 3px 3px 0 rgba(29, 78, 216, 0.25),
2426
+ 0 8px 24px -4px rgba(29, 78, 216, 0.18),
2427
+ inset 0 1px 0 #ffffff;
2428
+ }
2429
+ .markdy-scene-root[data-markdy-theme="ink"] .markdy-node[data-focal="1"] .markdy-node__icon {
2430
+ background: rgba(29, 78, 216, 0.12);
2431
+ border-color: rgba(29, 78, 216, 0.40);
2432
+ }
2433
+ .markdy-scene-root[data-markdy-theme="ink"] .markdy-node[data-shape="diamond"][data-focal="1"] {
2434
+ 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));
2435
+ }
2436
+ .markdy-scene-root[data-markdy-theme="doodle"] .markdy-node {
2437
+ background: #ffffff;
2438
+ border: 2px solid #18181b;
2439
+ border-radius: 255px 15px 225px 15px/15px 225px 15px 255px;
2440
+ box-shadow: 4px 4px 0 #18181b, 0 8px 16px -4px rgba(24, 24, 27, 0.08);
2441
+ }
2442
+ .markdy-scene-root[data-markdy-theme="doodle"] .markdy-node[data-visible="1"]:hover {
2443
+ transform: translate(-1.5px, -1.5px) rotate(-0.6deg);
2444
+ box-shadow: 5.5px 5.5px 0 #18181b, 0 10px 20px -4px rgba(24, 24, 27, 0.12);
2445
+ }
2446
+ .markdy-scene-root[data-markdy-theme="doodle"] .markdy-node__icon {
2447
+ background: color-mix(in srgb, var(--md-role-color, var(--md-accent)) 16%, #ffffff);
2448
+ border: 1.75px solid #18181b;
2449
+ border-radius: 50% 45% 55% 48% / 48% 55% 45% 50%;
2450
+ width: 30px;
2451
+ height: 30px;
2452
+ box-shadow: 1.5px 1.5px 0 #18181b;
2453
+ }
2454
+ .markdy-scene-root[data-markdy-theme="doodle"] .markdy-node__tech {
2455
+ background: #fef08a;
2456
+ color: #18181b;
2457
+ border: 1.5px solid #18181b;
2458
+ border-radius: 4px 8px 5px 7px;
2459
+ font-weight: 800;
2460
+ box-shadow: 2px 2px 0 #18181b;
2461
+ transform: rotate(-1.2deg);
2462
+ }
2463
+ .markdy-scene-root[data-markdy-theme="doodle"] .markdy-node[data-shape="diamond"] {
2464
+ filter: drop-shadow(0 0 1px #18181b) drop-shadow(4px 4px 0 #18181b);
2465
+ }
2466
+ .markdy-scene-root[data-markdy-theme="doodle"] .markdy-node[data-focal="1"] {
2467
+ border: 2.25px solid #18181b;
2468
+ background: linear-gradient(135deg, #ffffff 0%, #fff1f2 100%);
2469
+ box-shadow: 4.5px 4.5px 0 #f43f5e, 0 0 0 2px #18181b;
2470
+ }
2471
+ .markdy-scene-root[data-markdy-theme="doodle"] .markdy-node[data-focal="1"] .markdy-node__icon {
2472
+ background: #f43f5e;
2473
+ color: #ffffff;
2474
+ border-color: #18181b;
2475
+ }
2476
+ .markdy-scene-root[data-markdy-theme="doodle"] .markdy-node[data-shape="diamond"][data-focal="1"] {
2477
+ filter: drop-shadow(0 0 1.5px #18181b) drop-shadow(4.5px 4.5px 0 #f43f5e);
2478
+ }
2199
2479
  .markdy-scene-root[data-markdy-theme="nebula"] .markdy-node[data-shape="diamond"] {
2200
2480
  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
2481
  }
@@ -2511,7 +2791,10 @@ function createNodeEl(node, theme, assets) {
2511
2791
  const el = document.createElement("div");
2512
2792
  el.className = "markdy-node markdy-scene-node";
2513
2793
  el.dataset.node = node.id;
2514
- el.dataset.role = node.role;
2794
+ el.dataset.nodeId = node.id;
2795
+ el.setAttribute("data-node-id", node.id);
2796
+ el.setAttribute("data-node", node.id);
2797
+ el.id = `node-${node.id}`;
2515
2798
  el.style.left = `${node.x}px`;
2516
2799
  el.style.top = `${node.y}px`;
2517
2800
  el.style.setProperty("--md-node-w", `${node.width}px`);
@@ -2533,11 +2816,21 @@ function createNodeEl(node, theme, assets) {
2533
2816
  el.setAttribute("aria-label", el.title);
2534
2817
  const body = document.createElement("div");
2535
2818
  body.className = "markdy-node__body";
2819
+ if (node.shape !== "diamond") body.append(createNodeMediaEl(document, node, assets));
2820
+ const content = document.createElement("div");
2821
+ content.className = "markdy-node__content";
2536
2822
  const label = document.createElement("div");
2537
2823
  label.className = "markdy-node__label";
2538
2824
  label.textContent = node.label;
2539
- if (node.shape !== "diamond") body.append(createNodeMediaEl(document, node, assets));
2540
- body.append(label);
2825
+ content.appendChild(label);
2826
+ const tech = node.props?.tech ?? node.props?.sub;
2827
+ if (tech !== void 0 && tech !== null && String(tech).trim().length > 0) {
2828
+ const techEl = document.createElement("div");
2829
+ techEl.className = "markdy-node__tech";
2830
+ techEl.textContent = String(tech);
2831
+ content.appendChild(techEl);
2832
+ }
2833
+ body.append(content);
2541
2834
  const value = node.props?.value ?? node.props?.metric;
2542
2835
  if (value !== void 0 && value !== null) {
2543
2836
  const valueEl = document.createElement("div");
@@ -2658,10 +2951,11 @@ function mountSequenceLayer(layer, nodes, messages, activations, theme, bounds)
2658
2951
  cap.setAttribute("opacity", "0.85");
2659
2952
  svg.appendChild(cap);
2660
2953
  }
2661
- for (const activation of activations) {
2954
+ activations.forEach((activation, index) => {
2662
2955
  const x = centerX(activation.participant);
2663
2956
  const bar = doc.createElementNS("http://www.w3.org/2000/svg", "rect");
2664
2957
  bar.classList.add("markdy-sequence-activation");
2958
+ bar.setAttribute("data-activation-index", String(index));
2665
2959
  bar.setAttribute("x", String(x - 6));
2666
2960
  bar.setAttribute("y", String(activation.y));
2667
2961
  bar.setAttribute("width", "12");
@@ -2671,7 +2965,7 @@ function mountSequenceLayer(layer, nodes, messages, activations, theme, bounds)
2671
2965
  bar.setAttribute("opacity", "0");
2672
2966
  bar.style.filter = `drop-shadow(0 0 6px ${theme.accent}66)`;
2673
2967
  svg.appendChild(bar);
2674
- }
2968
+ });
2675
2969
  const animations = [];
2676
2970
  for (const message of messages) {
2677
2971
  const fromX = centerX(message.from);
@@ -2679,6 +2973,7 @@ function mountSequenceLayer(layer, nodes, messages, activations, theme, bounds)
2679
2973
  const group = doc.createElementNS("http://www.w3.org/2000/svg", "g");
2680
2974
  group.classList.add("markdy-sequence-message");
2681
2975
  group.setAttribute("data-message", message.id);
2976
+ group.setAttribute("data-message-id", message.id);
2682
2977
  group.style.opacity = "0";
2683
2978
  const line = doc.createElementNS("http://www.w3.org/2000/svg", "line");
2684
2979
  line.setAttribute("x1", String(fromX));
@@ -2712,16 +3007,39 @@ function mountSequenceLayer(layer, nodes, messages, activations, theme, bounds)
2712
3007
  group.appendChild(plate);
2713
3008
  group.appendChild(createText(doc, midX, message.y - 14.5, message.label, theme));
2714
3009
  }
3010
+ const pulse = doc.createElementNS("http://www.w3.org/2000/svg", "circle");
3011
+ pulse.setAttribute("r", "4");
3012
+ pulse.setAttribute("fill", theme.edges[message.kind] || theme.accent);
3013
+ pulse.classList.add("markdy-sequence-pulse");
3014
+ pulse.style.opacity = "0";
3015
+ pulse.style.filter = `drop-shadow(0 0 6px ${theme.edges[message.kind] || theme.accent})`;
3016
+ group.appendChild(pulse);
2715
3017
  svg.appendChild(group);
3018
+ const durMs = Math.max(160, message.duration * 1e3);
3019
+ const startMs = message.start * 1e3;
2716
3020
  animations.push(
2717
3021
  group.animate(
2718
3022
  [{ opacity: 0 }, { opacity: 1 }],
2719
3023
  {
2720
- duration: Math.max(160, message.duration * 1e3),
2721
- delay: message.start * 1e3,
3024
+ duration: 120,
3025
+ delay: startMs,
2722
3026
  fill: "forwards",
2723
3027
  easing: "ease-out"
2724
3028
  }
3029
+ ),
3030
+ pulse.animate(
3031
+ [
3032
+ { transform: `translate(${fromX}px, ${message.y}px)`, opacity: 0 },
3033
+ { transform: `translate(${fromX}px, ${message.y}px)`, opacity: 1, offset: 0.1 },
3034
+ { transform: `translate(${toX}px, ${message.y}px)`, opacity: 1, offset: 0.9 },
3035
+ { transform: `translate(${toX}px, ${message.y}px)`, opacity: 0 }
3036
+ ],
3037
+ {
3038
+ duration: durMs,
3039
+ delay: startMs,
3040
+ fill: "forwards",
3041
+ easing: "cubic-bezier(0.2, 0.85, 0.4, 1)"
3042
+ }
2725
3043
  )
2726
3044
  );
2727
3045
  }
@@ -2866,47 +3184,45 @@ function ensureSceneStyles(doc) {
2866
3184
  .markdy-scene-root::before {
2867
3185
  z-index: 0;
2868
3186
  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;
3187
+ radial-gradient(circle at 50% 50%, var(--md-grid-minor) 1.2px, transparent 1.2px) 0 0 / 24px 24px,
3188
+ linear-gradient(var(--md-grid-major) 1px, transparent 1px) 0 0 / 120px 120px,
3189
+ linear-gradient(90deg, var(--md-grid-major) 1px, transparent 1px) 0 0 / 120px 120px;
3190
+ mask-image: radial-gradient(ellipse at 50% 48%, #000 65%, transparent 100%);
3191
+ opacity: 0.55;
2875
3192
  }
2876
3193
  .markdy-scene-root::after {
2877
3194
  z-index: 1;
2878
3195
  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;
3196
+ radial-gradient(ellipse at 50% -12%, color-mix(in srgb, var(--md-accent) 14%, transparent), transparent 50%),
3197
+ linear-gradient(180deg, transparent 0%, rgba(2, 6, 23, 0.04) 55%, var(--md-vignette) 100%);
3198
+ opacity: 0.68;
2882
3199
  }
2883
3200
  .markdy-scene-content { z-index: 2; }
2884
3201
  .markdy-scene-root[data-markdy-theme="nebula"]::before {
2885
3202
  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;
3203
+ radial-gradient(circle at 18% 18%, color-mix(in srgb, var(--md-soft) 20%, transparent), transparent 36%),
3204
+ radial-gradient(circle at 84% 72%, color-mix(in srgb, var(--md-accent) 22%, transparent), transparent 40%),
3205
+ radial-gradient(circle at 50% 50%, var(--md-grid-minor) 1.5px, transparent 1.5px) 0 0 / 28px 28px;
3206
+ mask-image: radial-gradient(ellipse at 50% 50%, #000 70%, transparent 100%);
3207
+ opacity: 0.95;
2892
3208
  }
2893
3209
  .markdy-scene-root[data-markdy-theme="nebula"]::after {
2894
3210
  background:
2895
- radial-gradient(ellipse at 50% 42%, color-mix(in srgb, var(--md-accent) 12%, transparent), transparent 56%),
3211
+ radial-gradient(ellipse at 50% 42%, color-mix(in srgb, var(--md-accent) 16%, transparent), transparent 56%),
2896
3212
  linear-gradient(180deg, transparent 0%, var(--md-vignette) 100%);
2897
- opacity: 0.8;
3213
+ opacity: 0.85;
2898
3214
  }
2899
3215
  .markdy-scene-root[data-markdy-theme="terminal"]::before {
2900
3216
  background:
2901
- radial-gradient(circle at 50% 50%, rgba(255, 255, 255, 0.06) 1px, transparent 1px) 0 0 / 22px 22px;
3217
+ radial-gradient(circle at 50% 50%, rgba(255, 255, 255, 0.08) 1px, transparent 1px) 0 0 / 20px 20px;
2902
3218
  mask-image: none;
2903
- opacity: 0.4;
3219
+ opacity: 0.45;
2904
3220
  }
2905
3221
  .markdy-scene-root[data-markdy-theme="terminal"]::after {
2906
3222
  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;
3223
+ radial-gradient(ellipse at 50% 0%, rgba(255, 90, 54, 0.1), transparent 52%),
3224
+ linear-gradient(180deg, transparent, rgba(0, 0, 0, 0.55) 100%);
3225
+ opacity: 0.75;
2910
3226
  }
2911
3227
  .markdy-scene-root[data-markdy-theme="sketchy"]::before {
2912
3228
  background: none;
@@ -2916,18 +3232,45 @@ function ensureSceneStyles(doc) {
2916
3232
  background: none;
2917
3233
  opacity: 0;
2918
3234
  }
3235
+ .markdy-scene-root[data-markdy-theme="ink"]::before {
3236
+ background:
3237
+ radial-gradient(circle at 50% 50%, color-mix(in srgb, var(--md-accent) 9%, transparent) 1px, transparent 1px) 0 0 / 20px 20px,
3238
+ linear-gradient(color-mix(in srgb, var(--md-accent) 6%, transparent) 1px, transparent 1px) 0 0 / 20px 20px,
3239
+ linear-gradient(90deg, color-mix(in srgb, var(--md-accent) 6%, transparent) 1px, transparent 1px) 0 0 / 20px 20px;
3240
+ mask-image: radial-gradient(ellipse at 50% 50%, #000 75%, transparent 100%);
3241
+ opacity: 0.75;
3242
+ }
3243
+ .markdy-scene-root[data-markdy-theme="ink"]::after {
3244
+ background:
3245
+ radial-gradient(ellipse at 50% -10%, color-mix(in srgb, var(--md-accent) 12%, transparent), transparent 50%),
3246
+ radial-gradient(ellipse at 100% 100%, rgba(30, 58, 138, 0.05), transparent 40%),
3247
+ linear-gradient(180deg, transparent 0%, rgba(219, 234, 254, 0.25) 80%, var(--md-vignette) 100%);
3248
+ opacity: 0.85;
3249
+ }
3250
+ .markdy-scene-root[data-markdy-theme="doodle"]::before {
3251
+ background:
3252
+ radial-gradient(circle at 50% 50%, rgba(24, 24, 27, 0.06) 1.5px, transparent 1.5px) 0 0 / 20px 20px;
3253
+ mask-image: none;
3254
+ opacity: 0.7;
3255
+ }
3256
+ .markdy-scene-root[data-markdy-theme="doodle"]::after {
3257
+ background:
3258
+ radial-gradient(ellipse at 85% 15%, rgba(244, 63, 94, 0.05), transparent 45%),
3259
+ radial-gradient(ellipse at 15% 85%, rgba(37, 99, 235, 0.05), transparent 45%);
3260
+ opacity: 0.6;
3261
+ }
2919
3262
  @keyframes markdy-star-twinkle {
2920
3263
  from { opacity: 0.24; transform: scale(0.85); }
2921
3264
  to { opacity: 0.9; transform: scale(1.15); }
2922
3265
  }
2923
3266
  @keyframes markdy-flow-dash {
2924
- to { stroke-dashoffset: -24; }
3267
+ to { stroke-dashoffset: -32; }
2925
3268
  }
2926
3269
  .markdy-edge {
2927
3270
  transition: opacity 0.2s ease;
2928
3271
  }
2929
3272
  .markdy-edge-path--flowing {
2930
- animation: markdy-flow-dash 1.2s linear infinite;
3273
+ animation: markdy-flow-dash 1.1s linear infinite;
2931
3274
  }
2932
3275
  .markdy-edge-path {
2933
3276
  transition: stroke 0.2s ease, stroke-width 0.2s ease, filter 0.2s ease;
@@ -2987,6 +3330,24 @@ function ensureSceneStyles(doc) {
2987
3330
  transform: translateY(8px);
2988
3331
  will-change: opacity, transform;
2989
3332
  }
3333
+ .markdy-scene-root[data-markdy-theme="ink"] .markdy-beat-caption {
3334
+ background: rgba(255, 255, 255, 0.96);
3335
+ border: 1.5px solid #1d4ed8;
3336
+ color: #1e3a8a;
3337
+ box-shadow:
3338
+ 2.5px 2.5px 0 rgba(29, 78, 216, 0.16),
3339
+ 0 10px 24px -6px rgba(29, 78, 216, 0.12);
3340
+ font-weight: 600;
3341
+ }
3342
+ .markdy-scene-root[data-markdy-theme="doodle"] .markdy-beat-caption {
3343
+ background: #ffffff;
3344
+ border: 2px solid #18181b;
3345
+ color: #18181b;
3346
+ border-radius: 255px 15px 225px 15px/15px 225px 15px 255px;
3347
+ box-shadow: 4px 4px 0 #18181b, 0 8px 20px -4px rgba(24, 24, 27, 0.12);
3348
+ font-weight: 800;
3349
+ padding: 10px 20px;
3350
+ }
2990
3351
  .markdy-diagram-root {
2991
3352
  position: relative;
2992
3353
  display: flex;
@@ -3639,6 +4000,10 @@ function applyThemeToScene(scene, theme) {
3639
4000
  }
3640
4001
 
3641
4002
  // src/export/svg-exporter.ts
4003
+ import {
4004
+ parseAndCompile,
4005
+ resolveTheme
4006
+ } from "@markdy/core";
3642
4007
  function copyRenderedStyles(source, clone) {
3643
4008
  if (typeof window === "undefined" || typeof window.getComputedStyle !== "function") return;
3644
4009
  const sourceElements = [source, ...Array.from(source.querySelectorAll("*"))];
@@ -3659,11 +4024,6 @@ function normalizeExportViewport(scene) {
3659
4024
  viewportTransform.style.willChange = "auto";
3660
4025
  });
3661
4026
  }
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
4027
  function prepareHtmlSceneForExport(sceneEl, options = {}) {
3668
4028
  const clonedScene = sceneEl.cloneNode(true);
3669
4029
  copyRenderedStyles(sceneEl, clonedScene);
@@ -3689,100 +4049,1486 @@ function prepareHtmlSceneForExport(sceneEl, options = {}) {
3689
4049
  }
3690
4050
  return { sceneEl, clonedScene, width, height, scaledWidth, scaledHeight };
3691
4051
  }
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");
4052
+ function escapeXml(str) {
4053
+ if (str === null || str === void 0) return "";
4054
+ return String(str).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
4055
+ }
4056
+ function dedupePoints2(points) {
4057
+ const out = [];
4058
+ for (const p of points) {
4059
+ const last = out[out.length - 1];
4060
+ if (!last || Math.abs(last.x - p.x) > 0.01 || Math.abs(last.y - p.y) > 0.01) out.push(p);
4061
+ }
4062
+ return out.length >= 2 ? out : points;
4063
+ }
4064
+ function circleBoundaryRoute2(from, to) {
4065
+ const fromCenter = { x: from.x + from.width / 2, y: from.y + from.height / 2 };
4066
+ const toCenter = { x: to.x + to.width / 2, y: to.y + to.height / 2 };
4067
+ const dx = toCenter.x - fromCenter.x;
4068
+ const dy = toCenter.y - fromCenter.y;
4069
+ const distance = Math.hypot(dx, dy) || 1;
4070
+ const ux = dx / distance;
4071
+ const uy = dy / distance;
4072
+ const fromRadius = Math.min(from.width, from.height) / 2;
4073
+ const toRadius = Math.min(to.width, to.height) / 2;
4074
+ return dedupePoints2([
4075
+ { x: fromCenter.x + ux * fromRadius, y: fromCenter.y + uy * fromRadius },
4076
+ { x: toCenter.x - ux * toRadius, y: toCenter.y - uy * toRadius }
4077
+ ]);
4078
+ }
4079
+ function snapPortToNodeShape2(node, port, neighbor, isSource) {
4080
+ if (!node.shape || node.shape === "card" || node.shape === "rounded" || node.shape === "terminal" || node.shape === "container") {
4081
+ return port;
4082
+ }
4083
+ const cx = node.x + node.width / 2;
4084
+ const cy = node.y + node.height / 2;
4085
+ const hw = node.width / 2;
4086
+ const hh = node.height / 2;
4087
+ if (node.shape === "diamond") {
4088
+ const isVert = Math.abs(port.x - neighbor.x) < 0.01;
4089
+ const isHoriz = Math.abs(port.y - neighbor.y) < 0.01;
4090
+ if (isVert) {
4091
+ const goingDown = isSource ? neighbor.y > port.y : port.y > neighbor.y;
4092
+ 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));
4093
+ return { x: port.x, y: Math.round(boundaryY * 10) / 10 };
4094
+ }
4095
+ if (isHoriz) {
4096
+ const goingRight = isSource ? neighbor.x > port.x : port.x > neighbor.x;
4097
+ 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));
4098
+ return { x: Math.round(boundaryX * 10) / 10, y: port.y };
3698
4099
  }
3699
- const serializer2 = new XMLSerializer();
3700
- return `<?xml version="1.0" encoding="UTF-8" standalone="no"?>
3701
- ${serializer2.serializeToString(clonedSvg)}`;
3702
4100
  }
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
- }
4101
+ if (node.shape === "circle") {
4102
+ const r = Math.min(node.width, node.height) / 2;
4103
+ const isVert = Math.abs(port.x - neighbor.x) < 0.01;
4104
+ const isHoriz = Math.abs(port.y - neighbor.y) < 0.01;
4105
+ if (isVert) {
4106
+ const goingDown = isSource ? neighbor.y > port.y : port.y > neighbor.y;
4107
+ return { x: cx, y: goingDown ? cy + r : cy - r };
4108
+ }
4109
+ if (isHoriz) {
4110
+ const goingRight = isSource ? neighbor.x > port.x : port.x > neighbor.x;
4111
+ return { x: goingRight ? cx + r : cx - r, y: cy };
3721
4112
  }
3722
- styleEl.textContent = combinedStyles;
3723
- svg.appendChild(styleEl);
3724
4113
  }
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);
4114
+ if (node.shape === "pill") {
4115
+ const r = node.height / 2;
4116
+ const isVert = Math.abs(port.x - neighbor.x) < 0.01;
4117
+ const isHoriz = Math.abs(port.y - neighbor.y) < 0.01;
4118
+ if (isHoriz) {
4119
+ const goingRight = isSource ? neighbor.x > port.x : port.x > neighbor.x;
4120
+ return { x: goingRight ? node.x + node.width : node.x, y: cy };
4121
+ }
4122
+ if (isVert) {
4123
+ const goingDown = isSource ? neighbor.y > port.y : port.y > neighbor.y;
4124
+ const clampedX = Math.max(node.x + r, Math.min(node.x + node.width - r, port.x));
4125
+ return { x: clampedX, y: goingDown ? node.y + node.height : node.y };
4126
+ }
4127
+ }
4128
+ return port;
3733
4129
  }
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)));
4130
+ function snapRouteEndpointsToShapes2(points, from, to) {
4131
+ if (points.length < 2) return points;
4132
+ const out = [...points];
4133
+ out[0] = snapPortToNodeShape2(from, out[0], out[1], true);
4134
+ out[out.length - 1] = snapPortToNodeShape2(to, out[out.length - 1], out[out.length - 2], false);
4135
+ return dedupePoints2(out);
3745
4136
  }
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;
4137
+ function routeEdgePoints2(from, to, routeObstacles, bounds, lane) {
4138
+ if (from.shape === "circle" && to.shape === "circle") return circleBoundaryRoute2(from, to);
4139
+ const raw = routeOrthogonal(boxRect(from), boxRect(to), routeObstacles, bounds, lane);
4140
+ return snapRouteEndpointsToShapes2(raw, from, to);
3758
4141
  }
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
- );
4142
+ function isDarkTheme2(theme) {
4143
+ if (theme.name === "paper" || theme.name === "editorial" || theme.name === "sketchy" || theme.name === "ink" || theme.name === "doodle") {
4144
+ return false;
3779
4145
  }
3780
- return anims;
4146
+ const canvas = (theme.canvas || theme.surface || "").trim();
4147
+ if (canvas.startsWith("#")) {
4148
+ const hex = canvas.slice(1);
4149
+ const r = parseInt(hex.length === 3 ? hex[0] + hex[0] : hex.slice(0, 2), 16) || 0;
4150
+ const g = parseInt(hex.length === 3 ? hex[1] + hex[1] : hex.slice(2, 4), 16) || 0;
4151
+ const b = parseInt(hex.length === 3 ? hex[2] + hex[2] : hex.slice(4, 6), 16) || 0;
4152
+ const luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255;
4153
+ return luminance < 0.5;
4154
+ }
4155
+ return true;
3781
4156
  }
3782
- function createDiagram(opts) {
3783
- const {
3784
- container,
3785
- code,
4157
+ function computeEdgeLabelColor2(edgeColor, isDark) {
4158
+ return isDark ? "#f8fafc" : "#0f172a";
4159
+ }
4160
+ var EDGE_STYLES2 = {
4161
+ request: { dash: "", marker: "arrow" },
4162
+ response: { dash: "6 4", marker: "arrow-open" },
4163
+ event: { dash: "2 6", marker: "dot" },
4164
+ dependency: { dash: "4 4", marker: "none" }
4165
+ };
4166
+ function wrapNodeLabel(label, maxWidthPx, fontSize = 13.5) {
4167
+ if (!label) return [];
4168
+ const avgCharWidth = fontSize * 0.52;
4169
+ const maxChars = Math.max(10, Math.floor(maxWidthPx / avgCharWidth));
4170
+ if (label.length <= maxChars) return [label];
4171
+ const words = label.trim().split(/\s+/);
4172
+ if (words.length <= 1) return [label];
4173
+ const lines = [];
4174
+ let current = "";
4175
+ for (const word of words) {
4176
+ if (!current) {
4177
+ current = word;
4178
+ } else if ((current + " " + word).length <= maxChars) {
4179
+ current += " " + word;
4180
+ } else {
4181
+ lines.push(current);
4182
+ current = word;
4183
+ if (lines.length === 2) break;
4184
+ }
4185
+ }
4186
+ if (current && lines.length < 3) {
4187
+ lines.push(current);
4188
+ }
4189
+ return lines;
4190
+ }
4191
+ function renderPureVectorSvg(plan, options = {}) {
4192
+ const width = plan.meta.width;
4193
+ const height = plan.meta.height;
4194
+ const theme = plan.theme || resolveTheme(plan.meta?.theme || "paper");
4195
+ const isDark = isDarkTheme2(theme);
4196
+ const canvasBg = options.transparentBackground ? "none" : theme.canvas || (isDark ? "#0b0f19" : "#f6f8fc");
4197
+ const surface = theme.surface || (isDark ? "#141c2e" : "#ffffff");
4198
+ const surfaceRaised = theme.surfaceRaised || (isDark ? "#1e293b" : "#f1f5f9");
4199
+ const border = theme.border || (isDark ? "#334155" : "#cbd5e1");
4200
+ const textColor = theme.text || (isDark ? "#f8fafc" : "#0f172a");
4201
+ const textMuted = theme.textMuted || (isDark ? "#94a3b8" : "#64748b");
4202
+ const accent = theme.accent || "#2563eb";
4203
+ const bounds = { width, height };
4204
+ const routeObstacles = [
4205
+ ...plan.nodes.map((n) => inflateRect(boxRect(n), 12)),
4206
+ ...(plan.groupBoundaries ?? []).map((gb) => boxRect(gb))
4207
+ ];
4208
+ const labelObstacles = plan.nodes.map((n) => inflateRect(boxRect(n), 6));
4209
+ const existingPaths = [];
4210
+ let svg = `<?xml version="1.0" encoding="UTF-8" standalone="no"?>
4211
+ <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}">
4212
+ <defs>
4213
+ <!-- Embedded Typography & Anti-Aliasing -->
4214
+ <style>
4215
+ text {
4216
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Inter, Roboto, "Helvetica Neue", Arial, sans-serif;
4217
+ text-rendering: geometricPrecision;
4218
+ -webkit-font-smoothing: antialiased;
4219
+ }
4220
+ .markdy-svg-text {
4221
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Inter, Roboto, "Helvetica Neue", Arial, sans-serif;
4222
+ text-rendering: geometricPrecision;
4223
+ -webkit-font-smoothing: antialiased;
4224
+ }
4225
+ .markdy-svg-mono {
4226
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
4227
+ text-rendering: geometricPrecision;
4228
+ -webkit-font-smoothing: antialiased;
4229
+ }
4230
+ </style>
4231
+
4232
+ <!-- Drop Shadow Filter -->
4233
+ <filter id="markdy-node-shadow" x="-10%" y="-10%" width="130%" height="130%">
4234
+ <feDropShadow dx="0" dy="4" stdDeviation="6" flood-color="#020617" flood-opacity="${isDark ? "0.45" : "0.12"}"/>
4235
+ <feDropShadow dx="0" dy="1" stdDeviation="2" flood-color="#020617" flood-opacity="${isDark ? "0.25" : "0.08"}"/>
4236
+ </filter>
4237
+
4238
+ <!-- Grid Patterns -->
4239
+ <pattern id="markdy-grid-minor" width="32" height="32" patternUnits="userSpaceOnUse">
4240
+ <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"/>
4241
+ </pattern>
4242
+ <pattern id="markdy-grid-major" width="160" height="160" patternUnits="userSpaceOnUse">
4243
+ <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"/>
4244
+ </pattern>
4245
+
4246
+ <!-- Arrowhead Markers -->
4247
+ <marker id="arrow-request" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto">
4248
+ <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}"/>
4249
+ </marker>
4250
+ <marker id="arrow-response" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto">
4251
+ <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"/>
4252
+ </marker>
4253
+ <marker id="arrow-event" viewBox="0 0 10 10" refX="5" refY="5" markerWidth="6" markerHeight="6" orient="auto">
4254
+ <circle cx="5" cy="5" r="3" fill="${theme.edges?.event || accent}"/>
4255
+ </marker>
4256
+ </defs>
4257
+
4258
+ <!-- Background -->
4259
+ ${options.transparentBackground ? "" : `
4260
+ <rect width="100%" height="100%" fill="${canvasBg}"/>
4261
+ <rect width="100%" height="100%" fill="url(#markdy-grid-minor)"/>
4262
+ <rect width="100%" height="100%" fill="url(#markdy-grid-major)"/>
4263
+ `}
4264
+ `;
4265
+ if (plan.title) {
4266
+ svg += `
4267
+ <!-- Diagram Title -->
4268
+ <g class="markdy-title-layer">
4269
+ <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>
4270
+ </g>
4271
+ `;
4272
+ }
4273
+ const cameraTransformAttr = options.cameraTransform && options.cameraTransform !== "none" ? ` transform="${escapeXml(options.cameraTransform)}"` : "";
4274
+ svg += ` <!-- Main Scene Content -->
4275
+ <g class="markdy-camera-layer"${cameraTransformAttr}>
4276
+ `;
4277
+ if (plan.groupBoundaries && plan.groupBoundaries.length > 0) {
4278
+ svg += ` <!-- Group Boundaries -->
4279
+ <g class="markdy-groups-layer">
4280
+ `;
4281
+ for (const gb of plan.groupBoundaries) {
4282
+ svg += ` <g id="group-${escapeXml(gb.id)}" transform="translate(${gb.x}, ${gb.y})">
4283
+ <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"/>
4284
+ `;
4285
+ if (gb.label) {
4286
+ const labelText = gb.label.toUpperCase();
4287
+ const labelW = Math.max(54, labelText.length * 6.8 + 20);
4288
+ svg += ` <rect x="14" y="10" width="${labelW}" height="20" rx="6" fill="${surfaceRaised}" fill-opacity="0.95" stroke="${border}" stroke-width="1"/>
4289
+ <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>
4290
+ `;
4291
+ }
4292
+ svg += ` </g>
4293
+ `;
4294
+ }
4295
+ svg += ` </g>
4296
+ `;
4297
+ }
4298
+ if (plan.treeBuses && plan.treeBuses.length > 0) {
4299
+ svg += ` <!-- Tree Buses -->
4300
+ <g class="markdy-tree-layer">
4301
+ `;
4302
+ const busStroke = theme.edges?.dependency ?? theme.border ?? "#64748b";
4303
+ for (const bus of plan.treeBuses) {
4304
+ for (const childX of bus.childXs) {
4305
+ let d;
4306
+ if (Math.abs(childX - bus.parentX) < 1) {
4307
+ d = toPathD([
4308
+ { x: bus.parentX, y: bus.parentY },
4309
+ { x: childX, y: bus.childY }
4310
+ ], 12);
4311
+ } else {
4312
+ d = toPathD([
4313
+ { x: bus.parentX, y: bus.parentY },
4314
+ { x: bus.parentX, y: bus.branchY },
4315
+ { x: childX, y: bus.branchY },
4316
+ { x: childX, y: bus.childY }
4317
+ ], 12);
4318
+ }
4319
+ svg += ` <path d="${d}" fill="none" stroke="${busStroke}" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/>
4320
+ `;
4321
+ }
4322
+ }
4323
+ svg += ` </g>
4324
+ `;
4325
+ }
4326
+ if (plan.diagramType === "sequence") {
4327
+ svg += ` <!-- Sequence Layer -->
4328
+ <g class="markdy-sequence-layer">
4329
+ `;
4330
+ const nodeById = new Map(plan.nodes.map((node) => [node.id, node]));
4331
+ const centerX = (id) => {
4332
+ const node = nodeById.get(id);
4333
+ return node ? node.x + node.width / 2 : 0;
4334
+ };
4335
+ const lifelineStroke = theme.edges?.dependency ?? theme.rule ?? theme.border ?? "#64748b";
4336
+ for (const node of plan.nodes) {
4337
+ const x = centerX(node.id);
4338
+ const y1 = node.y + node.height;
4339
+ const y2 = Math.max(y1 + 40, height - 36);
4340
+ 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"/>
4341
+ `;
4342
+ svg += ` <circle class="markdy-sequence-lifeline-cap" cx="${x}" cy="${y2}" r="2.5" fill="${lifelineStroke}" opacity="0.85"/>
4343
+ `;
4344
+ }
4345
+ if (plan.sequenceActivations) {
4346
+ plan.sequenceActivations.forEach((activation, idx) => {
4347
+ const x = centerX(activation.participant);
4348
+ const actState = options.sequenceActivationStates?.get(idx);
4349
+ const actOpacity = actState !== void 0 ? actState.opacity : options.sequenceActivationStates ? 0 : 0.9;
4350
+ if (actOpacity > 1e-3) {
4351
+ const opacityAttr = actOpacity < 0.999 ? `opacity="${actOpacity}"` : "";
4352
+ svg += ` <rect class="markdy-sequence-activation" x="${x - 6}" y="${activation.y}" width="12" height="${activation.height}" rx="4" fill="${accent}" ${opacityAttr}/>
4353
+ `;
4354
+ }
4355
+ });
4356
+ }
4357
+ if (plan.sequenceMessages) {
4358
+ for (const msg of plan.sequenceMessages) {
4359
+ const fromX = centerX(msg.from);
4360
+ const toX = centerX(msg.to);
4361
+ const msgColor = theme.edges?.[msg.kind] || accent;
4362
+ const markerAttr = msg.kind === "response" ? 'marker-end="url(#arrow-response)"' : 'marker-end="url(#arrow-request)"';
4363
+ const dashAttr = msg.kind === "response" ? 'stroke-dasharray="6 4"' : msg.kind === "event" ? 'stroke-dasharray="2 6"' : "";
4364
+ const msgState = options.sequenceMessageStates?.get(msg.id);
4365
+ const msgOpacity = msgState !== void 0 ? msgState.opacity : 1;
4366
+ if (msgOpacity <= 1e-3) continue;
4367
+ const opacityAttr = msgOpacity < 0.999 ? `opacity="${msgOpacity}"` : "";
4368
+ svg += ` <g class="markdy-sequence-message" data-message="${escapeXml(msg.id)}" ${opacityAttr}>
4369
+ <line x1="${fromX}" y1="${msg.y}" x2="${toX}" y2="${msg.y}" stroke="${msgColor}" stroke-width="2" stroke-linecap="round" ${dashAttr} ${markerAttr}/>
4370
+ `;
4371
+ if (msg.label) {
4372
+ const midX = (fromX + toX) / 2;
4373
+ const msgPlateW = msg.label.length * 6.8 + 16;
4374
+ const plateFill = theme.labelPlate ?? theme.surface ?? (isDark ? "#1e293b" : "#ffffff");
4375
+ const plateStroke = theme.hairline ?? theme.border ?? (isDark ? "#334155" : "#cbd5e1");
4376
+ 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"/>
4377
+ <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>
4378
+ `;
4379
+ }
4380
+ svg += ` </g>
4381
+ `;
4382
+ }
4383
+ }
4384
+ svg += ` </g>
4385
+ `;
4386
+ }
4387
+ if (plan.diagramType !== "sequence" && plan.edges && plan.edges.length > 0) {
4388
+ svg += ` <!-- Edge Connections -->
4389
+ <g class="markdy-edges-layer">
4390
+ `;
4391
+ const nodeMap = new Map(plan.nodes.map((n) => [n.id, n]));
4392
+ plan.edges.forEach((edge, index) => {
4393
+ const from = nodeMap.get(edge.from);
4394
+ const to = nodeMap.get(edge.to);
4395
+ if (!from || !to) return;
4396
+ const edgeState = edge.id ? options.edgeStates?.get(edge.id) : void 0;
4397
+ const edgeOpacity = edgeState ? edgeState.opacity : 1;
4398
+ if (edgeOpacity <= 1e-3) return;
4399
+ const color = theme.edges?.[edge.kind] || accent;
4400
+ const style = EDGE_STYLES2[edge.kind] || EDGE_STYLES2.request;
4401
+ const isSelfLoop = from.id === to.id;
4402
+ const points = isSelfLoop ? dedupePoints2(selfLoopPath(from, bounds)) : dedupePoints2(routeEdgePoints2(from, to, routeObstacles, bounds, index));
4403
+ const d = toPathD(points, 14, existingPaths);
4404
+ existingPaths.push(points);
4405
+ 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)"' : "";
4406
+ const dashAttr = style.dash ? `stroke-dasharray="${style.dash}"` : "";
4407
+ const dashOffsetAttr = edgeState?.strokeDashoffset && edgeState.strokeDashoffset !== "0px" && edgeState.strokeDashoffset !== "0" ? `stroke-dashoffset="${escapeXml(edgeState.strokeDashoffset)}"` : "";
4408
+ const opacityAttr = edgeOpacity < 0.999 ? `opacity="${edgeOpacity}"` : "";
4409
+ svg += ` <g id="edge-${escapeXml(edge.id || `flow_${index}`)}" class="markdy-edge" ${opacityAttr}>
4410
+ <path d="${d}" fill="none" stroke="${color}" stroke-width="${edge.kind === "dependency" ? "1.5" : "2"}" stroke-linecap="round" stroke-linejoin="round" ${dashAttr} ${dashOffsetAttr} ${markerAttr}/>
4411
+ `;
4412
+ if (edge.label) {
4413
+ let longestSegLen = 0;
4414
+ for (let i = 0; i < points.length - 1; i++) {
4415
+ longestSegLen = Math.max(longestSegLen, Math.hypot(points[i + 1].x - points[i].x, points[i + 1].y - points[i].y));
4416
+ }
4417
+ const maxAvailW = Math.max(48, longestSegLen - 24);
4418
+ const lines = wrapFlowLabelText(edge.label, maxAvailW);
4419
+ const maxChars = Math.max(...lines.map((l) => l.length));
4420
+ const textWidth = Math.max(36, maxChars * 6.6 + 8);
4421
+ const lineHeight = 13;
4422
+ const boxHeight = lines.length === 1 ? 18 : lines.length * lineHeight + 6;
4423
+ const placement = placeFlowLabel(points, textWidth, labelObstacles, bounds, boxHeight);
4424
+ const padX = 6;
4425
+ const halfW = textWidth / 2;
4426
+ const labelX = placement.x - halfW - padX;
4427
+ const labelY = placement.y - boxHeight / 2;
4428
+ const labelColor = computeEdgeLabelColor2(color, isDark);
4429
+ svg += ` <!-- Edge Label -->
4430
+ <rect x="${labelX}" y="${labelY}" width="${textWidth + padX * 2}" height="${boxHeight}" rx="4" fill="${canvasBg}" stroke="${border}" stroke-width="1"/>
4431
+ `;
4432
+ if (lines.length === 1) {
4433
+ 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>
4434
+ `;
4435
+ } else {
4436
+ lines.forEach((lineText, idx) => {
4437
+ const lineY = placement.y - (lines.length - 1) * lineHeight / 2 + idx * lineHeight;
4438
+ 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>
4439
+ `;
4440
+ });
4441
+ }
4442
+ }
4443
+ svg += ` </g>
4444
+ `;
4445
+ });
4446
+ svg += ` </g>
4447
+ `;
4448
+ }
4449
+ svg += ` <!-- Node Cards -->
4450
+ <g class="markdy-nodes-layer">
4451
+ `;
4452
+ for (const node of plan.nodes) {
4453
+ const nodeState = options.nodeStates?.get(node.id);
4454
+ const nodeOpacity = nodeState ? nodeState.opacity : 1;
4455
+ if (nodeOpacity <= 1e-3) continue;
4456
+ const roleColor = theme.roles && theme.roles[node.role] || accent;
4457
+ const iconKey = iconKeyForNode(node);
4458
+ const glyphSpec = ICON_REGISTRY[iconKey] || ICON_REGISTRY.service;
4459
+ const isDiamond = node.shape === "diamond";
4460
+ const isCircle = node.shape === "circle";
4461
+ const isPill = node.shape === "pill";
4462
+ const transformStr = nodeState?.transform && nodeState.transform !== "none" ? `translate(${node.x}, ${node.y}) ${nodeState.transform}` : `translate(${node.x}, ${node.y})`;
4463
+ const opacityAttr = nodeOpacity < 0.999 ? `opacity="${nodeOpacity}"` : "";
4464
+ svg += ` <g id="node-${escapeXml(node.id)}" transform="${escapeXml(transformStr)}" ${opacityAttr}>
4465
+ `;
4466
+ if (isDiamond) {
4467
+ const hw = node.width / 2;
4468
+ const hh = node.height / 2;
4469
+ 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)"/>
4470
+ `;
4471
+ } else if (isCircle) {
4472
+ const r = Math.min(node.width, node.height) / 2;
4473
+ svg += ` <circle cx="${node.width / 2}" cy="${node.height / 2}" r="${r}" fill="${surface}" stroke="${border}" stroke-width="1" filter="url(#markdy-node-shadow)"/>
4474
+ `;
4475
+ } else if (isPill) {
4476
+ svg += ` <rect width="${node.width}" height="${node.height}" rx="${node.height / 2}" fill="${surface}" stroke="${border}" stroke-width="1" filter="url(#markdy-node-shadow)"/>
4477
+ `;
4478
+ } else {
4479
+ const rx = node.shape === "terminal" ? "8" : node.shape === "rounded" ? "16" : "12";
4480
+ svg += ` <rect width="${node.width}" height="${node.height}" rx="${rx}" fill="${surface}" stroke="${border}" stroke-width="1" filter="url(#markdy-node-shadow)"/>
4481
+ <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"/>
4482
+ `;
4483
+ }
4484
+ const hasTech = Boolean(node.props?.tech || node.props?.sub);
4485
+ const techText = String(node.props?.tech || node.props?.sub || "");
4486
+ const value = node.props?.value ?? node.props?.metric;
4487
+ const valText = value !== void 0 && value !== null ? String(value) : "";
4488
+ const valWidth = valText ? valText.length * 9.5 + 16 : 0;
4489
+ const iconSize = 26;
4490
+ if (isDiamond) {
4491
+ const availTextWidth = Math.max(40, node.width * 0.65);
4492
+ const lines = wrapNodeLabel(node.label, availTextWidth, 12.5);
4493
+ const centerX = node.width / 2;
4494
+ if (hasTech) {
4495
+ const labelCenterY = node.height / 2 - 8;
4496
+ if (lines.length === 1) {
4497
+ 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>
4498
+ `;
4499
+ } else {
4500
+ const startY = labelCenterY - (lines.length - 1) * 14 / 2;
4501
+ lines.forEach((l, idx) => {
4502
+ 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>
4503
+ `;
4504
+ });
4505
+ }
4506
+ const techBadgeW = Math.min(availTextWidth, techText.length * 6.2 + 12);
4507
+ const techBadgeY = node.height / 2 + 5;
4508
+ 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"/>
4509
+ <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>
4510
+ `;
4511
+ } else {
4512
+ if (lines.length === 1) {
4513
+ 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>
4514
+ `;
4515
+ } else {
4516
+ const startY = node.height / 2 - (lines.length - 1) * 15 / 2;
4517
+ lines.forEach((l, idx) => {
4518
+ 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>
4519
+ `;
4520
+ });
4521
+ }
4522
+ }
4523
+ } else if (isCircle) {
4524
+ const centerX = node.width / 2;
4525
+ const availTextWidth = Math.max(40, node.width * 0.72);
4526
+ const lines = wrapNodeLabel(node.label, availTextWidth, 11.5);
4527
+ const circleIconSize = 20;
4528
+ const iconX = (node.width - circleIconSize) / 2;
4529
+ const iconY = node.height / 2 - 20;
4530
+ const rawImage = node.props?.image ?? node.props?.logo;
4531
+ if (typeof rawImage === "string" && rawImage.length > 0) {
4532
+ svg += ` <!-- Centered Custom Image -->
4533
+ <image href="${escapeXml(rawImage)}" x="${iconX}" y="${iconY}" width="${circleIconSize}" height="${circleIconSize}" preserveAspectRatio="xMidYMid meet"/>
4534
+ `;
4535
+ } else {
4536
+ svg += ` <!-- Centered Icon Glyph -->
4537
+ <g transform="translate(${iconX}, ${iconY}) scale(${circleIconSize / 24})" fill="none" stroke="${roleColor}" stroke-width="1.85" stroke-linecap="round" stroke-linejoin="round">
4538
+ `;
4539
+ if (glyphSpec) {
4540
+ for (const [tag, attrs] of glyphSpec) {
4541
+ const attrStr = Object.entries(attrs).map(([k, v]) => `${k}="${escapeXml(v)}"`).join(" ");
4542
+ svg += ` <${tag} ${attrStr} />
4543
+ `;
4544
+ }
4545
+ }
4546
+ svg += ` </g>
4547
+ `;
4548
+ }
4549
+ const textCenterY = node.height / 2 + 10;
4550
+ if (lines.length === 1) {
4551
+ 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>
4552
+ `;
4553
+ } else {
4554
+ const startY = textCenterY - (lines.length - 1) * 13 / 2;
4555
+ lines.forEach((l, idx) => {
4556
+ 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>
4557
+ `;
4558
+ });
4559
+ }
4560
+ } else {
4561
+ const iconX = 16;
4562
+ const iconY = (node.height - iconSize) / 2;
4563
+ const rawImage = node.props?.image ?? node.props?.logo;
4564
+ if (typeof rawImage === "string" && rawImage.length > 0) {
4565
+ svg += ` <!-- Node Custom Image -->
4566
+ <image href="${escapeXml(rawImage)}" x="${iconX}" y="${iconY}" width="${iconSize}" height="${iconSize}" preserveAspectRatio="xMidYMid meet"/>
4567
+ `;
4568
+ } else {
4569
+ svg += ` <!-- Frameless Icon Glyph -->
4570
+ <g transform="translate(${iconX}, ${iconY}) scale(${iconSize / 24})" fill="none" stroke="${roleColor}" stroke-width="1.85" stroke-linecap="round" stroke-linejoin="round">
4571
+ `;
4572
+ if (glyphSpec) {
4573
+ for (const [tag, attrs] of glyphSpec) {
4574
+ const attrStr = Object.entries(attrs).map(([k, v]) => `${k}="${escapeXml(v)}"`).join(" ");
4575
+ svg += ` <${tag} ${attrStr} />
4576
+ `;
4577
+ }
4578
+ }
4579
+ svg += ` </g>
4580
+ `;
4581
+ }
4582
+ const textStartX = 54;
4583
+ const availTextWidth = node.width - textStartX - (valWidth > 0 ? valWidth + 14 : 14);
4584
+ const lines = wrapNodeLabel(node.label, availTextWidth, 13.5);
4585
+ if (hasTech) {
4586
+ const labelCenterY = Math.round(node.height / 2 - 8);
4587
+ if (lines.length === 1) {
4588
+ svg += ` <!-- Label -->
4589
+ <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>
4590
+ `;
4591
+ } else {
4592
+ const startY = Math.round(labelCenterY - (lines.length - 1) * 14 / 2);
4593
+ svg += ` <!-- Label -->
4594
+ <text class="markdy-svg-text" font-size="12.5" font-weight="600" letter-spacing="-0.01em" fill="${textColor}">
4595
+ `;
4596
+ lines.forEach((l, idx) => {
4597
+ svg += ` <tspan x="${textStartX}" y="${startY + idx * 14}" dominant-baseline="central">${escapeXml(l)}</tspan>
4598
+ `;
4599
+ });
4600
+ svg += ` </text>
4601
+ `;
4602
+ }
4603
+ const techBadgeW = Math.min(availTextWidth, techText.length * 6.2 + 12);
4604
+ const techBadgeY = Math.round(node.height / 2 + 5);
4605
+ svg += ` <!-- Tech Badge -->
4606
+ <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"/>
4607
+ <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>
4608
+ `;
4609
+ } else {
4610
+ if (lines.length === 1) {
4611
+ svg += ` <!-- Label -->
4612
+ <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>
4613
+ `;
4614
+ } else if (lines.length === 2) {
4615
+ const startY = Math.round(node.height / 2 - 8);
4616
+ svg += ` <!-- Label -->
4617
+ <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>
4618
+ <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>
4619
+ `;
4620
+ } else {
4621
+ const startY = Math.round(node.height / 2 - 15);
4622
+ svg += ` <!-- Label -->
4623
+ <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>
4624
+ <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>
4625
+ <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>
4626
+ `;
4627
+ }
4628
+ }
4629
+ }
4630
+ if (valText) {
4631
+ svg += ` <!-- Metric Value -->
4632
+ <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>
4633
+ `;
4634
+ }
4635
+ svg += ` </g>
4636
+ `;
4637
+ }
4638
+ svg += ` </g>
4639
+ `;
4640
+ if (options.flowDots && options.flowDots.length > 0) {
4641
+ svg += ` <!-- Flow Particles -->
4642
+ <g class="markdy-flow-particles">
4643
+ `;
4644
+ for (const dot of options.flowDots) {
4645
+ if (dot.opacity > 1e-3) {
4646
+ svg += ` <circle cx="${dot.x}" cy="${dot.y}" r="${dot.r}" fill="${dot.fill}" opacity="${dot.opacity}"/>
4647
+ `;
4648
+ }
4649
+ }
4650
+ svg += ` </g>
4651
+ `;
4652
+ }
4653
+ svg += ` </g>
4654
+ `;
4655
+ if (options.activeCaption && options.activeCaption.opacity > 0.01 && options.activeCaption.text) {
4656
+ const capX = width / 2;
4657
+ const capY = height - 32;
4658
+ const capW = options.activeCaption.text.length * 7.5 + 28;
4659
+ svg += ` <!-- Live Beat Caption -->
4660
+ <g class="markdy-live-caption" opacity="${options.activeCaption.opacity}">
4661
+ `;
4662
+ 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)"/>
4663
+ `;
4664
+ 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>
4665
+ `;
4666
+ svg += ` </g>
4667
+ `;
4668
+ }
4669
+ svg += `
4670
+ <!-- Watermark -->
4671
+ <g class="markdy-watermark" transform="translate(${width - 120}, ${height - 18})">
4672
+ <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>
4673
+ </g>
4674
+ </svg>`;
4675
+ return svg;
4676
+ }
4677
+ function exportLiveSceneAsPureVectorSvg(containerEl, options = {}) {
4678
+ const sceneEl = containerEl.classList?.contains("markdy-scene-root") ? containerEl : containerEl.querySelector(".markdy-scene-root") || containerEl;
4679
+ const rootEl = containerEl.classList?.contains("markdy-diagram-root") ? containerEl : containerEl.closest?.(".markdy-diagram-root") || containerEl;
4680
+ const storedPlan = rootEl.__markdyPlan || sceneEl.__markdyPlan || containerEl.__markdyPlan;
4681
+ const storedCode = rootEl.__markdyCode || sceneEl.__markdyCode || containerEl.__markdyCode;
4682
+ let plan = storedPlan ?? null;
4683
+ if (!plan && storedCode && typeof storedCode === "string") {
4684
+ try {
4685
+ plan = parseAndCompile(storedCode).plan;
4686
+ } catch {
4687
+ plan = null;
4688
+ }
4689
+ }
4690
+ if (plan) {
4691
+ const nodeStates = /* @__PURE__ */ new Map();
4692
+ const edgeStates = /* @__PURE__ */ new Map();
4693
+ const sequenceMessageStates = /* @__PURE__ */ new Map();
4694
+ const sequenceActivationStates = /* @__PURE__ */ new Map();
4695
+ const flowDots = [];
4696
+ let activeCaption;
4697
+ let cameraTransform;
4698
+ if (typeof window !== "undefined" && typeof window.getComputedStyle === "function") {
4699
+ const cameraEl = sceneEl.querySelector(".markdy-camera-layer");
4700
+ if (cameraEl) {
4701
+ const comp = window.getComputedStyle(cameraEl);
4702
+ if (comp.transform && comp.transform !== "none") {
4703
+ cameraTransform = comp.transform;
4704
+ }
4705
+ }
4706
+ for (const node of plan.nodes) {
4707
+ const nodeEl = sceneEl.querySelector(`[data-node="${node.id}"], [data-node-id="${node.id}"], #node-${node.id}`);
4708
+ if (nodeEl) {
4709
+ const comp = window.getComputedStyle(nodeEl);
4710
+ const opacity = comp.display === "none" || comp.visibility === "hidden" ? 0 : parseFloat(comp.opacity || "1");
4711
+ nodeStates.set(node.id, {
4712
+ opacity: isNaN(opacity) ? 1 : opacity,
4713
+ transform: comp.transform && comp.transform !== "none" ? comp.transform : void 0
4714
+ });
4715
+ }
4716
+ }
4717
+ for (const edge of plan.edges) {
4718
+ const edgeId = edge.id;
4719
+ if (edgeId) {
4720
+ const edgeEl = sceneEl.querySelector(`[data-edge-id="${edgeId}"], [data-edge="${edgeId}"], #edge-${edgeId}`);
4721
+ if (edgeEl) {
4722
+ const comp = window.getComputedStyle(edgeEl);
4723
+ const opacity = comp.display === "none" || comp.visibility === "hidden" ? 0 : parseFloat(comp.opacity || "1");
4724
+ const pathEl = edgeEl.querySelector(".markdy-edge-path");
4725
+ const pathComp = pathEl ? window.getComputedStyle(pathEl) : comp;
4726
+ edgeStates.set(edgeId, {
4727
+ opacity: isNaN(opacity) ? 1 : opacity,
4728
+ strokeDashoffset: pathComp.strokeDashoffset && pathComp.strokeDashoffset !== "0px" ? pathComp.strokeDashoffset : void 0
4729
+ });
4730
+ }
4731
+ }
4732
+ }
4733
+ const seqMsgEls = sceneEl.querySelectorAll(".markdy-sequence-message, [data-message], [data-message-id]");
4734
+ seqMsgEls.forEach((msgEl) => {
4735
+ const msgId = msgEl.getAttribute("data-message") || msgEl.getAttribute("data-message-id");
4736
+ if (msgId) {
4737
+ const comp = window.getComputedStyle(msgEl);
4738
+ const opacity = comp.display === "none" || comp.visibility === "hidden" ? 0 : parseFloat(comp.opacity || "1");
4739
+ sequenceMessageStates.set(msgId, {
4740
+ opacity: isNaN(opacity) ? 1 : opacity
4741
+ });
4742
+ }
4743
+ });
4744
+ const seqActEls = sceneEl.querySelectorAll(".markdy-sequence-activation");
4745
+ seqActEls.forEach((actEl, idx) => {
4746
+ const indexAttr = actEl.getAttribute("data-activation-index");
4747
+ const actIndex = indexAttr ? parseInt(indexAttr, 10) : idx;
4748
+ const comp = window.getComputedStyle(actEl);
4749
+ const opacity = comp.display === "none" || comp.visibility === "hidden" ? 0 : parseFloat(comp.opacity || "1");
4750
+ sequenceActivationStates.set(actIndex, {
4751
+ opacity: isNaN(opacity) ? 0 : opacity
4752
+ });
4753
+ });
4754
+ const dotEls = sceneEl.querySelectorAll(".markdy-edge-dot, .markdy-sequence-pulse");
4755
+ dotEls.forEach((dotEl) => {
4756
+ const comp = window.getComputedStyle(dotEl);
4757
+ const opacity = comp.display === "none" || comp.visibility === "hidden" ? 0 : parseFloat(comp.opacity || "0");
4758
+ if (opacity > 0.01) {
4759
+ const transform = comp.transform;
4760
+ let tx = 0;
4761
+ let ty = 0;
4762
+ if (transform && transform !== "none") {
4763
+ const matrixMatch = transform.match(/matrix\(([^)]+)\)/);
4764
+ if (matrixMatch) {
4765
+ const parts = matrixMatch[1].split(",").map(Number);
4766
+ tx = parts[4] || 0;
4767
+ ty = parts[5] || 0;
4768
+ } else {
4769
+ const translateMatch = transform.match(/translate\(([^,]+)px,\s*([^)]+)px\)/);
4770
+ if (translateMatch) {
4771
+ tx = parseFloat(translateMatch[1]) || 0;
4772
+ ty = parseFloat(translateMatch[2]) || 0;
4773
+ }
4774
+ }
4775
+ }
4776
+ const cx = parseFloat(dotEl.getAttribute("cx") || "0") + tx;
4777
+ const cy = parseFloat(dotEl.getAttribute("cy") || "0") + ty;
4778
+ const r = parseFloat(dotEl.getAttribute("r") || "4.5");
4779
+ const fill = comp.fill || dotEl.getAttribute("fill") || "#38bdf8";
4780
+ flowDots.push({ x: cx, y: cy, r, fill, opacity });
4781
+ }
4782
+ });
4783
+ const capEls = sceneEl.querySelectorAll(".markdy-beat-caption");
4784
+ for (const capEl of Array.from(capEls)) {
4785
+ const comp = window.getComputedStyle(capEl);
4786
+ const opacity = comp.display === "none" || comp.visibility === "hidden" ? 0 : parseFloat(comp.opacity || "0");
4787
+ if (opacity > 0.05 && capEl.textContent) {
4788
+ activeCaption = {
4789
+ text: capEl.textContent.trim(),
4790
+ opacity
4791
+ };
4792
+ break;
4793
+ }
4794
+ }
4795
+ return renderPureVectorSvg(plan, {
4796
+ ...options,
4797
+ nodeStates,
4798
+ edgeStates,
4799
+ sequenceMessageStates,
4800
+ sequenceActivationStates,
4801
+ flowDots,
4802
+ activeCaption,
4803
+ cameraTransform
4804
+ });
4805
+ }
4806
+ return renderPureVectorSvg(plan, {
4807
+ ...options,
4808
+ nodeStates,
4809
+ edgeStates,
4810
+ cameraTransform
4811
+ });
4812
+ }
4813
+ return exportDiagramAsVectorSvg(containerEl, { ...options, mode: "pure" });
4814
+ }
4815
+ function exportDiagramAsVectorSvg(target, options = {}) {
4816
+ if (typeof target === "string") {
4817
+ const { plan } = parseAndCompile(target);
4818
+ return renderPureVectorSvg(plan, options);
4819
+ }
4820
+ if (typeof target === "object" && target !== null && "meta" in target && "nodes" in target) {
4821
+ return renderPureVectorSvg(target, options);
4822
+ }
4823
+ if (typeof HTMLElement !== "undefined" && target instanceof HTMLElement) {
4824
+ const rootEl = target.classList?.contains("markdy-diagram-root") ? target : target.closest?.(".markdy-diagram-root") || target;
4825
+ const storedCode = rootEl.__markdyCode || target.__markdyCode;
4826
+ if (storedCode && typeof storedCode === "string") {
4827
+ const { plan } = parseAndCompile(storedCode);
4828
+ return renderPureVectorSvg(plan, options);
4829
+ }
4830
+ const storedPlan = rootEl.__markdyPlan || target.__markdyPlan;
4831
+ if (storedPlan && typeof storedPlan === "object" && "meta" in storedPlan) {
4832
+ return renderPureVectorSvg(storedPlan, options);
4833
+ }
4834
+ if (target.tagName?.toLowerCase() === "svg") {
4835
+ const clonedSvg = target.cloneNode(true);
4836
+ if (!clonedSvg.getAttribute("xmlns")) {
4837
+ clonedSvg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
4838
+ }
4839
+ const serializer = new XMLSerializer();
4840
+ return `<?xml version="1.0" encoding="UTF-8" standalone="no"?>
4841
+ ${serializer.serializeToString(clonedSvg)}`;
4842
+ }
4843
+ }
4844
+ const sceneEl = typeof HTMLElement !== "undefined" && target instanceof HTMLElement ? target.querySelector(".markdy-scene-root") || target : null;
4845
+ if (sceneEl) {
4846
+ const { clonedScene, scaledWidth, scaledHeight } = prepareHtmlSceneForExport(sceneEl, options);
4847
+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
4848
+ svg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
4849
+ svg.setAttribute("width", String(scaledWidth));
4850
+ svg.setAttribute("height", String(scaledHeight));
4851
+ svg.setAttribute("viewBox", `0 0 ${scaledWidth} ${scaledHeight}`);
4852
+ const foreignObject = document.createElementNS("http://www.w3.org/2000/svg", "foreignObject");
4853
+ foreignObject.setAttribute("width", "100%");
4854
+ foreignObject.setAttribute("height", "100%");
4855
+ foreignObject.appendChild(clonedScene);
4856
+ svg.appendChild(foreignObject);
4857
+ const serializer = new XMLSerializer();
4858
+ return `<?xml version="1.0" encoding="UTF-8" standalone="no"?>
4859
+ ` + serializer.serializeToString(svg);
4860
+ }
4861
+ throw new Error("Could not export diagram: invalid target or missing Markdy script.");
4862
+ }
4863
+
4864
+ // src/export/inline-resources.ts
4865
+ var TRANSPARENT_PIXEL_DATA_URI = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
4866
+ var RESOURCE_FETCH_TIMEOUT_MS = 3e3;
4867
+ var dataUriCache = /* @__PURE__ */ new Map();
4868
+ function shouldInlineUrl(url) {
4869
+ const trimmed = url.trim();
4870
+ return !!trimmed && !trimmed.startsWith("data:") && !trimmed.startsWith("blob:") && !trimmed.startsWith("#");
4871
+ }
4872
+ async function toDataUri(url) {
4873
+ if (dataUriCache.has(url)) return dataUriCache.get(url);
4874
+ const request = (async () => {
4875
+ const controller = new AbortController();
4876
+ const timeout = setTimeout(() => controller.abort(), RESOURCE_FETCH_TIMEOUT_MS);
4877
+ try {
4878
+ const resp = await fetch(url, { mode: "cors", credentials: "same-origin", signal: controller.signal });
4879
+ if (!resp.ok) return null;
4880
+ const arrayBuffer = await resp.arrayBuffer();
4881
+ const mimeType = resp.headers.get("Content-Type") || "application/octet-stream";
4882
+ const base64 = btoa(
4883
+ new Uint8Array(arrayBuffer).reduce((data, byte) => data + String.fromCharCode(byte), "")
4884
+ );
4885
+ return `data:${mimeType};base64,${base64}`;
4886
+ } catch {
4887
+ return null;
4888
+ } finally {
4889
+ clearTimeout(timeout);
4890
+ }
4891
+ })();
4892
+ dataUriCache.set(url, request);
4893
+ return request;
4894
+ }
4895
+ async function inlineCssUrls(cssValue) {
4896
+ const urlPattern = /url\(["']?([^"')]+)["']?\)/g;
4897
+ const matches = [];
4898
+ let m;
4899
+ while ((m = urlPattern.exec(cssValue)) !== null) {
4900
+ const src = m[1];
4901
+ if (shouldInlineUrl(src)) {
4902
+ matches.push({ full: m[0], src });
4903
+ }
4904
+ }
4905
+ let result = cssValue;
4906
+ await Promise.all(
4907
+ matches.map(async ({ full, src }) => {
4908
+ try {
4909
+ const absoluteSrc = new URL(src, document.baseURI).href;
4910
+ const dataUri = await toDataUri(absoluteSrc);
4911
+ result = result.split(full).join(dataUri ? `url("${dataUri}")` : "none");
4912
+ } catch {
4913
+ result = result.split(full).join("none");
4914
+ }
4915
+ })
4916
+ );
4917
+ return result;
4918
+ }
4919
+ async function inlineExternalResources(root) {
4920
+ const tasks = [];
4921
+ root.querySelectorAll("img").forEach((img) => {
4922
+ const src = img.getAttribute("src");
4923
+ if (src && shouldInlineUrl(src)) {
4924
+ tasks.push(
4925
+ Promise.resolve().then(() => toDataUri(new URL(src, document.baseURI).href)).then((dataUri) => {
4926
+ img.setAttribute("src", dataUri || TRANSPARENT_PIXEL_DATA_URI);
4927
+ })
4928
+ );
4929
+ }
4930
+ });
4931
+ const allEls = [root, ...Array.from(root.querySelectorAll("*"))];
4932
+ allEls.forEach((el) => {
4933
+ const style = el.getAttribute("style");
4934
+ if (style && style.includes("url(")) {
4935
+ tasks.push(
4936
+ inlineCssUrls(style).then((inlined) => {
4937
+ if (inlined !== style) el.setAttribute("style", inlined);
4938
+ })
4939
+ );
4940
+ }
4941
+ });
4942
+ await Promise.all(tasks);
4943
+ }
4944
+ async function inlineSerializedSvgResources(svgXml) {
4945
+ const doc = new DOMParser().parseFromString(svgXml, "image/svg+xml");
4946
+ if (doc.querySelector("parsererror")) return svgXml;
4947
+ await inlineExternalResources(doc.documentElement);
4948
+ const serializer = new XMLSerializer();
4949
+ const serializedSvg = serializer.serializeToString(doc.documentElement);
4950
+ return `<?xml version="1.0" encoding="UTF-8" standalone="no"?>
4951
+ ${serializedSvg}`;
4952
+ }
4953
+
4954
+ // src/export/png-exporter.ts
4955
+ async function exportDiagramAsPng(containerEl, options = {}) {
4956
+ const canvas = await rasterizeDiagramToCanvas(containerEl, options, options.pixelRatio || 2);
4957
+ return new Promise((resolve, reject) => {
4958
+ canvas.toBlob((b) => {
4959
+ if (b) resolve(b);
4960
+ else reject(new Error("Canvas toBlob failed for PNG export"));
4961
+ }, "image/png");
4962
+ });
4963
+ }
4964
+ async function rasterizeDiagramToCanvas(containerEl, options = {}, pixelRatio = 1) {
4965
+ const pixelRatioForSvg = pixelRatio || 1;
4966
+ const svgXml = exportLiveSceneAsPureVectorSvg(containerEl, options);
4967
+ const inlinedSvgXml = await inlineSerializedSvgResources(svgXml);
4968
+ const blob = new Blob([inlinedSvgXml], { type: "image/svg+xml;charset=utf-8" });
4969
+ const url = URL.createObjectURL(blob);
4970
+ const img = new Image();
4971
+ await new Promise((resolve, reject) => {
4972
+ img.onload = () => resolve();
4973
+ img.onerror = () => {
4974
+ URL.revokeObjectURL(url);
4975
+ reject(new Error("Failed to rasterize SVG into Image for canvas export"));
4976
+ };
4977
+ img.src = url;
4978
+ });
4979
+ const width = img.naturalWidth || (containerEl.clientWidth || 800);
4980
+ const height = img.naturalHeight || (containerEl.clientHeight || 400);
4981
+ const canvas = document.createElement("canvas");
4982
+ canvas.width = Math.max(1, Math.round(width * pixelRatioForSvg));
4983
+ canvas.height = Math.max(1, Math.round(height * pixelRatioForSvg));
4984
+ const ctx = canvas.getContext("2d");
4985
+ if (!ctx) {
4986
+ URL.revokeObjectURL(url);
4987
+ throw new Error("Could not get 2D canvas context for export");
4988
+ }
4989
+ ctx.scale(pixelRatioForSvg, pixelRatioForSvg);
4990
+ ctx.drawImage(img, 0, 0, width, height);
4991
+ URL.revokeObjectURL(url);
4992
+ return canvas;
4993
+ }
4994
+
4995
+ // src/export/gif-encoder.ts
4996
+ var GIF_HEADER = "GIF89a";
4997
+ var TRANSPARENT_COLOR_INDEX = 255;
4998
+ function buildAdaptivePalette(frames, maxColors = 254) {
4999
+ const histogram = /* @__PURE__ */ new Map();
5000
+ const stepFrame = Math.max(1, Math.floor(frames.length / 8));
5001
+ for (let f = 0; f < frames.length; f += stepFrame) {
5002
+ const data = frames[f].imageData.data;
5003
+ const len = data.length;
5004
+ for (let i = 0; i < len; i += 8) {
5005
+ const a = data[i + 3];
5006
+ if (a < 16) continue;
5007
+ const r = data[i];
5008
+ const g = data[i + 1];
5009
+ const b = data[i + 2];
5010
+ const key = r << 16 | g << 8 | b;
5011
+ histogram.set(key, (histogram.get(key) || 0) + 1);
5012
+ }
5013
+ }
5014
+ const entries = Array.from(histogram.entries());
5015
+ let paletteColors = [];
5016
+ if (entries.length <= maxColors) {
5017
+ paletteColors = entries.map(([key]) => [
5018
+ key >> 16 & 255,
5019
+ key >> 8 & 255,
5020
+ key & 255
5021
+ ]);
5022
+ } else {
5023
+ entries.sort((a, b) => b[1] - a[1]);
5024
+ const topCount = Math.min(128, Math.floor(maxColors * 0.6));
5025
+ for (let i = 0; i < topCount; i++) {
5026
+ const key = entries[i][0];
5027
+ paletteColors.push([
5028
+ key >> 16 & 255,
5029
+ key >> 8 & 255,
5030
+ key & 255
5031
+ ]);
5032
+ }
5033
+ const buckets = /* @__PURE__ */ new Map();
5034
+ for (let i = topCount; i < entries.length; i++) {
5035
+ const [key, count] = entries[i];
5036
+ const r = key >> 16 & 255;
5037
+ const g = key >> 8 & 255;
5038
+ const b = key & 255;
5039
+ const bKey = r >> 3 << 10 | g >> 3 << 5 | b >> 3;
5040
+ let buck = buckets.get(bKey);
5041
+ if (!buck) {
5042
+ buck = { rSum: 0, gSum: 0, bSum: 0, count: 0 };
5043
+ buckets.set(bKey, buck);
5044
+ }
5045
+ buck.rSum += r * count;
5046
+ buck.gSum += g * count;
5047
+ buck.bSum += b * count;
5048
+ buck.count += count;
5049
+ }
5050
+ const bucketList = Array.from(buckets.values()).sort((a, b) => b.count - a.count);
5051
+ const remainSlots = maxColors - paletteColors.length;
5052
+ for (let i = 0; i < Math.min(remainSlots, bucketList.length); i++) {
5053
+ const b = bucketList[i];
5054
+ paletteColors.push([
5055
+ Math.round(b.rSum / b.count),
5056
+ Math.round(b.gSum / b.count),
5057
+ Math.round(b.bSum / b.count)
5058
+ ]);
5059
+ }
5060
+ }
5061
+ if (paletteColors.length === 0) {
5062
+ paletteColors.push([255, 255, 255]);
5063
+ }
5064
+ const globalPalette = new Uint8Array(256 * 3);
5065
+ for (let i = 0; i < paletteColors.length; i++) {
5066
+ globalPalette[i * 3] = paletteColors[i][0];
5067
+ globalPalette[i * 3 + 1] = paletteColors[i][1];
5068
+ globalPalette[i * 3 + 2] = paletteColors[i][2];
5069
+ }
5070
+ for (let i = paletteColors.length; i < 255; i++) {
5071
+ globalPalette[i * 3] = 0;
5072
+ globalPalette[i * 3 + 1] = 0;
5073
+ globalPalette[i * 3 + 2] = 0;
5074
+ }
5075
+ globalPalette[255 * 3] = 0;
5076
+ globalPalette[255 * 3 + 1] = 0;
5077
+ globalPalette[255 * 3 + 2] = 0;
5078
+ const lookupCache = new Uint8Array(32768);
5079
+ const colorCount = paletteColors.length;
5080
+ for (let r5 = 0; r5 < 32; r5++) {
5081
+ const r = r5 << 3 | r5 >> 2;
5082
+ for (let g5 = 0; g5 < 32; g5++) {
5083
+ const g = g5 << 3 | g5 >> 2;
5084
+ for (let b5 = 0; b5 < 32; b5++) {
5085
+ const b = b5 << 3 | b5 >> 2;
5086
+ let bestIdx = 0;
5087
+ let bestDist = Infinity;
5088
+ for (let i = 0; i < colorCount; i++) {
5089
+ const pr = globalPalette[i * 3];
5090
+ const pg = globalPalette[i * 3 + 1];
5091
+ const pb = globalPalette[i * 3 + 2];
5092
+ const dist = (r - pr) ** 2 * 2 + (g - pg) ** 2 * 4 + (b - pb) ** 2 * 1;
5093
+ if (dist < bestDist) {
5094
+ bestDist = dist;
5095
+ bestIdx = i;
5096
+ if (dist === 0) break;
5097
+ }
5098
+ }
5099
+ const cacheKey = r5 << 10 | g5 << 5 | b5;
5100
+ lookupCache[cacheKey] = bestIdx;
5101
+ }
5102
+ }
5103
+ }
5104
+ return {
5105
+ palette: globalPalette,
5106
+ quantize(imageData) {
5107
+ const { width, height, data } = imageData;
5108
+ const pixelCount = width * height;
5109
+ const out = new Uint8Array(pixelCount);
5110
+ for (let i = 0; i < pixelCount; i++) {
5111
+ const idx = i * 4;
5112
+ const a = data[idx + 3];
5113
+ if (a < 16) {
5114
+ out[i] = 255;
5115
+ continue;
5116
+ }
5117
+ const r = data[idx];
5118
+ const g = data[idx + 1];
5119
+ const b = data[idx + 2];
5120
+ const cacheKey = r >> 3 << 10 | g >> 3 << 5 | b >> 3;
5121
+ out[i] = lookupCache[cacheKey];
5122
+ }
5123
+ return out;
5124
+ }
5125
+ };
5126
+ }
5127
+ var BITS = 12;
5128
+ var HSIZE = 5003;
5129
+ var MASKS = [
5130
+ 0,
5131
+ 1,
5132
+ 3,
5133
+ 7,
5134
+ 15,
5135
+ 31,
5136
+ 63,
5137
+ 127,
5138
+ 255,
5139
+ 511,
5140
+ 1023,
5141
+ 2047,
5142
+ 4095,
5143
+ 8191,
5144
+ 16383,
5145
+ 32767,
5146
+ 65535
5147
+ ];
5148
+ function lzwCompress(pixels, minCodeSize = 8) {
5149
+ const out = [];
5150
+ const accum = new Uint8Array(256);
5151
+ const htab = new Int32Array(HSIZE);
5152
+ const codetab = new Int32Array(HSIZE);
5153
+ htab.fill(-1);
5154
+ codetab.fill(0);
5155
+ const init_bits = minCodeSize + 1;
5156
+ const g_init_bits = init_bits;
5157
+ let clear_flg = false;
5158
+ let n_bits = g_init_bits;
5159
+ let maxcode = (1 << n_bits) - 1;
5160
+ const ClearCode = 1 << minCodeSize;
5161
+ const EOFCode = ClearCode + 1;
5162
+ let free_ent = ClearCode + 2;
5163
+ let a_count = 0;
5164
+ let cur_accum = 0;
5165
+ let cur_bits = 0;
5166
+ let ent = pixels[0] ?? 0;
5167
+ let hshift = 0;
5168
+ for (let fcode = HSIZE; fcode < 65536; fcode *= 2) {
5169
+ ++hshift;
5170
+ }
5171
+ hshift = 8 - hshift;
5172
+ out.push(minCodeSize);
5173
+ output(ClearCode);
5174
+ for (let idx = 1; idx < pixels.length; idx++) {
5175
+ next_block: {
5176
+ const c = pixels[idx];
5177
+ const fcode = (c << BITS) + ent;
5178
+ let i = c << hshift ^ ent;
5179
+ if (htab[i] === fcode) {
5180
+ ent = codetab[i];
5181
+ break next_block;
5182
+ }
5183
+ const disp = i === 0 ? 1 : HSIZE - i;
5184
+ while (htab[i] >= 0) {
5185
+ i -= disp;
5186
+ if (i < 0) i += HSIZE;
5187
+ if (htab[i] === fcode) {
5188
+ ent = codetab[i];
5189
+ break next_block;
5190
+ }
5191
+ }
5192
+ output(ent);
5193
+ ent = c;
5194
+ if (free_ent < 1 << BITS) {
5195
+ codetab[i] = free_ent++;
5196
+ htab[i] = fcode;
5197
+ } else {
5198
+ htab.fill(-1);
5199
+ free_ent = ClearCode + 2;
5200
+ clear_flg = true;
5201
+ output(ClearCode);
5202
+ }
5203
+ }
5204
+ }
5205
+ output(ent);
5206
+ output(EOFCode);
5207
+ out.push(0);
5208
+ return new Uint8Array(out);
5209
+ function output(code) {
5210
+ cur_accum &= MASKS[cur_bits];
5211
+ if (cur_bits > 0) cur_accum |= code << cur_bits;
5212
+ else cur_accum = code;
5213
+ cur_bits += n_bits;
5214
+ while (cur_bits >= 8) {
5215
+ accum[a_count++] = cur_accum & 255;
5216
+ if (a_count >= 254) {
5217
+ out.push(a_count);
5218
+ for (let j = 0; j < a_count; j++) out.push(accum[j]);
5219
+ a_count = 0;
5220
+ }
5221
+ cur_accum >>= 8;
5222
+ cur_bits -= 8;
5223
+ }
5224
+ if (free_ent > maxcode || clear_flg) {
5225
+ if (clear_flg) {
5226
+ n_bits = g_init_bits;
5227
+ maxcode = (1 << n_bits) - 1;
5228
+ clear_flg = false;
5229
+ } else {
5230
+ ++n_bits;
5231
+ maxcode = n_bits === BITS ? 1 << n_bits : (1 << n_bits) - 1;
5232
+ }
5233
+ }
5234
+ if (code === EOFCode) {
5235
+ while (cur_bits > 0) {
5236
+ accum[a_count++] = cur_accum & 255;
5237
+ if (a_count >= 254) {
5238
+ out.push(a_count);
5239
+ for (let j = 0; j < a_count; j++) out.push(accum[j]);
5240
+ a_count = 0;
5241
+ }
5242
+ cur_accum >>= 8;
5243
+ cur_bits -= 8;
5244
+ }
5245
+ if (a_count > 0) {
5246
+ out.push(a_count);
5247
+ for (let j = 0; j < a_count; j++) out.push(accum[j]);
5248
+ a_count = 0;
5249
+ }
5250
+ }
5251
+ }
5252
+ }
5253
+ function encodeGifSequence(frames, options = {}) {
5254
+ if (frames.length === 0) {
5255
+ throw new Error("Cannot encode GIF without frames");
5256
+ }
5257
+ const { width, height } = frames[0].imageData;
5258
+ const enableDiff = options.diff !== false;
5259
+ const quantizer = buildAdaptivePalette(frames);
5260
+ const buffer = [];
5261
+ const pushString = (str) => {
5262
+ for (let i = 0; i < str.length; i++) buffer.push(str.charCodeAt(i));
5263
+ };
5264
+ const pushU16 = (val) => {
5265
+ buffer.push(val & 255, val >> 8 & 255);
5266
+ };
5267
+ pushString(GIF_HEADER);
5268
+ pushU16(width);
5269
+ pushU16(height);
5270
+ buffer.push(247);
5271
+ buffer.push(0);
5272
+ buffer.push(0);
5273
+ for (let i = 0; i < quantizer.palette.length; i++) {
5274
+ buffer.push(quantizer.palette[i]);
5275
+ }
5276
+ if (options.loop !== false) {
5277
+ buffer.push(33, 255, 11);
5278
+ pushString("NETSCAPE2.0");
5279
+ buffer.push(3, 1, 0, 0, 0);
5280
+ }
5281
+ let prevQuantized = null;
5282
+ for (let frameIdx = 0; frameIdx < frames.length; frameIdx++) {
5283
+ const frame = frames[frameIdx];
5284
+ const currQuantized = quantizer.quantize(frame.imageData);
5285
+ const delayHundredths = Math.max(2, Math.round(frame.delayMs / 10));
5286
+ if (!enableDiff || prevQuantized === null || frameIdx === 0) {
5287
+ const compressedWithHeader = lzwCompress(currQuantized);
5288
+ buffer.push(33, 249, 4, 4);
5289
+ pushU16(delayHundredths);
5290
+ buffer.push(0, 0);
5291
+ buffer.push(44);
5292
+ pushU16(0);
5293
+ pushU16(0);
5294
+ pushU16(width);
5295
+ pushU16(height);
5296
+ buffer.push(0);
5297
+ for (let i = 0; i < compressedWithHeader.length; i++) {
5298
+ buffer.push(compressedWithHeader[i]);
5299
+ }
5300
+ prevQuantized = currQuantized;
5301
+ } else {
5302
+ let minX = width;
5303
+ let minY = height;
5304
+ let maxX = -1;
5305
+ let maxY = -1;
5306
+ for (let y = 0; y < height; y++) {
5307
+ const rowOffset = y * width;
5308
+ for (let x = 0; x < width; x++) {
5309
+ if (currQuantized[rowOffset + x] !== prevQuantized[rowOffset + x]) {
5310
+ if (x < minX) minX = x;
5311
+ if (x > maxX) maxX = x;
5312
+ if (y < minY) minY = y;
5313
+ if (y > maxY) maxY = y;
5314
+ }
5315
+ }
5316
+ }
5317
+ if (maxX < minX || maxY < minY) {
5318
+ continue;
5319
+ }
5320
+ const diffW = maxX - minX + 1;
5321
+ const diffH = maxY - minY + 1;
5322
+ const diffData = new Uint8Array(diffW * diffH);
5323
+ for (let dy = 0; dy < diffH; dy++) {
5324
+ const gy = minY + dy;
5325
+ const gRowOffset = gy * width;
5326
+ const dRowOffset = dy * diffW;
5327
+ for (let dx = 0; dx < diffW; dx++) {
5328
+ const gx = minX + dx;
5329
+ const currCol = currQuantized[gRowOffset + gx];
5330
+ const prevCol = prevQuantized[gRowOffset + gx];
5331
+ diffData[dRowOffset + dx] = currCol === prevCol ? TRANSPARENT_COLOR_INDEX : currCol;
5332
+ }
5333
+ }
5334
+ const compressedWithHeader = lzwCompress(diffData);
5335
+ buffer.push(33, 249, 4, 5);
5336
+ pushU16(delayHundredths);
5337
+ buffer.push(TRANSPARENT_COLOR_INDEX, 0);
5338
+ buffer.push(44);
5339
+ pushU16(minX);
5340
+ pushU16(minY);
5341
+ pushU16(diffW);
5342
+ pushU16(diffH);
5343
+ buffer.push(0);
5344
+ for (let i = 0; i < compressedWithHeader.length; i++) {
5345
+ buffer.push(compressedWithHeader[i]);
5346
+ }
5347
+ prevQuantized = currQuantized;
5348
+ }
5349
+ }
5350
+ buffer.push(59);
5351
+ return new Uint8Array(buffer);
5352
+ }
5353
+
5354
+ // src/export/gif-exporter.ts
5355
+ var nextFrame = () => new Promise((resolve) => {
5356
+ let settled = false;
5357
+ const finish = () => {
5358
+ if (settled) return;
5359
+ settled = true;
5360
+ resolve();
5361
+ };
5362
+ const fallback = setTimeout(finish, 80);
5363
+ requestAnimationFrame(() => requestAnimationFrame(() => {
5364
+ clearTimeout(fallback);
5365
+ finish();
5366
+ }));
5367
+ });
5368
+ var DEFAULT_GIF_PIXEL_RATIO = 2;
5369
+ var DEFAULT_GIF_FPS = 20;
5370
+ var MAX_GIF_FRAMES = 96;
5371
+ async function rasterizeFrame(container, pixelRatio, options) {
5372
+ const canvas = await rasterizeDiagramToCanvas(container, options, pixelRatio);
5373
+ const context = canvas.getContext("2d");
5374
+ if (!context) throw new Error("Could not create GIF canvas context");
5375
+ return context.getImageData(0, 0, canvas.width, canvas.height);
5376
+ }
5377
+ async function exportDiagramAsGif(container, timeline, options = {}) {
5378
+ const requestedFps = Math.min(30, Math.max(1, Math.round(options.fps ?? DEFAULT_GIF_FPS)));
5379
+ const rawDuration = timeline.duration();
5380
+ const duration = Math.max(Number.isFinite(rawDuration) ? rawDuration : 1, 0.1);
5381
+ const fps = Math.min(requestedFps, Math.max(6, Math.round(MAX_GIF_FRAMES / duration)));
5382
+ const frameCount = Math.max(1, Math.ceil(duration * fps));
5383
+ const delayMs = Math.max(20, Math.round(1e3 / fps));
5384
+ const pixelRatio = options.pixelRatio ?? DEFAULT_GIF_PIXEL_RATIO;
5385
+ const holdEndMs = Math.max(delayMs, options.holdEndMs ?? 1400);
5386
+ const priorTime = timeline.currentTime();
5387
+ const wasPlaying = timeline.isPlaying();
5388
+ timeline.pause();
5389
+ try {
5390
+ const frames = [];
5391
+ const totalFrames = frameCount + 1;
5392
+ for (let frame = 0; frame < frameCount; frame++) {
5393
+ timeline.seek(Math.min(duration, frame / fps));
5394
+ await nextFrame();
5395
+ const imageData = await rasterizeFrame(container, pixelRatio, options);
5396
+ frames.push({
5397
+ imageData,
5398
+ delayMs
5399
+ });
5400
+ options.onProgress?.(frames.length / totalFrames, frames.length, totalFrames);
5401
+ }
5402
+ timeline.seek(duration);
5403
+ await nextFrame();
5404
+ const finalImageData = await rasterizeFrame(container, pixelRatio, options);
5405
+ frames.push({
5406
+ imageData: finalImageData,
5407
+ delayMs: holdEndMs
5408
+ });
5409
+ options.onProgress?.(1, totalFrames, totalFrames);
5410
+ const encoded = encodeGifSequence(frames, {
5411
+ dither: options.dither ?? false,
5412
+ loop: options.loop ?? true,
5413
+ diff: options.diff ?? true
5414
+ });
5415
+ const bytes = new Uint8Array(encoded.byteLength);
5416
+ bytes.set(encoded);
5417
+ return new Blob([bytes], { type: "image/gif" });
5418
+ } finally {
5419
+ timeline.seek(priorTime);
5420
+ if (wasPlaying) timeline.play();
5421
+ }
5422
+ }
5423
+
5424
+ // src/diagram.ts
5425
+ var NORMAL_PLAYBACK_RATE = 4 / 5;
5426
+ var MIN_VIEWPORT_ZOOM = 0.5;
5427
+ var MAX_VIEWPORT_ZOOM = 3;
5428
+ var VIEWPORT_ZOOM_STEP = 15e-4;
5429
+ var DRAG_CLICK_THRESHOLD_PX = 4;
5430
+ var BEAT_NAV_EPSILON_S = 0.05;
5431
+ var MARKDY_PLAYGROUND_URL = "https://markdy.com/playground/";
5432
+ function encodeCodeForPlaygroundHash(code) {
5433
+ return encodeURIComponent(btoa(encodeURIComponent(code)));
5434
+ }
5435
+ function createBeatCaptionLayer(doc, beats) {
5436
+ const layer = doc.createElement("div");
5437
+ layer.className = "markdy-beat-caption-layer";
5438
+ for (const beat of beats) {
5439
+ if (!beat.label) continue;
5440
+ const caption = doc.createElement("div");
5441
+ caption.className = "markdy-beat-caption";
5442
+ caption.textContent = beat.label;
5443
+ caption.dataset.beat = beat.name;
5444
+ layer.appendChild(caption);
5445
+ }
5446
+ return layer;
5447
+ }
5448
+ function buildBeatCaptionAnimations(beats, layer) {
5449
+ const anims = [];
5450
+ const captions = Array.from(layer.querySelectorAll(".markdy-beat-caption"));
5451
+ for (const beat of beats) {
5452
+ if (!beat.label) continue;
5453
+ const caption = captions.find((item) => item.dataset.beat === beat.name);
5454
+ if (!caption) continue;
5455
+ const startMs = beat.start * 1e3;
5456
+ const durMs = Math.max((beat.end - beat.start) * 1e3, 650);
5457
+ anims.push(
5458
+ caption.animate(
5459
+ [
5460
+ { opacity: 0, transform: "translateY(8px)" },
5461
+ { opacity: 1, transform: "translateY(0)", offset: 0.16 },
5462
+ { opacity: 1, transform: "translateY(0)", offset: 0.82 },
5463
+ { opacity: 0, transform: "translateY(-4px)" }
5464
+ ],
5465
+ { duration: durMs, delay: startMs, fill: "forwards", easing: "ease-out" }
5466
+ )
5467
+ );
5468
+ }
5469
+ return anims;
5470
+ }
5471
+ function isDarkBgColor(colorStr) {
5472
+ if (!colorStr || colorStr === "transparent" || colorStr === "rgba(0, 0, 0, 0)") return null;
5473
+ const match = colorStr.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/i);
5474
+ if (!match) return null;
5475
+ const r = parseInt(match[1], 10);
5476
+ const g = parseInt(match[2], 10);
5477
+ const b = parseInt(match[3], 10);
5478
+ const luma = 0.2126 * r + 0.7152 * g + 0.0722 * b;
5479
+ return luma < 128;
5480
+ }
5481
+ function checkElementTheme(el) {
5482
+ 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");
5483
+ if (themeAttr) {
5484
+ const lower = themeAttr.toLowerCase();
5485
+ if (lower.includes("dark")) return "nebula";
5486
+ if (lower.includes("light")) return "paper";
5487
+ }
5488
+ const cls = el.className;
5489
+ if (typeof cls === "string" && cls.length > 0) {
5490
+ if (/\b(dark|dark-mode|dark-theme|theme-dark|vscode-dark)\b/i.test(cls)) return "nebula";
5491
+ if (/\b(light|light-mode|light-theme|theme-light|vscode-light)\b/i.test(cls)) return "paper";
5492
+ }
5493
+ return null;
5494
+ }
5495
+ function detectHostTheme(container) {
5496
+ if (typeof document === "undefined") return "nebula";
5497
+ let current = container ?? null;
5498
+ while (current) {
5499
+ const check = checkElementTheme(current);
5500
+ if (check) return check;
5501
+ current = current.parentElement;
5502
+ }
5503
+ const docRoot = document.documentElement;
5504
+ const rootCheck = checkElementTheme(docRoot);
5505
+ if (rootCheck) return rootCheck;
5506
+ if (document.body) {
5507
+ const bodyCheck = checkElementTheme(document.body);
5508
+ if (bodyCheck) return bodyCheck;
5509
+ }
5510
+ if (typeof window !== "undefined" && typeof window.getComputedStyle === "function") {
5511
+ let bgEl = container ?? document.body ?? null;
5512
+ while (bgEl) {
5513
+ try {
5514
+ const bg = window.getComputedStyle(bgEl).backgroundColor;
5515
+ const isDark = isDarkBgColor(bg);
5516
+ if (isDark === true) return "nebula";
5517
+ if (isDark === false) return "paper";
5518
+ } catch {
5519
+ }
5520
+ bgEl = bgEl.parentElement;
5521
+ }
5522
+ }
5523
+ if (typeof window !== "undefined" && window.matchMedia?.("(prefers-color-scheme: dark)").matches) {
5524
+ return "nebula";
5525
+ }
5526
+ return "paper";
5527
+ }
5528
+ function createDiagram(opts) {
5529
+ const {
5530
+ container,
5531
+ code,
3786
5532
  assets,
3787
5533
  progressBar,
3788
5534
  sceneBoundaryProgress,
@@ -3800,10 +5546,18 @@ function createDiagram(opts) {
3800
5546
  onPlayStateChange,
3801
5547
  onEnded
3802
5548
  } = opts;
3803
- const { ast, plan } = parseAndCompile(code);
5549
+ const { ast, plan } = parseAndCompile2(code);
3804
5550
  for (const w of ast.diagnostics) {
3805
5551
  if (w.severity === "warning") onWarning(w);
3806
5552
  }
5553
+ const hasExplicitTheme = Boolean(ast.meta.explicitTheme === true && ast.meta.theme !== "auto");
5554
+ if (!hasExplicitTheme) {
5555
+ const detected = detectHostTheme(container);
5556
+ plan.theme = resolveTheme2(detected);
5557
+ }
5558
+ let hostThemeObserver = null;
5559
+ let mediaQueryListener = null;
5560
+ let colorSchemeQuery = null;
3807
5561
  const hostProgress = sceneBoundaryProgress === false || sceneBoundaryProgress === void 0 && progressBar === false ? "none" : void 0;
3808
5562
  const hostProgressColor = progressColor ?? progressBarColor ?? (typeof sceneBoundaryProgress === "string" && sceneBoundaryProgress !== "true" && sceneBoundaryProgress !== "false" ? sceneBoundaryProgress : typeof progressBar === "string" && progressBar !== "true" && progressBar !== "false" ? progressBar : void 0);
3809
5563
  const player = resolvePlayer(plan.meta.player, {
@@ -3838,6 +5592,7 @@ function createDiagram(opts) {
3838
5592
  resetView: resetViewButton,
3839
5593
  fullscreen: fullscreenButton,
3840
5594
  svg: svgButton,
5595
+ gif: gifButton,
3841
5596
  share: shareButton,
3842
5597
  code: codeButton,
3843
5598
  theme: themeButton
@@ -3852,6 +5607,8 @@ function createDiagram(opts) {
3852
5607
  const totalDurationMs = plan.duration * 1e3;
3853
5608
  const durationSeconds = plan.duration;
3854
5609
  container.classList.add("markdy-diagram-root");
5610
+ container.__markdyCode = code;
5611
+ container.__markdyPlan = plan;
3855
5612
  applyThemeVariables(container, plan.theme);
3856
5613
  Object.assign(container.style, {
3857
5614
  position: "relative",
@@ -4222,6 +5979,7 @@ function createDiagram(opts) {
4222
5979
  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
5980
  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
5981
  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>',
5982
+ 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
5983
  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
5984
  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
5985
  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 +6182,7 @@ function createDiagram(opts) {
4424
6182
  diagram.seek(target);
4425
6183
  },
4426
6184
  setTheme(theme) {
4427
- const newTheme = typeof theme === "string" ? resolveTheme(theme) : theme;
6185
+ const newTheme = typeof theme === "string" ? resolveTheme2(theme) : theme;
4428
6186
  plan.theme = newTheme;
4429
6187
  applyThemeVariables(container, newTheme);
4430
6188
  applyThemeToScene(scene, newTheme);
@@ -4521,10 +6279,44 @@ function createDiagram(opts) {
4521
6279
  height: plan.meta.height
4522
6280
  });
4523
6281
  }
4524
- if (totalDurationMs > 0) updateProgressBar(sceneMs / totalDurationMs);
6282
+ if (totalDurationMs > 0) updateProgressBar(sceneMs / totalDurationMs);
6283
+ },
6284
+ exportSvg(options) {
6285
+ const resumeAt = sceneMs;
6286
+ const wasPlaying = isPlaying;
6287
+ try {
6288
+ diagram.pause();
6289
+ diagram.seek(durationSeconds);
6290
+ return exportDiagramAsVectorSvg(container, options);
6291
+ } finally {
6292
+ diagram.seek(resumeAt / 1e3);
6293
+ if (wasPlaying) diagram.play();
6294
+ }
6295
+ },
6296
+ async exportPng(options) {
6297
+ const resumeAt = sceneMs;
6298
+ const wasPlaying = isPlaying;
6299
+ try {
6300
+ diagram.pause();
6301
+ diagram.seek(durationSeconds);
6302
+ return await exportDiagramAsPng(container, options);
6303
+ } finally {
6304
+ diagram.seek(resumeAt / 1e3);
6305
+ if (wasPlaying) diagram.play();
6306
+ }
6307
+ },
6308
+ async exportGif(options) {
6309
+ return await exportDiagramAsGif(container, diagram, options);
4525
6310
  },
4526
6311
  destroy() {
4527
6312
  diagram.pause();
6313
+ hostThemeObserver?.disconnect();
6314
+ hostThemeObserver = null;
6315
+ if (colorSchemeQuery && mediaQueryListener) {
6316
+ colorSchemeQuery.removeEventListener?.("change", mediaQueryListener);
6317
+ mediaQueryListener = null;
6318
+ colorSchemeQuery = null;
6319
+ }
4528
6320
  if (keyboardShortcuts && typeof window !== "undefined") {
4529
6321
  window.removeEventListener("keydown", handleKeyDown);
4530
6322
  }
@@ -4541,6 +6333,43 @@ function createDiagram(opts) {
4541
6333
  if (viewport.parentNode === container) container.removeChild(viewport);
4542
6334
  }
4543
6335
  };
6336
+ if (!hasExplicitTheme && typeof document !== "undefined") {
6337
+ const syncWithHost = () => {
6338
+ const nextTheme = detectHostTheme(container);
6339
+ diagram.setTheme(nextTheme);
6340
+ };
6341
+ const attributeFilter = [
6342
+ "data-theme",
6343
+ "data-mode",
6344
+ "data-bs-theme",
6345
+ "data-color-mode",
6346
+ "data-color-scheme",
6347
+ "class",
6348
+ "style"
6349
+ ];
6350
+ hostThemeObserver = new MutationObserver(syncWithHost);
6351
+ hostThemeObserver.observe(document.documentElement, {
6352
+ attributes: true,
6353
+ attributeFilter
6354
+ });
6355
+ if (document.body) {
6356
+ hostThemeObserver.observe(document.body, {
6357
+ attributes: true,
6358
+ attributeFilter
6359
+ });
6360
+ }
6361
+ if (container && container.parentElement && container !== document.body) {
6362
+ hostThemeObserver.observe(container.parentElement, {
6363
+ attributes: true,
6364
+ attributeFilter
6365
+ });
6366
+ }
6367
+ if (typeof window !== "undefined" && window.matchMedia) {
6368
+ colorSchemeQuery = window.matchMedia("(prefers-color-scheme: dark)");
6369
+ mediaQueryListener = syncWithHost;
6370
+ colorSchemeQuery.addEventListener?.("change", mediaQueryListener);
6371
+ }
6372
+ }
4544
6373
  function togglePlayback() {
4545
6374
  if (isPlaying) diagram.pause();
4546
6375
  else {
@@ -4664,6 +6493,39 @@ function createDiagram(opts) {
4664
6493
  });
4665
6494
  toolbar.appendChild(button);
4666
6495
  }
6496
+ function mountGifControl(toolbar) {
6497
+ if (!gifButton) return;
6498
+ const button = makeControlButton("GIF", "Export diagram as animated GIF", ICONS2.gif);
6499
+ button.className = "markdy-control-gif";
6500
+ let exporting = false;
6501
+ button.addEventListener("click", async () => {
6502
+ if (exporting) return;
6503
+ exporting = true;
6504
+ flashControlLabel(button, "Recording...");
6505
+ button.setAttribute("disabled", "true");
6506
+ try {
6507
+ const blob = await diagram.exportGif();
6508
+ const name = (plan.title || "markdy-diagram").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
6509
+ const url = URL.createObjectURL(blob);
6510
+ const link = document.createElement("a");
6511
+ link.href = url;
6512
+ link.download = `${name || "markdy-diagram"}.gif`;
6513
+ link.style.display = "none";
6514
+ document.body.appendChild(link);
6515
+ link.click();
6516
+ document.body.removeChild(link);
6517
+ URL.revokeObjectURL(url);
6518
+ flashControlLabel(button, "Saved");
6519
+ } catch (error) {
6520
+ onWarning({ severity: "warning", message: `GIF export failed: ${String(error)}`, line: 0 });
6521
+ flashControlLabel(button, "Failed");
6522
+ } finally {
6523
+ exporting = false;
6524
+ button.removeAttribute("disabled");
6525
+ }
6526
+ });
6527
+ toolbar.appendChild(button);
6528
+ }
4667
6529
  function mountShareControl(toolbar) {
4668
6530
  if (!shareButton) return;
4669
6531
  const button = makeControlButton("Share", "Copy a share link for this diagram", ICONS2.share);
@@ -4687,7 +6549,7 @@ function createDiagram(opts) {
4687
6549
  button.className = "markdy-control-theme";
4688
6550
  button.addEventListener("click", () => {
4689
6551
  const darkThemes = ["midnight", "blueprint", "graphite", "nebula", "terminal"];
4690
- const lightThemes = ["paper", "editorial", "sketchy"];
6552
+ const lightThemes = ["paper", "editorial", "sketchy", "ink", "doodle"];
4691
6553
  const currentName = plan.theme.name || "paper";
4692
6554
  const isDark = darkThemes.includes(currentName);
4693
6555
  const targetThemes = isDark ? lightThemes : darkThemes;
@@ -5049,7 +6911,7 @@ function createDiagram(opts) {
5049
6911
  mountResetViewControl(toolsGroup);
5050
6912
  mountFullscreenControl(toolsGroup);
5051
6913
  }
5052
- if (svgButton || shareButton || codeButton || themeButton) {
6914
+ if (svgButton || gifButton || shareButton || codeButton || themeButton) {
5053
6915
  if (toolsGroup.children.length > 0) {
5054
6916
  const divider = document.createElement("div");
5055
6917
  divider.className = "markdy-control-divider";
@@ -5057,6 +6919,7 @@ function createDiagram(opts) {
5057
6919
  }
5058
6920
  mountThemeControl(toolsGroup);
5059
6921
  mountSvgControl(toolsGroup);
6922
+ mountGifControl(toolsGroup);
5060
6923
  mountShareControl(toolsGroup);
5061
6924
  mountCodeControl(toolsGroup);
5062
6925
  }
@@ -5093,461 +6956,6 @@ function createDiagram(opts) {
5093
6956
  return diagram;
5094
6957
  }
5095
6958
 
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");
5337
- }
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
- );
5363
- }
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));
5408
- }
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();
5460
- }
5461
- }
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");
5486
- }
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();
5548
- }
5549
- }
5550
-
5551
6959
  // src/presentation-controller.ts
5552
6960
  var DiagramPresentationController = class {
5553
6961
  diagram;
@@ -5632,8 +7040,12 @@ export {
5632
7040
  DiagramPresentationController,
5633
7041
  ICON_REGISTRY,
5634
7042
  createDiagram,
7043
+ detectHostTheme,
5635
7044
  encodeGifSequence,
5636
7045
  exportDiagramAsGif,
5637
7046
  exportDiagramAsPng,
5638
- exportDiagramAsVectorSvg
7047
+ exportDiagramAsVectorSvg,
7048
+ exportLiveSceneAsPureVectorSvg,
7049
+ iconKeyForNode,
7050
+ renderPureVectorSvg
5639
7051
  };