@markdy/renderer-dom 1.4.2 → 1.4.4

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
@@ -4,12 +4,14 @@
4
4
  <a href="https://markdy.com/playground/"><img src="https://img.shields.io/badge/⚡_Live_Studio-markdy.com%2Fplayground-3b82f6?style=for-the-badge" alt="Live Studio" /></a>
5
5
  <a href="https://markdy.com/docs/"><img src="https://img.shields.io/badge/📖_Docs-Documentation-10b981?style=for-the-badge" alt="Documentation" /></a>
6
6
  <a href="https://markdy.com/examples/"><img src="https://img.shields.io/badge/🌟_Blueprints-30+_Examples-f59e0b?style=for-the-badge" alt="Examples" /></a>
7
+ <a href="https://github.com/sponsors/HoangYell"><img src="https://img.shields.io/badge/💖_Sponsor-Support_Markdy-ea4aaa?style=for-the-badge" alt="Sponsor Markdy" /></a>
7
8
  </p>
8
9
 
9
10
  Web Animations API renderer for [MarkdyScript](https://markdy.com/docs/) scenes. Translates a parsed AST into 60fps GPU-accelerated DOM elements and drives the animation timeline with interactive analytical capabilities (Blast Radius, Route Pathfinder, and SVG/GIF export).
10
11
 
11
12
  > 🚀 **Try it live**: Test MarkdyScript in the browser at **[markdy.com/playground](https://markdy.com/playground/)**
12
- > 📚 **Documentation**: Complete syntax guide and examples at **[markdy.com/docs](https://markdy.com/docs/)**
13
+ > 📚 **Documentation**: Complete syntax guide and examples at **[markdy.com/docs](https://markdy.com/docs/)**
14
+ > 💼 **Enterprise & Commercial**: Free under MIT. To support development or request custom architecture blueprints, explore **[GitHub Sponsors](https://github.com/sponsors/HoangYell)**.
13
15
 
14
16
  ## Features
15
17
 
@@ -76,6 +78,66 @@ const shortestPath = findShortestRoute("Client", "LedgerDb", ast);
76
78
  console.log("Route:", shortestPath); // ['Client', 'Gateway', 'PaymentSvc', 'LedgerDb']
77
79
  ```
78
80
 
81
+ ## Responsive Playback
82
+
83
+ Animations run on the browser's Web Animations timeline. JavaScript synchronizes
84
+ them on play, pause, seek, speed changes, and layout changes, not on every frame.
85
+
86
+ `responsiveLayout` controls whether the renderer may change orientation:
87
+
88
+ - `"auto"` (default): adapt diagrams without an explicit `layout` directive.
89
+ - `true`: also adapt diagrams that declare a direction, as in the playground.
90
+ - `false`: keep the source layout fixed and only scale the scene.
91
+
92
+ With `fitMode: "auto"` (default), automatically sized architecture, flowchart,
93
+ state, and tree diagrams compare cached horizontal and vertical layouts against
94
+ the available width and height. Orientation changes only when the alternative
95
+ improves the fitted scale by more than 20%. Other cases use a width breakpoint
96
+ around 640px with a 32px margin on either side. Reverse flow stays BT/RL, and
97
+ explicit scene dimensions are preserved, including partially specified sizes.
98
+
99
+ Auto fitting uses width-first framing in natural-height embeds and contain
100
+ framing in height-constrained hosts. If fitting requires a scale below
101
+ `minReadableScale` (default `0.9`, valid range `0` to `1`), the viewport scrolls
102
+ instead of shrinking further. Set it to `0` to disable the readability floor.
103
+ The Fit control toggles between a contained overview and readable framing.
104
+ Scrollable framing starts horizontally centered and pins storyboard camera motion
105
+ so frame cues do not compete with manual scrolling; other animations keep playing.
106
+ Explicit `fitMode: "width"` and `fitMode: "contain"` keep their original scaling
107
+ behavior without a readability floor.
108
+
109
+ Bounds include routed paths and label rectangles, even outside the estimated
110
+ scene dimensions, and are cached after mounting or re-layout. Container resizing
111
+ preserves playback time and state. ResizeObserver handles split panes as well as
112
+ window resizing; hosts can call `diagram.resize()` after revealing a hidden preview.
113
+
114
+ ## Animated GIF Export
115
+
116
+ ```typescript
117
+ const gif = await diagram.exportGif({
118
+ fps: 12,
119
+ pixelRatio: 1,
120
+ maxFrames: 120,
121
+ maxWidth: 1600,
122
+ holdEndMs: 1400,
123
+ loop: true,
124
+ onProgress: (progress) => console.log(Math.round(progress * 100)),
125
+ });
126
+ ```
127
+
128
+ GIF export captures the rendered DOM, including node styling, shadows, and
129
+ the current animation state. Use `mode: "pure"` for the previous vector-based
130
+ rasterization path. PNG and SVG exports keep their existing defaults.
131
+
132
+ `fps` and `pixelRatio` are targets. Long scenes are sampled evenly across the
133
+ complete timeline, with at most `maxFrames` frames including the final hold.
134
+ Output width is capped by `maxWidth`; resolution is reduced further when needed
135
+ to keep captured frames within a 48-megapixel budget. Repeated frames are merged
136
+ without losing their delays, so compression preserves playback duration.
137
+
138
+ Playback time and playing/paused state are restored after export, including
139
+ when capture fails. Browser font and cross-origin image restrictions still apply.
140
+
79
141
  ## API Exports
80
142
 
81
143
  | Export | Type | Description |
@@ -87,7 +149,17 @@ console.log("Route:", shortestPath); // ['Client', 'Gateway', 'PaymentSvc', 'Led
87
149
  | `clearImpactHighlight(container)` | `Function` | Resets all impact highlighting |
88
150
  | `exportDiagramAsVectorSvg(container, opts?)` | `Function` | Export pure SVG vector snapshot of active scene frame |
89
151
  | `exportDiagramAsPng(container, opts?)` | `Function` | Export high-DPI rasterized PNG Blob |
90
- | `exportDiagramAsGif(diagram, opts?)` | `Function` | Export animated GIF89a recording |
152
+ | `exportDiagramAsGif(container, timeline, opts?)` | `Function` | Export animated GIF89a recording |
153
+
154
+ ## Development & Visual Harness
155
+
156
+ To inspect the renderer visually during local development:
157
+
158
+ ```sh
159
+ pnpm --filter @markdy/renderer-dom run harness
160
+ ```
161
+
162
+ The harness runs on **`http://127.0.0.1:4325`** (port 4325 is decoupled from Astro's default port 4321 to avoid collisions with documentation previews). It serves canonical test fixtures, live theme switching, and real-time interactive DOM rendering.
91
163
 
92
164
  ## Ecosystem & Documentation
93
165
 
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).
@@ -151,6 +186,18 @@ interface DiagramOptions {
151
186
  * Defaults to 28px for grouped diagrams and 22px for ungrouped diagrams.
152
187
  */
153
188
  contentPadding?: number;
189
+ /**
190
+ * Initial fit-all-in-view state. Defaults to true when undeclared.
191
+ * If false, starts in unconstrained mode.
192
+ */
193
+ defaultFit?: boolean;
194
+ /** Alias for defaultFit. */
195
+ fit?: boolean;
196
+ /**
197
+ * Optional custom fullscreen toggle handler.
198
+ * When provided, the footer fullscreen control delegates toggling to this callback.
199
+ */
200
+ onFullscreen?: (isFull: boolean) => void;
154
201
  }
155
202
  interface Diagram {
156
203
  play(): void;
@@ -171,6 +218,7 @@ interface Diagram {
171
218
  exportGif(options?: GifDiagramExportOptions): Promise<Blob>;
172
219
  resize(): void;
173
220
  resetView(): void;
221
+ syncFullscreen(isFull?: boolean): void;
174
222
  destroy(): void;
175
223
  }
176
224
  /**
@@ -183,6 +231,7 @@ declare function detectHostTheme(container?: HTMLElement): "nebula" | "paper";
183
231
  declare function computeDiagramContentBounds(plan: RenderPlan, options?: {
184
232
  tight?: boolean;
185
233
  padding?: number;
234
+ routedEdges?: Iterable<Pick<EdgeRuntime, "points" | "labelRect">>;
186
235
  }): {
187
236
  minX: number;
188
237
  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,40 @@ function createDiagram(opts) {
6079
6211
  onTimeUpdate,
6080
6212
  onPlayStateChange,
6081
6213
  onEnded,
6082
- responsiveLayout = true,
6083
- fitMode = "width",
6214
+ onFullscreen,
6215
+ responsiveLayout = "auto",
6216
+ fitMode = "auto",
6217
+ minReadableScale = 0.9,
6084
6218
  targetWidthRatio = 0.96,
6085
- contentPadding
6219
+ contentPadding,
6220
+ defaultFit,
6221
+ fit: explicitFitOption
6086
6222
  } = 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";
6223
+ function detectContainerOrientation(previous) {
6224
+ const width = container.clientWidth || (typeof window === "undefined" ? 1024 : window.innerWidth);
6225
+ const height = container.clientHeight || 0;
6226
+ const breakpoint = previous === "portrait" ? 672 : previous === "landscape" ? 608 : 640;
6227
+ if (height > 0 && container.clientHeight > 0) {
6228
+ const ratio = width / height;
6229
+ const ratioBreakpoint = previous === "portrait" ? 1.15 : previous === "landscape" ? 0.88 : 1;
6230
+ if (ratio >= ratioBreakpoint) {
6231
+ return "landscape";
6093
6232
  }
6094
- return "landscape";
6095
- }
6096
- const isMobileViewport = window.innerWidth < 768;
6097
- if (isMobileViewport) {
6098
6233
  return "portrait";
6099
6234
  }
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";
6235
+ return width < breakpoint ? "portrait" : "landscape";
6105
6236
  }
6106
6237
  const ast = parse(code);
6107
6238
  for (const w of ast.diagnostics) {
6108
6239
  if (w.severity === "warning") onWarning(w);
6109
6240
  }
6110
6241
  const hasExplicitDirection = ast.meta.explicitDirection === true;
6111
- const shouldAdaptOrientation = responsiveLayout !== false && !hasExplicitDirection;
6242
+ const shouldAdaptOrientation = responsiveLayout === true || responsiveLayout === "auto" && !hasExplicitDirection;
6243
+ const reverseDirection = ast.meta.direction === "RL" || ast.meta.direction === "BT";
6244
+ const directionForOrientation = (orientation) => orientation === "portrait" ? reverseDirection ? "BT" : "TB" : reverseDirection ? "RL" : "LR";
6112
6245
  let activeOrientation = detectContainerOrientation();
6113
6246
  if (shouldAdaptOrientation) {
6114
- ast.meta.direction = activeOrientation === "portrait" ? "TB" : "LR";
6247
+ ast.meta.direction = directionForOrientation(activeOrientation);
6115
6248
  }
6116
6249
  if (!ast.meta.explicitWidth || !ast.meta.explicitHeight) {
6117
6250
  const dims = computeAdaptiveDimensions(ast);
@@ -6209,16 +6342,21 @@ function createDiagram(opts) {
6209
6342
  progressEl = document.createElement("div");
6210
6343
  progressEl.className = progressMode === "bar" ? "markdy-progress-bar" : "markdy-boundary-progress";
6211
6344
  Object.assign(progressEl.style, {
6212
- position: "absolute",
6213
- ...progressMode === "bar" ? { left: "0", right: "0", bottom: "0", height: "3px" } : { inset: "0" },
6345
+ ...progressMode === "bar" ? { position: "absolute", left: "0", right: "0", bottom: "0", height: "3px" } : {
6346
+ position: "sticky",
6347
+ top: "0",
6348
+ left: "0",
6349
+ width: "100%",
6350
+ height: "100%",
6351
+ marginRight: "-100%",
6352
+ marginBottom: "-100%"
6353
+ },
6214
6354
  zIndex: "9999",
6215
6355
  pointerEvents: "none",
6216
6356
  borderRadius: "inherit"
6217
6357
  });
6218
6358
  viewport.appendChild(progressEl);
6219
6359
  }
6220
- const tlAngle = Math.atan2(-plan.meta.width / 2, plan.meta.height / 2) * 180 / Math.PI;
6221
- const tlAngleNorm = (tlAngle % 360 + 360) % 360;
6222
6360
  function updateProgressBar(pct) {
6223
6361
  if (!progressEl) return;
6224
6362
  if (progressMode === "bar") {
@@ -6229,7 +6367,11 @@ function createDiagram(opts) {
6229
6367
  }
6230
6368
  const deg = pct * 360;
6231
6369
  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)`;
6370
+ const vw = progressEl.clientWidth || viewport.clientWidth || plan.meta.width;
6371
+ const vh = progressEl.clientHeight || viewport.clientHeight || plan.meta.height;
6372
+ const currentAngle = Math.atan2(-vw / 2, vh / 2) * 180 / Math.PI;
6373
+ const currentAngleNorm = (currentAngle % 360 + 360) % 360;
6374
+ progressEl.style.background = `conic-gradient(from ${currentAngleNorm}deg, ${colorStops} ${deg}deg, transparent ${deg}deg)`;
6233
6375
  progressEl.style.mask = "linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0)";
6234
6376
  progressEl.style.webkitMask = progressEl.style.mask;
6235
6377
  progressEl.style.maskComposite = "exclude";
@@ -6292,6 +6434,10 @@ function createDiagram(opts) {
6292
6434
  }
6293
6435
  ensureSceneStyles(document);
6294
6436
  ensureNodeStyles(document);
6437
+ const sceneFrame = document.createElement("div");
6438
+ sceneFrame.className = "markdy-scene-frame";
6439
+ Object.assign(sceneFrame.style, { position: "absolute", left: "0", top: "0", width: "100%", height: "100%", overflow: "hidden" });
6440
+ viewport.appendChild(sceneFrame);
6295
6441
  const scene = document.createElement("div");
6296
6442
  scene.className = "markdy-scene-root";
6297
6443
  Object.assign(scene.style, {
@@ -6305,7 +6451,7 @@ function createDiagram(opts) {
6305
6451
  transformOrigin: "0 0"
6306
6452
  });
6307
6453
  applyThemeToScene(scene, plan.theme);
6308
- viewport.appendChild(scene);
6454
+ sceneFrame.appendChild(scene);
6309
6455
  const viewportTransform = document.createElement("div");
6310
6456
  viewportTransform.className = "markdy-viewport-transform";
6311
6457
  Object.assign(viewportTransform.style, {
@@ -6453,26 +6599,31 @@ function createDiagram(opts) {
6453
6599
  let fitScale = 1;
6454
6600
  let sceneOffsetX = 0;
6455
6601
  let sceneOffsetY = 0;
6602
+ let scrollableViewport = false;
6603
+ let lastScrollBounds = null;
6604
+ let contentBounds = computeDiagramContentBounds(plan, { padding: contentPadding, routedEdges: edgeRuntimes.values() });
6605
+ viewport.style.aspectRatio = `${contentBounds.width} / ${contentBounds.height}`;
6606
+ const layoutPlans = /* @__PURE__ */ new Map();
6607
+ layoutPlans.set(ast.meta.direction, { plan: { ...plan, meta: { ...plan.meta } }, bounds: initialBounds });
6608
+ function layoutForDirection(direction) {
6609
+ const cached = layoutPlans.get(direction);
6610
+ if (cached?.plan.theme === plan.theme) return cached;
6611
+ const candidate = compilePlan({ ...ast, meta: { ...ast.meta, direction } }, plan.theme);
6612
+ const entry = { plan: candidate, bounds: computeDiagramContentBounds(candidate, { padding: contentPadding }) };
6613
+ layoutPlans.set(direction, entry);
6614
+ return entry;
6615
+ }
6456
6616
  function computeContentBounds() {
6457
- return computeDiagramContentBounds(plan, contentPadding !== void 0 ? { padding: contentPadding } : void 0);
6617
+ return contentBounds;
6458
6618
  }
6459
6619
  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);
6620
+ const { plan: newPlan, bounds: newBounds } = layoutForDirection(newDirection);
6621
+ Object.assign(ast.meta, newPlan.meta);
6466
6622
  scene.style.width = `${newPlan.meta.width}px`;
6467
6623
  scene.style.height = `${newPlan.meta.height}px`;
6468
6624
  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;
6625
+ Object.assign(plan, newPlan);
6626
+ contentBounds = newBounds;
6476
6627
  for (const node of plan.nodes) {
6477
6628
  const el = nodeEls.get(node.id);
6478
6629
  if (el) {
@@ -6502,6 +6653,14 @@ function createDiagram(opts) {
6502
6653
  } else if (plan.diagramType === "gantt") {
6503
6654
  mountGanttLayer(constellationLayer, plan.nodes, plan.theme, { width: plan.meta.width, height: plan.meta.height });
6504
6655
  }
6656
+ for (const anim of allAnims) anim.cancel();
6657
+ cameraLayer.querySelectorAll(":scope > svg").forEach((layer) => layer.remove());
6658
+ sequenceLayer.replaceChildren();
6659
+ annotationLayer.replaceChildren();
6660
+ mountAnnotations(annotationLayer, plan.annotations, plan.nodes, plan.theme, {
6661
+ width: plan.meta.width,
6662
+ height: plan.meta.height
6663
+ });
6505
6664
  structuralEdgeHost.innerHTML = "";
6506
6665
  edgeRuntimes.clear();
6507
6666
  const newStructuralAnims = buildStructuralEdgeAnimations(
@@ -6516,7 +6675,6 @@ function createDiagram(opts) {
6516
6675
  plan.cues,
6517
6676
  Boolean(plan.treeBuses?.some((b) => b.vertical) || ast.meta.direction === "TB")
6518
6677
  );
6519
- for (const anim of allAnims) anim.cancel();
6520
6678
  allAnims = [
6521
6679
  ...plan.diagramType === "sequence" ? mountSequenceLayer(
6522
6680
  sequenceLayer,
@@ -6543,6 +6701,8 @@ function createDiagram(opts) {
6543
6701
  ),
6544
6702
  ...buildBeatCaptionAnimations(plan.beats, captionLayer)
6545
6703
  ];
6704
+ contentBounds = computeDiagramContentBounds(plan, { padding: contentPadding, routedEdges: edgeRuntimes.values() });
6705
+ viewport.style.aspectRatio = `${contentBounds.width} / ${contentBounds.height}`;
6546
6706
  applyCurrentTime();
6547
6707
  scaleScene();
6548
6708
  }
@@ -6558,29 +6718,48 @@ function createDiagram(opts) {
6558
6718
  scene.style.transform = "scale(1)";
6559
6719
  return;
6560
6720
  }
6561
- if (shouldAdaptOrientation) {
6562
- const currentOrientation = detectContainerOrientation();
6721
+ const vWidth = viewport.clientWidth || container.clientWidth || plan.meta.width;
6722
+ const naturalHeight = vWidth * contentBounds.height / contentBounds.width;
6723
+ const vHeight = viewport.clientHeight || container.clientHeight || naturalHeight;
6724
+ const resolvedFit = fitViewActive ? "contain" : fitMode === "auto" ? Math.abs(vHeight - naturalHeight) > 2 ? "contain" : "width" : fitMode;
6725
+ const targetRatio = Math.min(1, Math.max(0.9, targetWidthRatio ?? 0.96));
6726
+ if (shouldAdaptOrientation && !fitViewActive) {
6727
+ let currentOrientation = detectContainerOrientation(activeOrientation);
6728
+ if (fitMode === "auto" && (!ast.meta.explicitWidth || !ast.meta.explicitHeight) && ["architecture", "flowchart", "state", "tree", "medallion", "swimlane", "timeline", "gantt", "layers", "loop"].includes(plan.diagramType)) {
6729
+ const isHeightConstrained = resolvedFit === "contain" || vHeight > 0 && Math.abs(vHeight - naturalHeight) > 2;
6730
+ const containerRatio = vWidth / Math.max(1, vHeight);
6731
+ if (!(activeOrientation === "landscape" && containerRatio >= 1)) {
6732
+ const score = (orientation) => {
6733
+ const { bounds: bounds2 } = layoutForDirection(directionForOrientation(orientation));
6734
+ const widthScale2 = vWidth * targetRatio / bounds2.width;
6735
+ const heightScale = isHeightConstrained ? Math.max(1, vHeight - 24) * targetRatio / bounds2.height : 1;
6736
+ return Math.min(1, widthScale2, heightScale);
6737
+ };
6738
+ const alternative = activeOrientation === "portrait" ? "landscape" : "portrait";
6739
+ currentOrientation = score(alternative) > score(activeOrientation) * 1.2 ? alternative : activeOrientation;
6740
+ }
6741
+ }
6563
6742
  if (currentOrientation !== activeOrientation) {
6564
6743
  activeOrientation = currentOrientation;
6565
- relayoutOrientation(activeOrientation === "portrait" ? "TB" : "LR");
6744
+ relayoutOrientation(directionForOrientation(activeOrientation));
6566
6745
  return;
6567
6746
  }
6568
6747
  }
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
6748
  const bounds = computeContentBounds();
6573
6749
  const contentW = bounds.width;
6574
6750
  const contentH = bounds.height;
6575
- const targetRatio = Math.min(1, Math.max(0.9, targetWidthRatio ?? 0.96));
6576
6751
  const widthScale = vWidth * targetRatio / contentW;
6577
- if (fitMode === "contain") {
6752
+ if (resolvedFit === "contain") {
6578
6753
  const heightScale = (vHeight - 24) * targetRatio / contentH;
6579
6754
  fitScale = Math.min(widthScale, heightScale);
6580
6755
  } else {
6581
6756
  fitScale = widthScale;
6582
6757
  }
6583
6758
  if (!Number.isFinite(fitScale) || fitScale <= 0) fitScale = 1;
6759
+ if (fitMode === "auto" && !fitViewActive) {
6760
+ const minimum = Number.isFinite(minReadableScale) && minReadableScale >= 0 && minReadableScale <= 1 ? minReadableScale : 0.9;
6761
+ fitScale = Math.max(fitScale, minimum);
6762
+ }
6584
6763
  scene.style.setProperty("--markdy-scale", fitScale.toFixed(4));
6585
6764
  viewport.style.setProperty("--markdy-scale", fitScale.toFixed(4));
6586
6765
  container.style.setProperty("--markdy-scale", fitScale.toFixed(4));
@@ -6589,9 +6768,26 @@ function createDiagram(opts) {
6589
6768
  }
6590
6769
  const scaledContentW = contentW * fitScale;
6591
6770
  const scaledContentH = contentH * fitScale;
6592
- sceneOffsetX = (vWidth - scaledContentW) / 2 - bounds.minX * fitScale;
6593
- if (fitMode === "contain") {
6594
- sceneOffsetY = (vHeight - scaledContentH) / 2 - bounds.minY * fitScale;
6771
+ const resetScroll = !scrollableViewport || lastScrollBounds !== bounds;
6772
+ scrollableViewport = fitMode === "auto" && (scaledContentW > vWidth || scaledContentH > vHeight);
6773
+ lastScrollBounds = bounds;
6774
+ const frameWidth = scrollableViewport ? Math.max(vWidth, scaledContentW + 24) : vWidth;
6775
+ const frameHeight = scrollableViewport ? Math.max(vHeight, scaledContentH + 28) : vHeight;
6776
+ sceneFrame.style.width = scrollableViewport ? `${frameWidth}px` : "100%";
6777
+ sceneFrame.style.height = scrollableViewport ? `${frameHeight}px` : "100%";
6778
+ viewport.style.overflow = scrollableViewport ? "auto" : "hidden";
6779
+ viewport.style.touchAction = scrollableViewport ? "pan-x pan-y" : interactiveViewport ? "pan-y" : "auto";
6780
+ viewport.dataset.fitMode = resolvedFit;
6781
+ if (scrollableViewport) {
6782
+ viewport.tabIndex = 0;
6783
+ viewport.setAttribute("aria-label", plan.title || "Diagram");
6784
+ } else {
6785
+ viewport.removeAttribute("tabindex");
6786
+ viewport.removeAttribute("aria-label");
6787
+ }
6788
+ sceneOffsetX = (frameWidth - scaledContentW) / 2 - bounds.minX * fitScale;
6789
+ if (resolvedFit === "contain") {
6790
+ sceneOffsetY = (frameHeight - scaledContentH) / 2 - bounds.minY * fitScale;
6595
6791
  } else {
6596
6792
  const topSafeMargin = scaledContentH <= vHeight ? Math.max(14, Math.min(24, (vHeight - scaledContentH) / 2)) : 14;
6597
6793
  sceneOffsetY = topSafeMargin - bounds.minY * fitScale;
@@ -6600,11 +6796,28 @@ function createDiagram(opts) {
6600
6796
  scene.style.top = `${sceneOffsetY}px`;
6601
6797
  scene.style.transformOrigin = "0 0";
6602
6798
  scene.style.transform = `scale(${fitScale})`;
6799
+ if (scrollableViewport || fitViewActive) {
6800
+ cameraLayer.style.setProperty("transform", "none", "important");
6801
+ } else if (cameraLayer.style.getPropertyPriority("transform") === "important") {
6802
+ cameraLayer.style.removeProperty("transform");
6803
+ }
6804
+ if (scrollableViewport && resetScroll) {
6805
+ viewport.scrollLeft = Math.max(0, (frameWidth - vWidth) / 2);
6806
+ viewport.scrollTop = 0;
6807
+ }
6603
6808
  }
6604
- scaleScene();
6605
- const resizeObserver = typeof ResizeObserver === "function" ? new ResizeObserver(scaleScene) : null;
6809
+ let resizeRafId = null;
6810
+ function scheduleResize() {
6811
+ if (resizeRafId !== null) return;
6812
+ resizeRafId = requestAnimationFrame(() => {
6813
+ resizeRafId = null;
6814
+ scaleScene();
6815
+ });
6816
+ }
6817
+ const resizeObserver = typeof ResizeObserver === "function" ? new ResizeObserver(scheduleResize) : null;
6606
6818
  resizeObserver?.observe(viewport);
6607
6819
  if (container !== viewport) resizeObserver?.observe(container);
6820
+ if (!resizeObserver && typeof window !== "undefined") window.addEventListener("resize", scheduleResize);
6608
6821
  let sceneMs = 0;
6609
6822
  let lastRafTs = null;
6610
6823
  let isPlaying = false;
@@ -6625,7 +6838,11 @@ function createDiagram(opts) {
6625
6838
  let controlsTimeEl = null;
6626
6839
  let controlsFitButton = null;
6627
6840
  let closeCodePanel = null;
6628
- let fitViewActive = false;
6841
+ const explicitFit = defaultFit ?? explicitFitOption;
6842
+ let fitViewActive = explicitFit !== void 0 ? Boolean(explicitFit) : plan.meta.player?.controls?.fit !== void 0 ? Boolean(plan.meta.player.controls.fit) : opts.fitMode === "contain" || Boolean(fitViewButton);
6843
+ if (fitViewActive) {
6844
+ cameraLayer.style.setProperty("transform", "none", "important");
6845
+ }
6629
6846
  const ICONS2 = {
6630
6847
  play: '<svg class="markdy-icon" width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>',
6631
6848
  pause: '<svg class="markdy-icon" width="12" height="12" viewBox="0 0 24 24" fill="currentColor"><path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/></svg>',
@@ -6650,12 +6867,15 @@ function createDiagram(opts) {
6650
6867
  viewportScale = 1;
6651
6868
  viewportPanX = 0;
6652
6869
  viewportPanY = 0;
6870
+ viewport.scrollLeft = scrollableViewport ? Math.max(0, (contentBounds.width * fitScale + 24 - (viewport.clientWidth || container.clientWidth)) / 2) : 0;
6871
+ viewport.scrollTop = 0;
6653
6872
  applyViewportTransform();
6654
6873
  }
6655
6874
  function releaseFitView() {
6656
6875
  if (!fitViewActive) return;
6657
6876
  fitViewActive = false;
6658
6877
  cameraLayer.style.removeProperty("transform");
6878
+ scaleScene();
6659
6879
  }
6660
6880
  function toggleFitView() {
6661
6881
  if (fitViewActive) {
@@ -6663,21 +6883,23 @@ function createDiagram(opts) {
6663
6883
  syncControls();
6664
6884
  return;
6665
6885
  }
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;
6886
+ viewportScale = 1;
6887
+ viewportPanX = 0;
6888
+ viewportPanY = 0;
6671
6889
  applyViewportTransform();
6672
6890
  fitViewActive = true;
6673
6891
  cameraLayer.style.setProperty("transform", "none", "important");
6892
+ scaleScene();
6893
+ viewport.scrollLeft = 0;
6894
+ viewport.scrollTop = 0;
6674
6895
  syncControls();
6675
6896
  }
6676
6897
  function handleViewportWheel(event) {
6898
+ if (scrollableViewport && !event.ctrlKey && !event.metaKey) return;
6677
6899
  event.preventDefault();
6678
6900
  const rect = viewport.getBoundingClientRect();
6679
- const pointerX = (event.clientX - rect.left - sceneOffsetX) / fitScale;
6680
- const pointerY = (event.clientY - rect.top - sceneOffsetY) / fitScale;
6901
+ const pointerX = (event.clientX - rect.left + viewport.scrollLeft - sceneOffsetX) / fitScale;
6902
+ const pointerY = (event.clientY - rect.top + viewport.scrollTop - sceneOffsetY) / fitScale;
6681
6903
  const nextScale = Math.min(MAX_VIEWPORT_ZOOM, Math.max(MIN_VIEWPORT_ZOOM, viewportScale * Math.exp(-event.deltaY * VIEWPORT_ZOOM_STEP)));
6682
6904
  if (nextScale === viewportScale) return;
6683
6905
  const sceneX = (pointerX - viewportPanX) / viewportScale;
@@ -6688,6 +6910,7 @@ function createDiagram(opts) {
6688
6910
  applyViewportTransform();
6689
6911
  }
6690
6912
  function handleViewportPointerDown(event) {
6913
+ if (scrollableViewport) return;
6691
6914
  if (!allowPan) return;
6692
6915
  if (event.button !== 0 || activePointerId !== null) return;
6693
6916
  activePointerId = event.pointerId;
@@ -6757,18 +6980,34 @@ function createDiagram(opts) {
6757
6980
  syncControls();
6758
6981
  }
6759
6982
  function applyCurrentTime() {
6760
- for (const anim of allAnims) anim.currentTime = sceneMs;
6983
+ const timelineTime = document.timeline?.currentTime;
6984
+ const effectiveRate = playbackRate * NORMAL_PLAYBACK_RATE;
6985
+ for (const anim of allAnims) {
6986
+ anim.playbackRate = effectiveRate;
6987
+ if (isPlaying) {
6988
+ anim.currentTime = sceneMs;
6989
+ anim.play();
6990
+ if (typeof timelineTime === "number") anim.startTime = timelineTime - sceneMs / effectiveRate;
6991
+ } else {
6992
+ anim.pause();
6993
+ anim.currentTime = sceneMs;
6994
+ }
6995
+ }
6996
+ lastRafTs = isPlaying && typeof timelineTime === "number" ? timelineTime : null;
6761
6997
  onTimeUpdate?.(sceneMs / 1e3, durationSeconds);
6762
6998
  }
6763
6999
  function rafTick(timestamp) {
6764
7000
  if (lastRafTs !== null) sceneMs += (timestamp - lastRafTs) * playbackRate * NORMAL_PLAYBACK_RATE;
6765
7001
  lastRafTs = timestamp;
6766
7002
  if (totalDurationMs > 0 && sceneMs >= totalDurationMs) {
6767
- if (loop) sceneMs = sceneMs % totalDurationMs;
6768
- else {
6769
- sceneMs = totalDurationMs;
7003
+ if (loop) {
7004
+ sceneMs = sceneMs % totalDurationMs;
6770
7005
  applyCurrentTime();
7006
+ } else {
7007
+ sceneMs = totalDurationMs;
6771
7008
  isPlaying = false;
7009
+ applyCurrentTime();
7010
+ updateProgressBar(1);
6772
7011
  emitPlayStateChange(false);
6773
7012
  lastRafTs = null;
6774
7013
  rafId = null;
@@ -6776,7 +7015,7 @@ function createDiagram(opts) {
6776
7015
  return;
6777
7016
  }
6778
7017
  }
6779
- applyCurrentTime();
7018
+ onTimeUpdate?.(sceneMs / 1e3, durationSeconds);
6780
7019
  if (totalDurationMs > 0) updateProgressBar(sceneMs / totalDurationMs);
6781
7020
  rafId = requestAnimationFrame(rafTick);
6782
7021
  }
@@ -6784,13 +7023,14 @@ function createDiagram(opts) {
6784
7023
  play() {
6785
7024
  if (isPlaying) return;
6786
7025
  isPlaying = true;
7026
+ applyCurrentTime();
6787
7027
  emitPlayStateChange(true);
6788
- lastRafTs = null;
6789
7028
  rafId = requestAnimationFrame(rafTick);
6790
7029
  },
6791
7030
  pause() {
6792
7031
  if (!isPlaying) return;
6793
7032
  isPlaying = false;
7033
+ applyCurrentTime();
6794
7034
  emitPlayStateChange(false);
6795
7035
  if (rafId !== null) cancelAnimationFrame(rafId);
6796
7036
  rafId = null;
@@ -6805,6 +7045,7 @@ function createDiagram(opts) {
6805
7045
  setPlaybackRate(rate) {
6806
7046
  if (!Number.isFinite(rate) || rate <= 0) return;
6807
7047
  playbackRate = rate;
7048
+ applyCurrentTime();
6808
7049
  syncControls();
6809
7050
  },
6810
7051
  playbackRate() {
@@ -6973,8 +7214,12 @@ function createDiagram(opts) {
6973
7214
  resetView() {
6974
7215
  resetViewportTransform();
6975
7216
  },
7217
+ syncFullscreen(isFull) {
7218
+ syncFullscreenHandler?.(isFull);
7219
+ },
6976
7220
  destroy() {
6977
7221
  diagram.pause();
7222
+ syncFullscreenHandler = null;
6978
7223
  hostThemeObserver?.disconnect();
6979
7224
  hostThemeObserver = null;
6980
7225
  if (colorSchemeQuery && mediaQueryListener) {
@@ -6987,6 +7232,8 @@ function createDiagram(opts) {
6987
7232
  }
6988
7233
  for (const anim of allAnims) anim.cancel();
6989
7234
  resizeObserver?.disconnect();
7235
+ if (resizeRafId !== null) cancelAnimationFrame(resizeRafId);
7236
+ if (!resizeObserver && typeof window !== "undefined") window.removeEventListener("resize", scheduleResize);
6990
7237
  removeFullscreenListeners?.();
6991
7238
  closeCodePanel?.();
6992
7239
  closeCodePanel = null;
@@ -7376,7 +7623,7 @@ function createDiagram(opts) {
7376
7623
  if (!fitViewButton) return;
7377
7624
  controlsFitButton = makeControlButton("Fit", "Fit all items in view and ignore camera zoom", ICONS2.fit);
7378
7625
  controlsFitButton.className = "markdy-control-fit";
7379
- controlsFitButton.setAttribute("aria-pressed", "false");
7626
+ controlsFitButton.setAttribute("aria-pressed", fitViewActive ? "true" : "false");
7380
7627
  controlsFitButton.addEventListener("click", toggleFitView);
7381
7628
  toolbar.appendChild(controlsFitButton);
7382
7629
  }
@@ -7388,6 +7635,7 @@ function createDiagram(opts) {
7388
7635
  toolbar.appendChild(button);
7389
7636
  }
7390
7637
  let removeFullscreenListeners = null;
7638
+ let syncFullscreenHandler = null;
7391
7639
  function mountFullscreenControl(toolbar) {
7392
7640
  if (!fullscreenButton) return;
7393
7641
  const button = makeControlButton("Full", "Toggle fullscreen view", ICONS2.fullscreen);
@@ -7405,8 +7653,8 @@ function createDiagram(opts) {
7405
7653
  document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullScreenEnabled || document.msFullscreenEnabled
7406
7654
  );
7407
7655
  }
7408
- function syncFullscreenState() {
7409
- const isFull = isPseudoFull || document.fullscreenElement === host || document.fullscreenElement === viewport || document.webkitFullscreenElement === host || document.webkitFullscreenElement === viewport || document.mozFullScreenElement === host || document.msFullscreenElement === host;
7656
+ function syncFullscreenState(explicitFull) {
7657
+ const isFull = typeof explicitFull === "boolean" ? explicitFull : isPseudoFull || document.fullscreenElement === host || document.fullscreenElement === viewport || document.webkitFullscreenElement === host || document.webkitFullscreenElement === viewport || document.mozFullScreenElement === host || document.msFullscreenElement === host;
7410
7658
  button.setAttribute("aria-pressed", isFull ? "true" : "false");
7411
7659
  button.title = isFull ? "Exit fullscreen" : "Toggle fullscreen view";
7412
7660
  button.innerHTML = isFull ? `${ICONS2.fullscreen}Exit` : `${ICONS2.fullscreen}Full`;
@@ -7438,9 +7686,14 @@ function createDiagram(opts) {
7438
7686
  syncControls();
7439
7687
  }, 120);
7440
7688
  }
7689
+ syncFullscreenHandler = (isFull) => syncFullscreenState(isFull);
7441
7690
  async function toggleFullscreen() {
7442
7691
  try {
7443
- const isCurrentlyFull = isPseudoFull || document.fullscreenElement === host || document.fullscreenElement === viewport || document.webkitFullscreenElement === host || document.webkitFullscreenElement === viewport || document.mozFullScreenElement === host || document.msFullscreenElement === host;
7692
+ const isCurrentlyFull = button.getAttribute("aria-pressed") === "true" || isPseudoFull || document.fullscreenElement === host || document.fullscreenElement === viewport || document.webkitFullscreenElement === host || document.webkitFullscreenElement === viewport || document.mozFullScreenElement === host || document.msFullscreenElement === host;
7693
+ if (onFullscreen) {
7694
+ onFullscreen(!isCurrentlyFull);
7695
+ return;
7696
+ }
7444
7697
  if (!isCurrentlyFull) {
7445
7698
  let enteredNative = false;
7446
7699
  if (isNativeFullscreenSupported()) {
@@ -7508,6 +7761,7 @@ function createDiagram(opts) {
7508
7761
  document.addEventListener("MSFullscreenChange", syncFullscreenState);
7509
7762
  window.addEventListener("keydown", handleEscKey);
7510
7763
  removeFullscreenListeners = () => {
7764
+ syncFullscreenHandler = null;
7511
7765
  document.removeEventListener("fullscreenchange", syncFullscreenState);
7512
7766
  document.removeEventListener("webkitfullscreenchange", syncFullscreenState);
7513
7767
  document.removeEventListener("mozfullscreenchange", syncFullscreenState);
@@ -7659,6 +7913,7 @@ function createDiagram(opts) {
7659
7913
  if (keyboardShortcuts && typeof window !== "undefined") {
7660
7914
  window.addEventListener("keydown", handleKeyDown);
7661
7915
  }
7916
+ scaleScene();
7662
7917
  if (autoplay) diagram.play();
7663
7918
  return diagram;
7664
7919
  }
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.4",
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.4"
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.4"
57
57
  },
58
58
  "scripts": {
59
59
  "build": "tsup",