Files
outline/shared/editor/extensions/Mermaid.ts
T
Tom MoorandClaude Fable 5.1 1887db2dab fix: Mermaid diagrams laid out with nodes thousands of pixels apart (#13648)
* fix: Mermaid diagrams laid out with nodes thousands of pixels apart

Render diagrams with SVG text labels instead of HTML labels, except mindmaps. HTML labels are measured through foreignObject elements that some browsers size incorrectly in Mermaid's hidden render container, inflating node sizes for layout. Also removes the render container that was never passed to Mermaid.

* chore: Clarify Mermaid render container comment

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-04 17:15:39 -04:00

609 lines
19 KiB
TypeScript

import { last, sortBy } from "es-toolkit/compat";
import { t } from "i18next";
import { v4 as uuidv4 } from "uuid";
import type MermaidUnsafe from "mermaid";
import type { IconPack } from "@fortawesome/fontawesome-common-types";
import type { Node } from "prosemirror-model";
import type { Transaction } from "prosemirror-state";
import { NodeSelection, Plugin, PluginKey } from "prosemirror-state";
import { Decoration, DecorationSet } from "prosemirror-view";
import { errToString } from "../../utils/error";
import { isCode, isMermaid } from "../lib/isCode";
import { isRemoteTransaction, mapDecorations } from "../lib/multiplayer";
import { findBlockNodes } from "../queries/findChildren";
import { findParentNode } from "../queries/findParentNode";
import type { NodeWithPos } from "../types";
import type { Editor } from "../../../app/editor";
import { LightboxImageFactory } from "../lib/Lightbox";
import { hashString } from "../../utils/string";
import { LRUCache } from "../../utils/LRUCache";
import { sanitizeUrl } from "../../utils/urls";
import { isModKey } from "../../utils/keyboard";
export const pluginKey = new PluginKey("mermaid");
export type MermaidState = {
decorationSet: DecorationSet;
isDark: boolean;
editingId?: string;
};
// The `v4` namespace discards entries cached before the switch to SVG text
// labels, so previously mis-sized diagrams are re-rendered instead of served
// from cache.
const cache = new LRUCache<string>({
max: 20,
namespace: "mermaid:v4",
storage: "sessionStorage",
});
let mermaid: typeof MermaidUnsafe;
/** Minimal Iconify JSON icon set format required by Mermaid's `registerIconPacks` API. */
interface IconifyIconSet {
prefix: string;
icons: Record<string, { body: string; width: number; height: number }>;
}
/**
* Converts a FontAwesome icon pack to the Iconify JSON format expected by Mermaid's
* `registerIconPacks` API.
*
* @param pack the FontAwesome icon pack to convert.
* @param prefix the Iconify prefix to use (e.g. "fa-solid" or "fa-brands").
* @returns an Iconify-compatible JSON icon set.
*/
function fontAwesomeToIconify(pack: IconPack, prefix: string): IconifyIconSet {
const icons: IconifyIconSet["icons"] = {};
for (const iconDef of Object.values(pack)) {
// icon array layout: [width, height, ligatures, unicode, svgPathData]
if (!iconDef.iconName || !iconDef.icon) {
continue;
}
const [width, height, , , paths] = iconDef.icon;
const body = Array.isArray(paths)
? paths.map((p) => `<path d="${p}"/>`).join("")
: `<path d="${paths}"/>`;
icons[iconDef.iconName] = { body, width, height };
}
return { prefix, icons };
}
/**
* Determines whether a diagram should be rendered with HTML labels.
*
* HTML labels are measured through `foreignObject` elements, which some
* browsers size incorrectly in Mermaid's hidden render container, producing
* diagrams with nodes spread thousands of pixels apart. SVG text labels are
* measured reliably, so they are used everywhere except mindmaps, which
* Mermaid cannot lay out correctly without HTML labels.
*
* @param text the diagram source.
* @returns true if HTML labels should be used.
*/
function shouldUseHtmlLabels(text: string): boolean {
try {
return mermaid.detectType(text) === "mindmap";
} catch (_err) {
return false;
}
}
class MermaidRenderer {
readonly diagramId: string;
readonly element: HTMLElement;
readonly elementId: string;
constructor() {
this.diagramId = uuidv4();
this.elementId = `mermaid-diagram-wrapper-${this.diagramId}`;
this.element =
document.getElementById(this.elementId) || document.createElement("div");
this.element.id = this.elementId;
this.element.classList.add("mermaid-diagram-wrapper");
}
render = async (block: { node: Node; pos: number }, isDark: boolean) => {
const element = this.element;
const text = block.node.textContent;
const cacheKey = hashString(`${isDark ? "dark" : "light"}-${text}`);
const cached = cache.get(cacheKey);
if (cached) {
element.classList.remove("parse-error", "empty");
element.innerHTML = cached;
return;
}
// Mermaid renders into a temporary element it appends to the body with
// this id prefixed by "d", which a global style positions offscreen.
const tempId =
"offscreen-mermaid-" + Math.random().toString(36).substr(2, 9);
try {
if (!mermaid) {
mermaid = (await import("mermaid")).default;
mermaid.registerLayoutLoaders([
{
name: "elk",
loader: async () => {
const { default: elkLayouts } =
await import("@mermaid-js/layout-elk");
const elkDef = elkLayouts.find(
(d: { name: string }) => d.name === "elk"
);
if (!elkDef) {
throw new Error("ELK layout not found");
}
return elkDef.loader();
},
},
]);
mermaid.registerIconPacks([
{
name: "fa-solid",
loader: async () => {
const { fas } = await import("@fortawesome/free-solid-svg-icons");
return fontAwesomeToIconify(fas, "fa-solid");
},
},
{
name: "fa-brands",
loader: async () => {
const { fab } =
await import("@fortawesome/free-brands-svg-icons");
return fontAwesomeToIconify(fab, "fa-brands");
},
},
]);
}
mermaid.initialize({
startOnLoad: true,
suppressErrorRendering: true,
// TODO: Make dynamic based on the width of the editor or remove in
// the future if Mermaid is able to handle this automatically.
gantt: { useWidth: 700 },
pie: { useWidth: 700 },
fontFamily: getComputedStyle(this.element).fontFamily || "inherit",
theme: isDark ? "dark" : "default",
darkMode: isDark,
htmlLabels: shouldUseHtmlLabels(text),
});
const { svg, bindFunctions } = await mermaid.render(tempId, text);
element.classList.remove("parse-error", "empty");
element.innerHTML = svg;
// Allow the user to interact with the diagram
bindFunctions?.(element);
// Mermaid sizes the SVG from a getBBox() taken in the hidden render
// element, which is unreliable on high-DPI/RDP displays and leaves
// diagrams too large or too small (#11782). Re-frame from the now-visible
// SVG, where getBBox() reflects the real content.
const rendered = element.querySelector("svg");
if (rendered instanceof SVGSVGElement) {
const box = rendered.getBBox();
if (box.width > 0 && box.height > 0) {
const padding = 8;
const frameWidth = box.width + padding * 2;
rendered.setAttribute(
"viewBox",
`${box.x - padding} ${box.y - padding} ${frameWidth} ${box.height + padding * 2}`
);
rendered.style.width = "100%";
rendered.style.maxWidth = `${frameWidth}px`;
}
}
// Cache the corrected SVG so we won't need to calculate it again this session
if (text) {
cache.set(cacheKey, element.innerHTML);
}
} catch (error) {
const isEmpty = block.node.textContent.trim().length === 0;
if (isEmpty) {
element.innerText = "Empty diagram";
element.classList.add("empty");
} else {
element.innerText = errToString(error);
element.classList.add("parse-error");
}
}
};
}
function overlap(
start1: number,
end1: number,
start2: number,
end2: number
): number {
return Math.max(0, Math.min(end1, end2) - Math.max(start1, start2));
}
/*
This code find the decoration that overlap the most with a given node.
This will ensure we can find the best decoration that match the last change set
See: https://github.com/outline/outline/pull/5852/files#r1334929120
*/
function findBestOverlapDecoration(
decorations: Decoration[],
block: NodeWithPos
): Decoration | undefined {
if (decorations.length === 0) {
return undefined;
}
return last(
sortBy(decorations, (decoration) =>
overlap(
decoration.from,
decoration.to,
block.pos,
block.pos + block.node.nodeSize
)
)
);
}
function getNewState({
doc,
pluginState,
autoEditEmpty = false,
}: {
doc: Node;
pluginState: MermaidState;
autoEditEmpty?: boolean;
}): MermaidState {
const decorations: Decoration[] = [];
const usedRenderers = new Set<MermaidRenderer>();
let newEditingId: string | undefined;
// Find all blocks that represent Mermaid diagrams (supports both "mermaid" and "mermaidjs"),
// descending into containers so diagrams inside toggle blocks are also discovered.
const blocks = findBlockNodes(doc, true).filter((item) =>
isMermaid(item.node)
);
blocks.forEach((block) => {
const existingDecorations = pluginState.decorationSet
.find(
block.pos,
block.pos + block.node.nodeSize,
(spec) => !!spec.diagramId
)
// A widget sitting exactly at the start of this block belongs to the
// preceding diagram, whose end position is shared with this one.
.filter((decoration) => {
if (
decoration.from === decoration.to &&
decoration.from === block.pos
) {
return false;
}
// Each renderer owns a single DOM element, so it can only back one
// diagram — reusing it would place the same node in two places.
return !usedRenderers.has(decoration.spec.renderer);
});
const bestDecoration = findBestOverlapDecoration(
existingDecorations,
block
);
const isNewBlock = !bestDecoration;
const renderer: MermaidRenderer =
bestDecoration?.spec?.renderer ?? new MermaidRenderer();
usedRenderers.add(renderer);
// Auto-enter edit mode for newly created empty mermaid diagrams
if (
autoEditEmpty &&
isNewBlock &&
block.node.textContent.trim().length === 0
) {
newEditingId = renderer.diagramId;
}
void renderer.render(block, pluginState.isDark);
const diagramDecoration = Decoration.widget(
block.pos + block.node.nodeSize,
() => renderer.element,
{
diagramId: renderer.diagramId,
renderer,
side: -10,
key: `mermaid-${renderer.diagramId}`,
}
);
const diagramIdDecoration = Decoration.node(
block.pos,
block.pos + block.node.nodeSize,
{},
{
diagramId: renderer.diagramId,
renderer,
}
);
decorations.push(diagramDecoration);
decorations.push(diagramIdDecoration);
});
return {
...pluginState,
...(newEditingId !== undefined ? { editingId: newEditingId } : {}),
decorationSet: DecorationSet.create(doc, decorations),
};
}
export default function Mermaid({
isDark,
editor,
}: {
isDark: boolean;
editor: Editor;
}) {
const { onClickLink, onNotice } = editor.props;
return new Plugin({
key: pluginKey,
state: {
init: (_, { doc }) => {
const pluginState: MermaidState = {
decorationSet: DecorationSet.create(doc, []),
isDark,
};
return getNewState({
doc,
pluginState,
});
},
apply: (
transaction: Transaction,
pluginState: MermaidState,
oldState,
state
) => {
const themeMeta = transaction.getMeta("theme");
const mermaidMeta = transaction.getMeta(pluginKey);
const themeToggled = themeMeta?.isDark !== undefined;
const nextPluginState = {
...pluginState,
isDark: themeToggled ? themeMeta.isDark : pluginState.isDark,
editingId:
mermaidMeta && "editingId" in mermaidMeta
? mermaidMeta.editingId
: pluginState.editingId,
decorationSet: mapDecorations(
pluginState.decorationSet,
transaction,
state
),
};
if (
transaction.selectionSet &&
nextPluginState.editingId &&
!mermaidMeta
) {
const codeBlock = findParentNode(isCode)(state.selection);
let isEditing = codeBlock && isMermaid(codeBlock.node);
if (isEditing && codeBlock && !transaction.docChanged) {
const decorations = nextPluginState.decorationSet.find(
codeBlock.pos,
codeBlock.pos + codeBlock.node.nodeSize
);
const nodeDecoration = decorations.find(
(d) => d.spec.diagramId && d.from === codeBlock.pos
);
if (nodeDecoration?.spec.diagramId !== nextPluginState.editingId) {
isEditing = false;
}
}
if (!isEditing) {
nextPluginState.editingId = undefined;
}
}
const node = state.selection.$head.parent;
const previousNode = oldState.selection.$head.parent;
const codeBlockChanged =
transaction.docChanged &&
(isMermaid(node) || isMermaid(previousNode));
// @ts-expect-error accessing private field.
const isPaste = transaction.meta?.paste;
if (
isPaste ||
mermaidMeta ||
themeToggled ||
codeBlockChanged ||
isRemoteTransaction(transaction, state)
) {
return getNewState({
doc: transaction.doc,
pluginState: nextPluginState,
autoEditEmpty:
codeBlockChanged &&
transaction.docChanged &&
!isPaste &&
!isRemoteTransaction(transaction, state),
});
}
return nextPluginState;
},
},
appendTransaction(_transactions, _oldState, newState) {
const { selection } = newState;
if (selection instanceof NodeSelection) {
return null;
}
const codeBlock = findParentNode(isCode)(selection);
if (!codeBlock || !isMermaid(codeBlock.node)) {
return null;
}
const mermaidState = pluginKey.getState(newState) as MermaidState;
const decorations = mermaidState?.decorationSet.find(
codeBlock.pos,
codeBlock.pos + codeBlock.node.nodeSize
);
const nodeDecoration = decorations?.find(
(d) => d.spec.diagramId && d.from === codeBlock.pos
);
if (
nodeDecoration?.spec.diagramId &&
mermaidState?.editingId === nodeDecoration.spec.diagramId
) {
return null;
}
return newState.tr.setSelection(
NodeSelection.create(newState.doc, codeBlock.pos)
);
},
view: (view) => {
view.dispatch(view.state.tr.setMeta(pluginKey, { loaded: true }));
return {};
},
props: {
decorations(state) {
return this.getState(state)?.decorationSet;
},
handleKeyDown(view, event) {
if (
event.key === "Enter" &&
isModKey(event) &&
!editor.props.readOnly
) {
const { selection } = view.state;
const isNodeSel = selection instanceof NodeSelection;
const isMermaidNode =
isNodeSel && isMermaid((selection as NodeSelection).node);
if (isNodeSel && isMermaidNode) {
editor.commands.edit_mermaid();
return true;
}
}
if (event.key === "Escape") {
const mermaidState = pluginKey.getState(view.state) as MermaidState;
const codeBlock = findParentNode(isCode)(view.state.selection);
if (mermaidState?.editingId) {
if (codeBlock && isMermaid(codeBlock.node)) {
editor.commands.edit_mermaid();
return true;
}
}
}
return false;
},
handleDOMEvents: {
click(_view, event: MouseEvent) {
const target = event.target as HTMLElement;
const anchor = target?.closest("a");
if (anchor instanceof SVGAElement) {
event.stopPropagation();
event.preventDefault();
return false;
}
return true;
},
mousedown(view, event) {
const target = event.target as HTMLElement;
const diagram = target?.closest(".mermaid-diagram-wrapper");
if (!diagram) {
return false;
}
// Let clicks on a link within the diagram through, they are handled
// on mouseup and should not select the node or open the lightbox.
if (target?.closest("a") instanceof SVGAElement) {
return false;
}
const codeBlock = diagram.previousElementSibling;
if (!codeBlock) {
return false;
}
const pos = view.posAtDOM(codeBlock, 0);
const $pos = view.state.doc.resolve(pos);
const nodePos = $pos.before();
const node = view.state.doc.nodeAt(nodePos);
const isSelected =
view.state.selection instanceof NodeSelection &&
view.state.selection.from === nodePos;
event.preventDefault();
if (isSelected || editor.props.readOnly) {
// Already selected or read-only, open lightbox unless the diagram
// failed to render (no valid image to show)
const hasError =
diagram.classList.contains("parse-error") ||
diagram.classList.contains("empty");
if (!hasError && node && node.textContent.trim().length > 0) {
editor.updateActiveLightboxImage(
LightboxImageFactory.createLightboxImage(view, nodePos)
);
}
} else {
// First click, select the node
view.dispatch(
view.state.tr
.setSelection(NodeSelection.create(view.state.doc, nodePos))
.scrollIntoView()
);
}
return true;
},
mouseup(view, event) {
const target = event.target as HTMLElement;
const diagram = target?.closest(".mermaid-diagram-wrapper");
if (!diagram) {
return false;
}
const anchor = target?.closest("a");
if (anchor instanceof SVGAElement) {
const href = anchor.getAttribute("xlink:href");
try {
if (onClickLink && href) {
event.stopPropagation();
event.preventDefault();
onClickLink(sanitizeUrl(href) ?? "");
}
} catch (_err) {
onNotice?.(
t("Sorry, that type of link is not supported"),
"error"
);
}
}
return false;
},
},
},
});
}