mermaid-flow-player
v0.1.11
Published
Animate Mermaid-rendered diagrams with semantic node/edge steps and scenarios
Downloads
487
Maintainers
Readme
mermaid-flow-player
Animate Mermaid-rendered diagrams (flowcharts, etc.) with a semantic API: target nodes by ID (e.g. A, B, X1) and play scenarios (steps over time) without depending on Mermaid's internal DOM structure.
Use via CDN with no install required. (Not published to npm; only built dist is published. Use CDN URLs or build from source and host the scripts yourself.)
Quick start (CDN)
One script: CSS is bundled and injected by the library. Add Mermaid, then the flow player:
<!-- 1. Mermaid -->
<script src="https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js"></script>
<!-- 2. Flow player (auto mode: zero config, styles injected automatically) -->
<script type="module" src="https://cdn.jsdelivr.net/npm/mermaid-flow-player/auto.js"></script>Every .mermaid diagram gets play controls automatically. Or use the API with the full library (one script, styles still injected):
<script type="module">
import { createFlowPlayer } from 'https://cdn.jsdelivr.net/npm/mermaid-flow-player';
const player = createFlowPlayer({
root: document.getElementById('diagram')
});
await player.ready();
await player.play(player.path('A', 'B', 'C'));
</script>CDN URL builder: docs site → CDN Builder. Pick options and copy script tags or query params.
Usage (programmatic)
import { createFlowPlayer } from 'https://cdn.jsdelivr.net/npm/mermaid-flow-player';
const root = document.getElementById("diagram");
const player = createFlowPlayer({
root,
persist: "visited",
dim: "others",
edgeMode: "bestEffort",
});
await player.ready();
await player.play(player.path("A", "B", "C", "E", "F", "G", "J"), { speed: 1.1 });Use stable, simple node IDs in your Mermaid diagram (e.g. A, B, X1) so path() and steps line up.
Features
Multi-Diagram Support
Auto-detects and animates 7 diagram types:
- Flowcharts, Sequence Diagrams, State Diagrams, Gantt Charts, User Journey, Class Diagrams, ER Diagrams
All diagram types use the same animation API; just change your Mermaid diagram type and the player adapts automatically.
Narration
Automatically update narration text as animation progresses:
createFlowPlayer({
root: diagram,
narrationTarget: '#narration',
});
await player.play([
{ type: 'node', id: 'A', note: 'Starting...' },
{ type: 'node', id: 'B', note: 'Processing...' },
]);Narrated walkthroughs — captions, voice, transcript, deep-links
Every step (auto-play and manual Next/Previous) emits a single mfp:step
event, and the per-step text is auto-derived from the Mermaid markup — a
sequence message's label or a node's label — so authors get narration for free
just by writing normal diagrams. Sequence diagrams step through their messages
in order.
Sequence Note over/of … lines are picked up automatically as the richer
commentary for the message they follow; otherwise the message label is used.
<mermaid-flow-player controls captions chapters speak karaoke scroll-steps>
sequenceDiagram
Req->>W: POST /access-requests
Note over Req,W: A worker validates the caller and opens a request.
W->>WF: create instance
WF->>Req: signed approval link
</mermaid-flow-player>Opt-in attributes:
| Attribute | Effect |
| --- | --- |
| captions | Live caption bar showing the current step's text (ARIA-announced). |
| speak | Reads each step aloud via the browser's SpeechSynthesis — zero audio files. |
| chapters | Clickable chapter rail (one entry per step); click to jump. |
| karaoke | Auto-advances when each step's narration (audio clip or voice) ends. |
| scroll-steps | Drives the step index from page scroll (scrollytelling). |
| step="N" / ?step=N | Deep-link straight to a step. |
Hook mfp:step to drive your own audio commentary, analytics, or scroll-sync —
it fires on auto-play and manual stepping with { index, node, text }:
const el = document.querySelector('mermaid-flow-player');
// Option A: bind clips and let the player manage playback (+ karaoke timing)
el.audioTracks = { 0: 'audio/01.mp3', 1: 'audio/02.mp3' };
// Option B: react to the event yourself
el.addEventListener('mfp:step', (e) => {
const { index, node, text } = e.detail; // text = markup-derived narration
analytics.track('diagram_step', { index, text });
});Browser autoplay rules apply: bound audio plays after a user gesture (clicking Play/Next), so
karaokeruns once the reader interacts.
Build a transcript, captions file, or chapter list from the steps:
import { toTranscript, toVtt } from 'mermaid-flow-player';
const steps = el.player.getSteps(); // [{ index, node, text }, ...]
toTranscript(steps); // "1. ...\n2. ..." (Markdown/plain text)
toVtt(steps, { secondsPerCue: 5 }); // WebVTT subtitle trackAnimation Easing
Control animation timing with 30+ easing functions: standard CSS, back, elastic, bounce, power curves, and custom cubic-bezier().
createFlowPlayer({
root: diagram,
easing: {
default: 'ease-out-back',
states: {
active: 'ease-out-elastic',
success: 'ease-out-bounce',
}
}
});Enhanced Edge Animation
Multi-strategy edge detection with automatic fallback:
createFlowPlayer({
root: diagram,
edgeMode: 'bestEffort',
edgeDetection: {
strategy: ['title', 'data-attr', 'text', 'path-trace'],
debug: true,
}
});Scenario Builder API
Build complex animations with a fluent, chainable API:
import { createScenarioBuilder } from 'https://cdn.jsdelivr.net/npm/mermaid-flow-player@latest';
await createScenarioBuilder()
.node('Start', { note: 'Beginning' })
.wait(500)
.node('Process', { state: 'active' })
.node('End', { state: 'success' })
.play(player);Features: chainable methods, diagram-specific builders (flowchart, sequence, state), repeat(), conditional(), template registry.
Plugin System
Extend functionality with lifecycle hooks:
import { createFlowPlayer, type Plugin } from 'https://cdn.jsdelivr.net/npm/mermaid-flow-player@latest';
import { AnalyticsPlugin, KeyboardControlsPlugin } from 'https://cdn.jsdelivr.net/npm/mermaid-flow-player@latest';
const player = createFlowPlayer({
root: diagram,
plugins: [AnalyticsPlugin, KeyboardControlsPlugin],
});Built-in plugins: AnalyticsPlugin (event tracking), KeyboardControlsPlugin (Space/R/Arrow keys).
Web Component
Drop-in <mermaid-flow-player> custom element. Diagram from inner text (or diagram attribute):
<script src="https://cdn.jsdelivr.net/npm/mermaid-flow-player@latest/mermaid-flow-player.element.js"></script>
<mermaid-flow-player autoplay controls>
graph LR; A-->B-->C
</mermaid-flow-player>Narration is opt-in: add the narration attribute (or narration-text="…") to show the narration area; otherwise it isn't rendered. Playback exposes a single lifecycle status — "idle" | "playing" | "paused" — via el.player.getStatus(), and every transition fires a bubbling mfp:statechange event (detail.status), which the play/pause control reflects automatically.
Interactive Mode
Step-through with user-controlled path selection:
const player = createFlowPlayer({ root: diagram, mode: 'interactive' });
await player.nextStep();Viewport & readable fit
Zoom, pan, and fitView() keep large diagrams legible: fit never shrinks below a readable floor, so when a diagram is too big to show whole it stays readable and the viewport scrolls/pans (pinned to the start) instead of becoming a postage stamp. Tune the floor with viewport.minReadableScale (default 0.6):
createFlowPlayer({ root: diagram, viewport: { minReadableScale: 0.6 } });Validation and user feedback
Diagram validity comes from Mermaid (they run in the browser). We propagate their errors; listen for mfp:error or use normalizeMermaidError(e) when you call mermaid.run() / mermaid.render(). For scenario-vs-index (after render), use player.validateScenario(steps) and show result.availableNodeIds for suggestions.
import { normalizeMermaidError } from '…';
try {
await mermaid.run({ nodes: [el] });
} catch (e) {
const payload = normalizeMermaidError(e);
showInUI(payload.message, payload.detail);
}Scenario-vs-index (after the diagram has rendered): use player.validateScenario(steps) to check that step IDs exist and get availableNodeIds for "Did you mean: A, B, C?". assertIds(ids) throws with available node IDs in the message.
Auto Modes
Zero-config usage:
import { autoInit } from 'https://cdn.jsdelivr.net/npm/mermaid-flow-player@latest/auto-init.js';
autoInit({ controls: true, narration: true });URL Query Parameter Configuration
Configure via URL without JavaScript: page.html?theme=dark&speed=1.5&dim=none
| Parameter | Values | Default |
|-----------|--------|---------|
| theme | light, dark, auto | auto |
| speed | 0.1 to 10 | 1.2 |
| dim | none, others | others |
| persist | none, visited | visited |
| edge | off, bestEffort | off |
| mode | sequential, interactive | sequential |
| selector | CSS selector (e.g. .my-diagram) | .mermaid (auto modes only) |
| debug | (presence) | false |
| autoplay | (presence) | false |
License
MIT
