Skip to content

Commit 05f8a3e

Browse files
zoomote[bot]roomoteedelauna
authored
[Fix] Mermaid labels are unreadable in light IDE themes (#1285)
* fix(webview): adapt Mermaid diagrams to IDE themes * fix(webview): add Mermaid visual regression baselines for all IDE themes --------- Co-authored-by: Roomote <[email protected]> Co-authored-by: Elliott de Launay <[email protected]>
1 parent 38d5ee0 commit 05f8a3e

9 files changed

Lines changed: 453 additions & 87 deletions

‎webview-ui/src/components/common/MermaidBlock.tsx‎

Lines changed: 20 additions & 87 deletions
Original file line numberDiff line numberDiff line change
@@ -7,82 +7,7 @@ import { useAppTranslation } from "@src/i18n/TranslationContext"
77
import { useCopyToClipboard } from "@src/utils/clipboard"
88
import CodeBlock from "./CodeBlock"
99
import { MermaidButton } from "@/components/common/MermaidButton"
10-
11-
// Removed previous attempts at static imports for individual diagram types
12-
// as the paths were incorrect for Mermaid v11.4.1 and caused errors.
13-
// The primary strategy will now rely on Vite's bundling configuration.
14-
15-
const MERMAID_THEME = {
16-
background: "#1e1e1e", // VS Code dark theme background
17-
textColor: "#ffffff", // Main text color
18-
mainBkg: "#2d2d2d", // Background for nodes
19-
nodeBorder: "#888888", // Border color for nodes
20-
lineColor: "#cccccc", // Lines connecting nodes
21-
primaryColor: "#3c3c3c", // Primary color for highlights
22-
primaryTextColor: "#ffffff", // Text in primary colored elements
23-
primaryBorderColor: "#888888",
24-
secondaryColor: "#2d2d2d", // Secondary color for alternate elements
25-
tertiaryColor: "#454545", // Third color for special elements
26-
27-
// Class diagram specific
28-
classText: "#ffffff",
29-
30-
// State diagram specific
31-
labelColor: "#ffffff",
32-
33-
// Sequence diagram specific
34-
actorLineColor: "#cccccc",
35-
actorBkg: "#2d2d2d",
36-
actorBorder: "#888888",
37-
actorTextColor: "#ffffff",
38-
39-
// Flow diagram specific
40-
fillType0: "#2d2d2d",
41-
fillType1: "#3c3c3c",
42-
fillType2: "#454545",
43-
}
44-
45-
mermaid.initialize({
46-
startOnLoad: false,
47-
// "strict" is required: mermaid renders LLM-generated source, and looser modes allow HTML injection through diagram labels.
48-
securityLevel: "strict",
49-
theme: "dark",
50-
suppressErrorRendering: true,
51-
themeVariables: {
52-
...MERMAID_THEME,
53-
fontSize: "16px",
54-
fontFamily: "var(--vscode-font-family, 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif)",
55-
56-
// Additional styling
57-
noteTextColor: "#ffffff",
58-
noteBkgColor: "#454545",
59-
noteBorderColor: "#888888",
60-
61-
// Improve contrast for special elements
62-
critBorderColor: "#ff9580",
63-
critBkgColor: "#803d36",
64-
65-
// Task diagram specific
66-
taskTextColor: "#ffffff",
67-
taskTextOutsideColor: "#ffffff",
68-
taskTextLightColor: "#ffffff",
69-
70-
// Numbers/sections
71-
sectionBkgColor: "#2d2d2d",
72-
sectionBkgColor2: "#3c3c3c",
73-
74-
// Alt sections in sequence diagrams
75-
altBackground: "#2d2d2d",
76-
77-
// Links
78-
linkColor: "#6cb6ff",
79-
80-
// Borders and lines
81-
compositeBackground: "#2d2d2d",
82-
compositeBorder: "#888888",
83-
titleColor: "#ffffff",
84-
},
85-
})
10+
import { getMermaidBackgroundColor, getMermaidConfig, useMermaidTheme } from "./mermaidTheme"
8611

8712
interface MermaidBlockProps {
8813
code: string
@@ -93,43 +18,51 @@ export default function MermaidBlock({ code }: MermaidBlockProps) {
9318
const [isLoading, setIsLoading] = useState(false)
9419
const [error, setError] = useState<string | null>(null)
9520
const [isErrorExpanded, setIsErrorExpanded] = useState(false)
21+
const renderVersionRef = useRef(0)
22+
const theme = useMermaidTheme()
9623
const { showCopyFeedback, copyWithFeedback } = useCopyToClipboard()
9724
const { t } = useAppTranslation()
9825

99-
// 1) Whenever `code` changes, mark that we need to re-render a new chart
26+
// Whenever the source or host theme changes, invalidate in-flight rendering.
10027
useEffect(() => {
28+
renderVersionRef.current += 1
10129
setIsLoading(true)
10230
setError(null)
103-
}, [code])
31+
}, [code, theme.signature])
10432

105-
// 2) Debounce the actual parse/render
10633
useDebounceEffect(
10734
() => {
35+
const renderVersion = renderVersionRef.current
10836
if (containerRef.current) {
10937
containerRef.current.innerHTML = ""
11038
}
11139

40+
mermaid.initialize(getMermaidConfig(theme.kind))
11241
mermaid
11342
.parse(code)
11443
.then(() => {
11544
const id = `mermaid-${Math.random().toString(36).substring(2)}`
11645
return mermaid.render(id, code)
11746
})
11847
.then(({ svg }) => {
119-
if (containerRef.current) {
48+
if (containerRef.current && renderVersion === renderVersionRef.current) {
12049
containerRef.current.innerHTML = svg
12150
}
12251
})
12352
.catch((err) => {
124-
console.warn("Mermaid parse/render failed:", err)
125-
setError(err.message || "Failed to render Mermaid diagram")
53+
if (renderVersion === renderVersionRef.current) {
54+
console.warn("Mermaid parse/render failed:", err)
55+
setError(err.message || "Failed to render Mermaid diagram")
56+
}
12657
})
12758
.finally(() => {
128-
setIsLoading(false)
59+
if (renderVersion === renderVersionRef.current) {
60+
setIsLoading(false)
61+
}
12962
})
13063
},
131-
500, // Delay 500ms
132-
[code], // Dependencies for scheduling
64+
500,
65+
[code, theme.signature],
13366
)
13467

13568
/**
@@ -225,6 +158,7 @@ export default function MermaidBlock({ code }: MermaidBlockProps) {
225158
}
226159

227160
async function svgToPng(svgEl: SVGElement): Promise<string> {
161+
const backgroundColor = getMermaidBackgroundColor()
228162
// Clone the SVG to avoid modifying the original
229163
const svgClone = svgEl.cloneNode(true) as SVGElement
230164

@@ -266,8 +200,7 @@ async function svgToPng(svgEl: SVGElement): Promise<string> {
266200
const ctx = canvas.getContext("2d")
267201
if (!ctx) return reject("Canvas context not available")
268202

269-
// Fill background with Mermaid's dark theme background color
270-
ctx.fillStyle = MERMAID_THEME.background
203+
ctx.fillStyle = backgroundColor
271204
ctx.fillRect(0, 0, canvas.width, canvas.height)
272205

273206
ctx.imageSmoothingEnabled = true
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
import { act, render, waitFor } from "@testing-library/react"
2+
import { beforeEach, describe, expect, it, vi } from "vitest"
3+
4+
import MermaidBlock from "../MermaidBlock"
5+
6+
const mermaidMocks = vi.hoisted(() => ({
7+
initialize: vi.fn(),
8+
parse: vi.fn(),
9+
renderDiagram: vi.fn(),
10+
}))
11+
12+
vi.mock("mermaid", () => ({
13+
default: {
14+
initialize: mermaidMocks.initialize,
15+
parse: mermaidMocks.parse,
16+
render: mermaidMocks.renderDiagram,
17+
},
18+
}))
19+
20+
vi.mock("@src/i18n/TranslationContext", () => ({
21+
useAppTranslation: () => ({ t: (key: string) => key }),
22+
}))
23+
24+
vi.mock("@src/utils/clipboard", () => ({
25+
useCopyToClipboard: () => ({ showCopyFeedback: false, copyWithFeedback: vi.fn() }),
26+
}))
27+
28+
vi.mock("@/components/common/MermaidButton", () => ({
29+
MermaidButton: ({ children }: { children: React.ReactNode }) => children,
30+
}))
31+
32+
describe("MermaidBlock", () => {
33+
beforeEach(() => {
34+
vi.clearAllMocks()
35+
document.body.className = "vscode-light"
36+
document.body.dataset.vscodeThemeId = "Default Light Modern"
37+
document.body.style.setProperty("--vscode-editor-background", "#ffffff")
38+
document.body.style.setProperty("--vscode-editor-foreground", "#333333")
39+
document.body.style.setProperty("--vscode-input-background", "#f3f3f3")
40+
document.body.style.setProperty("--vscode-input-border", "#717171")
41+
mermaidMocks.parse.mockResolvedValue({ diagramType: "flowchart-v2" })
42+
mermaidMocks.renderDiagram.mockResolvedValue({ svg: '<svg data-testid="rendered-diagram"></svg>' })
43+
})
44+
45+
it("rerenders an existing diagram when the host theme changes", async () => {
46+
const { getByTestId } = render(<MermaidBlock code="graph TD; A-->B" />)
47+
48+
await waitFor(() => expect(mermaidMocks.renderDiagram).toHaveBeenCalledTimes(1), { timeout: 1_500 })
49+
expect(getByTestId("rendered-diagram")).toBeInTheDocument()
50+
expect(mermaidMocks.initialize).toHaveBeenLastCalledWith(
51+
expect.objectContaining({ themeVariables: expect.objectContaining({ darkMode: false }) }),
52+
)
53+
54+
act(() => {
55+
document.body.className = "vscode-dark"
56+
document.body.dataset.vscodeThemeId = "Default Dark Modern"
57+
document.body.style.setProperty("--vscode-editor-background", "#1e1e1e")
58+
document.body.style.setProperty("--vscode-editor-foreground", "#d4d4d4")
59+
})
60+
61+
await waitFor(() => expect(mermaidMocks.renderDiagram).toHaveBeenCalledTimes(2), { timeout: 1_500 })
62+
expect(mermaidMocks.initialize).toHaveBeenLastCalledWith(
63+
expect.objectContaining({ themeVariables: expect.objectContaining({ darkMode: true }) }),
64+
)
65+
})
66+
67+
it("does not replace the current theme with a stale render", async () => {
68+
let resolveFirstRender!: (value: { svg: string }) => void
69+
mermaidMocks.renderDiagram
70+
.mockImplementationOnce(() => new Promise((resolve) => (resolveFirstRender = resolve)))
71+
.mockResolvedValueOnce({ svg: '<svg data-testid="dark-diagram"></svg>' })
72+
const { queryByTestId } = render(<MermaidBlock code="graph TD; A-->B" />)
73+
74+
await waitFor(() => expect(mermaidMocks.renderDiagram).toHaveBeenCalledTimes(1), { timeout: 1_500 })
75+
act(() => {
76+
document.body.className = "vscode-dark"
77+
document.body.dataset.vscodeThemeId = "Default Dark Modern"
78+
document.body.style.setProperty("--vscode-editor-background", "#1e1e1e")
79+
document.body.style.setProperty("--vscode-editor-foreground", "#d4d4d4")
80+
})
81+
82+
await waitFor(() => expect(mermaidMocks.renderDiagram).toHaveBeenCalledTimes(2), { timeout: 1_500 })
83+
await waitFor(() => expect(queryByTestId("dark-diagram")).toBeInTheDocument())
84+
await act(async () => resolveFirstRender({ svg: '<svg data-testid="stale-light-diagram"></svg>' }))
85+
86+
expect(queryByTestId("dark-diagram")).toBeInTheDocument()
87+
expect(queryByTestId("stale-light-diagram")).not.toBeInTheDocument()
88+
})
89+
})
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
import React from "react"
2+
3+
import { expect, test } from "../../../../playwright/coverage-fixture"
4+
import MermaidBlock from "../MermaidBlock"
5+
6+
const diagram = `gantt
7+
title Project plan
8+
dateFormat YYYY-MM-DD
9+
section Planning
10+
Define scope :done, scope, 2026-08-01, 3d
11+
section Delivery
12+
Ship release :active, release, after scope, 3d`
13+
14+
const themes = [
15+
{
16+
name: "dark",
17+
bodyClass: "vscode-dark",
18+
themeId: "Default Dark Modern",
19+
colors: {},
20+
},
21+
{
22+
name: "light",
23+
bodyClass: "vscode-light",
24+
themeId: "Default Light Modern",
25+
colors: {},
26+
},
27+
{
28+
name: "high-contrast",
29+
bodyClass: "vscode-high-contrast",
30+
themeId: "Default High Contrast",
31+
colors: {
32+
"--vscode-editor-background": "#000000",
33+
"--vscode-editor-foreground": "#ffffff",
34+
"--vscode-input-background": "#000000",
35+
"--vscode-input-border": "#ffffff",
36+
"--vscode-textLink-foreground": "#6fc3df",
37+
},
38+
},
39+
{
40+
name: "high-contrast-light",
41+
bodyClass: "vscode-high-contrast-light",
42+
themeId: "Default High Contrast Light",
43+
colors: {
44+
"--vscode-editor-background": "#ffffff",
45+
"--vscode-editor-foreground": "#000000",
46+
"--vscode-input-background": "#ffffff",
47+
"--vscode-input-border": "#000000",
48+
"--vscode-textLink-foreground": "#0044cc",
49+
},
50+
},
51+
] as const
52+
53+
for (const theme of themes) {
54+
test(`renders Mermaid sections in the VS Code ${theme.name} theme`, async ({ mount, page }) => {
55+
await page.evaluate(({ bodyClass, themeId, colors }) => {
56+
document.documentElement.className = bodyClass
57+
document.body.className = bodyClass
58+
document.body.dataset.vscodeThemeId = themeId
59+
for (const [property, value] of Object.entries(colors)) {
60+
document.body.style.setProperty(property, value)
61+
}
62+
}, theme)
63+
64+
const component = await mount(<MermaidBlock code={diagram} />)
65+
await expect(component.locator("svg")).toBeVisible({ timeout: 10_000 })
66+
67+
const contrastRatio = await component.locator("svg").evaluate((svg) => {
68+
const section = svg.querySelector(".section0")!
69+
const title = svg.querySelector(".sectionTitle0")!
70+
const sectionStyles = getComputedStyle(section)
71+
const titleStyles = getComputedStyle(title)
72+
const fill = sectionStyles.fill
73+
.match(/\d+(?:\.\d+)?/g)!
74+
.slice(0, 3)
75+
.map(Number)
76+
const foreground = titleStyles.fill
77+
.match(/\d+(?:\.\d+)?/g)!
78+
.slice(0, 3)
79+
.map(Number)
80+
const body = getComputedStyle(document.body)
81+
.backgroundColor.match(/\d+(?:\.\d+)?/g)!
82+
.slice(0, 3)
83+
.map(Number)
84+
const alpha = Number(sectionStyles.opacity) * Number(sectionStyles.fillOpacity)
85+
const background = fill.map((channel, index) => Math.round(channel * alpha + body[index] * (1 - alpha)))
86+
const luminance = (rgb: number[]) => {
87+
const channels = rgb.map((channel) => {
88+
const value = channel / 255
89+
return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4
90+
})
91+
return 0.2126 * channels[0] + 0.7152 * channels[1] + 0.0722 * channels[2]
92+
}
93+
const lighter = Math.max(luminance(background), luminance(foreground))
94+
const darker = Math.min(luminance(background), luminance(foreground))
95+
return (lighter + 0.05) / (darker + 0.05)
96+
})
97+
98+
expect(contrastRatio).toBeGreaterThanOrEqual(4.5)
99+
100+
await expect(component).toHaveScreenshot(`mermaid-gantt-${theme.name}.png`)
101+
})
102+
}
9.38 KB
Loading
9.57 KB
Loading
10.4 KB
Loading
9.72 KB
Loading

0 commit comments

Comments
 (0)