@markdy/renderer-dom 1.4.1 → 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).
@@ -169,6 +204,8 @@ interface Diagram {
169
204
  exportSvg(options?: SvgExportOptions): string;
170
205
  exportPng(options?: PngExportOptions): Promise<Blob>;
171
206
  exportGif(options?: GifDiagramExportOptions): Promise<Blob>;
207
+ resize(): void;
208
+ resetView(): void;
172
209
  destroy(): void;
173
210
  }
174
211
  /**
@@ -181,6 +218,7 @@ declare function detectHostTheme(container?: HTMLElement): "nebula" | "paper";
181
218
  declare function computeDiagramContentBounds(plan: RenderPlan, options?: {
182
219
  tight?: boolean;
183
220
  padding?: number;
221
+ routedEdges?: Iterable<Pick<EdgeRuntime, "points" | "labelRect">>;
184
222
  }): {
185
223
  minX: number;
186
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) {
@@ -4179,18 +4168,32 @@ function ensureSceneStyles(doc) {
4179
4168
  inset: 0 !important;
4180
4169
  z-index: 999999 !important;
4181
4170
  width: 100vw !important;
4171
+ width: 100dvw !important;
4182
4172
  height: 100vh !important;
4173
+ height: 100dvh !important;
4183
4174
  max-width: 100vw !important;
4175
+ max-width: 100dvw !important;
4184
4176
  max-height: 100vh !important;
4177
+ max-height: 100dvh !important;
4185
4178
  background-color: var(--md-canvas, #0b101b) !important;
4186
4179
  box-sizing: border-box !important;
4187
4180
  display: flex !important;
4188
4181
  flex-direction: column !important;
4189
4182
  justify-content: space-between !important;
4190
4183
  align-items: center !important;
4191
- padding: 16px 20px 12px !important;
4184
+ padding: max(16px, env(safe-area-inset-top, 16px)) max(20px, env(safe-area-inset-right, 20px)) max(12px, env(safe-area-inset-bottom, 12px)) max(20px, env(safe-area-inset-left, 20px)) !important;
4192
4185
  overflow: hidden !important;
4193
4186
  }
4187
+ .markdy-fullscreen-host .markdy-diagram-root,
4188
+ .markdy--pseudo-fullscreen .markdy-diagram-root {
4189
+ flex: 1 1 auto !important;
4190
+ width: 100% !important;
4191
+ height: 100% !important;
4192
+ display: flex !important;
4193
+ flex-direction: column !important;
4194
+ justify-content: space-between !important;
4195
+ align-items: center !important;
4196
+ }
4194
4197
  .markdy-diagram-root:fullscreen .markdy-viewport,
4195
4198
  .markdy-diagram-root:-webkit-full-screen .markdy-viewport,
4196
4199
  .markdy-diagram-root:-moz-full-screen .markdy-viewport,
@@ -4202,6 +4205,7 @@ function ensureSceneStyles(doc) {
4202
4205
  height: 100% !important;
4203
4206
  max-width: 100% !important;
4204
4207
  max-height: calc(100vh - 64px) !important;
4208
+ max-height: calc(100dvh - 64px) !important;
4205
4209
  display: flex !important;
4206
4210
  align-items: center !important;
4207
4211
  justify-content: center !important;
@@ -4216,7 +4220,7 @@ function ensureSceneStyles(doc) {
4216
4220
  width: 100% !important;
4217
4221
  max-width: 1400px !important;
4218
4222
  margin: 0 auto !important;
4219
- padding: 8px 12px 4px !important;
4223
+ padding: 8px 12px max(4px, env(safe-area-inset-bottom, 4px)) !important;
4220
4224
  }
4221
4225
  @media (hover: none) and (pointer: coarse) {
4222
4226
  .markdy-controls {
@@ -4337,6 +4341,11 @@ function normalizeExportViewport(scene) {
4337
4341
  viewportTransform.style.willChange = "auto";
4338
4342
  });
4339
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
+ }
4340
4349
  function prepareHtmlSceneForExport(sceneEl, options = {}) {
4341
4350
  const clonedScene = sceneEl.cloneNode(true);
4342
4351
  copyRenderedStyles(sceneEl, clonedScene);
@@ -5378,12 +5387,36 @@ async function exportDiagramAsPng(containerEl, options = {}) {
5378
5387
  }, "image/png");
5379
5388
  });
5380
5389
  }
5381
- async function rasterizeDiagramToCanvas(containerEl, options = {}, pixelRatio = 1) {
5390
+ async function rasterizeDiagramToCanvas(containerEl, options = {}, pixelRatio = 1, preparedScene) {
5382
5391
  const pixelRatioForSvg = pixelRatio || 1;
5383
- const svgXml = exportLiveSceneAsPureVectorSvg(containerEl, options);
5384
- 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);
5385
5418
  const blob = new Blob([inlinedSvgXml], { type: "image/svg+xml;charset=utf-8" });
5386
- const url = URL.createObjectURL(blob);
5419
+ const url = captureHtml ? `data:image/svg+xml;charset=utf-8,${encodeURIComponent(inlinedSvgXml)}` : URL.createObjectURL(blob);
5387
5420
  const img = new Image();
5388
5421
  await new Promise((resolve, reject) => {
5389
5422
  img.onload = () => resolve();
@@ -5408,6 +5441,72 @@ async function rasterizeDiagramToCanvas(containerEl, options = {}, pixelRatio =
5408
5441
  URL.revokeObjectURL(url);
5409
5442
  return canvas;
5410
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
+ }
5411
5510
 
5412
5511
  // src/export/gif-encoder.ts
5413
5512
  var GIF_HEADER = "GIF89a";
@@ -5696,6 +5795,7 @@ function encodeGifSequence(frames, options = {}) {
5696
5795
  buffer.push(3, 1, 0, 0, 0);
5697
5796
  }
5698
5797
  let prevQuantized = null;
5798
+ let previousDelayOffset = -1;
5699
5799
  for (let frameIdx = 0; frameIdx < frames.length; frameIdx++) {
5700
5800
  const frame = frames[frameIdx];
5701
5801
  const currQuantized = quantizer.quantize(frame.imageData);
@@ -5703,6 +5803,7 @@ function encodeGifSequence(frames, options = {}) {
5703
5803
  if (!enableDiff || prevQuantized === null || frameIdx === 0) {
5704
5804
  const compressedWithHeader = lzwCompress(currQuantized);
5705
5805
  buffer.push(33, 249, 4, 4);
5806
+ previousDelayOffset = buffer.length;
5706
5807
  pushU16(delayHundredths);
5707
5808
  buffer.push(0, 0);
5708
5809
  buffer.push(44);
@@ -5732,7 +5833,14 @@ function encodeGifSequence(frames, options = {}) {
5732
5833
  }
5733
5834
  }
5734
5835
  if (maxX < minX || maxY < minY) {
5735
- 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;
5736
5844
  }
5737
5845
  const diffW = maxX - minX + 1;
5738
5846
  const diffH = maxY - minY + 1;
@@ -5750,6 +5858,7 @@ function encodeGifSequence(frames, options = {}) {
5750
5858
  }
5751
5859
  const compressedWithHeader = lzwCompress(diffData);
5752
5860
  buffer.push(33, 249, 4, 5);
5861
+ previousDelayOffset = buffer.length;
5753
5862
  pushU16(delayHundredths);
5754
5863
  buffer.push(TRANSPARENT_COLOR_INDEX, 0);
5755
5864
  buffer.push(44);
@@ -5782,34 +5891,51 @@ var nextFrame = () => new Promise((resolve) => {
5782
5891
  finish();
5783
5892
  }));
5784
5893
  });
5785
- var DEFAULT_GIF_PIXEL_RATIO = 2;
5786
- var DEFAULT_GIF_FPS = 20;
5787
- var MAX_GIF_FRAMES = 96;
5788
- async function rasterizeFrame(container, pixelRatio, options) {
5789
- 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);
5790
5905
  const context = canvas.getContext("2d");
5791
5906
  if (!context) throw new Error("Could not create GIF canvas context");
5792
5907
  return context.getImageData(0, 0, canvas.width, canvas.height);
5793
5908
  }
5794
5909
  async function exportDiagramAsGif(container, timeline, options = {}) {
5795
- 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");
5796
5916
  const rawDuration = timeline.duration();
5797
5917
  const duration = Math.max(Number.isFinite(rawDuration) ? rawDuration : 1, 0.1);
5798
- const fps = Math.min(requestedFps, Math.max(6, Math.round(MAX_GIF_FRAMES / duration)));
5799
- const frameCount = Math.max(1, Math.ceil(duration * fps));
5800
- const delayMs = Math.max(20, Math.round(1e3 / fps));
5801
- const pixelRatio = options.pixelRatio ?? DEFAULT_GIF_PIXEL_RATIO;
5802
- 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);
5803
5928
  const priorTime = timeline.currentTime();
5804
5929
  const wasPlaying = timeline.isPlaying();
5805
5930
  timeline.pause();
5806
5931
  try {
5932
+ await container.ownerDocument.fonts?.ready;
5807
5933
  const frames = [];
5808
- const totalFrames = frameCount + 1;
5809
5934
  for (let frame = 0; frame < frameCount; frame++) {
5810
- timeline.seek(Math.min(duration, frame / fps));
5935
+ timeline.seek(duration * frame / frameCount);
5811
5936
  await nextFrame();
5812
- 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));
5813
5939
  frames.push({
5814
5940
  imageData,
5815
5941
  delayMs
@@ -5818,7 +5944,7 @@ async function exportDiagramAsGif(container, timeline, options = {}) {
5818
5944
  }
5819
5945
  timeline.seek(duration);
5820
5946
  await nextFrame();
5821
- const finalImageData = await rasterizeFrame(container, pixelRatio, options);
5947
+ const finalImageData = await rasterizeFrame(capture, pixelRatio);
5822
5948
  frames.push({
5823
5949
  imageData: finalImageData,
5824
5950
  delayMs: holdEndMs
@@ -5951,6 +6077,27 @@ var CANVAS_WIDE_ARCHETYPES = /* @__PURE__ */ new Set([
5951
6077
  "gantt"
5952
6078
  ]);
5953
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
+ }
5954
6101
  if (!plan.nodes || plan.nodes.length === 0) {
5955
6102
  return { minX: 0, minY: 0, maxX: plan.meta.width, maxY: plan.meta.height, width: plan.meta.width, height: plan.meta.height };
5956
6103
  }
@@ -6008,8 +6155,8 @@ function computeDiagramContentBounds(plan, options) {
6008
6155
  const titleText = (plan.title ?? plan.meta?.title ?? "").trim();
6009
6156
  const hasTitle = titleText.length > 0;
6010
6157
  if (hasTitle) {
6011
- minX = 0;
6012
- minY = 0;
6158
+ minX = Math.min(minX, 0);
6159
+ minY = Math.min(minY, 0);
6013
6160
  const titleEstimatedW = Math.min(plan.meta.width, 56 + titleText.length * 17 + 56);
6014
6161
  maxX = Math.max(maxX, titleEstimatedW);
6015
6162
  maxY = Math.max(maxY, 72);
@@ -6029,15 +6176,15 @@ function computeDiagramContentBounds(plan, options) {
6029
6176
  }
6030
6177
  const defaultPad = plan.groupBoundaries && plan.groupBoundaries.length > 0 ? 28 : 22;
6031
6178
  const pad = options?.padding ?? (options?.tight === false ? 36 : defaultPad);
6032
- minX = Math.max(-pad, minX - pad);
6033
- minY = Math.max(-pad, minY - pad);
6034
- maxX = Math.min(plan.meta.width + pad, maxX + pad);
6035
- maxY = Math.min(plan.meta.height + pad, maxY + pad);
6179
+ minX -= pad;
6180
+ minY -= pad;
6181
+ maxX += pad;
6182
+ maxY += pad;
6036
6183
  if (minX > 0 && minX <= pad) minX = 0;
6037
6184
  if (minY > 0 && minY <= pad) minY = 0;
6038
6185
  if (hasTitle) {
6039
- minX = 0;
6040
- minY = 0;
6186
+ if (minX === -pad) minX = 0;
6187
+ if (minY === -pad) minY = 0;
6041
6188
  }
6042
6189
  const width = Math.max(maxX - minX, 100);
6043
6190
  const height = Math.max(maxY - minY, 80);
@@ -6064,39 +6211,37 @@ function createDiagram(opts) {
6064
6211
  onTimeUpdate,
6065
6212
  onPlayStateChange,
6066
6213
  onEnded,
6067
- responsiveLayout = true,
6068
- fitMode = "width",
6214
+ responsiveLayout = "auto",
6215
+ fitMode = "auto",
6216
+ minReadableScale = 0.9,
6069
6217
  targetWidthRatio = 0.96,
6070
6218
  contentPadding
6071
6219
  } = opts;
6072
- function detectContainerOrientation() {
6073
- const cWidth = container?.clientWidth || 0;
6074
- const cHeight = container?.clientHeight || 0;
6075
- if (typeof window === "undefined") {
6076
- if (cWidth > 0 && cHeight > 0) {
6077
- 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";
6078
6229
  }
6079
- return "landscape";
6080
- }
6081
- const isMobileViewport = window.innerWidth < 768;
6082
- if (isMobileViewport) {
6083
6230
  return "portrait";
6084
6231
  }
6085
- if (cWidth > 0 && cHeight > 0) {
6086
- if (cHeight > cWidth * 1.18) return "portrait";
6087
- return "landscape";
6088
- }
6089
- return window.innerWidth < window.innerHeight ? "portrait" : "landscape";
6232
+ return width < breakpoint ? "portrait" : "landscape";
6090
6233
  }
6091
6234
  const ast = parse(code);
6092
6235
  for (const w of ast.diagnostics) {
6093
6236
  if (w.severity === "warning") onWarning(w);
6094
6237
  }
6095
6238
  const hasExplicitDirection = ast.meta.explicitDirection === true;
6096
- 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";
6097
6242
  let activeOrientation = detectContainerOrientation();
6098
6243
  if (shouldAdaptOrientation) {
6099
- ast.meta.direction = activeOrientation === "portrait" ? "TB" : "LR";
6244
+ ast.meta.direction = directionForOrientation(activeOrientation);
6100
6245
  }
6101
6246
  if (!ast.meta.explicitWidth || !ast.meta.explicitHeight) {
6102
6247
  const dims = computeAdaptiveDimensions(ast);
@@ -6194,16 +6339,21 @@ function createDiagram(opts) {
6194
6339
  progressEl = document.createElement("div");
6195
6340
  progressEl.className = progressMode === "bar" ? "markdy-progress-bar" : "markdy-boundary-progress";
6196
6341
  Object.assign(progressEl.style, {
6197
- position: "absolute",
6198
- ...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
+ },
6199
6351
  zIndex: "9999",
6200
6352
  pointerEvents: "none",
6201
6353
  borderRadius: "inherit"
6202
6354
  });
6203
6355
  viewport.appendChild(progressEl);
6204
6356
  }
6205
- const tlAngle = Math.atan2(-plan.meta.width / 2, plan.meta.height / 2) * 180 / Math.PI;
6206
- const tlAngleNorm = (tlAngle % 360 + 360) % 360;
6207
6357
  function updateProgressBar(pct) {
6208
6358
  if (!progressEl) return;
6209
6359
  if (progressMode === "bar") {
@@ -6214,7 +6364,11 @@ function createDiagram(opts) {
6214
6364
  }
6215
6365
  const deg = pct * 360;
6216
6366
  const colorStops = customColor ? customColor.includes(",") ? customColor : `${customColor} 0deg, ${customColor}` : DEFAULT_RAINBOW;
6217
- 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)`;
6218
6372
  progressEl.style.mask = "linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0)";
6219
6373
  progressEl.style.webkitMask = progressEl.style.mask;
6220
6374
  progressEl.style.maskComposite = "exclude";
@@ -6277,6 +6431,10 @@ function createDiagram(opts) {
6277
6431
  }
6278
6432
  ensureSceneStyles(document);
6279
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);
6280
6438
  const scene = document.createElement("div");
6281
6439
  scene.className = "markdy-scene-root";
6282
6440
  Object.assign(scene.style, {
@@ -6290,7 +6448,7 @@ function createDiagram(opts) {
6290
6448
  transformOrigin: "0 0"
6291
6449
  });
6292
6450
  applyThemeToScene(scene, plan.theme);
6293
- viewport.appendChild(scene);
6451
+ sceneFrame.appendChild(scene);
6294
6452
  const viewportTransform = document.createElement("div");
6295
6453
  viewportTransform.className = "markdy-viewport-transform";
6296
6454
  Object.assign(viewportTransform.style, {
@@ -6438,26 +6596,31 @@ function createDiagram(opts) {
6438
6596
  let fitScale = 1;
6439
6597
  let sceneOffsetX = 0;
6440
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
+ }
6441
6613
  function computeContentBounds() {
6442
- return computeDiagramContentBounds(plan, contentPadding !== void 0 ? { padding: contentPadding } : void 0);
6614
+ return contentBounds;
6443
6615
  }
6444
6616
  function relayoutOrientation(newDirection) {
6445
- ast.meta.direction = newDirection;
6446
- const dims = computeAdaptiveDimensions(ast);
6447
- if (!ast.meta.explicitWidth) ast.meta.width = dims.width;
6448
- if (!ast.meta.explicitHeight) ast.meta.height = dims.height;
6449
- const newPlan = compilePlan(ast, plan.theme);
6450
- 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);
6451
6619
  scene.style.width = `${newPlan.meta.width}px`;
6452
6620
  scene.style.height = `${newPlan.meta.height}px`;
6453
6621
  viewport.style.aspectRatio = `${newBounds.width} / ${newBounds.height}`;
6454
- plan.nodes = newPlan.nodes;
6455
- plan.edges = newPlan.edges;
6456
- plan.groupBoundaries = newPlan.groupBoundaries;
6457
- plan.treeBuses = newPlan.treeBuses;
6458
- plan.cues = newPlan.cues;
6459
- plan.beats = newPlan.beats;
6460
- plan.meta = newPlan.meta;
6622
+ Object.assign(plan, newPlan);
6623
+ contentBounds = newBounds;
6461
6624
  for (const node of plan.nodes) {
6462
6625
  const el = nodeEls.get(node.id);
6463
6626
  if (el) {
@@ -6487,6 +6650,14 @@ function createDiagram(opts) {
6487
6650
  } else if (plan.diagramType === "gantt") {
6488
6651
  mountGanttLayer(constellationLayer, plan.nodes, plan.theme, { width: plan.meta.width, height: plan.meta.height });
6489
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
+ });
6490
6661
  structuralEdgeHost.innerHTML = "";
6491
6662
  edgeRuntimes.clear();
6492
6663
  const newStructuralAnims = buildStructuralEdgeAnimations(
@@ -6501,7 +6672,6 @@ function createDiagram(opts) {
6501
6672
  plan.cues,
6502
6673
  Boolean(plan.treeBuses?.some((b) => b.vertical) || ast.meta.direction === "TB")
6503
6674
  );
6504
- for (const anim of allAnims) anim.cancel();
6505
6675
  allAnims = [
6506
6676
  ...plan.diagramType === "sequence" ? mountSequenceLayer(
6507
6677
  sequenceLayer,
@@ -6528,6 +6698,8 @@ function createDiagram(opts) {
6528
6698
  ),
6529
6699
  ...buildBeatCaptionAnimations(plan.beats, captionLayer)
6530
6700
  ];
6701
+ contentBounds = computeDiagramContentBounds(plan, { padding: contentPadding, routedEdges: edgeRuntimes.values() });
6702
+ viewport.style.aspectRatio = `${contentBounds.width} / ${contentBounds.height}`;
6531
6703
  applyCurrentTime();
6532
6704
  scaleScene();
6533
6705
  }
@@ -6543,29 +6715,48 @@ function createDiagram(opts) {
6543
6715
  scene.style.transform = "scale(1)";
6544
6716
  return;
6545
6717
  }
6546
- if (shouldAdaptOrientation) {
6547
- 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
+ }
6548
6739
  if (currentOrientation !== activeOrientation) {
6549
6740
  activeOrientation = currentOrientation;
6550
- relayoutOrientation(activeOrientation === "portrait" ? "TB" : "LR");
6741
+ relayoutOrientation(directionForOrientation(activeOrientation));
6551
6742
  return;
6552
6743
  }
6553
6744
  }
6554
- const vWidth = viewport.clientWidth || container.clientWidth || plan.meta.width;
6555
- const fallbackHeight = vWidth * plan.meta.height / plan.meta.width;
6556
- const vHeight = viewport.clientHeight || container.clientHeight || fallbackHeight;
6557
6745
  const bounds = computeContentBounds();
6558
6746
  const contentW = bounds.width;
6559
6747
  const contentH = bounds.height;
6560
- const targetRatio = Math.min(1, Math.max(0.9, targetWidthRatio ?? 0.96));
6561
6748
  const widthScale = vWidth * targetRatio / contentW;
6562
- if (fitMode === "contain") {
6749
+ if (resolvedFit === "contain") {
6563
6750
  const heightScale = (vHeight - 24) * targetRatio / contentH;
6564
6751
  fitScale = Math.min(widthScale, heightScale);
6565
6752
  } else {
6566
6753
  fitScale = widthScale;
6567
6754
  }
6568
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
+ }
6569
6760
  scene.style.setProperty("--markdy-scale", fitScale.toFixed(4));
6570
6761
  viewport.style.setProperty("--markdy-scale", fitScale.toFixed(4));
6571
6762
  container.style.setProperty("--markdy-scale", fitScale.toFixed(4));
@@ -6574,9 +6765,26 @@ function createDiagram(opts) {
6574
6765
  }
6575
6766
  const scaledContentW = contentW * fitScale;
6576
6767
  const scaledContentH = contentH * fitScale;
6577
- sceneOffsetX = (vWidth - scaledContentW) / 2 - bounds.minX * fitScale;
6578
- if (fitMode === "contain") {
6579
- 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;
6580
6788
  } else {
6581
6789
  const topSafeMargin = scaledContentH <= vHeight ? Math.max(14, Math.min(24, (vHeight - scaledContentH) / 2)) : 14;
6582
6790
  sceneOffsetY = topSafeMargin - bounds.minY * fitScale;
@@ -6585,11 +6793,28 @@ function createDiagram(opts) {
6585
6793
  scene.style.top = `${sceneOffsetY}px`;
6586
6794
  scene.style.transformOrigin = "0 0";
6587
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
+ }
6805
+ }
6806
+ let resizeRafId = null;
6807
+ function scheduleResize() {
6808
+ if (resizeRafId !== null) return;
6809
+ resizeRafId = requestAnimationFrame(() => {
6810
+ resizeRafId = null;
6811
+ scaleScene();
6812
+ });
6588
6813
  }
6589
- scaleScene();
6590
- const resizeObserver = typeof ResizeObserver === "function" ? new ResizeObserver(scaleScene) : null;
6814
+ const resizeObserver = typeof ResizeObserver === "function" ? new ResizeObserver(scheduleResize) : null;
6591
6815
  resizeObserver?.observe(viewport);
6592
6816
  if (container !== viewport) resizeObserver?.observe(container);
6817
+ if (!resizeObserver && typeof window !== "undefined") window.addEventListener("resize", scheduleResize);
6593
6818
  let sceneMs = 0;
6594
6819
  let lastRafTs = null;
6595
6820
  let isPlaying = false;
@@ -6635,12 +6860,15 @@ function createDiagram(opts) {
6635
6860
  viewportScale = 1;
6636
6861
  viewportPanX = 0;
6637
6862
  viewportPanY = 0;
6863
+ viewport.scrollLeft = scrollableViewport ? Math.max(0, (contentBounds.width * fitScale + 24 - (viewport.clientWidth || container.clientWidth)) / 2) : 0;
6864
+ viewport.scrollTop = 0;
6638
6865
  applyViewportTransform();
6639
6866
  }
6640
6867
  function releaseFitView() {
6641
6868
  if (!fitViewActive) return;
6642
6869
  fitViewActive = false;
6643
6870
  cameraLayer.style.removeProperty("transform");
6871
+ scaleScene();
6644
6872
  }
6645
6873
  function toggleFitView() {
6646
6874
  if (fitViewActive) {
@@ -6648,21 +6876,23 @@ function createDiagram(opts) {
6648
6876
  syncControls();
6649
6877
  return;
6650
6878
  }
6651
- const bounds = computeContentBounds();
6652
- const scale = Math.min(plan.meta.width / bounds.width, plan.meta.height / bounds.height);
6653
- viewportScale = Number.isFinite(scale) && scale > 0 ? scale : 1;
6654
- viewportPanX = -bounds.minX * viewportScale + (plan.meta.width - bounds.width * viewportScale) / 2;
6655
- viewportPanY = -bounds.minY * viewportScale + (plan.meta.height - bounds.height * viewportScale) / 2;
6879
+ viewportScale = 1;
6880
+ viewportPanX = 0;
6881
+ viewportPanY = 0;
6656
6882
  applyViewportTransform();
6657
6883
  fitViewActive = true;
6658
6884
  cameraLayer.style.setProperty("transform", "none", "important");
6885
+ scaleScene();
6886
+ viewport.scrollLeft = 0;
6887
+ viewport.scrollTop = 0;
6659
6888
  syncControls();
6660
6889
  }
6661
6890
  function handleViewportWheel(event) {
6891
+ if (scrollableViewport && !event.ctrlKey && !event.metaKey) return;
6662
6892
  event.preventDefault();
6663
6893
  const rect = viewport.getBoundingClientRect();
6664
- const pointerX = (event.clientX - rect.left - sceneOffsetX) / fitScale;
6665
- 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;
6666
6896
  const nextScale = Math.min(MAX_VIEWPORT_ZOOM, Math.max(MIN_VIEWPORT_ZOOM, viewportScale * Math.exp(-event.deltaY * VIEWPORT_ZOOM_STEP)));
6667
6897
  if (nextScale === viewportScale) return;
6668
6898
  const sceneX = (pointerX - viewportPanX) / viewportScale;
@@ -6673,6 +6903,7 @@ function createDiagram(opts) {
6673
6903
  applyViewportTransform();
6674
6904
  }
6675
6905
  function handleViewportPointerDown(event) {
6906
+ if (scrollableViewport) return;
6676
6907
  if (!allowPan) return;
6677
6908
  if (event.button !== 0 || activePointerId !== null) return;
6678
6909
  activePointerId = event.pointerId;
@@ -6742,18 +6973,34 @@ function createDiagram(opts) {
6742
6973
  syncControls();
6743
6974
  }
6744
6975
  function applyCurrentTime() {
6745
- 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;
6746
6990
  onTimeUpdate?.(sceneMs / 1e3, durationSeconds);
6747
6991
  }
6748
6992
  function rafTick(timestamp) {
6749
6993
  if (lastRafTs !== null) sceneMs += (timestamp - lastRafTs) * playbackRate * NORMAL_PLAYBACK_RATE;
6750
6994
  lastRafTs = timestamp;
6751
6995
  if (totalDurationMs > 0 && sceneMs >= totalDurationMs) {
6752
- if (loop) sceneMs = sceneMs % totalDurationMs;
6753
- else {
6754
- sceneMs = totalDurationMs;
6996
+ if (loop) {
6997
+ sceneMs = sceneMs % totalDurationMs;
6755
6998
  applyCurrentTime();
6999
+ } else {
7000
+ sceneMs = totalDurationMs;
6756
7001
  isPlaying = false;
7002
+ applyCurrentTime();
7003
+ updateProgressBar(1);
6757
7004
  emitPlayStateChange(false);
6758
7005
  lastRafTs = null;
6759
7006
  rafId = null;
@@ -6761,7 +7008,7 @@ function createDiagram(opts) {
6761
7008
  return;
6762
7009
  }
6763
7010
  }
6764
- applyCurrentTime();
7011
+ onTimeUpdate?.(sceneMs / 1e3, durationSeconds);
6765
7012
  if (totalDurationMs > 0) updateProgressBar(sceneMs / totalDurationMs);
6766
7013
  rafId = requestAnimationFrame(rafTick);
6767
7014
  }
@@ -6769,13 +7016,14 @@ function createDiagram(opts) {
6769
7016
  play() {
6770
7017
  if (isPlaying) return;
6771
7018
  isPlaying = true;
7019
+ applyCurrentTime();
6772
7020
  emitPlayStateChange(true);
6773
- lastRafTs = null;
6774
7021
  rafId = requestAnimationFrame(rafTick);
6775
7022
  },
6776
7023
  pause() {
6777
7024
  if (!isPlaying) return;
6778
7025
  isPlaying = false;
7026
+ applyCurrentTime();
6779
7027
  emitPlayStateChange(false);
6780
7028
  if (rafId !== null) cancelAnimationFrame(rafId);
6781
7029
  rafId = null;
@@ -6790,6 +7038,7 @@ function createDiagram(opts) {
6790
7038
  setPlaybackRate(rate) {
6791
7039
  if (!Number.isFinite(rate) || rate <= 0) return;
6792
7040
  playbackRate = rate;
7041
+ applyCurrentTime();
6793
7042
  syncControls();
6794
7043
  },
6795
7044
  playbackRate() {
@@ -6950,6 +7199,14 @@ function createDiagram(opts) {
6950
7199
  async exportGif(options) {
6951
7200
  return await exportDiagramAsGif(container, diagram, options);
6952
7201
  },
7202
+ resize() {
7203
+ scaleScene();
7204
+ applyViewportTransform();
7205
+ syncControls();
7206
+ },
7207
+ resetView() {
7208
+ resetViewportTransform();
7209
+ },
6953
7210
  destroy() {
6954
7211
  diagram.pause();
6955
7212
  hostThemeObserver?.disconnect();
@@ -6964,6 +7221,8 @@ function createDiagram(opts) {
6964
7221
  }
6965
7222
  for (const anim of allAnims) anim.cancel();
6966
7223
  resizeObserver?.disconnect();
7224
+ if (resizeRafId !== null) cancelAnimationFrame(resizeRafId);
7225
+ if (!resizeObserver && typeof window !== "undefined") window.removeEventListener("resize", scheduleResize);
6967
7226
  removeFullscreenListeners?.();
6968
7227
  closeCodePanel?.();
6969
7228
  closeCodePanel = null;
@@ -7372,6 +7631,16 @@ function createDiagram(opts) {
7372
7631
  button.setAttribute("aria-pressed", "false");
7373
7632
  const host = container;
7374
7633
  let isPseudoFull = false;
7634
+ let originalBodyOverflow = null;
7635
+ function isNativeFullscreenSupported() {
7636
+ if (typeof document === "undefined") return false;
7637
+ if (typeof navigator !== "undefined" && /iPhone|iPod/i.test(navigator.userAgent)) {
7638
+ return false;
7639
+ }
7640
+ return Boolean(
7641
+ document.fullscreenEnabled || document.webkitFullscreenEnabled || document.mozFullScreenEnabled || document.msFullscreenEnabled
7642
+ );
7643
+ }
7375
7644
  function syncFullscreenState() {
7376
7645
  const isFull = isPseudoFull || document.fullscreenElement === host || document.fullscreenElement === viewport || document.webkitFullscreenElement === host || document.webkitFullscreenElement === viewport || document.mozFullScreenElement === host || document.msFullscreenElement === host;
7377
7646
  button.setAttribute("aria-pressed", isFull ? "true" : "false");
@@ -7379,54 +7648,82 @@ function createDiagram(opts) {
7379
7648
  button.innerHTML = isFull ? `${ICONS2.fullscreen}Exit` : `${ICONS2.fullscreen}Full`;
7380
7649
  if (isFull) {
7381
7650
  host.classList.add("markdy-fullscreen-host");
7651
+ if (isPseudoFull) {
7652
+ host.classList.add("markdy--pseudo-fullscreen");
7653
+ if (typeof document !== "undefined" && document.body && originalBodyOverflow === null) {
7654
+ originalBodyOverflow = document.body.style.overflow;
7655
+ document.body.style.overflow = "hidden";
7656
+ }
7657
+ }
7382
7658
  } else {
7383
7659
  host.classList.remove("markdy-fullscreen-host");
7384
7660
  host.classList.remove("markdy--pseudo-fullscreen");
7661
+ if (typeof document !== "undefined" && document.body && originalBodyOverflow !== null) {
7662
+ document.body.style.overflow = originalBodyOverflow;
7663
+ originalBodyOverflow = null;
7664
+ }
7385
7665
  }
7386
7666
  requestAnimationFrame(() => {
7387
7667
  scaleScene();
7388
7668
  applyViewportTransform();
7389
7669
  syncControls();
7390
7670
  });
7671
+ setTimeout(() => {
7672
+ scaleScene();
7673
+ applyViewportTransform();
7674
+ syncControls();
7675
+ }, 120);
7391
7676
  }
7392
7677
  async function toggleFullscreen() {
7393
7678
  try {
7394
- const isCurrentlyFull = isPseudoFull || document.fullscreenElement === host || document.fullscreenElement === viewport || document.webkitFullscreenElement === host || document.mozFullScreenElement === host || document.msFullscreenElement === host;
7679
+ const isCurrentlyFull = isPseudoFull || document.fullscreenElement === host || document.fullscreenElement === viewport || document.webkitFullscreenElement === host || document.webkitFullscreenElement === viewport || document.mozFullScreenElement === host || document.msFullscreenElement === host;
7395
7680
  if (!isCurrentlyFull) {
7396
- const req = host.requestFullscreen?.bind(host) || host.webkitRequestFullscreen?.bind(host) || host.mozRequestFullScreen?.bind(host) || host.msRequestFullscreen?.bind(host) || viewport.requestFullscreen?.bind(viewport) || viewport.webkitRequestFullscreen?.bind(viewport);
7397
- if (req) {
7398
- try {
7399
- await req();
7400
- } catch {
7401
- isPseudoFull = true;
7402
- host.classList.add("markdy--pseudo-fullscreen");
7403
- syncFullscreenState();
7681
+ let enteredNative = false;
7682
+ if (isNativeFullscreenSupported()) {
7683
+ const req = host.requestFullscreen?.bind(host) || host.webkitRequestFullscreen?.bind(host) || host.mozRequestFullScreen?.bind(host) || host.msRequestFullscreen?.bind(host) || viewport.requestFullscreen?.bind(viewport) || viewport.webkitRequestFullscreen?.bind(viewport);
7684
+ if (req) {
7685
+ try {
7686
+ const res = req();
7687
+ if (res && typeof res.then === "function") {
7688
+ await res;
7689
+ }
7690
+ enteredNative = Boolean(
7691
+ document.fullscreenElement === host || document.fullscreenElement === viewport || document.webkitFullscreenElement === host || document.webkitFullscreenElement === viewport || document.mozFullScreenElement === host || document.msFullscreenElement === host
7692
+ );
7693
+ } catch {
7694
+ enteredNative = false;
7695
+ }
7404
7696
  }
7405
- } else {
7697
+ }
7698
+ if (!enteredNative) {
7406
7699
  isPseudoFull = true;
7407
- host.classList.add("markdy--pseudo-fullscreen");
7408
7700
  syncFullscreenState();
7409
7701
  }
7410
7702
  } else {
7411
7703
  if (isPseudoFull) {
7412
7704
  isPseudoFull = false;
7413
- host.classList.remove("markdy--pseudo-fullscreen");
7414
7705
  syncFullscreenState();
7415
7706
  } else {
7416
7707
  const exit = document.exitFullscreen?.bind(document) || document.webkitExitFullscreen?.bind(document) || document.mozCancelFullScreen?.bind(document) || document.msExitFullscreen?.bind(document);
7417
7708
  if (exit) {
7418
- await exit();
7709
+ try {
7710
+ const res = exit();
7711
+ if (res && typeof res.then === "function") {
7712
+ await res;
7713
+ }
7714
+ } catch {
7715
+ }
7419
7716
  }
7717
+ isPseudoFull = false;
7718
+ syncFullscreenState();
7420
7719
  }
7421
7720
  }
7422
7721
  } catch {
7423
7722
  if (!isPseudoFull) {
7424
7723
  isPseudoFull = true;
7425
- host.classList.add("markdy--pseudo-fullscreen");
7426
7724
  syncFullscreenState();
7427
7725
  } else {
7428
7726
  isPseudoFull = false;
7429
- host.classList.remove("markdy--pseudo-fullscreen");
7430
7727
  syncFullscreenState();
7431
7728
  }
7432
7729
  }
@@ -7438,7 +7735,6 @@ function createDiagram(opts) {
7438
7735
  const handleEscKey = (e) => {
7439
7736
  if (e.key === "Escape" && isPseudoFull) {
7440
7737
  isPseudoFull = false;
7441
- host.classList.remove("markdy--pseudo-fullscreen");
7442
7738
  syncFullscreenState();
7443
7739
  }
7444
7740
  };
@@ -7453,7 +7749,12 @@ function createDiagram(opts) {
7453
7749
  document.removeEventListener("mozfullscreenchange", syncFullscreenState);
7454
7750
  document.removeEventListener("MSFullscreenChange", syncFullscreenState);
7455
7751
  window.removeEventListener("keydown", handleEscKey);
7752
+ if (originalBodyOverflow !== null && typeof document !== "undefined" && document.body) {
7753
+ document.body.style.overflow = originalBodyOverflow;
7754
+ originalBodyOverflow = null;
7755
+ }
7456
7756
  if (isPseudoFull) {
7757
+ isPseudoFull = false;
7457
7758
  host.classList.remove("markdy--pseudo-fullscreen");
7458
7759
  host.classList.remove("markdy-fullscreen-host");
7459
7760
  }
@@ -7594,6 +7895,7 @@ function createDiagram(opts) {
7594
7895
  if (keyboardShortcuts && typeof window !== "undefined") {
7595
7896
  window.addEventListener("keydown", handleKeyDown);
7596
7897
  }
7898
+ scaleScene();
7597
7899
  if (autoplay) diagram.play();
7598
7900
  return diagram;
7599
7901
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@markdy/renderer-dom",
3
- "version": "1.4.1",
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.1"
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.1"
56
+ "@markdy/stdlib-systems": "1.4.3"
57
57
  },
58
58
  "scripts": {
59
59
  "build": "tsup",