animate-mermaid 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 animate-mermaid contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,145 @@
1
- # Temporary Holding Version
1
+ # animate-mermaid
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Smooth animations for [Mermaid](https://mermaid.js.org) diagrams, usable from any framework, with export to **animated SVG**, **GIF** and **PNG**.
4
+
5
+ - **Follows the graph**: roots appear first, each edge draws toward its target, then the target pops in. Subgraphs fade in just before their contents.
6
+ - **Smooth and light**: pure CSS keyframes, so it runs on the browser's compositor with no JS animation loop and no GSAP. Core is about 6 KB gzipped (Mermaid is a peer dependency).
7
+ - **Works anywhere**: vanilla JS, React, Next.js (App Router and Pages), TanStack Start/Router, Svelte/SvelteKit, plus a `<animated-mermaid>` web component for Vue, Angular, Solid, Astro or plain HTML.
8
+ - **Export**: the animated SVG plays by itself in browsers, `<img>` tags and READMEs. GIF export records the full animation for Slack, slides, docs or anywhere SVG isn't supported. PNG export captures the finished diagram or any frame.
9
+ - **Controllable**: `play`, `pause`, `restart`, `seek(ms)`, looping, and play-when-visible.
10
+ - **Accessible**: honors `prefers-reduced-motion`.
11
+
12
+ Tested with Mermaid 12 on flowcharts, sequence, state and class diagrams. Other diagram types fall back to a top-to-bottom reveal.
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ npm i animate-mermaid mermaid
18
+ ```
19
+
20
+ ## Vanilla JS
21
+
22
+ ```js
23
+ import { renderAnimated, toSvgString, toGif, toPng, download } from 'animate-mermaid';
24
+
25
+ const ctrl = await renderAnimated(document.getElementById('diagram'), `
26
+ flowchart LR
27
+ A[Client] --> B[API] --> C[(DB)]
28
+ `, { loop: true });
29
+
30
+ ctrl.pause(); ctrl.seek(800); ctrl.play();
31
+
32
+ download(toSvgString(ctrl.svg), 'diagram.svg'); // animated SVG
33
+ download(await toGif(ctrl), 'diagram.gif'); // animated GIF
34
+ download(await toPng(ctrl.svg), 'diagram.png'); // final frame PNG
35
+ ```
36
+
37
+ If you already render with Mermaid yourself, animate the existing SVG:
38
+
39
+ ```js
40
+ import { animate } from 'animate-mermaid';
41
+ const ctrl = animate(document.querySelector('#my-diagram svg'));
42
+ ```
43
+
44
+ ## React / Next.js / TanStack
45
+
46
+ ```tsx
47
+ import { AnimatedMermaid, useAnimatedMermaid } from 'animate-mermaid/react';
48
+
49
+ <AnimatedMermaid chart={source} order="flow" loop ref={ctrlRef} />
50
+
51
+ // or the hook
52
+ const { ref, controller, error } = useAnimatedMermaid(source, { autoplay: 'visible' });
53
+ return <div ref={ref} />;
54
+ ```
55
+
56
+ The React entry ships with `"use client"`, so it drops straight into Next.js App Router server components. Mermaid is imported lazily inside an effect, so SSR never touches the DOM.
57
+
58
+ ## Svelte / SvelteKit
59
+
60
+ ```svelte
61
+ <script>
62
+ import { animatedMermaid } from 'animate-mermaid/svelte';
63
+ let chart = `flowchart TD; A-->B`;
64
+ </script>
65
+
66
+ <div use:animatedMermaid={{ chart, loop: true, onReady: (c) => console.log(c.duration) }} />
67
+ ```
68
+
69
+ ## Web component (Vue, Angular, Astro, HTML…)
70
+
71
+ ```html
72
+ <script type="module">import 'animate-mermaid/element';</script>
73
+
74
+ <animated-mermaid order="flow" node-effect="pop" loop>
75
+ flowchart LR
76
+ A --> B --> C
77
+ </animated-mermaid>
78
+ ```
79
+
80
+ The element has `play()`, `pause()`, `restart()`, `seek(ms)`, `toSvg()`, `toPng()` and `toGif()` methods, and fires `ready` and `error` events.
81
+
82
+ ## Options
83
+
84
+ | Option | Default | Description |
85
+ | --- | --- | --- |
86
+ | `order` | `'flow'` | `'flow'` follows edges, `'position'` reveals top-to-bottom, `'together'` reveals everything at once |
87
+ | `nodeEffect` | `'pop'` | `'pop' \| 'fade' \| 'slide' \| 'none'` |
88
+ | `edgeEffect` | `'draw'` | `'draw' \| 'fade' \| 'none'`. Dashed and dotted edges always fade |
89
+ | `nodeDuration` / `edgeDuration` | `450` / `500` | Duration in ms |
90
+ | `stagger` | `120` | Gap between items in `position` order (ms) |
91
+ | `delay` | `0` | Initial delay (ms) |
92
+ | `easing` / `edgeEasing` | ease-out / ease-in-out | Any CSS easing |
93
+ | `loop` / `loopHold` | `false` / `1500` | Replay forever, holding the finished diagram for `loopHold` ms between runs |
94
+ | `autoplay` | `true` | `true`, `false` (wait for `play()`), or `'visible'` (start on scroll into view) |
95
+ | `respectReducedMotion` | `true` | Skip the animation for reduced-motion users |
96
+ | `mermaid` / `mermaidConfig` | — | Your own Mermaid instance, or config passed to `mermaid.initialize` |
97
+
98
+ ## Export API
99
+
100
+ | Function | Returns |
101
+ | --- | --- |
102
+ | `toSvgString(svg, { frame?, background? })` | Animated SVG markup. Pass `frame` (ms or `'end'`) to freeze it |
103
+ | `toSvgBlob(svg, opts)` | The same, as a `Blob` |
104
+ | `toGif(controller, { fps = 20, scale = 1, maxWidth = 1200, background = 'white', holdEnd = 1500, repeat = 0, onProgress, signal })` | Animated GIF `Blob` covering the whole animation |
105
+ | `toPng(svg, { frame = 'end', scale = 2, background = 'white' })` | PNG `Blob` |
106
+ | `renderFrame(svg, opts)` | `HTMLCanvasElement`, for building GIF/APNG/video frames |
107
+ | `shareFile(blob, { filename, title, text, fallbackToDownload = true })` | Opens the system share sheet (WhatsApp, Slack, Teams, Messages, Mail, AirDrop, or whatever is installed). Downloads instead where sharing isn't supported. Resolves to `'shared' \| 'downloaded' \| 'cancelled' \| 'unsupported'` |
108
+ | `canShareFile(blob, filename?)` | Whether the share sheet is available for this file (GIF and PNG are shareable, SVG isn't in Chrome) |
109
+ | `download(blobOrString, filename)` | Triggers a browser download |
110
+
111
+ ### Sharing a GIF to WhatsApp, Slack or Teams
112
+
113
+ ```js
114
+ // click 1: build the GIF (takes a few seconds)
115
+ const gif = await toGif(ctrl);
116
+ // click 2: share it
117
+ shareButton.onclick = () => shareFile(gif, { filename: 'diagram.gif', title: 'Architecture' });
118
+ ```
119
+
120
+ Browsers only allow the share sheet for a few seconds after a click, so build the GIF first and share it on a second click. The examples work this way: **Make GIF**, then a preview, then **Share**.
121
+
122
+ The share sheet works in mobile browsers, Safari, and Chrome or Edge on Windows, macOS and ChromeOS. Firefox desktop doesn't support it and downloads the file instead, which you can then drag into Slack, Teams or WhatsApp Web. Posting straight into a Slack channel or Teams chat without the share sheet would need your own server using each platform's API (a bot token or webhook), which is outside a front-end library.
123
+
124
+ ### Notes
125
+
126
+ - **GIF**: frames are rendered one by one rather than screen-recorded in real time, so the timing is exact even on a slow machine. A 3 s flowchart at 20 fps is about 60 frames, roughly 400 KB, and takes a few seconds to build. Lower `fps` or `scale` for smaller files. Every frame uses one 256-color palette taken from the finished diagram, so colors don't flicker. `background: 'transparent'` gives 1-bit transparency, so edges come out hard. The encoder ([gifenc](https://github.com/mattdesl/gifenc), MIT) loads only when you call `toGif`.
127
+ - A PNG can't animate. Use the animated SVG or GIF, or call `renderFrame` to get individual frames.
128
+ - Exported SVGs use the browser's default fonts unless you inline a webfont.
129
+ - Safari may refuse to rasterize HTML labels (`<foreignObject>`) to PNG or GIF. If that happens, render with `mermaidConfig: { htmlLabels: false }`.
130
+
131
+ ## Examples
132
+
133
+ Runnable sample projects live in [examples/](examples/): [plain HTML](examples/html/), [React](examples/react/) and [Svelte](examples/svelte/).
134
+
135
+ ## Develop
136
+
137
+ ```bash
138
+ npm run dev # demo playground (Vite) at demo/
139
+ npm test # unit tests (vitest)
140
+ npm run build # ESM + CJS + .d.ts into dist/
141
+ ```
142
+
143
+ ## License
144
+
145
+ MIT
@@ -0,0 +1,476 @@
1
+ // src/graph.ts
2
+ var NODE_SEL = 'g.node, g.nodes > g, g.mindmap-node, g[data-node="true"]';
3
+ var EDGE_SEL = [
4
+ "path.flowchart-link",
5
+ "g.edgePaths > path",
6
+ "g.edgePaths > g > path",
7
+ 'path[data-edge="true"]',
8
+ "path.relation",
9
+ "path.transition",
10
+ "path.relationshipLine",
11
+ "path.er.relationshipLine",
12
+ "path.edge"
13
+ ].join(", ");
14
+ var LABEL_SEL = "g.edgeLabel";
15
+ var CLUSTER_SEL = "g.cluster";
16
+ function nodeKey(id, dataId) {
17
+ if (dataId) return dataId;
18
+ if (!id) return void 0;
19
+ const m = /(?:flowchart|state|classId|entity|node)-(.+)-\d+$/.exec(id);
20
+ return m ? m[1] : id;
21
+ }
22
+ function parseEdgeId(id, nodes) {
23
+ if (!id) return void 0;
24
+ const m = /(?:^|[-_])L([-_])(.+)\1\d+$/.exec(id);
25
+ if (!m) return void 0;
26
+ const sep = m[1];
27
+ const mid = m[2];
28
+ for (let i = mid.indexOf(sep); i !== -1; i = mid.indexOf(sep, i + 1)) {
29
+ const from = mid.slice(0, i);
30
+ const to = mid.slice(i + 1);
31
+ if (nodes.has(from) && nodes.has(to)) return { from, to };
32
+ }
33
+ return void 0;
34
+ }
35
+ function uniq(list) {
36
+ const seen = /* @__PURE__ */ new Set();
37
+ const out = [];
38
+ for (const el of list) {
39
+ if (seen.has(el)) continue;
40
+ let nested = false;
41
+ for (const s of seen) if (s.contains(el)) {
42
+ nested = true;
43
+ break;
44
+ }
45
+ if (!nested) {
46
+ seen.add(el);
47
+ out.push(el);
48
+ }
49
+ }
50
+ return out;
51
+ }
52
+ function distToRect(x, y, r) {
53
+ const dx = Math.max(r.left - x, 0, x - r.right);
54
+ const dy = Math.max(r.top - y, 0, y - r.bottom);
55
+ return Math.hypot(dx, dy);
56
+ }
57
+ function endpoints(el) {
58
+ const geo = el;
59
+ if (typeof geo.getTotalLength !== "function") return void 0;
60
+ const ctm = el.getScreenCTM();
61
+ if (!ctm) return void 0;
62
+ try {
63
+ const len = geo.getTotalLength();
64
+ const a = geo.getPointAtLength(0);
65
+ const b = geo.getPointAtLength(len);
66
+ return [
67
+ new DOMPoint(a.x, a.y).matrixTransform(ctm),
68
+ new DOMPoint(b.x, b.y).matrixTransform(ctm)
69
+ ];
70
+ } catch {
71
+ return void 0;
72
+ }
73
+ }
74
+ function collectUnits(svg) {
75
+ const q = (sel) => Array.from(svg.querySelectorAll(sel));
76
+ const inDefs = (el) => !!el.closest("defs, marker");
77
+ const clusters = uniq(q(CLUSTER_SEL).filter((e) => !inDefs(e)));
78
+ const nodes = uniq(q(NODE_SEL).filter((e) => !inDefs(e) && !e.classList.contains("cluster")));
79
+ const edges = uniq(q(EDGE_SEL).filter((e) => !inDefs(e)));
80
+ const labels = uniq(q(LABEL_SEL).filter((e) => !inDefs(e) && (e.textContent ?? "").trim() !== ""));
81
+ if (nodes.length === 0 && edges.length === 0) return fallbackUnits(svg);
82
+ const nodeUnits = nodes.map((el) => ({
83
+ el,
84
+ kind: "node",
85
+ key: nodeKey(el.getAttribute("id"), el.getAttribute("data-id"))
86
+ }));
87
+ const keys = new Set(nodeUnits.map((n) => n.key).filter(Boolean));
88
+ const rects = nodeUnits.map((n) => n.el.getBoundingClientRect());
89
+ const edgeUnits = edges.map((el) => {
90
+ const id = el.getAttribute("data-id") ?? el.getAttribute("id");
91
+ const unit = { el, kind: "edge", key: id ?? void 0 };
92
+ const parsed = parseEdgeId(id, keys);
93
+ if (parsed) return { ...unit, ...parsed };
94
+ const pts = endpoints(el);
95
+ if (pts && nodeUnits.length) {
96
+ const nearest = (p) => {
97
+ let best = 0;
98
+ let bestD = Infinity;
99
+ rects.forEach((r, i) => {
100
+ const d = distToRect(p.x, p.y, r);
101
+ if (d < bestD) {
102
+ bestD = d;
103
+ best = i;
104
+ }
105
+ });
106
+ return nodeUnits[best].key;
107
+ };
108
+ const from = nearest(pts[0]);
109
+ const to = nearest(pts[1]);
110
+ if (from && to && from !== to) return { ...unit, from, to };
111
+ }
112
+ return unit;
113
+ });
114
+ const labelUnits = labels.map((el) => {
115
+ const inner = el.querySelector("[data-id]");
116
+ return { el, kind: "label", key: inner?.getAttribute("data-id") ?? el.getAttribute("data-id") ?? void 0 };
117
+ });
118
+ return [
119
+ ...clusters.map((el) => ({ el, kind: "cluster" })),
120
+ ...edgeUnits,
121
+ ...labelUnits,
122
+ ...nodeUnits
123
+ ];
124
+ }
125
+ function fallbackUnits(svg) {
126
+ let root = svg;
127
+ for (; ; ) {
128
+ const kids = Array.from(root.children).filter((c) => !/^(defs|style|title|desc|marker)$/i.test(c.tagName));
129
+ if (kids.length === 1 && kids[0].tagName.toLowerCase() === "g") root = kids[0];
130
+ else break;
131
+ }
132
+ const units = [];
133
+ for (const c of Array.from(root.children)) {
134
+ const tag = c.tagName.toLowerCase();
135
+ if (/^(defs|style|title|desc|marker|script)$/.test(tag)) continue;
136
+ const el = c;
137
+ const box = el.getBoundingClientRect();
138
+ if (box.width === 0 && box.height === 0) continue;
139
+ units.push({ el, kind: tag === "path" || tag === "line" || tag === "polyline" ? "edge" : "node" });
140
+ }
141
+ return units;
142
+ }
143
+
144
+ // src/timeline.ts
145
+ var cx = (r) => (r.left + r.right) / 2;
146
+ var cy = (r) => (r.top + r.bottom) / 2;
147
+ function schedule(items, t) {
148
+ const durOf = (it) => it.kind === "edge" ? t.edgeDuration : t.nodeDuration;
149
+ let slots;
150
+ const hasGraph = items.some((i) => i.kind === "edge" && i.from && i.to);
151
+ if (t.order === "together") {
152
+ slots = items.map((it) => ({ start: 0, dur: durOf(it) }));
153
+ } else if (t.order === "flow" && hasGraph) {
154
+ slots = flow(items, t);
155
+ } else {
156
+ slots = byPosition(items, t);
157
+ }
158
+ return slots.map((s) => ({ start: s.start + t.delay, dur: s.dur }));
159
+ }
160
+ function byPosition(items, t) {
161
+ const order = items.map((it, i) => i).sort((a, b) => {
162
+ const ra = items[a].rect;
163
+ const rb = items[b].rect;
164
+ if (Math.abs(ra.top - rb.top) > 4) return ra.top - rb.top;
165
+ return ra.left - rb.left;
166
+ });
167
+ const slots = new Array(items.length);
168
+ order.forEach((idx, n) => {
169
+ const it = items[idx];
170
+ slots[idx] = { start: n * t.stagger, dur: it.kind === "edge" ? t.edgeDuration : t.nodeDuration };
171
+ });
172
+ return slots;
173
+ }
174
+ function flow(items, t) {
175
+ const lead = t.nodeDuration * 0.5;
176
+ const step = lead + t.edgeDuration;
177
+ const nodeIdx = /* @__PURE__ */ new Map();
178
+ items.forEach((it, i) => {
179
+ if (it.kind === "node" && it.key) nodeIdx.set(it.key, i);
180
+ });
181
+ const out = /* @__PURE__ */ new Map();
182
+ const indeg = /* @__PURE__ */ new Map();
183
+ for (const k of nodeIdx.keys()) {
184
+ out.set(k, []);
185
+ indeg.set(k, 0);
186
+ }
187
+ for (const it of items) {
188
+ if (it.kind !== "edge" || !it.from || !it.to) continue;
189
+ if (!nodeIdx.has(it.from) || !nodeIdx.has(it.to)) continue;
190
+ out.get(it.from).push(it.to);
191
+ indeg.set(it.to, (indeg.get(it.to) ?? 0) + 1);
192
+ }
193
+ const level = /* @__PURE__ */ new Map();
194
+ const visit = (roots) => {
195
+ const queue = [...roots];
196
+ roots.forEach((r) => level.set(r, 0));
197
+ while (queue.length) {
198
+ const u = queue.shift();
199
+ for (const v of out.get(u)) {
200
+ if (!level.has(v)) {
201
+ level.set(v, level.get(u) + 1);
202
+ queue.push(v);
203
+ }
204
+ }
205
+ }
206
+ };
207
+ const readingOrder = [...nodeIdx.keys()].sort((a, b) => {
208
+ const ra = items[nodeIdx.get(a)].rect;
209
+ const rb = items[nodeIdx.get(b)].rect;
210
+ return ra.top - rb.top || ra.left - rb.left;
211
+ });
212
+ visit(readingOrder.filter((k) => indeg.get(k) === 0));
213
+ for (const k of readingOrder) if (!level.has(k)) visit([k]);
214
+ const slots = new Array(items.length);
215
+ const nodeStart = (k) => level.get(k) * step;
216
+ items.forEach((it, i) => {
217
+ if (it.kind === "node") {
218
+ slots[i] = { start: it.key && level.has(it.key) ? nodeStart(it.key) : 0, dur: t.nodeDuration };
219
+ }
220
+ });
221
+ const lastNode = Math.max(0, ...slots.filter(Boolean).map((s) => s.start));
222
+ const edgeSlot = /* @__PURE__ */ new Map();
223
+ const edgeOrder = [];
224
+ items.forEach((it, i) => {
225
+ if (it.kind !== "edge") return;
226
+ edgeOrder.push(i);
227
+ let start;
228
+ if (it.from && it.to && level.has(it.from) && level.has(it.to)) {
229
+ const lf = level.get(it.from);
230
+ const lt = level.get(it.to);
231
+ start = lt > lf ? nodeStart(it.from) + lead : Math.max(nodeStart(it.from), nodeStart(it.to)) + t.nodeDuration;
232
+ } else {
233
+ start = lastNode + t.nodeDuration;
234
+ }
235
+ slots[i] = { start, dur: t.edgeDuration };
236
+ if (it.key) edgeSlot.set(it.key, slots[i]);
237
+ });
238
+ let labelN = 0;
239
+ items.forEach((it, i) => {
240
+ if (it.kind !== "label") return;
241
+ const byKey = it.key ? edgeSlot.get(it.key) : void 0;
242
+ const e = byKey ?? (edgeOrder[labelN] !== void 0 ? slots[edgeOrder[labelN]] : void 0);
243
+ labelN++;
244
+ slots[i] = e ? { start: e.start + e.dur * 0.5, dur: t.nodeDuration * 0.7 } : { start: lastNode + t.nodeDuration, dur: t.nodeDuration };
245
+ });
246
+ items.forEach((it, i) => {
247
+ if (it.kind !== "cluster") return;
248
+ let first = Infinity;
249
+ items.forEach((n, j) => {
250
+ if (n.kind !== "node") return;
251
+ const x = cx(n.rect);
252
+ const y = cy(n.rect);
253
+ if (x >= it.rect.left && x <= it.rect.right && y >= it.rect.top && y <= it.rect.bottom) {
254
+ first = Math.min(first, slots[j].start);
255
+ }
256
+ });
257
+ const start = first === Infinity ? 0 : Math.max(0, first - t.nodeDuration * 0.4);
258
+ slots[i] = { start, dur: t.nodeDuration };
259
+ });
260
+ return slots;
261
+ }
262
+
263
+ // src/animate.ts
264
+ var DEFAULTS = {
265
+ order: "flow",
266
+ nodeEffect: "pop",
267
+ edgeEffect: "draw",
268
+ nodeDuration: 450,
269
+ edgeDuration: 500,
270
+ stagger: 120,
271
+ delay: 0,
272
+ easing: "cubic-bezier(0.22, 1, 0.36, 1)",
273
+ edgeEasing: "cubic-bezier(0.65, 0, 0.35, 1)",
274
+ loop: false,
275
+ loopHold: 1500,
276
+ autoplay: true,
277
+ respectReducedMotion: true
278
+ };
279
+ var FADE_OUT = 400;
280
+ var UNIT_CLASS = "am-u";
281
+ var WRAP_CLASS = "am-w";
282
+ var STYLE_ATTR = "data-animate-mermaid";
283
+ var instances = 0;
284
+ var HIDDEN = {
285
+ fade: "opacity:0",
286
+ pop: "opacity:0;transform:scale(0.6)",
287
+ slide: "opacity:0;transform:translateY(12px)"
288
+ };
289
+ var SHOWN = "opacity:1;transform:none";
290
+ var pct = (ms, period) => `${Math.min(100, Math.max(0, ms / period * 100)).toFixed(3)}%`;
291
+ function isPatterned(el, dash) {
292
+ const cls = el.getAttribute("class") ?? "";
293
+ if (/dotted|dashed|edge-animation/.test(cls)) return true;
294
+ if (/pattern-solid/.test(cls)) return false;
295
+ return dash !== "none" && !/^0(px)?,?\s+0(px)?[,\s]/.test(dash) && !/^0(px)?$/.test(dash);
296
+ }
297
+ function wrap(el) {
298
+ if (el.tagName.toLowerCase() !== "g") return el;
299
+ const w = document.createElementNS("http://www.w3.org/2000/svg", "g");
300
+ w.setAttribute("class", WRAP_CLASS);
301
+ while (el.firstChild) w.appendChild(el.firstChild);
302
+ el.appendChild(w);
303
+ return w;
304
+ }
305
+ function unwrap(w) {
306
+ const parent = w.parentNode;
307
+ if (!parent) return;
308
+ while (w.firstChild) parent.insertBefore(w.firstChild, w);
309
+ w.remove();
310
+ }
311
+ function nodeFrames(effect, s, period, easing, loopEnd) {
312
+ const a = pct(s.start, period);
313
+ const b = pct(s.start + s.dur, period);
314
+ const tail = loopEnd !== void 0 ? `${b},${pct(loopEnd, period)}{${SHOWN};animation-timing-function:ease-in}100%{opacity:0;transform:none}` : `${b},100%{${SHOWN}}`;
315
+ return `0%,${a}{${HIDDEN[effect]};animation-timing-function:${easing}}${tail}`;
316
+ }
317
+ function edgeFrames(s, period, easing, geo, markers, loopEnd) {
318
+ const L = geo.length.toFixed(2);
319
+ const a = pct(s.start, period);
320
+ const b = pct(s.start + s.dur, period);
321
+ const justBefore = pct(Math.max(s.start, s.start + s.dur - 1), period);
322
+ const restore = pct(s.start + s.dur + 1, period);
323
+ const mk = (v) => [markers.start && `marker-start:${v(markers.start)}`, markers.end && `marker-end:${v(markers.end)}`].filter(Boolean).join(";");
324
+ const hideMk = mk(() => "none");
325
+ const showMk = mk((m) => m);
326
+ let f = `0%,${a}{stroke-dasharray:${L} ${L};stroke-dashoffset:${L};animation-timing-function:${easing}}`;
327
+ f += `${b}{stroke-dasharray:${L} ${L};stroke-dashoffset:0}`;
328
+ f += `${restore},100%{stroke-dasharray:${geo.dash};stroke-dashoffset:${geo.offset}}`;
329
+ if (hideMk) f += `0%,${justBefore}{${hideMk}}${b},100%{${showMk}}`;
330
+ if (loopEnd !== void 0) f += `0%,${pct(loopEnd, period)}{opacity:1;animation-timing-function:ease-in}100%{opacity:0}`;
331
+ return f;
332
+ }
333
+ function animate(svg, options = {}) {
334
+ const o = { ...DEFAULTS, ...stripUndefined(options) };
335
+ const id = `am${++instances}`;
336
+ const units = collectUnits(svg);
337
+ const slots = schedule(
338
+ units.map((u) => ({ kind: u.kind, key: u.key, from: u.from, to: u.to, rect: u.el.getBoundingClientRect() })),
339
+ o
340
+ );
341
+ const duration = Math.max(0, ...slots.map((s) => s.start + s.dur));
342
+ const loopEnd = o.loop ? duration + o.loopHold : void 0;
343
+ const period = o.loop ? duration + o.loopHold + FADE_OUT : Math.max(duration, 1);
344
+ const plans = [];
345
+ const wrappers = [];
346
+ units.forEach((u, i) => {
347
+ const s = slots[i];
348
+ const name = `${id}-k${i}`;
349
+ if (u.kind === "edge") {
350
+ let effect2 = o.edgeEffect;
351
+ if (effect2 === "none") return;
352
+ const cs = getComputedStyle(u.el);
353
+ const geom = u.el;
354
+ if (effect2 === "draw" && (isPatterned(u.el, cs.strokeDasharray) || typeof geom.getTotalLength !== "function")) effect2 = "fade";
355
+ if (effect2 === "draw") {
356
+ const geo = { length: geom.getTotalLength() + 1, dash: cs.strokeDasharray || "none", offset: cs.strokeDashoffset || "0" };
357
+ const markers = {
358
+ start: u.el.getAttribute("marker-start") ?? void 0,
359
+ end: u.el.getAttribute("marker-end") ?? void 0
360
+ };
361
+ plans.push({ target: u.el, name, frames: edgeFrames(s, period, o.edgeEasing, geo, markers, loopEnd) });
362
+ } else {
363
+ plans.push({ target: u.el, name, frames: nodeFrames("fade", s, period, o.easing, loopEnd) });
364
+ }
365
+ return;
366
+ }
367
+ const effect = u.kind === "cluster" && o.nodeEffect === "pop" ? "fade" : o.nodeEffect;
368
+ if (effect === "none") return;
369
+ const target = wrap(u.el);
370
+ if (target !== u.el) wrappers.push(target);
371
+ plans.push({ target, name, frames: nodeFrames(effect, s, period, o.easing, loopEnd) });
372
+ });
373
+ const iter = o.loop ? "infinite" : "1";
374
+ let css = `.${WRAP_CLASS},.${UNIT_CLASS}{transform-box:fill-box;transform-origin:center}`;
375
+ plans.forEach((p, i) => {
376
+ const cls = `${id}-u${i}`;
377
+ p.target.classList.add(UNIT_CLASS, cls);
378
+ css += `@keyframes ${p.name}{${p.frames}}`;
379
+ css += `.${cls}{animation:${p.name} ${period}ms linear 0ms ${iter} both}`;
380
+ });
381
+ css += `.${id}-paused .${UNIT_CLASS}{animation-play-state:paused}`;
382
+ if (o.respectReducedMotion) {
383
+ css += `@media (prefers-reduced-motion: reduce){.${UNIT_CLASS}{animation:none!important}}`;
384
+ }
385
+ const style = document.createElementNS("http://www.w3.org/2000/svg", "style");
386
+ style.setAttribute(STYLE_ATTR, id);
387
+ style.textContent = css;
388
+ svg.appendChild(style);
389
+ const pausedClass = `${id}-paused`;
390
+ if (o.autoplay !== true) svg.classList.add(pausedClass);
391
+ const anims = () => svg.getAnimations({ subtree: true }).filter(
392
+ (a) => typeof a.animationName === "string" && a.animationName.startsWith(`${id}-`)
393
+ );
394
+ let observer;
395
+ const ctrl = {
396
+ svg,
397
+ duration,
398
+ period,
399
+ play() {
400
+ svg.classList.remove(pausedClass);
401
+ anims().forEach((a) => a.play());
402
+ },
403
+ pause() {
404
+ anims().forEach((a) => a.pause());
405
+ },
406
+ restart() {
407
+ ctrl.seek(0);
408
+ ctrl.play();
409
+ },
410
+ seek(ms) {
411
+ const t = o.loop ? (ms % period + period) % period : Math.min(Math.max(ms, 0), period);
412
+ anims().forEach((a) => {
413
+ a.currentTime = t;
414
+ });
415
+ },
416
+ destroy() {
417
+ observer?.disconnect();
418
+ style.remove();
419
+ svg.classList.remove(pausedClass);
420
+ plans.forEach((p, i) => p.target.classList.remove(UNIT_CLASS, `${id}-u${i}`));
421
+ wrappers.forEach(unwrap);
422
+ }
423
+ };
424
+ if (o.autoplay === "visible" && typeof IntersectionObserver !== "undefined") {
425
+ observer = new IntersectionObserver((entries) => {
426
+ if (entries.some((e) => e.isIntersecting)) {
427
+ observer?.disconnect();
428
+ ctrl.restart();
429
+ }
430
+ }, { threshold: 0.25 });
431
+ observer.observe(svg);
432
+ }
433
+ return ctrl;
434
+ }
435
+ function stripUndefined(obj) {
436
+ return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== void 0));
437
+ }
438
+
439
+ // src/render.ts
440
+ function isAbortError(e) {
441
+ return e instanceof Error && e.name === "AbortError";
442
+ }
443
+ function throwIfAborted(signal) {
444
+ if (signal?.aborted) {
445
+ const err = new Error("animate-mermaid: render aborted");
446
+ err.name = "AbortError";
447
+ throw err;
448
+ }
449
+ }
450
+ var counter = 0;
451
+ var initialized = false;
452
+ async function renderAnimated(container, code, options = {}) {
453
+ const { mermaid: provided, mermaidConfig, signal, ...animOptions } = options;
454
+ throwIfAborted(signal);
455
+ const mermaid = provided ?? (await import("mermaid")).default;
456
+ if (mermaidConfig || !provided && !initialized) {
457
+ mermaid.initialize({ startOnLoad: false, ...mermaidConfig });
458
+ initialized = true;
459
+ }
460
+ const id = `animate-mermaid-${++counter}`;
461
+ const { svg, bindFunctions } = await mermaid.render(id, code);
462
+ throwIfAborted(signal);
463
+ container.innerHTML = svg;
464
+ bindFunctions?.(container);
465
+ const el = container.querySelector("svg");
466
+ if (!el) throw new Error("animate-mermaid: Mermaid did not produce an <svg>");
467
+ return animate(el, animOptions);
468
+ }
469
+
470
+ export {
471
+ UNIT_CLASS,
472
+ animate,
473
+ isAbortError,
474
+ renderAnimated
475
+ };
476
+ //# sourceMappingURL=chunk-7IECNHKF.js.map