refactor: render highlight language (#38793)

Avoid CSS injection

More details are in the comment of CodeBlockAttributes
This commit is contained in:
wxiaoguang
2026-08-06 18:07:36 +08:00
committed by GitHub
parent 231ba1da19
commit 6ff3a65708
17 changed files with 112 additions and 56 deletions
+5 -4
View File
@@ -1,14 +1,15 @@
import {displayError} from './common.ts';
import {queryElems} from '../utils/dom.ts';
function targetElement(el: Element): {target: Element, displayAsBlock: boolean} {
function targetElement(elCode: Element): {target: Element, displayAsBlock: boolean} {
// The target element is either the parent "code block with loading indicator", or itself
// It is designed to work for 2 cases (guaranteed by backend code):
// * <pre class="code-block is-loading"><code class="language-math display">...</code></pre>
// * <pre class="code-block"><code class="language-math">...</code></pre>
// * <code class="language-math">...</code>
const elPre = elCode.parentElement?.matches('pre.code-block') ? elCode.parentElement : null;
return {
target: el.closest('.code-block.is-loading') ?? el,
displayAsBlock: el.classList.contains('display'),
target: elPre ?? elCode,
displayAsBlock: elPre !== null,
};
}
+2 -2
View File
@@ -156,11 +156,11 @@ let elkLayoutsRegistered = false;
export async function initMarkupCodeMermaid(elMarkup: HTMLElement): Promise<void> {
// .markup code.language-mermaid
const mermaidBlocks: Array<{source: string, parentContainer: HTMLElement}> = [];
const mermaidBlocks: Array<{source: string, parentContainer: Element}> = [];
const attrMermaidRendered = 'data-markup-mermaid-rendered';
let needElkRender = false;
for (const elCodeBlock of queryElems(elMarkup, 'code.language-mermaid')) {
const parentContainer = elCodeBlock.closest('pre')!; // it must exist, if no, there must be a bug
const parentContainer = elCodeBlock.closest('pre.code-block')!; // it must exist, if no, there must be a bug
if (parentContainer.hasAttribute(attrMermaidRendered)) continue;
parentContainer.setAttribute(attrMermaidRendered, 'true');