WIP: Render Mermaid diagrams with Pele #252

Draft
eleith-gitea-agent Bot wants to merge 6 commits from feat/mermaid-diagrams into main
pull from: feat/mermaid-diagrams
20 changed files with 572 additions and 43 deletions

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
---
'@luzzle/web': patch
'@luzzle/web.worker': patch
---
Render Mermaid fences in piece Markdown as inline diagrams on public Pages and admin Page previews, without loading a diagram renderer in the browser. If Pele cannot render a fence, show its source and log a warning.
@@ -0,0 +1,29 @@
---
title: From Notebook to Garden
summary: Two diagrams show how to revise a draft and take a notebook idea to a public page.
date_published: 2026-11-30
keywords: writing, diagrams, mermaid
---
## Revise a note
```mermaid
flowchart TD
accTitle: A short revision pass
accDescr: Write a draft, read it aloud, and revise it.
A[Draft] --> B[Read aloud] --> C[Revise]
```
## Publish a note
```mermaid
flowchart LR
accTitle: From notebook to public page
accDescr: Collect notebook ideas, choose one useful thread, arrange the paragraphs, write a draft, read it aloud, review the saved preview, then publish to the garden.
A[Collect notebook ideas] --> B[Select one useful thread]
B --> C[Arrange the paragraphs]
C --> D[Write a first draft]
D --> E[Read the draft aloud]
E --> F[Review the saved preview]
F --> G[Publish to the garden]
```
+37
View File
@@ -0,0 +1,37 @@
@import '@luzzle/web.theme/styles/markdown.css';
/* Browser-only: Share PNGs use the shared stylesheet and cannot scroll. */
.markdown figure[data-luzzle-mermaid] {
margin-block: var(--space-4);
--pele-bg: var(--color-surface);
--pele-fg: var(--color-on-surface);
--pele-muted: var(--color-on-surface-variant);
--pele-line: var(--color-on-surface-variant);
--pele-surface: var(--color-surface-container-low);
--pele-surface-alt: var(--color-surface-container);
--pele-border: var(--color-outline);
--pele-accent: var(--color-primary);
--pele-critical: var(--color-error);
@media screen {
> div {
overflow-x: auto;
/* Keep the SVG's width out of an authored grid or flex track's minimum size. */
contain: inline-size;
&:focus-visible {
outline: 2px solid var(--color-primary);
outline-offset: 2px;
}
> svg {
display: block;
/* After modest scaling, scroll instead of shrinking labels further. */
width: clamp(calc(var(--mermaid-natural-width) * 0.85), 100%, var(--mermaid-natural-width));
max-width: none;
height: auto;
}
}
}
}
@@ -1,7 +1,7 @@
<script lang="ts">
import '@luzzle/web.theme/styles/reset.css'
import '@luzzle/web.theme/styles/base.css'
import '@luzzle/web.theme/styles/markdown.css'
import '#lib/templates/markdown.css'
import type { LayoutProps } from './$types'
@@ -1,7 +1,7 @@
<script lang="ts">
import '@luzzle/web.theme/styles/reset.css'
import '@luzzle/web.theme/styles/base.css'
import '@luzzle/web.theme/styles/markdown.css'
import '#lib/templates/markdown.css'
import type { LayoutProps } from './$types'
@@ -1,7 +1,7 @@
<script lang="ts">
import '@luzzle/web.theme/styles/reset.css'
import '@luzzle/web.theme/styles/base.css'
import '@luzzle/web.theme/styles/markdown.css'
import '#lib/templates/markdown.css'
import type { LayoutProps } from './$types'
import ViewerHeader from '#lib/pieces/viewer/ViewerHeader.svelte'
+1 -1
View File
@@ -1,7 +1,7 @@
<script lang="ts">
import '@luzzle/web.theme/styles/reset.css'
import '@luzzle/web.theme/styles/base.css'
import '@luzzle/web.theme/styles/markdown.css'
import '#lib/templates/markdown.css'
import { page } from '$app/state'
import { isPiecesPath } from '#lib/pieces/navigation.js'
import EditSourceShortcut from '#lib/components/layout/simple/EditSourceShortcut.svelte'
+1
View File
@@ -80,6 +80,7 @@
"micromark-util-types": "2.0.2",
"mime-types": "3.0.2",
"openworkflow": "0.11.0",
"pele": "1.13.0",
"rehype-autolink-headings": "7.1.0",
"rehype-katex": "7.0.1",
"rehype-pretty-code": "0.14.1",
@@ -8,6 +8,7 @@ import type { TemplateConfig } from '@luzzle/web.templates/config'
import type { PublicWebPiece, PublicWebPieceAsset } from '@luzzle/web.pieces'
import { loadOpengraphFonts } from './opengraph-fonts.js'
import { renderOpengraphPng } from './render-opengraph-png.js'
import { processMarkdown } from '../transforms/markdown/engine.js'
import { ImageResponse } from 'takumi-js/response'
import type * as TakumiResponse from 'takumi-js/response'
@@ -172,6 +173,49 @@ describe('pieces/render-opengraph-png', () => {
expect((await coverPixel(published)).toString('hex')).toBe('22bb66')
})
test('renders an authored Share PNG with Mermaid in body and field Markdown', async () => {
const config = makeConfig()
const file = path.join(TEMP_DIR, 'markdown-card.svelte')
writeFileSync(file, `<script>let { piece, helpers } = $props();</script>
{@html piece.assets.find((asset) => asset.transformation === 'markdown').content}
{@html helpers.getPieceAssetContent(piece.key, 'markdown.caption')}`)
config.pieces.books.templates!.opengraph = { file }
const flowchart = [
'```mermaid',
'flowchart LR',
'A[Collect notebook ideas] --> B[Select one useful thread]',
'B --> C[Arrange the paragraphs]',
'C --> D[Write a first draft]',
'D --> E[Read the draft aloud]',
'E --> F[Review the saved preview]',
'F --> G[Publish to the garden]',
'```',
].join('\n')
const sankey = '```mermaid\nsankey-beta\nDraft,Preview,5\nPreview,Published,3\n```'
const themes = config.theme.markdown.code
const body = await processMarkdown(`Body before.\n\n${flowchart}\n\nBody after.`, themes, {
fragment: { pieceKey: 'k1' },
})
const field = await processMarkdown(`${sankey}\n\nCaption after.`, themes, {
fragment: { pieceKey: 'k1', fieldPath: 'caption' },
})
const assets: PublicWebPieceAsset[] = [
{ asset_key: 'k1', transformation: 'markdown', mime_type: 'text/html', content: body },
{ asset_key: 'k1', transformation: 'markdown.caption', mime_type: 'text/html', content: field },
]
const piece = makePiece(assets)
expectPng(await renderOpengraphPng(piece, assets, config))
const [html] = vi.mocked(ImageResponse).mock.calls.at(-1)!
expect(html).toContain('class="pele pele-flowchart"')
expect(html).toContain('class="pele pele-sankey"')
expect(html).toContain('<linearGradient')
const svg = /<svg\b[\s\S]*?<\/svg>/g
expect(html.match(svg)).toEqual([...(body.match(svg) ?? []), ...(field.match(svg) ?? [])])
expect(html).toContain('Body after.')
expect(html).toContain('Caption after.')
})
test('renders the packaged default component to a PNG without a piece configuration', async () => {
const config = makeConfig()
config.pieces = {}
@@ -143,6 +143,55 @@ test('marks styled math and warns about invalid formulas in the note and nested
expect(input.webPiece.json_metadata).toBe(jsonMetadata)
})
test('renders Mermaid in the body and indexed Markdown fields with distinct, stable IDs', async () => {
const input = makeInput({
pieces: {
getPiece: vi.fn().mockResolvedValue({
fields: [
{
name: 'sections',
type: 'array',
items: { type: 'object', properties: { caption: { type: 'string', format: 'markdown' } } },
},
],
}),
} as unknown as Pieces,
})
const diagram = '```mermaid\nflowchart LR\naccTitle: A route\nA --> B\n```'
const broken = '```mermaid\nflowchart LR\nA --> [\n```'
input.webPiece.note = diagram
input.webPiece.json_metadata = JSON.stringify({
sections: [{ caption: diagram }, { caption: `${diagram}\n\n${broken}` }],
})
const records = await run(input)
const titleRefs = records.map(({ content }) => content?.match(/aria-labelledby="([^"]+)"/)?.[1])
expect(records.map(({ transformation }) => transformation)).toEqual([
'markdown',
'markdown.sections.0.caption',
'markdown.sections.1.caption',
])
expect(titleRefs).toEqual(
Array.from({ length: 3 }, () => expect.stringMatching(/^luzzle-mermaid-[a-f0-9]+-1-title$/))
)
expect(new Set(titleRefs).size).toBe(3)
expect(records[2].content).toContain('Diagram unavailable')
expect(input.logger.warn).toHaveBeenCalledExactlyOnceWith('Could not render Markdown Mermaid', {
file: 'essay.words.md',
part: 'field',
field: 'sections.1.caption',
reason: 'syntax',
markdownLine: 7,
markdownColumn: 1,
})
expect(await run(input)).toEqual(records)
const [otherBody] = await run({ ...input, webPiece: { ...input.webPiece, key: 'other-piece' } })
const otherTitleRef = otherBody.content?.match(/aria-labelledby="([^"]+)"/)?.[1]
expect(otherTitleRef).toMatch(/^luzzle-mermaid-[a-f0-9]+-1-title$/)
expect(otherTitleRef).not.toBe(titleRefs[0])
})
test('warns and preserves destinations without a registered, generated original', async () => {
const input = makeInput({
assetKeyToPath: new Map([['variant', '.assets/variant-only.png']]),
@@ -0,0 +1,13 @@
export type MarkdownFragment = {
pieceKey: string
fieldPath?: string
}
export type MarkdownWarning = {
feature: string
reason: string
line?: number
column?: number
}
export type ReportMarkdownWarning = (warning: MarkdownWarning) => void
@@ -10,8 +10,12 @@ const themes = validateConfig({}).theme.markdown.code
const mathWrapper = '<section class="markdown" data-luzzle-math>'
function renderMarkdown(markdown: string) {
return processMarkdown(markdown, themes, { fragment: { pieceKey: 'test' } })
}
test('keeps the existing wrapper and HTML for ordinary Markdown', async () => {
const html = await processMarkdown('Plain text\n\n<!-- comment -->\n\n<em>Raw HTML</em>', themes)
const html = await renderMarkdown('Plain text\n\n<!-- comment -->\n\n<em>Raw HTML</em>')
expect(html).toBe(
'<section class="markdown"><p>Plain text</p>\n<!-- comment -->\n<p><em>Raw HTML</em></p></section>'
)
@@ -24,7 +28,7 @@ test.each([
['a nested math code fence', '> ~~~math\n> x^2\n> ~~~', true],
['a math fence with an encoded separator', '```math&nbsp;\nx^2\n```', true],
] as const)('typesets %s with both visual HTML and MathML', async (_name, markdown, display) => {
const html = await processMarkdown(markdown, themes)
const html = await renderMarkdown(markdown)
expect(html).toContain(mathWrapper)
expect(html).not.toContain('data-luzzle-math-placeholder')
expect(html).toContain('class="katex-html"')
@@ -35,15 +39,14 @@ test.each([
})
test('keeps escaped currency and code literal and still highlights non-math fences', async () => {
const html = await processMarkdown(
const html = await renderMarkdown(
[
'Prices are \\$5 and \\$10. Show `$x$` as code.',
'',
'```js',
'const price = "$10"',
'```',
].join('\n'),
themes
].join('\n')
)
expect(html).toContain('Prices are $5 and $10. Show <code>$x$</code> as code.')
expect(html).toContain('data-rehype-pretty-code-figure')
@@ -51,18 +54,17 @@ test('keeps escaped currency and code literal and still highlights non-math fenc
})
test('uses stock dollar parsing, including an unclosed display fence', async () => {
const currency = await processMarkdown('Prices are $5 and $10.', themes)
const currency = await renderMarkdown('Prices are $5 and $10.')
expect(currency).toContain('>5 and </annotation>')
const unclosed = await processMarkdown('$$\nx^2\n\n## After', themes)
const unclosed = await renderMarkdown('$$\nx^2\n\n## After')
expect(unclosed).not.toContain('<h2')
expect(unclosed).toContain('## After')
})
test('typesets after assigning heading links and renders math inside sidenotes', async () => {
const html = await processMarkdown(
'# Energy $E=mc^2$[^1]\n\nAlso see this[^2].\n\n[^1]: Inline $x^2$.\n\n[^2]: A block follows.\n\n $$\n y^2\n $$',
themes
const html = await renderMarkdown(
'# Energy $E=mc^2$[^1]\n\nAlso see this[^2].\n\n[^1]: Inline $x^2$.\n\n[^2]: A block follows.\n\n $$\n y^2\n $$'
)
const id = 'energy-emc211-inline-x2sidenote-111-inline-x2'
expect(html).toContain(`<h1 id="${id}">`)
@@ -77,7 +79,7 @@ test.each([
'<pre><code class="language-math" id="example">Raw example</code></pre>',
'<div class="math-display" id="notes"><em>Notes</em></div>',
])('preserves raw HTML without typesetting its classes: %s', async (raw) => {
const html = await processMarkdown(raw, themes)
const html = await renderMarkdown(raw)
expect(html).toContain(raw)
expect(html).not.toContain(mathWrapper)
})
@@ -85,7 +87,7 @@ test.each([
test('preserves raw links and displays with math classes alongside actual Markdown math', async () => {
const link = '<a class="language-math" href="/proof">Proof</a>'
const display = '<div class="math-display" id="proof"><em>Proof notes</em></div>'
const html = await processMarkdown(`${link} and $x^2$.\n\n${display}`, themes)
const html = await renderMarkdown(`${link} and $x^2$.\n\n${display}`)
expect(html).toContain(mathWrapper)
expect(html).toContain(link)
expect(html).toContain(display)
@@ -93,12 +95,12 @@ test('preserves raw links and displays with math classes alongside actual Markdo
})
test('recognizes parser math and preserves raw links in BOM-prefixed Markdown', async () => {
const math = await processMarkdown('\uFEFF$x$', themes)
const math = await renderMarkdown('\uFEFF$x$')
expect(math).toContain(mathWrapper)
expect(math).toContain('<math')
const rawLink = '<a class="language-math" href="/proof">Proof</a>'
const rawHtml = await processMarkdown(`\uFEFF\`x\`${rawLink} and $y$.`, themes)
const rawHtml = await renderMarkdown(`\uFEFF\`x\`${rawLink} and $y$.`)
expect(rawHtml).toContain(rawLink)
expect(rawHtml.match(/<math\b/g)).toHaveLength(1)
})
@@ -106,26 +108,25 @@ test('recognizes parser math and preserves raw links in BOM-prefixed Markdown',
test('keeps raw HTML classes when list indentation shifts raw source offsets', async () => {
const raw = '<span class="math-inline">r</span>'
const markdown = `- <div>\n${'\ttext\n'.repeat(41)}\t${raw}</div>\n\n$x$`
const html = await processMarkdown(markdown, themes)
const html = await renderMarkdown(markdown)
expect(html).toContain(raw)
expect(html.match(/<math\b/g)).toHaveLength(1)
})
test('cleans up internal markers in inert HTML templates without typesetting them', async () => {
const markdown = '<template>\n\n<template>\n\n$x$\n\n</template>\n\n</template>'
const html = await processMarkdown(markdown, themes)
const html = await renderMarkdown(markdown)
expect(html).toContain('<template>')
expect(html).toContain('>x</span>')
expect(html).not.toContain('data-luzzle-math')
expect(html).not.toMatch(/<math\b/)
expect(await processMarkdown(markdown, themes)).toBe(html)
expect(await renderMarkdown(markdown)).toBe(html)
})
test('does not allow TeX commands to add external resources or arbitrary HTML attributes', async () => {
const html = await processMarkdown(
String.raw`$\includegraphics{https://example.test/image.png}$ $\htmlId{author-id}{x}$ $\href{https://example.test/link}{link}$`,
themes
const html = await renderMarkdown(
String.raw`$\includegraphics{https://example.test/image.png}$ $\htmlId{author-id}{x}$ $\href{https://example.test/link}{link}$`
)
expect(html).not.toContain('<img')
expect(html).not.toContain('id="author-id"')
@@ -136,7 +137,7 @@ const inlineDefinition =
'First **para**graph. A [link](https://example.com), <em>in</em>line, and `code`.'
async function renderMarkdownTree(markdown: string) {
const html = await processMarkdown(markdown, themes)
const html = await renderMarkdown(markdown)
return unified()
.use(rehypeRaw)
.runSync({
@@ -7,8 +7,9 @@ import {
rehypeTypesetMarkdownMath,
rehypeWrapMarkdown,
remarkKeepInlineMathOutOfCodeHighlighting,
type MathWarning,
} from './math.js'
import { rehypeRenderMermaid, remarkMarkMermaidFences } from './mermaid/markdown.js'
import type { MarkdownFragment, ReportMarkdownWarning } from './context.js'
import remarkGfm from './remark-gfm.js'
import { remarkSidenoteSyntax, remarkResolveSidenotes } from './remark-sidenotes.js'
import { sidenoteHandler, rehypePlaceSidenotes, rehypePresentSidenotes } from './sidenotes/html.js'
@@ -26,11 +27,16 @@ import type { Config } from '@luzzle/web.config'
export type CodeThemes = Config['theme']['markdown']['code']
type MarkdownOptions = {
assets?: AssetUrls
fragment: MarkdownFragment
warn?: ReportMarkdownWarning
}
export async function processMarkdown(
markdown: string,
themes: CodeThemes,
assets?: AssetUrls,
warnMath?: (warning: MathWarning) => void
{ assets, fragment, warn = () => undefined }: MarkdownOptions
): Promise<string> {
const processor = unified()
.use(remarkGfm, { plugins: { footnote: false } })
@@ -41,6 +47,7 @@ export async function processMarkdown(
.use(remarkResolveSidenotes)
.use(remarkGemoji)
.use(remarkDirective)
.use(remarkMarkMermaidFences)
.use(remarkRehype, {
allowDangerousHtml: true,
handlers: {
@@ -57,7 +64,8 @@ export async function processMarkdown(
.use(rehypePresentSidenotes)
.use(rehypeAutolinkHeadings)
.use(rehypeTypesetMarkdownMath)
.use(rehypeReportMathWarnings, warnMath)
.use(rehypeReportMathWarnings, warn)
.use(rehypeRenderMermaid, fragment, warn)
.use(rehypeWrapMarkdown)
.use(rehypeStringify, { allowDangerousHtml: true })
@@ -2,7 +2,7 @@ import { filterFrontmatterFields, getFrontmatterValues, resolveFieldPaths } from
import type { PieceFrontmatterProperty } from '@luzzle/core'
import { encodeAssetPath } from '@luzzle/web.pieces'
import { processMarkdown } from './engine.js'
import type { MathWarning } from './math.js'
import type { ReportMarkdownWarning } from './context.js'
import type { AssetUrls } from './rehype-asset-urls.js'
import type { TransformInput, AssetRecord } from '../utils/types.js'
@@ -12,8 +12,11 @@ export async function run(input: TransformInput): Promise<AssetRecord[]> {
const { webPiece, config } = input
const assets = createMarkdownAssets(input)
const render = (markdown: string, fieldPath?: string) => {
const warnMath = createMathWarningHandler(input, fieldPath)
return processMarkdown(markdown, config.theme.markdown.code, assets, warnMath)
return processMarkdown(markdown, config.theme.markdown.code, {
assets,
fragment: { pieceKey: webPiece.key, fieldPath },
warn: createWarningHandler(input, fieldPath),
})
}
const records: AssetRecord[] = []
@@ -33,10 +36,13 @@ export async function run(input: TransformInput): Promise<AssetRecord[]> {
return records
}
function createMathWarningHandler({ webPiece, logger }: TransformInput, field?: string) {
function createWarningHandler(
{ webPiece, logger }: TransformInput,
field?: string
): ReportMarkdownWarning {
const part = field ? 'field' : 'body'
return ({ reason, line, column }: MathWarning) => {
logger.warn('Could not render Markdown math', {
return ({ feature, reason, line, column }) => {
logger.warn(`Could not render Markdown ${feature}`, {
file: webPiece.file_path,
part,
field,
@@ -5,8 +5,7 @@ import type { Root as MarkdownRoot } from 'mdast'
import rehypeKatex from 'rehype-katex'
import type { Transformer } from 'unified'
import { EXIT, visit } from 'unist-util-visit'
export type MathWarning = { reason: string; line?: number; column?: number }
import type { ReportMarkdownWarning } from './context.js'
type MarkdownFile = Parameters<Transformer<HtmlRoot>>[1]
type RenderMessage = MarkdownFile['messages'][number]
@@ -123,17 +122,13 @@ function getMathWarningLocation(message: RenderMessage) {
}
}
export function rehypeReportMathWarnings(
warnMath?: (warning: MathWarning) => void
): Transformer<HtmlRoot> {
export function rehypeReportMathWarnings(warn: ReportMarkdownWarning): Transformer<HtmlRoot> {
return (_tree, file) => {
if (!warnMath) return
for (const message of file.messages) {
if (message.source !== 'rehype-katex') continue
const reason = message.cause instanceof Error ? message.cause.message : message.reason
const location = getMathWarningLocation(message)
warnMath({ reason, ...location })
warn({ feature: 'math', reason, ...location })
}
}
}
@@ -0,0 +1,131 @@
import { expect, test, vi } from 'vitest'
import { validateConfig } from '@luzzle/web.config'
import rehypeRaw from 'rehype-raw'
import { unified } from 'unified'
import { visit } from 'unist-util-visit'
import type { Element } from 'hast'
import { processMarkdown } from '../engine.js'
import type { ReportMarkdownWarning } from '../context.js'
const themes = validateConfig({}).theme.markdown.code
const fragment = { pieceKey: 'test' }
const flowchart = 'flowchart LR\naccTitle: Publishing flow\nA[Draft] --> B[Publish]'
const fence = ['```mermaid', flowchart, '```'].join('\n')
function render(markdown: string, warn?: ReportMarkdownWarning) {
return processMarkdown(markdown, themes, { fragment, warn })
}
function parseHtml(html: string) {
return unified().use(rehypeRaw).runSync({
type: 'root',
children: [{ type: 'raw', value: html }],
})
}
test('keeps a Mermaid example literal when written in a text fence', async () => {
const html = await render(['```text', flowchart, '```'].join('\n'))
expect(html).toContain('flowchart LR')
expect(html).not.toMatch(/<svg\b/)
})
test('replaces a Mermaid fence in place without changing math or other code fences', async () => {
const markdown = ['Before $x^2$.', fence, 'After.', '```js\nconst value = 1\n```'].join('\n\n')
const html = await render(markdown)
expect(html).toMatch(/<figure data-luzzle-mermaid><div\b[^>]*><svg\b/)
expect(html).toMatch(/aria-labelledby="(luzzle-mermaid-[a-f0-9]+-1-title)"[^>]*><title id="\1">Publishing flow<\/title>/)
expect(html.indexOf('<figure data-luzzle-mermaid>')).toBeLessThan(html.indexOf('<p>After.</p>'))
expect(html).not.toContain('flowchart LR')
expect(html).not.toContain('data-luzzle-mermaid-fence')
expect(html).toContain('class="katex-mathml"')
expect(html.match(/data-rehype-pretty-code-figure/g)).toHaveLength(1)
})
test('wraps the SVG in a named, keyboard-focusable region using its natural width', async () => {
const html = await render(fence)
const regions: Element[] = []
visit(parseHtml(html), 'element', (node, _index, parent) => {
if (parent?.type === 'element' && Object.hasOwn(parent.properties, 'dataLuzzleMermaid')) {
regions.push(node)
}
})
expect(regions).toHaveLength(1)
const [region] = regions
expect(region.properties).toMatchObject({
role: 'region',
tabIndex: 0,
ariaLabel: expect.stringMatching(/\S/),
'aria-description': expect.stringMatching(/\S/),
})
const svg = region.children[0]
if (svg?.type !== 'element' || svg.tagName !== 'svg') throw new Error('Expected an inline SVG')
expect(Number(svg.properties.width)).toBeGreaterThan(0)
expect(region.properties.style).toBe(`--mermaid-natural-width: ${svg.properties.width}px`)
})
test('renders tilde fences nested in a blockquote', async () => {
const markdown = ['~~~mermaid', ...flowchart.split('\n'), '~~~']
.map((line) => `> ${line}`)
.join('\n')
const html = await render(markdown)
expect(html).toMatch(/<blockquote>\s*<figure data-luzzle-mermaid><div\b[^>]*><svg\b/)
})
test('gives repeated sidenote diagrams distinct IDs that are stable across renders', async () => {
const definition = fence.split('\n').map((line) => ` ${line}`).join('\n')
const markdown = `First[^shared] and again[^shared].\n\n[^shared]: A publishing diagram.\n\n${definition}`
const html = await render(markdown)
const occurrences = [...html.matchAll(/aria-labelledby="luzzle-mermaid-[a-f0-9]+-(\d+)-title"/g)]
.map(([, ordinal]) => ordinal)
expect(occurrences).toEqual(['1', '2'])
expect(await render(markdown)).toBe(html)
})
test('leaves author HTML and inline code alone and scrubs inert template markers', async () => {
const raw = '<pre><code class="language-mermaid" data-luzzle-mermaid-fence="author">Raw code</code></pre>'
const template = ['<template>', '<template>', fence, '</template>', '</template>'].join('\n\n')
const warn = vi.fn()
const html = await render([raw, '`mermaid`', template].join('\n\n'), warn)
expect(html).toContain(raw)
expect(html).toContain('<code>mermaid</code>')
expect(html).toContain('<template>')
expect(html).toContain('<pre><code>flowchart LR')
expect(html.match(/data-luzzle-mermaid-fence/g)).toHaveLength(1)
expect(html).not.toMatch(/<svg\b/)
expect(warn).not.toHaveBeenCalled()
})
test('does not render a fence swallowed by raw HTML parsing', async () => {
const warn = vi.fn()
const html = await render(['<iframe>', fence, '</iframe>'].join('\n\n'), warn)
expect(html).toContain('<iframe>')
expect(html).not.toMatch(/<svg\b|data-luzzle-mermaid/)
expect(warn).not.toHaveBeenCalled()
})
test('warns at the opening fence, preserves the exact source, and renders the next diagram', async () => {
const invalid = 'flowchart LR\nA --> [\n<em>Not HTML</em>'
const brokenFence = ['```mermaid', invalid, '```'].join('\n')
const markdown = ['Before.', brokenFence, fence].join('\n\n')
const warn = vi.fn()
const html = await render(markdown, warn)
expect(await processMarkdown(markdown, themes, { fragment })).toBe(html)
const fallback: string[] = []
visit(parseHtml(html), 'element', (node) => {
if (node.tagName !== 'code') return
for (const child of node.children) if (child.type === 'text') fallback.push(child.value)
})
expect(fallback).toEqual([`${invalid}\n`])
expect(html).toMatch(/<p>Diagram unavailable<\/p><pre>[\s\S]*<figure data-luzzle-mermaid><div\b[^>]*><svg\b/)
expect(html).not.toContain('<em>Not HTML</em>')
expect(html).not.toContain('data-luzzle-mermaid-fence')
expect(warn).toHaveBeenCalledExactlyOnceWith({ feature: 'Mermaid', reason: 'syntax', line: 3, column: 1 })
})
@@ -0,0 +1,110 @@
import { createHash, randomUUID } from 'node:crypto'
import type { Element, Root as HtmlRoot } from 'hast'
import { h } from 'hastscript'
import type { Code, Root as MarkdownRoot } from 'mdast'
import type { Raw } from 'mdast-util-to-hast'
import type { Transformer } from 'unified'
import { SKIP, visit } from 'unist-util-visit'
import { renderMermaid } from './render.js'
import type { MarkdownFragment, ReportMarkdownWarning } from '../context.js'
type MarkdownFile = Parameters<Transformer<HtmlRoot>>[1]
type MermaidFencesByMarker = Map<string, Code>
const fencesByFile = new WeakMap<MarkdownFile, MermaidFencesByMarker>()
export function remarkMarkMermaidFences(): Transformer<MarkdownRoot> {
return (tree, file) => {
const fences: MermaidFencesByMarker = new Map()
let token: string | undefined
visit(tree, 'code', (node) => {
if (node.lang !== 'mermaid') return
// Remark sees actual fences only. The token keeps raw HTML from matching later.
token ??= randomUUID()
const key = `${token}-${fences.size}`
fences.set(key, node)
node.data ??= {}
node.data.hProperties = { ...node.data.hProperties, dataLuzzleMermaidFence: key }
// Let the normal code handler produce a plain <pre><code> block that Shiki skips.
node.lang = null
node.meta = null
})
if (fences.size) fencesByFile.set(file, fences)
}
}
function removeMermaidFenceMarker(node: Element, fences: MermaidFencesByMarker): Code | undefined {
const key = node.properties.dataLuzzleMermaidFence
if (typeof key !== 'string') return
const fence = fences.get(key)
if (fence) delete node.properties.dataLuzzleMermaidFence
return fence
}
function clearInertFences(tree: HtmlRoot, fences: MermaidFencesByMarker) {
visit(tree, 'element', (node) => {
removeMermaidFenceMarker(node, fences)
if (node.content) clearInertFences(node.content, fences)
})
}
function takeMermaidFenceFromCodeBlock(node: Element, fences: MermaidFencesByMarker) {
const code = node.children[0]
if (node.tagName !== 'pre' || code?.type !== 'element' || code.tagName !== 'code') return
return removeMermaidFenceMarker(code, fences)
}
function renderDiagramFigure(svg: string, width: number): Element {
const diagram: Raw = { type: 'raw', value: svg }
const scrollRegion = h(
'div',
{
role: 'region',
tabIndex: 0,
ariaLabel: 'Mermaid diagram',
'aria-description': 'Scroll horizontally if the diagram does not fit.',
style: `--mermaid-natural-width: ${width}px`,
},
[diagram]
)
return h('figure', { dataLuzzleMermaid: true }, [scrollRegion])
}
function mermaidIdPrefix({ pieceKey, fieldPath }: MarkdownFragment): string {
// The body and each concrete field path get a distinct, SVG-safe namespace.
const scope = createHash('sha256').update(JSON.stringify([pieceKey, fieldPath ?? null])).digest('hex')
return `luzzle-mermaid-${scope}`
}
export function rehypeRenderMermaid(
fragment: MarkdownFragment,
warn: ReportMarkdownWarning
): Transformer<HtmlRoot> {
return (tree, file) => {
const fences = fencesByFile.get(file)
if (!fences) return
const idPrefix = mermaidIdPrefix(fragment)
let occurrence = 0
visit(tree, 'element', (node, index, parent) => {
if (node.content) clearInertFences(node.content, fences)
// Discard markers left on code outside a block after raw HTML parsing.
if (node.tagName === 'code') removeMermaidFenceMarker(node, fences)
const fence = takeMermaidFenceFromCodeBlock(node, fences)
if (!fence || !parent || index === undefined) return
// Use the live output order, not source positions that can repeat in sidenotes.
const diagram = renderMermaid(fence.value, `${idPrefix}-${++occurrence}`)
if (diagram.ok) {
parent.children[index] = renderDiagramFigure(diagram.svg, diagram.width)
} else {
const start = fence.position?.start
warn({ feature: 'Mermaid', reason: diagram.reason, line: start?.line, column: start?.column })
parent.children[index] = h('div', [h('p', 'Diagram unavailable'), node])
}
return SKIP
})
}
}
@@ -0,0 +1,49 @@
import { expect, test } from 'vitest'
import { renderMermaid } from './render.js'
const idPrefix = 'luzzle-mermaid-test-body-1'
test('renders a left-to-right flowchart with prefixed accessible metadata', () => {
const result = renderMermaid(
'flowchart LR\naccTitle: Publishing\naccDescr: Review the draft, then publish it.\nA[Review] --> B[Publish]',
idPrefix
)
if (!result.ok) throw new Error(`Diagram failed: ${result.reason}`)
expect(result.type).toBe('flowchart')
expect(result.width).toBeGreaterThan(result.height)
expect(result.svg).toContain(`aria-labelledby="${idPrefix}-title"`)
expect(result.svg).toContain(`<title id="${idPrefix}-title">Publishing</title>`)
expect(result.svg).toContain(`aria-describedby="${idPrefix}-desc"`)
expect(result.svg).toContain(`<desc id="${idPrefix}-desc">Review the draft, then publish it.</desc>`)
})
test('renders without emitting links or image resources', () => {
const result = renderMermaid(
[
'flowchart TD',
'A[Read more] --> B@{ img: "https://example.test/picture.png", label: "Picture" }',
'click A href "https://example.test/read-more"',
].join('\n'),
idPrefix
)
if (!result.ok) throw new Error(`Diagram failed: ${result.reason}`)
expect(result.svg).toContain('Read more')
expect(result.svg).not.toMatch(/<a\b|<image\b|https:\/\/example\.test/)
})
test('returns a syntax reason without exposing the diagram source', () => {
expect(renderMermaid('flowchart LR\nA --> [', idPrefix)).toEqual({ ok: false, reason: 'syntax' })
})
test('uses Pele’s character limit rather than an additional byte limit', () => {
const withComment = (comment: string) => `flowchart LR\n%% ${comment}\nA --> B`
// Fewer than 16,384 characters, but more than 16,384 UTF-8 bytes.
expect(renderMermaid(withComment('界'.repeat(6_000)), idPrefix)).toMatchObject({ ok: true })
expect(renderMermaid(withComment('x'.repeat(17_000)), idPrefix)).toEqual({
ok: false,
reason: 'limit',
})
})
@@ -0,0 +1,41 @@
import { PeleError, render } from 'pele'
import type { DiagramType, PeleErrorCode } from 'pele'
const maxSourceLength = 16 * 1024
const maxSvgLength = 256 * 1024
const maxEdges = 200
type RenderedDiagram = {
ok: true
svg: string
width: number
height: number
type: DiagramType
}
type RenderFailure = {
ok: false
reason: PeleErrorCode | 'render-error'
}
type RenderResult = RenderedDiagram | RenderFailure
// Treat Pele’s SVG like author-supplied Markdown HTML.
export function renderMermaid(source: string, idPrefix: string): RenderResult {
try {
const { svg, width, height, type } = render(source, {
idPrefix,
responsive: false,
autoDirection: false,
links: false,
images: false,
limit: maxSourceLength,
outputLimit: maxSvgLength,
maxEdges,
})
return { ok: true, svg, width, height, type }
} catch (error) {
// Pele's error text may contain excerpts from the diagram.
return { ok: false, reason: error instanceof PeleError ? error.code : 'render-error' }
}
}
+9
View File
@@ -879,6 +879,9 @@ importers:
openworkflow:
specifier: 0.11.0
version: 0.11.0
pele:
specifier: 1.13.0
version: 1.13.0
rehype-autolink-headings:
specifier: 7.1.0
version: 7.1.0
@@ -3592,6 +3595,10 @@ packages:
pathe@2.0.3:
resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}
pele@1.13.0:
resolution: {integrity: sha512-Ie8UKY9x00MsuR3jO6AzUwzK2Z6MIV3Tf4EDdITiuk8Uaz8K7g0R082WqsqNaSU8DdgkrRvZThzhit83mi/uiw==}
engines: {node: '>=20'}
picocolors@1.1.1:
resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}
@@ -7398,6 +7405,8 @@ snapshots:
pathe@2.0.3: {}
pele@1.13.0: {}
picocolors@1.1.1: {}
picomatch@4.0.4: {}