Repository navigation
fix(frontend): resolve mermaid label text clipping caused by global CSS pollution - #735
Conversation
…SS pollution Mermaid flowcharts render labels inside SVG <foreignObject> elements with standard HTML content (<p>, <div>, <span>). These elements were being affected by global typography styles (MUI CssBaseline, dynamic root fontSize, markdown fontFamily inheritance), causing text metrics to differ from what Mermaid computed during layout. This resulted in: - Bottom line of node labels being clipped/hidden - Edge labels appearing cramped against their background rects - Vertical text offset within label containers Changes: - Pass configured fontFamily from Redux store to mermaid.initialize() - Wait for document.fonts.ready before rendering - Use MUI styled() to scope CSS resets inside mermaid containers: - Reset margin/padding/line-height on foreignObject children - Allow foreignObject overflow: visible for slight deviations - Add flowchart.useMaxWidth: true for responsive sizing - Update tests and snapshots
✅ Deploy Preview for mdts-unhappychoice ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
📝 WalkthroughWalkthroughMermaidRenderer now retrieves ChangesMermaid rendering with font config and CSS scoping
🎯 3 (Moderate) | ⏱️ ~25 minutes 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 ESLint
packages/frontend/src/components/Content/MarkdownContent/MarkdownRenderer/MermaidRenderer.tsxESLint skipped: missing config or dependency (missing-dependency). The ESLint configuration references a package that is not available in the sandbox. packages/frontend/test/unit/components/Content/MarkdownContent/MarkdownRenderer/MermaidRenderer.test.tsxESLint skipped: the ESLint configuration for this file references a package that is not available in the sandbox. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/frontend/test/unit/components/Content/MarkdownContent/MarkdownRenderer/MermaidRenderer.test.tsx (1)
116-124: ⚡ Quick winAdd a rerender test for non-empty → empty
charttransition.Current coverage only checks initial empty input. Add a transition case to catch stale-SVG regressions when
chartbecomes empty after a successful render.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/frontend/test/unit/components/Content/MarkdownContent/MarkdownRenderer/MermaidRenderer.test.tsx` around lines 116 - 124, Add a test in the MermaidRenderer suite that first renders <MermaidRenderer chart="some valid mermaid source" /> (using renderWithTheme) and asserts mermaid.initialize/mermaid.render were called and screen.getByTestId('mermaid-svg') exists, then call the returned rerender with <MermaidRenderer chart="" /> and assert the component removes the SVG (screen.queryByTestId('mermaid-svg') is null) and that no new mermaid.render/initialize calls occur; reference MermaidRenderer, mermaid.initialize, mermaid.render, renderWithTheme, and rerender to locate where to add this transition test.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In
`@packages/frontend/src/components/Content/MarkdownContent/MarkdownRenderer/MermaidRenderer.tsx`:
- Around line 50-82: The effect currently returns early on !chart without
clearing svg and allows stale async renders to call setSvg; update the useEffect
handling so that when chart is falsy you call setSvg(null) before returning, and
add a cancellation/ordering guard for renderMermaid: introduce a
renderIdRef/useRef counter (or an isMounted boolean) that you increment/assign
at the start of each render in renderMermaid, capture the local id, then after
awaiting mermaid.render only call setSvg(svg) if the local id matches
renderIdRef.current and the component is still mounted; also reset or mark
cancelled in the effect cleanup to prevent async completion from overwriting
newer renders or setting state after unmount (references: useEffect,
renderMermaid, setSvg, mermaid.render, svg).
---
Nitpick comments:
In
`@packages/frontend/test/unit/components/Content/MarkdownContent/MarkdownRenderer/MermaidRenderer.test.tsx`:
- Around line 116-124: Add a test in the MermaidRenderer suite that first
renders <MermaidRenderer chart="some valid mermaid source" /> (using
renderWithTheme) and asserts mermaid.initialize/mermaid.render were called and
screen.getByTestId('mermaid-svg') exists, then call the returned rerender with
<MermaidRenderer chart="" /> and assert the component removes the SVG
(screen.queryByTestId('mermaid-svg') is null) and that no new
mermaid.render/initialize calls occur; reference MermaidRenderer,
mermaid.initialize, mermaid.render, renderWithTheme, and rerender to locate
where to add this transition test.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 1f0b710c-4b69-41d5-923b-ffe1175cc971
⛔ Files ignored due to path filters (2)
packages/frontend/test/unit/components/Content/MarkdownContent/MarkdownRenderer/__snapshots__/MarkdownCode.test.tsx.snapis excluded by!**/*.snappackages/frontend/test/unit/components/Content/MarkdownContent/MarkdownRenderer/__snapshots__/MermaidRenderer.test.tsx.snapis excluded by!**/*.snap
📒 Files selected for processing (2)
packages/frontend/src/components/Content/MarkdownContent/MarkdownRenderer/MermaidRenderer.tsxpackages/frontend/test/unit/components/Content/MarkdownContent/MarkdownRenderer/MermaidRenderer.test.tsx
| if (!chart) { | ||
| return; | ||
| } | ||
|
|
||
| const renderMermaid = async () => { | ||
| try { | ||
| // Wait for fonts to load before rendering to ensure accurate text measurement | ||
| if (document.fonts) { | ||
| await document.fonts.ready; | ||
| } | ||
| }; | ||
|
|
||
| renderMermaid(); | ||
| } | ||
| }, [chart, theme.palette.mode]); | ||
| mermaid.initialize({ | ||
| startOnLoad: false, | ||
| theme: theme.palette.mode === 'dark' ? 'dark' : 'neutral', | ||
| securityLevel: 'loose', | ||
| fontFamily: fontFamily || 'inherit', | ||
| flowchart: { | ||
| useMaxWidth: true, | ||
| htmlLabels: true, | ||
| }, | ||
| }); | ||
|
|
||
| const id = `mermaid-div-${Math.random().toString(36).substring(2, 9)}`; | ||
| const { svg } = await mermaid.render(id, chart); | ||
| setSvg(svg); | ||
| } catch (error) { | ||
| console.error('Error rendering mermaid chart:', error); | ||
| setSvg(null); | ||
| } | ||
| }; | ||
|
|
||
| renderMermaid(); | ||
| }, [chart, theme.palette.mode, fontFamily]); |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE="packages/frontend/src/components/Content/MarkdownContent/MarkdownRenderer/MermaidRenderer.tsx"
echo "=== File: $FILE ==="
ls -l "$FILE" || true
echo
echo "=== Lines 1-220 ==="
nl -ba "$FILE" | sed -n '1,220p'Repository: unhappychoice/mdts
Length of output: 396
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE="packages/frontend/src/components/Content/MarkdownContent/MarkdownRenderer/MermaidRenderer.tsx"
echo "=== File: $FILE ==="
wc -l "$FILE" || true
echo
echo "=== Lines 1-220 ==="
cat -n "$FILE" | sed -n '1,220p'Repository: unhappychoice/mdts
Length of output: 3767
Reset stale SVG and guard async race in Mermaid render effect.
useEffectreturns early when!chart(lines 50-52) without clearingsvg, so a previously rendered diagram can remain visible whenchartbecomes empty.renderMermaidis async with no cancellation/ordering guard; ifchart/themechanges or the component unmounts while awaitingmermaid.render, a stale render can still callsetSvgand overwrite the latest output.
Suggested fix
useEffect(() => {
- if (!chart) {
- return;
- }
+ let cancelled = false;
+
+ if (!chart) {
+ setSvg(null);
+ return () => {
+ cancelled = true;
+ };
+ }
const renderMermaid = async () => {
try {
// Wait for fonts to load before rendering to ensure accurate text measurement
- if (document.fonts) {
+ if (document.fonts?.ready) {
await document.fonts.ready;
}
mermaid.initialize({
startOnLoad: false,
theme: theme.palette.mode === 'dark' ? 'dark' : 'neutral',
securityLevel: 'loose',
fontFamily: fontFamily || 'inherit',
flowchart: {
useMaxWidth: true,
htmlLabels: true,
},
});
const id = `mermaid-div-${Math.random().toString(36).substring(2, 9)}`;
- const { svg } = await mermaid.render(id, chart);
- setSvg(svg);
+ const { svg: renderedSvg } = await mermaid.render(id, chart);
+ if (!cancelled) {
+ setSvg(renderedSvg);
+ }
} catch (error) {
- console.error('Error rendering mermaid chart:', error);
- setSvg(null);
+ if (!cancelled) {
+ console.error('Error rendering mermaid chart:', error);
+ setSvg(null);
+ }
}
};
+ setSvg(null);
renderMermaid();
+
+ return () => {
+ cancelled = true;
+ };
}, [chart, theme.palette.mode, fontFamily]);🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@packages/frontend/src/components/Content/MarkdownContent/MarkdownRenderer/MermaidRenderer.tsx`
around lines 50 - 82, The effect currently returns early on !chart without
clearing svg and allows stale async renders to call setSvg; update the useEffect
handling so that when chart is falsy you call setSvg(null) before returning, and
add a cancellation/ordering guard for renderMermaid: introduce a
renderIdRef/useRef counter (or an isMounted boolean) that you increment/assign
at the start of each render in renderMermaid, capture the local id, then after
awaiting mermaid.render only call setSvg(svg) if the local id matches
renderIdRef.current and the component is still mounted; also reset or mark
cancelled in the effect cleanup to prevent async completion from overwriting
newer renders or setting state after unmount (references: useEffect,
renderMermaid, setSvg, mermaid.render, svg).
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #735 +/- ##
=======================================
Coverage 99.34% 99.35%
=======================================
Files 69 69
Lines 1537 1543 +6
Branches 371 374 +3
=======================================
+ Hits 1527 1533 +6
Misses 9 9
Partials 1 1
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
Problem
Mermaid flowchart labels are rendered inside SVG
<foreignObject>elements containing standard HTML (<p>,<div>,<span>). These elements are vulnerable to global CSS pollution from:CssBaselinedocument.documentElement.style.fontSizefontFamilyinheritanceThis caused text metrics inside foreignObjects to differ from what Mermaid computed during layout, resulting in:
Solution
fontFamilyfrom the Redux store tomermaid.initialize(), so Mermaid measures text with the same font that will actually be used for rendering.document.fonts.readybefore callingmermaid.render(), preventing measurement against fallback fonts.styled()to isolate mermaid containers from global typography styles:margin,padding,line-heightonforeignObjectchildrenoverflow: visibleonforeignObjectto tolerate slight measurement deviationsrx/ryrounding to edge label backgroundsflowchart.useMaxWidth: trueso SVG scales responsively within its container.Changes
MermaidRenderer.tsxMermaidRenderer.test.tsxdocument.fonts, update initialize assertions*.snapTesting
Summary by CodeRabbit
Bug Fixes
Style
Tests