From fc4e4fa39a6c38f0779282f4386202145eed075c Mon Sep 17 00:00:00 2001 From: faysou Date: Tue, 24 Nov 2026 18:17:02 +0000 Subject: [PATCH] fix(markdown): keep large previews responsive when scrolling and switching tabs (#5249) Fast scrolling could leave either pane of a Markdown split blank, and large previews were rebuilt on every tab switch. - The source draws newly visible lines before painting a large scroll jump; the preview follows wrapped lines and table rows, handles trackpad gestures from their first wheel event, and updates its position while the scrollbar thumb is dragged (the Git log's scrollbar, resized as content grows). - Recent Markdown tabs stay mounted while hidden (text editor wrappers can now opt into keepAlive); the hidden source view is detached as before and the preview is moved off screen on its own layer. - Edits reuse unchanged equation and Mermaid SVGs, including diagrams with math labels; changing a TeX macro refreshes the equations that use it. - Long embedded image payloads are folded in the source, and the Markdown parser skips the payload bytes of standalone images. On a 5.85 MB document in WebKit, first open went from 22.9 s to 3.25 s and returning to the tab from 14.4 s to 0.24 s. Co-authored-by: faysou <893862+faysou@users.noreply.github.com> --- e2e/editor.spec.ts | 74 +++++ src/editor/core/cm/folding.test.ts | 22 ++ src/editor/core/cm/folding.ts | 22 ++ src/editor/core/model/slot.ts | 7 +- src/editor/core/view/EditorArea.module.css | 22 ++ src/editor/core/view/EditorArea.tsx | 89 +++-- .../core/view/editorLayoutActions.test.tsx | 3 +- src/editor/lsp/markdownMath.ts | 27 +- src/features/viewers/index.ts | 1 + .../viewers/markdown/Markdown.module.css | 8 + .../viewers/markdown/MarkdownEditor.tsx | 305 +++++++++++++----- src/features/viewers/markdown/live.test.ts | 116 +++++++ src/features/viewers/markdown/live.ts | 149 +++++++-- src/features/viewers/markdown/mathSvg.test.ts | 9 +- src/features/viewers/markdown/mathSvg.ts | 17 +- src/features/viewers/markdown/mermaid.test.ts | 10 + src/features/viewers/markdown/mermaid.ts | 22 +- .../viewers/markdown/previewScroll.test.tsx | 89 ++++- src/features/viewers/markdown/render.test.ts | 35 ++ src/features/viewers/markdown/render.ts | 96 ++++-- .../viewers/markdown/splitScroll.test.ts | 58 ++++ src/features/viewers/markdown/splitScroll.ts | 59 ++++ src/features/viewers/markdown/zoom.test.tsx | 3 +- src/ui/selectableSurfaces.test.tsx | 4 +- src/workbench/contributions.ts | 1 + 25 files changed, 1061 insertions(+), 187 deletions(-) create mode 100644 src/features/viewers/markdown/live.test.ts create mode 100644 src/features/viewers/markdown/splitScroll.test.ts create mode 100644 src/features/viewers/markdown/splitScroll.ts diff --git a/e2e/editor.spec.ts b/e2e/editor.spec.ts index 84ee08e0b..e1999f06a 100644 --- a/e2e/editor.spec.ts +++ b/e2e/editor.spec.ts @@ -568,6 +568,80 @@ test("Markdown preview keeps following find and edits after scrolling the source await expect(preview.locator("strong [data-math-svg] > svg")).toHaveAttribute("aria-label", "v_0"); }); +test("drags the Markdown preview scrollbar through a document after it grows", async ({ workbench: page }) => { + const editor = await openFromTree(page, "README.md"); + const content = editor.locator(".cm-content"); + await content.click(); + await page.keyboard.press("Meta+a"); + await page.keyboard.insertText("Short"); + const preview = page.getByRole("document", { name: "Markdown preview" }); + await expect(preview).toHaveText("Short"); + await content.press("Meta+a"); + await page.keyboard.insertText(Array.from({ length: 180 }, (_, i) => `Paragraph ${i}`).join("\n\n")); + await expect(preview).toContainText("Paragraph 179"); + const thumb = preview.locator("..").locator(":scope > [aria-hidden=true] > div"); + await expect(thumb).toBeVisible(); + const thumbBox = (await thumb.boundingBox())!; + const box = (await preview.boundingBox())!; + const x = thumbBox.x + thumbBox.width / 2; + await page.mouse.move(x, thumbBox.y + thumbBox.height / 2); + await page.mouse.down(); + try { + for (const end of [true, false, true]) { + await page.mouse.move(x, box.y + (end ? box.height - 1 : 0), { steps: 3 }); + expect(await preview.evaluate((el) => Math.round(el.scrollTop))).toBe( + end ? await preview.evaluate((el) => el.scrollHeight - el.clientHeight) : 0, + ); + } + } finally { + await page.mouse.up(); + } +}); + +test("keeps diagrams and their math labels when editing or switching Markdown tabs", async ({ workbench: page }) => { + const editor = await openFromTree(page, "README.md"); + const content = editor.locator(".cm-content"); + await content.click(); + await page.keyboard.press("Meta+a"); + const source = [ + "An equation $x^2$ and [a link](#title).", + '```mermaid\nflowchart LR\n A["$$x^2$$"] --> B\n```', + "Text to edit", + ].join("\n\n"); + await page.keyboard.insertText(source); + const preview = page.getByRole("document", { name: "Markdown preview" }); + const diagram = preview.locator(".mermaid-output .pan-zoom-content > svg"); + await expect(diagram.locator("foreignObject math")).toHaveCount(1); + const original = await diagram.elementHandle(); + const formula = preview.locator("[data-math-svg] > svg").first(); + const equation = await formula.elementHandle(); + await content.press("Control+End"); + await page.keyboard.insertText(" here"); + await expect(preview).toContainText("Text to edit here"); + expect(await diagram.evaluate((svg, old) => svg === old, original)).toBe(true); + expect(await formula.evaluate((svg, old) => svg === old, equation)).toBe(true); + + await content.press("Meta+a"); + await page.keyboard.insertText(source.replace("$$x^2$$", () => "$$z^3$$")); + await expect(diagram.locator("foreignObject math mi")).toHaveText("z"); + const edited = await diagram.elementHandle(); + expect(await diagram.evaluate((svg, old) => svg === old, original)).toBe(false); + expect(await formula.evaluate((svg, old) => svg === old, equation)).toBe(true); + + const other = await openFromTree(page, "settings.gradle.kts"); + await expect(other.locator(".cm-content")).toBeVisible(); + await expect(preview).toHaveCount(0); + expect(await edited!.evaluate((svg) => svg.isConnected)).toBe(true); + const hiddenLink = page.locator('a[href="#title"]'); + await expect(hiddenLink).toBeHidden(); + await hiddenLink.evaluate((el) => el.focus()); + await expect(hiddenLink).not.toBeFocused(); + await page.getByRole("tab", { name: /README/ }).click(); + await expect(preview).toBeVisible(); + expect(await diagram.evaluate((svg, old) => svg === old, edited)).toBe(true); + await expect(diagram.locator("foreignObject math")).toHaveCount(1); +}); + test("Markdown preview aligns Mermaid diagrams to their container align attribute", async ({ workbench: page }) => { const editor = await openFromTree(page, "README.md"); const content = editor.locator(".cm-content"); diff --git a/src/editor/core/cm/folding.test.ts b/src/editor/core/cm/folding.test.ts index e91f660e4..c88d7f194 100644 --- a/src/editor/core/cm/folding.test.ts +++ b/src/editor/core/cm/folding.test.ts @@ -11,6 +11,7 @@ import { foldChipWidth, foldSelectionEffects, foldsFromRanges, + markdownImageFolds, foldingExtension, foldToExpand, setBackendFolds, @@ -459,3 +460,24 @@ describe("foldChipWidth", () => { view.destroy(); }); }); + +it("folds long embedded image payloads without changing the Markdown source", () => { + const data = "abcd".repeat(100); + const url = "data:image/png;base64," + data; + const first = `![a](<${url}>)`; + const second = `b`; + const source = [first, second, "```md", first, "```", "![small](data:image/png;base64,YQ==)"].join("\n"); + const state = EditorState.create({ doc: source, extensions: codeFolding() }); + const folded = state.update({ effects: markdownImageFolds(state) }).state; + const ranges: number[][] = []; + foldedRanges(folded).between(0, source.length, (from, to) => { + ranges.push([from, to]); + }); + const a = first.indexOf(data), + b = first.length + 1 + second.indexOf(data); + expect(ranges).toEqual([ + [a, a + data.length], + [b, b + data.length], + ]); + expect(folded.doc.toString()).toBe(source); +}); diff --git a/src/editor/core/cm/folding.ts b/src/editor/core/cm/folding.ts index b7e058267..bc9f9db83 100644 --- a/src/editor/core/cm/folding.ts +++ b/src/editor/core/cm/folding.ts @@ -481,6 +481,28 @@ export function foldChipWidth(el: HTMLElement): number { return Math.round(chip.getBoundingClientRect().width); } +// Long image payloads would occupy thousands of soft-wrapped rows before the first editor measure. +export function markdownImageFolds(state: EditorState) { + const effects = []; + const destination = + /(?:\]\(\s*]*?\ssrc\s*=\s*["'])data:image\/[\w.+-]+;base64,([A-Za-z0-9+/]{256,}={0,2})(?=[>\s)"'])/gi; + let offset = 0; + let fence = ""; + for (const line of state.doc.iterLines()) { + const marker = /^ {0,3}(`{3,}|~{3,})/.exec(line)?.[1]; + if (marker && !fence) fence = marker; + else if (marker && marker.startsWith(fence) && !line.trim().slice(marker.length).trim()) fence = ""; + else if (!fence && line.length >= 256) { + for (const match of line.matchAll(destination)) { + const to = offset + match.index + match[0].length; + effects.push(foldEffect.of({ from: to - match[1]!.length, to })); + } + } + offset += line.length + 1; + } + return effects; +} + export function foldingExtension(showOutline = true, visibility: FoldingOutlineVisibility = "hover"): Extension { return [ // The chevron column sits right of contributed icon gutters (IDEA new UI). diff --git a/src/editor/core/model/slot.ts b/src/editor/core/model/slot.ts index 145901acb..6da35c3ab 100644 --- a/src/editor/core/model/slot.ts +++ b/src/editor/core/model/slot.ts @@ -33,6 +33,7 @@ import { } from "@/editor/api"; import { showContextMenu } from "@/ui"; import { baseExtensions, compartments, contributionExtensions } from "../cm/setup"; +import { markdownImageFolds } from "../cm/folding"; import { gutterMenuItems, inGutterMenuArea } from "../gutterMenu"; import { offerMakeWritable } from "../fileAttributes"; import type { DocModel } from "./document"; @@ -142,6 +143,10 @@ export class EditorSlot { }), ], }); + if (model.ctx().language === "markdown") { + const effects = markdownImageFolds(this.stored); + if (effects.length) this.stored = this.stored.update({ effects }).state; + } this.contributionsVersion = model.manager.contributionsVersion; if (source?.view) this.scroll = source.view.scrollSnapshot(); else if (source) this.scroll = source.scroll; @@ -155,7 +160,7 @@ export class EditorSlot { } /** The visible or kept view: the one holding the tab's state. */ - private get live(): EditorView | null { + get live(): EditorView | null { return this.view ?? this.kept; } diff --git a/src/editor/core/view/EditorArea.module.css b/src/editor/core/view/EditorArea.module.css index 3fa48d6e9..32ae1e6ae 100644 --- a/src/editor/core/view/EditorArea.module.css +++ b/src/editor/core/view/EditorArea.module.css @@ -69,6 +69,28 @@ content-visibility: visible; opacity: 0; } +/* Keep the typeset page on its own layer. Hiding every glyph invalidates WebKit's text layout. */ +.keptText { + will-change: transform; + transform: translateZ(0); +} +.keptText.keptHidden { + content-visibility: visible; + transform: translate3d(-100vw, 0, 0); +} +.keptText.keptHidden + :is( + :any-link, + :enabled, + summary, + iframe, + audio[controls], + video[controls], + [tabindex]:not([tabindex="-1"]), + [contenteditable]:not([contenteditable="false"]) + ) { + visibility: hidden; +} .host { flex: 1; min-height: 0; diff --git a/src/editor/core/view/EditorArea.tsx b/src/editor/core/view/EditorArea.tsx index 3c46ca12e..38c8e0b0b 100644 --- a/src/editor/core/view/EditorArea.tsx +++ b/src/editor/core/view/EditorArea.tsx @@ -40,6 +40,7 @@ import { useTextEditorWrappers, type EditorInput, type EditorKindContribution, + useEditorShown, type TextEditorWrapperContribution, } from "@/workbench/contributions"; import { useDistractionFree } from "@/workbench/distractionFree"; @@ -186,6 +187,7 @@ function PaneView({ paneId }: { paneId: string }) { const isActivePane = useTabs((s) => s.activePane === paneId); const multiPane = useTabs((s) => s.layout.kind === "split"); const kinds = useContributions((s) => s.editorKinds); + const wrappers = useTextEditorWrappers((s) => s.wrappers); const titleRevision = useEditorTabTitles((s) => s.revision); const tabs = useMemo(() => pane?.tabs ?? [], [pane]); const paths = tabs.map((t) => t.input.path ?? ""); @@ -344,7 +346,7 @@ function PaneView({ paneId }: { paneId: string }) { if (!pane) return null; const active = pane.tabs.find((t) => t.id === pane.active) ?? null; - const kept = keptTabs(pane.tabs, pane.mru, kinds); + const kept = keptTabs(pane.tabs, pane.mru, kinds, wrappers); const onFocus = () => { setContext("editorFocus", true); @@ -431,7 +433,13 @@ function PaneView({ paneId }: { paneId: string }) { ref={contentRef} > {kept.map((tab) => ( - + + {isTextInput(tab.input) ? ( + + ) : ( + + )} + ))} {!active ? ( @@ -492,20 +500,22 @@ function PaneBreadcrumbs({ } function PaneContent({ paneId, tab, tabsVisible }: { paneId: string; tab: Tab; tabsVisible: boolean }) { - const crumbs = !useDistractionFree((s) => s.active); + const shown = useEditorShown(); + const crumbs = !useDistractionFree((s) => s.active) && shown; const wrappers = useTextEditorWrappers((s) => s.wrappers); if (isTextInput(tab.input)) { const virtual = tab.input.kind === "virtual" ? virtualData(tab.input) : undefined; const wrapper = tab.input.kind === "file" ? textEditorWrapperFor(wrappers, tab.input.path) : undefined; - const host = ; + const host = shown && ; return ( <> - {virtual ? ( - - ) : ( - - )} - + {shown && + (virtual ? ( + + ) : ( + + ))} + {shown && } {crumbs && ( ); } - return ; + return ( + + + + ); } /** Tabs of a pane kept mounted while hidden: the most recently used ones of `keepAlive` kinds. */ const KEPT_TABS = 5; -function keptTabs(tabs: Tab[], mru: string[], kinds: Map): Tab[] { +function keptTabs( + tabs: Tab[], + mru: string[], + kinds: Map, + wrappers: ReadonlyMap, +): Tab[] { const recent = mru .map((id) => tabs.find((t) => t.id === id)) - .filter((t): t is Tab => !!t && !!kinds.get(t.input.kind)?.keepAlive) + .filter( + (t): t is Tab => + !!t && + (!!kinds.get(t.input.kind)?.keepAlive || + (t.input.kind === "file" && + t.input.path !== undefined && + !!textEditorWrapperFor(wrappers, t.input.path)?.keepAlive)), + ) .slice(0, KEPT_TABS); // In tab order, so switching tabs doesn't move their DOM (which would lose scroll offsets). return tabs.filter((t) => recent.includes(t)); @@ -559,7 +585,17 @@ function keptTabs(tabs: Tab[], mru: string[], kinds: Map(null); useSelectionVisibility(ref, kept); useLayoutEffect(() => { @@ -571,27 +607,34 @@ function KindEditor({ tab, shown, kept = false }: { tab: Tab; shown: boolean; ke sel.removeAllRanges(); } }, [kept, shown]); - const kinds = useContributions((s) => s.editorKinds); - const kind = kinds.get(tab.input.kind); - if (!kind) return ; - const Component = kind.component; return (
- - - + {children}
); } +function KindEditor({ tab }: { tab: Tab }) { + const kinds = useContributions((s) => s.editorKinds); + const kind = kinds.get(tab.input.kind); + if (!kind) return ; + const Component = kind.component; + return ; +} + /** Actions at the right end of the tab row (IDEA: split, tab actions ⋮). */ function EditorTabActions({ paneId, tab }: { paneId: string; tab: Tab }) { const ctrl = editorController(); diff --git a/src/editor/core/view/editorLayoutActions.test.tsx b/src/editor/core/view/editorLayoutActions.test.tsx index 9940bdade..9589f0d68 100644 --- a/src/editor/core/view/editorLayoutActions.test.tsx +++ b/src/editor/core/view/editorLayoutActions.test.tsx @@ -13,7 +13,7 @@ import { EditorAreaView } from "./EditorArea"; vi.mock("../controller", async (original) => ({ ...(await original()), - editorController: () => ({ publishContext: vi.fn(), tabMenu: () => [] }), + editorController: () => ({ publishContext: vi.fn(), tabMenu: () => [], slotFor: () => null }), })); vi.mock("./TextEditorHost", () => ({ TextEditorHost: () => })); vi.mock("./FindBar", () => ({ FindBar: () => null })); @@ -45,6 +45,7 @@ beforeEach(() => { disposers = [ registerTextEditorWrapper({ id: "test.markdown", + keepAlive: true, matches: (path) => path.endsWith(".md"), component: MarkdownEditor, tabActions: MarkdownLayoutActions, diff --git a/src/editor/lsp/markdownMath.ts b/src/editor/lsp/markdownMath.ts index 5c2c60a00..e7803bb50 100644 --- a/src/editor/lsp/markdownMath.ts +++ b/src/editor/lsp/markdownMath.ts @@ -21,6 +21,9 @@ interface MathToken extends Tokens.Generic { const escapeHtml = (s: string) => s.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); +export const declaresMathMacros = (source: string) => + /\\(?:(?:re)?new(?:command|environment)|def|let|DeclareMathOperator)\b/.test(source); + export function mathPlaceholder(tex: string, display: boolean, block = display): string { const tag = block ? "div" : "span"; const mode = display ? "display" : "inline"; @@ -129,26 +132,22 @@ function matchBlockMath(src: string): { raw: string; text: string } | null { /** Masks math spans with `a`s (preserving newlines) so `*` and `_` inside math never trigger emphasis. */ function maskInlineMath(src: string): string { + const delimiters = /[$\\]/g; let out = ""; - let i = 0; - while (i < src.length) { + let start = 0; + for (let at = delimiters.exec(src); at; at = delimiters.exec(src)) { + const i = at.index; if (src[i] === "\\" && src[i + 1] !== "(" && src[i + 1] !== "[") { - out += src.slice(i, i + 2); - i += 2; + delimiters.lastIndex++; continue; } - if (src[i] === "$" || (src[i] === "\\" && (src[i + 1] === "(" || src[i + 1] === "["))) { - const m = matchInlineMath(src.slice(i), MASKED_PROTECTED_INLINE_DOLLAR); - if (m) { - out += m.raw.replace(/[^\r\n]/g, "a"); - i += m.raw.length; - continue; - } + const math = matchInlineMath(src.slice(i), MASKED_PROTECTED_INLINE_DOLLAR); + if (math) { + out += src.slice(start, i) + math.raw.replace(/[^\r\n]/g, "a"); + start = delimiters.lastIndex = i + math.raw.length; } - out += src[i]!; - i++; } - return out; + return start ? out + src.slice(start) : src; } export function mathExtension(): MarkedExtension { diff --git a/src/features/viewers/index.ts b/src/features/viewers/index.ts index 67906c6d0..3d17bef39 100644 --- a/src/features/viewers/index.ts +++ b/src/features/viewers/index.ts @@ -124,6 +124,7 @@ export function activate(): () => void { }), registerTextEditorWrapper({ id: "viewers.markdown", + keepAlive: true, matches: isMarkdownPath, component: lazyComponent(() => import("./markdown/MarkdownEditor").then((m) => m.MarkdownEditor), { prefetch: true, diff --git a/src/features/viewers/markdown/Markdown.module.css b/src/features/viewers/markdown/Markdown.module.css index 0a7c734a7..01465a969 100644 --- a/src/features/viewers/markdown/Markdown.module.css +++ b/src/features/viewers/markdown/Markdown.module.css @@ -42,7 +42,15 @@ height: var(--h-floating-toolbar-button); } +.previewPane { + position: relative; + display: flex; + flex: 1; + min-height: 0; + min-width: 0; +} .preview { + contain: strict; flex: 1; min-height: 0; min-width: 0; diff --git a/src/features/viewers/markdown/MarkdownEditor.tsx b/src/features/viewers/markdown/MarkdownEditor.tsx index ea82b0700..d38070cd2 100644 --- a/src/features/viewers/markdown/MarkdownEditor.tsx +++ b/src/features/viewers/markdown/MarkdownEditor.tsx @@ -20,13 +20,25 @@ import { type ReactNode, } from "react"; import clsx from "clsx"; +import { Text } from "@codemirror/state"; +import { editorController } from "@/editor/core/controller"; +import type { EditorView } from "@codemirror/view"; import { call, commands, isTauri } from "@/platform/ipc"; import { editorPrefs, useEditorPrefs } from "@/platform/editorSettings"; import { useMarkdownPreviewFontSize, useMarkdownPreviewLayout } from "@/platform/languageSettings"; -import { maybeEditorService, registerFontZoomSurface } from "@/workbench/contributions"; +import { maybeEditorService, registerFontZoomSurface, useEditorShown } from "@/workbench/contributions"; import { editorsFor, setShownLine } from "@/editor/api"; import { highlightInto } from "@/editor/lsp/markdown"; -import { FloatingToolbar, Spinner, SplitGroup, SplitHandle, SplitPanel, selectableText } from "@/ui"; +import { + FloatingToolbar, + Scrollbar, + Spinner, + SplitGroup, + SplitHandle, + SplitPanel, + hideNativeScrollbar, + selectableText, +} from "@/ui"; import { FIND_CURRENT_HIGHLIGHT, FIND_HIGHLIGHT, @@ -40,10 +52,17 @@ import { selectionMatchesInNode, setPreviewHighlight, } from "./highlight"; -import { publishPreviewSelection, publishPreviewTop, stepMarkdownPreviewFontZoom, useLiveMarkdown } from "./live"; +import { followMarkdownSource } from "./splitScroll"; +import { + installMarkdownSourceScroll, + publishPreviewSelection, + publishPreviewTop, + stepMarkdownPreviewFontZoom, + useLiveMarkdown, +} from "./live"; import { subscribeTheme, themeKey } from "@/platform/themeWatch"; import { hasMermaid, MERMAID_SELECTOR, renderMermaidIn } from "./mermaid"; -import { renderMath } from "@/editor/lsp/markdownMath"; +import { declaresMathMacros, renderMath } from "@/editor/lsp/markdownMath"; import type { renderMathSvg } from "./mathSvg"; import { modeOf, pinMarkdownMode, useMarkdownModes } from "./modes"; import { MarkdownLayoutActions } from "./MarkdownLayoutActions"; @@ -127,6 +146,10 @@ export function MarkdownEditor({ const ref = useRef(null); const editorRef = useRef(null); + useEffect(() => { + if (mode === "split" && editorRef.current) return installMarkdownSourceScroll(editorRef.current); + }, [mode]); + // CodeMirror's internal ResizeObserver skips resizes within 75ms of a view update // and debounces by 50ms; re-measure immediately on drag and mode transitions. useEffect(() => { @@ -174,7 +197,7 @@ export function MarkdownEditor({ } > - + )} @@ -188,13 +211,45 @@ export function MarkdownEditor({ ); } -const blocksOf = (root: HTMLElement) => - [...root.querySelectorAll(":scope > [data-preview-blocks] > [data-line]")].map((el) => ({ - line: Number(el.dataset.line), - get top() { - return el.offsetTop; - }, - })); +function blocksOf(root: HTMLElement) { + const blocks = []; + for (const el of root.querySelectorAll(":scope > [data-preview-blocks] > [data-line]")) { + const line = Number(el.dataset.line); + const endLine = Number(el.dataset.endLine); + const table = el.firstElementChild; + if ( + table instanceof HTMLTableElement && + table.hasAttribute("data-markdown-table") && + table.rows.length + 1 === endLine - line + ) { + for (const [i, row] of Array.from(table.rows).entries()) { + const start = i === 0 ? line : line + i + 1; + blocks.push({ + line: start, + endLine: i === 0 ? line + 2 : start + 1, + get top() { + return row.getBoundingClientRect().top - root.getBoundingClientRect().top + root.scrollTop; + }, + get bottom() { + return row.getBoundingClientRect().bottom - root.getBoundingClientRect().top + root.scrollTop; + }, + }); + } + } else { + blocks.push({ + line, + endLine, + get top() { + return el.offsetTop; + }, + get bottom() { + return el.offsetTop + el.offsetHeight; + }, + }); + } + } + return blocks; +} let svgRenderer: Promise | undefined; @@ -205,21 +260,61 @@ function loadSvgRenderer() { )); } -function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) { +let lastParse: { source: Text; html: string } | undefined; +const parkedPreviews = new WeakMap(); +const previewGraphics = new WeakMap>(); + +function previewMarkup(source: Text, render: (text: string) => string, view: EditorView | null | undefined) { + const parked = view && parkedPreviews.get(view); + if (parked?.source === source) return parked.html; + if (lastParse?.source !== source) lastParse = { source, html: render(source.toString()) }; + return lastParse.html; +} + +function typesetPreview(content: HTMLElement, previous: HTMLElement, svg: typeof renderMathSvg | null) { + const inputs = [...content.querySelectorAll("[data-math], [data-mermaid]")]; + // A declaration can change the meaning of a later formula with identical source. + const declaresMacros = inputs.some((el) => el.hasAttribute("data-math") && declaresMathMacros(el.textContent ?? "")); + const available = previewGraphics.get(previous); + const rendered = new Map(); + for (const input of inputs) { + if (input.hasAttribute("data-math") && (declaresMacros || input.childElementCount)) continue; + const key = input.outerHTML; + const found = available?.get(key)?.pop(); + if (found) input.replaceWith(found); + const copies = rendered.get(key); + if (copies) copies.push(found ?? input); + else rendered.set(key, [found ?? input]); + } + for (const copies of rendered.values()) copies.reverse(); + svg?.(content); + renderMath(content); + return rendered; +} + +function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; sync: boolean }) { + const shown = useEditorShown(); const text = useLiveMarkdown((s) => s[path]?.text); const fontZoom = useLiveMarkdown((s) => s[path]?.fontZoom ?? 0); const fontSize = useMarkdownPreviewFontSize(); const zoomScale = Number((Math.max(4, fontSize + fontZoom) / fontSize).toFixed(4)); - const topLine = useLiveMarkdown((s) => s[path]?.topLine ?? 0); - const scrollSeq = useLiveMarkdown((s) => s[path]?.scrollSeq ?? 0); + const follower = useRef | null>(null); const caretLine = useLiveMarkdown((s) => s[path]?.caretLine ?? 0); const caretSeq = useLiveMarkdown((s) => s[path]?.caretSeq ?? 0); const find = useLiveMarkdown((s) => s[path]?.find ?? null); const editorSelection = useLiveMarkdown((s) => s[path]?.editorSelection ?? ""); const highlightSelection = useEditorPrefs().codeEditing.highlightSelection; - const deferred = useDeferredValue(text ?? ""); + const deferred = useDeferredValue(text ?? Text.empty); const [render] = useState(createMarkdownRenderer); - const html = useMemo(() => render(deferred), [render, deferred]); + const slot = editorController().slotFor(tabId); + const html = useMemo(() => previewMarkup(deferred, render, slot?.live), [render, deferred, slot]); + const sourceOffsets = useMemo(() => { + if (!sync) return undefined; + const offsets = [0]; + for (let n = 2; n <= deferred.lines; n++) offsets.push(deferred.line(n).from); + offsets.push(deferred.length); + return offsets; + }, [deferred, sync]); const renderSvg = html.includes(' data-math="') ? use(loadSvgRenderer()) : null; const ref = useRef(null); const linkRequest = useRef(0); @@ -227,6 +322,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) { const theme = useSyncExternalStore(subscribeTheme, themeKey, () => ""); const diagrams = useRef([]); const [diagramsDrawn, setDiagramsDrawn] = useState(0); + const [contentHeight, setContentHeight] = useState(0); const seenCaret = useRef(caretSeq); const seenFindMatch = useRef(null); /** scrollTop set by navigation, whose scroll event isn't the user's. */ @@ -239,25 +335,43 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) { useLayoutEffect(() => { toggled.current.clear(); - return () => { - linkRequest.current++; - }; }, [path]); + useLayoutEffect( + () => () => { + linkRequest.current++; + }, + [path, shown], + ); useLayoutEffect(() => { - ref.current?.querySelectorAll("details").forEach((d, i) => { + const root = ref.current; + if (!root) return; + const view = slot?.live; + const parked = view && parkedPreviews.get(view); + if (view) parkedPreviews.delete(view); + const cached = parked?.html === html ? parked.root : null; + if (cached !== root) { + if (cached) { + root.replaceChildren(...cached.children); + const graphics = previewGraphics.get(cached); + if (graphics) previewGraphics.set(root, graphics); + } else { + const content = document.createElement("div"); + content.dataset.previewBlocks = ""; + content.innerHTML = html; + previewGraphics.set(root, typesetPreview(content, parked?.root ?? root, renderSvg)); + root.replaceChildren(content); + } + } + root.querySelectorAll("details").forEach((d, i) => { const open = toggled.current.get(i); if (open !== undefined) d.open = open; }); - }, [html]); - - // Math before the preview index: typesetting changes the blocks' heights. - useLayoutEffect(() => { - if (!ref.current) return; - renderSvg?.(ref.current); - renderMath(ref.current); - blocks.current = blocksOf(ref.current); - invalidatePreviewIndex(ref.current); - }, [html, renderSvg]); + blocks.current = blocksOf(root); + invalidatePreviewIndex(root); + return () => { + if (view) parkedPreviews.set(view, { source: deferred, html, root }); + }; + }, [html, deferred, slot, renderSvg]); // Mermaid diagrams: before paint, so cached ones don't flash their source. useLayoutEffect(() => { @@ -294,7 +408,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) { setDiagramsDrawn((n) => n + 1); } }; - img.src = url; + if (img.getAttribute("src") !== url) img.src = url; if (!img.hasAttribute("data-natural-width") && img.complete && img.naturalWidth > 0 && img.naturalHeight > 0) { size(img, { w: img.naturalWidth, h: img.naturalHeight }); } @@ -332,27 +446,22 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) { }; }, [html, path]); - // Scroll sync: editor → preview. useLayoutEffect(() => { const root = ref.current; - if (!root || !sync) return; - root.scrollTop = topLine <= 0 ? 0 : previewOffsetForLine(blocks.current, topLine, root.scrollHeight); - }, [html, topLine, scrollSeq, sync, diagramsDrawn, fontZoom, fontSize]); + if (!root || !sync || !shown) return; + const follow = followMarkdownSource(path, root, (line) => + line <= 0 ? 0 : previewOffsetForLine(blocks.current, line, root.scrollHeight, sourceOffsets), + ); + follower.current = follow; + return () => { + follow.dispose(); + follower.current = null; + }; + }, [path, shown, sync, sourceOffsets]); - // Keep the split preview anchored to `topLine` as dragging the divider or resizing the window reflows text. - useEffect(() => { - const root = ref.current; - if (!root || !sync || typeof ResizeObserver === "undefined") return; - let width = root.clientWidth; - const ro = new ResizeObserver(() => { - if (root.clientWidth === width) return; - width = root.clientWidth; - const top = useLiveMarkdown.getState()[path]?.topLine ?? 0; - root.scrollTop = top <= 0 ? 0 : previewOffsetForLine(blocks.current, top, root.scrollHeight); - }); - ro.observe(root); - return () => ro.disconnect(); - }, [path, sync]); + useLayoutEffect(() => { + follower.current?.align(); + }, [path, sync, html, sourceOffsets, diagramsDrawn, fontZoom, fontSize]); useEffect(() => { const root = ref.current; @@ -371,15 +480,17 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) { let timer: number | undefined; const apply = () => { if (!width || width === settled) return; + const follow = follower.current; const top = root.scrollTop; const atBottom = top > 0 && top + root.clientHeight >= root.scrollHeight - 1; - const line = top > 0 ? previewLineAtOffset(blocks.current, top) : -1; + const line = !follow && top > 0 ? previewLineAtOffset(blocks.current, top) : -1; const block = line >= 0 ? blocks.current.find((b) => b.line === line) : undefined; const within = block ? top - block.top : 0; settled = width; root.removeAttribute("data-constrain-blocks"); root.style.setProperty("--markdown-block-width", `${width}px`); - if (atBottom) root.scrollTop = root.scrollHeight; + if (follow) follow.align(); + else if (atBottom) root.scrollTop = root.scrollHeight; else if (block) root.scrollTop = block.top + within; }; const schedule = () => { @@ -412,9 +523,16 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) { }; }, [html]); - // The preview's own scroll offset: tab switches and mode toggles unmount the - // preview, so Preview Only would otherwise start over at the top. Writes made - // by the split sync above are captured too — the last visible position wins. + useLayoutEffect(() => { + const root = ref.current; + if (!root) return; + const measure = () => setContentHeight(root.scrollHeight); + measure(); + root.addEventListener("toggle", measure, true); + return () => root.removeEventListener("toggle", measure, true); + }, [html, diagramsDrawn, fontZoom, fontSize]); + + // Restore Preview Only after a mode change or eviction from the kept tabs. useEffect(() => { const root = ref.current; if (!root) return; @@ -458,7 +576,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) { // Preview only: go where the hidden editor's caret was sent (Structure, Go to Symbol…). useLayoutEffect(() => { const root = ref.current; - if (!root || caretSeq === seenCaret.current) return; + if (!root || !shown || caretSeq === seenCaret.current) return; // First-open navigation can arrive before the destination's deferred Markdown is rendered. if (!sync && deferred !== text) return; seenCaret.current = caretSeq; @@ -482,12 +600,12 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) { restoreRetry.current = null; } setShownLine(path, caretLine); - }, [caretSeq, caretLine, sync, path, find, deferred, text]); + }, [caretSeq, caretLine, shown, sync, path, find, deferred, text]); // Search (⌘F) and selection occurrence highlights in the preview. useLayoutEffect(() => { const root = ref.current; - if (!root) return; + if (!root || !shown) return; const applyFind = () => { if (!find) { seenFindMatch.current = null; @@ -552,7 +670,7 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) { document.removeEventListener("selectionchange", applySelection); root.removeEventListener("toggle", applyAll, true); }; - }, [html, path, sync, find, editorSelection, highlightSelection]); + }, [html, path, shown, sync, find, editorSelection, highlightSelection]); useEffect(() => { const root = ref.current; @@ -578,10 +696,40 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) { e.stopPropagation(); if (zoom) stepMarkdownPreviewFontZoom(path, root, zoom); }; + const onPreviewWheel = (e: WheelEvent) => { + if ( + e.defaultPrevented || + !e.cancelable || + e.ctrlKey || + e.metaKey || + e.altKey || + e.shiftKey || + e.deltaMode !== WheelEvent.DOM_DELTA_PIXEL || + !e.deltaY || + Math.abs(e.deltaY) < Math.abs(e.deltaX) + ) + return; + const max = root.scrollHeight - root.clientHeight; + if (max <= root.clientHeight || (e.deltaY > 0 ? root.scrollTop >= max : root.scrollTop <= 0)) return; + for (let el = e.target instanceof Element ? e.target : null; el && el !== root; el = el.parentElement) { + if (el.scrollHeight <= el.clientHeight && (!e.deltaX || el.scrollWidth <= el.clientWidth)) continue; + const style = getComputedStyle(el); + if ( + (el.scrollHeight > el.clientHeight && /^(auto|scroll)$/.test(style.overflowY)) || + (e.deltaX && el.scrollWidth > el.clientWidth && /^(auto|scroll)$/.test(style.overflowX)) + ) + return; + } + // WebKit decides on the first wheel event whether it can scroll ahead of paint for the entire gesture. + e.preventDefault(); + root.scrollBy(e.deltaX, e.deltaY); + }; + root.addEventListener("wheel", onPreviewWheel, { passive: false }); root.addEventListener("wheel", onWheel, { capture: true, passive: false }); const release = registerFontZoomSurface(root, (delta) => stepMarkdownPreviewFontZoom(path, root, delta)); return () => { root.removeEventListener("wheel", onWheel, { capture: true }); + root.removeEventListener("wheel", onPreviewWheel); release(); }; }, [path]); @@ -590,10 +738,10 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) { // cleared when the editor is back or the preview goes away. useEffect(() => { const root = ref.current; - if (!root || sync) return; + if (!root || sync || !shown) return; setShownLine(path, previewLineAtOffset(blocks.current, root.scrollTop)); return () => setShownLine(path, null); - }, [sync, path]); + }, [sync, path, shown]); useEffect(() => () => cancelAnimationFrame(scrollFrame.current), []); const onScroll = () => { @@ -646,23 +794,24 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) { }; return ( -
-
+
+
+
); } diff --git a/src/features/viewers/markdown/live.test.ts b/src/features/viewers/markdown/live.test.ts new file mode 100644 index 000000000..22882fd72 --- /dev/null +++ b/src/features/viewers/markdown/live.test.ts @@ -0,0 +1,116 @@ +import { EditorState } from "@codemirror/state"; +import { BlockType, EditorView, type BlockInfo } from "@codemirror/view"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { editorContributions, type EditorDocContext } from "@/editor/api"; +import { installMarkdownSourceScroll, registerMarkdownLiveSource, useLiveMarkdown } from "./live"; + +const ctx: EditorDocContext = { doc: 1, path: "/p/README.md", language: "markdown", uiMode: null, readOnly: false }; + +describe("Markdown source scroll", () => { + let view: EditorView; + let unregister: () => void; + + beforeEach(() => { + unregister = registerMarkdownLiveSource(); + const contribution = editorContributions().find((item) => item.id === "viewers.markdownLive")!; + view = new EditorView({ + state: EditorState.create({ + doc: "# Title\nA wrapped line\nMore text", + extensions: contribution.extensions(ctx), + }), + }); + Object.defineProperties(view.scrollDOM, { + clientHeight: { value: 100 }, + scrollHeight: { value: 500 }, + }); + vi.spyOn(view.scrollDOM, "getBoundingClientRect").mockReturnValue(new DOMRect(0, 100, 400, 100)); + }); + + afterEach(() => { + view.destroy(); + unregister(); + useLiveMarkdown.setState({}, true); + vi.restoreAllMocks(); + }); + + function sourceBlock(lineNumber: number, top: number, height: number): BlockInfo { + const { from, to, length } = view.state.doc.line(lineNumber); + return { + from, + to, + length, + top, + height, + bottom: top + height, + type: BlockType.Text, + widget: null, + widgetLineBreaks: 0, + }; + } + + it("publishes progress within the visible line and tracks the source bottom", () => { + vi.spyOn(view, "requestMeasure").mockImplementation((request) => { + if (request) request.write?.(request.read(view), view); + }); + vi.spyOn(view, "documentTop", "get").mockReturnValue(30); + vi.spyOn(view, "lineBlockAtHeight").mockReturnValue(sourceBlock(2, 50, 40)); + const scroller = view.scrollDOM; + const position = () => useLiveMarkdown.getState()[ctx.path]; + + scroller.scrollTop = 75; + scroller.dispatchEvent(new Event("scroll")); + expect(view.lineBlockAtHeight).toHaveBeenCalledWith(70); + expect(position()).toMatchObject({ topLine: 1.5, sourceAtEnd: false, scrollSeq: 1 }); + + scroller.scrollTop = 399.5; + scroller.dispatchEvent(new Event("scroll")); + expect(position()).toMatchObject({ topLine: 1.5, sourceAtEnd: true, scrollSeq: 2 }); + + scroller.scrollTop = 75; + scroller.dispatchEvent(new Event("scroll")); + expect(position()).toMatchObject({ topLine: 1.5, sourceAtEnd: false, scrollSeq: 3 }); + }); + + it("weights the top visual row by the source characters in that wrap", () => { + vi.spyOn(view, "requestMeasure").mockImplementation((request) => { + if (request) request.write?.(request.read(view), view); + }); + vi.spyOn(view, "inView", "get").mockReturnValue(true); + vi.spyOn(view, "documentTop", "get").mockReturnValue(35); + vi.spyOn(view, "lineWrapping", "get").mockReturnValue(true); + vi.spyOn(view, "defaultLineHeight", "get").mockReturnValue(10); + vi.spyOn(view, "lineBlockAtHeight").mockReturnValue(sourceBlock(2, 50, 30)); + const line = view.state.doc.line(2); + vi.spyOn(view, "posAtCoords") + .mockReturnValueOnce(line.from + 7) + .mockReturnValueOnce(line.from + 9); + view.scrollDOM.dispatchEvent(new Event("scroll")); + expect(useLiveMarkdown.getState()[ctx.path]?.topLine).toBeCloseTo(1 + 8 / (line.length + 1)); + }); + + it("measures a wheel jump that would expose an unrendered part of the source", () => { + const block = sourceBlock(1, 0, 140); + vi.spyOn(view, "documentTop", "get").mockReturnValue(100); + vi.spyOn(view, "viewport", "get").mockReturnValue({ from: block.from, to: block.to }); + vi.spyOn(view, "viewportLineBlocks", "get").mockReturnValue([block]); + const measure = vi.spyOn(view, "requestMeasure").mockImplementation(() => {}); + const lineAtHeight = vi.spyOn(view, "lineBlockAtHeight").mockReturnValue(block); + const scrollBy = vi.fn(); + Object.defineProperty(view.scrollDOM, "scrollBy", { value: scrollBy }); + const dispose = installMarkdownSourceScroll(view.dom); + const wheel = (init: WheelEventInit) => + view.contentDOM.dispatchEvent(new WheelEvent("wheel", { bubbles: true, cancelable: true, ...init })); + + try { + expect(wheel({ deltaY: 10 })).toBe(true); + expect(wheel({ deltaY: 100, ctrlKey: true })).toBe(true); + expect(wheel({ deltaX: 100, deltaY: 10 })).toBe(true); + expect(wheel({ deltaX: 3, deltaY: 100 })).toBe(false); + expect(scrollBy).toHaveBeenCalledExactlyOnceWith(3, 100); + expect(measure).toHaveBeenCalledTimes(1); + expect(lineAtHeight).toHaveBeenCalledExactlyOnceWith(100); + } finally { + dispose(); + } + }); +}); diff --git a/src/features/viewers/markdown/live.ts b/src/features/viewers/markdown/live.ts index d9178ba14..6e66d3809 100644 --- a/src/features/viewers/markdown/live.ts +++ b/src/features/viewers/markdown/live.ts @@ -1,11 +1,10 @@ /** * Live Markdown source for the preview: an editor contribution on Markdown - * files publishes the document text (debounced while typing), the first - * visible line of the editor (for scroll sync) and caret moves (so a Preview - * only preview follows navigation in its hidden editor), per path. + * files publishes the text, scroll position, and caret moves per path. + * Preview Only follows navigation in the hidden editor. */ -import { StateEffect, type EditorState } from "@codemirror/state"; -import { Decoration, ViewPlugin, type DecorationSet, type EditorView, type ViewUpdate } from "@codemirror/view"; +import { StateEffect, Text, type EditorState } from "@codemirror/state"; +import { Decoration, Direction, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view"; import { SearchCursor, getSearchQuery } from "@codemirror/search"; import { create } from "zustand"; import { registerEditorContribution, useEditorRegistry } from "@/editor/api"; @@ -26,9 +25,11 @@ export interface LiveMarkdownFind { } export interface LiveMarkdown { - text: string; - /** 0-based first visible source line of the editor that scrolled last. */ + text: Text; + /** 0-based source line at the top of the editor, including progress through the line. */ topLine: number; + /** Whether the scrolling editor has reached its bottom. */ + sourceAtEnd: boolean; /** Bumped when the editor scrolls, so equal lines still resync. */ scrollSeq: number; /** The editor's font zoom in px; the preview scales its text by the same amount. */ @@ -56,8 +57,9 @@ const previewSelectionMark = Decoration.mark({ class: "cm-selectionMatch" }); function publish(path: string, patch: Partial) { useLiveMarkdown.setState((s) => { const prev = s[path] ?? { - text: "", + text: Text.empty, topLine: 0, + sourceAtEnd: false, scrollSeq: 0, fontZoom: 0, caretLine: 0, @@ -152,9 +154,93 @@ function previewSelectionDecorations(view: EditorView, query: string): Decoratio return Decoration.set(ranges); } -function topLineOf(view: EditorView): number { - const block = view.lineBlockAtHeight(view.scrollDOM.scrollTop); - return view.state.doc.lineAt(block.from).number - 1; +function sourcePositionOf(view: EditorView) { + const scroller = view.scrollDOM; + if (!view.inView || !scroller.clientHeight) return null; + const y = Math.max(0, sourceViewportTop(view)); + const block = view.lineBlockAtHeight(y); + const line = view.state.doc.lineAt(block.from); + let fraction = block.height > 0 ? Math.max(0, Math.min(1, (y - block.top) / block.height)) : 0; + const rowHeight = view.defaultLineHeight; + if ( + view.lineWrapping && + rowHeight > 0 && + block.height > rowHeight * 1.5 && + block.from === line.from && + block.to === line.to + ) { + // Interpolate between the source offsets of the visible wrapped row and the following row. + const row = Math.floor((y - block.top) / rowHeight); + const rowTop = block.top + row * rowHeight; + const rect = view.contentDOM.getBoundingClientRect(); + const x = view.textDirectionAt(line.from) === Direction.LTR ? rect.left + 1 : rect.right - 1; + const middle = view.documentTop + rowTop + rowHeight / 2; + const start = view.posAtCoords({ x, y: middle }); + const next = + rowTop + rowHeight >= block.bottom - 0.5 ? line.to + 1 : view.posAtCoords({ x, y: middle + rowHeight }); + if (start !== null && next !== null && start >= line.from && next >= start && next <= line.to + 1) { + const withinRow = Math.max(0, Math.min(1, (y - rowTop) / rowHeight)); + const span = line.length + Number(line.number < view.state.doc.lines); + if (span) fraction = Math.min(1, (start - line.from + withinRow * (next - start)) / span); + } + } + const topLine = line.number - 1 + fraction; + const sourceAtEnd = scroller.scrollTop > 0 && scroller.scrollHeight - scroller.clientHeight - scroller.scrollTop <= 1; + return { topLine, sourceAtEnd }; +} + +/** Redraws the split source before paint when a wheel jump passes its rendered lines. */ +export function installMarkdownSourceScroll(root: HTMLElement): () => void { + const onWheel = (event: WheelEvent) => { + if ( + event.defaultPrevented || + !event.cancelable || + event.ctrlKey || + event.metaKey || + event.shiftKey || + event.altKey || + event.deltaMode !== WheelEvent.DOM_DELTA_PIXEL || + !event.deltaY || + Math.abs(event.deltaX) > Math.abs(event.deltaY) || + !(event.target instanceof Element) + ) + return; + + const scroller = event.target.closest(".cm-scroller"); + const view = scroller && EditorView.findFromDOM(scroller); + if (!scroller || !view) return; + + const current = scroller.scrollTop; + const height = scroller.clientHeight; + const max = scroller.scrollHeight - height; + const target = Math.min(max, Math.max(0, current + event.deltaY)); + if (max <= 0 || target === current) return; + + const scale = view.scaleY; + const nextTop = sourceViewportTop(view) + (target - current) * scale; + const blocks = view.viewportLineBlocks; + const first = blocks[0]; + const last = blocks.at(-1); + if (!first || !last) return; + if ( + (view.viewport.from === 0 || nextTop >= first.top) && + (view.viewport.to === view.state.doc.length || nextTop + height * scale <= last.bottom) + ) + return; + + // A native jump can expose a virtual gap before CodeMirror redraws. Move and measure together. + event.preventDefault(); + scroller.scrollBy(event.deltaX, target - current); + view.requestMeasure(); + view.lineBlockAtHeight(nextTop); + }; + root.addEventListener("wheel", onWheel, { passive: false }); + return () => root.removeEventListener("wheel", onWheel); +} + +function sourceViewportTop(view: EditorView): number { + const scroller = view.scrollDOM; + return scroller.getBoundingClientRect().top + scroller.clientTop * view.scaleY - view.documentTop; } function livePlugin(path: string) { @@ -162,16 +248,25 @@ function livePlugin(path: string) { class { decorations: DecorationSet = Decoration.none; private timer: ReturnType | undefined; - private frame = 0; + private scrolled = false; + private destroyed = false; private previewSel = ""; private unsubscribe: () => void; + private readonly measureSource = { + read: sourcePositionOf, + write: (position: ReturnType) => { + const scrolled = this.scrolled; + this.scrolled = false; + if (this.destroyed || !position) return; + const prev = useLiveMarkdown.getState()[path]; + if (scrolled || position.topLine !== prev?.topLine || position.sourceAtEnd !== prev?.sourceAtEnd) { + publish(path, { ...position, scrollSeq: (prev?.scrollSeq ?? 0) + Number(scrolled) }); + } + }, + }; private readonly onScroll = () => { - if (this.frame) return; - this.frame = requestAnimationFrame(() => { - this.frame = 0; - const seq = (useLiveMarkdown.getState()[path]?.scrollSeq ?? 0) + 1; - publish(path, { topLine: topLineOf(this.view), scrollSeq: seq }); - }); + this.scrolled = true; + this.view.requestMeasure(this.measureSource); }; constructor(private view: EditorView) { @@ -179,7 +274,7 @@ function livePlugin(path: string) { this.previewSel = current?.previewSelection ?? ""; this.decorations = previewSelectionDecorations(view, this.previewSel); publish(path, { - text: view.state.doc.toString(), + text: view.state.doc, fontZoom: view.state.field(fontZoom, false) ?? 0, find: findStateOf(view.state), editorSelection: editorSelectionOf(view.state), @@ -235,30 +330,22 @@ function livePlugin(path: string) { this.decorations = previewSelectionDecorations(u.view, this.previewSel); } + if (u.geometryChanged) u.view.requestMeasure(this.measureSource); if (!u.docChanged) { - if (u.geometryChanged && u.view.scrollDOM.scrollTop > 0) { - u.view.requestMeasure({ - key: this, - read: topLineOf, - write: (topLine) => { - if (topLine !== useLiveMarkdown.getState()[path]?.topLine) publish(path, { topLine }); - }, - }); - } if (u.selectionSet) this.publishCaret(); return; } clearTimeout(this.timer); - this.timer = setTimeout(() => publish(path, { text: this.view.state.doc.toString() }), TEXT_DELAY); + this.timer = setTimeout(() => publish(path, { text: this.view.state.doc }), TEXT_DELAY); } destroy() { + this.destroyed = true; clearTimeout(this.timer); - cancelAnimationFrame(this.frame); this.unsubscribe(); this.view.scrollDOM.removeEventListener("scroll", this.onScroll); // Flush the latest edit for a preview that outlives this view. - publish(path, { text: this.view.state.doc.toString() }); + publish(path, { text: this.view.state.doc }); } }, { decorations: (v) => v.decorations }, diff --git a/src/features/viewers/markdown/mathSvg.test.ts b/src/features/viewers/markdown/mathSvg.test.ts index 56339b32f..f5421169e 100644 --- a/src/features/viewers/markdown/mathSvg.test.ts +++ b/src/features/viewers/markdown/mathSvg.test.ts @@ -14,12 +14,9 @@ it("renders inline and display equations as independent SVGs with accessible Mat expect(display).toHaveLength(1); expect(root.querySelector("strong > [data-math-svg] > svg")?.getAttribute("aria-label")).toBe("v_0"); expect(root.querySelectorAll("mjx-assistive-mml math")).toHaveLength(3); - expect( - [...root.querySelectorAll("svg use")].every((use) => { - const href = use.getAttribute("xlink:href"); - return href?.startsWith("#") && use.closest("svg")?.querySelector(`[id="${href.slice(1)}"]`); - }), - ).toBe(true); + expect([...inline, ...display].every((svg) => svg.querySelector("path[d]"))).toBe(true); + expect(inline[0]!.innerHTML).toBe(inline[1]!.innerHTML); + expect(inline[0]!.firstChild).not.toBe(inline[1]!.firstChild); }); it("leaves unsupported formulas for KaTeX without enabling TeX links", () => { diff --git a/src/features/viewers/markdown/mathSvg.ts b/src/features/viewers/markdown/mathSvg.ts index 7f2cb3790..fc640be91 100644 --- a/src/features/viewers/markdown/mathSvg.ts +++ b/src/features/viewers/markdown/mathSvg.ts @@ -11,6 +11,8 @@ import { mathjax } from "@mathjax/src/js/mathjax.js"; import { SVG } from "@mathjax/src/js/output/svg.js"; import { SafeHandler } from "@mathjax/src/js/ui/safe/SafeHandler.js"; +import { declaresMathMacros } from "@/editor/lsp/markdownMath"; + function createSvgRenderer() { const handler = RegisterHTMLHandler(browserAdaptor()); SafeHandler(handler); @@ -23,7 +25,7 @@ function createSvgRenderer() { }); const math = mathjax.document("", { InputJax: tex, - OutputJax: new SVG({ fontData: MathJaxTexFont, fontCache: "local" }), + OutputJax: new SVG({ fontData: MathJaxTexFont, fontCache: "none" }), safeOptions: { allow: { URLs: "none", classes: "none", cssIDs: "none", styles: "none" } }, }); return (source: string, display: boolean) => { @@ -35,11 +37,21 @@ function createSvgRenderer() { let convert: ReturnType | undefined; export function renderMathSvg(root: HTMLElement) { - for (const element of root.querySelectorAll("[data-math]")) { + const inputs = [...root.querySelectorAll("[data-math]")]; + const copies = inputs.some((el) => declaresMathMacros(el.textContent ?? "")) ? null : new Map(); + for (const element of inputs) { const mode = element.getAttribute("data-math"); const source = element.textContent?.trim(); if (!source || (mode !== "inline" && mode !== "display")) continue; try { + const key = mode + ":" + source; + const cached = copies?.get(key); + if (cached) { + element.replaceChildren(...Array.from(cached.childNodes, (node) => node.cloneNode(true))); + element.setAttribute("data-math-svg", mode); + element.removeAttribute("data-math"); + continue; + } convert ??= createSvgRenderer(); const output = convert(source, mode === "display"); const svg = output.querySelector("svg"); @@ -48,6 +60,7 @@ export function renderMathSvg(root: HTMLElement) { element.setAttribute("data-math-svg", mode); element.removeAttribute("data-math"); element.replaceChildren(...output.childNodes); + if (copies && !element.querySelector("[id]")) copies.set(key, element); } catch { // Keep unsupported TeX for the existing KaTeX renderer. } diff --git a/src/features/viewers/markdown/mermaid.test.ts b/src/features/viewers/markdown/mermaid.test.ts index 4ae70778d..c97899296 100644 --- a/src/features/viewers/markdown/mermaid.test.ts +++ b/src/features/viewers/markdown/mermaid.test.ts @@ -151,6 +151,16 @@ describe("mermaid in the markdown preview", () => { expect(root.querySelector("svg")).toBe(svg); }); + it("renders repeated diagrams with math labels once in the same pass", async () => { + const diagram = '```mermaid\nflowchart LR\n A["$$x^2$$"] --> B\n```\n'; + const root = preview([diagram, diagram, diagram.replace("x^2", "x^3")].join("\n")); + await renderMermaidIn(root).done; + const drawings = [...root.querySelectorAll(".mermaid-output svg")]; + expect(m.render).toHaveBeenCalledTimes(2); + expect(drawings).toHaveLength(3); + expect(new Set(drawings.map((drawing) => drawing.id)).size).toBe(3); + }); + it("applies a cached diagram with fresh SVG ids so copies don't share markers", async () => { const first = preview(SEQ); await renderMermaidIn(first, []).done; diff --git a/src/features/viewers/markdown/mermaid.ts b/src/features/viewers/markdown/mermaid.ts index e164f5792..97a63a1a6 100644 --- a/src/features/viewers/markdown/mermaid.ts +++ b/src/features/viewers/markdown/mermaid.ts @@ -217,7 +217,15 @@ async function renderOne(source: string, key: string): Promise { /** Resolves `null` when the pass was superseded before its turn came. */ function enqueue(source: string, key: string, live: () => boolean): Promise { - const p = queue.then(() => (live() ? renderOne(source, key) : null)); + const k = `${key}\n${source}`; + const p = queue.then(async () => { + if (!live()) return null; + const cached = cache.get(k); + if (cached) return cached; + const result = await renderOne(source, key); + remember(k, result); + return result; + }); queue = p.catch(() => undefined); return p; } @@ -289,6 +297,7 @@ export function renderMermaidIn(root: HTMLElement, previous: Node[] = []): Merma if (!blocks.length) return { async: false, done: Promise.resolve(), cancel: () => {} }; const key = themeKey(); const pending: Promise[] = []; + const rendering = new Map>(); blocks.forEach((block, i) => { const source = (block.querySelector("code")?.textContent ?? "").replace(/\n+$/, ""); const k = `${key}\n${source}`; @@ -310,11 +319,14 @@ export function renderMermaidIn(root: HTMLElement, previous: Node[] = []): Merma } drawn.delete(block); show(block, null, previous[i]); + let result = rendering.get(k); + if (!result) { + result = enqueue(source, key, () => live); + rendering.set(k, result); + } pending.push( - enqueue(source, key, () => live).then((r) => { - if (!r) return; - remember(k, r); - if (!live) return; + result.then((r) => { + if (!live || !r) return; show(block, r); drawn.set(block, k); keep(); diff --git a/src/features/viewers/markdown/previewScroll.test.tsx b/src/features/viewers/markdown/previewScroll.test.tsx index 87c531e98..332be2b9c 100644 --- a/src/features/viewers/markdown/previewScroll.test.tsx +++ b/src/features/viewers/markdown/previewScroll.test.tsx @@ -11,6 +11,7 @@ let activeSlot: Partial | null = null; vi.mock("@/editor/core/controller", async (importOriginal) => ({ ...(await importOriginal()), editorController: () => ({ + slotFor: () => activeSlot, get activeSlot() { return activeSlot; }, @@ -38,7 +39,7 @@ describe("preview-only scroll position", () => { views.push(view); return view; }; - const activate = (view: EditorView) => (activeSlot = { view, disposed: false }); + const activate = (view: EditorView) => (activeSlot = { view, live: view, disposed: false }); beforeEach(() => { disposers.push(registerMarkdownLiveSource()); @@ -80,6 +81,92 @@ describe("preview-only scroll position", () => { second.unmount(); }); + it("handles a long preview gesture from its first pixel and leaves nested scrolling native", () => { + open(mdCtx); + act(() => useMarkdownModes.setState((s) => ({ byTab: { ...s.byTab, t: "preview" } }))); + render( + +
+ , + ); + const preview = screen.getByRole("document", { name: "Markdown preview" }); + Object.defineProperties(preview, { + clientHeight: { value: 400 }, + scrollHeight: { value: 2000, configurable: true }, + }); + const scrollBy = vi.fn(); + preview.scrollBy = scrollBy; + const nested = document.createElement("pre"); + nested.style.overflowY = "auto"; + Object.defineProperties(nested, { clientHeight: { value: 30 }, scrollHeight: { value: 120 } }); + preview.appendChild(nested); + const wheel = (target: Element, init: WheelEventInit) => + target.dispatchEvent( + new WheelEvent("wheel", { + bubbles: true, + cancelable: true, + ...init, + }), + ); + expect(wheel(preview, { deltaY: 1 })).toBe(false); + expect(wheel(preview, { deltaY: -300 })).toBe(true); + expect(wheel(preview, { deltaY: 300, deltaMode: 1 })).toBe(true); + expect(wheel(preview, { deltaY: 300, deltaX: 400 })).toBe(true); + expect(wheel(nested, { deltaY: 300 })).toBe(true); + expect(wheel(preview, { deltaY: 300, deltaX: 1 })).toBe(false); + Object.defineProperty(preview, "scrollHeight", { value: 650 }); + expect(wheel(preview, { deltaY: 1 })).toBe(true); + expect(scrollBy.mock.calls).toEqual([ + [0, 1], + [1, 300], + ]); + }); + + it("keeps unchanged equations across edits and tab switches", async () => { + const view = open(mdCtx); + activate(view); + const source = "$x$ and $y$."; + act(() => view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: source } })); + const preview = () => + render( + +
+ , + ); + const nodes = () => [...screen.getByRole("document").querySelectorAll("[data-math-svg] > svg")]; + const first = preview(); + await vi.waitFor(() => expect(nodes()).toHaveLength(2)); + const [x, y] = nodes(); + const at = source.indexOf("y"); + act(() => view.dispatch({ changes: { from: at, to: at + 1, insert: "z" } })); + await vi.waitFor(() => expect(nodes().map((n) => n.getAttribute("aria-label"))).toEqual(["x", "z"])); + const [sameX, z] = nodes(); + expect(sameX).toBe(x); + expect(z).not.toBe(y); + first.unmount(); + preview(); + expect(nodes()[0]).toBe(x); + expect(nodes()[1]).toBe(z); + }); + + it("refreshes dependent equations after a TeX macro changes", async () => { + const view = open(mdCtx); + activate(view); + const text = String.raw`$\def\previewletter{a}\previewletter$ and $\previewletter$`; + act(() => view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: text } })); + render( + +
+ , + ); + const letters = () => + [...screen.getByRole("document").querySelectorAll("mjx-assistive-mml mi")].map((el) => el.textContent); + await vi.waitFor(() => expect(letters()).toEqual(["a", "a"])); + const at = text.indexOf("{a}") + 1; + act(() => view.dispatch({ changes: { from: at, to: at + 1, insert: "b" } })); + await vi.waitFor(() => expect(letters()).toEqual(["b", "b"])); + }); + it("re-applies a restore that clamped to not-yet-drawn content", async () => { open(mdCtx); activate(views[0]!); diff --git a/src/features/viewers/markdown/render.test.ts b/src/features/viewers/markdown/render.test.ts index 8f28c73bb..3135c3e66 100644 --- a/src/features/viewers/markdown/render.test.ts +++ b/src/features/viewers/markdown/render.test.ts @@ -131,6 +131,19 @@ describe("markdown preview rendering", () => { expect(root.querySelector("h1")?.id).toBe("user-content-title"); }); + it("keeps embedded image destinations and code samples intact", () => { + const url = "data:image/png;base64," + "abcd".repeat(100); + const line = `![](${url})`; + const render = createMarkdownRenderer(); + const root = document.createElement("div"); + root.innerHTML = render([line, "", "## Next", "", line].join("\n")); + expect([...root.querySelectorAll("img")].map((img) => img.dataset.src)).toEqual([url, url]); + expect(root.querySelector("h2")?.parentElement?.dataset.line).toBe("2"); + root.innerHTML = render([line, "", "```md", line, "```"].join("\n")); + expect(root.querySelector("code")?.textContent?.trimEnd()).toBe(line); + expect(root.querySelector("img")?.dataset.src).toBe(url); + }); + it("sanitizes and defers image loading", () => { const root = document.createElement("div"); root.innerHTML = renderMarkdown( @@ -362,6 +375,28 @@ describe("markdown preview rendering", () => { expect(previewOffsetForLine([], 3, 400)).toBe(0); }); + it("tracks table rows across the delimiter and excludes trailing blank lines from a block", () => { + const root = document.createElement("div"); + root.innerHTML = renderMarkdown("| a | b |\n|---|---|\n| 1 | 2 |\n| 3 | 4 |\n\nNext"); + const table = root.querySelector("table[data-markdown-table]")!; + expect(table.querySelectorAll("tr")).toHaveLength(3); + expect(table.parentElement?.dataset).toMatchObject({ line: "0", endLine: "4" }); + expect(root.lastElementChild?.getAttribute("data-line")).toBe("5"); + }); + + it("follows source characters inside a wrapped block and crosses the gap below its rendered box", () => { + const blocks = [ + { line: 0, endLine: 2, top: 10, bottom: 110 }, + { line: 4, endLine: 5, top: 130, bottom: 160 }, + ]; + const sourceOffsets = [0, 80, 100, 101, 102, 110]; + expect(previewOffsetForLine(blocks, 0.5, 400, sourceOffsets)).toBe(50); + expect(previewOffsetForLine(blocks, 1, 400, sourceOffsets)).toBe(90); + expect(previewOffsetForLine(blocks, 2, 400, sourceOffsets)).toBe(110); + expect(previewOffsetForLine(blocks, 3, 400, sourceOffsets)).toBe(120); + expect(previewOffsetForLine(blocks, 4, 400, sourceOffsets)).toBe(130); + }); + it("finds the block at the top of a scrolled preview", () => { const blocks = [ { line: 2, top: 0 }, diff --git a/src/features/viewers/markdown/render.ts b/src/features/viewers/markdown/render.ts index c5f4680c4..970975e19 100644 --- a/src/features/viewers/markdown/render.ts +++ b/src/features/viewers/markdown/render.ts @@ -150,29 +150,61 @@ function trackContainers(raw: string, open: string[]) { } } -/** The preview's blocks: each top-level block, or run of blocks inside one HTML container, as unsanitized HTML. */ -function blocks(text: string): { line: number; html: string }[] { +type MarkdownBlock = { line: number; endLine: number; html: string }; + +function lexBlocks(body: string): TokensList { + // Marked repeatedly scans the remaining input for block boundaries. Keep the bytes of + // standalone embedded images out of those scans and restore their URLs before rendering. + const prefix = "openidea-embedded-image-"; + if (!body.includes(";base64,") || body.includes(prefix)) return marked.lexer(body); + const urls: string[] = []; + const compact = body.replace( + /^!\[\]\((data:image\/[\w.+-]+;base64,[A-Za-z0-9+/]{256,}={0,2})\)(?=[ \t]*\r?$)/gm, + (_, url: string) => { + urls.push(url); + return `![](${prefix}${urls.length - 1})`; + }, + ); + const tokens = marked.lexer(compact); + let restored = 0; + for (const token of tokens) { + if (restored === urls.length) break; + if (!token.raw.includes(prefix)) continue; + const image = token.type === "paragraph" && token.tokens?.length === 1 && token.tokens[0]; + if (!image || image.type !== "image" || image.href !== prefix + restored || token.raw.trimEnd() !== image.raw) + return marked.lexer(body); + image.href = urls[restored++]!; + } + return restored === urls.length ? tokens : marked.lexer(body); +} + +/** Top-level source ranges; an open HTML container groups its enclosed blocks. */ +function blocks(text: string): MarkdownBlock[] { const front = frontMatter(text); const body = front ? text.split("\n").slice(front.lines).join("\n") : text; - const tokens = marked.lexer(body); + const tokens = lexBlocks(body); const slugs = new Map(); let line = front?.lines ?? 0; - const out = front ? [{ line: 0, html: frontMatterTable(front.fields) }] : []; + const out = front ? [{ line: 0, endLine: front.lines, html: frontMatterTable(front.fields) }] : []; // Blocks inside an HTML container left open (`
`, `
`…) share its wrapper up to // the close: a wrapper per block would end the container early and spill its content out. const open: string[] = []; - let group: { line: number; html: string } | null = null; + let group: MarkdownBlock | null = null; for (const token of tokens) { const start = line; line += countLines(token.raw); if (token.type === "space" || token.type === "footnoteDefinition") continue; const list = Object.assign([token], { links: tokens.links }) as TokensList; let body = marked.parser(list); + if (token.type === "table") { + body = body.replace(/^/, '
'); + } if (token.type === "heading") { const id = headingId(slugs, (token as Token & { text: string }).text); body = body.replace(/^/, ``); } - group ??= { line: start, html: "" }; + group ??= { line: start, endLine: start, html: "" }; + group.endLine = start + countLines(token.raw.trimEnd()) + 1; group.html += body; if (token.type === "html") trackContainers(token.raw, open); if (open.length) continue; @@ -181,23 +213,24 @@ function blocks(text: string): { line: number; html: string }[] { } if (group) out.push(group); const footnotes = renderFootnotes(marked, tokens); - if (footnotes) out.push({ line: countLines(text), html: footnotes }); + if (footnotes) out.push({ line: countLines(text), endLine: countLines(text) + 1, html: footnotes }); return out; } const SANITIZE = { USE_PROFILES: { html: true }, - ADD_ATTR: ["data-src", "data-line", "data-front-matter", "data-math"], + ADD_ATTR: ["data-src", "data-line", "data-end-line", "data-markdown-table", "data-front-matter", "data-math"], // The preview shares the IDE's document: a `