Keep the view in place while scrolling through tables and images

The view jumped to other text in large documents. A short line with
another height, such as a code fence, became the CodeMirror reference
for the line height. CodeMirror then estimated all heights again, and
its layout loop stopped before it restored the scroll position. Each new
table or image height started this check.

- A mark span keeps lines with another height out of that reading.
- A resize observer records the preview heights. A measure request from
  `toDOM` restarted the layout loop.
- A hidden layer measures each table before its first draw.
- Images keep their space from their natural size, in Write and Read.

The scrollStability smoke test and the imageSizes unit test check this.
Real wheel input on large documents gave no jumps in Write and Read.
Card be7df1de.
This commit is contained in:
Knotty Wyvern
2026-11-04 21:41:20 -07:00
parent cbdaa12c84
commit 2b28707ba0
9 changed files with 370 additions and 16 deletions
@@ -0,0 +1,145 @@
// Scrolling in Write and Read through a large document with large tables, images, code blocks, and short lines keeps the text in place.
import assert from "node:assert/strict";
import { chooseView, mockTauri, runSmoke, smokeUrl } from "../_harness/index.mjs";
const words = "lorem ipsum dolor sit amet consectetur adipiscing elit sed do eiusmod tempor incididunt ut labore et dolore magna aliqua".split(" ");
const text = (seed, count) => Array.from({ length: count }, (_, i) => words[(seed * 7 + i * 3) % words.length]).join(" ");
/** A short first heading holds the caret when the document opens. Short code lines and fences have another line height than prose. */
function largeDocument() {
const parts = ["# Large\n"];
for (let section = 0; section < 10; section++) {
parts.push(`## Section ${section}\n`, `Short line ${section}\n`, " \n");
for (let p = 0; p < 5; p++) parts.push(`P${section}.${p} ${text(section + p, 30 + (p * 37) % 90)}\n`);
const rows = Array.from({ length: 25 + (section * 17) % 50 }, (_, r) => `| T${section}R${r} | ${text(r, 2)} | ${text(section + r, 6 + (r * 11) % 50)} |`);
parts.push(["| Row | Name | Description |", "| --- | --- | --- |", ...rows].join("\n") + "\n");
if (section % 2 === 0) parts.push(`![Picture ${section}](img${section}.svg)\n`);
if (section % 3 === 0) parts.push("```python\nx = 1\ny = 2\n```\n");
parts.push(`- item ${section} one\n- item ${section} two\n`);
}
return parts.join("\n");
}
await runSmoke("editor/scrollStability", async ({ page }) => {
await mockTauri(page, {
state: { source: largeDocument() },
commands: test => {
const svg = (width, height) => btoa(`<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}"><rect width="100%" height="100%" fill="#336"/></svg>`);
const files = { "notes/large.md": test.state.source };
for (let section = 0; section < 10; section += 2) files[`notes/img${section}.svg`] = svg(1400, 700 + section * 60);
const workspace = test.workspace({ root: "C:/smoke-workspace", files });
return {
...workspace,
workspace_read_data_url: ({ rel }) => {
if (!workspace.files.has(rel)) throw new Error("missing image");
return "data:image/svg+xml;base64," + workspace.files.get(rel);
},
};
},
});
await page.setViewportSize({ width: 1440, height: 1000 });
/** Wheel over the view. After each tick lands, the text must be where the tick put it. Returns the ticks where the text moved by itself, and the document heights. */
async function wheel(selector, delta, ticks) {
const box = await page.locator(selector).boundingBox();
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
await page.evaluate(selector => {
const scroller = document.querySelector(selector);
const unique = /^s*(Td+Rd+|Pd+.d+|Short line d+|item d+ (?:one|two)|Section d+)/;
const keyOf = element => unique.exec(element.textContent || "")?.[1] ?? "";
const items = () => [...scroller.querySelectorAll(".cm-line, tr, .reading p, .reading h2, .reading li")];
const frame = () => new Promise(resolve => requestAnimationFrame(resolve));
const atEdge = () => scroller.scrollTop <= 0 || scroller.scrollTop + scroller.clientHeight >= scroller.scrollHeight - 2;
let tracked = null;
window.__scroll = {
jumps: [], heights: [],
before(delta) {
const area = scroller.getBoundingClientRect(), margin = Math.abs(delta) + 60;
const element = items().find(item => { const rect = item.getBoundingClientRect(); return rect.height > 0 && rect.top >= area.top + margin && rect.top <= area.bottom - margin && keyOf(item); });
tracked = element ? { element, key: keyOf(element), top: element.getBoundingClientRect().top, delta, scrollTop: scroller.scrollTop } : null;
},
// A tick can land some frames later on a busy computer. Wait for it, then for the layout passes of the editor.
async after() {
for (let waited = 0; tracked && scroller.scrollTop === tracked.scrollTop && waited < 60; waited++) await frame();
for (let settled = 0; settled < 3; settled++) await frame();
this.heights.push(scroller.scrollHeight);
if (atEdge()) return true;
if (!tracked) return false;
const element = tracked.element.isConnected ? tracked.element : items().find(item => keyOf(item) === tracked.key);
if (!element) this.jumps.push(`${tracked.key} left the view`);
else {
const moved = Math.round(element.getBoundingClientRect().top - (tracked.top - tracked.delta));
if (Math.abs(moved) > 4) this.jumps.push(`${tracked.key} moved ${moved}`);
}
return false;
},
};
}, selector);
for (let tick = 0; tick < ticks; tick++) {
await page.evaluate(delta => window.__scroll.before(delta), delta);
await page.mouse.wheel(0, delta);
if (await page.evaluate(() => window.__scroll.after()) && tick > 0) break;
}
return page.evaluate(() => ({ jumps: window.__scroll.jumps, heights: window.__scroll.heights }));
}
const jump = (selector, fraction) => page.evaluate(({ selector, fraction }) => { const scroller = document.querySelector(selector); scroller.scrollTop = scroller.scrollHeight * fraction; }, { selector, fraction });
await page.goto(smokeUrl);
await page.getByText(/smoke-workspace/).first().waitFor();
await page.keyboard.press("Control+p");
await page.getByRole("textbox", { name: "Find a file" }).fill("large.md");
await page.getByRole("dialog").getByRole("button").filter({ hasText: "large.md" }).first().click();
await page.locator(".cm-content").waitFor();
await page.waitForTimeout(400);
// Text that was not on screen yet: the heights are estimates until the first draw.
await jump(".cm-scroller", .6);
await page.waitForTimeout(300);
const first = await wheel(".cm-scroller", -200, 120);
assert.deepEqual(first.jumps, [], "Wheel up through new tables and images");
const spread = heights => Math.max(...heights) - Math.min(...heights);
// Line heights are estimates, but tables and images have their heights before the first draw.
assert.ok(spread(first.heights) < Math.max(...first.heights) * .05, `The document keeps about its height at the first draw: ${Math.min(...first.heights)} to ${Math.max(...first.heights)}`);
// Text that was drawn before: images and tables come back with their heights.
await jump(".cm-scroller", 0);
await page.waitForTimeout(200);
const down = await wheel(".cm-scroller", 400, 130);
assert.deepEqual(down.jumps, [], "Wheel down to the end");
const up = await wheel(".cm-scroller", -400, 130);
assert.deepEqual(up.jumps, [], "Wheel up to the start");
assert.ok(spread(up.heights) < 200, `The document keeps its height on the way back: ${Math.min(...up.heights)} to ${Math.max(...up.heights)}`);
// A short heading with the caret and a code block with the caret have another line height too.
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
const view = EditorView.findFromDOM(document.querySelector(".cm-content"));
const heading = view.state.doc.toString().indexOf("## Section 3");
view.dispatch({ selection: { anchor: heading + 3 }, scrollIntoView: true });
});
await page.waitForTimeout(300);
const caret = await wheel(".cm-scroller", 300, 25);
assert.deepEqual(caret.jumps, [], "Wheel down with the caret in a short heading");
assert.ok(spread(caret.heights) < 200, `The document keeps its height with the caret in a short heading: ${Math.min(...caret.heights)} to ${Math.max(...caret.heights)}`);
// Images in Write keep their space before they load.
const image = page.locator(".cm-content img[data-md-src]").first();
await page.evaluate(async () => {
const { EditorView } = await import("/node_modules/@codemirror/view/dist/index.js");
const view = EditorView.findFromDOM(document.querySelector(".cm-content"));
view.scrollDOM.scrollTop = view.lineBlockAt(view.state.doc.toString().indexOf("![Picture 0]")).top;
});
await image.waitFor();
assert.equal(await image.getAttribute("width"), "1400");
assert.equal(await image.getAttribute("height"), "700");
// Read shows the same document without virtual lines.
await chooseView(page, "Read");
await page.locator(".md-page > .reading").waitFor();
await page.waitForTimeout(300);
await jump(".md-page", .6);
await page.waitForTimeout(300);
const reading = await wheel(".md-page", -300, 60);
assert.deepEqual(reading.jumps, [], "Wheel up in Read");
assert.equal(await page.locator(".md-page img[data-md-src]").first().getAttribute("height"), "700", "Images in Read keep their space before they load");
}, { timeout: 30000 });