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..58a5988e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ > 本文档收录 dsh-better-sidebar 的完整发布历史(最新版摘要见 [README](README_ZH.md);同步发布于 [GitHub Releases](https://github.com/omdsh-dev/DSH-better-sidebar/releases))。 +### 未发布 + +- ⚡ **大 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)。 +- ⚡ **大文档滚动流畅性:渲染让位于滚动、隐藏页签不空转、摘掉全量 DOM 扫描**:图表渲染队列在滚动期间暂停(停止滚动 350 ms 后恢复),并且只服务当前可见的预览——隐藏页签里的图表保持占位、切回时才渲染;`Markdown` 变更触发的两次全量扫描(内联 HTML pass、标题锚点 pass)由「每次 mutation 跑一遍」(实测 8–15 ms/次)改为 80 ms 合并一次;打开文档时的近视口判断改为先批量读 rect、再统一写入,去掉每张图一次强制布局;`.mermaidWrap` 增加 `content-visibility: auto` + `contain-intrinsic-size` + `contain: layout paint style`,视口外的图表不再参与布局与绘制。滚动时不再有后台渲染、全量扫描与视口外 SVG 重绘抢主线程;图表仍会在滚动停止后或进入视口时补齐,不退化为代码块。 +- 🐞 **图表渲染失败时直接显示 mermaid 的解析错误**:之前只显示通用「Mermaid 渲染失败」+ 源码块(完整错误只在 hover title 里)。现在错误条下方直接给出 mermaid 报错的首两行(如 `Parse error on line 10 ... Expecting 'SEMI', ... got 'UNICODE_TEXT'`),配合下方源码可快速定位坏围栏;错误信息仍完整保留在 title 中。 + ### v0.29.0 - **侧边对话接入 GenUI**:通过现有 `ctx.betterSidebar` 服务新增可选的 `registerSidechatSurfaceAdapter`,支持 GenUI 0.15.0 渲染已结算的助手回复;未注册消费方时保持原 Markdown。 @@ -16,6 +22,7 @@ - 📏 **实测(40,157,518 字节会话,本机重建)**:12 个 `session.cwd` + 36 个绕过入口调用并发 → **1 次 header 读、0 次整读、3 ms、RSS +0.3 MB**;同产物用修复前代码(`43db17f`)跑 6 个绕过入口并发 → 6 次整读、峰值 RSS +1002 MB(外推 36 次 ≈ 6.0 GB,与事故 6.2 GB 峰值吻合)。单次整读成本 467 ms / +501.6 MB。方法与边界见[记录](docs/plans/2026-10-27-workspace-cwd-over-cold-reads.md) §5.2。 - 🧪 测试:`tests/smoke.spec.ts` 重写该组 8 例(header 优先于陈旧提示、header 只读一次、12 并发共享一次 header 读、无 `stat`/`stat` 失败回落客户端提示、live committed 优先、相对 cwd 拒绝为 `bad-request`、`defaultDirectory` 与进程 cwd 兜底)。机制与取舍见 [记录](docs/plans/2026-10-27-workspace-cwd-over-cold-reads.md)。 + ### v0.28.1 - 🛡 **并发同键冷读合并(OOM 修复)**:全量重启后会话全部转为 detached,12 条 `/sidebar/*` 路由共享的 cwd 解析会对同一会话各做一次宿主冷观察(整份日志读 + 解码;39MB 级会话 × 44 个并发请求 ≈ 1.7GB → OOM)。现在 `cwdOf()` 把**同一会话 + 同一客户端 cwd 提示**的并发请求合并为一次真实读,其余 await 同一结果;不引入 TTL(宿主本身按持久化 revision 缓存已完成冷读),客户端提示参与 key 以免跨提示串味。`tests/smoke.spec.ts` 新增「12 并发 → 1 次冷读」与「不同提示不合并」两例。 diff --git a/CHANGELOG_EN.md b/CHANGELOG_EN.md index 094f26ee..55a541d0 100644 --- a/CHANGELOG_EN.md +++ b/CHANGELOG_EN.md @@ -4,6 +4,12 @@ > > 📝 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). +- ⚡ **Smooth scrolling for large documents**: the render queue pauses while the reader scrolls (resuming 350 ms after the last scroll event) and only serves the preview that is actually on screen — hidden tabs keep placeholders and warm their diagrams when shown again. The two mutation-driven full-document scans (inline HTML pass, heading-anchor pass) coalesce bursts into one pass every 80 ms (previously a scan per mutation, measured at 8–15 ms each); initial near-viewport detection reads every rect in one batch before the swap writes, removing one forced layout per diagram; `.mermaidWrap` gains `content-visibility: auto` + `contain-intrinsic-size` + `contain: layout paint style`, so off-screen diagrams leave layout and paint entirely. Scrolling no longer competes with background renders, document-wide scans or off-screen SVG repaint; diagrams still fill in when the reader stops or scrolls them into view — never as code blocks. +- 🐞 **A failed diagram shows the mermaid parse error inline**: instead of only a generic "Mermaid render failed" label plus the source block (the full error was hidden in the hover title), the error strip now prints the first two lines of mermaid's message (e.g. `Parse error on line 10 ... Expecting 'SEMI', ...`), so a broken fence is found without hunting; the full text stays on the title. + ### 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..d3c6923d --- /dev/null +++ b/docs/plans/2026-10-23-mermaid-iframe-isolation.md @@ -0,0 +1,192 @@ +# 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/MarkdownHtml.tsx b/src/client/MarkdownHtml.tsx index b9914b01..f6fd2753 100644 --- a/src/client/MarkdownHtml.tsx +++ b/src/client/MarkdownHtml.tsx @@ -236,17 +236,45 @@ function MarkdownSegment({ text, hasMermaid, media, codeLabels }: MarkdownSegmen const container = containerRef.current if (container === null) return runInlineHtmlPass(container, media) - let scheduled = false + let timer: number | undefined + /** A pass was skipped because the page was hidden; flush it on return. */ + let dirty = false + const runPass = (): void => { + // Only `hidden` pauses the pass; jsdom reports a non-visible state too, + // and the initial pass already ran there. + if (document.visibilityState === 'hidden') { + dirty = true + return + } + dirty = false + runInlineHtmlPass(container, media) + } const observer = new MutationObserver(() => { - if (scheduled) return - scheduled = true - queueMicrotask(() => { - scheduled = false - runInlineHtmlPass(container, media) - }) + if (timer !== undefined) return + // Coalesce a burst of mutations (shiki settling, diagram swaps, inline + // HTML injection) into one pass: the scan walks every text node in the + // document, so a pass per mutation turns a diagram-heavy render into a + // stream of full-document scans. + timer = window.setTimeout(() => { + timer = undefined + runPass() + }, 80) }) + const onVisibilityChange = (): void => { + if (document.visibilityState === 'hidden' || !dirty) return + if (timer !== undefined) { + window.clearTimeout(timer) + timer = undefined + } + runPass() + } + document.addEventListener('visibilitychange', onVisibilityChange) observer.observe(container, { childList: true, subtree: true }) - return () => { observer.disconnect() } + return () => { + observer.disconnect() + document.removeEventListener('visibilitychange', onVisibilityChange) + if (timer !== undefined) window.clearTimeout(timer) + } }, [text, media]) return (
diff --git a/src/client/mermaid-frame.ts b/src/client/mermaid-frame.ts new file mode 100644 index 00000000..de76f0e8 --- /dev/null +++ b/src/client/mermaid-frame.ts @@ -0,0 +1,271 @@ +/** + * 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. + * + * Two failure classes stay separate on purpose: a diagram that mermaid itself + * rejects is a per-diagram error (source + message on that block only), while a + * frame that never loads, times out or answers with garbage is a transport + * error (one retry, then a fast-fail breaker for the rest of the page). A bad + * fence must never poison the diagrams after it. + */ +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 +/** Guard against a hostile/broken payload being posted to the frame. */ +const MAX_DIAGRAM_SOURCE_LENGTH = 500_000 + +/** mermaid rejected this diagram (syntax/unsupported feature). Only this + * diagram falls back to its source; the frame stays healthy. */ +export class MermaidDiagramError extends Error { + constructor(message: string) { + super(message) + this.name = 'MermaidDiagramError' + } +} + +/** The frame itself failed (load/handshake/timeout/protocol). Retry once, then + * fail fast for the remaining diagrams on the page. */ +export class MermaidFrameError extends Error { + constructor(message: string, options?: { cause?: unknown }) { + super(message, options) + this.name = 'MermaidFrameError' + } +} + +/** One pending render waiting on the frame's postMessage answer. */ +interface PendingRender { + resolve: (svg: string) => void + reject: (error: Error) => void + timer: number +} + +/** A validated answer from the frame. */ +export type FrameMessage = + | { kind: 'result'; id: number; svg: string } + | { kind: 'error'; id: number; message: string } + +/** The subset of MessageEvent the protocol needs (easy to unit-test). */ +export interface MessageEventLike { + source: unknown + origin: string + data: unknown +} + +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 +} + +/** Test seam for the frame layer itself: replaces the postMessage transport + * while keeping `renderMermaidDiagram`'s error classification/retry/breaker. */ +let testTransport: ((code: string, theme: MermaidTheme) => Promise) | null = null +export function setMermaidFrameTransportForTests( + transport: ((code: string, theme: MermaidTheme) => Promise) | null, +): void { + testTransport = transport + frameUnavailable = false +} + +/** Restore the real frame and clear the breaker (module state persists across + * specs in one vitest file). */ +export function resetMermaidFrameForTests(): void { + testRenderer = null + testTransport = null + frameUnavailable = false +} + +/** + * Validate one message against the frame protocol. + * + * The sandboxed frame has an opaque origin (`'null'`), so the source window is + * the primary identity check; the origin allowlist keeps a same-origin page + * that happens to reuse the message shape from being accepted. + * @param event - the incoming message event (or a test double of it). + * @param expectedWindow - the frame's `contentWindow`; `null` rejects all. + * @returns the validated message, or `null` when it must be ignored. + */ +export function acceptFrameMessage(event: MessageEventLike, expectedWindow: Window | null): FrameMessage | null { + if (expectedWindow === null || event.source !== expectedWindow) return null + if (event.origin !== 'null' && event.origin !== '') return null + const data = event.data as { type?: unknown; id?: unknown; svg?: unknown; message?: unknown } | null + if (data === null || typeof data !== 'object') return null + if (data.type !== 'mermaid-result' && data.type !== 'mermaid-error') return null + if (typeof data.id !== 'number' || !Number.isInteger(data.id) || data.id <= 0) return null + if (data.type === 'mermaid-result') { + return typeof data.svg === 'string' ? { kind: 'result', id: data.id, svg: data.svg } : null + } + return typeof data.message === 'string' + ? { kind: 'error', id: data.id, message: data.message } + : null +} + +/** 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 message = acceptFrameMessage(event, frame?.contentWindow ?? null) + if (message === null) return + const entry = pending.get(message.id) + if (entry === undefined) return + pending.delete(message.id) + window.clearTimeout(entry.timer) + if (message.kind === 'result') entry.resolve(message.svg) + else entry.reject(new MermaidDiagramError(message.message)) + }) +} + +/** Reject every in-flight render (frame replaced/disposed) instead of leaving + * them to their timeouts. */ +function failPending(error: Error): void { + for (const [id, entry] of pending) { + pending.delete(id) + window.clearTimeout(entry.timer) + entry.reject(error) + } +} + +/** Drop the current frame (failed load, page teardown) and its blob URL. */ +function disposeFrame(): void { + failPending(new MermaidFrameError('mermaid frame was reset')) + 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 + if (event.origin !== 'null' && event.origin !== '') 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 MermaidFrameError('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 MermaidFrameError('mermaid frame disappeared') + const id = ++requestSeq + return new Promise((resolve, reject) => { + const timer = window.setTimeout(() => { + pending.delete(id) + reject(new MermaidFrameError('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. + * + * A `MermaidDiagramError` is final for that one diagram (no retry, no breaker); + * a transport failure gets one retry with a fresh frame, then flips the + * page-level breaker so later diagrams fail fast instead of paying a timeout + * each. + * @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 (code.length > MAX_DIAGRAM_SOURCE_LENGTH) { + throw new MermaidDiagramError(`diagram source is too large (${code.length} chars)`) + } + if (frameUnavailable) throw new MermaidFrameError('mermaid rendering frame is unavailable') + const renderOnce = async (): Promise => ( + testTransport !== null ? testTransport(code, theme) : renderInFrame(code, theme) + ) + try { + return await renderOnce() + } catch (firstError) { + // A bad diagram is not a broken frame: report it and leave the frame alone. + if (firstError instanceof MermaidDiagramError) throw firstError + disposeFrame() + try { + return await renderOnce() + } catch (secondError) { + if (secondError instanceof MermaidDiagramError) throw secondError + frameUnavailable = true + throw new MermaidFrameError( + `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..16658246 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,149 @@ 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', - }) +/** One mounted preview's visibility. Background diagrams of a hidden preview + * (parked tab, collapsed dock) must not warm-render: they would spend CPU on + * content nobody can see and make the visible document's scrolling compete + * with diagrams from other tabs. */ +interface MermaidPreviewHandle { + visible: boolean + wake: () => void +} + +interface MermaidTask { + priority: MermaidPriority + run: () => Promise + /** The preview this render belongs to. */ + owner: MermaidPreviewHandle +} + +/** 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 + +/** How long after the last scroll event background rendering stays paused. + * Scrolling must not compete with diagram layout for the main thread. */ +const SCROLL_QUIET_MS = 350 +/** Timestamp of the most recent captured scroll event on the page. */ +let lastScrollAt = 0 +if (typeof window !== 'undefined') { + window.addEventListener('scroll', () => { lastScrollAt = performance.now() }, { capture: true, passive: true }) +} + +/** Resolve once the page has stopped scrolling for {@link SCROLL_QUIET_MS}. */ +async function waitForScrollQuiet(): Promise { + while (performance.now() - lastScrollAt < SCROLL_QUIET_MS) { + await new Promise((resolve) => { setTimeout(resolve, 120) }) + } +} + +/** Register one preview's visibility gate (see {@link MermaidPreviewHandle}). */ +function createPreviewHandle(): MermaidPreviewHandle { + return { + visible: true, + wake: () => { void drainMermaidQueue() }, + } +} + +/** Drop queued renders that belong to a preview that is going away. */ +function dropPreviewTasks(handle: MermaidPreviewHandle): void { + for (let index = mermaidQueue.length - 1; index >= 0; index -= 1) { + const task = mermaidQueue[index] + if (task !== undefined && task.owner === handle) mermaidQueue.splice(index, 1) + } +} + +/** 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 + lastScrollAt = 0 +} + +/** 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, gives the browser (input, layout, the watchdog's probe) + * a turn between two renders, and yields entirely while the reader is + * scrolling or while a preview is off screen — so a document with dozens of + * diagrams stays scrollable and every diagram still ends up rendered. + */ +async function drainMermaidQueue(): Promise { + if (mermaidPumping) return + mermaidPumping = true + const epoch = mermaidQueueEpoch + try { + while (epoch === mermaidQueueEpoch) { + mermaidQueue.sort((a, b) => a.priority - b.priority) + // Hidden previews keep their diagrams queued, not rendered: the visible + // document owns the main thread until its own diagrams are warm. + const runnable = mermaidQueue.findIndex((task) => task.owner.visible) + if (runnable === -1) break + const [task] = mermaidQueue.splice(runnable, 1) + if (task === undefined) break + if (task.priority > 0) await waitForScrollQuiet() + 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, owner: MermaidPreviewHandle): void { + mermaidQueue.push({ priority, run, owner }) + 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 isNearViewportRect(rect: DOMRect): boolean { + 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). */ @@ -218,8 +339,17 @@ function MermaidZoomModal({ svg, onClose }: { svg: SVGSVGElement; onClose: () => ) } +interface MermaidDiagramProps { + code: string + /** The preview this diagram belongs to (queue visibility owner). */ + owner: MermaidPreviewHandle + /** True when the fence was already near the viewport at mount; the whole + * document reads its rects in one batch (see MermaidMarkdown). */ + initiallyNearViewport: boolean +} + /** One rendered mermaid fence: header chrome + diagram (or error + source). */ -function MermaidDiagram({ code }: { code: string }): React.ReactNode { +function MermaidDiagram({ code, owner, initiallyNearViewport }: MermaidDiagramProps): React.ReactNode { const [svg, setSvg] = useState(null) const [error, setError] = useState(null) const [copied, setCopied] = useState(false) @@ -228,33 +358,73 @@ 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() + }, owner) + }, [renderNow, owner]) + + // 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 + scheduleRender(initiallyNearViewport ? 0 : 1) + }, [code, dark, initiallyNearViewport, 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 +449,7 @@ function MermaidDiagram({ code }: { code: string }): React.ReactNode { } return ( -
+
mermaid
- {error !== null &&
{t('mermaidError')}
} + {svg === null && error === null && ( +
+ + + +
+ )} + {error !== null && ( +
+ {t('mermaidError')} + {error.split('\n').slice(0, 2).join(' ').slice(0, 240)} +
+ )} {svg !== null && (
): boolea export function MermaidMarkdown({ text, codeLabels }: MermaidMarkdownProps): React.ReactNode { const containerRef = useRef(null) const mountsRef = useRef(new Map()) + /** Visibility gate shared by every diagram of this document. */ + const handleRef = useRef(null) + if (handleRef.current === null) handleRef.current = createPreviewHandle() + const handle = handleRef.current + + // Background renders wait while this preview is off screen (parked tab, + // collapsed dock, hidden page); showing it again wakes the shared queue. + // jsdom has neither layout nor IntersectionObserver, so specs keep the + // default (visible) gate with only the document-visibility guard. + useEffect(() => { + const container = containerRef.current + if (container === null) return () => { dropPreviewTasks(handle) } + const update = (visible: boolean): void => { + if (handle.visible === visible) return + handle.visible = visible + if (visible) handle.wake() + } + const present = (): boolean => + document.visibilityState !== 'hidden' && container.getClientRects().length > 0 + const onVisibilityChange = (): void => { + if (typeof IntersectionObserver === 'undefined') update(document.visibilityState !== 'hidden') + else update(present()) + } + document.addEventListener('visibilitychange', onVisibilityChange) + if (typeof IntersectionObserver === 'undefined') { + return () => { + document.removeEventListener('visibilitychange', onVisibilityChange) + dropPreviewTasks(handle) + } + } + update(present()) + const observer = new IntersectionObserver((entries) => { + for (const entry of entries) update(entry.isIntersecting && document.visibilityState !== 'hidden') + }) + observer.observe(container) + return () => { + observer.disconnect() + document.removeEventListener('visibilitychange', onVisibilityChange) + dropPreviewTasks(handle) + } + }, [handle]) useLayoutEffect(() => { const container = containerRef.current @@ -377,10 +605,20 @@ export function MermaidMarkdown({ text, codeLabels }: MermaidMarkdownProps): Rea const mounts = mountsRef.current const seen = new Set() const bodies = mermaidFenceBodies(text) + const blocks = [...container.querySelectorAll('.md-code-block')] - for (const block of container.querySelectorAll('.md-code-block')) { + // One read phase, then one write phase. Reading each diagram's rect inside + // the swap loop (between root renders) forces a full layout per diagram — + // dozens of forced reflows when a diagram-heavy document opens. + const near = new Map() + for (const block of blocks) { + if (!isMermaidBlock(block, bodies)) continue + near.set(block, isNearViewportRect(block.getBoundingClientRect())) + } + + for (const block of blocks) { const mount = mounts.get(block) - const isMermaid = isMermaidBlock(block, bodies) + const isMermaid = near.has(block) if (!isMermaid) { // A previously swapped block that is no longer a mermaid fence: // restore the CodeBlock children React still manages, so the plain @@ -404,10 +642,14 @@ export function MermaidMarkdown({ text, codeLabels }: MermaidMarkdownProps): Rea block.setAttribute('data-mermaid-processed', 'true') const root = createRoot(host) mounts.set(block, { root, source, removed }) - root.render() + root.render( + , + ) } else { mount.source = source - mount.root.render() + mount.root.render( + , + ) } } @@ -418,12 +660,13 @@ export function MermaidMarkdown({ text, codeLabels }: MermaidMarkdownProps): Rea mount.root.unmount() mounts.delete(block) } - }, [text]) + }, [text, handle]) useEffect(() => () => { for (const { root } of mountsRef.current.values()) root.unmount() mountsRef.current.clear() - }, []) + dropPreviewTasks(handle) + }, [handle]) return (
diff --git a/src/client/sidebar.module.css b/src/client/sidebar.module.css index b93ec2f7..e2b47fc0 100644 --- a/src/client/sidebar.module.css +++ b/src/client/sidebar.module.css @@ -1872,6 +1872,15 @@ body[data-dsh-sidebar-dragging] .bottomPanel { border-radius: 6px; background: var(--dsw-alias-bg-layer-1); overflow: hidden; + /* Scroll performance: a rendered diagram is a large SVG. Skip layout and + paint for the diagrams outside the viewport (a diagram-heavy article can + hold dozens) and remember the measured height once a block has been on + screen, so scrolling past already-rendered diagrams costs nothing. */ + content-visibility: auto; + contain-intrinsic-size: auto 240px; + /* Isolate the box: a diagram landing must not invalidate the layout or paint + of the surrounding article. */ + contain: layout paint style; } .mermaidHeader { @@ -1921,6 +1930,55 @@ body[data-dsh-sidebar-dragging] .bottomPanel { height: auto; } +/* Lazy render placeholder: the fence's diagram is queued and swaps in as soon + as the render queue reaches it (visible diagrams first, the rest while the + browser is idle). The min-height comes from the fence's line count so the + article does not jump under the reader's cursor when the diagram arrives. */ +.mermaidPending { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 10px; + padding: 18px 24px; +} + +.mermaidPendingBar { + display: block; + width: min(320px, 70%); + height: 10px; + border-radius: 5px; + background: var(--dsw-alias-bg-layer-2); + animation: mermaidPendingPulse 1.4s ease-in-out infinite; +} + +.mermaidPendingBar:nth-child(2) { + width: min(240px, 55%); + animation-delay: 0.15s; +} + +.mermaidPendingBar:nth-child(3) { + width: min(160px, 40%); + animation-delay: 0.3s; +} + +@keyframes mermaidPendingPulse { + 0%, + 100% { + opacity: 0.45; + } + + 50% { + opacity: 1; + } +} + +@media (prefers-reduced-motion: reduce) { + .mermaidPendingBar { + animation: none; + } +} + .mermaidError { padding: 6px 10px; border-bottom: 1px solid var(--dsw-alias-border-l1); @@ -1928,6 +1986,17 @@ body[data-dsh-sidebar-dragging] .bottomPanel { font: var(--dsw-font-xxxs-11); } +/* The mermaid parse/render message itself: the generic label alone makes a + broken fence hard to find, so the first lines follow it (mermaid's full + dump stays on the hover title). */ +.mermaidErrorDetail { + display: block; + margin-top: 2px; + color: var(--dsw-alias-label-tertiary); + white-space: pre-wrap; + word-break: break-word; +} + /* The diagram source shown under a render error (helps fixing the fence). */ .mermaidCode { margin: 0; diff --git a/src/client/use-markdown-surface.ts b/src/client/use-markdown-surface.ts index 12cdcb21..cd96bb67 100644 --- a/src/client/use-markdown-surface.ts +++ b/src/client/use-markdown-surface.ts @@ -160,20 +160,22 @@ function attachMarkdownSurface( // write to the scroller. if (pending !== null) queueMicrotask(applyPending) - let scheduled = false + let scheduled: number | undefined const observer = new MutationObserver(() => { - if (scheduled) return - scheduled = true - queueMicrotask(() => { - scheduled = false + if (scheduled !== undefined) return + // Coalesce a burst of mutations into one DOM pass: each pass walks the + // whole preview, and diagram swapping / shiki settling emit many mutations. + scheduled = window.setTimeout(() => { + scheduled = undefined prepareMarkdownAnchors(container) applyPending() - }) + }, 80) }) observer.observe(container, { childList: true, subtree: true }) return () => { observer.disconnect() + if (scheduled !== undefined) window.clearTimeout(scheduled) container.removeAttribute(MARKDOWN_SURFACE_ATTR) } } diff --git a/tests/mermaid-frame-asset.spec.ts b/tests/mermaid-frame-asset.spec.ts new file mode 100644 index 00000000..50c7025c --- /dev/null +++ b/tests/mermaid-frame-asset.spec.ts @@ -0,0 +1,39 @@ +/** + * The generated mermaid frame asset must stay a single self-contained HTML + * document: the preview loads it into an opaque-origin sandboxed iframe, which + * can fetch no subresources, and a raw ` { + 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') + }) + + it('validates the sender and the payload on the frame side', () => { + // The opaque-origin sandbox cannot compare origins, so the frame binds + // requests to its parent window and validates every field it consumes. + expect(MERMAID_FRAME_HTML).toContain('event.source !== window.parent') + expect(MERMAID_FRAME_HTML).toContain("typeof data.id !== 'number'") + expect(MERMAID_FRAME_HTML).toContain("typeof data.code !== 'string'") + expect(MERMAID_FRAME_HTML).toContain('data.code.length > MAX_SOURCE') + expect(MERMAID_FRAME_HTML).toContain("data.theme === 'dark' ? 'dark' : 'default'") + }) +}) diff --git a/tests/mermaid-frame.spec.ts b/tests/mermaid-frame.spec.ts new file mode 100644 index 00000000..7dac6a73 --- /dev/null +++ b/tests/mermaid-frame.spec.ts @@ -0,0 +1,106 @@ +/** + * The mermaid frame boundary: a diagram that mermaid itself rejects is a + * per-diagram error (only its block falls back to the source), while frame + * load/handshake/timeout failures retry once and then trip a page-level + * fast-fail breaker. The postMessage bridge is identity- and shape-validated on + * both sides. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + MermaidDiagramError, + MermaidFrameError, + acceptFrameMessage, + renderMermaidDiagram, + resetMermaidFrameForTests, + setMermaidFrameTransportForTests, +} from '../src/client/mermaid-frame.ts' + +const SVG = 'OK' + +beforeEach(() => { resetMermaidFrameForTests() }) +afterEach(() => { resetMermaidFrameForTests() }) + +describe('renderMermaidDiagram failure classes', () => { + it('keeps rendering the rest of the document after one diagram is rejected', async () => { + const transport = vi.fn() + .mockRejectedValueOnce(new MermaidDiagramError('Parse error on line 1')) + .mockResolvedValueOnce(SVG) + setMermaidFrameTransportForTests(transport) + + await expect(renderMermaidDiagram('bad', 'default')).rejects.toBeInstanceOf(MermaidDiagramError) + await expect(renderMermaidDiagram('good', 'default')).resolves.toBe(SVG) + // A diagram error is final for that diagram: no retry, no breaker. + expect(transport).toHaveBeenCalledTimes(2) + }) + + it('retries a transport failure once and recovers', async () => { + const transport = vi.fn() + .mockRejectedValueOnce(new MermaidFrameError('frame did not become ready')) + .mockResolvedValueOnce(SVG) + setMermaidFrameTransportForTests(transport) + + await expect(renderMermaidDiagram('graph TD', 'default')).resolves.toBe(SVG) + expect(transport).toHaveBeenCalledTimes(2) + }) + + it('breaks the page only after two transport failures, not after a diagram error', async () => { + const transport = vi.fn().mockRejectedValue(new MermaidFrameError('frame died')) + setMermaidFrameTransportForTests(transport) + + await expect(renderMermaidDiagram('graph TD', 'default')).rejects.toBeInstanceOf(MermaidFrameError) + expect(transport).toHaveBeenCalledTimes(2) + const callsAfterBreaker = transport.mock.calls.length + // Fast fail: later diagrams must not pay another timeout/retry. + await expect(renderMermaidDiagram('graph LR', 'default')).rejects.toBeInstanceOf(MermaidFrameError) + expect(transport.mock.calls.length).toBe(callsAfterBreaker) + }) +}) + +describe('acceptFrameMessage', () => { + const frameWindow = {} as Window + const event = (overrides: Record = {}): { + source: unknown + origin: string + data: unknown + } => ({ + source: frameWindow, + origin: 'null', + data: { type: 'mermaid-result', id: 1, svg: SVG }, + ...overrides, + }) + + it('accepts a well-formed result from the frame window', () => { + expect(acceptFrameMessage(event(), frameWindow)).toEqual({ kind: 'result', id: 1, svg: SVG }) + }) + + it('accepts a well-formed diagram error', () => { + expect( + acceptFrameMessage(event({ data: { type: 'mermaid-error', id: 2, message: 'Parse error' } }), frameWindow), + ).toEqual({ kind: 'error', id: 2, message: 'Parse error' }) + }) + + it('rejects a message from any window other than the frame', () => { + expect(acceptFrameMessage(event({ source: {} }), frameWindow)).toBeNull() + expect(acceptFrameMessage(event(), null)).toBeNull() + }) + + it('rejects a same-shape message from a different origin', () => { + expect(acceptFrameMessage(event({ origin: 'https://example.com' }), frameWindow)).toBeNull() + }) + + it('rejects malformed payloads', () => { + const bad = [ + null, + { type: 'mermaid-result', id: '1', svg: SVG }, + { type: 'mermaid-result', id: 0, svg: SVG }, + { type: 'mermaid-result', id: 1.5, svg: SVG }, + { type: 'mermaid-result', id: 1, svg: 42 }, + { type: 'mermaid-error', id: 1 }, + { type: 'mermaid-frame-ready' }, + { type: 'mermaid-render', id: 1, code: 'graph TD' }, + ] + for (const data of bad) { + expect(acceptFrameMessage(event({ data }), frameWindow)).toBeNull() + } + }) +}) diff --git a/tests/mermaid-markdown.spec.tsx b/tests/mermaid-markdown.spec.tsx index 68a1b6c7..b6f12353 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,99 @@ 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.textContent, 'the mermaid error itself is shown, not only a generic label').toContain('boom') + 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 +155,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) } }