From 31eb2fbf3e11881ccedc87232983597dcbedefaa Mon Sep 17 00:00:00 2001 From: omkarht Date: Fri, 28 Nov 2025 17:14:22 +0530 Subject: [PATCH] 7194 : fix for markdown processing to KaTeX text to preserve newlines on-behalf-of: @Mermaid-Chart --- cypress/integration/rendering/katex.spec.js | 66 +++++++++++++++++++ .../mermaid/src/rendering-util/createText.ts | 4 +- 2 files changed, 69 insertions(+), 1 deletion(-) diff --git a/cypress/integration/rendering/katex.spec.js b/cypress/integration/rendering/katex.spec.js index fb1d13392..1baa0f465 100644 --- a/cypress/integration/rendering/katex.spec.js +++ b/cypress/integration/rendering/katex.spec.js @@ -33,4 +33,70 @@ describe('Katex', () => { // { fontFamily: 'courier' } // ); // }); + + describe('Katex with newlines (issue #7194)', () => { + it('5: should render newlines in plain text nodes with math', () => { + imgSnapshotTest( + `graph TD + plainmath["line 0 + line 1 + $$x=42$$ + line 2"]`, + { fontFamily: 'courier' } + ); + }); + + it('6: should render newlines in markdown nodes with math', () => { + imgSnapshotTest( + `graph TD + markdownmath["\`line 0 + line 1 + $$x=42$$ + line 2\`"]`, + { fontFamily: 'courier' } + ); + }); + + it('7: should render multiple math equations with newlines between them', () => { + imgSnapshotTest( + `graph TD + multimath["$$a=1$$ + text between + $$b=2$$"]`, + { fontFamily: 'courier' } + ); + }); + + it('8: should render newlines before and after math in markdown', () => { + imgSnapshotTest( + `graph TD + beforeafter["\`line before + $$x=42$$ + line after\`"]`, + { fontFamily: 'courier' } + ); + }); + + it('9: should render complex example with multiple nodes containing math and newlines', () => { + imgSnapshotTest( + `graph TD + plain["line 0 + line 1"] + markdown["\`line 0 + line 1\`"] + plainmath["line 0 + line 1 + $$x=42$$ + line 2"] + markdownmath["\`line 0 + line 1 + $$x=42$$ + \`"] + plain --> markdown + markdown --> plainmath + plainmath --> markdownmath`, + { fontFamily: 'courier' } + ); + }); + }); }); diff --git a/packages/mermaid/src/rendering-util/createText.ts b/packages/mermaid/src/rendering-util/createText.ts index 759330390..3abf904bc 100644 --- a/packages/mermaid/src/rendering-util/createText.ts +++ b/packages/mermaid/src/rendering-util/createText.ts @@ -248,7 +248,9 @@ export const createText = async ( const decodedReplacedText = await replaceIconSubstring(decodeEntities(htmlText), config); //for Katex the text could contain escaped characters, \\relax that should be transformed to \relax - const inputForKatex = text.replace(/\\\\/g, '\\'); + const inputForKatex = hasKatex(text) + ? markdownToHTML(text.replace(/\\\\/g, '\\'), config) + : text.replace(/\\\\/g, '\\'); const node = { isNode,