feat: render mermaid note diagrams

This commit is contained in:
lucaronin
2026-04-27 22:14:23 +02:00
parent a5c4b8fa20
commit 98fde6571a
18 changed files with 1752 additions and 28 deletions

View File

@@ -509,6 +509,15 @@ Defined in `src/utils/mathMarkdown.ts`, `src/components/editorSchema.tsx`, and s
- `serializeMathAwareBlocks()` converts math nodes back to Markdown delimiters before save, raw-mode entry, and editor-position snapshots.
- Raw CodeMirror mode always shows the plain Markdown source, so imported technical notes stay editable outside Tolaria.
### Mermaid Diagrams
Defined in `src/utils/mermaidMarkdown.ts`, `src/components/MermaidDiagram.tsx`, `src/components/editorSchema.tsx`, and styled in `src/components/EditorTheme.css`:
- Fenced `mermaid` blocks become `mermaidBlock` schema nodes before BlockNote sees the Markdown body.
- Each `mermaidBlock` stores the original fenced Markdown plus the diagram body, so raw-mode entry and saves can restore the canonical source instead of serializing generated SVG.
- The rich editor renders diagrams with the `mermaid` package and uses the original source as an inline fallback when rendering fails.
- `serializeMermaidAwareBlocks()` wraps the math-aware serializer so math, wikilinks, and diagrams share the same Markdown-first save path.
### Formatting Surface Policy
Defined in `src/components/tolariaEditorFormatting.tsx` and `src/components/tolariaEditorFormattingConfig.ts`:
@@ -527,24 +536,25 @@ Defined in `src/components/tolariaEditorFormatting.tsx` and `src/components/tola
```mermaid
flowchart LR
A["📄 Raw markdown\n(from disk)"] --> B["splitFrontmatter()\n→ yaml + body"]
B --> C["preProcessWikilinks(body)\n[[target]]token"]
C --> D["preProcessMathMarkdown(body)\n$...$ / $$...$$ → tokens"]
D --> E["tryParseMarkdownToBlocks()\n→ BlockNote block tree"]
E --> F["injectWikilinks + injectMathInBlocks\n tokens → schema nodes"]
F --> G["editor.replaceBlocks()\n→ rendered editor"]
B --> C["preProcessMermaidMarkdown(body)\nmermaid fence → token"]
C --> D["preProcessWikilinks(body)\n[[target]]token"]
D --> E["preProcessMathMarkdown(body)\n$...$ / $$...$$ → tokens"]
E --> F["tryParseMarkdownToBlocks()\n→ BlockNote block tree"]
F --> G["injectWikilinks + injectMathInBlocks + injectMermaidInBlocks\n tokens → schema nodes"]
G --> H["editor.replaceBlocks()\n→ rendered editor"]
style A fill:#f8f9fa,stroke:#6c757d,color:#000
style G fill:#d4edda,stroke:#28a745,color:#000
style H fill:#d4edda,stroke:#28a745,color:#000
```
> Wikilink placeholder tokens use `\u2039` and `\u203A`; math placeholder tokens use ASCII sentinels with URI-encoded LaTeX payloads.
> Wikilink placeholder tokens use `\u2039` and `\u203A`; math and Mermaid placeholder tokens use ASCII sentinels with URI-encoded payloads.
### BlockNote-to-Markdown Pipeline (Save)
```mermaid
flowchart LR
A["✏️ BlockNote blocks\n(editor state)"] --> B["blocksToMarkdownLossy()"]
B --> C["restoreWikilinks + serializeMathAwareBlocks()\nschema nodes → Markdown source"]
B --> C["restoreWikilinks + serializeMermaidAwareBlocks()\nschema nodes → Markdown source"]
C --> D["prepend frontmatter yaml"]
D --> E["invoke('save_note_content')\n→ disk write"]

View File

@@ -91,6 +91,7 @@ flowchart LR
| Frontend | React + TypeScript | React 19, TS 5.9 |
| Editor | BlockNote | 0.46.2 |
| Code block highlighting | @blocknote/code-block | 0.46.2 |
| Diagram rendering | Mermaid | 11.14.0 |
| Raw editor | CodeMirror 6 | - |
| Styling | Tailwind CSS v4 + CSS variables | 4.1.18 |
| UI primitives | Radix UI + shadcn/ui | - |
@@ -180,7 +181,7 @@ flowchart TD
- **Sidebar** (150-400px, resizable): Top-level filters (All Notes, Changes, Pulse), collapsible type-based section groups, and a dedicated folder tree. The folder tree shows user-created folders plus default vault folders such as `attachments/` and `views/`; only the dedicated `type/` directory stays hidden because note types already have their own sidebar section. The folder tree supports inline folder creation and rename, exposes a right-click menu for rename/delete plus filesystem reveal/copy-path actions, and auto-expands ancestor folders when the current selection or rename target is nested. Type sections and folder rows also act as note drop targets: dropping a note on a type updates its `type:` frontmatter, while dropping it on a folder runs the same crash-safe move path as the command palette flow. Each type can have a custom icon, color, sort, and visibility set via its type document in `type/`.
- **Note List / Pulse View** (200-500px, resizable): When a section group, filter, or saved view is selected, shows filtered notes with snippets, modified dates, status indicators, and per-context note-list controls. When `selection.kind === 'entity'`, the same pane enters **Neighborhood** mode: the source note is pinned at the top as a normal active row, outgoing relationship groups render first, inverse/backlink groups follow, empty groups stay visible with `0`, and duplicates across groups are allowed when multiple relationships are true. Plain click / `Enter` open the focused note without replacing the current Neighborhood, while Cmd/Ctrl-click and Cmd/Ctrl-`Enter` pivot the pane into the clicked note's Neighborhood. Folder-backed lists also show non-Markdown files: previewable image binaries get an image indicator and open in the editor pane, while unsupported binaries remain muted instead of auto-launching an external app. Saved views reuse the same sort and visible-column controls as the built-in lists, and those changes persist back into the view `.yml` definition (`sort`, `listPropertiesDisplay`). When Pulse filter is active, shows `PulseView` — a chronological git activity feed grouped by day.
- **Editor** (flex, fills remaining space): Single note open at a time (no tabs — see ADR-0003). Breadcrumb bar with word count and note-layout toggle, BlockNote rich text editor with wikilink support, Markdown-compatible inline/display math rendering, markdown-safe formatting controls, and schema-backed fenced code block highlighting via `@blocknote/code-block`. Can toggle to diff view (modified files), raw CodeMirror view, or a wide-screen left-aligned note column while preserving the same readable max width. Binary image files render through `FilePreview` as ordinary vault files using Tauri asset URLs, with explicit unsupported/broken fallback states and keyboard focus returning to the note list on `Escape`. Decomposed into `Editor` (orchestrator), `EditorContent`, `FilePreview`, `EditorRightPanel`, `SingleEditorView`, with hooks `useDiffMode`, `useEditorFocus`, and `useEditorSave`, plus the `useRawMode`/`RawEditorView` pair for markdown source editing. Rich BlockNote input and raw CodeMirror input both route typed `->`, `<-`, and `<->` through the shared `src/utils/arrowLigatures.ts` resolver so arrow ligatures stay consistent across mode switches while escaped ASCII sequences remain literal. Navigation history (Cmd+[/]) replaces tabs.
- **Editor** (flex, fills remaining space): Single note open at a time (no tabs — see ADR-0003). Breadcrumb bar with word count and note-layout toggle, BlockNote rich text editor with wikilink support, Markdown-compatible inline/display math rendering, first-class Mermaid diagram blocks, markdown-safe formatting controls, and schema-backed fenced code block highlighting via `@blocknote/code-block`. Can toggle to diff view (modified files), raw CodeMirror view, or a wide-screen left-aligned note column while preserving the same readable max width. Binary image files render through `FilePreview` as ordinary vault files using Tauri asset URLs, with explicit unsupported/broken fallback states and keyboard focus returning to the note list on `Escape`. Decomposed into `Editor` (orchestrator), `EditorContent`, `FilePreview`, `EditorRightPanel`, `SingleEditorView`, with hooks `useDiffMode`, `useEditorFocus`, and `useEditorSave`, plus the `useRawMode`/`RawEditorView` pair for markdown source editing. Rich BlockNote input and raw CodeMirror input both route typed `->`, `<-`, and `<->` through the shared `src/utils/arrowLigatures.ts` resolver so arrow ligatures stay consistent across mode switches while escaped ASCII sequences remain literal. Navigation history (Cmd+[/]) replaces tabs.
- **Inspector / AI Agent** (200-500px or 40px collapsed): Toggles between Inspector (frontmatter, relationships, instances, backlinks, git history) and AI Agent panel (the selected CLI agent with tool execution). The Sparkle icon in the breadcrumb bar toggles between them. Per-note `icon` is a suggested Inspector property and the command palette's "Set Note Icon" action opens that field directly. When viewing a Type note, the Inspector shows an **Instances** section listing all notes of that type (sorted by modified_at desc, capped at 50).
Panels are separated by `ResizeHandle` components that support drag-to-resize.

View File

@@ -0,0 +1,40 @@
---
type: ADR
id: "0088"
title: "Markdown-durable Mermaid diagrams in notes"
status: active
date: 2026-04-27
---
## Context
Tolaria notes are plain Markdown files, while the rich editor uses BlockNote and raw mode uses CodeMirror. Users need fenced `mermaid` blocks to render as diagrams in the note surface without changing the canonical file format or hiding the source from raw editing.
BlockNote can parse fenced code blocks, but a generic highlighted code block does not provide diagram rendering. Rendering Mermaid directly from the Markdown fence also has to preserve the original fence source when notes are saved, copied through raw mode, closed, and reopened.
## Decision
**Tolaria will support Mermaid diagrams through a Markdown placeholder round-trip owned by the editor pipeline and rendered with the `mermaid` package.**
The implementation:
- Converts fenced `mermaid` blocks to temporary placeholders before BlockNote parses Markdown.
- Replaces placeholders with a `mermaidBlock` schema block that stores both the original fenced source and the diagram body.
- Renders the block through Mermaid in the rich editor.
- Serializes `mermaidBlock` nodes back to their stored fenced Markdown before save, raw-mode entry, and editor-position snapshots.
- Shows the original source as an inline fallback when Mermaid cannot render a diagram.
## Options considered
- **Tolaria-owned placeholder round-trip with Mermaid rendering** (chosen): matches the existing wikilink and math architecture, keeps Markdown as the source of truth, and gives Tolaria explicit control over serialization.
- **Render all `mermaid` code blocks by overriding the generic code-block renderer**: smaller surface, but it couples diagram behavior to the code-highlighting package and makes exact source preservation harder.
- **Raw-mode-only Mermaid support**: preserves source but fails the enhanced note reading experience users expect.
- **Store parsed diagram metadata outside the Markdown body**: enables richer future editing, but violates the files-first model.
## Consequences
- `src/utils/mermaidMarkdown.ts` is the canonical parser/serializer bridge for note diagrams.
- Rich mode renders diagrams as schema-backed blocks; raw mode remains the direct source editor.
- Invalid Mermaid source remains visible instead of breaking the editor surface.
- `mermaid` is now a runtime dependency and should be upgraded deliberately with rendering regression coverage.
- Future diagram controls, such as copy source or expand, can attach to the same `mermaidBlock` without changing storage.

View File

@@ -140,3 +140,4 @@ proposed → active → superseded
| [0082](0082-markdown-durable-math-notes.md) | Markdown-durable math in notes | active |
| [0083](0083-dual-architecture-macos-release-artifacts.md) | Dual-architecture macOS release artifacts | active |
| [0085](0085-non-git-vault-support.md) | Non-git vaults open with explicit later Git initialization | active |
| [0088](0088-markdown-durable-mermaid-diagrams.md) | Markdown-durable Mermaid diagrams in notes | active |

View File

@@ -60,6 +60,7 @@
"date-fns": "^4.1.0",
"katex": "^0.16.28",
"lucide-react": "^0.564.0",
"mermaid": "^11.14.0",
"posthog-js": "^1.363.5",
"radix-ui": "^1.4.3",
"react": "^19.2.0",
@@ -75,12 +76,12 @@
"unicode-emoji-json": "^0.8.0"
},
"devDependencies": {
"@translated/lara-cli": "^1.3.2",
"@eslint/js": "^9.39.1",
"@playwright/test": "^1.58.2",
"@tauri-apps/cli": "^2.10.0",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@translated/lara-cli": "^1.3.2",
"@types/node": "^24.10.1",
"@types/react": "^19.2.7",
"@types/react-dom": "^19.2.3",

926
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -268,6 +268,59 @@
white-space: pre-wrap;
}
.editor__blocknote-container .mermaid-diagram {
width: 100%;
margin: 10px 0;
color: var(--colors-text);
}
.editor__blocknote-container .mermaid-diagram__viewport {
max-width: 100%;
overflow: auto;
padding: 14px;
border: 1px solid var(--border-primary);
border-radius: 8px;
background: var(--surface-editor);
}
.editor__blocknote-container .mermaid-diagram__viewport:focus-visible {
outline: 2px solid var(--border-focus);
outline-offset: 2px;
}
.editor__blocknote-container .mermaid-diagram__viewport svg {
display: block;
max-width: none;
min-width: min-content;
height: auto;
margin: 0 auto;
}
.editor__blocknote-container .mermaid-diagram--error {
padding: 12px;
border: 1px solid var(--destructive);
border-radius: 8px;
background: color-mix(in srgb, var(--destructive) 8%, transparent);
}
.editor__blocknote-container .mermaid-diagram--error figcaption {
margin-bottom: 8px;
color: var(--destructive);
font-size: 0.85rem;
font-weight: 600;
}
.editor__blocknote-container .mermaid-diagram--error pre {
max-width: 100%;
overflow: auto;
margin: 0;
padding: 10px;
border-radius: 6px;
background: var(--inline-styles-code-background-color);
color: var(--inline-styles-code-color);
font-size: 0.85rem;
}
.editor__blocknote-container[data-follow-links] .bn-editor a,
.editor__blocknote-container[data-follow-links] .wikilink {
cursor: pointer;

View File

@@ -0,0 +1,49 @@
import { render, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { MermaidDiagram } from './MermaidDiagram'
const mermaidMock = vi.hoisted(() => ({
initialize: vi.fn(),
render: vi.fn(),
}))
vi.mock('mermaid', () => ({
default: mermaidMock,
}))
describe('MermaidDiagram', () => {
beforeEach(() => {
vi.clearAllMocks()
mermaidMock.render.mockResolvedValue({
svg: '<svg aria-label="Rendered Mermaid"><g><text>A to B</text></g></svg>',
})
})
it('renders Mermaid SVG for valid source', async () => {
render(
<MermaidDiagram
diagram={'flowchart LR\nA --> B'}
source={'```mermaid\nflowchart LR\nA --> B\n```'}
/>,
)
await waitFor(() => {
expect(screen.getByTestId('mermaid-diagram-viewport').querySelector('svg')).not.toBeNull()
})
expect(mermaidMock.render).toHaveBeenCalledWith(expect.stringMatching(/^tolaria-mermaid-/), 'flowchart LR\nA --> B')
})
it('falls back to the original source when Mermaid cannot render', async () => {
mermaidMock.render.mockRejectedValueOnce(new Error('parse error'))
render(
<MermaidDiagram
diagram={'flowchart LR\nA --'}
source={'```mermaid\nflowchart LR\nA --\n```'}
/>,
)
expect(await screen.findByText('Mermaid diagram unavailable')).toBeInTheDocument()
expect(screen.getByLabelText('Mermaid source')).toHaveTextContent('flowchart LR')
})
})

View File

@@ -0,0 +1,105 @@
import { useEffect, useId, useMemo, useState } from 'react'
type MermaidApi = typeof import('mermaid')['default']
interface MermaidDiagramProps {
diagram: string
source: string
}
interface RenderState {
diagram: string
svg: string
error: boolean
}
let initialized = false
let renderQueue = Promise.resolve()
function renderIdFromReactId(reactId: string): string {
const safeId = reactId.replace(/[^a-zA-Z0-9_-]/g, '')
return `tolaria-mermaid-${safeId || 'diagram'}`
}
function initializeMermaid(mermaid: MermaidApi) {
if (initialized) return
mermaid.initialize({
startOnLoad: false,
securityLevel: 'strict',
theme: 'base',
themeVariables: {
background: '#ffffff',
primaryColor: '#f8fafc',
primaryTextColor: '#111827',
primaryBorderColor: '#94a3b8',
lineColor: '#64748b',
secondaryColor: '#f1f5f9',
tertiaryColor: '#e0f2fe',
fontFamily: 'ui-sans-serif, system-ui, sans-serif',
},
})
initialized = true
}
async function renderMermaidDiagram({
diagram,
renderId,
}: {
diagram: string
renderId: string
}): Promise<string> {
const render = async () => {
const mermaid = (await import('mermaid')).default
initializeMermaid(mermaid)
const result = await mermaid.render(renderId, diagram)
return result.svg
}
const nextRender = renderQueue.then(render, render)
renderQueue = nextRender.then(() => undefined, () => undefined)
return nextRender
}
export function MermaidDiagram({ diagram, source }: MermaidDiagramProps) {
const reactId = useId()
const renderId = useMemo(() => renderIdFromReactId(reactId), [reactId])
const [state, setState] = useState<RenderState>({ diagram: '', svg: '', error: false })
useEffect(() => {
let active = true
if (!diagram.trim()) return () => { active = false }
renderMermaidDiagram({ diagram, renderId })
.then((svg) => {
if (active) setState({ diagram, svg, error: false })
})
.catch(() => {
if (active) setState({ diagram, svg: '', error: true })
})
return () => { active = false }
}, [diagram, renderId])
const currentState = state.diagram === diagram ? state : { diagram, svg: '', error: false }
if (!diagram.trim() || currentState.error) {
return (
<figure className="mermaid-diagram mermaid-diagram--error" data-testid="mermaid-diagram-error">
<figcaption>Mermaid diagram unavailable</figcaption>
<pre aria-label="Mermaid source"><code>{source}</code></pre>
</figure>
)
}
return (
<figure className="mermaid-diagram" data-testid="mermaid-diagram">
<div
aria-label="Mermaid diagram"
className="mermaid-diagram__viewport"
data-testid="mermaid-diagram-viewport"
role="img"
tabIndex={0}
dangerouslySetInnerHTML={{ __html: currentState.svg }}
/>
</figure>
)
}

View File

@@ -1,6 +1,6 @@
import { compactMarkdown } from '../utils/compact-markdown'
import { restoreWikilinksInBlocks, splitFrontmatter } from '../utils/wikilinks'
import { serializeMathAwareBlocks } from '../utils/mathMarkdown'
import { serializeMermaidAwareBlocks } from '../utils/mermaidMarkdown'
import { findNearestTextCursorBlockById } from './blockNoteCursorTarget'
interface BlockLike {
@@ -129,11 +129,11 @@ function getLineIndexFromRatio({ totalLines, ratio }: { totalLines: number; rati
}
function serializeBlock(editor: BlockNotePositionEditor, block: BlockLike): string {
return compactMarkdown(serializeMathAwareBlocks(editor, restoreWikilinksInBlocks([block])))
return compactMarkdown(serializeMermaidAwareBlocks(editor, restoreWikilinksInBlocks([block])))
}
function serializeEditorBody(editor: BlockNotePositionEditor): string {
return compactMarkdown(serializeMathAwareBlocks(editor, restoreWikilinksInBlocks(editor.document)))
return compactMarkdown(serializeMermaidAwareBlocks(editor, restoreWikilinksInBlocks(editor.document)))
}
function buildBlockLineRanges({

View File

@@ -0,0 +1,31 @@
import { describe, expect, it, vi } from 'vitest'
import { MERMAID_BLOCK_TYPE } from '../utils/mermaidMarkdown'
import { serializeEditorDocumentToMarkdown } from './editorRawModeSync'
describe('editorRawModeSync Mermaid serialization', () => {
it('keeps the original fenced Mermaid source when rich content enters raw mode', () => {
const source = [
'~~~mermaid',
'flowchart LR',
' A["Draft"] --> B["Saved"]',
'~~~',
].join('\n')
const editor = {
document: [{
id: 'diagram-1',
type: MERMAID_BLOCK_TYPE,
props: {
source,
diagram: 'flowchart LR\n A["Draft"] --> B["Saved"]\n',
},
children: [],
}],
blocksToMarkdownLossy: vi.fn(),
}
expect(serializeEditorDocumentToMarkdown(
editor as never,
'---\ntitle: Flow\n---\n\n# Flow\n',
)).toBe(`---\ntitle: Flow\n---\n${source}\n`)
})
})

View File

@@ -2,7 +2,7 @@ import type { useCreateBlockNote } from '@blocknote/react'
import type { VaultEntry } from '../types'
import { splitFrontmatter, restoreWikilinksInBlocks } from '../utils/wikilinks'
import { compactMarkdown } from '../utils/compact-markdown'
import { serializeMathAwareBlocks } from '../utils/mathMarkdown'
import { serializeMermaidAwareBlocks } from '../utils/mermaidMarkdown'
import { portableImageUrls } from '../utils/vaultImages'
interface Tab {
@@ -30,7 +30,7 @@ export function serializeEditorDocumentToMarkdown(
): string {
const blocks = editor.document
const restored = restoreWikilinksInBlocks(blocks)
const rawBodyMarkdown = compactMarkdown(serializeMathAwareBlocks(editor, restored))
const rawBodyMarkdown = compactMarkdown(serializeMermaidAwareBlocks(editor, restored))
const bodyMarkdown = vaultPath ? portableImageUrls(rawBodyMarkdown, vaultPath) : rawBodyMarkdown
const [frontmatter] = splitFrontmatter(tabContent)
return `${frontmatter}${bodyMarkdown}`

View File

@@ -5,8 +5,10 @@ import { createReactBlockSpec, createReactInlineContentSpec } from '@blocknote/r
import { resolveWikilinkColor as resolveColor } from '../utils/wikilinkColors'
import { resolveEntry } from '../utils/wikilink'
import { MATH_BLOCK_TYPE, MATH_INLINE_TYPE, renderMathToHtml } from '../utils/mathMarkdown'
import { MERMAID_BLOCK_TYPE } from '../utils/mermaidMarkdown'
import type { VaultEntry } from '../types'
import { NoteTitleIcon } from './NoteTitleIcon'
import { MermaidDiagram } from './MermaidDiagram'
// Module-level cache so the WikiLink renderer (defined outside React) can access entries
export const _wikilinkEntriesRef: { current: VaultEntry[] } = { current: [] }
@@ -104,11 +106,31 @@ const MathBlock = createReactBlockSpec(
},
)
const MermaidBlock = createReactBlockSpec(
{
type: MERMAID_BLOCK_TYPE,
propSchema: {
source: { default: '' },
diagram: { default: '' },
},
content: 'none',
},
{
render: (props) => (
<MermaidDiagram
diagram={props.block.props.diagram}
source={props.block.props.source}
/>
),
},
)
const codeBlock = createCodeBlockSpec({
...codeBlockOptions,
defaultLanguage: 'text',
})
const mathBlock = MathBlock()
const mermaidBlock = MermaidBlock()
export const schema = BlockNoteSchema.create({
inlineContentSpecs: {
@@ -120,5 +142,6 @@ export const schema = BlockNoteSchema.create({
blockSpecs: {
codeBlock,
mathBlock,
mermaidBlock,
},
})

View File

@@ -3,7 +3,8 @@ import type { useCreateBlockNote } from '@blocknote/react'
import type { VaultEntry } from '../types'
import { splitFrontmatter, preProcessWikilinks, injectWikilinks, restoreWikilinksInBlocks } from '../utils/wikilinks'
import { compactMarkdown } from '../utils/compact-markdown'
import { injectMathInBlocks, preProcessMathMarkdown, serializeMathAwareBlocks } from '../utils/mathMarkdown'
import { injectMathInBlocks, preProcessMathMarkdown } from '../utils/mathMarkdown'
import { injectMermaidInBlocks, preProcessMermaidMarkdown, serializeMermaidAwareBlocks } from '../utils/mermaidMarkdown'
import { failNoteOpenTrace, finishNoteOpenTrace } from '../utils/noteOpenPerformance'
import { resolveImageUrls, portableImageUrls } from '../utils/vaultImages'
import {
@@ -134,6 +135,19 @@ async function parseMarkdownBlocks(
return result as EditorBlocks
}
function preProcessEditorMarkdown(markdown: string, vaultPath?: string): string {
const withMermaid = preProcessMermaidMarkdown({ markdown })
const withImages = vaultPath ? resolveImageUrls(withMermaid, vaultPath) : withMermaid
const withWikilinks = preProcessWikilinks(withImages)
return preProcessMathMarkdown({ markdown: withWikilinks })
}
function injectEditorMarkdownBlocks(blocks: EditorBlocks): EditorBlocks {
const withWikilinks = injectWikilinks(blocks)
const withMath = injectMathInBlocks(withWikilinks)
return injectMermaidInBlocks(withMath) as EditorBlocks
}
async function resolveBlocksForTarget(
options: {
editor: ReturnType<typeof useCreateBlockNote>
@@ -148,8 +162,7 @@ async function resolveBlocksForTarget(
if (cached?.sourceContent === content) return cached
const body = extractEditorBody(content)
const withImages = vaultPath ? resolveImageUrls(body, vaultPath) : body
const preprocessed = preProcessMathMarkdown({ markdown: preProcessWikilinks(withImages) })
const preprocessed = preProcessEditorMarkdown(body, vaultPath)
const fastPathBlocks = buildFastPathBlocks({ preprocessed })
if (fastPathBlocks) {
const nextState = { blocks: fastPathBlocks, scrollTop: 0, sourceContent: content }
@@ -158,9 +171,7 @@ async function resolveBlocksForTarget(
}
const parsed = normalizeParsedImageBlocks(await parseMarkdownBlocks(editor, preprocessed)) as EditorBlocks
const withWikilinks = injectWikilinks(parsed)
const withMath = injectMathInBlocks(withWikilinks)
const nextState = { blocks: withMath, scrollTop: 0, sourceContent: content }
const nextState = { blocks: injectEditorMarkdownBlocks(parsed), scrollTop: 0, sourceContent: content }
cacheEditorState(cache, targetPath, nextState)
return nextState
}
@@ -247,13 +258,10 @@ async function resolveEmptyHeadingHtml(
if (remainder === null) return null
if (!remainder.trim()) return '<h1></h1><p></p>'
const withImages = vaultPath ? resolveImageUrls(remainder, vaultPath) : remainder
const parsed = normalizeParsedImageBlocks(
await parseMarkdownBlocks(editor, preProcessMathMarkdown({ markdown: preProcessWikilinks(withImages) })),
await parseMarkdownBlocks(editor, preProcessEditorMarkdown(remainder, vaultPath)),
) as EditorBlocks
const withWikilinks = injectWikilinks(parsed)
const withMath = injectMathInBlocks(withWikilinks)
return `<h1></h1>${editor.blocksToHTMLLossy(withMath as typeof parsed)}`
return `<h1></h1>${editor.blocksToHTMLLossy(injectEditorMarkdownBlocks(parsed) as typeof parsed)}`
}
function findActiveTab(options: {
@@ -268,7 +276,7 @@ function findActiveTab(options: {
function serializeEditorBody(editor: ReturnType<typeof useCreateBlockNote>): string {
const restored = restoreWikilinksInBlocks(editor.document)
return compactMarkdown(serializeMathAwareBlocks(editor, restored))
return compactMarkdown(serializeMermaidAwareBlocks(editor, restored))
}
function normalizeTabBody(options: { content: string }): string {

View File

@@ -76,7 +76,8 @@ function processMarkdownLine(
}
function isFenceDelimiter({ line }: MarkdownLineValue): boolean {
return line.trimStart().startsWith('```')
const trimmed = line.trimStart()
return trimmed.startsWith('```') || trimmed.startsWith('~~~')
}
function normalizeMarkdownLine({ line }: MarkdownLineValue): string {

View File

@@ -0,0 +1,84 @@
import { describe, expect, it, vi } from 'vitest'
import {
MERMAID_BLOCK_TYPE,
injectMermaidInBlocks,
preProcessMermaidMarkdown,
serializeMermaidAwareBlocks,
} from './mermaidMarkdown'
describe('mermaid markdown round-trip', () => {
it('injects fenced Mermaid source into dedicated diagram blocks', () => {
const markdown = [
'```mermaid',
'flowchart LR',
' A --> B',
'```',
].join('\n')
const preprocessed = preProcessMermaidMarkdown({ markdown })
const blocks = [{
type: 'paragraph',
content: [{ type: 'text', text: preprocessed, styles: {} }],
children: [],
}]
const [block] = injectMermaidInBlocks(blocks) as Array<{
type: string
props: { source: string; diagram: string }
}>
expect(block.type).toBe(MERMAID_BLOCK_TYPE)
expect(block.props.source).toBe(markdown)
expect(block.props.diagram).toBe('flowchart LR\n A --> B\n')
})
it('preserves multiple Mermaid blocks independently when serializing', () => {
const editor = {
blocksToMarkdownLossy: vi.fn((blocks: unknown[]) => {
return (blocks as Array<{ content?: Array<{ text?: string }> }>)
.map((block) => block.content?.map((item) => item.text ?? '').join('') ?? '')
.join('\n\n')
}),
}
const firstSource = '```mermaid\nflowchart TD\nA --> B\n```'
const secondSource = '~~~mermaid\nsequenceDiagram\nAlice->>Bob: Hi\n~~~'
const blocks = [
{ type: 'paragraph', content: [{ type: 'text', text: 'Intro' }], children: [] },
{ type: MERMAID_BLOCK_TYPE, props: { source: firstSource, diagram: 'flowchart TD\nA --> B\n' }, children: [] },
{ type: 'paragraph', content: [{ type: 'text', text: 'Between' }], children: [] },
{ type: MERMAID_BLOCK_TYPE, props: { source: secondSource, diagram: 'sequenceDiagram\nAlice->>Bob: Hi\n' }, children: [] },
]
expect(serializeMermaidAwareBlocks(editor, blocks)).toBe([
'Intro',
firstSource,
'Between',
secondSource,
].join('\n\n'))
})
it('leaves non-Mermaid and unclosed fences as normal Markdown', () => {
const markdown = [
'```ts',
'const graph = "mermaid"',
'```',
'',
'```mermaid',
'flowchart LR',
].join('\n')
expect(preProcessMermaidMarkdown({ markdown })).toBe(markdown)
})
it('serializes fallback source for Mermaid blocks created without original fence text', () => {
const editor = { blocksToMarkdownLossy: vi.fn(() => '') }
const blocks = [{
type: MERMAID_BLOCK_TYPE,
props: { source: '', diagram: 'flowchart LR\nA --> B' },
children: [],
}]
expect(serializeMermaidAwareBlocks(editor, blocks)).toBe(
'```mermaid\nflowchart LR\nA --> B\n```',
)
})
})

View File

@@ -0,0 +1,241 @@
import { serializeMathAwareBlocks } from './mathMarkdown'
export const MERMAID_BLOCK_TYPE = 'mermaidBlock'
const TOKEN_PREFIX = '@@TOLARIA_MERMAID_BLOCK:'
const TOKEN_SUFFIX = '@@'
interface InlineItem {
type: string
text?: string
props?: Record<string, string>
content?: unknown
[key: string]: unknown
}
interface BlockLike {
type?: string
content?: InlineItem[]
props?: Record<string, string>
children?: BlockLike[]
[key: string]: unknown
}
interface MarkdownSerializer {
blocksToMarkdownLossy: (blocks: unknown[]) => string
}
interface MermaidPayload {
source: string
diagram: string
}
interface MermaidFenceStart {
character: '`' | '~'
length: number
}
interface MarkdownLine {
line: string
}
interface EncodedPayload {
encoded: string
}
interface TokenText {
text: string
}
interface FenceSearch {
lines: string[]
start: number
opening: MermaidFenceStart
}
interface FenceRange {
lines: string[]
start: number
end: number
}
interface DiagramSource {
diagram: string
}
function lineEnding({ line }: MarkdownLine): string {
if (line.endsWith('\r\n')) return '\r\n'
return line.endsWith('\n') ? '\n' : ''
}
function lineText({ line }: MarkdownLine): string {
const ending = lineEnding({ line })
return ending ? line.slice(0, -ending.length) : line
}
function splitMarkdownLines(markdown: string): string[] {
const lines = markdown.match(/[^\n]*(?:\n|$)/g) ?? []
return lines.filter((line, index) => line !== '' || index < lines.length - 1)
}
function encodePayload(payload: MermaidPayload): string {
return encodeURIComponent(JSON.stringify(payload))
}
function decodePayload({ encoded }: EncodedPayload): MermaidPayload | null {
try {
const payload = JSON.parse(decodeURIComponent(encoded)) as Partial<MermaidPayload>
if (typeof payload.source !== 'string') return null
if (typeof payload.diagram !== 'string') return null
return { source: payload.source, diagram: payload.diagram }
} catch {
return null
}
}
function mermaidToken(payload: MermaidPayload): string {
return `${TOKEN_PREFIX}${encodePayload(payload)}${TOKEN_SUFFIX}`
}
function readMermaidToken({ text }: TokenText): MermaidPayload | null {
const trimmed = text.trim()
if (!trimmed.startsWith(TOKEN_PREFIX) || !trimmed.endsWith(TOKEN_SUFFIX)) return null
return decodePayload({ encoded: trimmed.slice(TOKEN_PREFIX.length, -TOKEN_SUFFIX.length) })
}
function readMermaidFenceStart({ line }: MarkdownLine): MermaidFenceStart | null {
const match = /^( {0,3})(`{3,}|~{3,})[ \t]*(.*)$/.exec(line)
if (!match) return null
const fence = match[2]
const language = match[3].trim().split(/\s+/)[0]?.toLowerCase()
if (language !== 'mermaid') return null
return {
character: fence[0] as '`' | '~',
length: fence.length,
}
}
function isClosingFence({ line, opening }: MarkdownLine & { opening: MermaidFenceStart }): boolean {
const match = /^( {0,3})(`{3,}|~{3,})[ \t]*$/.exec(line)
if (!match) return false
const fence = match[2]
return fence[0] === opening.character && fence.length >= opening.length
}
function findClosingFence({ lines, start, opening }: FenceSearch): number {
for (let index = start + 1; index < lines.length; index++) {
if (isClosingFence({ line: lineText({ line: lines[index] }), opening })) return index
}
return -1
}
function buildPayload({ lines, start, end }: FenceRange): MermaidPayload {
return {
source: lines.slice(start, end + 1).join(''),
diagram: lines.slice(start + 1, end).join(''),
}
}
export function preProcessMermaidMarkdown({ markdown }: { markdown: string }): string {
const lines = splitMarkdownLines(markdown)
const result: string[] = []
for (let index = 0; index < lines.length; index++) {
const opening = readMermaidFenceStart({ line: lineText({ line: lines[index] }) })
if (!opening) {
result.push(lines[index])
continue
}
const closingIndex = findClosingFence({ lines, start: index, opening })
if (closingIndex === -1) {
result.push(lines[index])
continue
}
const payload = buildPayload({ lines, start: index, end: closingIndex })
result.push(`${mermaidToken(payload)}${lineEnding({ line: lines[closingIndex] })}`)
index = closingIndex
}
return result.join('')
}
function readMermaidPayload(content: InlineItem[] | undefined): MermaidPayload | null {
const onlyItem = content?.length === 1 ? content[0] : null
if (onlyItem?.type !== 'text' || typeof onlyItem.text !== 'string') return null
return readMermaidToken({ text: onlyItem.text })
}
function buildMermaidBlock({ block, payload }: { block: BlockLike; payload: MermaidPayload }): BlockLike {
return {
...block,
type: MERMAID_BLOCK_TYPE,
props: {
...(block.props ?? {}),
source: payload.source,
diagram: payload.diagram,
},
content: undefined,
children: [],
}
}
function injectMermaidInBlock(block: BlockLike): BlockLike {
const payload = readMermaidPayload(block.content)
if (payload) return buildMermaidBlock({ block, payload })
const children = Array.isArray(block.children) ? block.children.map(injectMermaidInBlock) : block.children
return { ...block, children }
}
function isMermaidBlock(block: BlockLike): boolean {
return block.type === MERMAID_BLOCK_TYPE
&& typeof block.props?.source === 'string'
&& typeof block.props?.diagram === 'string'
}
function fallbackMermaidSource({ diagram }: DiagramSource): string {
const body = diagram.endsWith('\n') ? diagram : `${diagram}\n`
return `\`\`\`mermaid\n${body}\`\`\``
}
function mermaidMarkdown(block: BlockLike): string {
const source = block.props?.source
if (source) return source
return fallbackMermaidSource({ diagram: block.props?.diagram ?? '' })
}
export function injectMermaidInBlocks(blocks: unknown[]): unknown[] {
return (blocks as BlockLike[]).map(injectMermaidInBlock)
}
export function serializeMermaidAwareBlocks(editor: MarkdownSerializer, blocks: unknown[]): string {
const chunks: string[] = []
let pending: unknown[] = []
const flushPending = () => {
if (pending.length === 0) return
const markdown = serializeMathAwareBlocks(editor, pending).trimEnd()
if (markdown) chunks.push(markdown)
pending = []
}
for (const block of blocks as BlockLike[]) {
if (isMermaidBlock(block)) {
flushPending()
chunks.push(mermaidMarkdown(block))
} else {
pending.push(block)
}
}
flushPending()
return chunks.join('\n\n')
}

View File

@@ -0,0 +1,150 @@
import { expect, test, type Page } from '@playwright/test'
import fs from 'fs'
import path from 'path'
import { createFixtureVaultCopy, openFixtureVault, removeFixtureVaultCopy } from '../helpers/fixtureVault'
import { executeCommand, openCommandPalette } from './helpers'
let tempVaultDir: string
const FIRST_DIAGRAM = [
'```mermaid',
'flowchart LR',
' A[Draft] --> B[Saved]',
'```',
].join('\n')
const UPDATED_FIRST_DIAGRAM = FIRST_DIAGRAM.replace('B[Saved]', 'C[Published]')
const SECOND_DIAGRAM = [
'```mermaid',
'sequenceDiagram',
' Alice->>Bob: Hello',
'```',
].join('\n')
const INVALID_DIAGRAM = [
'```mermaid',
'not a diagram',
'```',
].join('\n')
test.beforeEach(async ({ page }, testInfo) => {
testInfo.setTimeout(90_000)
tempVaultDir = createFixtureVaultCopy()
await openFixtureVault(page, tempVaultDir)
})
test.afterEach(async () => {
removeFixtureVaultCopy(tempVaultDir)
})
async function openNote(page: Page, title: string): Promise<void> {
await page.locator('[data-testid="note-list-container"]').getByText(title, { exact: true }).click()
await expect(page.locator('.bn-editor')).toBeVisible({ timeout: 5_000 })
}
async function toggleRawMode(page: Page, visibleSelector: '.bn-editor' | '.cm-content'): Promise<void> {
await openCommandPalette(page)
await executeCommand(page, 'Toggle Raw')
await expect(page.locator(visibleSelector)).toBeVisible({ timeout: 5_000 })
}
async function getRawEditorContent(page: Page): Promise<string> {
return page.evaluate(() => {
type CodeMirrorHost = Element & {
cmTile?: {
view?: {
state: {
doc: {
toString(): string
}
}
}
}
}
const host = document.querySelector('.cm-content') as CodeMirrorHost | null
return host?.cmTile?.view?.state.doc.toString() ?? host?.textContent ?? ''
})
}
async function setRawEditorContent(page: Page, content: string): Promise<void> {
await page.evaluate((nextContent) => {
type CodeMirrorHost = Element & {
cmTile?: {
view?: {
state: {
doc: {
length: number
}
}
dispatch(update: {
changes: {
from: number
to: number
insert: string
}
}): void
}
}
}
const host = document.querySelector('.cm-content') as CodeMirrorHost | null
const view = host?.cmTile?.view
if (!view) return
view.dispatch({
changes: { from: 0, to: view.state.doc.length, insert: nextContent },
})
}, content)
}
async function expectRenderedDiagramCount(page: Page, count: number): Promise<void> {
await expect(page.locator('[data-testid="mermaid-diagram-viewport"] svg')).toHaveCount(count, { timeout: 15_000 })
}
function readNoteBFile(): string {
return fs.readFileSync(path.join(tempVaultDir, 'note', 'note-b.md'), 'utf8')
}
test('Mermaid diagrams render, fall back, and round-trip through raw mode', async ({ page }) => {
await openNote(page, 'Note B')
await toggleRawMode(page, '.cm-content')
const originalContent = await getRawEditorContent(page)
const nextContent = `${originalContent.trimEnd()}
${FIRST_DIAGRAM}
${INVALID_DIAGRAM}
${SECOND_DIAGRAM}
`
await setRawEditorContent(page, nextContent)
await expect.poll(readNoteBFile).toContain(FIRST_DIAGRAM)
await toggleRawMode(page, '.bn-editor')
await expectRenderedDiagramCount(page, 2)
await expect(page.locator('[data-testid="mermaid-diagram-error"]')).toHaveCount(1)
await expect(page.locator('[data-testid="mermaid-diagram-error"]')).toContainText('not a diagram')
await toggleRawMode(page, '.cm-content')
const rawAfterRichMode = await getRawEditorContent(page)
expect(rawAfterRichMode).toContain(FIRST_DIAGRAM)
expect(rawAfterRichMode).toContain(INVALID_DIAGRAM)
expect(rawAfterRichMode).toContain(SECOND_DIAGRAM)
await setRawEditorContent(page, rawAfterRichMode.replace(FIRST_DIAGRAM, UPDATED_FIRST_DIAGRAM))
await expect.poll(readNoteBFile).toContain(UPDATED_FIRST_DIAGRAM)
await toggleRawMode(page, '.bn-editor')
await expectRenderedDiagramCount(page, 2)
await expect(page.locator('[data-testid="mermaid-diagram-viewport"]').first()).toContainText('Published')
await openNote(page, 'Note C')
await openNote(page, 'Note B')
await toggleRawMode(page, '.cm-content')
const reopenedRaw = await getRawEditorContent(page)
expect(reopenedRaw).toContain(UPDATED_FIRST_DIAGRAM)
expect(reopenedRaw).toContain(INVALID_DIAGRAM)
expect(reopenedRaw).toContain(SECOND_DIAGRAM)
})