diff --git a/packages/session-ui/src/components/markdown-code-machine.test.ts b/packages/session-ui/src/components/markdown-code-machine.test.ts new file mode 100644 index 00000000000..0cb93c186c4 --- /dev/null +++ b/packages/session-ui/src/components/markdown-code-machine.test.ts @@ -0,0 +1,229 @@ +import { describe, expect, test } from "bun:test" +import { + EMPTY_CODE_EFFECTS, + INITIAL_CODE_DECORATION_STATE, + transitionCodeDecoration, + viewCodeDecoration, + type CodeDecorationEvent, + type CodeDecorationState, +} from "./markdown-code-machine" + +const sync = (source: string, complete: boolean, language = "mermaid") => + ({ type: "sync", language, source, complete, match: undefined }) as const + +function run(events: CodeDecorationEvent[], state = INITIAL_CODE_DECORATION_STATE) { + return events.reduce( + (result, event) => { + const next = transitionCodeDecoration(result.state, event) + + return { state: next.state, effects: next.effects } + }, + { state, effects: EMPTY_CODE_EFFECTS }, + ) +} + +function svg(state: CodeDecorationState) { + return viewCodeDecoration(state).svg +} + +const claim = (language: string) => ({ render: new Set([language]), actions: new Set() }) + +describe("markdown code decoration", () => { + test("keeps plain code on the same state with no effects", () => { + const match = claim("python") + + const first = transitionCodeDecoration(INITIAL_CODE_DECORATION_STATE, { + type: "sync", + language: "ts", + source: "const a", + complete: false, + match, + }) + + const second = transitionCodeDecoration(first.state, { + type: "sync", + language: "ts", + source: "const a = 1", + complete: false, + match, + }) + + expect(first.state).toBe(INITIAL_CODE_DECORATION_STATE) + expect(second.state).toBe(INITIAL_CODE_DECORATION_STATE) + expect(second.effects).toBe(EMPTY_CODE_EFFECTS) + }) + + test("ignores a slow render of earlier streamed lines once a newer diagram rendered", () => { + const started = run([sync("flowchart LR\nA --> B\n", false), sync("flowchart LR\nA --> B\nB --> C", true)]) + + expect(started.effects).toEqual([{ type: "render-mermaid", attempt: 2, input: "flowchart LR\nA --> B\nB --> C" }]) + const newer = transitionCodeDecoration(started.state, { type: "mermaid.resolved", attempt: 2, svg: "2" }) + const older = transitionCodeDecoration(newer.state, { type: "mermaid.resolved", attempt: 1, svg: "1" }) + + expect(svg(newer.state)).toBe("2") + expect(older.state).toBe(newer.state) + expect(older.effects).toBe(EMPTY_CODE_EFFECTS) + }) + + test("renders a replaced diagram of the same length", () => { + const ready = run([ + sync("flowchart LR\nA --> B", true), + { type: "mermaid.resolved", attempt: 1, svg: "1" }, + ]) + + const replaced = transitionCodeDecoration(ready.state, sync("flowchart TD\nX --> Y", true)) + + expect(replaced.effects).toEqual([{ type: "render-mermaid", attempt: 2, input: "flowchart TD\nX --> Y" }]) + expect(svg(replaced.state)).toBe("1") + }) + + test("shows the empty diagram box until the first line ends, then renders whole lines once", () => { + const first = run([sync("flowchart LR", false)]) + + expect(viewCodeDecoration(first.state).pending).toBe(true) + expect(first.effects).toEqual([]) + const line = transitionCodeDecoration(first.state, sync("flowchart LR\nA", false)) + const token = transitionCodeDecoration(line.state, sync("flowchart LR\nA -", false)) + + expect(line.effects).toEqual([{ type: "render-mermaid", attempt: 1, input: "flowchart LR\n" }]) + expect(token.state).toBe(line.state) + }) + + test("shows the code when a streamed diagram fails, and renders the next lines behind it", () => { + const failed = run([sync("invalid\n", false), { type: "mermaid.failed", attempt: 1 }]) + + expect(failed.state.status).toBe("code") + expect(viewCodeDecoration(failed.state).pending).toBe(false) + expect(transitionCodeDecoration(failed.state, sync("invalid\nmore", false)).state).toBe(failed.state) + const retry = transitionCodeDecoration(failed.state, sync("invalid\nflowchart LR\n", false)) + + expect(retry.state.status).toBe("code") + expect(retry.effects).toEqual([{ type: "render-mermaid", attempt: 2, input: "invalid\nflowchart LR\n" }]) + const recovered = transitionCodeDecoration(retry.state, { type: "mermaid.resolved", attempt: 2, svg: "" }) + + expect(svg(recovered.state)).toBe("") + }) + + test("treats a render without output like a failure", () => { + const declined = run([sync("not a diagram", true), { type: "mermaid.resolved", attempt: 1, svg: undefined }]) + + expect(declined.state.status).toBe("code") + expect(transitionCodeDecoration(declined.state, sync("not a diagram", true)).state).toBe(declined.state) + }) + + test("keeps the last diagram while newer lines fail, and shows the code when the complete diagram fails", () => { + const ready = run([sync("flowchart LR\n", false), { type: "mermaid.resolved", attempt: 1, svg: "1" }]) + const refreshing = transitionCodeDecoration(ready.state, sync("flowchart LR\nA[\n", false)) + + expect(viewCodeDecoration(refreshing.state)).toMatchObject({ pending: false, svg: "1" }) + const kept = transitionCodeDecoration(refreshing.state, { type: "mermaid.failed", attempt: 2 }) + + expect(svg(kept.state)).toBe("1") + const complete = run([sync("flowchart LR\nA[", true), { type: "mermaid.failed", attempt: 3 }], kept.state) + + expect(complete.state.status).toBe("code") + expect(viewCodeDecoration(complete.state).diagram).toBe(false) + }) + + test("ignores a Mermaid render that finishes after a plugin claimed the block", () => { + const match = claim("mermaid") + const pending = run([sync("flowchart LR\nA --> B\n", false)]) + + const plugin = transitionCodeDecoration(pending.state, { + type: "sync", + language: "mermaid", + source: "flowchart LR\nA --> B\n", + complete: true, + match, + }) + + expect(plugin.effects).toEqual([ + { type: "mount-plugin", attempt: 2, block: { code: "flowchart LR\nA --> B", language: "mermaid" } }, + ]) + const late = transitionCodeDecoration(plugin.state, { type: "mermaid.resolved", attempt: 1, svg: "" }) + + expect(late.state).toBe(plugin.state) + expect(viewCodeDecoration(plugin.state)).toMatchObject({ content: true, svg: undefined }) + const fallback = transitionCodeDecoration(plugin.state, { type: "plugin.failed", attempt: 2 }) + + expect(fallback.state.status).toBe("diagram-pending") + expect(fallback.effects).toEqual([ + { type: "clear-plugin" }, + { type: "render-mermaid", attempt: 3, input: "flowchart LR\nA --> B\n" }, + ]) + }) + + test("keeps the code after plugin content fails until the block changes", () => { + const match = claim("chart") + const event = { type: "sync", language: "chart", source: "x", complete: true, match } as const + const mounted = transitionCodeDecoration(INITIAL_CODE_DECORATION_STATE, event) + const failed = transitionCodeDecoration(mounted.state, { type: "plugin.failed", attempt: 1 }) + const stale = transitionCodeDecoration(failed.state, { type: "plugin.failed", attempt: 1 }) + + expect(failed.state.status).toBe("code") + expect(stale.state).toBe(failed.state) + expect(transitionCodeDecoration(failed.state, event).state).toBe(failed.state) + expect(transitionCodeDecoration(failed.state, { ...event, source: "y" }).effects).toEqual([ + { type: "mount-plugin", attempt: 2, block: { code: "y", language: "chart" } }, + ]) + }) + + test("waits for the closing fence before mounting claimed content", () => { + const match = claim("chart") + + const streaming = transitionCodeDecoration(INITIAL_CODE_DECORATION_STATE, { + type: "sync", + language: "chart", + source: "x", + complete: false, + match, + }) + + expect(streaming.state).toBe(INITIAL_CODE_DECORATION_STATE) + }) + + test("mounts actions for a complete block and moves them when it changes", () => { + const match = { render: new Set(), actions: new Set(["sql"]) } + const event = { type: "sync", language: "sql", source: "select 1\n", complete: true, match } as const + const mounted = transitionCodeDecoration(INITIAL_CODE_DECORATION_STATE, event) + + expect(mounted.effects).toEqual([{ type: "mount-actions", block: { code: "select 1", language: "sql" } }]) + expect(transitionCodeDecoration(mounted.state, event).state).toBe(mounted.state) + expect(transitionCodeDecoration(mounted.state, { ...event, match: undefined }).effects).toEqual([ + { type: "clear-actions" }, + ]) + }) + + test("clears mounted content on dispose and ignores results that arrive later", () => { + const match = { render: new Set(["chart"]), actions: new Set(["chart"]) } + + const mounted = transitionCodeDecoration(INITIAL_CODE_DECORATION_STATE, { + type: "sync", + language: "chart", + source: "x", + complete: true, + match, + }) + + const disposed = transitionCodeDecoration(mounted.state, { type: "disposed" }) + + expect(disposed.effects).toEqual([{ type: "clear-actions" }, { type: "clear-plugin" }]) + expect(transitionCodeDecoration(disposed.state, { type: "plugin.failed", attempt: 1 }).state).toBe(disposed.state) + const pending = run([sync("flowchart LR\n", false), { type: "disposed" }]) + + expect(viewCodeDecoration(pending.state).diagram).toBe(false) + expect( + transitionCodeDecoration(pending.state, { type: "mermaid.resolved", attempt: 1, svg: "" }).state, + ).toBe(pending.state) + }) + + test("leaves the diagram when the block stops being Mermaid", () => { + const pending = run([sync("flowchart LR\n", false)]) + const code = transitionCodeDecoration(pending.state, sync("flowchart LR\n", false, "text")) + + expect(code.state.status).toBe("code") + expect(transitionCodeDecoration(code.state, { type: "mermaid.resolved", attempt: 1, svg: "" }).state).toBe( + code.state, + ) + }) +}) diff --git a/packages/session-ui/src/components/markdown-code-machine.ts b/packages/session-ui/src/components/markdown-code-machine.ts new file mode 100644 index 00000000000..4fba400e32d --- /dev/null +++ b/packages/session-ui/src/components/markdown-code-machine.ts @@ -0,0 +1,200 @@ +import type { MarkdownCodeBlock, MarkdownCodeBlockMatch } from "../context/markdown" + +/** A complete block as plugin content or actions received it; another key means the content must mount again. */ +export type CodeBlockKey = { + readonly match: MarkdownCodeBlockMatch + readonly language: string + readonly source: string +} + +/** What a Mermaid render draws: whole lines while the block streams, the full source once it is complete. */ +export type MermaidInput = { readonly input: string; readonly complete: boolean } + +export type MermaidRender = MermaidInput & { readonly attempt: number } + +type Shared = { + /** Started renders and plugin mounts. A result whose attempt is not the current one is stale. */ + readonly attempts: number + readonly actions?: CodeBlockKey + /** Plugin content that declined or failed for this exact block, so the block keeps its code until it changes. */ + readonly declined?: CodeBlockKey +} + +/** + * One fenced code block. `code` shows the highlighted source, `diagram-pending` the empty diagram box until the first + * Mermaid render lands, `diagram` the last good SVG, and `plugin` content a plugin mounted for the block's language. + * `render` is the Mermaid render in flight; `tried` is the input of the last one that settled, so the same input never + * renders twice. + */ +export type CodeDecorationState = + | (Shared & { readonly status: "code"; readonly render?: MermaidRender; readonly tried?: MermaidInput }) + | (Shared & { readonly status: "diagram-pending"; readonly render?: MermaidRender }) + | (Shared & { + readonly status: "diagram" + readonly svg: string + readonly render?: MermaidRender + readonly tried: MermaidInput + }) + | (Shared & { readonly status: "plugin"; readonly plugin: CodeBlockKey }) + +export type CodeDecorationEvent = + | { + readonly type: "sync" + readonly language: string + readonly source: string + readonly complete: boolean + readonly match: MarkdownCodeBlockMatch | undefined + } + | { readonly type: "mermaid.resolved"; readonly attempt: number; readonly svg: string | undefined } + | { readonly type: "mermaid.failed"; readonly attempt: number } + | { readonly type: "plugin.failed"; readonly attempt: number } + | { readonly type: "disposed" } + +export type CodeDecorationEffect = + | { readonly type: "clear-actions" } + | { readonly type: "clear-plugin" } + | { readonly type: "mount-actions"; readonly block: MarkdownCodeBlock } + | { readonly type: "mount-plugin"; readonly attempt: number; readonly block: MarkdownCodeBlock } + | { readonly type: "render-mermaid"; readonly attempt: number; readonly input: string } + +export type CodeDecorationTransition = { + readonly state: CodeDecorationState + readonly effects: readonly CodeDecorationEffect[] +} + +type Sync = Extract + +export const INITIAL_CODE_DECORATION_STATE: CodeDecorationState = Object.freeze({ status: "code", attempts: 0 }) + +export const EMPTY_CODE_EFFECTS: readonly CodeDecorationEffect[] = Object.freeze([]) + +export function transitionCodeDecoration( + state: CodeDecorationState, + event: CodeDecorationEvent, +): CodeDecorationTransition { + if (event.type === "sync") return settle(state, sync(state, event, state.declined)) + + if (event.type === "plugin.failed") { + if (state.status !== "plugin" || event.attempt !== state.attempts) return { state, effects: EMPTY_CODE_EFFECTS } + const plugin = state.plugin + + return settle(state, sync(state, { type: "sync", ...plugin, complete: true }, plugin)) + } + + if (event.type === "disposed") return settle(state, { status: "code", attempts: state.attempts }) + + if (state.status === "plugin" || state.render?.attempt !== event.attempt) + return { state, effects: EMPTY_CODE_EFFECTS } + const render = state.render + const shared = { attempts: state.attempts, actions: state.actions, declined: state.declined } + + if (event.type === "mermaid.resolved" && event.svg) + return settle(state, { ...shared, status: "diagram", svg: event.svg, tried: render }) + + // A partial diagram often fails until more lines arrive, so the last good one stays; a complete failure shows the code. + if (state.status === "diagram" && !render.complete) + return settle(state, { ...shared, status: "diagram", svg: state.svg, tried: render }) + + return settle(state, { ...shared, status: "code", tried: render }) +} + +export function viewCodeDecoration(state: CodeDecorationState) { + return { + diagram: state.status === "diagram-pending" || state.status === "diagram", + pending: state.status === "diagram-pending", + svg: state.status === "diagram" ? state.svg : undefined, + content: state.status === "plugin", + } +} + +function sync(state: CodeDecorationState, event: Sync, declined: CodeBlockKey | undefined): CodeDecorationState { + const match = event.match + const claimed = !!match?.render.has(event.language) + const failed = declined && sameBlock(declined, event) ? declined : undefined + + const actions = + !match || !event.complete || !match.actions.has(event.language) + ? undefined + : state.actions && sameBlock(state.actions, event) + ? state.actions + : { match, language: event.language, source: event.source } + + if (match && claimed && event.complete && !failed) { + if (state.status === "plugin" && sameBlock(state.plugin, event)) return keep(state, actions, failed) + + return { + status: "plugin", + attempts: state.attempts + 1, + plugin: { match, language: event.language, source: event.source }, + actions, + } + } + + // Claimed content waits for the closing fence and gets the code until then, not the built-in diagram. + if (event.language !== "mermaid" || !event.source || (claimed && !failed)) { + if (state.status === "code" && !state.render && !state.tried) return keep(state, actions, failed) + + return { status: "code", attempts: state.attempts, actions, declined: failed } + } + + const input = event.complete ? event.source : event.source.slice(0, event.source.lastIndexOf("\n") + 1) + + if (state.status === "plugin" || (state.status === "code" && !state.render && !state.tried)) { + if (!input) return { status: "diagram-pending", attempts: state.attempts, actions, declined: failed } + const attempt = state.attempts + 1 + + return { + status: "diagram-pending", + attempts: attempt, + render: { attempt, input, complete: event.complete }, + actions, + declined: failed, + } + } + + const latest = state.render ?? (state.status === "diagram-pending" ? undefined : state.tried) + + if (!input || (latest?.input === input && latest.complete === event.complete)) return keep(state, actions, failed) + const render = { attempt: state.attempts + 1, input, complete: event.complete } + + return { ...state, attempts: render.attempt, render, actions, declined: failed } +} + +function keep(state: CodeDecorationState, actions: CodeBlockKey | undefined, declined: CodeBlockKey | undefined) { + if (state.actions === actions && state.declined === declined) return state + + return { ...state, actions, declined } +} + +// Effects follow from the difference between the two states, so every transition mounts and clears the same way. +function settle(state: CodeDecorationState, next: CodeDecorationState): CodeDecorationTransition { + if (next === state) return { state, effects: EMPTY_CODE_EFFECTS } + const plugin = state.status === "plugin" ? state.attempts : undefined + const nextPlugin = next.status === "plugin" ? next : undefined + const render = state.status === "plugin" ? undefined : state.render + const nextRender = next.status === "plugin" ? undefined : next.render + + const effects: CodeDecorationEffect[] = [ + ...(state.actions && state.actions !== next.actions ? [{ type: "clear-actions" as const }] : []), + ...(plugin !== undefined && plugin !== nextPlugin?.attempts ? [{ type: "clear-plugin" as const }] : []), + ...(next.actions && next.actions !== state.actions + ? [{ type: "mount-actions" as const, block: block(next.actions) }] + : []), + ...(nextPlugin && nextPlugin.attempts !== plugin + ? [{ type: "mount-plugin" as const, attempt: nextPlugin.attempts, block: block(nextPlugin.plugin) }] + : []), + ...(nextRender && nextRender !== render + ? [{ type: "render-mermaid" as const, attempt: nextRender.attempt, input: nextRender.input }] + : []), + ] + + return { state: next, effects } +} + +function block(key: CodeBlockKey): MarkdownCodeBlock { + return { code: key.source.replace(/\n$/, ""), language: key.language } +} + +function sameBlock(key: CodeBlockKey, event: Pick) { + return key.match === event.match && key.language === event.language && key.source === event.source +} diff --git a/packages/session-ui/src/components/markdown.tsx b/packages/session-ui/src/components/markdown.tsx index 995f77e1f12..f0e3ad7cdd7 100644 --- a/packages/session-ui/src/components/markdown.tsx +++ b/packages/session-ui/src/components/markdown.tsx @@ -37,6 +37,13 @@ import { type MarkdownCacheEntry, } from "./markdown-cache" import { inlineCodeKind } from "./markdown-inline-code-kind" +import { + INITIAL_CODE_DECORATION_STATE, + transitionCodeDecoration, + viewCodeDecoration, + type CodeDecorationEffect, + type CodeDecorationEvent, +} from "./markdown-code-machine" import { renderMermaidSvg } from "./markdown-mermaid" import { createMarkdownRenderer } from "./markdown-solid" import { @@ -208,18 +215,7 @@ function setCopyState(host: HTMLElement, labels: CopyLabels, copied: boolean) { host.removeAttribute("data-copied") } -// The Solid roots a code block holds besides its Copy button: plugin content and action buttons. -const codeHostDisposers = new WeakMap void>() - -const codeHostSelector = - '[data-slot="markdown-copy-button"], [data-slot="markdown-code-actions"], [data-slot="markdown-code-content"]' - -function disposeCodeHost(host: HTMLElement) { - copyButtonState.get(host)?.dispose() - copyButtonState.delete(host) - codeHostDisposers.get(host)?.() - codeHostDisposers.delete(host) -} +const codeHostSelector = '[data-slot="markdown-copy-button"], [data-component="markdown-code"]' function disposeCodeHosts(root: Element) { const hosts = [ @@ -227,7 +223,12 @@ function disposeCodeHosts(root: Element) { ...Array.from(root.querySelectorAll(codeHostSelector)).filter((el): el is HTMLElement => el instanceof HTMLElement), ] - hosts.forEach(disposeCodeHost) + hosts.forEach((host) => { + copyButtonState.get(host)?.dispose() + copyButtonState.delete(host) + codeDrivers.get(host)?.dispatch({ type: "disposed" }) + codeDrivers.delete(host) + }) } function disposeRenderedMarkdown(root: Element) { @@ -263,114 +264,29 @@ function applyCodeMetadata(wrapper: HTMLElement, language: string | undefined) { else delete wrapper.dataset.codeKind } -function decorateMermaid(wrapper: HTMLElement, code: HTMLElement, complete: boolean) { - if (!code.classList.contains("language-mermaid")) { - clearMermaid(wrapper) - - return - } - - const source = code.textContent ?? "" - - if (!source) return - const diagram = wrapper.querySelector('[data-component="markdown-mermaid"]') ?? document.createElement("div") - diagram.setAttribute("data-component", "markdown-mermaid") - - if (!diagram.parentElement) wrapper.appendChild(diagram) - wrapper.dataset.mermaidPending = "true" - const input = complete ? source : source.slice(0, source.lastIndexOf("\n") + 1) - - if (!input) return - const attempt = `${complete ? "complete" : "streaming"}:${input.length}` - - if (wrapper.dataset.mermaidAttempt === attempt) return - wrapper.dataset.mermaidAttempt = attempt - void renderMermaidSvg(input) - .then((svg) => { - if (!svg) { - if (complete && code.textContent === source) clearMermaid(wrapper) - - return - } - - if (!(code.textContent ?? "").startsWith(input)) return - diagram.innerHTML = svg - delete wrapper.dataset.mermaidPending - wrapper.dataset.mermaidReady = "true" - }) - .catch(() => { - if (!complete || code.textContent !== source) return - clearMermaid(wrapper) - }) -} - -function clearMermaid(wrapper: HTMLElement) { - delete wrapper.dataset.mermaidAttempt - delete wrapper.dataset.mermaidPending - delete wrapper.dataset.mermaidReady - wrapper.querySelector('[data-component="markdown-mermaid"]')?.remove() -} - type CodePlugins = { blocks: MarkdownCodeBlocks; match: MarkdownCodeBlockMatch } -type CodeMount = { match: MarkdownCodeBlockMatch; source: string; content?: HTMLElement } +// The plugins are the driver's input for mounting; the block's phase lives only in the machine's state. +type CodeDriver = { plugins: CodePlugins | undefined; dispatch: (event: CodeDecorationEvent) => void } -const codeMounts = new WeakMap() +const codeDrivers = new WeakMap() + +// Plugin content mounted into a block; `dispose` arrives once the plugin's render returns. +type CodeContent = { host: HTMLElement; dispose?: () => void } // Content for a block's language replaces its code only once the closing fence arrived, so it never receives half a // block; until then, and when the content declines or fails, the block shows its code (or the built-in diagram). -// Blocks of other languages take the plain path. +// Blocks of other languages take the plain path and never get a driver. function decorateCode(wrapper: HTMLElement, code: HTMLElement, complete: boolean, plugins: CodePlugins | undefined) { - const previous = codeMounts.get(wrapper) - - if (!plugins && !previous) return decorateMermaid(wrapper, code, complete) - const language = codeLanguage(wrapper.dataset.language) - const claimed = !!plugins?.match.render.has(language) - const acted = complete && !!plugins?.match.actions.has(language) + const existing = codeDrivers.get(wrapper) - if (!previous && !acted && !(claimed && complete)) - return claimed ? clearMermaid(wrapper) : decorateMermaid(wrapper, code, complete) + if (!existing && !plugins && language !== "mermaid") return + const driver = existing ?? createCodeDriver(wrapper) - const source = (code.textContent ?? "").replace(/\n$/, "") - - if (previous?.match === plugins?.match && previous?.source === source) return - - if (previous) clearCodeMount(wrapper, previous) - - if (!plugins || (!claimed && !acted)) return decorateMermaid(wrapper, code, complete) - - if (!complete) return clearMermaid(wrapper) - - const block = { code: source, language } - const mount: CodeMount = { match: plugins.match, source } - codeMounts.set(wrapper, mount) - - if (acted) - wrapper.insertBefore( - createCodeActions(plugins.blocks, block), - wrapper.querySelector(':scope > [data-slot="markdown-copy-button"]'), - ) - - if (!claimed) return decorateMermaid(wrapper, code, complete) - - clearMermaid(wrapper) - const content = document.createElement("div") - content.dataset.slot = "markdown-code-content" - mount.content = content - wrapper.dataset.codeContent = "" - wrapper.appendChild(content) - - const dispose = plugins.blocks.render(content, block, () => { - if (mount.content === content) showCode(wrapper, code, mount) - }) - - // The content already failed while it rendered. - if (mount.content !== content) return dispose?.() - - if (!dispose) return showCode(wrapper, code, mount) - - codeHostDisposers.set(content, dispose) + if (!existing) codeDrivers.set(wrapper, driver) + driver.plugins = plugins + driver.dispatch({ type: "sync", language, source: code.textContent ?? "", complete, match: plugins?.match }) } // Matches the language the worker's parser puts in a block's class, so streamed and completed blocks agree. @@ -378,61 +294,126 @@ function codeLanguage(language: string | undefined) { return (language ?? "").toLowerCase().replace(/[^\w#+.-]/g, "") } -function showCode(wrapper: HTMLElement, code: HTMLElement, mount: CodeMount) { - const content = mount.content - mount.content = undefined - delete wrapper.dataset.codeContent +function createCodeDriver(wrapper: HTMLElement): CodeDriver { + let state = INITIAL_CODE_DECORATION_STATE + let actions: { host: HTMLElement; dispose: () => void } | undefined + let content: CodeContent | undefined - if (content) { - disposeCodeHost(content) - content.remove() + const dispatch = (event: CodeDecorationEvent) => { + const previous = state + const next = transitionCodeDecoration(state, event) + + if (next.state === previous) return + state = next.state + showCodeDecoration(wrapper, viewCodeDecoration(previous), viewCodeDecoration(state)) + next.effects.forEach(run) } - decorateMermaid(wrapper, code, true) + const run = (effect: CodeDecorationEffect) => { + if (effect.type === "clear-actions") { + actions?.dispose() + actions?.host.remove() + actions = undefined + + return + } + + if (effect.type === "clear-plugin") { + content?.dispose?.() + content?.host.remove() + content = undefined + + return + } + + if (effect.type === "render-mermaid") { + void renderMermaidSvg(effect.input).then( + (svg) => dispatch({ type: "mermaid.resolved", attempt: effect.attempt, svg }), + () => dispatch({ type: "mermaid.failed", attempt: effect.attempt }), + ) + + return + } + + const blocks = driver.plugins?.blocks + + if (effect.type === "mount-actions") { + if (!blocks) return + actions = createCodeActions(blocks, effect.block) + wrapper.insertBefore(actions.host, wrapper.querySelector(':scope > [data-slot="markdown-copy-button"]')) + + return + } + + const host = document.createElement("div") + host.dataset.slot = "markdown-code-content" + wrapper.appendChild(host) + const mounted: CodeContent = { host } + content = mounted + const fallback = () => dispatch({ type: "plugin.failed", attempt: effect.attempt }) + const dispose = blocks?.render(host, effect.block, fallback) + + // The content already failed while it rendered. + if (content !== mounted) return dispose?.() + + if (!dispose) return fallback() + mounted.dispose = dispose + } + + const driver: CodeDriver = { plugins: undefined, dispatch } + + return driver } -function clearCodeMount(wrapper: HTMLElement, mount: CodeMount) { - codeMounts.delete(wrapper) - mount.content = undefined - delete wrapper.dataset.codeContent - wrapper - .querySelectorAll( - ':scope > [data-slot="markdown-code-actions"], :scope > [data-slot="markdown-code-content"]', - ) - .forEach((host) => { - disposeCodeHost(host) - host.remove() - }) +function showCodeDecoration( + wrapper: HTMLElement, + previous: ReturnType, + view: ReturnType, +) { + if (view.pending) wrapper.dataset.mermaidPending = "true" + else delete wrapper.dataset.mermaidPending + + if (view.svg !== undefined) wrapper.dataset.mermaidReady = "true" + else delete wrapper.dataset.mermaidReady + wrapper.toggleAttribute("data-code-content", view.content) + const existing = wrapper.querySelector(':scope > [data-component="markdown-mermaid"]') + + if (!view.diagram) return existing?.remove() + const diagram = existing ?? document.createElement("div") + + if (!existing) { + diagram.setAttribute("data-component", "markdown-mermaid") + wrapper.appendChild(diagram) + } + + if (!existing || view.svg !== previous.svg) diagram.innerHTML = view.svg ?? "" } function createCodeActions(blocks: MarkdownCodeBlocks, block: MarkdownCodeBlock) { const host = document.createElement("div") host.setAttribute("data-slot", "markdown-code-actions") - codeHostDisposers.set( - host, - render( - () => ( - - {(action) => ( - - } - onClick={() => action.run(block)} - /> - - )} - - ), - host, + const dispose = render( + () => ( + + {(action) => ( + + } + onClick={() => action.run(block)} + /> + + )} + ), + host, ) - return host + return { host, dispose } } function markCodeLinks(root: HTMLDivElement) {