@markdy/renderer-dom 1.4.2 → 1.4.3

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/README.md CHANGED
@@ -76,6 +76,66 @@ const shortestPath = findShortestRoute("Client", "LedgerDb", ast);
76
76
  console.log("Route:", shortestPath); // ['Client', 'Gateway', 'PaymentSvc', 'LedgerDb']
77
77
  ```
78
78
 
79
+ ## Responsive Playback
80
+
81
+ Animations run on the browser's Web Animations timeline. JavaScript synchronizes
82
+ them on play, pause, seek, speed changes, and layout changes, not on every frame.
83
+
84
+ `responsiveLayout` controls whether the renderer may change orientation:
85
+
86
+ - `"auto"` (default): adapt diagrams without an explicit `layout` directive.
87
+ - `true`: also adapt diagrams that declare a direction, as in the playground.
88
+ - `false`: keep the source layout fixed and only scale the scene.
89
+
90
+ With `fitMode: "auto"` (default), automatically sized architecture, flowchart,
91
+ state, and tree diagrams compare cached horizontal and vertical layouts against
92
+ the available width and height. Orientation changes only when the alternative
93
+ improves the fitted scale by more than 20%. Other cases use a width breakpoint
94
+ around 640px with a 32px margin on either side. Reverse flow stays BT/RL, and
95
+ explicit scene dimensions are preserved, including partially specified sizes.
96
+
97
+ Auto fitting uses width-first framing in natural-height embeds and contain
98
+ framing in height-constrained hosts. If fitting requires a scale below
99
+ `minReadableScale` (default `0.9`, valid range `0` to `1`), the viewport scrolls
100
+ instead of shrinking further. Set it to `0` to disable the readability floor.
101
+ The Fit control toggles between a contained overview and readable framing.
102
+ Scrollable framing starts horizontally centered and pins storyboard camera motion
103
+ so frame cues do not compete with manual scrolling; other animations keep playing.
104
+ Explicit `fitMode: "width"` and `fitMode: "contain"` keep their original scaling
105
+ behavior without a readability floor.
106
+
107
+ Bounds include routed paths and label rectangles, even outside the estimated
108
+ scene dimensions, and are cached after mounting or re-layout. Container resizing
109
+ preserves playback time and state. ResizeObserver handles split panes as well as
110
+ window resizing; hosts can call `diagram.resize()` after revealing a hidden preview.
111
+
112
+ ## Animated GIF Export
113
+
114
+ ```typescript
115
+ const gif = await diagram.exportGif({
116
+ fps: 12,
117
+ pixelRatio: 1,
118
+ maxFrames: 120,
119
+ maxWidth: 1600,
120
+ holdEndMs: 1400,
121
+ loop: true,
122
+ onProgress: (progress) => console.log(Math.round(progress * 100)),
123
+ });
124
+ ```
125
+
126
+ GIF export captures the rendered DOM, including node styling, shadows, and
127
+ the current animation state. Use `mode: "pure"` for the previous vector-based
128
+ rasterization path. PNG and SVG exports keep their existing defaults.
129
+
130
+ `fps` and `pixelRatio` are targets. Long scenes are sampled evenly across the
131
+ complete timeline, with at most `maxFrames` frames including the final hold.
132
+ Output width is capped by `maxWidth`; resolution is reduced further when needed
133
+ to keep captured frames within a 48-megapixel budget. Repeated frames are merged
134
+ without losing their delays, so compression preserves playback duration.
135
+
136
+ Playback time and playing/paused state are restored after export, including
137
+ when capture fails. Browser font and cross-origin image restrictions still apply.
138
+
79
139
  ## API Exports
80
140
 
81
141
  | Export | Type | Description |
@@ -87,7 +147,7 @@ console.log("Route:", shortestPath); // ['Client', 'Gateway', 'PaymentSvc', 'Led
87
147
  | `clearImpactHighlight(container)` | `Function` | Resets all impact highlighting |
88
148
  | `exportDiagramAsVectorSvg(container, opts?)` | `Function` | Export pure SVG vector snapshot of active scene frame |
89
149
  | `exportDiagramAsPng(container, opts?)` | `Function` | Export high-DPI rasterized PNG Blob |
90
- | `exportDiagramAsGif(diagram, opts?)` | `Function` | Export animated GIF89a recording |
150
+ | `exportDiagramAsGif(container, timeline, opts?)` | `Function` | Export animated GIF89a recording |
91
151
 
92
152
  ## Ecosystem & Documentation
93
153
 
package/dist/index.d.ts CHANGED
@@ -1,4 +1,35 @@
1
- import { RenderPlan, BeatRange, ThemeTokens, PlayerControlsConfig, Diagnostic, PositionedNode, DiagramAST } from '@markdy/core';
1
+ import { EdgeKind, RenderPlan, BeatRange, ThemeTokens, PlayerControlsConfig, Diagnostic, PositionedNode, DiagramAST } from '@markdy/core';
2
+
3
+ /**
4
+ * Pure 2-D geometry helpers for node bounds, hit-testing, and orthogonal
5
+ * edge routing. Nothing here touches the DOM or WAAPI — it operates purely on
6
+ * plain points and rectangles, which keeps the flow-edge routing logic (the
7
+ * only consumer that needs obstacle avoidance) unit testable without a browser.
8
+ */
9
+ interface Point {
10
+ x: number;
11
+ y: number;
12
+ }
13
+ interface Rect {
14
+ x1: number;
15
+ y1: number;
16
+ x2: number;
17
+ y2: number;
18
+ }
19
+
20
+ interface EdgeRuntime {
21
+ group: SVGGElement;
22
+ path: SVGPathElement;
23
+ label?: SVGTextElement;
24
+ labelPlate?: SVGRectElement;
25
+ dot: SVGCircleElement;
26
+ pathLen: number;
27
+ points: Point[];
28
+ labelRect?: Rect;
29
+ kind: EdgeKind;
30
+ color: string;
31
+ drawReveal: boolean;
32
+ }
2
33
 
3
34
  /**
4
35
  * packages/renderer-dom/src/export/svg-exporter.ts
@@ -84,6 +115,8 @@ interface GifDiagramExportOptions extends SvgExportOptions {
84
115
  dither?: boolean;
85
116
  diff?: boolean;
86
117
  holdEndMs?: number;
118
+ maxFrames?: number;
119
+ maxWidth?: number;
87
120
  onProgress?: (progress: number, currentFrame: number, totalFrames: number) => void;
88
121
  }
89
122
  declare function exportDiagramAsGif(container: HTMLElement, timeline: TimelineController, options?: GifDiagramExportOptions): Promise<Blob>;
@@ -129,18 +162,20 @@ interface DiagramOptions {
129
162
  onPlayStateChange?: (playing: boolean) => void;
130
163
  onEnded?: () => void;
131
164
  /**
132
- * Adaptive orientation & responsive layout mode.
133
- * When true or "auto", switches to vertical Top-to-Bottom (TB) on mobile / portrait viewports,
134
- * and horizontal Left-to-Right (LR) on desktop / landscape viewports.
135
- * Defaults to true.
165
+ * Adapts orientation to the available container width.
166
+ * "auto" (default) respects explicit script directions; true also adapts explicit directions.
167
+ * false keeps the script layout fixed. Reverse flow (RL/BT) is preserved.
136
168
  */
137
- responsiveLayout?: boolean;
169
+ responsiveLayout?: boolean | "auto";
138
170
  /**
139
171
  * Auto-scaling mode for diagram framing:
140
- * - "width" (default): Width-First Responsiveness (scale factor = containerWidth / contentWidth, filling 95% - 100% width).
172
+ * - "auto" (default): Fits the host, with scrolling when shrinking would compromise readability.
173
+ * - "width": Scales to the container width.
141
174
  * - "contain": Scales to fit both width and height within container bounds.
142
175
  */
143
- fitMode?: "width" | "contain";
176
+ fitMode?: "auto" | "width" | "contain";
177
+ /** Minimum scale in auto mode, before scrolling is used. Defaults to 0.9; 0 disables the floor. */
178
+ minReadableScale?: number;
144
179
  /**
145
180
  * Target container width fill fraction (0.90 - 1.0) when fitMode is "width".
146
181
  * Defaults to 0.96 (clean edge-to-edge framing with comfortable 2% safe margins).
@@ -183,6 +218,7 @@ declare function detectHostTheme(container?: HTMLElement): "nebula" | "paper";
183
218
  declare function computeDiagramContentBounds(plan: RenderPlan, options?: {
184
219
  tight?: boolean;
185
220
  padding?: number;
221
+ routedEdges?: Iterable<Pick<EdgeRuntime, "points" | "labelRect">>;
186
222
  }): {
187
223
  minX: number;
188
224
  minY: number;
package/dist/index.js CHANGED
@@ -8,6 +8,9 @@ import {
8
8
  resolveTheme as resolveTheme2
9
9
  } from "@markdy/core";
10
10
 
11
+ // src/edges.ts
12
+ import { selectOptimalPorts } from "@markdy/core";
13
+
11
14
  // src/geometry/rect.ts
12
15
  function boxRect(box) {
13
16
  return { x1: box.x, y1: box.y, x2: box.x + box.width, y2: box.y + box.height };
@@ -386,6 +389,22 @@ function cleanCollinearPoints(points) {
386
389
  result.push(points[points.length - 1]);
387
390
  return result;
388
391
  }
392
+ function portCoordinate(center, min, max, lane, bias = 0) {
393
+ if (max <= min) return center;
394
+ const inset = (max - min) * 0.1;
395
+ const anchor = clamp(center + bias, min + inset, max - inset);
396
+ if (lane <= 0) return anchor;
397
+ let index = Math.ceil(lane / 2);
398
+ let fraction = 0;
399
+ let divisor = 2;
400
+ while (index > 0) {
401
+ fraction += index % 2 / divisor;
402
+ index = Math.floor(index / 2);
403
+ divisor *= 2;
404
+ }
405
+ const boundary = lane % 2 === 1 ? min : max;
406
+ return anchor + (boundary - anchor) * fraction;
407
+ }
389
408
  function routeOrthogonal(sourceRect, targetRect, obstacles, bounds, lane = 0) {
390
409
  const laneShift = laneOffset(lane);
391
410
  const sourceCenter = rectCenter(sourceRect);
@@ -397,18 +416,9 @@ function routeOrthogonal(sourceRect, targetRect, obstacles, bounds, lane = 0) {
397
416
  const allObstacles = obstacles;
398
417
  const candidates = [];
399
418
  if (dy >= 20) {
400
- let sX = sourceCenter.x;
401
- let tX = targetCenter.x;
402
- if (dx > 16) {
403
- sX = clamp(sourceCenter.x + (lane > 0 ? Math.abs(laneShift) : 6), sourceRect.x1 + 14, sourceRect.x2 - 14);
404
- tX = clamp(targetCenter.x - (lane > 0 ? Math.abs(laneShift) : 6), targetRect.x1 + 14, targetRect.x2 - 14);
405
- } else if (dx < -16) {
406
- sX = clamp(sourceCenter.x - (lane > 0 ? Math.abs(laneShift) : 6), sourceRect.x1 + 14, sourceRect.x2 - 14);
407
- tX = clamp(targetCenter.x + (lane > 0 ? Math.abs(laneShift) : 6), targetRect.x1 + 14, targetRect.x2 - 14);
408
- } else {
409
- sX = clamp(sourceCenter.x + laneShift, sourceRect.x1 + 14, sourceRect.x2 - 14);
410
- tX = clamp(targetCenter.x + laneShift, targetRect.x1 + 14, targetRect.x2 - 14);
411
- }
419
+ const bias = Math.abs(dx) > 16 ? Math.sign(dx) * 6 : -8;
420
+ const sX = portCoordinate(sourceCenter.x, sourceRect.x1 + 14, sourceRect.x2 - 14, lane, bias);
421
+ const tX = portCoordinate(targetCenter.x, targetRect.x1 + 14, targetRect.x2 - 14, lane, Math.abs(dx) > 16 ? -bias : bias);
412
422
  const sPort = { x: sX, y: sourceRect.y2 };
413
423
  const tPort = { x: tX, y: targetRect.y1 };
414
424
  if (Math.abs(sX - tX) < 1) {
@@ -449,18 +459,9 @@ function routeOrthogonal(sourceRect, targetRect, obstacles, bounds, lane = 0) {
449
459
  tPort
450
460
  ]);
451
461
  } else if (dy <= -20) {
452
- let sX = sourceCenter.x;
453
- let tX = targetCenter.x;
454
- if (dx > 16) {
455
- sX = clamp(sourceCenter.x + (lane > 0 ? Math.abs(laneShift) : 6), sourceRect.x1 + 14, sourceRect.x2 - 14);
456
- tX = clamp(targetCenter.x - (lane > 0 ? Math.abs(laneShift) : 6), targetRect.x1 + 14, targetRect.x2 - 14);
457
- } else if (dx < -16) {
458
- sX = clamp(sourceCenter.x - (lane > 0 ? Math.abs(laneShift) : 6), sourceRect.x1 + 14, sourceRect.x2 - 14);
459
- tX = clamp(targetCenter.x + (lane > 0 ? Math.abs(laneShift) : 6), targetRect.x1 + 14, targetRect.x2 - 14);
460
- } else {
461
- sX = clamp(sourceCenter.x + laneShift, sourceRect.x1 + 14, sourceRect.x2 - 14);
462
- tX = clamp(targetCenter.x + laneShift, targetRect.x1 + 14, targetRect.x2 - 14);
463
- }
462
+ const bias = Math.abs(dx) > 16 ? Math.sign(dx) * 6 : -8;
463
+ const sX = portCoordinate(sourceCenter.x, sourceRect.x1 + 14, sourceRect.x2 - 14, lane, bias);
464
+ const tX = portCoordinate(targetCenter.x, targetRect.x1 + 14, targetRect.x2 - 14, lane, Math.abs(dx) > 16 ? -bias : bias);
464
465
  const sPort = { x: sX, y: sourceRect.y1 };
465
466
  const tPort = { x: tX, y: targetRect.y2 };
466
467
  if (Math.abs(sX - tX) < 1) {
@@ -498,17 +499,9 @@ function routeOrthogonal(sourceRect, targetRect, obstacles, bounds, lane = 0) {
498
499
  ]);
499
500
  }
500
501
  if (dx >= 20) {
501
- let sY = sourceCenter.y;
502
- let tY = targetCenter.y;
503
- if (Math.abs(dy) > 16) {
504
- const dirSign = Math.sign(dy);
505
- sY = clamp(sourceCenter.y + dirSign * 12, sourceRect.y1 + 10, sourceRect.y2 - 10);
506
- tY = clamp(targetCenter.y - dirSign * 12, targetRect.y1 + 10, targetRect.y2 - 10);
507
- } else {
508
- const fwdShift = lane > 0 ? lane % 2 === 1 ? -10 : -18 : 0;
509
- sY = clamp(sourceCenter.y + fwdShift, sourceRect.y1 + 10, sourceRect.y2 - 10);
510
- tY = clamp(targetCenter.y + fwdShift, targetRect.y1 + 10, targetRect.y2 - 10);
511
- }
502
+ const bias = Math.abs(dy) > 16 ? Math.sign(dy) * 12 : 0;
503
+ const sY = portCoordinate(sourceCenter.y, sourceRect.y1 + 10, sourceRect.y2 - 10, lane, bias);
504
+ const tY = portCoordinate(targetCenter.y, targetRect.y1 + 10, targetRect.y2 - 10, lane, -bias);
512
505
  const sPort = { x: sourceRect.x2, y: sY };
513
506
  const tPort = { x: targetRect.x1, y: tY };
514
507
  if (Math.abs(sY - tY) < 1) {
@@ -565,17 +558,9 @@ function routeOrthogonal(sourceRect, targetRect, obstacles, bounds, lane = 0) {
565
558
  { x: tX, y: highwayYBottom },
566
559
  { x: tX, y: targetRect.y2 }
567
560
  ]);
568
- let sY = sourceCenter.y;
569
- let tY = targetCenter.y;
570
- if (Math.abs(dy) > 16) {
571
- const dirSign = Math.sign(dy);
572
- sY = clamp(sourceCenter.y + dirSign * 12, sourceRect.y1 + 10, sourceRect.y2 - 10);
573
- tY = clamp(targetCenter.y - dirSign * 12, targetRect.y1 + 10, targetRect.y2 - 10);
574
- } else {
575
- const retShift = lane > 0 ? lane % 2 === 1 ? 10 : 18 : 10;
576
- sY = clamp(sourceCenter.y + retShift, sourceRect.y1 + 10, sourceRect.y2 - 10);
577
- tY = clamp(targetCenter.y + retShift, targetRect.y1 + 10, targetRect.y2 - 10);
578
- }
561
+ const bias = Math.abs(dy) > 16 ? Math.sign(dy) * 12 : 0;
562
+ const sY = portCoordinate(sourceCenter.y, sourceRect.y1 + 10, sourceRect.y2 - 10, lane, bias);
563
+ const tY = portCoordinate(targetCenter.y, targetRect.y1 + 10, targetRect.y2 - 10, lane, -bias);
579
564
  const sPortL = { x: sourceRect.x1, y: sY };
580
565
  const tPortR = { x: targetRect.x2, y: tY };
581
566
  const midX = round1((sPortL.x + tPortR.x) / 2 + laneShift);
@@ -586,7 +571,13 @@ function routeOrthogonal(sourceRect, targetRect, obstacles, bounds, lane = 0) {
586
571
  tPortR
587
572
  ]);
588
573
  }
574
+ for (const candidate of candidates) {
575
+ const cleaned = cleanCollinearPoints(candidate.map((point) => clampPointToScene(point, bounds)));
576
+ if (cleaned.length === 2 && (cleaned[0].x === cleaned[1].x || cleaned[0].y === cleaned[1].y) && countPathIntersections(cleaned, allObstacles) === 0) return cleaned;
577
+ }
578
+ const blockedCorridors = candidates.map(cleanCollinearPoints);
589
579
  for (const obstacle of allObstacles) {
580
+ if (!blockedCorridors.some((path) => countPathIntersections(path, [obstacle]) > 0)) continue;
590
581
  const bypassYTop = Math.max(16, obstacle.y1 - 18 - Math.abs(laneShift));
591
582
  const bypassYBottom = Math.min(bounds.height - 16, obstacle.y2 + 18 + Math.abs(laneShift));
592
583
  const sourceRight = dx >= 0;
@@ -619,7 +610,7 @@ function routeOrthogonal(sourceRect, targetRect, obstacles, bounds, lane = 0) {
619
610
  let best = candidates[0];
620
611
  let bestScore = Number.POSITIVE_INFINITY;
621
612
  for (const candidate of candidates) {
622
- const cleaned = cleanCollinearPoints(candidate);
613
+ const cleaned = cleanCollinearPoints(candidate.map((point) => clampPointToScene(point, bounds)));
623
614
  const hits = countPathIntersections(cleaned, allObstacles);
624
615
  const bends = routeBends(cleaned);
625
616
  const length = routeLength(cleaned);
@@ -1107,13 +1098,11 @@ function nextEdgeLane(lanes, from, to) {
1107
1098
  const pair = [fromId, toId].sort().join("|");
1108
1099
  const keys = [`pair:${pair}`, `out:${fromId}`, `in:${toId}`];
1109
1100
  if (typeof from !== "string" && typeof to !== "string") {
1110
- const colFrom = Math.round(from.x / 80);
1111
- const colTo = Math.round(to.x / 80);
1112
- const corridorKey = colFrom !== colTo ? `corridor-x:${Math.min(colFrom, colTo)}-${Math.max(colFrom, colTo)}` : `corridor-y:${Math.round(from.y / 60)}-${Math.round(to.y / 60)}`;
1113
- keys.push(corridorKey);
1101
+ const ports = selectOptimalPorts(from, to);
1102
+ keys.push(`port:${fromId}:${ports.sourcePort}`, `port:${toId}:${ports.targetPort}`);
1114
1103
  }
1115
1104
  const lane = Math.max(...keys.map((key) => lanes.get(key) ?? 0));
1116
- for (const key of keys) lanes.set(key, (lanes.get(key) ?? 0) + 1);
1105
+ for (const key of keys) lanes.set(key, lane + 1);
1117
1106
  return lane;
1118
1107
  }
1119
1108
  function dotTravelKeyframes(points) {
@@ -4352,6 +4341,11 @@ function normalizeExportViewport(scene) {
4352
4341
  viewportTransform.style.willChange = "auto";
4353
4342
  });
4354
4343
  }
4344
+ function getDiagramSceneElement(containerEl) {
4345
+ const sceneEl = containerEl.classList?.contains("markdy-scene-root") ? containerEl : containerEl.querySelector(".markdy-scene-root") || containerEl.querySelector("svg") || (containerEl.tagName?.toLowerCase() === "svg" ? containerEl : null);
4346
+ if (!sceneEl) throw new Error("No Markdy scene element found in container");
4347
+ return sceneEl;
4348
+ }
4355
4349
  function prepareHtmlSceneForExport(sceneEl, options = {}) {
4356
4350
  const clonedScene = sceneEl.cloneNode(true);
4357
4351
  copyRenderedStyles(sceneEl, clonedScene);
@@ -5393,12 +5387,36 @@ async function exportDiagramAsPng(containerEl, options = {}) {
5393
5387
  }, "image/png");
5394
5388
  });
5395
5389
  }
5396
- async function rasterizeDiagramToCanvas(containerEl, options = {}, pixelRatio = 1) {
5390
+ async function rasterizeDiagramToCanvas(containerEl, options = {}, pixelRatio = 1, preparedScene) {
5397
5391
  const pixelRatioForSvg = pixelRatio || 1;
5398
- const svgXml = exportLiveSceneAsPureVectorSvg(containerEl, options);
5399
- const inlinedSvgXml = await inlineSerializedSvgResources(svgXml);
5392
+ const scene = getDiagramSceneElement(containerEl);
5393
+ const captureHtml = options.mode === "foreignObject" && scene.tagName.toLowerCase() !== "svg";
5394
+ let svgXml;
5395
+ if (captureHtml) {
5396
+ const { clonedScene, scaledWidth, scaledHeight } = preparedScene ?? prepareHtmlSceneForExport(scene, options);
5397
+ clonedScene.removeAttribute("xmlns");
5398
+ clonedScene.style.insetBlock = "auto";
5399
+ clonedScene.style.insetInline = "auto";
5400
+ for (const element of [clonedScene, ...Array.from(clonedScene.querySelectorAll("*"))]) {
5401
+ element.style.animation = "none";
5402
+ element.style.transition = "none";
5403
+ }
5404
+ if (!preparedScene) await inlineExternalResources(clonedScene);
5405
+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
5406
+ svg.setAttribute("width", String(scaledWidth));
5407
+ svg.setAttribute("height", String(scaledHeight));
5408
+ const content = document.createElementNS("http://www.w3.org/2000/svg", "foreignObject");
5409
+ content.setAttribute("width", "100%");
5410
+ content.setAttribute("height", "100%");
5411
+ content.appendChild(clonedScene);
5412
+ svg.appendChild(content);
5413
+ svgXml = new XMLSerializer().serializeToString(svg);
5414
+ } else {
5415
+ svgXml = exportLiveSceneAsPureVectorSvg(containerEl, options);
5416
+ }
5417
+ const inlinedSvgXml = captureHtml ? svgXml : await inlineSerializedSvgResources(svgXml);
5400
5418
  const blob = new Blob([inlinedSvgXml], { type: "image/svg+xml;charset=utf-8" });
5401
- const url = URL.createObjectURL(blob);
5419
+ const url = captureHtml ? `data:image/svg+xml;charset=utf-8,${encodeURIComponent(inlinedSvgXml)}` : URL.createObjectURL(blob);
5402
5420
  const img = new Image();
5403
5421
  await new Promise((resolve, reject) => {
5404
5422
  img.onload = () => resolve();
@@ -5423,6 +5441,72 @@ async function rasterizeDiagramToCanvas(containerEl, options = {}, pixelRatio =
5423
5441
  URL.revokeObjectURL(url);
5424
5442
  return canvas;
5425
5443
  }
5444
+ var FRAME_STYLE_PROPERTIES = [
5445
+ "opacity",
5446
+ "visibility",
5447
+ "transform",
5448
+ "transform-origin",
5449
+ "filter",
5450
+ "clip-path",
5451
+ "box-shadow",
5452
+ "text-shadow",
5453
+ "background-color",
5454
+ "color",
5455
+ "border-color",
5456
+ "border-top-color",
5457
+ "border-right-color",
5458
+ "border-bottom-color",
5459
+ "border-left-color",
5460
+ "fill",
5461
+ "fill-opacity",
5462
+ "stroke",
5463
+ "stroke-opacity",
5464
+ "stroke-width",
5465
+ "stroke-dasharray",
5466
+ "stroke-dashoffset",
5467
+ "offset-path",
5468
+ "offset-distance",
5469
+ "offset-rotate",
5470
+ "offset-anchor"
5471
+ ];
5472
+ var FRAME_SVG_ATTRIBUTES = ["cx", "cy", "r", "x", "y", "d", "points", "transform"];
5473
+ function createDiagramFrameRasterizer(container, options) {
5474
+ const scene = getDiagramSceneElement(container);
5475
+ if (options.mode !== "foreignObject" || scene.tagName.toLowerCase() === "svg") {
5476
+ return (pixelRatio) => rasterizeDiagramToCanvas(container, options, pixelRatio);
5477
+ }
5478
+ let prepared;
5479
+ let sources = [];
5480
+ let clones = [];
5481
+ return async (pixelRatio) => {
5482
+ if (!prepared) {
5483
+ prepared = prepareHtmlSceneForExport(scene, options);
5484
+ sources = Array.from(scene.querySelectorAll("*"));
5485
+ clones = Array.from(prepared.clonedScene.querySelectorAll("*"));
5486
+ await inlineExternalResources(prepared.clonedScene);
5487
+ } else {
5488
+ if (scene.querySelectorAll("*").length !== sources.length || sources.some((source) => !scene.contains(source))) {
5489
+ throw new Error("Scene changed during GIF export");
5490
+ }
5491
+ for (let index = 0; index < sources.length; index++) {
5492
+ const source = sources[index];
5493
+ const clone = clones[index];
5494
+ if (source.classList.contains("markdy-viewport-transform")) continue;
5495
+ const computed = getComputedStyle(source);
5496
+ for (const property of FRAME_STYLE_PROPERTIES) {
5497
+ clone.style.setProperty(property, computed.getPropertyValue(property));
5498
+ }
5499
+ if (source.namespaceURI === "http://www.w3.org/2000/svg") {
5500
+ for (const attribute of FRAME_SVG_ATTRIBUTES) {
5501
+ const value = source.getAttribute(attribute);
5502
+ if (value !== null) clone.setAttribute(attribute, value);
5503
+ }
5504
+ }
5505
+ }
5506
+ }
5507
+ return rasterizeDiagramToCanvas(container, options, pixelRatio, prepared);
5508
+ };
5509
+ }
5426
5510
 
5427
5511
  // src/export/gif-encoder.ts
5428
5512
  var GIF_HEADER = "GIF89a";
@@ -5711,6 +5795,7 @@ function encodeGifSequence(frames, options = {}) {
5711
5795
  buffer.push(3, 1, 0, 0, 0);
5712
5796
  }
5713
5797
  let prevQuantized = null;
5798
+ let previousDelayOffset = -1;
5714
5799
  for (let frameIdx = 0; frameIdx < frames.length; frameIdx++) {
5715
5800
  const frame = frames[frameIdx];
5716
5801
  const currQuantized = quantizer.quantize(frame.imageData);
@@ -5718,6 +5803,7 @@ function encodeGifSequence(frames, options = {}) {
5718
5803
  if (!enableDiff || prevQuantized === null || frameIdx === 0) {
5719
5804
  const compressedWithHeader = lzwCompress(currQuantized);
5720
5805
  buffer.push(33, 249, 4, 4);
5806
+ previousDelayOffset = buffer.length;
5721
5807
  pushU16(delayHundredths);
5722
5808
  buffer.push(0, 0);
5723
5809
  buffer.push(44);
@@ -5747,7 +5833,14 @@ function encodeGifSequence(frames, options = {}) {
5747
5833
  }
5748
5834
  }
5749
5835
  if (maxX < minX || maxY < minY) {
5750
- continue;
5836
+ const previousDelay = buffer[previousDelayOffset] | buffer[previousDelayOffset + 1] << 8;
5837
+ const combinedDelay = previousDelay + delayHundredths;
5838
+ if (combinedDelay <= 65535) {
5839
+ buffer[previousDelayOffset] = combinedDelay & 255;
5840
+ buffer[previousDelayOffset + 1] = combinedDelay >> 8;
5841
+ continue;
5842
+ }
5843
+ minX = maxX = minY = maxY = 0;
5751
5844
  }
5752
5845
  const diffW = maxX - minX + 1;
5753
5846
  const diffH = maxY - minY + 1;
@@ -5765,6 +5858,7 @@ function encodeGifSequence(frames, options = {}) {
5765
5858
  }
5766
5859
  const compressedWithHeader = lzwCompress(diffData);
5767
5860
  buffer.push(33, 249, 4, 5);
5861
+ previousDelayOffset = buffer.length;
5768
5862
  pushU16(delayHundredths);
5769
5863
  buffer.push(TRANSPARENT_COLOR_INDEX, 0);
5770
5864
  buffer.push(44);
@@ -5797,34 +5891,51 @@ var nextFrame = () => new Promise((resolve) => {
5797
5891
  finish();
5798
5892
  }));
5799
5893
  });
5800
- var DEFAULT_GIF_PIXEL_RATIO = 2;
5801
- var DEFAULT_GIF_FPS = 20;
5802
- var MAX_GIF_FRAMES = 96;
5803
- async function rasterizeFrame(container, pixelRatio, options) {
5804
- const canvas = await rasterizeDiagramToCanvas(container, options, pixelRatio);
5894
+ var DEFAULT_GIF_PIXEL_RATIO = 1;
5895
+ var DEFAULT_GIF_FPS = 12;
5896
+ var MAX_GIF_FRAMES = 120;
5897
+ var MAX_GIF_PIXELS = 48 * 1024 * 1024;
5898
+ function positiveOption(value, fallback, name) {
5899
+ const resolved = value ?? fallback;
5900
+ if (!Number.isFinite(resolved) || resolved <= 0) throw new RangeError(`${name} must be a positive finite number`);
5901
+ return resolved;
5902
+ }
5903
+ async function rasterizeFrame(capture, pixelRatio) {
5904
+ const canvas = await capture(pixelRatio);
5805
5905
  const context = canvas.getContext("2d");
5806
5906
  if (!context) throw new Error("Could not create GIF canvas context");
5807
5907
  return context.getImageData(0, 0, canvas.width, canvas.height);
5808
5908
  }
5809
5909
  async function exportDiagramAsGif(container, timeline, options = {}) {
5810
- const requestedFps = Math.min(30, Math.max(1, Math.round(options.fps ?? DEFAULT_GIF_FPS)));
5910
+ const requestedFps = Math.min(30, positiveOption(options.fps, DEFAULT_GIF_FPS, "fps"));
5911
+ const maxFrames = Math.floor(positiveOption(options.maxFrames, MAX_GIF_FRAMES, "maxFrames"));
5912
+ if (maxFrames < 2) throw new RangeError("maxFrames must be at least 2");
5913
+ const maxWidth = positiveOption(options.maxWidth, 1600, "maxWidth");
5914
+ const requestedPixelRatio = positiveOption(options.pixelRatio, DEFAULT_GIF_PIXEL_RATIO, "pixelRatio");
5915
+ const scale = positiveOption(options.scale, 1, "scale");
5811
5916
  const rawDuration = timeline.duration();
5812
5917
  const duration = Math.max(Number.isFinite(rawDuration) ? rawDuration : 1, 0.1);
5813
- const fps = Math.min(requestedFps, Math.max(6, Math.round(MAX_GIF_FRAMES / duration)));
5814
- const frameCount = Math.max(1, Math.ceil(duration * fps));
5815
- const delayMs = Math.max(20, Math.round(1e3 / fps));
5816
- const pixelRatio = options.pixelRatio ?? DEFAULT_GIF_PIXEL_RATIO;
5817
- const holdEndMs = Math.max(delayMs, options.holdEndMs ?? 1400);
5918
+ const frameCount = Math.min(maxFrames - 1, Math.max(1, Math.ceil(duration * requestedFps)));
5919
+ const totalFrames = frameCount + 1;
5920
+ const holdEndMs = Math.max(20, options.holdEndMs ?? 1400);
5921
+ if (!Number.isFinite(holdEndMs)) throw new RangeError("holdEndMs must be finite");
5922
+ const scene = getDiagramSceneElement(container);
5923
+ const width = (scene.clientWidth || parseFloat(scene.style.width) || 800) * scale;
5924
+ const height = (scene.clientHeight || parseFloat(scene.style.height) || 400) * scale;
5925
+ const pixelRatio = Math.min(requestedPixelRatio, maxWidth / width, Math.sqrt(MAX_GIF_PIXELS / (width * height * totalFrames)));
5926
+ const captureOptions = { ...options, mode: options.mode ?? "foreignObject" };
5927
+ const capture = createDiagramFrameRasterizer(container, captureOptions);
5818
5928
  const priorTime = timeline.currentTime();
5819
5929
  const wasPlaying = timeline.isPlaying();
5820
5930
  timeline.pause();
5821
5931
  try {
5932
+ await container.ownerDocument.fonts?.ready;
5822
5933
  const frames = [];
5823
- const totalFrames = frameCount + 1;
5824
5934
  for (let frame = 0; frame < frameCount; frame++) {
5825
- timeline.seek(Math.min(duration, frame / fps));
5935
+ timeline.seek(duration * frame / frameCount);
5826
5936
  await nextFrame();
5827
- const imageData = await rasterizeFrame(container, pixelRatio, options);
5937
+ const imageData = await rasterizeFrame(capture, pixelRatio);
5938
+ const delayMs = 10 * (Math.round((frame + 1) * duration * 100 / frameCount) - Math.round(frame * duration * 100 / frameCount));
5828
5939
  frames.push({
5829
5940
  imageData,
5830
5941
  delayMs
@@ -5833,7 +5944,7 @@ async function exportDiagramAsGif(container, timeline, options = {}) {
5833
5944
  }
5834
5945
  timeline.seek(duration);
5835
5946
  await nextFrame();
5836
- const finalImageData = await rasterizeFrame(container, pixelRatio, options);
5947
+ const finalImageData = await rasterizeFrame(capture, pixelRatio);
5837
5948
  frames.push({
5838
5949
  imageData: finalImageData,
5839
5950
  delayMs: holdEndMs
@@ -5966,6 +6077,27 @@ var CANVAS_WIDE_ARCHETYPES = /* @__PURE__ */ new Set([
5966
6077
  "gantt"
5967
6078
  ]);
5968
6079
  function computeDiagramContentBounds(plan, options) {
6080
+ if (options?.routedEdges) {
6081
+ const bounds = computeDiagramContentBounds(plan, { tight: options.tight, padding: options.padding });
6082
+ const padding = options.padding ?? (options.tight === false ? 36 : plan.groupBoundaries?.length ? 28 : 22);
6083
+ for (const edge of options.routedEdges) {
6084
+ for (const point of edge.points) {
6085
+ bounds.minX = Math.min(bounds.minX, point.x - padding);
6086
+ bounds.minY = Math.min(bounds.minY, point.y - padding);
6087
+ bounds.maxX = Math.max(bounds.maxX, point.x + padding);
6088
+ bounds.maxY = Math.max(bounds.maxY, point.y + padding);
6089
+ }
6090
+ if (edge.labelRect) {
6091
+ bounds.minX = Math.min(bounds.minX, edge.labelRect.x1 - padding);
6092
+ bounds.minY = Math.min(bounds.minY, edge.labelRect.y1 - padding);
6093
+ bounds.maxX = Math.max(bounds.maxX, edge.labelRect.x2 + padding);
6094
+ bounds.maxY = Math.max(bounds.maxY, edge.labelRect.y2 + padding);
6095
+ }
6096
+ }
6097
+ bounds.width = bounds.maxX - bounds.minX;
6098
+ bounds.height = bounds.maxY - bounds.minY;
6099
+ return bounds;
6100
+ }
5969
6101
  if (!plan.nodes || plan.nodes.length === 0) {
5970
6102
  return { minX: 0, minY: 0, maxX: plan.meta.width, maxY: plan.meta.height, width: plan.meta.width, height: plan.meta.height };
5971
6103
  }
@@ -6023,8 +6155,8 @@ function computeDiagramContentBounds(plan, options) {
6023
6155
  const titleText = (plan.title ?? plan.meta?.title ?? "").trim();
6024
6156
  const hasTitle = titleText.length > 0;
6025
6157
  if (hasTitle) {
6026
- minX = 0;
6027
- minY = 0;
6158
+ minX = Math.min(minX, 0);
6159
+ minY = Math.min(minY, 0);
6028
6160
  const titleEstimatedW = Math.min(plan.meta.width, 56 + titleText.length * 17 + 56);
6029
6161
  maxX = Math.max(maxX, titleEstimatedW);
6030
6162
  maxY = Math.max(maxY, 72);
@@ -6044,15 +6176,15 @@ function computeDiagramContentBounds(plan, options) {
6044
6176
  }
6045
6177
  const defaultPad = plan.groupBoundaries && plan.groupBoundaries.length > 0 ? 28 : 22;
6046
6178
  const pad = options?.padding ?? (options?.tight === false ? 36 : defaultPad);
6047
- minX = Math.max(-pad, minX - pad);
6048
- minY = Math.max(-pad, minY - pad);
6049
- maxX = Math.min(plan.meta.width + pad, maxX + pad);
6050
- maxY = Math.min(plan.meta.height + pad, maxY + pad);
6179
+ minX -= pad;
6180
+ minY -= pad;
6181
+ maxX += pad;
6182
+ maxY += pad;
6051
6183
  if (minX > 0 && minX <= pad) minX = 0;
6052
6184
  if (minY > 0 && minY <= pad) minY = 0;
6053
6185
  if (hasTitle) {
6054
- minX = 0;
6055
- minY = 0;
6186
+ if (minX === -pad) minX = 0;
6187
+ if (minY === -pad) minY = 0;
6056
6188
  }
6057
6189
  const width = Math.max(maxX - minX, 100);
6058
6190
  const height = Math.max(maxY - minY, 80);
@@ -6079,39 +6211,37 @@ function createDiagram(opts) {
6079
6211
  onTimeUpdate,
6080
6212
  onPlayStateChange,
6081
6213
  onEnded,
6082
- responsiveLayout = true,
6083
- fitMode = "width",
6214
+ responsiveLayout = "auto",
6215
+ fitMode = "auto",
6216
+ minReadableScale = 0.9,
6084
6217
  targetWidthRatio = 0.96,
6085
6218
  contentPadding
6086
6219
  } = opts;
6087
- function detectContainerOrientation() {
6088
- const cWidth = container?.clientWidth || 0;
6089
- const cHeight = container?.clientHeight || 0;
6090
- if (typeof window === "undefined") {
6091
- if (cWidth > 0 && cHeight > 0) {
6092
- return cHeight > cWidth * 1.05 ? "portrait" : "landscape";
6220
+ function detectContainerOrientation(previous) {
6221
+ const width = container.clientWidth || (typeof window === "undefined" ? 1024 : window.innerWidth);
6222
+ const height = container.clientHeight || 0;
6223
+ const breakpoint = previous === "portrait" ? 672 : previous === "landscape" ? 608 : 640;
6224
+ if (height > 0 && container.clientHeight > 0) {
6225
+ const ratio = width / height;
6226
+ const ratioBreakpoint = previous === "portrait" ? 1.15 : previous === "landscape" ? 0.88 : 1;
6227
+ if (ratio >= ratioBreakpoint) {
6228
+ return "landscape";
6093
6229
  }
6094
- return "landscape";
6095
- }
6096
- const isMobileViewport = window.innerWidth < 768;
6097
- if (isMobileViewport) {
6098
6230
  return "portrait";
6099
6231
  }
6100
- if (cWidth > 0 && cHeight > 0) {
6101
- if (cHeight > cWidth * 1.18) return "portrait";
6102
- return "landscape";
6103
- }
6104
- return window.innerWidth < window.innerHeight ? "portrait" : "landscape";
6232
+ return width < breakpoint ? "portrait" : "landscape";
6105
6233
  }
6106
6234
  const ast = parse(code);
6107
6235
  for (const w of ast.diagnostics) {
6108
6236
  if (w.severity === "warning") onWarning(w);
6109
6237
  }
6110
6238
  const hasExplicitDirection = ast.meta.explicitDirection === true;
6111
- const shouldAdaptOrientation = responsiveLayout !== false && !hasExplicitDirection;
6239
+ const shouldAdaptOrientation = responsiveLayout === true || responsiveLayout === "auto" && !hasExplicitDirection;
6240
+ const reverseDirection = ast.meta.direction === "RL" || ast.meta.direction === "BT";
6241
+ const directionForOrientation = (orientation) => orientation === "portrait" ? reverseDirection ? "BT" : "TB" : reverseDirection ? "RL" : "LR";
6112
6242
  let activeOrientation = detectContainerOrientation();
6113
6243
  if (shouldAdaptOrientation) {
6114
- ast.meta.direction = activeOrientation === "portrait" ? "TB" : "LR";
6244
+ ast.meta.direction = directionForOrientation(activeOrientation);
6115
6245
  }
6116
6246
  if (!ast.meta.explicitWidth || !ast.meta.explicitHeight) {
6117
6247
  const dims = computeAdaptiveDimensions(ast);
@@ -6209,16 +6339,21 @@ function createDiagram(opts) {
6209
6339
  progressEl = document.createElement("div");
6210
6340
  progressEl.className = progressMode === "bar" ? "markdy-progress-bar" : "markdy-boundary-progress";
6211
6341
  Object.assign(progressEl.style, {
6212
- position: "absolute",
6213
- ...progressMode === "bar" ? { left: "0", right: "0", bottom: "0", height: "3px" } : { inset: "0" },
6342
+ ...progressMode === "bar" ? { position: "absolute", left: "0", right: "0", bottom: "0", height: "3px" } : {
6343
+ position: "sticky",
6344
+ top: "0",
6345
+ left: "0",
6346
+ width: "100%",
6347
+ height: "100%",
6348
+ marginRight: "-100%",
6349
+ marginBottom: "-100%"
6350
+ },
6214
6351
  zIndex: "9999",
6215
6352
  pointerEvents: "none",
6216
6353
  borderRadius: "inherit"
6217
6354
  });
6218
6355
  viewport.appendChild(progressEl);
6219
6356
  }
6220
- const tlAngle = Math.atan2(-plan.meta.width / 2, plan.meta.height / 2) * 180 / Math.PI;
6221
- const tlAngleNorm = (tlAngle % 360 + 360) % 360;
6222
6357
  function updateProgressBar(pct) {
6223
6358
  if (!progressEl) return;
6224
6359
  if (progressMode === "bar") {
@@ -6229,7 +6364,11 @@ function createDiagram(opts) {
6229
6364
  }
6230
6365
  const deg = pct * 360;
6231
6366
  const colorStops = customColor ? customColor.includes(",") ? customColor : `${customColor} 0deg, ${customColor}` : DEFAULT_RAINBOW;
6232
- progressEl.style.background = `conic-gradient(from ${tlAngleNorm}deg, ${colorStops} ${deg}deg, transparent ${deg}deg)`;
6367
+ const vw = progressEl.clientWidth || viewport.clientWidth || plan.meta.width;
6368
+ const vh = progressEl.clientHeight || viewport.clientHeight || plan.meta.height;
6369
+ const currentAngle = Math.atan2(-vw / 2, vh / 2) * 180 / Math.PI;
6370
+ const currentAngleNorm = (currentAngle % 360 + 360) % 360;
6371
+ progressEl.style.background = `conic-gradient(from ${currentAngleNorm}deg, ${colorStops} ${deg}deg, transparent ${deg}deg)`;
6233
6372
  progressEl.style.mask = "linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0)";
6234
6373
  progressEl.style.webkitMask = progressEl.style.mask;
6235
6374
  progressEl.style.maskComposite = "exclude";
@@ -6292,6 +6431,10 @@ function createDiagram(opts) {
6292
6431
  }
6293
6432
  ensureSceneStyles(document);
6294
6433
  ensureNodeStyles(document);
6434
+ const sceneFrame = document.createElement("div");
6435
+ sceneFrame.className = "markdy-scene-frame";
6436
+ Object.assign(sceneFrame.style, { position: "absolute", left: "0", top: "0", width: "100%", height: "100%", overflow: "hidden" });
6437
+ viewport.appendChild(sceneFrame);
6295
6438
  const scene = document.createElement("div");
6296
6439
  scene.className = "markdy-scene-root";
6297
6440
  Object.assign(scene.style, {
@@ -6305,7 +6448,7 @@ function createDiagram(opts) {
6305
6448
  transformOrigin: "0 0"
6306
6449
  });
6307
6450
  applyThemeToScene(scene, plan.theme);
6308
- viewport.appendChild(scene);
6451
+ sceneFrame.appendChild(scene);
6309
6452
  const viewportTransform = document.createElement("div");
6310
6453
  viewportTransform.className = "markdy-viewport-transform";
6311
6454
  Object.assign(viewportTransform.style, {
@@ -6453,26 +6596,31 @@ function createDiagram(opts) {
6453
6596
  let fitScale = 1;
6454
6597
  let sceneOffsetX = 0;
6455
6598
  let sceneOffsetY = 0;
6599
+ let scrollableViewport = false;
6600
+ let lastScrollBounds = null;
6601
+ let contentBounds = computeDiagramContentBounds(plan, { padding: contentPadding, routedEdges: edgeRuntimes.values() });
6602
+ viewport.style.aspectRatio = `${contentBounds.width} / ${contentBounds.height}`;
6603
+ const layoutPlans = /* @__PURE__ */ new Map();
6604
+ layoutPlans.set(ast.meta.direction, { plan: { ...plan, meta: { ...plan.meta } }, bounds: initialBounds });
6605
+ function layoutForDirection(direction) {
6606
+ const cached = layoutPlans.get(direction);
6607
+ if (cached?.plan.theme === plan.theme) return cached;
6608
+ const candidate = compilePlan({ ...ast, meta: { ...ast.meta, direction } }, plan.theme);
6609
+ const entry = { plan: candidate, bounds: computeDiagramContentBounds(candidate, { padding: contentPadding }) };
6610
+ layoutPlans.set(direction, entry);
6611
+ return entry;
6612
+ }
6456
6613
  function computeContentBounds() {
6457
- return computeDiagramContentBounds(plan, contentPadding !== void 0 ? { padding: contentPadding } : void 0);
6614
+ return contentBounds;
6458
6615
  }
6459
6616
  function relayoutOrientation(newDirection) {
6460
- ast.meta.direction = newDirection;
6461
- const dims = computeAdaptiveDimensions(ast);
6462
- if (!ast.meta.explicitWidth) ast.meta.width = dims.width;
6463
- if (!ast.meta.explicitHeight) ast.meta.height = dims.height;
6464
- const newPlan = compilePlan(ast, plan.theme);
6465
- const newBounds = computeDiagramContentBounds(newPlan, contentPadding !== void 0 ? { padding: contentPadding } : void 0);
6617
+ const { plan: newPlan, bounds: newBounds } = layoutForDirection(newDirection);
6618
+ Object.assign(ast.meta, newPlan.meta);
6466
6619
  scene.style.width = `${newPlan.meta.width}px`;
6467
6620
  scene.style.height = `${newPlan.meta.height}px`;
6468
6621
  viewport.style.aspectRatio = `${newBounds.width} / ${newBounds.height}`;
6469
- plan.nodes = newPlan.nodes;
6470
- plan.edges = newPlan.edges;
6471
- plan.groupBoundaries = newPlan.groupBoundaries;
6472
- plan.treeBuses = newPlan.treeBuses;
6473
- plan.cues = newPlan.cues;
6474
- plan.beats = newPlan.beats;
6475
- plan.meta = newPlan.meta;
6622
+ Object.assign(plan, newPlan);
6623
+ contentBounds = newBounds;
6476
6624
  for (const node of plan.nodes) {
6477
6625
  const el = nodeEls.get(node.id);
6478
6626
  if (el) {
@@ -6502,6 +6650,14 @@ function createDiagram(opts) {
6502
6650
  } else if (plan.diagramType === "gantt") {
6503
6651
  mountGanttLayer(constellationLayer, plan.nodes, plan.theme, { width: plan.meta.width, height: plan.meta.height });
6504
6652
  }
6653
+ for (const anim of allAnims) anim.cancel();
6654
+ cameraLayer.querySelectorAll(":scope > svg").forEach((layer) => layer.remove());
6655
+ sequenceLayer.replaceChildren();
6656
+ annotationLayer.replaceChildren();
6657
+ mountAnnotations(annotationLayer, plan.annotations, plan.nodes, plan.theme, {
6658
+ width: plan.meta.width,
6659
+ height: plan.meta.height
6660
+ });
6505
6661
  structuralEdgeHost.innerHTML = "";
6506
6662
  edgeRuntimes.clear();
6507
6663
  const newStructuralAnims = buildStructuralEdgeAnimations(
@@ -6516,7 +6672,6 @@ function createDiagram(opts) {
6516
6672
  plan.cues,
6517
6673
  Boolean(plan.treeBuses?.some((b) => b.vertical) || ast.meta.direction === "TB")
6518
6674
  );
6519
- for (const anim of allAnims) anim.cancel();
6520
6675
  allAnims = [
6521
6676
  ...plan.diagramType === "sequence" ? mountSequenceLayer(
6522
6677
  sequenceLayer,
@@ -6543,6 +6698,8 @@ function createDiagram(opts) {
6543
6698
  ),
6544
6699
  ...buildBeatCaptionAnimations(plan.beats, captionLayer)
6545
6700
  ];
6701
+ contentBounds = computeDiagramContentBounds(plan, { padding: contentPadding, routedEdges: edgeRuntimes.values() });
6702
+ viewport.style.aspectRatio = `${contentBounds.width} / ${contentBounds.height}`;
6546
6703
  applyCurrentTime();
6547
6704
  scaleScene();
6548
6705
  }
@@ -6558,29 +6715,48 @@ function createDiagram(opts) {
6558
6715
  scene.style.transform = "scale(1)";
6559
6716
  return;
6560
6717
  }
6561
- if (shouldAdaptOrientation) {
6562
- const currentOrientation = detectContainerOrientation();
6718
+ const vWidth = viewport.clientWidth || container.clientWidth || plan.meta.width;
6719
+ const naturalHeight = vWidth * contentBounds.height / contentBounds.width;
6720
+ const vHeight = viewport.clientHeight || container.clientHeight || naturalHeight;
6721
+ const resolvedFit = fitViewActive ? "contain" : fitMode === "auto" ? Math.abs(vHeight - naturalHeight) > 2 ? "contain" : "width" : fitMode;
6722
+ const targetRatio = Math.min(1, Math.max(0.9, targetWidthRatio ?? 0.96));
6723
+ if (shouldAdaptOrientation && !fitViewActive) {
6724
+ let currentOrientation = detectContainerOrientation(activeOrientation);
6725
+ if (fitMode === "auto" && (!ast.meta.explicitWidth || !ast.meta.explicitHeight) && ["architecture", "flowchart", "state", "tree", "medallion", "swimlane", "timeline", "gantt", "layers", "loop"].includes(plan.diagramType)) {
6726
+ const isHeightConstrained = resolvedFit === "contain" || vHeight > 0 && Math.abs(vHeight - naturalHeight) > 2;
6727
+ const containerRatio = vWidth / Math.max(1, vHeight);
6728
+ if (!(activeOrientation === "landscape" && containerRatio >= 1)) {
6729
+ const score = (orientation) => {
6730
+ const { bounds: bounds2 } = layoutForDirection(directionForOrientation(orientation));
6731
+ const widthScale2 = vWidth * targetRatio / bounds2.width;
6732
+ const heightScale = isHeightConstrained ? Math.max(1, vHeight - 24) * targetRatio / bounds2.height : 1;
6733
+ return Math.min(1, widthScale2, heightScale);
6734
+ };
6735
+ const alternative = activeOrientation === "portrait" ? "landscape" : "portrait";
6736
+ currentOrientation = score(alternative) > score(activeOrientation) * 1.2 ? alternative : activeOrientation;
6737
+ }
6738
+ }
6563
6739
  if (currentOrientation !== activeOrientation) {
6564
6740
  activeOrientation = currentOrientation;
6565
- relayoutOrientation(activeOrientation === "portrait" ? "TB" : "LR");
6741
+ relayoutOrientation(directionForOrientation(activeOrientation));
6566
6742
  return;
6567
6743
  }
6568
6744
  }
6569
- const vWidth = viewport.clientWidth || container.clientWidth || plan.meta.width;
6570
- const fallbackHeight = vWidth * plan.meta.height / plan.meta.width;
6571
- const vHeight = viewport.clientHeight || container.clientHeight || fallbackHeight;
6572
6745
  const bounds = computeContentBounds();
6573
6746
  const contentW = bounds.width;
6574
6747
  const contentH = bounds.height;
6575
- const targetRatio = Math.min(1, Math.max(0.9, targetWidthRatio ?? 0.96));
6576
6748
  const widthScale = vWidth * targetRatio / contentW;
6577
- if (fitMode === "contain") {
6749
+ if (resolvedFit === "contain") {
6578
6750
  const heightScale = (vHeight - 24) * targetRatio / contentH;
6579
6751
  fitScale = Math.min(widthScale, heightScale);
6580
6752
  } else {
6581
6753
  fitScale = widthScale;
6582
6754
  }
6583
6755
  if (!Number.isFinite(fitScale) || fitScale <= 0) fitScale = 1;
6756
+ if (fitMode === "auto" && !fitViewActive) {
6757
+ const minimum = Number.isFinite(minReadableScale) && minReadableScale >= 0 && minReadableScale <= 1 ? minReadableScale : 0.9;
6758
+ fitScale = Math.max(fitScale, minimum);
6759
+ }
6584
6760
  scene.style.setProperty("--markdy-scale", fitScale.toFixed(4));
6585
6761
  viewport.style.setProperty("--markdy-scale", fitScale.toFixed(4));
6586
6762
  container.style.setProperty("--markdy-scale", fitScale.toFixed(4));
@@ -6589,9 +6765,26 @@ function createDiagram(opts) {
6589
6765
  }
6590
6766
  const scaledContentW = contentW * fitScale;
6591
6767
  const scaledContentH = contentH * fitScale;
6592
- sceneOffsetX = (vWidth - scaledContentW) / 2 - bounds.minX * fitScale;
6593
- if (fitMode === "contain") {
6594
- sceneOffsetY = (vHeight - scaledContentH) / 2 - bounds.minY * fitScale;
6768
+ const resetScroll = !scrollableViewport || lastScrollBounds !== bounds;
6769
+ scrollableViewport = fitMode === "auto" && (scaledContentW > vWidth || scaledContentH > vHeight);
6770
+ lastScrollBounds = bounds;
6771
+ const frameWidth = scrollableViewport ? Math.max(vWidth, scaledContentW + 24) : vWidth;
6772
+ const frameHeight = scrollableViewport ? Math.max(vHeight, scaledContentH + 28) : vHeight;
6773
+ sceneFrame.style.width = scrollableViewport ? `${frameWidth}px` : "100%";
6774
+ sceneFrame.style.height = scrollableViewport ? `${frameHeight}px` : "100%";
6775
+ viewport.style.overflow = scrollableViewport ? "auto" : "hidden";
6776
+ viewport.style.touchAction = scrollableViewport ? "pan-x pan-y" : interactiveViewport ? "pan-y" : "auto";
6777
+ viewport.dataset.fitMode = resolvedFit;
6778
+ if (scrollableViewport) {
6779
+ viewport.tabIndex = 0;
6780
+ viewport.setAttribute("aria-label", plan.title || "Diagram");
6781
+ } else {
6782
+ viewport.removeAttribute("tabindex");
6783
+ viewport.removeAttribute("aria-label");
6784
+ }
6785
+ sceneOffsetX = (frameWidth - scaledContentW) / 2 - bounds.minX * fitScale;
6786
+ if (resolvedFit === "contain") {
6787
+ sceneOffsetY = (frameHeight - scaledContentH) / 2 - bounds.minY * fitScale;
6595
6788
  } else {
6596
6789
  const topSafeMargin = scaledContentH <= vHeight ? Math.max(14, Math.min(24, (vHeight - scaledContentH) / 2)) : 14;
6597
6790
  sceneOffsetY = topSafeMargin - bounds.minY * fitScale;
@@ -6600,11 +6793,28 @@ function createDiagram(opts) {
6600
6793
  scene.style.top = `${sceneOffsetY}px`;
6601
6794
  scene.style.transformOrigin = "0 0";
6602
6795
  scene.style.transform = `scale(${fitScale})`;
6796
+ if (scrollableViewport || fitViewActive) {
6797
+ cameraLayer.style.setProperty("transform", "none", "important");
6798
+ } else if (cameraLayer.style.getPropertyPriority("transform") === "important") {
6799
+ cameraLayer.style.removeProperty("transform");
6800
+ }
6801
+ if (scrollableViewport && resetScroll) {
6802
+ viewport.scrollLeft = Math.max(0, (frameWidth - vWidth) / 2);
6803
+ viewport.scrollTop = 0;
6804
+ }
6603
6805
  }
6604
- scaleScene();
6605
- const resizeObserver = typeof ResizeObserver === "function" ? new ResizeObserver(scaleScene) : null;
6806
+ let resizeRafId = null;
6807
+ function scheduleResize() {
6808
+ if (resizeRafId !== null) return;
6809
+ resizeRafId = requestAnimationFrame(() => {
6810
+ resizeRafId = null;
6811
+ scaleScene();
6812
+ });
6813
+ }
6814
+ const resizeObserver = typeof ResizeObserver === "function" ? new ResizeObserver(scheduleResize) : null;
6606
6815
  resizeObserver?.observe(viewport);
6607
6816
  if (container !== viewport) resizeObserver?.observe(container);
6817
+ if (!resizeObserver && typeof window !== "undefined") window.addEventListener("resize", scheduleResize);
6608
6818
  let sceneMs = 0;
6609
6819
  let lastRafTs = null;
6610
6820
  let isPlaying = false;
@@ -6650,12 +6860,15 @@ function createDiagram(opts) {
6650
6860
  viewportScale = 1;
6651
6861
  viewportPanX = 0;
6652
6862
  viewportPanY = 0;
6863
+ viewport.scrollLeft = scrollableViewport ? Math.max(0, (contentBounds.width * fitScale + 24 - (viewport.clientWidth || container.clientWidth)) / 2) : 0;
6864
+ viewport.scrollTop = 0;
6653
6865
  applyViewportTransform();
6654
6866
  }
6655
6867
  function releaseFitView() {
6656
6868
  if (!fitViewActive) return;
6657
6869
  fitViewActive = false;
6658
6870
  cameraLayer.style.removeProperty("transform");
6871
+ scaleScene();
6659
6872
  }
6660
6873
  function toggleFitView() {
6661
6874
  if (fitViewActive) {
@@ -6663,21 +6876,23 @@ function createDiagram(opts) {
6663
6876
  syncControls();
6664
6877
  return;
6665
6878
  }
6666
- const bounds = computeContentBounds();
6667
- const scale = Math.min(plan.meta.width / bounds.width, plan.meta.height / bounds.height);
6668
- viewportScale = Number.isFinite(scale) && scale > 0 ? scale : 1;
6669
- viewportPanX = -bounds.minX * viewportScale + (plan.meta.width - bounds.width * viewportScale) / 2;
6670
- viewportPanY = -bounds.minY * viewportScale + (plan.meta.height - bounds.height * viewportScale) / 2;
6879
+ viewportScale = 1;
6880
+ viewportPanX = 0;
6881
+ viewportPanY = 0;
6671
6882
  applyViewportTransform();
6672
6883
  fitViewActive = true;
6673
6884
  cameraLayer.style.setProperty("transform", "none", "important");
6885
+ scaleScene();
6886
+ viewport.scrollLeft = 0;
6887
+ viewport.scrollTop = 0;
6674
6888
  syncControls();
6675
6889
  }
6676
6890
  function handleViewportWheel(event) {
6891
+ if (scrollableViewport && !event.ctrlKey && !event.metaKey) return;
6677
6892
  event.preventDefault();
6678
6893
  const rect = viewport.getBoundingClientRect();
6679
- const pointerX = (event.clientX - rect.left - sceneOffsetX) / fitScale;
6680
- const pointerY = (event.clientY - rect.top - sceneOffsetY) / fitScale;
6894
+ const pointerX = (event.clientX - rect.left + viewport.scrollLeft - sceneOffsetX) / fitScale;
6895
+ const pointerY = (event.clientY - rect.top + viewport.scrollTop - sceneOffsetY) / fitScale;
6681
6896
  const nextScale = Math.min(MAX_VIEWPORT_ZOOM, Math.max(MIN_VIEWPORT_ZOOM, viewportScale * Math.exp(-event.deltaY * VIEWPORT_ZOOM_STEP)));
6682
6897
  if (nextScale === viewportScale) return;
6683
6898
  const sceneX = (pointerX - viewportPanX) / viewportScale;
@@ -6688,6 +6903,7 @@ function createDiagram(opts) {
6688
6903
  applyViewportTransform();
6689
6904
  }
6690
6905
  function handleViewportPointerDown(event) {
6906
+ if (scrollableViewport) return;
6691
6907
  if (!allowPan) return;
6692
6908
  if (event.button !== 0 || activePointerId !== null) return;
6693
6909
  activePointerId = event.pointerId;
@@ -6757,18 +6973,34 @@ function createDiagram(opts) {
6757
6973
  syncControls();
6758
6974
  }
6759
6975
  function applyCurrentTime() {
6760
- for (const anim of allAnims) anim.currentTime = sceneMs;
6976
+ const timelineTime = document.timeline?.currentTime;
6977
+ const effectiveRate = playbackRate * NORMAL_PLAYBACK_RATE;
6978
+ for (const anim of allAnims) {
6979
+ anim.playbackRate = effectiveRate;
6980
+ if (isPlaying) {
6981
+ anim.currentTime = sceneMs;
6982
+ anim.play();
6983
+ if (typeof timelineTime === "number") anim.startTime = timelineTime - sceneMs / effectiveRate;
6984
+ } else {
6985
+ anim.pause();
6986
+ anim.currentTime = sceneMs;
6987
+ }
6988
+ }
6989
+ lastRafTs = isPlaying && typeof timelineTime === "number" ? timelineTime : null;
6761
6990
  onTimeUpdate?.(sceneMs / 1e3, durationSeconds);
6762
6991
  }
6763
6992
  function rafTick(timestamp) {
6764
6993
  if (lastRafTs !== null) sceneMs += (timestamp - lastRafTs) * playbackRate * NORMAL_PLAYBACK_RATE;
6765
6994
  lastRafTs = timestamp;
6766
6995
  if (totalDurationMs > 0 && sceneMs >= totalDurationMs) {
6767
- if (loop) sceneMs = sceneMs % totalDurationMs;
6768
- else {
6769
- sceneMs = totalDurationMs;
6996
+ if (loop) {
6997
+ sceneMs = sceneMs % totalDurationMs;
6770
6998
  applyCurrentTime();
6999
+ } else {
7000
+ sceneMs = totalDurationMs;
6771
7001
  isPlaying = false;
7002
+ applyCurrentTime();
7003
+ updateProgressBar(1);
6772
7004
  emitPlayStateChange(false);
6773
7005
  lastRafTs = null;
6774
7006
  rafId = null;
@@ -6776,7 +7008,7 @@ function createDiagram(opts) {
6776
7008
  return;
6777
7009
  }
6778
7010
  }
6779
- applyCurrentTime();
7011
+ onTimeUpdate?.(sceneMs / 1e3, durationSeconds);
6780
7012
  if (totalDurationMs > 0) updateProgressBar(sceneMs / totalDurationMs);
6781
7013
  rafId = requestAnimationFrame(rafTick);
6782
7014
  }
@@ -6784,13 +7016,14 @@ function createDiagram(opts) {
6784
7016
  play() {
6785
7017
  if (isPlaying) return;
6786
7018
  isPlaying = true;
7019
+ applyCurrentTime();
6787
7020
  emitPlayStateChange(true);
6788
- lastRafTs = null;
6789
7021
  rafId = requestAnimationFrame(rafTick);
6790
7022
  },
6791
7023
  pause() {
6792
7024
  if (!isPlaying) return;
6793
7025
  isPlaying = false;
7026
+ applyCurrentTime();
6794
7027
  emitPlayStateChange(false);
6795
7028
  if (rafId !== null) cancelAnimationFrame(rafId);
6796
7029
  rafId = null;
@@ -6805,6 +7038,7 @@ function createDiagram(opts) {
6805
7038
  setPlaybackRate(rate) {
6806
7039
  if (!Number.isFinite(rate) || rate <= 0) return;
6807
7040
  playbackRate = rate;
7041
+ applyCurrentTime();
6808
7042
  syncControls();
6809
7043
  },
6810
7044
  playbackRate() {
@@ -6987,6 +7221,8 @@ function createDiagram(opts) {
6987
7221
  }
6988
7222
  for (const anim of allAnims) anim.cancel();
6989
7223
  resizeObserver?.disconnect();
7224
+ if (resizeRafId !== null) cancelAnimationFrame(resizeRafId);
7225
+ if (!resizeObserver && typeof window !== "undefined") window.removeEventListener("resize", scheduleResize);
6990
7226
  removeFullscreenListeners?.();
6991
7227
  closeCodePanel?.();
6992
7228
  closeCodePanel = null;
@@ -7659,6 +7895,7 @@ function createDiagram(opts) {
7659
7895
  if (keyboardShortcuts && typeof window !== "undefined") {
7660
7896
  window.addEventListener("keydown", handleKeyDown);
7661
7897
  }
7898
+ scaleScene();
7662
7899
  if (autoplay) diagram.play();
7663
7900
  return diagram;
7664
7901
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@markdy/renderer-dom",
3
- "version": "1.4.2",
3
+ "version": "1.4.3",
4
4
  "description": "Browser renderer for diagram-native animated MarkdyScript architecture diagrams, built on the Web Animations API.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -46,14 +46,14 @@
46
46
  },
47
47
  "dependencies": {
48
48
  "html2canvas": "^1.4.1",
49
- "@markdy/core": "1.4.2"
49
+ "@markdy/core": "1.4.3"
50
50
  },
51
51
  "devDependencies": {
52
52
  "jsdom": "^29.1.1",
53
53
  "tsup": "^8.5.1",
54
54
  "typescript": "^5.9.3",
55
55
  "vitest": "^4.1.7",
56
- "@markdy/stdlib-systems": "1.4.2"
56
+ "@markdy/stdlib-systems": "1.4.3"
57
57
  },
58
58
  "scripts": {
59
59
  "build": "tsup",