A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat: add Mermaid theme customization options (#9478)
Will Dean7a010d6b3c9b
diff --git a/docs/api/diagrams.md b/docs/api/diagrams.mdindex 259115c4c2..e1f2124610 100644--- a/docs/api/diagrams.md+++ b/docs/api/diagrams.md@@ -14,4 +14,55 @@ def __():## Mermaid diagrams+Customize Mermaid styling with `theme` and `theme_variables`:++Theme only:++```python+mo.mermaid(+ diagram,+ theme="neutral",+)+```++```python+mo.mermaid(+ """+ graph TD+ A[Observed] --> B[Latent]+ B --> C[Posterior]+ """,+ theme="base",+ theme_variables={+ "primaryColor": "#E8EEF5",+ "primaryTextColor": "#1F2937",+ "primaryBorderColor": "#64748B",+ "lineColor": "#475569",+ "tertiaryColor": "#F8FAFC",+ },+)+```++`theme` supports `"base"`, `"dark"`, `"default"`, `"forest"`,+`"neutral"`, and `"null"`.++By default, `mo.mermaid(diagram)` follows the app light/dark theme.++For supported `theme_variables` keys and defaults, see Mermaid's theming docs:++- [Theme configuration](https://mermaid.js.org/config/theming.html)+- [Theme variables reference](https://mermaid.js.org/config/theming.html#theme-variables)++Per Mermaid docs, custom `theme_variables` are reliably applied with+`theme="base"`.++If you pass `theme_variables` with `theme=None`, marimo automatically uses+`theme="base"`.++If you pass `theme_variables` with any explicit non-`base` theme,+`mo.mermaid(...)` raises a `ValueError`.++If custom colors are not appearing, make sure you are not combining+`theme_variables` with a non-`base` theme.+::: marimo.mermaiddiff --git a/frontend/src/plugins/core/__test__/sanitize.test.ts b/frontend/src/plugins/core/__test__/sanitize.test.tsindex 6dca5840bf..dfd5517395 100644--- a/frontend/src/plugins/core/__test__/sanitize.test.ts+++ b/frontend/src/plugins/core/__test__/sanitize.test.ts@@ -145,6 +145,14 @@ describe("sanitizeHtml", () => {);});+ test("preserves marimo-mermaid with theme attributes", () => {+ const html =+ "<marimo-mermaid data-diagram='"graph TD\\nA --> B"' data-theme='"base"' data-theme_variables='{"primaryColor": "#E8EEF5", "lineColor": "#475569"}'></marimo-mermaid>";+ expect(sanitizeHtml(html)).toMatchInlineSnapshot(+ `"<marimo-mermaid data-diagram=""graph TD\\nA --> B"" data-theme=""base"" data-theme_variables="{"primaryColor": "#E8EEF5", "lineColor": "#475569"}"></marimo-mermaid>"`,+ );+ });+test("keeps style tags with FORCE_BODY", () => {const html = "<style>body { color: red; }</style><p>Text</p>";expect(sanitizeHtml(html)).toMatchInlineSnapshot(diff --git a/frontend/src/plugins/layout/__test__/MermaidPlugin.test.ts b/frontend/src/plugins/layout/__test__/MermaidPlugin.test.tsnew file mode 100644index 0000000000..4d80ef93aa--- /dev/null+++ b/frontend/src/plugins/layout/__test__/MermaidPlugin.test.ts@@ -0,0 +1,50 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { describe, expect, test } from "vitest";+import { MermaidPlugin } from "../mermaid/MermaidPlugin";++describe("MermaidPlugin validator", () => {+ test("accepts optional theme and theme_variables", () => {+ const plugin = new MermaidPlugin();+ const result = plugin.validator.safeParse({+ diagram: "graph TD\nA --> B",+ theme: "base",+ theme_variables: {+ primaryColor: "#E8EEF5",+ lineColor: "#475569",+ },+ });++ expect(result.success).toBe(true);+ if (!result.success) {+ return;+ }++ expect(result.data).toEqual({+ diagram: "graph TD\nA --> B",+ theme: "base",+ theme_variables: {+ primaryColor: "#E8EEF5",+ lineColor: "#475569",+ },+ });+ });++ test("accepts any string as theme", () => {+ const plugin = new MermaidPlugin();+ const result = plugin.validator.safeParse({+ diagram: "graph TD\nA --> B",+ theme: "invalid",+ });++ expect(result.success).toBe(true);+ if (!result.success) {+ return;+ }++ expect(result.data).toEqual({+ diagram: "graph TD\nA --> B",+ theme: "invalid",+ });+ });+});diff --git a/frontend/src/plugins/layout/mermaid/MermaidPlugin.tsx b/frontend/src/plugins/layout/mermaid/MermaidPlugin.tsxindex 9505114382..24dfdefaac 100644--- a/frontend/src/plugins/layout/mermaid/MermaidPlugin.tsx+++ b/frontend/src/plugins/layout/mermaid/MermaidPlugin.tsx@@ -9,6 +9,8 @@ import type {interface Data {diagram: string;+ theme?: string;+ theme_variables?: Record<string, string>;}export class MermaidPlugin implements IStatelessPlugin<Data> {@@ -16,10 +18,18 @@ export class MermaidPlugin implements IStatelessPlugin<Data> {validator = z.object({diagram: z.string(),+ theme: z.string().optional(),+ theme_variables: z.record(z.string(), z.string()).optional(),});render(props: IStatelessPluginProps<Data>): JSX.Element {- return <LazyMermaid diagram={props.data.diagram} />;+ return (+ <LazyMermaid+ diagram={props.data.diagram}+ theme={props.data.theme}+ themeVariables={props.data.theme_variables}+ />+ );}}diff --git a/frontend/src/plugins/layout/mermaid/mermaid.tsx b/frontend/src/plugins/layout/mermaid/mermaid.tsxindex 0add842407..d437dbcdbf 100644--- a/frontend/src/plugins/layout/mermaid/mermaid.tsx+++ b/frontend/src/plugins/layout/mermaid/mermaid.tsx@@ -10,6 +10,8 @@ import { Logger } from "@/utils/Logger";interface Props {diagram: string;+ theme?: string;+ themeVariables?: Record<string, string>;config?: MermaidConfig;}@@ -62,14 +64,16 @@ function randomAlpha() {).join("");}-const Mermaid: React.FC<Props> = ({ diagram }) => {+const Mermaid: React.FC<Props> = ({ diagram, theme, themeVariables }) => {// oxlint-disable-next-line react/hook-use-stateconst [id] = useState(() => randomAlpha());const darkMode = useTheme().theme === "dark";+ const resolvedTheme = theme ?? (darkMode ? "dark" : "forest");mermaid.initialize({...DEFAULT_CONFIG,- theme: darkMode ? "dark" : "forest",+ theme: resolvedTheme as MermaidConfig["theme"],+ themeVariables,darkMode: darkMode,});@@ -86,7 +90,7 @@ const Mermaid: React.FC<Props> = ({ diagram }) => {});return result.svg;- }, [trimmedDiagram, id, darkMode]);+ }, [trimmedDiagram, id, darkMode, resolvedTheme, themeVariables]);if (error) {return <ErrorBanner error={error} />;diff --git a/marimo/_plugins/stateless/mermaid.py b/marimo/_plugins/stateless/mermaid.pyindex 59d1516885..79371deccd 100644--- a/marimo/_plugins/stateless/mermaid.py+++ b/marimo/_plugins/stateless/mermaid.py@@ -4,10 +4,15 @@ from __future__ import annotationsfrom marimo._output.hypertext import Htmlfrom marimo._output.rich_help import mddocfrom marimo._plugins.core.web_component import build_stateless_plugin+from marimo._utils.dicts import remove_none_values@mddoc-def mermaid(diagram: str) -> Html:+def mermaid(+ diagram: str,+ theme: str | None = None,+ theme_variables: dict[str, str] | None = None,+) -> Html:"""Render a diagram with Mermaid.Mermaid is a tool for making diagrams such as flow charts and graphs. See@@ -16,6 +21,16 @@ def mermaid(diagram: str) -> Html:Args:diagram: a string containing a Mermaid diagram+ theme: optional Mermaid theme. See+ https://mermaid.js.org/config/theming.html#available-themes+ for available themes. If not provided, marimo picks+ a default based on app theme, unless `theme_variables` are+ provided.+ theme_variables: optional Mermaid `themeVariables` overrides.+ Mermaid defines supported keys and behavior; see+ https://mermaid.js.org/config/theming.html#theme-variables.+ If provided with `theme=None`, marimo automatically sets+ `theme="base"` so custom colors are applied.Returns:An `Html` object.@@ -30,11 +45,38 @@ def mermaid(diagram: str) -> Html:C --> D'''mo.mermaid(diagram)++ mo.mermaid(+ diagram,+ theme="base",+ theme_variables={+ "primaryColor": "#E8EEF5",+ "primaryTextColor": "#1F2937",+ "primaryBorderColor": "#64748B",+ "lineColor": "#475569",+ "tertiaryColor": "#F8FAFC",+ },+ )```"""+ if theme_variables is not None:+ if theme is None:+ theme = "base"+ elif theme != "base":+ raise ValueError(+ f"theme_variables require theme='base'. Got theme={theme!r}. "+ "See https://mermaid.js.org/config/theming.html"+ )+return Html(build_stateless_plugin(component_name="marimo-mermaid",- args={"diagram": diagram},+ args=remove_none_values(+ {+ "diagram": diagram,+ "theme": theme,+ "theme_variables": theme_variables,+ }+ ),))diff --git a/tests/_plugins/stateless/test_mermaid.py b/tests/_plugins/stateless/test_mermaid.pynew file mode 100644index 0000000000..2dbd58ce2d--- /dev/null+++ b/tests/_plugins/stateless/test_mermaid.py@@ -0,0 +1,56 @@+# Copyright 2026 Marimo. All rights reserved.++from typing import Any, cast++import pytest++from marimo._plugins.stateless.mermaid import mermaid+++def test_mo_mermaid_diagram_only() -> None:+ assert (+ mermaid("graph TD\nA --> B").text+ == "<marimo-mermaid data-diagram='"graph TD\nA --> B"'></marimo-mermaid>"+ )+++def test_mo_mermaid_theme_and_theme_variables() -> None:+ assert (+ mermaid(+ "graph TD\nA --> B",+ theme="base",+ theme_variables={+ "primaryColor": "#E8EEF5",+ "lineColor": "#475569",+ },+ ).text+ == "<marimo-mermaid data-diagram='"graph TD\nA --> B"' data-theme='"base"' data-theme_variables='{"primaryColor":"#E8EEF5","lineColor":"#475569"}'></marimo-mermaid>"+ )+++def test_mo_mermaid_theme_defaults_to_base_with_theme_variables() -> None:+ assert (+ mermaid(+ "graph TD\nA --> B",+ theme_variables={"primaryColor": "#E8EEF5"},+ ).text+ == "<marimo-mermaid data-diagram='"graph TD\nA --> B"' data-theme='"base"' data-theme_variables='{"primaryColor":"#E8EEF5"}'></marimo-mermaid>"+ )+++def test_mo_mermaid_rejects_theme_variables_with_non_base_theme() -> None:+ with pytest.raises(+ ValueError, match="theme_variables require theme='base'"+ ):+ mermaid(+ "graph TD\nA --> B",+ theme="neutral",+ theme_variables={"primaryColor": "#E8EEF5"},+ )+++def test_mo_mermaid_accepts_any_theme_string() -> None:+ assert (+ mermaid("graph TD\nA --> B", theme=cast(Any, "custom-new-theme")).text+ == "<marimo-mermaid data-diagram='"graph TD\nA --> B"' data-theme='"custom-new-theme"'></marimo-mermaid>"+ )