diff --git a/.changeset/piece-markdown-mermaid.md b/.changeset/piece-markdown-mermaid.md new file mode 100644 index 00000000..b55753f8 --- /dev/null +++ b/.changeset/piece-markdown-mermaid.md @@ -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. diff --git a/apps/web/demo/archive/words/from-notebook-to-garden.words.md b/apps/web/demo/archive/words/from-notebook-to-garden.words.md new file mode 100644 index 00000000..cee1750e --- /dev/null +++ b/apps/web/demo/archive/words/from-notebook-to-garden.words.md @@ -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] +``` diff --git a/apps/web/src/lib/templates/markdown.css b/apps/web/src/lib/templates/markdown.css new file mode 100644 index 00000000..0557b16d --- /dev/null +++ b/apps/web/src/lib/templates/markdown.css @@ -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; + } + } + } +} diff --git a/apps/web/src/routes/(auth)/admin/piece/[...path]/preview/+layout@.svelte b/apps/web/src/routes/(auth)/admin/piece/[...path]/preview/+layout@.svelte index 4f1e1796..008a8c23 100644 --- a/apps/web/src/routes/(auth)/admin/piece/[...path]/preview/+layout@.svelte +++ b/apps/web/src/routes/(auth)/admin/piece/[...path]/preview/+layout@.svelte @@ -1,7 +1,7 @@ + {@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('/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 = {} diff --git a/packages/web/worker/src/transforms/markdown/assets.test.ts b/packages/web/worker/src/transforms/markdown/assets.test.ts index d6fafa68..2a8482be 100644 --- a/packages/web/worker/src/transforms/markdown/assets.test.ts +++ b/packages/web/worker/src/transforms/markdown/assets.test.ts @@ -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']]), diff --git a/packages/web/worker/src/transforms/markdown/context.ts b/packages/web/worker/src/transforms/markdown/context.ts new file mode 100644 index 00000000..227543e5 --- /dev/null +++ b/packages/web/worker/src/transforms/markdown/context.ts @@ -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 diff --git a/packages/web/worker/src/transforms/markdown/engine.test.ts b/packages/web/worker/src/transforms/markdown/engine.test.ts index 99e4357d..87555f67 100644 --- a/packages/web/worker/src/transforms/markdown/engine.test.ts +++ b/packages/web/worker/src/transforms/markdown/engine.test.ts @@ -10,8 +10,12 @@ const themes = validateConfig({}).theme.markdown.code const mathWrapper = '
' +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\n\nRaw HTML', themes) + const html = await renderMarkdown('Plain text\n\n\n\nRaw HTML') expect(html).toBe( '

Plain text

\n\n

Raw HTML

' ) @@ -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 \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 $x$ 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 ') - const unclosed = await processMarkdown('$$\nx^2\n\n## After', themes) + const unclosed = await renderMarkdown('$$\nx^2\n\n## After') expect(unclosed).not.toContain(' { - 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(`

`) @@ -77,7 +79,7 @@ test.each([ '
Raw example
', '
Notes
', ])('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 = 'Proof' const display = '
Proof notes
' - 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(' { const raw = 'r' const markdown = `-
\n${'\ttext\n'.repeat(41)}\t${raw}
\n\n$x$` - const html = await processMarkdown(markdown, themes) + const html = await renderMarkdown(markdown) expect(html).toContain(raw) expect(html.match(/ { const markdown = '' - const html = await processMarkdown(markdown, themes) + const html = await renderMarkdown(markdown) expect(html).toContain('