A Diagram Renderer of your own

A Diagram Renderer turns a diagram's source text into an SVG string, for one or more diagram formats such as Mermaid. The editor shows the SVG as an image.

Quick start

This Diagram Renderer sends Mermaid source to a rendering service you host:

import type { DiagramRenderer } from '@tiptap-pro/extension-diagrams'

export function serviceDiagramRenderer(endpoint: string): DiagramRenderer {
  return {
    id: 'mermaid-service',
    label: 'Mermaid (service)',
    formats: ['mermaid'],
    async render({ source, theme, raster }) {
      const response = await fetch(endpoint, {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ source, theme, htmlLabels: !raster }),
      })
      if (!response.ok) throw new Error(`The diagram service answered ${response.status}`)
      const svg = await response.text()
      const root = new DOMParser().parseFromString(svg, 'image/svg+xml').documentElement
      const width = Number.parseFloat(root.getAttribute('width') ?? '') || 600
      const height = Number.parseFloat(root.getAttribute('height') ?? '') || 400
      return { svg, width, height }
    },
  }
}

Diagrams.configure({
  diagramRenderers: [serviceDiagramRenderer('https://diagrams.example.com/mermaid/svg')],
})

Members

MemberTypeDescription
idstringNames it in a menu and in rules, not stored
labelstringOptional. For a menu. Defaults to the id
formatsreadonly FlowDiagramFormat[]'mermaid', 'drawio', 'bpmn' or a format of your own
draws(source: string) => booleanOptional. Whether it draws this source. Without it, every source
rulesRendererRulesOptional. See Rules of your Renderer
render(input) => Promise<{ svg, width, height }>Draws the source, or rejects, which shows the error state
editingDiagramEditingOptional. See Editing in the diagram

Which Renderer draws a diagram

The first registered Diagram Renderer whose formats include the format and whose draws accepts the source draws it. Empty source goes to the first one of its format without asking draws.

When every Renderer of the format declines, the diagram shows what unavailable returns, with the reason 'unsupported-kind', such as a Mermaid kind that none of them draws. The source stays. Unlike a chart Renderer, a declining Diagram Renderer does not draw the diagram after all.

A format of your own

insertFlowDiagram and updateFlowDiagram accept a format while a registered Diagram Renderer lists it, with no other registration. Its id has up to 64 letters, digits, _ and -, and its source is stored as it is, up to 1,000,000 characters. A format no registered Renderer draws stays unchanged through every save, and shows what unavailable returns, with the reason 'no-renderer'.

What render receives

InputTypeDescription
formatFlowDiagramFormatOne of the Renderer's formats
sourcestringThe source as stored
themeDiagramThemeColors and fonts from the --tt-flow-diagram-* custom properties
rasterbooleanOptional. true when the SVG becomes a PNG, WebP, JPEG or Word image

theme holds background, nodeColor, nodeBorderColor, textColor, lineColor, groupColor, noteColor and fontFamily as strings, and fontSize in pixels. With raster, write labels as SVG text, without foreignObject, which a canvas cannot export.

What render returns

{ svg, width, height }: a standalone SVG string with a width and a height, and the drawing's size in pixels.

Editing in the diagram

Users can double click a text in a Mermaid diagram to edit it, and drag a shape of a Mermaid flowchart, see Editing in the diagram. The Renderer tells the extension where texts and shapes are through editing. The extension asks editing only for the mermaid format, so diagrams of other formats cannot be edited in the picture.

A Renderer that draws with mermaid.js can reuse the built-in editing, where render is your drawing function:

import type { DiagramRenderer } from '@tiptap-pro/extension-diagrams'
import { mermaidDiagramEditing } from '@tiptap-pro/extension-diagrams/mermaid'

const renderer: DiagramRenderer = {
  id: 'my-mermaid',
  formats: ['mermaid'],
  render,
  editing: mermaidDiagramEditing,
}

When your Renderer draws Mermaid source with another library, its SVG differs, so write editing yourself. Each function gets the SVG render returned and the source, and returns null for a diagram kind it does not handle:

MemberSignatureWithout it
labelAt(svg: string, point: DiagramPoint, source: string) => DiagramLabelHit | nullA double click opens nothing
nodeAt(svg: string, point: DiagramPoint, source: string) => DiagramNodeHit | nullNo dragging
movePositions(svg: string, positions: DiagramNodePositions, source: string) => string | nullNo dragging. Stored offsets stay, but are not drawn

These types come from @tiptap-pro/extension-diagrams, with lengths in the SVG's own units:

TypeShapeDescription
DiagramPoint{ x: number, y: number }Where the user clicked, through the viewBox
DiagramBox{ x, y, width, height }Where a text or shape is
DiagramLabelHit{ target, label, box }The text under the point, target naming it in the source
DiagramNodeHit{ id, label, box }The shape under the point, id from the source
DiagramNodePositionsRecord<string, { dx: number, dy: number }>Each shape's move right and down, by id, at most 10,000 either way

labelAt names the text it found with target, a MermaidLabelTarget from @tiptap-pro/extension-diagrams/core, and the extension writes the new text there in the source. target is { kind, id }, and id depends on kind:

kindid
'node', 'participant', 'state', 'class'Its id in the source, such as 'A' for A[Start]
'edge'L_<from>_<to>_<n>, such as L_A_B_0. <n> counts the edges between the same two nodes, from 0
'message'The message's place in a sequence diagram, from '0'
'text'The text itself, in the other kinds

Dragging needs nodeAt and movePositions. movePositions returns the SVG with each shape moved by its offset, or null when nothing moved. When a moved shape reaches past the picture, enlarge the viewBox of the SVG you return. The extension then shows the picture larger in the same proportion. Exports draw the moved shapes too.

Keeping your web page safe

The editor shows the SVG in an <img>, so its scripts and outside resources never run or load. Never evaluate the source in your page: render it on a server or in a sandboxed iframe, or, for a parser that needs no DOM, in a Web Worker, as Pele does.