Skip to content

Commit 1dd7418

Browse files
committed
fix(frontend): resolve mermaid label text clipping caused by global CSS 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
1 parent 4b9480d commit 1dd7418

4 files changed

Lines changed: 111 additions & 22 deletions

File tree

Lines changed: 73 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,43 +1,96 @@
11
import React, { useEffect, useState } from 'react';
22
import mermaid from 'mermaid';
33
import { useTheme } from '@mui/material';
4+
import { useSelector } from 'react-redux';
5+
import { styled } from '@mui/material/styles';
6+
import { RootState } from '../../../../store/store';
47

58
interface MermaidProps {
69
chart: string;
710
}
811

12+
/**
13+
* Styled container that isolates mermaid SVG from global CSS pollution.
14+
*
15+
* Mermaid flowcharts render labels inside SVG <foreignObject> elements,
16+
* which contain standard HTML (e.g. <p>, <div>). These elements are
17+
* vulnerable to global typography styles (margins, line-height, etc.).
18+
*
19+
* We use scoped CSS via MUI styled() to reset only the elements inside
20+
* the mermaid wrapper, without affecting the rest of the page.
21+
*/
22+
const MermaidContainer = styled('div')({
23+
overflow: 'visible',
24+
maxWidth: '100%',
25+
// Allow foreignObject content to overflow its boundary when mermaid's
26+
// size calculation is slightly off.
27+
'& foreignObject': {
28+
overflow: 'visible',
29+
},
30+
// Reset global CSS pollution inside foreignObject (e.g. MUI CssBaseline,
31+
// markdown typography) so that text metrics match what mermaid computed.
32+
'& foreignObject p, & foreignObject div, & foreignObject span': {
33+
margin: 0,
34+
padding: 0,
35+
lineHeight: 1.5,
36+
},
37+
// Slightly round the edge-label background rect for visual polish.
38+
'& .edgeLabel .labelBkg': {
39+
rx: 4,
40+
ry: 4,
41+
},
42+
});
43+
944
const MermaidRenderer: React.FC<MermaidProps> = ({ chart }) => {
1045
const [svg, setSvg] = useState<string | null>(null);
1146
const theme = useTheme();
47+
const { fontFamily } = useSelector((state: RootState) => state.config);
1248

1349
useEffect(() => {
14-
if (chart) {
15-
mermaid.initialize({
16-
startOnLoad: false,
17-
theme: theme.palette.mode === 'dark' ? 'dark' : 'neutral',
18-
securityLevel: 'loose',
19-
});
20-
21-
const renderMermaid = async () => {
22-
try {
23-
const id = `mermaid-div-${Math.random().toString(36).substring(2, 9)}`;
24-
const { svg } = await mermaid.render(id, chart);
25-
setSvg(svg);
26-
} catch (error) {
27-
console.error('Error rendering mermaid chart:', error);
28-
setSvg(null);
50+
if (!chart) {
51+
return;
52+
}
53+
54+
const renderMermaid = async () => {
55+
try {
56+
// Wait for fonts to load before rendering to ensure accurate text measurement
57+
if (document.fonts) {
58+
await document.fonts.ready;
2959
}
30-
};
3160

32-
renderMermaid();
33-
}
34-
}, [chart, theme.palette.mode]);
61+
mermaid.initialize({
62+
startOnLoad: false,
63+
theme: theme.palette.mode === 'dark' ? 'dark' : 'neutral',
64+
securityLevel: 'loose',
65+
fontFamily: fontFamily || 'inherit',
66+
flowchart: {
67+
useMaxWidth: true,
68+
htmlLabels: true,
69+
},
70+
});
71+
72+
const id = `mermaid-div-${Math.random().toString(36).substring(2, 9)}`;
73+
const { svg } = await mermaid.render(id, chart);
74+
setSvg(svg);
75+
} catch (error) {
76+
console.error('Error rendering mermaid chart:', error);
77+
setSvg(null);
78+
}
79+
};
80+
81+
renderMermaid();
82+
}, [chart, theme.palette.mode, fontFamily]);
3583

3684
if (!svg) {
3785
return <pre><code>{chart}</code></pre>;
3886
}
3987

40-
return <div dangerouslySetInnerHTML={{ __html: svg }} />;
88+
return (
89+
<MermaidContainer
90+
className="mermaid-wrapper"
91+
dangerouslySetInnerHTML={{ __html: svg }}
92+
/>
93+
);
4194
};
4295

4396
export default MermaidRenderer;

‎packages/frontend/test/unit/components/Content/MarkdownContent/MarkdownRenderer/MermaidRenderer.test.tsx‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,28 @@ jest.mock('mermaid', () => ({
1212
}),
1313
}));
1414

15+
// Mock react-redux
16+
jest.mock('react-redux', () => ({
17+
...jest.requireActual('react-redux'),
18+
useSelector: jest.fn((selector) => {
19+
// Provide a minimal mock state that satisfies the fontFamily selector
20+
const mockState = {
21+
config: {
22+
fontFamily: 'MockFont, sans-serif',
23+
},
24+
};
25+
return selector(mockState);
26+
}),
27+
}));
28+
29+
// Mock document.fonts.ready for font loading
30+
Object.defineProperty(document, 'fonts', {
31+
value: {
32+
ready: Promise.resolve(),
33+
},
34+
writable: true,
35+
});
36+
1537
const renderWithTheme = async (component: React.ReactElement, themeMode: 'light' | 'dark' = 'light') => {
1638
const theme = createTheme({
1739
palette: {
@@ -46,6 +68,11 @@ describe('Mermaid', () => {
4668
startOnLoad: false,
4769
theme: 'neutral',
4870
securityLevel: 'loose',
71+
fontFamily: 'MockFont, sans-serif',
72+
flowchart: {
73+
useMaxWidth: true,
74+
htmlLabels: true,
75+
},
4976
});
5077
});
5178

@@ -55,6 +82,11 @@ describe('Mermaid', () => {
5582
startOnLoad: false,
5683
theme: 'dark',
5784
securityLevel: 'loose',
85+
fontFamily: 'MockFont, sans-serif',
86+
flowchart: {
87+
useMaxWidth: true,
88+
htmlLabels: true,
89+
},
5890
});
5991
});
6092

‎packages/frontend/test/unit/components/Content/MarkdownContent/MarkdownRenderer/__snapshots__/MarkdownCode.test.tsx.snap‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,9 @@ exports[`MarkdownCode should render inline code correctly 1`] = `
2020

2121
exports[`MarkdownCode should render mermaid chart correctly 1`] = `
2222
<DocumentFragment>
23-
<div>
23+
<div
24+
class="mermaid-wrapper css-1c8xupo"
25+
>
2426
<svg />
2527
</div>
2628
</DocumentFragment>

‎packages/frontend/test/unit/components/Content/MarkdownContent/MarkdownRenderer/__snapshots__/MermaidRenderer.test.tsx.snap‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@
22

33
exports[`Mermaid should initialize mermaid with correct theme based on light mode 1`] = `
44
<DocumentFragment>
5-
<div>
5+
<div
6+
class="mermaid-wrapper css-1c8xupo"
7+
>
68
<svg
79
data-testid="mermaid-svg"
810
>

0 commit comments

Comments
 (0)