From 8207086d5f8756774aa460895dd75e11dc97deb8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9gis=20Hanol?= Date: Mon, 20 Jan 2025 20:26:43 +0100 Subject: [PATCH] FIX: supports quoting mathjax (#30876) This will properly extract the text used to generate mathjax expression (both inline and block display modes) as well as remove all the cruft that mathjax is adding in the DOM. Internal ref - t/135307 --- .../discourse/app/lib/to-markdown.js | 28 ++++++++++++++++++- .../tests/unit/lib/to-markdown-test.js | 24 ++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/app/assets/javascripts/discourse/app/lib/to-markdown.js b/app/assets/javascripts/discourse/app/lib/to-markdown.js index e3fdc370b74..3cb8dab4969 100644 --- a/app/assets/javascripts/discourse/app/lib/to-markdown.js +++ b/app/assets/javascripts/discourse/app/lib/to-markdown.js @@ -87,7 +87,6 @@ export class Tag { "address", "article", "dd", - "div", "dl", "dt", "fieldset", @@ -187,6 +186,24 @@ export class Tag { }; } + static div() { + return class extends Tag.block("div") { + decorate(text) { + const attr = this.element.attributes; + + if (/\bmathjax-math\b/.test(attr.class)) { + return ""; + } + + if (/\bmath\b/.test(attr.class) && attr["data-applied-mathjax"]) { + return "\n$$\n" + text + "\n$$\n"; + } + + return super.decorate(text); + } + }; + } + static aside() { return class extends Tag.block("aside") { constructor() { @@ -292,6 +309,14 @@ export class Tag { return ""; } + if (/\bmathjax-math\b/.test(attr.class)) { + return ""; + } + + if (/\bmath\b/.test(attr.class) && attr["data-applied-mathjax"]) { + return "$" + text + "$"; + } + return super.decorate(text); } }; @@ -689,6 +714,7 @@ function tagByName(name) { Tag.ol(), Tag.list("ul"), Tag.span(), + Tag.div(), ]; for (const tag of allTags) { diff --git a/app/assets/javascripts/discourse/tests/unit/lib/to-markdown-test.js b/app/assets/javascripts/discourse/tests/unit/lib/to-markdown-test.js index b1058300586..b008697c133 100644 --- a/app/assets/javascripts/discourse/tests/unit/lib/to-markdown-test.js +++ b/app/assets/javascripts/discourse/tests/unit/lib/to-markdown-test.js @@ -527,4 +527,28 @@ test2 assert.strictEqual(toMarkdown(html), "[quiet]hey\nthere[/quiet]"); }); + + test("converts inline mathjax", function (assert) { + const html = `

Lorem ipsum E=mc2 dolor sit amet.

`; + const markdown = `Lorem ipsum $E=mc^2$ dolor sit amet.`; + assert.strictEqual(toMarkdown(html), markdown); + }); + + test("converts block mathjax", function (assert) { + const html = `

Before

+
(1)23π
+

After

`; + + const markdown = `Before + +$$ +\\sqrt{(-1)} \\; 2^3 \\; \\sum \\; \\pi +$$ + +After`; + + assert.strictEqual(toMarkdown(html), markdown); + }); });