From aa198d792195ed5fc0894946f4a8b151bd0b33d7 Mon Sep 17 00:00:00 2001 From: OCILY Date: Fri, 23 Oct 2026 17:57:12 +0800 Subject: [PATCH] perf(mermaid): keep scrolling and hidden tabs off the render queue Follow-up to the iframe isolation: after that fix a 31-diagram document still felt janky while scrolling. The remaining cost was work competing with the scroll gesture: - background diagram renders kept running during scroll (each one injects an SVG, runs DOM passes and lays out); - hidden native tabs kept warming diagrams (tab bodies are keepMounted); - the inline-HTML and heading-anchor MutationObservers ran a full-document scan per mutation (measured 8-15 ms per pass, dozens of passes when a document swaps its diagrams in); - initial near-viewport detection read one rect per diagram between DOM writes, forcing a layout per diagram; - off-screen rendered SVGs still participated in layout and paint. The queue now pauses background work for 350 ms after the last captured scroll event, and only schedules renders whose preview is visible (IntersectionObserver gate per preview; hidden tabs keep placeholders and wake the queue when shown again, and unmounting a preview drops its queued tasks). The two mutation passes coalesce bursts into one 80 ms pass. Initial priorities come from one batched rect read before the swap writes. .mermaidWrap gains content-visibility:auto + contain-intrinsic-size + contain:layout paint style, so off-screen diagrams leave layout and paint. Visible diagrams still render on demand, every diagram is still eventually rendered, and nothing falls back to a code block. --- CHANGELOG.md | 1 + CHANGELOG_EN.md | 1 + .../2026-10-23-mermaid-iframe-isolation.md | 44 +++++- src/client/MarkdownHtml.tsx | 21 ++- src/client/mermaid.tsx | 142 +++++++++++++++--- src/client/sidebar.module.css | 9 ++ src/client/use-markdown-surface.ts | 14 +- 7 files changed, 195 insertions(+), 37 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 17381e54..166666ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,6 +52,7 @@ - **已结束分支整体聚合**:只有整条分支全部结束才自动聚合;仍有运行后代、当前查看路径或未知子代理目录的分支保持可见,聚合计数覆盖隐藏的 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)。 +- ⚡ **大文档滚动流畅性:渲染让位于滚动、隐藏页签不空转、摘掉全量 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 重绘抢主线程;图表仍会在滚动停止后或进入视口时补齐,不退化为代码块。 ### v0.28.0 diff --git a/CHANGELOG_EN.md b/CHANGELOG_EN.md index fa1fc436..187e3c0d 100644 --- a/CHANGELOG_EN.md +++ b/CHANGELOG_EN.md @@ -7,6 +7,7 @@ ### 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. ### v0.29.0 diff --git a/docs/plans/2026-10-23-mermaid-iframe-isolation.md b/docs/plans/2026-10-23-mermaid-iframe-isolation.md index ffd37a8c..3ebe3ddb 100644 --- a/docs/plans/2026-10-23-mermaid-iframe-isolation.md +++ b/docs/plans/2026-10-23-mermaid-iframe-isolation.md @@ -96,6 +96,38 @@ tsdown 之前生成;git 源安装走 `prepare`,因此同样可用。 - 占位骨架 `.mermaidPending` / `.mermaidPendingBar`:按围栏行数预留高度,主题 token、 `prefers-reduced-motion` 下停止动画,图到达时文章不跳动。 +### 3.4 滚动与多页签开销:渲染让位于交互 + +第一版(3.1–3.3)解决了冻结与单图耗时,但真机反馈「加载后滚动仍不够流畅」。滚动路径上 +剩余的开销来自五处,均已处理: + +- **滚动期间后台渲染**:队列原先在滚动时仍按 `requestIdleCallback` 补齐剩余图,每次图 + 落地都要注入 SVG、跑 DOM pass、触发布局——滚动中每 100–300 ms 撞一次就会掉帧。现在 + 全局捕获 `scroll`(passive capture),队列对**后台优先级**任务等待「停止滚动 350 ms」 + 后再继续;滚动时进入视口的图仍按需即时渲染。 +- **隐藏页签空转**:原生 tab `keepMounted`,隐藏预览若继续补渲染,会与可见文档抢主线程。 + 每个预览注册可见性 handle(`IntersectionObserver`,初始按容器盒判断),队列只调度 + `owner.visible` 的任务;隐藏页签的图保持占位,切回时 `wake()` 继续。预览卸载时 + `dropPreviewTasks()` 清掉它的待渲染任务。 +- **mutation 全量扫描**:`runInlineHtmlPass` 与 `prepareMarkdownAnchors` 原先每次 DOM + mutation 后跑一遍全文扫描(真机实测 8–15 ms/次;31 张图落地 = 几十次扫描)。现在 + 80 ms 合并一次(`setTimeout` coalesce,卸载时清理计时器),并在页面隐藏时跳过扫描。 +- **打开瞬间的强制布局**:原实现每张图在 effect 里各自 `getBoundingClientRect()`,且与 + 其它图的 DOM 写入交错 → 每张图一次强制布局。现在 `MermaidMarkdown` 的 layout effect + 先批量读所有 mermaid 块的 rect(一次读相位),再统一做替换/挂载(一次写相位),优先级 + 通过 `initiallyNearViewport` prop 传给图组件。 +- **视口外 SVG 的布局/绘制**:`.mermaidWrap` 加 `content-visibility: auto` + + `contain-intrinsic-size: auto 240px` + `contain: layout paint style`;已渲染的图滚出 + 视口后不再参与布局与绘制(`auto` 会记住实测高度;首次进入前的估算只影响滚动条的初始 + 长度)。 + +### 3.5 加载策略(打开速度) + +- 懒 chunk 只在文档含 mermaid fence 时加载;iframe 在首次渲染时才创建,之后复用。 +- 首屏同步渲染 Markdown(真机 commit ≈ 45 ms),图表先出占位骨架(按围栏行数预留高度), + 视口内/近视口的图优先渲染(初始优先级来自 3.4 的批量 rect 读取)。 +- 其余图不阻塞阅读:滚动时暂停,停止滚动后按空闲槽补齐;隐藏页签不参与。 + ## 4. 实测结果(同机、同文档、31 图) | 指标 | 修复前 | 修复后 | @@ -119,11 +151,15 @@ tsdown 之前生成;git 源安装走 `prepare`,因此同样可用。 - **可进一步压缩**:把 UMD 换成本项目 rolldown 构建的 minify chunk 可去重依赖 (当前内联 3.4 MB minified UMD,已比原 7.04 MB 非压缩 chunk 小);但需新增 chunk 名与 5 处镜像,超出本修复范围。 -- **仍受主线程调度影响**:图多时后台渲染会占用若干秒 CPU,但每次让出主线程,不触发 - 看门狗;滚动时新进入视口的图会插队。 +- **仍受主线程调度影响**:图多时后台渲染会占用若干秒 CPU,但每次让出主线程、滚动手势 + 优先(见 3.4),不触发看门狗;滚动停止后或图进入视口时才补齐。 - **测试限制**:jsdom 无法跑真实 iframe/blob,spec 通过 `setMermaidFrameRendererForTests()` 注入 stub;iframe 行为由真实挂载 lane (`diagram.md` 冒烟)覆盖。 +- **隐藏页签仍保留整份预览 DOM**:宿主原生 tab 的 `keepMounted` 约定下,隐藏的 + Markdown 预览 DOM 不会释放(本修复让它们不再渲染图表、不再参与滚动,内存仍在)。 + 要再降内存需要在可见性变化时卸载/重建正文,这会牵涉滚动位置、编辑态与宿主 tab + 契约,留作后续(见 AGENTS 稳态开销约定)。 ## 6. 验证清单 @@ -131,4 +167,6 @@ tsdown 之前生成;git 源安装走 `prepare`,因此同样可用。 - [x] 单图/总耗时测量(30–104 ms / ~5 s) - [x] 占位 → 图替换、失败 → 源码兜底、多围栏全量渲染、跨围栏引用语义 - [x] 生成资产结构(两段内联脚本、严格 safe 转义、strict 配置) -- [x] `pnpm typecheck` / `pnpm lint` / `pnpm build` / `pnpm test` / `check:consumer-types` +- [x] 滚动手势优先:滚动期间暂停后台渲染、隐藏页签不调度、mutation pass 合并、 + 批量 rect 读取、视口外图表 content-visibility +- [x] `pnpm typecheck` / `pnpm lint` / `pnpm build` / 相关 spec 全绿 diff --git a/src/client/MarkdownHtml.tsx b/src/client/MarkdownHtml.tsx index b9914b01..8a8c849d 100644 --- a/src/client/MarkdownHtml.tsx +++ b/src/client/MarkdownHtml.tsx @@ -236,17 +236,24 @@ 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 const observer = new MutationObserver(() => { - if (scheduled) return - scheduled = true - queueMicrotask(() => { - scheduled = false + 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 + if (document.visibilityState !== 'visible') return runInlineHtmlPass(container, media) - }) + }, 80) }) observer.observe(container, { childList: true, subtree: true }) - return () => { observer.disconnect() } + return () => { + observer.disconnect() + if (timer !== undefined) window.clearTimeout(timer) + } }, [text, media]) return (
diff --git a/src/client/mermaid.tsx b/src/client/mermaid.tsx index 5b00ad34..29acd2f3 100644 --- a/src/client/mermaid.tsx +++ b/src/client/mermaid.tsx @@ -41,9 +41,20 @@ import css from './sidebar.module.css' * render while the browser is idle. */ type MermaidPriority = 0 | 1 +/** 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. */ @@ -53,12 +64,45 @@ let mermaidPumping = false * 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 @@ -78,19 +122,25 @@ function whenIdle(callback: () => void): void { * 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. + * 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.length > 0) { + while (epoch === mermaidQueueEpoch) { mermaidQueue.sort((a, b) => a.priority - b.priority) - const task = mermaidQueue.shift() + // 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 { @@ -107,16 +157,15 @@ async function drainMermaidQueue(): Promise { } /** Queue one diagram render; {@link drainMermaidQueue} runs it. */ -function pushMermaidTask(priority: MermaidPriority, run: () => Promise): void { - mermaidQueue.push({ priority, run }) +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 isNearViewport(node: HTMLElement): boolean { - const rect = node.getBoundingClientRect() +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 @@ -290,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) @@ -339,8 +397,8 @@ function MermaidDiagram({ code }: { code: string }): React.ReactNode { pushMermaidTask(priority, async () => { if (generation !== generationRef.current) return await renderNow() - }) - }, [renderNow]) + }, owner) + }, [renderNow, owner]) // A new source or theme invalidates what is on screen and schedules a render. useEffect(() => { @@ -349,9 +407,8 @@ function MermaidDiagram({ code }: { code: string }): React.ReactNode { setSvg(null) setError(null) if (code.trim() === '') return - const node = wrapRef.current - scheduleRender(node !== null && isNearViewport(node) ? 0 : 1) - }, [code, dark, scheduleRender]) + scheduleRender(initiallyNearViewport ? 0 : 1) + }, [code, dark, initiallyNearViewport, scheduleRender]) // A placeholder that scrolls into view jumps ahead of the background queue. useEffect(() => { @@ -495,6 +552,34 @@ function isMermaidBlock(block: HTMLElement, bodies: ReadonlySet): 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); showing it again wakes the shared queue. jsdom has no + // IntersectionObserver, so specs keep the default (visible) gate. + useEffect(() => { + const container = containerRef.current + if (container === null || typeof IntersectionObserver === 'undefined') { + return () => { dropPreviewTasks(handle) } + } + const update = (visible: boolean): void => { + if (handle.visible === visible) return + handle.visible = visible + if (visible) handle.wake() + } + update(container.getClientRects().length > 0) + const observer = new IntersectionObserver((entries) => { + for (const entry of entries) update(entry.isIntersecting) + }) + observer.observe(container) + return () => { + observer.disconnect() + dropPreviewTasks(handle) + } + }, [handle]) useLayoutEffect(() => { const container = containerRef.current @@ -502,10 +587,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 @@ -529,10 +624,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( + , + ) } } @@ -543,12 +642,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 39dc8a6e..a84bb2b8 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 { 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) } }