From fe06211775d2a3454e015917332b1c5c6f84b8ef Mon Sep 17 00:00:00 2001 From: OCILY Date: Fri, 23 Oct 2026 12:29:42 +0800 Subject: [PATCH] fix(mermaid): isolate diagram layout in a sandboxed iframe Mermaid measures every label with SVGElement.getBBox() against a node appended to document.body, so each measurement flushes the whole host document's layout. Measured in the live DSH window (15,418 DOM nodes): 59-75 ms per measurement, versus 1 ms in an empty iframe document. One diagram therefore took 1.5-7.3 s, and a 31-diagram markdown document kept the renderer main thread blocked for >20 s - long enough for the desktop shell's surface watchdog to kill the renderer, with tab restoration turning it into a crash loop. CSS containment on the app root does not help (59-62 ms); only an independent layout tree does. Render diagrams inside a hidden sandboxed iframe instead: a self-contained blob: document (mermaid UMD bundle + a small postMessage protocol, both inlined by scripts/build-mermaid-frame-asset.mjs) renders each diagram; the parent only sends/receives and sanitizes the SVG. Diagrams now take 30-104 ms each and 31 diagrams complete in ~5 s in the background, while the client mermaid chunk shrinks from 7.04 MB to 3.69 MB (minified UMD replaces the unminified inline bundle). Also add a shared render queue: visible/near-viewport diagrams first, the rest filled in on requestIdleCallback with 16 ms main-thread yields between renders, so every diagram is still rendered (none degrades to a code block). Fence-line-sized placeholder skeletons reserve height while a diagram waits. No host-half route changes are needed. --- .gitignore | 3 + CHANGELOG.md | 1 + CHANGELOG_EN.md | 4 + .../2026-10-23-mermaid-iframe-isolation.md | 134 ++++++++++++ package.json | 9 +- scripts/build-mermaid-frame-asset.mjs | 140 ++++++++++++ src/client/mermaid-frame.ts | 169 ++++++++++++++ src/client/mermaid.tsx | 207 ++++++++++++++---- src/client/sidebar.module.css | 49 +++++ tests/mermaid-frame-asset.spec.ts | 29 +++ tests/mermaid-markdown.spec.tsx | 111 ++++++++-- tests/steady-state.spec.tsx | 5 +- 12 files changed, 794 insertions(+), 67 deletions(-) create mode 100644 docs/plans/2026-10-23-mermaid-iframe-isolation.md create mode 100644 scripts/build-mermaid-frame-asset.mjs create mode 100644 src/client/mermaid-frame.ts create mode 100644 tests/mermaid-frame-asset.spec.ts diff --git a/.gitignore b/.gitignore index 4cbe7d3a..cb9fe3c9 100644 --- a/.gitignore +++ b/.gitignore @@ -154,3 +154,6 @@ registry/ playwright-report/ test-results/ + +# generated by scripts/build-mermaid-frame-asset.mjs +src/client/mermaid-frame-asset.generated.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 7beabaf3..17381e54 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,6 +51,7 @@ - **任务页拖拽改为每帧一次更新**:图模式背景平移、后台任务浮窗标题拖动、锚定弹层拖动不再按鼠标事件频率重绘(高回报率鼠标下此前每个 pointermove 都提交整块画布);松手同步落位,点击判定与最终位置不变。实测同一帧内 100 次移动的画布提交由 98 次降到 1 次。 - **已结束分支整体聚合**:只有整条分支全部结束才自动聚合;仍有运行后代、当前查看路径或未知子代理目录的分支保持可见,聚合计数覆盖隐藏的 Agent 后代。 - **四项独立自动规则**:复用设置齿轮与现有偏好存储,分别控制已结束叶子聚合、已结束分支聚合、同一父级至少 3 个空闲队友聚合(workflow 内沿用原规则,也受空闲开关控制),以及 Agent 总数至少 8 个时后台任务抽屉自动收起,默认全部开启。未手动操作时设置即时生效;手动展开或收起始终优先。 +- ⚡ **大 Markdown 的 Mermaid 预览不再卡死渲染器(chunk 内测量隔离到沙箱 iframe)**:Mermaid 用 `SVGElement.getBBox()` 量文字,测量节点挂在 `document.body` 上 → 每次测量都刷新整个 DSH 文档布局。真机实测一次 `getBBox` **59–75 ms**(15,418 节点),空 iframe 里只要 **1 ms**;31 张图因此阻塞主线程 >20 s,触发桌面壳看门狗杀渲染器,恢复标签页后循环卡死。现在图表改在隐藏的 `sandbox="allow-scripts"` iframe(blob: 自包含 mermaid UMD + 协议)里渲染,父侧只做 postMessage 收发与 SVG 清洗:**单图 1,500–7,300 ms → 30–104 ms,31 图约 5 s 内完成**,客户端 mermaid chunk 同时从 **7.04 MB → 3.69 MB**。另加共享渲染队列(可见/近视口优先,其余 `requestIdleCallback` 逐张补齐,两次之间让出 16 ms 主线程;**所有图最终都会渲染成图,不再退化为代码块**)与按围栏行数预留高度的占位骨架。设计与实测见 [docs/plans/2026-10-23-mermaid-iframe-isolation.md](docs/plans/2026-10-23-mermaid-iframe-isolation.md)。 ### v0.28.0 diff --git a/CHANGELOG_EN.md b/CHANGELOG_EN.md index 094f26ee..fa1fc436 100644 --- a/CHANGELOG_EN.md +++ b/CHANGELOG_EN.md @@ -4,6 +4,10 @@ > > 📝 The Chinese [CHANGELOG](./CHANGELOG.md) is the authoritative, item-by-item record; this file carries the English summaries and has historically lagged behind it. Where the two disagree, the Chinese one is current. +### Unreleased + +- ⚡ **Mermaid previews of large Markdown documents no longer stall the renderer (layout measurement isolated in a sandboxed iframe)**: mermaid measures label text with `SVGElement.getBBox()` against a node appended to `document.body`, so every measurement flushes the whole DSH document layout — measured on a real desktop host at **59–75 ms per measurement** (15,418 nodes) versus **1 ms** in an empty iframe. A 31-diagram document therefore blocked the main thread for >20 s, tripping the desktop shell's surface watchdog and turning tab restoration into a crash loop. Diagrams now render inside a hidden `sandbox="allow-scripts"` iframe (a self-contained blob: document with the mermaid UMD bundle inlined plus a small postMessage protocol); the parent only sends/receives and sanitizes SVG: **per diagram 1,500–7,300 ms → 30–104 ms, 31 diagrams in ~5 s**, while the client mermaid chunk shrinks from **7.04 MB to 3.69 MB**. A shared render queue (visible/near-viewport diagrams first, the rest filled in on `requestIdleCallback`, 16 ms main-thread yields between renders — **every diagram is still rendered, none degrades to a code block**) and fence-line-sized placeholder skeletons complete the change. Design and measurements: [docs/plans/2026-10-23-mermaid-iframe-isolation.md](docs/plans/2026-10-23-mermaid-iframe-isolation.md). + ### v0.29.0 - **GenUI in side chats**: the existing `ctx.betterSidebar` service exposes the opt-in `registerSidechatSurfaceAdapter` for GenUI 0.15.0 to render settled assistant replies. Without a consumer, Markdown rendering stays unchanged. diff --git a/docs/plans/2026-10-23-mermaid-iframe-isolation.md b/docs/plans/2026-10-23-mermaid-iframe-isolation.md new file mode 100644 index 00000000..ffd37a8c --- /dev/null +++ b/docs/plans/2026-10-23-mermaid-iframe-isolation.md @@ -0,0 +1,134 @@ +# Markdown 预览 Mermaid 图表:布局测量隔离到沙箱 iframe + +- 日期:2026-10-23 +- 影响面:`src/client/mermaid.tsx`、`src/client/mermaid-frame.ts`(新增)、 + `scripts/build-mermaid-frame-asset.mjs`(新增)、`src/client/sidebar.module.css` +- 关联:v0.13.1 引入的 Mermaid 预览(#164)、#341(`suppressErrorRendering`) + +## 1. 现象 + +在 DSH Desktop(Windows,DSH 0.2.1-rc.2,插件 0.28.0)中打开一份约 90 KB、含 31 个 +mermaid 围栏的 Markdown(`SYSTEM_ARCHITECTURE.md`)时页面卡死:桌面壳日志出现 + +``` +renderer surface watchdog: page did not respond +terminating unresponsive renderer +unresponsive renderer replaced (reason: crashed, exitCode: 2) +``` + +后渲染器被杀、页面重载;侧栏恢复上次标签页后再次卡死,形成崩溃循环。 +同尺寸、把 mermaid 围栏换成普通代码围栏的文档打开完全正常 → 问题锁定在 Mermaid +预览渲染链路,而不是文档大小或 Markdown 解析。 + +## 2. 根因(真机实测) + +Mermaid 用 `SVGElement.getBBox()` 给每个标签测量文字尺寸(`calculateTextDimensions` +把测点 `` 追加到 `document.body`)。该测量与**整个宿主文档的布局**共享一个布局树: + +| 测量环境 | 一次 `getBBox` | 说明 | +|---|---|---| +| 真实 DSH 窗口(15,418 个 DOM 节点、复杂样式) | **59–75 ms** | 每次测量触发一次文档级样式/布局刷新 | +| 空 iframe 文档 | **1 ms** | 独立、极小的布局树 | + +一张图要做几十次测量,因此单图 **1.5–7.3 秒**;旧实现把文档里所有图在挂载时同时 +发起渲染(每块一个 React root + `mermaid.render` 并行),31 张图累计让主线程连续 +无响应 > 20 秒,超过桌面壳看门狗(5s 探测 / 10s 超时 / 连续 2 次)阈值。 + +对照实验(同页面内探针,2026-10-23): + +- `#root { contain: layout style }` / `contain: strict`:**无改善**(59/62 ms); +- `#root { content-visibility: hidden }`:1 ms,但会隐藏整个界面,不可接受; +- 同源空 iframe 内测量:**1 ms**。 + +结论:唯一既能保持界面可见、又能去掉测量成本的隔离边界是**独立的 iframe 文档**。 + +## 3. 方案 + +### 3.1 自包含的沙箱 iframe(渲染器) + +`src/client/mermaid-frame.ts`: + +- 首次需要渲染图表时懒创建隐藏 iframe: + `sandbox="allow-scripts"`(**不带 allow-same-origin**,opaque origin,无法访问 GUI + 文档),`position:fixed` 移到视口外、`visibility:hidden`; +- `src` 为 `blob:` URL,内容由 `MERMAID_FRAME_HTML` 提供(见 3.2); +- postMessage 协议: + - 父 → 子:`{ type: 'mermaid-render', id, code, theme }` + - 子 → 父:`{ type: 'mermaid-result', id, svg }` / `{ type: 'mermaid-error', id, message }` + - 子就绪:`{ type: 'mermaid-frame-ready' }` +- 单例复用、单请求 30s 超时、就绪 10s 超时;失败自动重建一次,连续失败后该页面 + 停止重试并让对应图走「错误 + 源码」兜底(仅故障时,不用于正常路径); +- 父侧仍在 `sanitizeSvg()` 之后注入 SVG,安全链路不变。 + +iframe 内的 iframe 协议(`FRAME_API`)负责 `mermaid.initialize()` 与 `render()`: +`securityLevel: 'strict'`、`htmlLabels: false`、`suppressErrorRendering: true`, +主题随请求传入(`'dark' | 'default'`)。 + +### 3.2 自包含资产(无 host 路由) + +`scripts/build-mermaid-frame-asset.mjs` 用插件自己的 `mermaid` 依赖 +(`mermaid/dist/mermaid.min.js`,UMD)与 `FRAME_API` 拼成一个完整 HTML,把两个 +` + +mermaid frame + + + + + + + +` + +/** The generated module. */ +const generated = `/** + * GENERATED by scripts/build-mermaid-frame-asset.mjs — do not edit. + * + * Self-contained mermaid iframe document (inline mermaid UMD + frame + * protocol). See src/client/mermaid-frame.ts for why the preview renders + * diagrams inside an iframe at all. + */ +// The explicit \`: string\` annotation keeps the ~3.5 MB literal out of the +// emitted .d.ts (otherwise tsc expands it into the declaration). +export const MERMAID_FRAME_HTML: string = ${JSON.stringify(frameHtml)} +` + +const target = new URL('../src/client/mermaid-frame-asset.generated.ts', import.meta.url) +writeFileSync(target, generated) +console.log( + 'mermaid frame asset written:', + `${(generated.length / 1024 / 1024).toFixed(2)} MB`, + '(mermaid UMD', + `${(mermaidSource.length / 1024 / 1024).toFixed(2)} MB)`, +) diff --git a/src/client/mermaid-frame.ts b/src/client/mermaid-frame.ts new file mode 100644 index 00000000..98eed12d --- /dev/null +++ b/src/client/mermaid-frame.ts @@ -0,0 +1,169 @@ +/** + * Client half of the isolated mermaid renderer. + * + * Mermaid sizes every label with `SVGElement.getBBox()`. In the live DSH + * window one such measurement costs ~60-75ms (the document is large and + * style-heavy, and the measurement node is appended to its body), so a single + * diagram takes seconds and a document with dozens of them keeps the renderer + * busy for minutes — long enough for the desktop shell's surface watchdog to + * kill the page. An iframe has its own small layout tree: the same measurement + * costs ~1ms, so diagrams render in milliseconds and the host window never + * blocks. + * + * The frame is self-contained (the mermaid UMD bundle and protocol are inlined + * by scripts/build-mermaid-frame-asset.mjs) and sandboxed WITHOUT + * `allow-same-origin`: it runs only our own rendering code, cannot touch the + * GUI document, and needs no host route. It is created lazily on the first + * diagram and reused for every following render on the page. + */ +import { MERMAID_FRAME_HTML } from './mermaid-frame-asset.generated.ts' + +export type MermaidTheme = 'dark' | 'default' + +/** Frame viewport width: the empty document diagrams are laid out against. */ +const FRAME_WIDTH = 1200 +const FRAME_HEIGHT = 900 +const FRAME_READY_TIMEOUT_MS = 10_000 +const FRAME_RENDER_TIMEOUT_MS = 30_000 + +/** One pending render waiting on the frame's postMessage answer. */ +interface PendingRender { + resolve: (svg: string) => void + reject: (error: Error) => void + timer: number +} + +const pending = new Map() +let requestSeq = 0 +let frame: HTMLIFrameElement | null = null +let frameReady: Promise | null = null +let frameObjectUrl: string | null = null +let messageListenerInstalled = false +/** Set once the frame failed to load twice: stop paying the timeout per diagram. */ +let frameUnavailable = false + +/** Test seam: jsdom cannot run the real frame asset, so specs replace the + * renderer with a stub. `null` restores the real one. */ +let testRenderer: ((code: string, theme: MermaidTheme) => Promise) | null = null +export function setMermaidFrameRendererForTests( + renderer: ((code: string, theme: MermaidTheme) => Promise) | null, +): void { + testRenderer = renderer +} + +/** Route the frame's result/error messages to their pending render. */ +function installMessageListener(): void { + if (messageListenerInstalled) return + messageListenerInstalled = true + window.addEventListener('message', (event: MessageEvent) => { + const data = event.data as { type?: unknown; id?: unknown; svg?: unknown; message?: unknown } | null + if (data === null || typeof data !== 'object') return + if (data.type !== 'mermaid-result' && data.type !== 'mermaid-error') return + const id = typeof data.id === 'number' ? data.id : -1 + const entry = pending.get(id) + if (entry === undefined) return + pending.delete(id) + window.clearTimeout(entry.timer) + if (data.type === 'mermaid-result' && typeof data.svg === 'string') entry.resolve(data.svg) + else entry.reject(new Error(typeof data.message === 'string' ? data.message : 'mermaid frame render failed')) + }) +} + +/** Drop the current frame (failed load, page teardown) and its blob URL. */ +function disposeFrame(): void { + frameReady = null + if (frame !== null) { + frame.remove() + frame = null + } + if (frameObjectUrl !== null) { + URL.revokeObjectURL(frameObjectUrl) + frameObjectUrl = null + } +} + +/** Create the hidden frame and resolve once its protocol posted `ready`. */ +function ensureFrame(): Promise { + if (frameReady !== null) return frameReady + installMessageListener() + frameReady = new Promise((resolve, reject) => { + const iframe = document.createElement('iframe') + // Opaque-origin sandbox: the frame runs only our inlined mermaid bundle and + // not the host origin's APIs. postMessage is the only bridge. + iframe.setAttribute('sandbox', 'allow-scripts') + iframe.setAttribute('aria-hidden', 'true') + iframe.tabIndex = -1 + iframe.style.cssText = `position:fixed;left:-12000px;top:0;width:${FRAME_WIDTH}px;height:${FRAME_HEIGHT}px;border:0;visibility:hidden;pointer-events:none` + let settled = false + const settle = (error?: Error): void => { + if (settled) return + settled = true + window.removeEventListener('message', onReady) + window.clearTimeout(timer) + if (error !== undefined) { + disposeFrame() + reject(error) + return + } + resolve() + } + const onReady = (event: MessageEvent): void => { + if (event.source !== iframe.contentWindow) return + const data = event.data as { type?: unknown } | null + if (data !== null && typeof data === 'object' && data.type === 'mermaid-frame-ready') settle() + } + const timer = window.setTimeout(() => { + settle(new Error('mermaid frame did not become ready')) + }, FRAME_READY_TIMEOUT_MS) + window.addEventListener('message', onReady) + frameObjectUrl = URL.createObjectURL(new Blob([MERMAID_FRAME_HTML], { type: 'text/html' })) + iframe.src = frameObjectUrl + document.body.appendChild(iframe) + frame = iframe + }) + return frameReady +} + +/** Ask the frame to render one diagram and resolve with the raw SVG markup. */ +async function renderInFrame(code: string, theme: MermaidTheme): Promise { + await ensureFrame() + const target = frame?.contentWindow + if (target === null || target === undefined) throw new Error('mermaid frame disappeared') + const id = ++requestSeq + return new Promise((resolve, reject) => { + const timer = window.setTimeout(() => { + pending.delete(id) + reject(new Error('mermaid frame render timed out')) + }, FRAME_RENDER_TIMEOUT_MS) + pending.set(id, { resolve, reject, timer }) + target.postMessage({ type: 'mermaid-render', id, code, theme }, '*') + }) +} + +/** + * Render one mermaid diagram off the host document's layout. + * @param code - the diagram source (one fenced block body). + * @param theme - mermaid theme to render with (follows the color scheme). + * @returns the raw SVG markup (sanitized by the caller before injection). + */ +export async function renderMermaidDiagram(code: string, theme: MermaidTheme): Promise { + if (testRenderer !== null) return testRenderer(code, theme) + if (frameUnavailable) throw new Error('mermaid rendering frame is unavailable') + try { + return await renderInFrame(code, theme) + } catch (_firstError) { + // One retry with a fresh frame covers a transient load failure; a second + // failure marks the frame unusable so later diagrams fail fast (the + // diagram body then shows the error + source instead of a placeholder). + disposeFrame() + try { + return await renderInFrame(code, theme) + } catch (secondError) { + frameUnavailable = true + throw new Error( + `mermaid frame unavailable: ${secondError instanceof Error ? secondError.message : String(secondError)}`, + { cause: secondError }, + ) + } + } +} diff --git a/src/client/mermaid.tsx b/src/client/mermaid.tsx index 5f78f920..5b00ad34 100644 --- a/src/client/mermaid.tsx +++ b/src/client/mermaid.tsx @@ -27,7 +27,6 @@ import { useCallback, useEffect, useLayoutEffect, useRef, useState, type MouseEvent as ReactMouseEvent } from 'react' import { createPortal } from 'react-dom' import { createRoot, type Root } from 'react-dom/client' -import mermaid from 'mermaid' import { IconCopyOutlineRegular, MarkdownText, writeClipboard } from '@deepseek-ai/dsh-client-ui-primitives' import { isDarkScheme, subscribeColorScheme } from './theme.ts' import { markdownTextProps } from './markdown-labels.tsx' @@ -35,27 +34,100 @@ import { t } from './locales.ts' import { sanitizeSvg } from './mermaid-sanitize.ts' import type { MermaidMarkdownProps } from './mermaid-blocks.ts' import { splitMermaidBlocks } from './mermaid-blocks.ts' +import { renderMermaidDiagram, type MermaidTheme } from './mermaid-frame.ts' import css from './sidebar.module.css' -/** Monotonic id seed: every render call gets a fresh, document-unique id. */ -let mermaidSeq = 0 +/** Render queue priorities: a diagram the reader can see goes first, the rest + * render while the browser is idle. */ +type MermaidPriority = 0 | 1 -/** Configure mermaid for the current color scheme (idempotent). */ -function configureMermaid(): void { - mermaid.initialize({ - startOnLoad: false, - securityLevel: 'strict', - // Labels as real SVG : mermaid's default htmlLabels renders node - // text inside , which the sanitizer strips wholesale — - // forcing pure SVG text keeps labels visible and the HTML label channel - // closed (strict already escapes label content). - htmlLabels: false, - // Mermaid 11 renders a large error SVG into document.body before rejecting - // invalid diagrams. The component already has its own error fallback, so - // suppress that global side effect to keep the DSH shell intact. - suppressErrorRendering: true, - theme: isDarkScheme() ? 'dark' : 'default', - }) +interface MermaidTask { + priority: MermaidPriority + run: () => Promise +} + +/** Pending renders, shared by every mounted preview on the page. */ +const mermaidQueue: MermaidTask[] = [] +let mermaidPumping = false +/** Incremented when a test tears the queue down; a drain loop from an older + * epoch stops at its next await instead of driving the fresh queue. */ +let mermaidQueueEpoch = 0 + +/** Drop every queued render and detach the current drain loop (test seam: + * module state persists across specs in one vitest file). */ +export function resetMermaidRenderQueueForTests(): void { + mermaidQueueEpoch += 1 + mermaidQueue.length = 0 + mermaidPumping = false +} + +/** Run a callback once the main thread is idle (bounded, so diagrams cannot + * starve forever while the page stays busy). */ +function whenIdle(callback: () => void): void { + if (typeof requestIdleCallback === 'function') { + requestIdleCallback(() => { callback() }, { timeout: 400 }) + return + } + setTimeout(callback, 0) +} + +/** + * Drain the render queue one diagram at a time. + * + * Rendering every fence of a document in one commit (the behaviour this + * replaced) could hold the main thread for minutes on diagram-heavy documents + * — long enough for the desktop shell's surface watchdog to declare the page + * unresponsive and kill it. The queue interleaves a visible diagram ahead of + * the background ones and gives the browser (input, layout, the watchdog's + * probe) a turn between two renders, so a document with dozens of diagrams + * stays interactive and every diagram still ends up rendered. + */ +async function drainMermaidQueue(): Promise { + if (mermaidPumping) return + mermaidPumping = true + const epoch = mermaidQueueEpoch + try { + while (epoch === mermaidQueueEpoch && mermaidQueue.length > 0) { + mermaidQueue.sort((a, b) => a.priority - b.priority) + const task = mermaidQueue.shift() + if (task === undefined) break + await new Promise((resolve) => { whenIdle(resolve) }) + if (epoch !== mermaidQueueEpoch) break + try { + await task.run() + } catch (error) { + // One broken fence must not stall the queue behind it. + console.error('[dsh-better-sidebar] mermaid render failed', error) + } + await new Promise((resolve) => { setTimeout(resolve, 16) }) + } + } finally { + if (epoch === mermaidQueueEpoch) mermaidPumping = false + } +} + +/** Queue one diagram render; {@link drainMermaidQueue} runs it. */ +function pushMermaidTask(priority: MermaidPriority, run: () => Promise): void { + mermaidQueue.push({ priority, run }) + void drainMermaidQueue() +} + +/** True when the block is at most about one viewport away from the visible + * area. A mounted-but-hidden body (parked tab, closed drawer) has a zero box; + * it is treated as off-screen so its diagrams take the idle path. */ +function isNearViewport(node: HTMLElement): boolean { + const rect = node.getBoundingClientRect() + if (rect.width === 0 && rect.height === 0) return false + const margin = window.innerHeight * 1.25 + return rect.bottom > -margin && rect.top < window.innerHeight + margin +} + +/** Rough first-paint height for the placeholder, derived from the fence's line + * count. Reserving some height keeps the article from jumping under the + * reader's cursor when the diagram arrives. */ +function placeholderHeight(code: string): number { + const lines = code.split('\n').length + return Math.min(480, Math.max(120, lines * 14)) } /** First lines of a mermaid error (its dumps are huge; the head explains). */ @@ -228,33 +300,74 @@ function MermaidDiagram({ code }: { code: string }): React.ReactNode { /** The cloned svg shown in the zoom modal (null = closed). */ const [zoomSvg, setZoomSvg] = useState(null) const copyTimer = useRef(undefined) + /** The wrapper the visibility observer watches; also the placeholder host. */ + const wrapRef = useRef(null) + /** Bumped whenever the source/theme changes or the component unmounts; a + * render result belonging to an older generation is dropped. */ + const generationRef = useRef(0) + /** Generation whose render is already queued (one task per generation). */ + const scheduledRef = useRef(-1) useEffect(() => subscribeColorScheme(() => { setDark(isDarkScheme()) }), []) + /** Render the current source and publish the sanitized SVG. */ + const renderNow = useCallback(async (): Promise => { + const generation = generationRef.current + const theme: MermaidTheme = dark ? 'dark' : 'default' + try { + const rendered = await renderMermaidDiagram(code, theme) + if (generation !== generationRef.current) return + const clean = sanitizeSvg(rendered) + if (clean === '') { + // Parse/sanitize rejection: never pass the raw string through. + setError(t('mermaidError')) + return + } + setSvg(clean) + } catch (reason) { + if (generation !== generationRef.current) return + setError(summarizeError(reason)) + } + }, [code, dark]) + + /** Queue one render of the current generation: a visible diagram goes + * first, the rest render on the idle path. */ + const scheduleRender = useCallback((priority: MermaidPriority): void => { + const generation = generationRef.current + if (scheduledRef.current === generation) return + scheduledRef.current = generation + pushMermaidTask(priority, async () => { + if (generation !== generationRef.current) return + await renderNow() + }) + }, [renderNow]) + + // A new source or theme invalidates what is on screen and schedules a render. useEffect(() => { - let cancelled = false + generationRef.current += 1 + scheduledRef.current = -1 setSvg(null) setError(null) - if (code.trim() === '') return () => { cancelled = true } - configureMermaid() - const id = `dsh-md-mermaid-${mermaidSeq += 1}` - mermaid.render(id, code) - .then(({ svg: rendered }) => { - if (cancelled) return - const clean = sanitizeSvg(rendered) - if (clean === '') { - // Parse/sanitize rejection: never pass the raw string through. - setError(t('mermaidError')) - return - } - setSvg(clean) - }) - .catch((reason: unknown) => { - if (cancelled) return - setError(summarizeError(reason)) - }) - return () => { cancelled = true } - }, [code, dark]) + if (code.trim() === '') return + const node = wrapRef.current + scheduleRender(node !== null && isNearViewport(node) ? 0 : 1) + }, [code, dark, scheduleRender]) + + // A placeholder that scrolls into view jumps ahead of the background queue. + useEffect(() => { + const node = wrapRef.current + if (node === null || typeof IntersectionObserver === 'undefined') return + const observer = new IntersectionObserver((entries) => { + if (!entries.some((entry) => entry.isIntersecting)) return + observer.disconnect() + scheduleRender(0) + }, { rootMargin: '800px 0px' }) + observer.observe(node) + return () => { observer.disconnect() } + }, [scheduleRender]) + + // Unmounting the preview drops renders that are still queued. + useEffect(() => () => { generationRef.current += 1 }, []) const onCopy = useCallback(() => { if (copied) return @@ -279,7 +392,7 @@ function MermaidDiagram({ code }: { code: string }): React.ReactNode { } return ( -
+
mermaid
+ {svg === null && error === null && ( +
+ + + +
+ )} {error !== null &&
{t('mermaidError')}
} {svg !== null && (
{ + it('is a self-contained HTML document with the frame protocol', () => { + expect(MERMAID_FRAME_HTML.startsWith('')).toBe(true) + expect(MERMAID_FRAME_HTML).toContain('window.__dshMermaidFrame') + expect(MERMAID_FRAME_HTML).toContain('mermaid-frame-ready') + expect(MERMAID_FRAME_HTML).toContain('dsh-frame-mermaid-') + }) + + it('inlines exactly two script bodies (mermaid UMD + frame protocol)', () => { + // Every `/gi)?.length).toBe(2) + }) + + it('carries the strict mermaid configuration used by the preview', () => { + expect(MERMAID_FRAME_HTML).toContain("securityLevel: 'strict'") + expect(MERMAID_FRAME_HTML).toContain('htmlLabels: false') + expect(MERMAID_FRAME_HTML).toContain('suppressErrorRendering: true') + }) +}) diff --git a/tests/mermaid-markdown.spec.tsx b/tests/mermaid-markdown.spec.tsx index 68a1b6c7..16b730c1 100644 --- a/tests/mermaid-markdown.spec.tsx +++ b/tests/mermaid-markdown.spec.tsx @@ -2,11 +2,12 @@ * MermaidMarkdown architecture spec: the preview renders the WHOLE document * through one MarkdownText pass (cross-fence reference-style links must * resolve — the P1 regression from the CR), then swaps every rendered - * mermaid CodeBlock for a diagram. mermaid is mocked so the swap + semantics - * are asserted without pulling the real layout engine into jsdom. + * mermaid CodeBlock for a diagram. The actual mermaid layout engine runs in + * the isolated iframe (see mermaid-frame.ts), so the specs inject a stub + * renderer instead of pulling mermaid into jsdom. */ // @vitest-environment jsdom -import { describe, expect, it, vi, beforeEach } from 'vitest' +import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest' import { createElement } from 'react' import { createRoot, type Root } from 'react-dom/client' import { act } from 'react-dom/test-utils' @@ -15,17 +16,13 @@ import { act } from 'react-dom/test-utils' import { setupReactAct } from './test-utils.ts' setupReactAct() -vi.mock('mermaid', () => ({ - default: { - initialize: vi.fn(), - render: async () => ({ - svg: 'MOCK-DIAGRAM', - }), - }, -})) +import { MermaidMarkdown, resetMermaidRenderQueueForTests } from '../src/client/mermaid.tsx' +import { setMermaidFrameRendererForTests, type MermaidTheme } from '../src/client/mermaid-frame.ts' -import mermaid from 'mermaid' -import { MermaidMarkdown } from '../src/client/mermaid.tsx' +/** The stub renderer the specs install; each test clears its call log. */ +const renderDiagram = vi.fn(async (_code: string, _theme: MermaidTheme) => ( + 'MOCK-DIAGRAM' +)) const codeLabels = { copyLabel: 'Copy', copiedLabel: 'Copied', codeLabel: 'Code block', wrapLabel: 'Wrap lines', unwrapLabel: 'Do not wrap lines', @@ -37,7 +34,7 @@ async function renderMarkdown(text: string): Promise<{ container: HTMLElement; r const root = createRoot(container) await act(async () => { root.render(createElement(MermaidMarkdown, { text, codeLabels })) - // Let the mocked mermaid.render promise settle inside the act scope. + // Let the queued render + its state update settle inside the act scope. await new Promise(resolve => { setTimeout(resolve, 0) }) }) return { container, root } @@ -47,25 +44,98 @@ async function unmount(root: Root): Promise { await act(async () => { root.unmount() }) } +/** + * Wait until `check` returns a truthy value. Diagram rendering is queued (one + * render at a time, idle slots between them — the whole point of the queue), so + * a swap lands asynchronously instead of in the mount commit. + */ +async function waitFor(check: () => T | null | false, timeoutMs = 3000): Promise { + const startedAt = Date.now() + for (;;) { + const value = check() + if (value) return value + if (Date.now() - startedAt > timeoutMs) throw new Error('timed out waiting for the diagram render') + await act(async () => { await new Promise(resolve => { setTimeout(resolve, 10) }) }) + } +} + beforeEach(() => { document.body.innerHTML = '' + renderDiagram.mockClear() + setMermaidFrameRendererForTests(renderDiagram) +}) + +afterEach(() => { + setMermaidFrameRendererForTests(null) + resetMermaidRenderQueueForTests() }) describe('MermaidMarkdown', () => { it('swaps the mermaid code block for a rendered diagram', async () => { const { container, root } = await renderMarkdown('```mermaid\ngraph TD\n A-->B\n```') - const diagram = container.querySelector('[data-mermaid-diagram] svg') + const diagram = await waitFor(() => container.querySelector('[data-mermaid-diagram] svg')) expect(diagram, 'the mermaid fence must be swapped for a diagram').not.toBeNull() expect(diagram?.textContent).toContain('MOCK-DIAGRAM') await unmount(root) }) - it('suppresses Mermaid global error rendering', async () => { - vi.mocked(mermaid.initialize).mockClear() + it('renders with the current scheme theme through the isolated renderer', async () => { const { root } = await renderMarkdown('```mermaid\ngraph TD\n A-->B\n```') - expect(mermaid.initialize).toHaveBeenCalledWith(expect.objectContaining({ - suppressErrorRendering: true, - })) + await waitFor(() => renderDiagram.mock.calls.length > 0) + expect(renderDiagram).toHaveBeenCalledWith(expect.stringContaining('graph TD'), 'default') + await unmount(root) + }) + + it('shows a sized placeholder while the render is queued, then swaps it out', async () => { + let release: ((svg: string) => void) | null = null + setMermaidFrameRendererForTests(() => new Promise((resolve) => { release = resolve })) + const { container, root } = await renderMarkdown('```mermaid\ngraph TD\n A-->B\n```') + const placeholder = await waitFor(() => container.querySelector('[data-mermaid-pending]')) + expect(placeholder, 'a diagram placeholder is shown while the render is queued').not.toBeNull() + expect(placeholder.style.minHeight, 'the placeholder reserves height so the article does not jump').not.toBe('') + // The queue starts the render on the next idle slot; release it only after + // the stub renderer was actually invoked. + await waitFor(() => (release === null ? null : true)) + await act(async () => { + release?.('LATE-DIAGRAM') + await new Promise(resolve => { setTimeout(resolve, 30) }) + }) + await waitFor(() => container.querySelector('[data-mermaid-diagram] svg')) + expect(container.querySelector('[data-mermaid-pending]'), 'the placeholder is gone once the diagram is in').toBeNull() + await unmount(root) + }) + + it('falls back to the fence source when the renderer fails', async () => { + setMermaidFrameRendererForTests(async () => { throw new Error('boom') }) + const { container, root } = await renderMarkdown('```mermaid\ngraph TD\n A-->B\n```') + const source = await waitFor(() => container.querySelector('pre code')) + expect(source?.textContent, 'a failed render keeps the source visible').toContain('graph TD') + expect(container.querySelector('[data-mermaid-diagram]'), 'no diagram is injected for a failed render').toBeNull() + await unmount(root) + }) + + it('drains every diagram of a multi-fence document', async () => { + const text = [ + '```mermaid', + 'graph TD', + ' A --> B', + '```', + '', + 'prose between fences', + '', + '```mermaid', + 'graph LR', + ' C --> D', + '```', + '', + '```mermaid', + 'sequenceDiagram', + ' A->>B: hi', + '```', + ].join('\n') + const { container, root } = await renderMarkdown(text) + await waitFor(() => container.querySelectorAll('[data-mermaid-diagram] svg').length >= 3 && true) + expect(container.querySelectorAll('[data-mermaid-diagram] svg').length, 'every fence must render, none may stay a code block').toBe(3) await unmount(root) }) @@ -84,6 +154,7 @@ describe('MermaidMarkdown', () => { const link = container.querySelector('a[href="https://example.com"]') expect(link, 'the definition after the fence must resolve the link before it').not.toBeNull() expect(link?.textContent).toContain('before') + await waitFor(() => container.querySelector('[data-mermaid-diagram] svg')) expect(container.querySelector('[data-mermaid-diagram] svg'), 'the diagram must still swap in').not.toBeNull() await unmount(root) }) diff --git a/tests/steady-state.spec.tsx b/tests/steady-state.spec.tsx index 314fedcd..3efd4f85 100644 --- a/tests/steady-state.spec.tsx +++ b/tests/steady-state.spec.tsx @@ -263,14 +263,15 @@ const TIMER_LEDGER: Array<{ file: string; gate: string; why: string }> = [ }, ] -/** `src/client` 下的 .ts/.tsx(跳过惰性 chunk 目录:它们不是常驻面)。 */ +/** `src/client` 下的 .ts/.tsx(跳过惰性 chunk 目录:它们不是常驻面;跳过 + * `*.generated.ts`:构建产出的资产(如内联的 mermaid UMD)不是手写源码)。 */ function clientSources(dir: string, out: string[] = []): string[] { for (const entry of readdirSync(dir, { withFileTypes: true })) { const path = join(dir, entry.name) if (entry.isDirectory()) { if (entry.name === 'chunks') continue clientSources(path, out) - } else if (/\.tsx?$/.test(entry.name)) { + } else if (/\.tsx?$/.test(entry.name) && !entry.name.endsWith('.generated.ts')) { out.push(path) } }