fix(session-ui): allocate less per streamed markdown delta (#60549)

This commit is contained in:
Luke Parker
2026-10-30 20:17:09 +10:00
committed by GitHub
Unverified
parent 56880cb41e
commit cfdb9dabe8
4 changed files with 47 additions and 50 deletions
@@ -24,16 +24,16 @@ const pending = new Map<
// A private instance keeps this hook set separate from other DOMPurify users.
const purifier = typeof window !== "undefined" ? DOMPurify(window) : DOMPurify
const config = {
USE_PROFILES: { html: true, mathMl: true },
SANITIZE_NAMED_PROPS: true,
FORBID_TAGS: ["style"],
FORBID_CONTENTS: ["style", "script"],
ADD_TAGS: ["svg", "path"],
ADD_ATTR: ["d", "viewBox", "preserveAspectRatio", "xmlns", "target"],
}
if (typeof window !== "undefined" && purifier.isSupported) {
// A config passed to sanitize() rebuilds every allow-list on each call; set once, every call reuses them.
purifier.setConfig({
USE_PROFILES: { html: true, mathMl: true },
SANITIZE_NAMED_PROPS: true,
FORBID_TAGS: ["style"],
FORBID_CONTENTS: ["style", "script"],
ADD_TAGS: ["svg", "path"],
ADD_ATTR: ["d", "viewBox", "preserveAspectRatio", "xmlns", "target"],
})
purifier.addHook("beforeSanitizeAttributes", (node) => {
if (node instanceof HTMLAnchorElement) {
// Local file links never navigate the document; the host decides how to open them.
@@ -76,7 +76,7 @@ if (typeof window !== "undefined" && purifier.isSupported) {
export function sanitizeMarkdown(html: string) {
if (!purifier.isSupported) return ""
return purifier.sanitize(html, config)
return purifier.sanitize(html)
}
export function getCachedMarkdown(key: string) {
@@ -6,8 +6,15 @@ beforeAll(() => GlobalRegistrator.register())
afterAll(() => GlobalRegistrator.unregister())
function parse(html: string, words: boolean, animate?: boolean) {
const template = document.createElement("template")
template.innerHTML = html
return parseMarkdownNodes(template.content, words, animate)
}
test("assigns stable paths to elements and individual words", () => {
expect(parseMarkdownNodes('<p class="lead">Hello <strong>streaming</strong> world</p>', true)).toEqual([
expect(parse('<p class="lead">Hello <strong>streaming</strong> world</p>', true)).toEqual([
{
key: "0",
type: "element",
@@ -31,7 +38,7 @@ test("assigns stable paths to elements and individual words", () => {
})
test("keeps completed block text compact", () => {
expect(parseMarkdownNodes("<p>Hello world</p>", false)).toEqual([
expect(parse("<p>Hello world</p>", false)).toEqual([
{
key: "0",
type: "element",
@@ -43,7 +50,7 @@ test("keeps completed block text compact", () => {
})
test("marks streamed inline code for animation", () => {
expect(parseMarkdownNodes("<p><code>file.ts:29-43</code></p>", true, true)).toEqual([
expect(parse("<p><code>file.ts:29-43</code></p>", true, true)).toEqual([
{
key: "0",
type: "element",
@@ -69,17 +76,13 @@ test("marks streamed inline code for animation", () => {
})
test("marks words for animation only when requested", () => {
expect(
parseMarkdownNodes("<p>Hello</p>", true).flatMap((node) => (node.type === "element" ? node.children : [node]))[0],
).toEqual({
expect(parse("<p>Hello</p>", true).flatMap((node) => (node.type === "element" ? node.children : [node]))[0]).toEqual({
key: "0.0:0",
type: "word",
text: "Hello",
})
expect(
parseMarkdownNodes("<p>Hello</p>", true, true).flatMap((node) =>
node.type === "element" ? node.children : [node],
)[0],
parse("<p>Hello</p>", true, true).flatMap((node) => (node.type === "element" ? node.children : [node]))[0],
).toEqual({
key: "0.0:0",
type: "word",
@@ -14,8 +14,8 @@ type MarkdownNode =
| { key: string; type: "text"; text: string }
| { key: string; type: "word"; text: string; animate?: true }
export function createMarkdownRenderer(root: HTMLDivElement, html: string, words: boolean) {
const [nodes, setNodes] = createStore(parseMarkdownNodes(html, words))
export function createMarkdownRenderer(root: HTMLDivElement, source: ParentNode, words: boolean) {
const [nodes, setNodes] = createStore(parseMarkdownNodes(source, words))
let ready = false
const dispose = render(
@@ -26,7 +26,7 @@ export function createMarkdownRenderer(root: HTMLDivElement, html: string, words
ready = true
return {
update(next: string, nextWords: boolean, animate = true) {
update(next: ParentNode, nextWords: boolean, animate = true) {
setNodes(reconcile(parseMarkdownNodes(next, nextWords, animate), { key: "key" }))
},
dispose,
@@ -63,11 +63,8 @@ function MarkdownDomNode(props: { node: MarkdownNode; animate: () => boolean })
)
}
export function parseMarkdownNodes(html: string, words: boolean, animate = false) {
const template = document.createElement("template")
template.innerHTML = html
return Array.from(template.content.childNodes).flatMap((node, index) => parseNode(node, `${index}`, words, animate))
export function parseMarkdownNodes(source: ParentNode, words: boolean, animate = false) {
return Array.from(source.childNodes).flatMap((node, index) => parseNode(node, `${index}`, words, animate))
}
function parseNode(node: Node, key: string, words: boolean, animate: boolean, inlineCode = false): MarkdownNode[] {
@@ -78,31 +75,28 @@ function parseNode(node: Node, key: string, words: boolean, animate: boolean, in
if (!text) return []
if (/^\s+$/.test(text)) return [{ key: `${key}:${index}`, type: "text", text }]
const word: Extract<MarkdownNode, { type: "word" }> = { key: `${key}:${index}`, type: "word", text }
return [{ key: `${key}:${index}`, type: "word", text, ...(animate ? { animate: true as const } : {}) }]
if (animate) word.animate = true
return [word]
})
}
if (!(node instanceof Element)) return []
const code = node.tagName === "CODE" && node.parentElement?.tagName !== "PRE"
return [
{
key,
type: "element",
tag: node.tagName.toLowerCase(),
attributes: Object.fromEntries(Array.from(node.attributes).map((attribute) => [attribute.name, attribute.value])),
children: Array.from(node.childNodes).flatMap((child, index) =>
parseNode(
child,
`${key}.${index}`,
words,
animate,
inlineCode || (node.tagName === "CODE" && node.parentElement?.tagName !== "PRE"),
),
),
...(words && animate && node.tagName === "CODE" && node.parentElement?.tagName !== "PRE"
? { animate: true as const }
: {}),
},
]
const element: Extract<MarkdownNode, { type: "element" }> = {
key,
type: "element",
tag: node.tagName.toLowerCase(),
attributes: Object.fromEntries(Array.from(node.attributes).map((attribute) => [attribute.name, attribute.value])),
children: Array.from(node.childNodes).flatMap((child, index) =>
parseNode(child, `${key}.${index}`, words, animate, inlineCode || code),
),
}
if (words && animate && code) element.animate = true
return [element]
}
@@ -1080,7 +1080,7 @@ function updateBlock(
markExternalLinkFavicons(source)
if (rendered) {
rendered.renderer.update(source.innerHTML, block.mode === "live", rendered.raw !== block.raw)
rendered.renderer.update(source, block.mode === "live", rendered.raw !== block.raw)
rendered.raw = block.raw
return pending
@@ -1089,7 +1089,7 @@ function updateBlock(
if (block.mode === "live") {
next.replaceChildren()
renderedMarkdown.set(next, {
renderer: createMarkdownRenderer(next, source.innerHTML, true),
renderer: createMarkdownRenderer(next, source, true),
raw: block.raw,
})
}