Skip to content

fix(frontend): resolve mermaid label text clipping caused by global CSS pollution - #735

Merged
unhappychoice merged 1 commit into
unhappychoice:mainfrom
ming2k:polish-mermaid
May 24, 2026
Merged

unhappychoice merged 1 commit into
unhappychoice:mainfrom
ming2k:polish-mermaid

Conversation

@ming2k

@ming2k ming2k commented May 23, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • MUI CssBaseline
  • Dynamic document.documentElement.style.fontSize
  • Markdown container fontFamily inheritance

This caused text metrics inside foreignObjects to differ from what Mermaid computed during layout, resulting in:

  • Bottom line of node labels being clipped / hidden
  • Edge labels appearing cramped / too close to their background rect
  • Vertical text offset within label containers

Solution

  1. Pass configured fontFamily from the Redux store to mermaid.initialize(), so Mermaid measures text with the same font that will actually be used for rendering.
  2. Wait for font loading with document.fonts.ready before calling mermaid.render(), preventing measurement against fallback fonts.
  3. Scope CSS resets using MUI styled() to isolate mermaid containers from global typography styles:
    • Reset margin, padding, line-height on foreignObject children
    • Set overflow: visible on foreignObject to tolerate slight measurement deviations
    • Add subtle rx/ry rounding to edge label backgrounds
  4. Add flowchart.useMaxWidth: true so SVG scales responsively within its container.

Changes

File Change
MermaidRenderer.tsx Add fontFamily, font loading wait, styled() container with scoped CSS, useMaxWidth
MermaidRenderer.test.tsx Mock document.fonts, update initialize assertions
*.snap Snapshot updates

Testing

cd packages/frontend
npm test -- --testPathPatterns="MermaidRenderer|MarkdownCode"

Summary by CodeRabbit

  • Bug Fixes

    • Improved Mermaid diagram text rendering accuracy by waiting for font loading completion.
  • Style

    • Enhanced diagram styling with improved CSS scoping for better visual consistency.
    • Diagram rendering now applies application-configured font settings.
  • Tests

    • Updated test suite to verify font configuration and rendering behavior.

Review Change Stack

…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
@ming2k
ming2k requested a review from unhappychoice as a code owner May 23, 2026 20:04
@netlify

netlify Bot commented May 23, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for mdts-unhappychoice ready!

Name Link
🔨 Latest commit 1dd7418
🔍 Latest deploy log https://app.netlify.com/projects/mdts-unhappychoice/deploys/6a1208577b9c170008c6c81b
😎 Deploy Preview https://deploy-preview-735--mdts-unhappychoice.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai

coderabbitai Bot commented May 23, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

MermaidRenderer now retrieves fontFamily from Redux config state and passes it to mermaid.initialize. Rendering waits for document.fonts.ready when available before calling mermaid.render to improve text measurement accuracy. SVG output is wrapped in a styled MermaidContainer that scopes CSS resets to Mermaid-generated <foreignObject> content. Tests mock Redux selectors and font readiness to validate these changes.

Changes

Mermaid rendering with font config and CSS scoping

Layer / File(s) Summary
Redux config integration and MermaidContainer styling
packages/frontend/src/components/Content/MarkdownContent/MarkdownRenderer/MermaidRenderer.tsx
useSelector hook reads fontFamily from RootState.config; new MermaidContainer styled component wraps SVG output and scopes CSS resets to <foreignObject> content with adjusted edge label background styling.
Mermaid rendering with font initialization
packages/frontend/src/components/Content/MarkdownContent/MarkdownRenderer/MermaidRenderer.tsx
useEffect refactored to early-return when chart is empty, await document.fonts.ready when available, and extend mermaid.initialize with fontFamily and flowchart/htmlLabels options; dependency list includes fontFamily.
SVG output wrapping in MermaidContainer
packages/frontend/src/components/Content/MarkdownContent/MarkdownRenderer/MermaidRenderer.tsx
Render return statement wraps SVG output in MermaidContainer instead of plain div; raw chart returned when SVG is absent.
Test mocks and updated assertions
packages/frontend/test/unit/components/Content/MarkdownContent/MarkdownRenderer/MermaidRenderer.test.tsx
Test setup mocks Redux useSelector to provide deterministic config.fontFamily and document.fonts.ready to resolve immediately; mermaid.initialize assertions updated to expect fontFamily and flowchart options for both light and dark modes.

🐰 Fonts now wait their turn with grace,
Redux brings config to the rendering space,
MermaidContainer holds the styled design,
Tests validate that everything aligns,
Diagrams now render with timing so fine! ✨

🎯 3 (Moderate) | ⏱️ ~25 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly addresses the main problem being fixed: mermaid label text clipping caused by CSS pollution, which aligns with the core objective to scope CSS resets and resolve text measurement mismatches.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

packages/frontend/src/components/Content/MarkdownContent/MarkdownRenderer/MermaidRenderer.tsx

ESLint 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.tsx

ESLint 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/frontend/test/unit/components/Content/MarkdownContent/MarkdownRenderer/MermaidRenderer.test.tsx (1)

116-124: ⚡ Quick win

Add a rerender test for non-empty → empty chart transition.

Current coverage only checks initial empty input. Add a transition case to catch stale-SVG regressions when chart becomes 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

📥 Commits

Reviewing files that changed from the base of the PR and between 4b9480d and 1dd7418.

⛔ Files ignored due to path filters (2)
  • packages/frontend/test/unit/components/Content/MarkdownContent/MarkdownRenderer/__snapshots__/MarkdownCode.test.tsx.snap is excluded by !**/*.snap
  • packages/frontend/test/unit/components/Content/MarkdownContent/MarkdownRenderer/__snapshots__/MermaidRenderer.test.tsx.snap is excluded by !**/*.snap
📒 Files selected for processing (2)
  • packages/frontend/src/components/Content/MarkdownContent/MarkdownRenderer/MermaidRenderer.tsx
  • packages/frontend/test/unit/components/Content/MarkdownContent/MarkdownRenderer/MermaidRenderer.test.tsx

Comment on lines +50 to +82
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]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 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.

  • useEffect returns early when !chart (lines 50-52) without clearing svg, so a previously rendered diagram can remain visible when chart becomes empty.
  • renderMermaid is async with no cancellation/ordering guard; if chart/theme changes or the component unmounts while awaiting mermaid.render, a stale render can still call setSvg and 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

codecov Bot commented May 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.35%. Comparing base (4b9480d) to head (1dd7418).

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           
Flag Coverage Δ
frontend 99.34% <100.00%> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@unhappychoice unhappychoice left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@unhappychoice
unhappychoice merged commit 56ad96d into unhappychoice:main May 24, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants