animate-mermaid 0.1.0 → 0.1.1

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
@@ -128,6 +128,25 @@ The share sheet works in mobile browsers, Safari, and Chrome or Edge on Windows,
128
128
  - Exported SVGs use the browser's default fonts unless you inline a webfont.
129
129
  - Safari may refuse to rasterize HTML labels (`<foreignObject>`) to PNG or GIF. If that happens, render with `mermaidConfig: { htmlLabels: false }`.
130
130
 
131
+ ## Agent skill
132
+
133
+ [skills/animate-mermaid](skills/animate-mermaid/) is an [Agent Skill](https://docs.claude.com/en/docs/agents-and-tools/agent-skills/overview): a `SKILL.md` plus a headless CLI. Coding agents use it to animate diagrams for you, either by writing an animated SVG, GIF or PNG file, or by adding the library to your app with the right snippet for your framework.
134
+
135
+ ```bash
136
+ # Claude Code: personal (all projects) or per project
137
+ cp -r skills/animate-mermaid ~/.claude/skills/
138
+ cp -r skills/animate-mermaid .claude/skills/
139
+
140
+ # one-time CLI setup
141
+ cd ~/.claude/skills/animate-mermaid/scripts && npm install
142
+ ```
143
+
144
+ For other agents, point them at `skills/animate-mermaid/SKILL.md` (for example from `AGENTS.md`). The CLI works on its own too:
145
+
146
+ ```bash
147
+ node skills/animate-mermaid/scripts/animate.mjs diagram.mmd -o diagram.svg -o diagram.gif --loop
148
+ ```
149
+
131
150
  ## Examples
132
151
 
133
152
  Runnable sample projects live in [examples/](examples/): [plain HTML](examples/html/), [React](examples/react/) and [Svelte](examples/svelte/).
@@ -0,0 +1,475 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } async function _asyncNullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return await rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// 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 (e2) {
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) && (_nullishCoalesce(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 = _nullishCoalesce(el.getAttribute("data-id"), () => ( el.getAttribute("id")));
91
+ const unit = { el, kind: "edge", key: _nullishCoalesce(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: _nullishCoalesce(_nullishCoalesce(_optionalChain([inner, 'optionalAccess', _ => _.getAttribute, 'call', _2 => _2("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, (_nullishCoalesce(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 = _nullishCoalesce(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 = _nullishCoalesce(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: _nullishCoalesce(u.el.getAttribute("marker-start"), () => ( void 0)),
359
+ end: _nullishCoalesce(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
+ _optionalChain([observer, 'optionalAccess', _3 => _3.disconnect, 'call', _4 => _4()]);
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
+ _optionalChain([observer, 'optionalAccess', _5 => _5.disconnect, 'call', _6 => _6()]);
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 (_optionalChain([signal, 'optionalAccess', _7 => _7.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 = await _asyncNullishCoalesce(provided, async () => ( (await Promise.resolve().then(() => _interopRequireWildcard(require("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
+ _optionalChain([bindFunctions, 'optionalCall', _8 => _8(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
+
471
+
472
+
473
+
474
+
475
+ exports.UNIT_CLASS = UNIT_CLASS; exports.animate = animate; exports.isAbortError = isAbortError; exports.renderAnimated = renderAnimated;
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  UNIT_CLASS
3
- } from "./chunk-7IECNHKF.js";
3
+ } from "./chunk-LYIYMF53.js";
4
4
 
5
5
  // src/export.ts
6
6
  var SVG_NS = "http://www.w3.org/2000/svg";
@@ -145,4 +145,3 @@ export {
145
145
  download,
146
146
  toGif
147
147
  };
148
- //# sourceMappingURL=chunk-SCGHSAXP.js.map
@@ -473,4 +473,3 @@ export {
473
473
  isAbortError,
474
474
  renderAnimated
475
475
  };
476
- //# sourceMappingURL=chunk-7IECNHKF.js.map
@@ -0,0 +1,147 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+ var _chunkC2V7ZENTcjs = require('./chunk-C2V7ZENT.cjs');
4
+
5
+ // src/export.ts
6
+ var SVG_NS = "http://www.w3.org/2000/svg";
7
+ function size(svg) {
8
+ const vb = _optionalChain([svg, 'access', _ => _.viewBox, 'optionalAccess', _2 => _2.baseVal]);
9
+ if (vb && vb.width && vb.height) return { width: vb.width, height: vb.height };
10
+ const r = svg.getBoundingClientRect();
11
+ return { width: r.width || 800, height: r.height || 600 };
12
+ }
13
+ function toSvgString(svg, options = {}) {
14
+ const clone = svg.cloneNode(true);
15
+ clone.setAttribute("xmlns", SVG_NS);
16
+ clone.setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
17
+ for (const c of Array.from(clone.classList)) if (/^am\d+-paused$/.test(c)) clone.classList.remove(c);
18
+ if (options.scale !== void 0) {
19
+ const { width, height } = size(svg);
20
+ clone.setAttribute("width", String(width * options.scale));
21
+ clone.setAttribute("height", String(height * options.scale));
22
+ clone.style.removeProperty("max-width");
23
+ }
24
+ if (options.background && options.background !== "transparent") {
25
+ clone.style.backgroundColor = options.background;
26
+ }
27
+ if (options.frame !== void 0) {
28
+ const freeze = document.createElementNS(SVG_NS, "style");
29
+ freeze.textContent = options.frame === "end" ? `.${_chunkC2V7ZENTcjs.UNIT_CLASS}{animation:none!important}` : `.${_chunkC2V7ZENTcjs.UNIT_CLASS}{animation-delay:${-Math.max(0, options.frame)}ms!important;animation-play-state:paused!important}`;
30
+ clone.appendChild(freeze);
31
+ }
32
+ return new XMLSerializer().serializeToString(clone);
33
+ }
34
+ async function renderFrame(svg, options = {}) {
35
+ const scale = _nullishCoalesce(options.scale, () => ( 2));
36
+ const background = _nullishCoalesce(options.background, () => ( "white"));
37
+ const { width, height } = size(svg);
38
+ const str = toSvgString(svg, { frame: _nullishCoalesce(options.frame, () => ( "end")), scale });
39
+ const img = new Image();
40
+ img.decoding = "sync";
41
+ img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(str)}`;
42
+ await img.decode();
43
+ const canvas = document.createElement("canvas");
44
+ canvas.width = Math.round(width * scale);
45
+ canvas.height = Math.round(height * scale);
46
+ const ctx = canvas.getContext("2d");
47
+ if (!ctx) throw new Error("animate-mermaid: 2D canvas unavailable");
48
+ if (background !== "transparent") {
49
+ ctx.fillStyle = background;
50
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
51
+ }
52
+ ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
53
+ return canvas;
54
+ }
55
+ async function toPng(svg, options = {}) {
56
+ const canvas = await renderFrame(svg, options);
57
+ return new Promise(
58
+ (resolve, reject) => canvas.toBlob((b) => b ? resolve(b) : reject(new Error("animate-mermaid: PNG encoding failed")), "image/png")
59
+ );
60
+ }
61
+ function toSvgBlob(svg, options = {}) {
62
+ return new Blob([toSvgString(svg, options)], { type: "image/svg+xml" });
63
+ }
64
+ function download(data, filename) {
65
+ const blob = typeof data === "string" ? new Blob([data], { type: "image/svg+xml" }) : data;
66
+ const url = URL.createObjectURL(blob);
67
+ const a = document.createElement("a");
68
+ a.href = url;
69
+ a.download = filename;
70
+ document.body.appendChild(a);
71
+ a.click();
72
+ a.remove();
73
+ setTimeout(() => URL.revokeObjectURL(url), 1e3);
74
+ }
75
+
76
+ // src/gif.ts
77
+ function isController(x) {
78
+ return !!x && typeof x === "object" && "svg" in x && "period" in x;
79
+ }
80
+ function measurePeriod(svg) {
81
+ let max = 0;
82
+ for (const a of svg.getAnimations({ subtree: true })) {
83
+ const d = Number(_optionalChain([a, 'access', _3 => _3.effect, 'optionalAccess', _4 => _4.getTiming, 'call', _5 => _5(), 'access', _6 => _6.duration]));
84
+ if (Number.isFinite(d)) max = Math.max(max, d);
85
+ }
86
+ return max;
87
+ }
88
+ var tick = () => new Promise((r) => setTimeout(r, 0));
89
+ async function toGif(source, options = {}) {
90
+ const { quantize, applyPalette, GIFEncoder } = await Promise.resolve().then(() => _interopRequireWildcard(require("gifenc")));
91
+ const svg = isController(source) ? source.svg : source;
92
+ const loops = isController(source) ? source.period > source.duration + 1 : false;
93
+ const duration = _nullishCoalesce(options.duration, () => ( (isController(source) ? source.period : measurePeriod(svg))));
94
+ const fps = Math.max(1, Math.min(50, _nullishCoalesce(options.fps, () => ( 20))));
95
+ const background = _nullishCoalesce(options.background, () => ( "white"));
96
+ const transparent = background === "transparent";
97
+ const holdEnd = _nullishCoalesce(options.holdEnd, () => ( (loops ? 0 : 1500)));
98
+ const vb = _optionalChain([svg, 'access', _7 => _7.viewBox, 'optionalAccess', _8 => _8.baseVal]);
99
+ const width = vb && vb.width ? vb.width : svg.getBoundingClientRect().width;
100
+ const scale = Math.min(_nullishCoalesce(options.scale, () => ( 1)), (_nullishCoalesce(options.maxWidth, () => ( 1200))) / Math.max(1, width));
101
+ const step = 1e3 / fps;
102
+ const times = [];
103
+ for (let t = 0; t < duration; t += step) times.push(t);
104
+ const last = loops ? duration : "end";
105
+ const grab = async (frame) => {
106
+ const canvas = await renderFrame(svg, { frame, scale, background });
107
+ const ctx = canvas.getContext("2d", { willReadFrequently: true });
108
+ return { data: ctx.getImageData(0, 0, canvas.width, canvas.height).data, w: canvas.width, h: canvas.height };
109
+ };
110
+ const final = await grab("end");
111
+ const format = transparent ? "rgba4444" : "rgb565";
112
+ const palette = quantize(final.data, 256, transparent ? { format, oneBitAlpha: true } : { format });
113
+ const transparentIndex = transparent ? palette.findIndex((c) => c[3] === 0) : -1;
114
+ const gif = GIFEncoder();
115
+ const total = times.length + 1;
116
+ const write = (data, w, h, delay, first) => {
117
+ gif.writeFrame(applyPalette(data, palette, format), w, h, {
118
+ palette: first ? palette : void 0,
119
+ delay,
120
+ repeat: first ? _nullishCoalesce(options.repeat, () => ( 0)) : void 0,
121
+ transparent: transparentIndex >= 0,
122
+ transparentIndex: Math.max(0, transparentIndex),
123
+ dispose: transparent ? 2 : -1
124
+ });
125
+ };
126
+ for (let i = 0; i < times.length; i++) {
127
+ if (_optionalChain([options, 'access', _9 => _9.signal, 'optionalAccess', _10 => _10.aborted])) throw Object.assign(new Error("animate-mermaid: GIF export aborted"), { name: "AbortError" });
128
+ const f = await grab(times[i]);
129
+ write(f.data, f.w, f.h, step, i === 0);
130
+ _optionalChain([options, 'access', _11 => _11.onProgress, 'optionalCall', _12 => _12((i + 1) / total)]);
131
+ if (i % 4 === 3) await tick();
132
+ }
133
+ const end = last === "end" ? final : await grab(last);
134
+ write(end.data, end.w, end.h, step + holdEnd, times.length === 0);
135
+ _optionalChain([options, 'access', _13 => _13.onProgress, 'optionalCall', _14 => _14(1)]);
136
+ gif.finish();
137
+ return new Blob([gif.bytes()], { type: "image/gif" });
138
+ }
139
+
140
+
141
+
142
+
143
+
144
+
145
+
146
+
147
+ exports.toSvgString = toSvgString; exports.renderFrame = renderFrame; exports.toPng = toPng; exports.toSvgBlob = toSvgBlob; exports.download = download; exports.toGif = toGif;