Mermaid diagram

Renders Mermaid code as a themeable SVG on a scrollable dot-grid board.

Cloudflare yes no Write MDX Build In budget? Deploy Trim assets Worker D1

Installation

CLI

pnpm dlx shadcn@latest add @riff/mermaid-diagram

Manual

  1. Install beautiful-mermaid

    pnpm add beautiful-mermaid
  2. Copy the component

    Save this as components/ui/mermaid-diagram.tsx:

    'use client';
    import { useId, useMemo } from 'react';
    import { renderMermaidSVG } from 'beautiful-mermaid';
    import './mermaid-diagram.css';
    
    const TONES = ['yellow', 'orange', 'red', 'green', 'blue', 'violet'] as const;
    export type DiagramTone = (typeof TONES)[number];
    
    type Point = [number, number];
    
    const escapeAttribute = (value: string) =>
      value
        .replaceAll('&', '&')
        .replaceAll('<', '&lt;')
        .replaceAll('>', '&gt;')
        .replaceAll('"', '&quot;');
    
    const fmt = ([x, y]: Point) => `${x.toFixed(2)},${y.toFixed(2)}`;
    
    function parsePoints(list: string): Point[] {
      const numbers = list
        .trim()
        .split(/[\s,]+/)
        .map(Number);
      const points: Point[] = [];
      for (let index = 0; index + 1 < numbers.length; index += 2)
        points.push([numbers[index] ?? 0, numbers[index + 1] ?? 0]);
      return points;
    }
    
    /** The point `distance` along the segment from `from` towards `to`. */
    function toward(from: Point, to: Point, distance: number): Point {
      const length = Math.hypot(to[0] - from[0], to[1] - from[1]) || 1;
      return [
        from[0] + ((to[0] - from[0]) / length) * distance,
        from[1] + ((to[1] - from[1]) / length) * distance,
      ];
    }
    
    /** A closed polygon (the decision diamond) with rounded corners. */
    function roundedPolygon(points: Point[], radius = 8) {
      const at = (index: number) =>
        points[(index + points.length) % points.length] ?? [0, 0];
      const corners = points.map((current, index) => {
        const previous = at(index - 1);
        const next = at(index + 1);
        const r = Math.min(
          radius,
          Math.hypot(current[0] - previous[0], current[1] - previous[1]) / 2,
          Math.hypot(next[0] - current[0], next[1] - current[1]) / 2,
        );
        return {
          current,
          before: toward(current, previous, r),
          after: toward(current, next, r),
        };
      });
      const [first] = corners;
      if (!first) return '';
      let d = `M ${fmt(first.after)}`;
      for (const { current, before, after } of [...corners.slice(1), first])
        d += ` L ${fmt(before)} Q ${fmt(current)} ${fmt(after)}`;
      return `${d} Z`;
    }
    
    /** An elbowed connector with its bends rounded off. */
    function roundedPath(points: Point[], radius = 10) {
      const [start = [0, 0]] = points;
      let d = `M ${fmt(start)}`;
      for (let index = 1; index < points.length - 1; index++) {
        const previous = points[index - 1] ?? start;
        const current = points[index] ?? start;
        const next = points[index + 1] ?? start;
        const r = Math.min(
          radius,
          Math.hypot(current[0] - previous[0], current[1] - previous[1]) / 2,
          Math.hypot(next[0] - current[0], next[1] - current[1]) / 2,
        );
        if (r < 0.5) d += ` L ${fmt(current)}`;
        else
          d += ` L ${fmt(toward(current, previous, r))} Q ${fmt(current)} ${fmt(toward(current, next, r))}`;
      }
      return `${d} L ${fmt(points.at(-1) ?? start)}`;
    }
    
    /**
     * Renders Mermaid code to SVG with beautiful-mermaid, then softens it: rounded
     * boxes, diamonds and elbows, filled arrowheads, unique marker ids, and
     * colours that read the component's custom properties so it follows the theme.
     */
    function renderDiagram(
      chart: string,
      title: string,
      uid: string,
      groups: Readonly<Record<string, DiagramTone>>,
    ) {
      const tones = TONES.map(
        (tone) =>
          `  classDef ${tone} fill:var(--riff-dg-${tone}-fill),stroke:var(--riff-dg-${tone}),color:var(--riff-dg-text)`,
      ).join('\n');
      let svg = renderMermaidSVG(`${chart.trim()}\n${tones}`, {
        bg: 'var(--riff-dg-surface)',
        fg: 'var(--riff-dg-text)',
        line: 'var(--riff-dg-line)',
        surface: 'var(--riff-dg-surface)',
        border: 'var(--riff-dg-border)',
        transparent: true,
        padding: 16,
        nodeSpacing: 16,
        layerSpacing: 28,
      });
      const width = Number(/width="([\d.]+)"/.exec(svg)?.[1] ?? 0);
      svg = svg
        // The host's font, not a web-font import.
        .replace(/@import url\([^)]*\);\s*/, '')
        .replace(/font-family:[^;]+;/, 'font-family: inherit;')
        // Fluid width; the viewBox keeps the proportions.
        .replace(
          /<svg([^>]*?) width="[\d.]+" height="[\d.]+"/,
          `<svg$1 role="img" aria-label="${escapeAttribute(title)}"`,
        )
        // Several diagrams can share a page.
        .replace(/ id="([^"]+)"/g, ` id="${uid}-$1"`)
        .replace(/url\(#([^)]+)\)/g, `url(#${uid}-$1)`)
        .replace(/<g class="subgraph" data-id="([^"]+)"/g, (match, id: string) =>
          groups[id] ? `${match} data-tone="${groups[id]}"` : match,
        )
        // Rounded corners: groups, then nodes, then edge-label pills.
        .replace(
          /(<g class="subgraph"[^>]*>\s*<rect[^>]*?) rx="0" ry="0"/g,
          '$1 rx="12" ry="12"',
        )
        .replace(/ rx="0" ry="0"/g, ' rx="8" ry="8"')
        .replace(/ rx="2" ry="2"/g, ' rx="6" ry="6"')
        // Filled triangle arrowheads.
        .replace(
          /<marker id="([^"]+)"[^>]*?orient="([^"]+)">\s*<polygon[^>]*?fill="([^"]+)"[^>]*\/>\s*<\/marker>/g,
          (_, id: string, orient: string, color: string) =>
            `<marker id="${id}" viewBox="0 0 12 12" markerWidth="10.5" markerHeight="10.5" markerUnits="userSpaceOnUse" refX="10.5" refY="6" orient="${orient}"><path d="M 1.5 1.5 L 10.5 6 L 1.5 10.5 Z" fill="${color}" stroke="${color}" stroke-width="1" stroke-linejoin="round" /></marker>`,
        )
        .replace(
          /<polygon points="([^"]+)"([^>]*?)\/>/g,
          (_, points: string, rest: string) =>
            `<path d="${roundedPolygon(parsePoints(points))}"${rest} stroke-linejoin="round" />`,
        )
        .replace(
          /<polyline([^>]*?) points="([^"]+)"([^>]*?)\/>/g,
          (_, before: string, points: string, after: string) =>
            `<path${before} d="${roundedPath(parsePoints(points))}"${after} stroke-linejoin="round" stroke-linecap="round" />`,
        );
    
      // Edge labels knock out the line behind them; inside a toned group the
      // knockout takes the group's tint, so tag each label with its group's tone.
      const boxes = [
        ...svg.matchAll(
          /<g class="subgraph"[^>]*data-tone="([^"]+)"[^>]*>\s*<rect x="([\d.]+)" y="([\d.]+)" width="([\d.]+)" height="([\d.]+)"/g,
        ),
      ]
        .map(([, tone = '', x, y, w, h]) => ({
          tone,
          x: Number(x),
          y: Number(y),
          w: Number(w),
          h: Number(h),
        }))
        .sort((a, b) => a.w * a.h - b.w * b.h);
      svg = svg.replace(
        /<g class="edge-label"([^>]*)>(\s*<rect x="([\d.]+)" y="([\d.]+)" width="([\d.]+)" height="([\d.]+)")/g,
        (
          _,
          attrs: string,
          rest: string,
          x: string,
          y: string,
          w: string,
          h: string,
        ) => {
          const cx = Number(x) + Number(w) / 2;
          const cy = Number(y) + Number(h) / 2;
          const box = boxes.find(
            (b) => cx > b.x && cx < b.x + b.w && cy > b.y && cy < b.y + b.h,
          );
          const labelWidth = Math.max(Number(w) - 12, 12);
          const tight = `<rect x="${(cx - labelWidth / 2).toFixed(2)}" y="${(cy - 10).toFixed(2)}" width="${labelWidth.toFixed(2)}" height="20"`;
          const tone = box ? ` data-tone="${box.tone}"` : '';
          return `<g class="edge-label"${tone}${attrs}>${rest.replace(/<rect[^>]*?height="[\d.]+"/, tight)}`;
        },
      );
      return { svg, width };
    }
    
    const NO_GROUPS: Readonly<Record<string, DiagramTone>> = {};
    
    /**
     * A Mermaid diagram (flowchart, sequence, state, class, ER or XY chart) on a
     * dot-grid board that scrolls sideways when the diagram is wider than it.
     * It renders during render, so server HTML already holds the SVG.
     */
    export function MermaidDiagram({
      chart,
      title,
      caption,
      groups = NO_GROUPS,
    }: {
      /** The Mermaid source. */
      chart: string;
      /** What the diagram shows, read by screen readers. */
      title: string;
      caption?: string;
      /** Tints `subgraph` ids, such as `{ api: 'blue' }`. */
      groups?: Readonly<Record<string, DiagramTone>>;
    }) {
      const id = useId();
      const uid = `riff-dg-${id.replace(/[^\w-]/g, '')}`;
      const result = useMemo(() => {
        try {
          return renderDiagram(chart, title, uid, groups);
        } catch (error) {
          return { error: error instanceof Error ? error.message : String(error) };
        }
      }, [chart, title, uid, groups]);
      return (
        <figure className="riff-diagram">
          <div
            className="riff-diagram-board"
            role="region"
            aria-label={title}
            aria-describedby={caption ? `${uid}-caption` : undefined}
            // A board wider than the page scrolls, so keyboards must reach it.
            // oxlint-disable-next-line jsx-a11y/no-noninteractive-tabindex
            tabIndex={0}
          >
            {'error' in result ? (
              <p className="riff-diagram-error" role="alert">
                This diagram couldn’t be drawn: {result.error}
              </p>
            ) : (
              <div
                className="riff-diagram-image"
                style={{
                  maxWidth: `${result.width}px`,
                  minWidth: `min(${result.width}px, 36rem)`,
                }}
                // The SVG comes from Mermaid's renderer, with labels escaped.
                // oxlint-disable-next-line react/no-danger
                dangerouslySetInnerHTML={{ __html: result.svg }}
              />
            )}
          </div>
          {caption && (
            <figcaption id={`${uid}-caption`} className="riff-diagram-caption">
              {caption}
            </figcaption>
          )}
        </figure>
      );
    }
  3. Copy its styles

    Save this beside it as mermaid-diagram.css:

    /* Host roles first, system colours after: the component reads your theme
       when it has these properties and stays legible when it does not. The
       renderer writes var(--riff-dg-*) into the SVG; neutrals follow the theme
       and the six tones keep their hues. */
    @layer components {
      .riff-diagram {
        --riff-dg-yellow: #ffdc49;
        --riff-dg-orange: #fe9f4d;
        --riff-dg-red: #ff6464;
        --riff-dg-green: #2cc75c;
        --riff-dg-blue: #659df2;
        --riff-dg-violet: #8f7fee;
        --riff-dg-board: var(--color-muted, Canvas);
        --riff-dg-dot: var(--color-border, GrayText);
        --riff-dg-surface: var(--color-background, Canvas);
        --riff-dg-line: var(--color-muted-foreground, GrayText);
        --riff-dg-border: color-mix(
          in srgb,
          var(--riff-dg-line) 75%,
          var(--riff-dg-surface)
        );
        --riff-dg-text: var(--color-foreground, CanvasText);
        --riff-dg-yellow-fill: color-mix(
          in srgb,
          var(--riff-dg-yellow) 30%,
          var(--riff-dg-surface)
        );
        --riff-dg-orange-fill: color-mix(
          in srgb,
          var(--riff-dg-orange) 30%,
          var(--riff-dg-surface)
        );
        --riff-dg-red-fill: color-mix(
          in srgb,
          var(--riff-dg-red) 30%,
          var(--riff-dg-surface)
        );
        --riff-dg-green-fill: color-mix(
          in srgb,
          var(--riff-dg-green) 30%,
          var(--riff-dg-surface)
        );
        --riff-dg-blue-fill: color-mix(
          in srgb,
          var(--riff-dg-blue) 30%,
          var(--riff-dg-surface)
        );
        --riff-dg-violet-fill: color-mix(
          in srgb,
          var(--riff-dg-violet) 30%,
          var(--riff-dg-surface)
        );
        display: flex;
        flex-direction: column;
        gap: 0.5rem;
        width: 100%;
        margin: 0;
      }
      /* A dot-grid canvas that scrolls sideways for wide diagrams. */
      .riff-diagram-board {
        overflow-x: auto;
        border: 1px solid var(--color-border, GrayText);
        border-radius: 0.75rem;
        padding: 0.5rem;
        background-color: var(--riff-dg-board);
        background-image: radial-gradient(
          circle,
          var(--riff-dg-dot) 1px,
          transparent 1.25px
        );
        background-position: center;
        background-size: 20px 20px;
        &:focus-visible {
          outline: 2px solid var(--color-ring, Highlight);
          outline-offset: 2px;
        }
      }
      .riff-diagram-image {
        margin-inline: auto;
      }
      .riff-diagram svg {
        display: block;
        width: 100%;
        height: auto;
        text-rendering: geometricPrecision;
      }
      .riff-diagram-error {
        margin: 0;
        padding: 1rem;
        color: var(--color-muted-foreground, GrayText);
        font-size: 0.875rem;
      }
      .riff-diagram-caption {
        color: var(--color-muted-foreground, GrayText);
        font-size: 0.875rem;
        line-height: 1.4;
      }
      .riff-diagram g.node > rect,
      .riff-diagram g.node > path,
      .riff-diagram g.node > ellipse,
      .riff-diagram g.node > line {
        stroke-width: 1.5px;
      }
      .riff-diagram path.edge {
        stroke-width: 1.25px;
      }
      /* Edge labels: plain text on the line, with a board-coloured gap. */
      .riff-diagram g.edge-label > rect {
        fill: var(--riff-dg-board);
        stroke: none;
      }
      .riff-diagram g.edge-label[data-tone] > rect {
        fill: color-mix(
          in srgb,
          var(--riff-dg-tone-fill) 30%,
          var(--riff-dg-board)
        );
      }
      .riff-diagram g.edge-label > text {
        fill: var(--riff-dg-text);
        font-weight: 500;
      }
      /* A group's label sits inside its box; drop the separate header band. */
      .riff-diagram g.subgraph > rect:nth-of-type(2) {
        fill: none;
        stroke: none;
      }
      .riff-diagram g.subgraph[data-tone] > rect:first-of-type {
        fill: color-mix(in srgb, var(--riff-dg-tone-fill) 30%, transparent);
        stroke: var(--riff-dg-tone);
        stroke-dasharray: 6 4;
        stroke-width: 1.5px;
      }
      .riff-diagram g[data-tone='yellow'] {
        --riff-dg-tone: var(--riff-dg-yellow);
        --riff-dg-tone-fill: var(--riff-dg-yellow-fill);
      }
      .riff-diagram g[data-tone='orange'] {
        --riff-dg-tone: var(--riff-dg-orange);
        --riff-dg-tone-fill: var(--riff-dg-orange-fill);
      }
      .riff-diagram g[data-tone='red'] {
        --riff-dg-tone: var(--riff-dg-red);
        --riff-dg-tone-fill: var(--riff-dg-red-fill);
      }
      .riff-diagram g[data-tone='green'] {
        --riff-dg-tone: var(--riff-dg-green);
        --riff-dg-tone-fill: var(--riff-dg-green-fill);
      }
      .riff-diagram g[data-tone='blue'] {
        --riff-dg-tone: var(--riff-dg-blue);
        --riff-dg-tone-fill: var(--riff-dg-blue-fill);
      }
      .riff-diagram g[data-tone='violet'] {
        --riff-dg-tone: var(--riff-dg-violet);
        --riff-dg-tone-fill: var(--riff-dg-violet-fill);
      }
    }

Usage

import { MermaidDiagram } from '@/components/ui/mermaid-diagram';

<MermaidDiagram
  title="Sign-in flow"
  chart={`flowchart TD
  A[Visit] --> B{Signed in?}
  B -->|Yes| C[Dashboard]
  B -->|No| D[Sign in]`}
/>;

It draws flowcharts, sequence, state, class and ER diagrams and XY charts with beautiful-mermaid. Rendering happens during render, so server HTML already holds the SVG. Tint a subgraph with groups, or a node with class id blue, using yellow, orange, red, green, blue or violet. Pass only Mermaid you wrote: the SVG is inserted as HTML.

Props

PropTypeDefaultDescription
chartstringThe Mermaid source.
titlestringWhat the diagram shows, for screen readers.
captionstringText under the board.
groupsRecord<string, DiagramTone>Tints subgraphs by id.