chore(web): draw Mermaid diagrams with Pele

Replace mermaid with pele for ```mermaid code blocks. Diagram types load
on first use through pele/lazy, the SVG takes its colors from --pele-*
variables mapped to the theme tokens in index.css, so a color scheme
change needs no redraw, and the layout shrinks to the memo's width while
keeping the author's direction.

Bump @usememos/editor to 26.10.22.
This commit is contained in:
johnnyjoygh
2026-10-19 00:35:57 +08:00
parent 0b53427b82
commit bf67323d1d
6 changed files with 54 additions and 948 deletions
+2 -2
View File
@@ -25,7 +25,7 @@
"@tailwindcss/vite": "^4.2.4",
"@tanstack/react-query": "^5.100.9",
"@tanstack/react-query-devtools": "^5.100.9",
"@usememos/editor": "26.10.21",
"@usememos/editor": "26.10.22",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"copy-to-clipboard": "^4.0.2",
@@ -42,9 +42,9 @@
"maplibre-gl": "^6.8.0",
"mdast-util-from-markdown": "^2.0.3",
"mdast-util-gfm": "^3.1.0",
"mermaid": "^11.14.0",
"micromark-extension-gfm": "^3.0.0",
"micromark-util-normalize-identifier": "^2.0.1",
"pele": "1.6.0",
"react": "^19.2.6",
"react-dom": "^19.2.6",
"react-hot-toast": "^2.6.0",
+14 -910
View File
File diff suppressed because it is too large Load Diff
+1 -19
View File
@@ -1,7 +1,7 @@
import type { Editor, EditorMode, Extension } from "@usememos/editor";
import { MarkdownEditor, type MarkdownEditorProps } from "@usememos/editor/react";
import "@usememos/editor/style.css";
import { type Ref, useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
import { type Ref, useCallback, useMemo, useState } from "react";
import { MEMO_EDITOR_THEME, MEMO_MARKDOWN, memoEditorLabels, memoExtensions, memoResolveUrl } from "@/lib/memo-markdown";
import type { Attachment } from "@/types/proto/api/attachment_service_pb";
import { useTranslate } from "@/utils/i18n";
@@ -41,16 +41,6 @@ export interface MemoMarkdownProps {
className?: string;
}
// A memo with a Mermaid diagram draws it in the page's color scheme; a new scheme draws
// the diagrams again.
const MERMAID_FENCE = /^ {0,3}(?:`{3,}|~{3,})[ \t]*mermaid\b/im;
const subscribeColorScheme = (onChange: () => void) => {
const observer = new MutationObserver(onChange);
observer.observe(document.documentElement, { attributes: true, attributeFilter: ["style"] });
return () => observer.disconnect();
};
const getColorScheme = () => document.documentElement.style.colorScheme;
const assignRef = <T,>(ref: Ref<T> | undefined, value: T) => {
if (typeof ref === "function") ref(value);
else if (ref) ref.current = value;
@@ -102,14 +92,6 @@ export const MemoMarkdown = (props: MemoMarkdownProps) => {
);
const labels = useMemo(() => memoEditorLabels(t), [t]);
const resolveUrl = useMemo(() => memoResolveUrl(attachments), [attachments]);
const colorScheme = useSyncExternalStore(subscribeColorScheme, getColorScheme, () => "");
const drawnScheme = useRef(colorScheme);
useEffect(() => {
if (drawnScheme.current === colorScheme) return;
drawnScheme.current = colorScheme;
if (MERMAID_FENCE.test(value)) editor?.refreshViews("code:mermaid");
}, [colorScheme, editor, value]);
return (
<MarkdownEditor
ref={attach}
+1 -1
View File
@@ -23,7 +23,7 @@ MemoEditor memo level: name | draft seed, mode, data, draft stor
└── Editor MemoMarkdown editable, with the composer's extensions, behind EditorController
```
- **`MemoMarkdown.tsx`** binds the editor to memos once: the memo Markdown dialect, the theme in the app's CSS variables, translated labels, the image and link URL policy, the memo syntax extensions (math, footnotes, tags, mentions, highlighted code, Mermaid, sanitized HTML) and the stylesheet. `useMemoDecorations` is the one flow for tag colors and resolved mentions, with one redecorate effect. Everything a surface adds sits around this component; nothing in memos styles the editor's own classes.
- **`MemoMarkdown.tsx`** binds the editor to memos once: the memo Markdown dialect, the theme in the app's CSS variables, translated labels, the image and link URL policy, the memo syntax extensions (math, footnotes, tags, mentions, highlighted code, Mermaid diagrams drawn by Pele, sanitized HTML) and the stylesheet. `useMemoDecorations` is the one flow for tag colors and resolved mentions, with one redecorate effect. Everything a surface adds sits around this component; nothing in memos styles the editor's own classes.
- **`view/`** is the read-only surface over `MemoMarkdown`: tags and mentions navigate, in-memo anchors scroll, a paragraph that is one bare link becomes a preview card through the editor's block view (`linkCards.ts`), the page's search matches are painted, and heading ids match the outline. Tag and mention clicks arrive through the editor's `onClick` callbacks, so nothing in memos matches the editor's class names or mutates its DOM. Previews that have Markdown but no memo query (the link-memo search, the share image) use `MemoContentView` directly.
- **`edit/`** is the editing surface: `EditSession` renders the chrome (timestamp, attachments, suggestions, toolbar, focus mode, audio recording) over the draft store `MemoEditor` provides, persists the draft while open, and saves through the memo mutations. `Editor.tsx` is the composer's editor: `MemoMarkdown` editable with the composer's own extensions (`#tag` and `:emoji` autocomplete, file paste and drop), behind the `EditorController` contract in `controller.ts`.
+14
View File
@@ -39,6 +39,20 @@
}
@layer components {
/* Mermaid diagrams drawn by Pele take the theme's colors; a new scheme recolors them live. */
.pele {
--pele-bg: var(--card);
--pele-fg: var(--foreground);
--pele-muted: var(--muted-foreground);
--pele-line: var(--foreground);
--pele-surface: var(--muted);
--pele-surface-alt: var(--accent);
--pele-border: var(--border);
--pele-accent: var(--primary);
--pele-critical: var(--destructive);
--pele-radius: calc(var(--radius) - 2px);
}
@media (prefers-reduced-motion: no-preference) {
.memos-logo .memos-mark {
transition: transform 180ms ease-out;
+22 -16
View File
@@ -117,26 +117,32 @@ const codeHighlight = (): Extension => ({
},
});
/** Mermaid diagrams for ```mermaid code blocks. The code shows until the diagram is drawn, and stays if it fails. */
const renderMermaid: SyntaxView = (source, element) => {
/**
* Mermaid diagrams for ```mermaid code blocks, drawn by Pele: the diagram types load on
* first use, the SVG takes its colors from the `.pele` variables in index.css, so a new
* color scheme needs no redraw, and the layout adapts to the memo's width. The code
* shows until the diagram is drawn, and stays if it fails.
*/
const renderDiagram: SyntaxView = (source, element) => {
const pre = document.createElement("pre");
pre.textContent = source;
element.appendChild(pre);
return (async () => {
const { default: mermaid } = await import("mermaid");
const { PeleError, renderAsync } = await import("pele/lazy");
await document.fonts?.ready;
mermaid.initialize({
startOnLoad: false,
theme: document.documentElement.style.colorScheme === "dark" ? "dark" : "default",
securityLevel: "strict",
fontFamily: getComputedStyle(document.body).fontFamily || "sans-serif",
suppressErrorRendering: true,
});
const style = getComputedStyle(element);
try {
const { svg } = await mermaid.render(`mermaid-${Math.random().toString(36).slice(2)}`, source);
element.classList.add("mermaid-diagram");
const { svg } = await renderAsync(source, {
fontFamily: style.fontFamily || "sans-serif",
fontFamilyMono: style.getPropertyValue("--font-mono").trim() || "monospace",
maxWidth: element.clientWidth || undefined,
// A memo column is narrow; the diagram shrinks to fit, but keeps the direction its author wrote.
autoDirection: false,
idPrefix: `diagram-${Math.random().toString(36).slice(2)}`,
});
element.innerHTML = svg;
} catch {
} catch (error) {
if (!(error instanceof PeleError)) throw error;
return false;
}
})();
@@ -212,8 +218,8 @@ interface MemoExtensionOptions {
/**
* The extensions every memo surface reads with, the composer and the memo view
* alike: math (KaTeX, loaded on demand), footnotes, #tags and @mentions,
* highlighted code, Mermaid diagrams and sanitized raw HTML. Everything the
* editor renders shows its source at the caret while editing.
* highlighted code, Mermaid diagrams (drawn by Pele) and sanitized raw HTML.
* Everything the editor renders shows its source at the caret while editing.
*/
export const memoExtensions = (options: MemoExtensionOptions = {}): Extension[] => [
math({ render: renderMath }),
@@ -221,7 +227,7 @@ export const memoExtensions = (options: MemoExtensionOptions = {}): Extension[]
tags(options.tags),
mentions(options.mentions),
codeHighlight(),
{ name: "memoViews", views: { "code:mermaid": renderMermaid, html: renderHtml } },
{ name: "memoViews", views: { "code:mermaid": renderDiagram, html: renderHtml } },
];
/** Images load from relative URLs and https only, as memos' sanitizer allowed; anything else is dropped. */