-
+
);
}
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