From cc5ff98e0d510c1923ad7cabc3e339f9cf0b570f Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Sat, 14 Dec 2024 13:43:05 +0800 Subject: Refactor markdown math render (#32831) Add more tests --- web_src/js/markup/math.ts | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) (limited to 'web_src/js') diff --git a/web_src/js/markup/math.ts b/web_src/js/markup/math.ts index 22a4de38e9..4777805e3c 100644 --- a/web_src/js/markup/math.ts +++ b/web_src/js/markup/math.ts @@ -1,8 +1,14 @@ import {displayError} from './common.ts'; -function targetElement(el: Element) { +function targetElement(el: Element): {target: Element, displayAsBlock: boolean} { // The target element is either the parent "code block with loading indicator", or itself - return el.closest('.code-block.is-loading') ?? el; + // It is designed to work for 2 cases (guaranteed by backend code): + // *
...
+ // * ... + return { + target: el.closest('.code-block.is-loading') ?? el, + displayAsBlock: el.classList.contains('display'), + }; } export async function renderMath(): Promise { @@ -19,7 +25,7 @@ export async function renderMath(): Promise { const MAX_EXPAND = 1000; for (const el of els) { - const target = targetElement(el); + const {target, displayAsBlock} = targetElement(el); if (target.hasAttribute('data-render-done')) continue; const source = el.textContent; @@ -27,16 +33,12 @@ export async function renderMath(): Promise { displayError(target, new Error(`Math source of ${source.length} characters exceeds the maximum allowed length of ${MAX_CHARS}.`)); continue; } - - const displayMode = el.classList.contains('display'); - const nodeName = displayMode ? 'p' : 'span'; - try { - const tempEl = document.createElement(nodeName); + const tempEl = document.createElement(displayAsBlock ? 'p' : 'span'); katex.render(source, tempEl, { maxSize: MAX_SIZE, maxExpand: MAX_EXPAND, - displayMode, + displayMode: displayAsBlock, // katex: true for display (block) mode, false for inline mode }); target.replaceWith(tempEl); } catch (error) { -- cgit v1.2.3