:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(notebooks): render mermaid code blocks as diagrams (#69490)
Matt Brooker7ea50745e749
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex d650af3b4b36..fe05e76c2196 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1228,6 +1228,18 @@ snapshots:hash: v1.k794b7964.69f3b0ede33d4b597caa7a923520e58945a4626196e203e552a7a1e029a0f525.pBiwxxHtJ2_3NfrUuKzwnrTNZ4b_y4zd49UQyDKRreccomponents-markdown-notebook--malformed-markdown-recovery--light:hash: v1.k794b7964.373448e5fe950e05adac4cf223b38920fa8d894d0d0034485cbbd7bdfd41566d.GDrMJvhqrK0U3zs9zESTR84PtJDeR9FOke5qH0EOWd4+ components-markdown-notebook--mermaid-diagram--dark:+ hash: v1.k794b7964.425e62645faba28d89678975e7e0d6d3d78caf0e997cbfe64e2b91511cee4f5d.UAvmMoEvnGg2GpzpcDKtTM4u6NymOVybkgU5_yHrm8A+ components-markdown-notebook--mermaid-diagram--light:+ hash: v1.k794b7964.cfdb5953653177193f610735cf2b003fef8816d27c6f527c23535bae6e34d68a.a_y-0vnbWLPDXSKCSOXnZcpB46z5XVtbyVz0r54p_60+ components-markdown-notebook--mermaid-diagram-fallback--dark:+ hash: v1.k794b7964.16cb85e3be806374ce574166a6d2439c79c87561278fb8080e48600d1f3eca19.6SeBym2Kx28qZOekCxkO-S6ceyOy48BbQD6sOCidnZ0+ components-markdown-notebook--mermaid-diagram-fallback--light:+ hash: v1.k794b7964.2df0be36671aaf0c329c6187bb03c752f3f5f701033c9c5c5a1b474f1a2b40da.db3C585yLQ6CyHGg4t5fme1f7J22QmLlkyK_3WpkOm4+ components-markdown-notebook--mermaid-diagram-wide--dark:+ hash: v1.k794b7964.be5f389ebf5f2a2d26ba094fb062861127e3af2fb49888f9fe6b5759d54a4a52.YpkWezxIcacFemijTJxzdy50UQMOQXbJwgt8gJSkRrQ+ components-markdown-notebook--mermaid-diagram-wide--light:+ hash: v1.k794b7964.76f82fa161da5c7ef652b22367b90c72eb99ff04fe14f13fa5a7965a18c27efd.gEEyp-lSpR49dY4srU6NDA_Jh0YhKYW69DTOckv4tS0components-markdown-notebook--mocked-collaboration--dark:hash: v1.k794b7964.e11be709065cefe6516361185b66e7aca286b7aeaf851f6f4f731a7b5a44625e.0cF2H1FOanpkyljIOsGiywdkMmu5WtzsAkxQ9xY9ttscomponents-markdown-notebook--mocked-collaboration--light:diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scssindex 1ba4339b02c4..d7c2d0870319 100644--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.scss@@ -1514,6 +1514,16 @@ h3.MarkdownNotebook__text-block--heading {opacity: 1;}+.MarkdownNotebook__mermaid-block {+ // Diagrams render at natural width (see MermaidDiagram's naturalWidth prop), so wide ones+ // scroll here instead of shrinking to fit. Don't cap the svg width, that would re-shrink them.+ overflow-x: auto;++ // Mermaid measures node label widths against the document font, but the surrounding+ // code group is monospace; without this reset labels render wider than their boxes and clip.+ font-family: var(--font-sans);+}+.MarkdownNotebook__divider-block {position: relative;padding: 0.625rem 0;diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.stories.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.stories.tsxindex bb728cd6c196..b7d37c163b61 100644--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.stories.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.stories.tsx@@ -64,6 +64,37 @@ const embedsNotebook = `# Embeds<Latex content="E=mc^2" />`+const mermaidNotebook = `# Release flow++A \`\`\`mermaid\`\`\` fence renders as a diagram in view mode while the source stays editable.++\`\`\`mermaid+flowchart LR+ A[Start] --> B{Tests pass?}+ B -->|Yes| C[Ship it]+ B -->|No| D[Fix it]+ D --> A+\`\`\``++const wideMermaidNotebook = `# Wide diagram++A diagram wider than the notebook column keeps its natural size and scrolls horizontally instead of shrinking.++\`\`\`mermaid+flowchart LR+ A[Signup form submitted] --> B[Validate email domain] --> C[Create organization] --> D[Provision default project] --> E[Send verification email] --> F[Track activation event] --> G[Redirect to onboarding] --> H[Show product tour]+\`\`\``++const invalidMermaidNotebook = `# Broken diagram++Invalid mermaid falls back to the plain source instead of crashing.++\`\`\`mermaid+flowchart LR+ A --> B -->+ this is not valid mermaid ]]]+\`\`\``+const malformedNotebook = `# Broken input<Query query={{"kind":`@@ -80,6 +111,7 @@ const meta: Meta<StoryArgs> = {tags: ['autodocs'],args: {showDebug: true,+ onInteractionStateChange: () => {},},render: (props) => <ControlledNotebook {...props} />,}@@ -207,6 +239,41 @@ export const Embeds: Story = {},}+export const MermaidDiagram: Story = {+ args: {+ value: mermaidNotebook,+ mode: 'view',+ },+ // Mermaid renders asynchronously (lazy chunk + async render); wait for the finished SVG+ // so the snapshot isn't captured mid-render.+ parameters: {+ testOptions: { waitForSelector: '[data-attr="mermaid-rendered"]' },+ },+}++export const MermaidDiagramWide: Story = {+ args: {+ value: wideMermaidNotebook,+ mode: 'view',+ },+ // Mermaid renders asynchronously (lazy chunk + async render); wait for the finished SVG+ // so the snapshot isn't captured mid-render.+ parameters: {+ testOptions: { waitForSelector: '[data-attr="mermaid-rendered"]' },+ },+}++export const MermaidDiagramFallback: Story = {+ args: {+ value: invalidMermaidNotebook,+ mode: 'view',+ },+ // Invalid mermaid resolves asynchronously to the error fallback; wait for it before snapshotting.+ parameters: {+ testOptions: { waitForSelector: '[data-attr="mermaid-error"]' },+ },+}+export const MalformedMarkdownRecovery: Story = {args: {value: malformedNotebook,diff --git a/frontend/src/lib/components/MarkdownNotebook/NotebookMermaidBlock.test.tsx b/frontend/src/lib/components/MarkdownNotebook/NotebookMermaidBlock.test.tsxnew file mode 100644index 000000000000..7a4081b928c9--- /dev/null+++ b/frontend/src/lib/components/MarkdownNotebook/NotebookMermaidBlock.test.tsx@@ -0,0 +1,68 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen } from '@testing-library/react'++import { NotebookCodeBlockNode } from './types'++jest.mock('kea', () => ({+ useValues: () => ({ isDarkModeOn: false }),+}))++jest.mock('~/layout/navigation-3000/themeLogic', () => ({+ themeLogic: { values: {} },+}))++const renderMock = jest.fn()++jest.mock('mermaid', () => ({+ __esModule: true,+ default: {+ initialize: jest.fn(),+ render: (...args: unknown[]) => renderMock(...args),+ },+}))++import { isMermaidCodeBlock, NotebookMermaidBlock } from './NotebookMermaidBlock'++function codeNode(text: string, language: string | undefined): NotebookCodeBlockNode {+ return { id: 'block-1', type: 'code', language, text }+}++describe('NotebookMermaidBlock', () => {+ afterEach(() => {+ cleanup()+ renderMock.mockReset()+ })++ it.each([+ ['mermaid', true],+ ['Mermaid', true],+ ['MERMAID', true],+ ['python', false],+ ['', false],+ [undefined, false],+ ])('isMermaidCodeBlock treats language %p as %p', (language, expected) => {+ expect(isMermaidCodeBlock(codeNode('flowchart LR; A-->B', language as string | undefined))).toBe(expected)+ })++ it('renders the diagram from the block source and registers a block ref', async () => {+ renderMock.mockResolvedValue({ svg: '<svg data-testid="rendered"><g/></svg>' })+ const setBlockRef = jest.fn()++ render(<NotebookMermaidBlock node={codeNode('flowchart LR; A-->B', 'mermaid')} setBlockRef={setBlockRef} />)++ const container = await screen.findByTestId('mermaid-rendered')+ expect(container.innerHTML).toContain('rendered')+ expect(renderMock).toHaveBeenCalledWith(expect.any(String), 'flowchart LR; A-->B')+ expect(setBlockRef).toHaveBeenCalledWith(expect.any(HTMLElement))+ })++ it('falls back to the plain source when the diagram fails to render', async () => {+ renderMock.mockRejectedValue(new Error('Parse error: bad syntax'))++ render(<NotebookMermaidBlock node={codeNode('not-a-real-diagram', 'mermaid')} setBlockRef={jest.fn()} />)++ const errorContainer = await screen.findByTestId('mermaid-error')+ expect(errorContainer).toHaveTextContent('not-a-real-diagram')+ })+})diff --git a/frontend/src/lib/components/MarkdownNotebook/NotebookMermaidBlock.tsx b/frontend/src/lib/components/MarkdownNotebook/NotebookMermaidBlock.tsxnew file mode 100644index 000000000000..3d610b7be029--- /dev/null+++ b/frontend/src/lib/components/MarkdownNotebook/NotebookMermaidBlock.tsx@@ -0,0 +1,39 @@+import { Suspense, lazy } from 'react'++import { Spinner } from 'lib/lemon-ui/Spinner'++import { NotebookCodeBlockNode } from './types'++// Loaded on demand so the mermaid library ships in its own chunk rather than the notebook bundle.+const LazyMermaidDiagram = lazy(() => import('lib/lemon-ui/LemonMarkdown/MermaidDiagram'))++export function isMermaidCodeBlock(node: NotebookCodeBlockNode): boolean {+ return node.language?.toLowerCase() === 'mermaid'+}++export function NotebookMermaidBlock({+ node,+ setBlockRef,+}: {+ node: NotebookCodeBlockNode+ setBlockRef: (element: HTMLElement | null) => void+}): JSX.Element {+ return (+ <div+ className="MarkdownNotebook__mermaid-block"+ ref={setBlockRef}+ contentEditable={false}+ data-markdown-notebook-node-id={node.id}+ >+ <Suspense+ fallback={+ <div className="flex items-center justify-center p-4">+ <Spinner />+ </div>+ }+ >+ <LazyMermaidDiagram code={node.text} naturalWidth />+ </Suspense>+ </div>+ )+}diff --git a/frontend/src/lib/components/MarkdownNotebook/renderNode.tsx b/frontend/src/lib/components/MarkdownNotebook/renderNode.tsxindex 1efcf2f98cb5..41ddb7d4aa06 100644--- a/frontend/src/lib/components/MarkdownNotebook/renderNode.tsx+++ b/frontend/src/lib/components/MarkdownNotebook/renderNode.tsx@@ -22,6 +22,7 @@ import {TextSelectionPointerStartEvent,} from './editorTypes'import { MemoizedNotebookComponentShell } from './NotebookComponentShell'+import { isMermaidCodeBlock, NotebookMermaidBlock } from './NotebookMermaidBlock'import { NotebookBlockNode, NotebookComponentRegistry, NotebookMode } from './types'export function renderNode({@@ -224,6 +225,11 @@ export function renderNode({}if (node.type === 'code') {+ // Render mermaid fences as diagrams in view mode; edit mode keeps the source editable.+ if (mode === 'view' && isMermaidCodeBlock(node)) {+ return <NotebookMermaidBlock node={node} setBlockRef={setBlockRef} />+ }+return (<EditableCodeBlocknode={node}diff --git a/frontend/src/lib/lemon-ui/LemonMarkdown/MermaidDiagram.test.tsx b/frontend/src/lib/lemon-ui/LemonMarkdown/MermaidDiagram.test.tsxindex de31d26fe484..c4c1f54eaff8 100644--- a/frontend/src/lib/lemon-ui/LemonMarkdown/MermaidDiagram.test.tsx+++ b/frontend/src/lib/lemon-ui/LemonMarkdown/MermaidDiagram.test.tsx@@ -44,6 +44,22 @@ describe('MermaidDiagram', () => {expect(container.innerHTML).toContain('rendered')})+ it('promotes the inline max-width to a fixed width when naturalWidth is set', async () => {+ renderMock.mockResolvedValue({ svg: '<svg style="max-width: 1200px;"><g/></svg>' })+ render(<MermaidDiagram code="flowchart LR; A-->B" naturalWidth />)+ const container = await screen.findByTestId('mermaid-rendered')+ const svgElement = container.querySelector('svg')+ expect(svgElement?.style.width).toBe('1200px')+ expect(svgElement?.style.maxWidth).toBe('')+ })++ it('keeps mermaid sizing untouched without naturalWidth', async () => {+ renderMock.mockResolvedValue({ svg: '<svg style="max-width: 1200px;"><g/></svg>' })+ render(<MermaidDiagram code="flowchart LR; A-->B" />)+ const container = await screen.findByTestId('mermaid-rendered')+ expect(container.querySelector('svg')?.style.maxWidth).toBe('1200px')+ })+it('falls back to the source and an error message when mermaid throws', async () => {renderMock.mockRejectedValue(new Error('Parse error: bad syntax'))render(<MermaidDiagram code="not-a-real-diagram" />)diff --git a/frontend/src/lib/lemon-ui/LemonMarkdown/MermaidDiagram.tsx b/frontend/src/lib/lemon-ui/LemonMarkdown/MermaidDiagram.tsxindex 631b6ce21a77..ad3de27be3f8 100644--- a/frontend/src/lib/lemon-ui/LemonMarkdown/MermaidDiagram.tsx+++ b/frontend/src/lib/lemon-ui/LemonMarkdown/MermaidDiagram.tsx@@ -27,9 +27,26 @@ let diagramCounter = 0export interface MermaidDiagramProps {code: stringclassName?: string+ /** Render at the diagram's intrinsic width instead of shrinking to fit the container.+ * Use inside a horizontally scrollable wrapper so wide diagrams scroll rather than becoming unreadably small. */+ naturalWidth?: boolean}-export function MermaidDiagram({ code, className }: MermaidDiagramProps): JSX.Element {+// Mermaid sizes its SVG with width="100%" plus an inline max-width of the intrinsic size, which+// scales wide diagrams down to the container. Inline styles beat any stylesheet rule, so the only+// way to let a scroll container take over is to rewrite the inline sizing to a fixed width.+function withNaturalWidth(svgMarkup: string): string {+ const host = document.createElement('div')+ host.innerHTML = svgMarkup+ const svgElement = host.querySelector('svg')+ if (svgElement && svgElement.style.maxWidth) {+ svgElement.style.width = svgElement.style.maxWidth+ svgElement.style.maxWidth = ''+ }+ return host.innerHTML+}++export function MermaidDiagram({ code, className, naturalWidth = false }: MermaidDiagramProps): JSX.Element {const { isDarkModeOn } = useValues(themeLogic)const reactId = useId()const [diagramId] = useState(() => {@@ -67,7 +84,7 @@ export function MermaidDiagram({ code, className }: MermaidDiagramProps): JSX.Elif (cancelled || !result) {return}- setSvg(result.svg)+ setSvg(naturalWidth ? withNaturalWidth(result.svg) : result.svg)}).catch((err: unknown) => {if (cancelled) {@@ -84,7 +101,7 @@ export function MermaidDiagram({ code, className }: MermaidDiagramProps): JSX.Elreturn () => {cancelled = true}- }, [code, isDarkModeOn, diagramId])+ }, [code, isDarkModeOn, diagramId, naturalWidth])if (error) {return (