Skip to content

Commit 1702939

Browse files
ServeurpersoCompwilkin
authored andcommitted
fix: add remark plugin to render raw HTML as literal text (ggml-org#16505)
* fix: add remark plugin to render raw HTML as literal text Implemented a missing MDAST stage to neutralize raw HTML like major LLM WebUIs do ensuring consistent and safe Markdown rendering Introduced 'remarkLiteralHtml', a plugin that converts raw HTML nodes in the Markdown AST into plain-text equivalents while preserving indentation and line breaks. This ensures consistent rendering and prevents unintended HTML execution, without altering valid Markdown structure Kept 'remarkRehype' in the pipeline since it performs the required conversion from MDAST to HAST for KaTeX, syntax highlighting, and HTML serialization Refined the link-enhancement logic to skip unnecessary DOM rewrites, fixing a subtle bug where extra paragraphs were injected after the first line due to full innerHTML reconstruction, and ensuring links open in new tabs only when required Final pipeline: remarkGfm -> remarkMath -> remarkBreaks -> remarkLiteralHtml -> remarkRehype -> rehypeKatex -> rehypeHighlight -> rehypeStringify * fix: address review feedback from allozaur * chore: update webui build output
1 parent f21f48a commit 1702939

File tree

6 files changed

+235
-4
lines changed

6 files changed

+235
-4
lines changed

tools/server/public/index.html.gz

451 Bytes
Binary file not shown.

tools/server/webui/package-lock.json

Lines changed: 69 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

tools/server/webui/package.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@
5252
"eslint-plugin-svelte": "^3.0.0",
5353
"fflate": "^0.8.2",
5454
"globals": "^16.0.0",
55+
"mdast": "^3.0.0",
5556
"mdsvex": "^0.12.3",
5657
"playwright": "^1.53.0",
5758
"prettier": "^3.4.2",
@@ -68,6 +69,7 @@
6869
"tw-animate-css": "^1.3.5",
6970
"typescript": "^5.0.0",
7071
"typescript-eslint": "^8.20.0",
72+
"unified": "^11.0.5",
7173
"uuid": "^13.0.0",
7274
"vite": "^7.0.4",
7375
"vite-plugin-devtools-json": "^0.2.0",

tools/server/webui/src/lib/components/app/misc/MarkdownContent.svelte

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import githubDarkCss from 'highlight.js/styles/github-dark.css?inline';
1515
import githubLightCss from 'highlight.js/styles/github.css?inline';
1616
import { mode } from 'mode-watcher';
17+
import { remarkLiteralHtml } from '$lib/markdown/literal-html';
1718
1819
interface Props {
1920
content: string;
@@ -50,36 +51,59 @@
5051
.use(remarkGfm) // GitHub Flavored Markdown
5152
.use(remarkMath) // Parse $inline$ and $$block$$ math
5253
.use(remarkBreaks) // Convert line breaks to <br>
53-
.use(remarkRehype) // Convert to rehype (HTML AST)
54+
.use(remarkLiteralHtml) // Treat raw HTML as literal text with preserved indentation
55+
.use(remarkRehype) // Convert Markdown AST to rehype
5456
.use(rehypeKatex) // Render math using KaTeX
5557
.use(rehypeHighlight) // Add syntax highlighting
5658
.use(rehypeStringify); // Convert to HTML string
5759
});
5860
5961
function enhanceLinks(html: string): string {
62+
if (!html.includes('<a')) {
63+
return html;
64+
}
65+
6066
const tempDiv = document.createElement('div');
6167
tempDiv.innerHTML = html;
6268
6369
// Make all links open in new tabs
6470
const linkElements = tempDiv.querySelectorAll('a[href]');
71+
let mutated = false;
72+
6573
for (const link of linkElements) {
74+
const target = link.getAttribute('target');
75+
const rel = link.getAttribute('rel');
76+
77+
if (target !== '_blank' || rel !== 'noopener noreferrer') {
78+
mutated = true;
79+
}
80+
6681
link.setAttribute('target', '_blank');
6782
link.setAttribute('rel', 'noopener noreferrer');
6883
}
6984
70-
return tempDiv.innerHTML;
85+
return mutated ? tempDiv.innerHTML : html;
7186
}
7287
7388
function enhanceCodeBlocks(html: string): string {
89+
if (!html.includes('<pre')) {
90+
return html;
91+
}
92+
7493
const tempDiv = document.createElement('div');
7594
tempDiv.innerHTML = html;
7695
7796
const preElements = tempDiv.querySelectorAll('pre');
97+
let mutated = false;
7898
7999
for (const [index, pre] of Array.from(preElements).entries()) {
80100
const codeElement = pre.querySelector('code');
81101
82-
if (!codeElement) continue;
102+
if (!codeElement) {
103+
continue;
104+
}
105+
106+
mutated = true;
83107
84108
let language = 'text';
85109
const classList = Array.from(codeElement.classList);
@@ -127,7 +151,7 @@
127151
pre.parentNode?.replaceChild(wrapper, pre);
128152
}
129153
130-
return tempDiv.innerHTML;
154+
return mutated ? tempDiv.innerHTML : html;
131155
}
132156
133157
async function processMarkdown(text: string): Promise<string> {
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
export const LINE_BREAK = /\r?\n/;
2+
3+
export const PHRASE_PARENTS = new Set([
4+
'paragraph',
5+
'heading',
6+
'emphasis',
7+
'strong',
8+
'delete',
9+
'link',
10+
'linkReference',
11+
'tableCell'
12+
]);
13+
14+
export const NBSP = '\u00a0';
15+
export const TAB_AS_SPACES = NBSP.repeat(4);
Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,121 @@
1+
import type { Plugin } from 'unified';
2+
import { visit } from 'unist-util-visit';
3+
import type { Break, Content, Paragraph, PhrasingContent, Root, Text } from 'mdast';
4+
import { LINE_BREAK, NBSP, PHRASE_PARENTS, TAB_AS_SPACES } from '$lib/constants/literal-html';
5+
6+
/**
7+
* remark plugin that rewrites raw HTML nodes into plain-text equivalents.
8+
*
9+
* remark parses inline HTML into `html` nodes even when we do not want to render
10+
* them. We turn each of those nodes into regular text (plus `<br>` break markers)
11+
* so the downstream rehype pipeline escapes the characters instead of executing
12+
* them. Leading spaces and tab characters are converted to non‑breaking spaces to
13+
* keep indentation identical to the original author input.
14+
*/
15+
16+
function preserveIndent(line: string): string {
17+
let index = 0;
18+
let output = '';
19+
20+
while (index < line.length) {
21+
const char = line[index];
22+
23+
if (char === ' ') {
24+
output += NBSP;
25+
index += 1;
26+
continue;
27+
}
28+
29+
if (char === '\t') {
30+
output += TAB_AS_SPACES;
31+
index += 1;
32+
continue;
33+
}
34+
35+
break;
36+
}
37+
38+
return output + line.slice(index);
39+
}
40+
41+
function createLiteralChildren(value: string): PhrasingContent[] {
42+
const lines = value.split(LINE_BREAK);
43+
const nodes: PhrasingContent[] = [];
44+
45+
for (const [lineIndex, rawLine] of lines.entries()) {
46+
if (lineIndex > 0) {
47+
nodes.push({ type: 'break' } as Break as unknown as PhrasingContent);
48+
}
49+
50+
nodes.push({
51+
type: 'text',
52+
value: preserveIndent(rawLine)
53+
} as Text as unknown as PhrasingContent);
54+
}
55+
56+
if (!nodes.length) {
57+
nodes.push({ type: 'text', value: '' } as Text as unknown as PhrasingContent);
58+
}
59+
60+
return nodes;
61+
}
62+
63+
export const remarkLiteralHtml: Plugin<[], Root> = () => {
64+
return (tree) => {
65+
visit(tree, 'html', (node, index, parent) => {
66+
if (!parent || typeof index !== 'number') {
67+
return;
68+
}
69+
70+
const replacement = createLiteralChildren(node.value);
71+
72+
if (!PHRASE_PARENTS.has(parent.type as string)) {
73+
const paragraph: Paragraph = {
74+
type: 'paragraph',
75+
children: replacement as Paragraph['children'],
76+
data: { literalHtml: true }
77+
};
78+
79+
const siblings = parent.children as unknown as Content[];
80+
siblings.splice(index, 1, paragraph as unknown as Content);
81+
82+
if (index > 0) {
83+
const previous = siblings[index - 1] as Paragraph | undefined;
84+
85+
if (
86+
previous?.type === 'paragraph' &&
87+
(previous.data as { literalHtml?: boolean } | undefined)?.literalHtml
88+
) {
89+
const prevChildren = previous.children as unknown as PhrasingContent[];
90+
91+
if (prevChildren.length) {
92+
const lastChild = prevChildren[prevChildren.length - 1];
93+
94+
if (lastChild.type !== 'break') {
95+
prevChildren.push({
96+
type: 'break'
97+
} as Break as unknown as PhrasingContent);
98+
}
99+
}
100+
101+
prevChildren.push(...(paragraph.children as unknown as PhrasingContent[]));
102+
103+
siblings.splice(index, 1);
104+
105+
return index;
106+
}
107+
}
108+
109+
return index + 1;
110+
}
111+
112+
(parent.children as unknown as PhrasingContent[]).splice(
113+
index,
114+
1,
115+
...(replacement as unknown as PhrasingContent[])
116+
);
117+
118+
return index + replacement.length;
119+
});
120+
};
121+
};

0 commit comments

Comments
 (0)