mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 11:42:17 +00:00
fix(session-ui): dispose live markdown renderer when blocks settle
This commit is contained in:
parent
4386838922
commit
d762e659dc
5 changed files with 303 additions and 40 deletions
|
|
@ -1,12 +1,14 @@
|
|||
import { createSignal, Show } from "solid-js"
|
||||
import { render } from "solid-js/web"
|
||||
import { DialogProvider } from "@opencode/ui/context/dialog"
|
||||
import { Markdown } from "../src/components/markdown"
|
||||
import { hasLiveMarkdownRenderer, Markdown } from "../src/components/markdown"
|
||||
import { preloadMarkdown } from "../src/components/markdown-cache"
|
||||
import { MarkdownProvider } from "../src/context/markdown"
|
||||
import { OpenCode } from "@opencode/client/promise"
|
||||
import { readLocalImage } from "../../app/src/runtime/server/image"
|
||||
|
||||
export { hasLiveMarkdownRenderer }
|
||||
|
||||
export {
|
||||
getCachedMarkdown,
|
||||
renderCachedMarkdown,
|
||||
|
|
|
|||
|
|
@ -492,25 +492,37 @@ story("renders the trailing chunk while the stream is paused", async ({ page })
|
|||
await expect(harness.getByLabel("Streaming")).toBeChecked()
|
||||
})
|
||||
|
||||
story("keeps live elements and selection when a stream completes and later changes", async ({ page }) => {
|
||||
story("disposes live renderers and word spans on settle while preserving selection", async ({ page }) => {
|
||||
await page.evaluate(async (fixture) => {
|
||||
const { mountMarkdown } = await import(fixture)
|
||||
await mountMarkdown({ text: "Hello **world**", streaming: true })
|
||||
}, fixture)
|
||||
const harness = page.getByTestId("markdown-fixture")
|
||||
const markdown = harness.locator('[data-component="markdown"]')
|
||||
const paragraph = markdown.locator("p")
|
||||
const block = markdown.locator("[data-markdown-block]").first()
|
||||
const paragraph = markdown.locator("p").first()
|
||||
await expect(markdown.locator("[data-markdown-word]")).toHaveCount(2)
|
||||
await block.evaluate((element) => element.setAttribute("data-retained", "true"))
|
||||
await paragraph.evaluate((element) => element.setAttribute("data-retained", "true"))
|
||||
await harness.getByLabel("Markdown text").fill("Hello **world** again")
|
||||
await expect(markdown.locator("[data-markdown-word]")).toHaveCount(3)
|
||||
await expect(paragraph).toHaveAttribute("data-retained", "true")
|
||||
await expect(markdown.locator("[data-markdown-enter]")).not.toHaveCount(0)
|
||||
expect(
|
||||
await page.evaluate(async (fixture) => {
|
||||
const { hasLiveMarkdownRenderer } = await import(fixture)
|
||||
|
||||
const element = document.querySelector<HTMLDivElement>(
|
||||
'[data-testid="markdown-fixture"] [data-markdown-block]',
|
||||
)!
|
||||
|
||||
return hasLiveMarkdownRenderer(element)
|
||||
}, fixture),
|
||||
).toBe(true)
|
||||
await paragraph.evaluate((element) => {
|
||||
const range = document.createRange()
|
||||
range.selectNodeContents(element.querySelector("strong")!)
|
||||
window.getSelection()!.removeAllRanges()
|
||||
window.getSelection()!.addRange(range)
|
||||
const [hello, world] = Array.from(element.querySelectorAll("[data-markdown-word]"), (span) => span.firstChild!)
|
||||
// Select backward from inside "world" to inside "Hello", as a right-to-left drag would.
|
||||
window.getSelection()!.setBaseAndExtent(world, 3, hello, 2)
|
||||
// Change the control without moving browser focus or selection.
|
||||
const input = document.querySelector<HTMLInputElement>('[data-testid="markdown-fixture"] input')!
|
||||
input.checked = false
|
||||
|
|
@ -518,16 +530,94 @@ story("keeps live elements and selection when a stream completes and later chang
|
|||
})
|
||||
await expect(harness.getByLabel("Streaming")).not.toBeChecked()
|
||||
await expect(markdown).toHaveAttribute("data-markdown-ready", "")
|
||||
await expect(block).toHaveAttribute("data-retained", "true")
|
||||
await expect(paragraph).toHaveAttribute("data-retained", "true")
|
||||
expect(await page.evaluate(() => window.getSelection()?.toString())).toBe("world")
|
||||
await expect(markdown.locator("[data-markdown-word]")).toHaveCount(0)
|
||||
expect(
|
||||
await page.evaluate(async (fixture) => {
|
||||
const { hasLiveMarkdownRenderer } = await import(fixture)
|
||||
|
||||
const element = document.querySelector<HTMLDivElement>(
|
||||
'[data-testid="markdown-fixture"] [data-markdown-block]',
|
||||
)!
|
||||
|
||||
return hasLiveMarkdownRenderer(element)
|
||||
}, fixture),
|
||||
).toBe(false)
|
||||
expect(
|
||||
await paragraph.evaluate((element) => {
|
||||
const selection = window.getSelection()!
|
||||
|
||||
return {
|
||||
text: selection.toString(),
|
||||
backward: selection.getRangeAt(0).endContainer === selection.anchorNode,
|
||||
// In-app Find matches within a single text node, so each run of words is one node again.
|
||||
nodes: Array.from(element.childNodes, (node) => node.textContent),
|
||||
}
|
||||
}),
|
||||
).toEqual({ text: "llo wor", backward: true, nodes: ["Hello ", "world", " again"] })
|
||||
await harness.getByLabel("Markdown text").fill("Changed **content**")
|
||||
await expect(paragraph).toHaveText("Changed content")
|
||||
await expect(paragraph).toHaveAttribute("data-retained", "true")
|
||||
await expect(block).toHaveAttribute("data-retained", "true")
|
||||
await expect(markdown.locator("[data-markdown-word]")).toHaveCount(0)
|
||||
await harness.getByRole("button", { name: "Toggle Markdown" }).click()
|
||||
await expect(markdown).toHaveCount(0)
|
||||
})
|
||||
|
||||
story("settles a live block in place when its final update also changes its content", async ({ page }) => {
|
||||
await page.evaluate(async (fixture) => {
|
||||
const { mountMarkdown } = await import(fixture)
|
||||
await mountMarkdown({ text: "Hello **world**", streaming: true })
|
||||
}, fixture)
|
||||
const harness = page.getByTestId("markdown-fixture")
|
||||
const markdown = harness.locator('[data-component="markdown"]')
|
||||
const paragraph = markdown.locator("p").first()
|
||||
await expect(markdown.locator("[data-markdown-word]")).toHaveCount(2)
|
||||
await paragraph.evaluate((element) => element.setAttribute("data-retained", "true"))
|
||||
await page.evaluate(() => {
|
||||
const textarea = document.querySelector<HTMLTextAreaElement>('[data-testid="markdown-fixture"] textarea')!
|
||||
const input = document.querySelector<HTMLInputElement>('[data-testid="markdown-fixture"] input')!
|
||||
textarea.value = "Hello **world** again"
|
||||
textarea.dispatchEvent(new Event("input", { bubbles: true }))
|
||||
input.checked = false
|
||||
input.dispatchEvent(new Event("change", { bubbles: true }))
|
||||
})
|
||||
await expect(markdown).toHaveAttribute("data-markdown-ready", "")
|
||||
await expect(paragraph).toHaveText("Hello world again")
|
||||
await expect(paragraph).toHaveAttribute("data-retained", "true")
|
||||
await expect(markdown.locator("[data-markdown-word]")).toHaveCount(0)
|
||||
expect(
|
||||
await page.evaluate(async (fixture) => {
|
||||
const { hasLiveMarkdownRenderer } = await import(fixture)
|
||||
|
||||
return hasLiveMarkdownRenderer(
|
||||
document.querySelector<HTMLDivElement>('[data-testid="markdown-fixture"] [data-markdown-block]')!,
|
||||
)
|
||||
}, fixture),
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
story("settles cache-keyed live blocks in place under their settled key", async ({ page }) => {
|
||||
await page.evaluate(async (fixture) => {
|
||||
const { mountMarkdown } = await import(fixture)
|
||||
await mountMarkdown({ text: "Hello **world**", streaming: true, cached: true })
|
||||
}, fixture)
|
||||
const harness = page.getByTestId("markdown-fixture")
|
||||
const markdown = harness.locator('[data-component="markdown"]')
|
||||
const paragraph = markdown.locator("p").first()
|
||||
await expect(markdown.locator("[data-markdown-word]")).toHaveCount(2)
|
||||
await paragraph.evaluate((element) => element.setAttribute("data-retained", "true"))
|
||||
await harness.getByLabel("Streaming").uncheck()
|
||||
await expect(markdown).toHaveAttribute("data-markdown-ready", "")
|
||||
await expect(markdown.locator("[data-markdown-word]")).toHaveCount(0)
|
||||
expect(
|
||||
await markdown.evaluate((element) => ({
|
||||
key: element.querySelector("[data-markdown-block]")?.getAttribute("data-markdown-key"),
|
||||
retained: element.querySelector("p")?.getAttribute("data-retained"),
|
||||
})),
|
||||
).toEqual({ key: expect.stringMatching(/:markdown-test:0:full$/), retained: "true" })
|
||||
})
|
||||
|
||||
story("replaces completed DOM before live rendering and retains streamed code copy actions", async ({ page }) => {
|
||||
await page.evaluate(async (fixture) => {
|
||||
const { mountMarkdown } = await import(fixture)
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { GlobalRegistrator } from "@happy-dom/global-registrator"
|
||||
import { afterAll, beforeAll, expect, test } from "bun:test"
|
||||
import { parseMarkdownNodes } from "./markdown-solid"
|
||||
import { parseMarkdownNodes, settleMarkdownWords, unwrapMarkdownWords } from "./markdown-solid"
|
||||
|
||||
beforeAll(() => GlobalRegistrator.register())
|
||||
|
||||
|
|
@ -87,3 +87,88 @@ test("marks words for animation only when requested", () => {
|
|||
animate: true,
|
||||
})
|
||||
})
|
||||
|
||||
test("unwraps word spans in place while retaining elements and selection", () => {
|
||||
const container = document.createElement("div")
|
||||
container.innerHTML =
|
||||
'<div id="settled"><p>Earlier block</p></div><div id="live"><p><span data-markdown-word="">Hello</span> <strong><span data-markdown-word="">world</span></strong> <span data-markdown-word="" data-markdown-enter="">again</span></p></div>'
|
||||
document.body.appendChild(container)
|
||||
|
||||
const settledText = container.querySelector("#settled p")!.firstChild!
|
||||
const block = container.querySelector<HTMLElement>("#live")!
|
||||
const paragraph = block.querySelector("p")!
|
||||
const strong = block.querySelector("strong")!
|
||||
const wordSpan = strong.querySelector("[data-markdown-word]")!
|
||||
const range = document.createRange()
|
||||
range.selectNodeContents(wordSpan)
|
||||
const selection = window.getSelection()!
|
||||
selection.removeAllRanges()
|
||||
selection.addRange(range)
|
||||
expect(selection.toString()).toBe("world")
|
||||
|
||||
unwrapMarkdownWords(block)
|
||||
|
||||
expect(block.querySelector("p")).toBe(paragraph)
|
||||
expect(block.querySelector("strong")).toBe(strong)
|
||||
expect(block.querySelectorAll("[data-markdown-word]").length).toBe(0)
|
||||
expect(block.querySelectorAll("[data-markdown-enter]").length).toBe(0)
|
||||
expect(window.getSelection()?.toString()).toBe("world")
|
||||
|
||||
// Cross-block selection anchored in Text nodes also survives unwrapping.
|
||||
block.innerHTML =
|
||||
'<p><span data-markdown-word="">Hello</span> <strong><span data-markdown-word="">world</span></strong></p>'
|
||||
const crossRange = document.createRange()
|
||||
crossRange.setStart(settledText, 8)
|
||||
crossRange.setEnd(block.querySelector("strong [data-markdown-word]")!.firstChild!, 3)
|
||||
selection.removeAllRanges()
|
||||
selection.addRange(crossRange)
|
||||
const expectedCross = selection.toString()
|
||||
unwrapMarkdownWords(block)
|
||||
expect(window.getSelection()?.toString()).toBe(expectedCross)
|
||||
|
||||
// A backward selection keeps its anchor after the focus. (happy-dom doesn't move ranges through
|
||||
// normalize(), so the words sit in separate elements here; the Chromium spec covers merged text.)
|
||||
block.innerHTML =
|
||||
'<p><em><span data-markdown-word="">Hello</span></em> <strong><span data-markdown-word="">world</span></strong></p>'
|
||||
const [hello, world] = Array.from(block.querySelectorAll("[data-markdown-word]"), (span) => span.firstChild!)
|
||||
selection.setBaseAndExtent(world, 3, hello, 1)
|
||||
unwrapMarkdownWords(block)
|
||||
expect(selection.toString()).toBe("ello wor")
|
||||
expect([selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset]).toEqual([
|
||||
world,
|
||||
3,
|
||||
hello,
|
||||
1,
|
||||
])
|
||||
|
||||
// Without an active selection inside the block, unwrapped text nodes are normalized.
|
||||
selection.removeAllRanges()
|
||||
block.innerHTML = '<p><span data-markdown-word="">Hello</span> <span data-markdown-word="">world</span></p>'
|
||||
unwrapMarkdownWords(block)
|
||||
expect(block.querySelector("p")?.childNodes.length).toBe(1)
|
||||
container.remove()
|
||||
})
|
||||
|
||||
test("waits for running enter animations before unwrapping word spans", async () => {
|
||||
const block = document.createElement("div")
|
||||
block.dataset.markdownHash = "1"
|
||||
block.dataset.markdownMode = "full"
|
||||
block.innerHTML = '<p><span data-markdown-word="" data-markdown-enter="">Hello</span></p>'
|
||||
document.body.appendChild(block)
|
||||
|
||||
const { promise: finished, resolve: finish } = Promise.withResolvers<void>()
|
||||
const enter = block.querySelector<HTMLElement>("[data-markdown-enter]")!
|
||||
|
||||
Object.defineProperty(enter, "getAnimations", {
|
||||
value: () => [{ playState: "running", finished }],
|
||||
})
|
||||
|
||||
settleMarkdownWords(block)
|
||||
expect(block.querySelectorAll("[data-markdown-word]").length).toBe(1)
|
||||
|
||||
finish()
|
||||
await finished
|
||||
await Promise.resolve()
|
||||
expect(block.querySelectorAll("[data-markdown-word]").length).toBe(0)
|
||||
block.remove()
|
||||
})
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
import { For, onMount } from "solid-js"
|
||||
import { createRoot, For, onMount } from "solid-js"
|
||||
import { createStore, reconcile } from "solid-js/store"
|
||||
import { Dynamic, render } from "solid-js/web"
|
||||
import { Dynamic, insert } from "solid-js/web"
|
||||
|
||||
type MarkdownNode =
|
||||
| {
|
||||
|
|
@ -18,10 +18,14 @@ export function createMarkdownRenderer(root: HTMLDivElement, html: string, words
|
|||
const [nodes, setNodes] = createStore(parseMarkdownNodes(html, words))
|
||||
let ready = false
|
||||
|
||||
const dispose = render(
|
||||
() => <For each={nodes}>{(node) => <MarkdownDomNode node={node} animate={() => ready} />}</For>,
|
||||
root,
|
||||
)
|
||||
const dispose = createRoot((dispose) => {
|
||||
insert(
|
||||
root,
|
||||
<For each={nodes}>{(node) => <MarkdownDomNode node={node} animate={() => ready} />}</For>,
|
||||
)
|
||||
|
||||
return dispose
|
||||
})
|
||||
|
||||
ready = true
|
||||
|
||||
|
|
@ -79,30 +83,92 @@ function parseNode(node: Node, key: string, words: boolean, animate: boolean, in
|
|||
|
||||
if (/^\s+$/.test(text)) return [{ key: `${key}:${index}`, type: "text", text }]
|
||||
|
||||
return [{ key: `${key}:${index}`, type: "word", text, ...(animate ? { animate: true as const } : {}) }]
|
||||
const item: MarkdownNode = { key: `${key}:${index}`, type: "word", text }
|
||||
|
||||
if (animate) item.animate = true
|
||||
|
||||
return [item]
|
||||
})
|
||||
}
|
||||
|
||||
if (!(node instanceof Element)) return []
|
||||
|
||||
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"),
|
||||
),
|
||||
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 || (node.tagName === "CODE" && node.parentElement?.tagName !== "PRE"),
|
||||
),
|
||||
...(words && animate && node.tagName === "CODE" && node.parentElement?.tagName !== "PRE"
|
||||
? { animate: true as const }
|
||||
: {}),
|
||||
},
|
||||
]
|
||||
),
|
||||
}
|
||||
|
||||
if (words && animate && node.tagName === "CODE" && node.parentElement?.tagName !== "PRE") {
|
||||
element.animate = true
|
||||
}
|
||||
|
||||
return [element]
|
||||
}
|
||||
|
||||
function resolveBoundary(node: Node, offset: number): [Node, number] {
|
||||
if (node instanceof HTMLElement && node.hasAttribute("data-markdown-word") && node.firstChild instanceof Text) {
|
||||
return [node.firstChild, offset === 0 ? 0 : node.firstChild.data.length]
|
||||
}
|
||||
|
||||
return [node, offset]
|
||||
}
|
||||
|
||||
export function unwrapMarkdownWords(root: HTMLElement) {
|
||||
for (const node of root.querySelectorAll<HTMLElement>("[data-markdown-enter]")) {
|
||||
node.removeAttribute("data-markdown-enter")
|
||||
}
|
||||
|
||||
const spans = root.querySelectorAll<HTMLElement>("[data-markdown-word]")
|
||||
|
||||
if (spans.length === 0) return
|
||||
const selection = window.getSelection?.()
|
||||
|
||||
const inside =
|
||||
!!selection?.anchorNode &&
|
||||
!!selection.focusNode &&
|
||||
!selection.isCollapsed &&
|
||||
(root.contains(selection.anchorNode) || root.contains(selection.focusNode))
|
||||
|
||||
const anchor = inside ? resolveBoundary(selection.anchorNode, selection.anchorOffset) : undefined
|
||||
const focus = inside ? resolveBoundary(selection.focusNode, selection.focusOffset) : undefined
|
||||
|
||||
for (const span of spans) {
|
||||
span.replaceWith(...span.childNodes)
|
||||
}
|
||||
|
||||
// Restoring base and extent keeps backward and in-progress drags anchored where they started.
|
||||
if (selection && anchor && focus) selection.setBaseAndExtent(anchor[0], anchor[1], focus[0], focus[1])
|
||||
|
||||
// Live ranges, including the selection, follow merged text nodes through normalize().
|
||||
root.normalize()
|
||||
}
|
||||
|
||||
export function settleMarkdownWords(root: HTMLElement) {
|
||||
const hash = root.dataset.markdownHash
|
||||
|
||||
const running = Array.from(root.querySelectorAll<HTMLElement>("[data-markdown-enter]")).flatMap((node) =>
|
||||
(node.getAnimations?.() ?? []).filter((animation) => animation.playState === "running"),
|
||||
)
|
||||
|
||||
if (running.length === 0) {
|
||||
unwrapMarkdownWords(root)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
void Promise.allSettled(running.map((animation) => animation.finished)).then(() => {
|
||||
if (!root.isConnected || root.dataset.markdownMode === "live" || root.dataset.markdownHash !== hash) return
|
||||
unwrapMarkdownWords(root)
|
||||
})
|
||||
}
|
||||
|
|
|
|||
|
|
@ -36,7 +36,7 @@ import {
|
|||
} from "./markdown-cache"
|
||||
import { inlineCodeKind } from "./markdown-inline-code-kind"
|
||||
import { renderMermaidSvg } from "./markdown-mermaid"
|
||||
import { createMarkdownRenderer } from "./markdown-solid"
|
||||
import { createMarkdownRenderer, settleMarkdownWords } from "./markdown-solid"
|
||||
import {
|
||||
useMarkdown,
|
||||
type OpenMarkdownLocalFile,
|
||||
|
|
@ -74,6 +74,10 @@ const renderedMarkdown = new WeakMap<
|
|||
{ renderer: ReturnType<typeof createMarkdownRenderer>; raw: string }
|
||||
>()
|
||||
|
||||
export function hasLiveMarkdownRenderer(block: HTMLDivElement) {
|
||||
return renderedMarkdown.has(block)
|
||||
}
|
||||
|
||||
function escape(text: string) {
|
||||
return text
|
||||
.replace(/&/g, "&")
|
||||
|
|
@ -889,14 +893,20 @@ function updateBlock(
|
|||
}
|
||||
|
||||
const existing =
|
||||
current instanceof HTMLDivElement && current.dataset.markdownKey === block.key && !renderedCodeTokens.has(current)
|
||||
current instanceof HTMLDivElement &&
|
||||
!renderedCodeTokens.has(current) &&
|
||||
// Block keys include the mode, so a live block that settles keeps its element under its new key.
|
||||
(current.dataset.markdownKey === block.key || (renderedMarkdown.has(current) && block.mode !== "live"))
|
||||
? current
|
||||
: undefined
|
||||
|
||||
if (existing?.dataset.markdownHash === block.hash) {
|
||||
// A block that finishes streaming keeps its DOM and the user's selection; only its file paths get checked now.
|
||||
if (existing.dataset.markdownMode === "live" && block.mode !== "live") {
|
||||
existing.dataset.markdownKey = block.key
|
||||
existing.dataset.markdownMode = block.mode
|
||||
disposeRenderedMarkdown(existing)
|
||||
settleMarkdownWords(existing)
|
||||
markInlineCode(existing, existing, false, localFileExists)
|
||||
}
|
||||
|
||||
|
|
@ -909,8 +919,8 @@ function updateBlock(
|
|||
next.dataset.markdownHash = block.hash
|
||||
next.dataset.markdownMode = block.mode
|
||||
next.style.display = "contents"
|
||||
|
||||
const rendered = renderedMarkdown.get(next)
|
||||
// Keep live renderers in control of their DOM, including after completion.
|
||||
const source = rendered || block.mode === "live" ? document.createElement("div") : next
|
||||
|
||||
if (source === next) disposeCopyButtons(next)
|
||||
|
|
@ -922,9 +932,19 @@ function updateBlock(
|
|||
markExternalLinkFavicons(source)
|
||||
|
||||
if (rendered) {
|
||||
rendered.renderer.update(source.innerHTML, block.mode === "live", rendered.raw !== block.raw)
|
||||
rendered.renderer.update(source.innerHTML, true, rendered.raw !== block.raw)
|
||||
rendered.raw = block.raw
|
||||
|
||||
if (block.mode === "live") return
|
||||
|
||||
// A block that settles with new content gets one last live patch, which Solid applies after this
|
||||
// effect, then settles in place.
|
||||
queueMicrotask(() => {
|
||||
if (renderedMarkdown.get(next) !== rendered || next.dataset.markdownMode === "live") return
|
||||
disposeRenderedMarkdown(next)
|
||||
settleMarkdownWords(next)
|
||||
})
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue