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
+7 -1
View File
@@ -16,6 +16,7 @@
import { documentHeadings } from "$lib/workspace/headingLinks";
import { editImageSource, imageSource } from "./imageSource";
import { markdownImages, documentBodyStart } from "$lib/workspace/noteHtml";
import { loadImageSize } from "$lib/workspace/imageSizes";
import { isMarkdownPath, isRemoteImage, resolveImageRel, imageFiles, hasFileDrag, imageInsertion, markdownTitle, pastedImageSource } from "$lib/workspace/media";
import { registerImageDropTarget } from "./workspaceImageDrop";
import { workspaceFileLink } from "./workspaceFileLink";
@@ -100,7 +101,12 @@
let decoded = source;
try { decoded = decodeURIComponent(source); } catch { /* Literal filename. */ }
for (const candidate of new Set([resolveImageRel(path, decoded), decoded.replace(/^\/+/, ""), decoded.split("/").pop()!])) {
try { urls.set(source, await workspaceReadDataUrl(candidate)); return; } catch { /* Try attachment location. */ }
try {
const url = await workspaceReadDataUrl(candidate);
await loadImageSize(url);
urls.set(source, url);
return;
} catch { /* Try attachment location. */ }
}
})();
loading.set(source, task);
+9
View File
@@ -5,6 +5,7 @@ import { attachTooltip } from "../ui/tooltip";
const tooltipCleanups = new WeakMap<HTMLElement, () => void>();
import type { ActionMenuItem } from "../ui/actionMenu";
import { showActionMenu, type MenuHandle } from "../ui/managedActionMenu";
import { imageSize, rememberImageSize } from "../workspace/imageSizes";
export type ImageActions = {
edit?: () => void;
@@ -56,6 +57,8 @@ function zoomImage(original: HTMLImageElement, trigger: HTMLButtonElement) {
viewport.className = "image-lightbox-viewport";
const image = original.cloneNode() as HTMLImageElement;
image.removeAttribute("loading");
image.removeAttribute("width");
image.removeAttribute("height");
image.draggable = false;
let scale = 0;
const status = document.createElement("span");
@@ -91,6 +94,12 @@ export function imageControls(root: HTMLElement, actions: ImageActions = {}, mea
const cleanup: (() => void)[] = [];
for (const image of root.querySelectorAll<HTMLImageElement>("img[data-md-src]")) {
if (image.closest(".md-image-frame")) continue;
// A remote image gives its size when it loads. The next view of this image keeps its space from the start.
const remember = () => rememberImageSize(image.src, image.naturalWidth, image.naturalHeight);
image.addEventListener("load", remember);
cleanup.push(() => image.removeEventListener("load", remember));
const known = !image.getAttribute("width") && imageSize(image.src);
if (known) { image.width = known.width; image.height = known.height; }
const frame = document.createElement("span");
frame.className = "md-image-frame";
frame.contentEditable = "false";
+2
View File
@@ -5,6 +5,7 @@ import { imageControls, type ImageActions } from "./imageControls";
import { editImageSource } from "./imageSource";
import { requestText } from "../workspace/dialogs.svelte";
import { isRemoteImage } from "../workspace/media";
import { estimatedImageHeight } from "../workspace/imageSizes";
import { actionIcon } from "../ui/actionIcons";
export type ImageContext = {
@@ -18,6 +19,7 @@ const cleanups = new WeakMap<HTMLElement, () => void>();
export class ImagePreview extends WidgetType {
constructor(readonly html: string, readonly source: string, readonly context: ImageContext, readonly editing = false, readonly block = true) { super(); }
eq(other: ImagePreview) { return this.html === other.html && this.source === other.source && this.editing === other.editing && this.block === other.block; }
get estimatedHeight() { return estimatedImageHeight(this.html); }
toDOM(view: EditorView) {
const dom = document.createElement(this.block ? "div" : "span");
dom.className = `reading writer-preview ${this.block ? "writer-image" : "writer-image-inline"}`;
+124 -13
View File
@@ -4,7 +4,7 @@ import { isMac } from "../ui/shortcuts";
/** The tooltip of a link in Write. A click with Ctrl, or Cmd on macOS, opens the link. */
const linkTooltip = () => tr("{modifier}+click to open link", { modifier: isMac() ? "⌘" : "Ctrl" });
import { EditorSelection, StateEffect, StateField, type EditorState, type Range } from "@codemirror/state";
import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet } from "@codemirror/view";
import { Decoration, EditorView, ViewPlugin, WidgetType, type DecorationSet, type ViewUpdate } from "@codemirror/view";
import { syntaxTree, foldedRanges, foldEffect, unfoldEffect } from "@codemirror/language";
import { renderMarkdownSections } from "../workspace/noteHtml";
import { renderDiagrams } from "../workspace/diagrams";
@@ -22,9 +22,34 @@ import { listLabels } from "./markdownLists";
import { activeTableFormulas } from "../formulas/index.ts";
const previewFormulas = new WeakMap<HTMLElement, unknown>();
const previewHtml = new WeakMap<HTMLElement, string>();
export const refreshImages = StateEffect.define<void>();
const imageCleanups = new WeakMap<HTMLElement, () => void>();
/**
* CodeMirror reads the line height of the document from the first short line that holds only plain text.
* A different height makes it estimate all heights again, and the view then jumps to other text.
* A mark span keeps a line with a different height out of that reading.
*/
const otherLineHeight = Decoration.mark({ class: "writer-line-text" });
// A resize observer records the height of a preview without a CodeMirror measure request.
// A request from toDOM restarts the layout loop of CodeMirror, and a loop that restarts too often does not restore the scroll position.
const previewHeights = new WeakMap<Element, { value: number }>();
let previewSizes: ResizeObserver | undefined;
function watchPreviewHeight(dom: HTMLElement, height: { value: number }) {
previewSizes ??= new ResizeObserver(entries => {
for (const { target } of entries) {
const holder = previewHeights.get(target);
if (holder && target.isConnected) holder.value = (target as HTMLElement).offsetHeight;
}
});
const known = previewHeights.get(dom);
if (known && known !== height) height.value = known.value;
previewHeights.set(dom, height);
previewSizes.observe(dom);
}
const linkTooltips = ViewPlugin.define(view => {
const attached = new Map<HTMLElement, () => void>();
const refresh = () => {
@@ -119,23 +144,35 @@ class ListLabel extends WidgetType {
ignoreEvent() { return false; }
}
/**
* The heights of previews, by their HTML, from a layout outside the editor. CodeMirror draws only the lines near the view.
* Without a height, a large table counts as one line until its first draw. The document then grows by thousands of pixels
* at one time, the scrollbar moves, and the layout loop of CodeMirror can stop before it restores the scroll position.
*/
const measuredHeights = new Map<string, { width: number; height: number }>();
const maxMeasuredHeights = 1000;
class Preview extends WidgetType {
readonly formulas = activeTableFormulas();
constructor(readonly html: string, readonly source: string, readonly actions: TableContextActions, readonly sourceVisible = false, readonly height = { value: -1 }) { super(); }
get estimatedHeight() { return this.height.value; }
eq(other: Preview) { return other.formulas === this.formulas && other.html === this.html && other.source === this.source && other.sourceVisible === this.sourceVisible; }
measure(dom: HTMLElement, view: EditorView) {
view.requestMeasure({ key: this.height, read: () => dom.offsetHeight, write: height => { this.height.value = height; } });
readonly estimate: number;
constructor(readonly html: string, readonly source: string, readonly actions: TableContextActions, readonly sourceVisible = false, readonly height = { value: -1 }) {
super();
this.estimate = measuredHeights.get(html)?.height ?? -1;
}
updateDOM(dom: HTMLElement, view: EditorView) {
if (previewFormulas.get(dom) !== this.formulas || tableEditors.get(dom)?.source !== this.source) return false;
this.measure(dom, view);
get estimatedHeight() { return this.height.value >= 0 ? this.height.value : this.estimate; }
// A new estimate must reach the height map of CodeMirror. updateDOM keeps the drawn table.
eq(other: Preview) { return other.formulas === this.formulas && other.html === this.html && other.source === this.source && other.sourceVisible === this.sourceVisible && other.estimate === this.estimate; }
updateDOM(dom: HTMLElement) {
const table = tableEditors.get(dom);
if (previewFormulas.get(dom) !== this.formulas || (table ? table.source !== this.source : previewHtml.get(dom) !== this.html)) return false;
watchPreviewHeight(dom, this.height);
return true;
}
destroy(dom: HTMLElement) { tableEditors.get(dom)?.destroy(); imageCleanups.get(dom)?.(); }
destroy(dom: HTMLElement) { previewSizes?.unobserve(dom); tableEditors.get(dom)?.destroy(); imageCleanups.get(dom)?.(); }
toDOM(view: EditorView) {
const dom = document.createElement("div");
previewFormulas.set(dom, this.formulas);
previewHtml.set(dom, this.html);
dom.className = "reading writer-preview";
dom.innerHTML = this.html;
// Widgets handle their own events, so CodeMirror's link handler cannot run.
@@ -153,7 +190,7 @@ class Preview extends WidgetType {
}, { capture: true });
tableControls(dom, view, this.source, this.actions);
imageCleanups.set(dom, imageControls(dom, {}, () => { if (dom.isConnected) view.requestMeasure(); }));
this.measure(dom, view);
watchPreviewHeight(dom, this.height);
dom.querySelectorAll("button.rs-fence-copy").forEach(button => button.remove());
dom.addEventListener("mousedown", event => {
if (event.target instanceof Element && event.target.closest(".writer-table, .table-footer")) return;
@@ -174,6 +211,45 @@ class Preview extends WidgetType {
ignoreEvent() { return true; }
}
function textColumnWidth(view: EditorView) {
const style = getComputedStyle(view.contentDOM);
return view.contentDOM.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight);
}
/** Measure previews in one layout pass, in a hidden copy of the text column. A copy has the table frame and footer, but not the table controls. */
function measurePreviews(view: EditorView, widgets: Preview[], width: number) {
const host = document.createElement("div");
host.className = view.contentDOM.className;
host.setAttribute("aria-hidden", "true");
host.style.cssText = "position:absolute;inset:0 0 auto 0;height:0;min-height:0;padding-block:0;overflow:hidden;visibility:hidden;pointer-events:none";
const footer = document.createElement("div");
footer.className = "table-footer";
const tools = activeTableFormulas()?.createFormulaTools(() => {}, () => {});
if (tools) footer.append(tools.formulaTools);
const copies = widgets.map(widget => {
const copy = document.createElement("div");
copy.className = "reading writer-preview";
copy.innerHTML = widget.html;
const scroll = copy.querySelector(".md-table-scroll");
if (scroll && parseMarkdownTable(widget.source)) {
const frame = document.createElement("div");
frame.className = "writer-table";
scroll.before(frame);
frame.append(scroll);
frame.after(footer.cloneNode(true));
}
host.append(copy);
return copy;
});
view.scrollDOM.append(host);
if (measuredHeights.size + widgets.length > maxMeasuredHeights) measuredHeights.clear();
copies.forEach((copy, index) => {
measuredHeights.set(widgets[index].html, { width, height: copy.offsetHeight });
widgets[index].height.value = -1;
});
host.remove();
}
export function liveMarkdown(urls: Map<string, string>, actions: TableContextActions = {}, images: ImageContext = {}) {
const selecting = StateEffect.define<boolean>();
const mouseSelecting = StateField.define({
@@ -256,7 +332,10 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
const hidden = (from: number, to: number) => hiddenBlocks.some(block => block.from <= from && block.to >= to);
for (let number = 1; number <= state.doc.lines; number++) {
const line = state.doc.line(number);
if (!line.text.trim() && !hidden(line.from, line.to)) ranges.push(Decoration.line({ class: "writer-blank" }).range(line.from));
if (!line.text.trim() && !hidden(line.from, line.to)) {
ranges.push(Decoration.line({ class: "writer-blank" }).range(line.from));
if (line.length) ranges.push(otherLineHeight.range(line.from, line.to));
}
}
const replace = (from: number, to: number) => { if (to > from) ranges.push(Decoration.replace({ atomic: true }).range(from, to)); };
const mark = (from: number, to: number, className: string) => { if (to > from) ranges.push(Decoration.mark({ class: className }).range(from, to)); };
@@ -274,6 +353,7 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
for (let number = first.number; number <= last.number; number++) {
const line = state.doc.line(number);
ranges.push(Decoration.line({ class: editingCode ? "writer-code-source" : `writer-code-line${number === first.number ? " writer-code-first" : ""}${number === last.number ? " writer-code-last" : ""}${fenced && (number === first.number || (closed && number === last.number)) ? " writer-code-fence" : ""}`, attributes: { spellcheck: "false" } }).range(line.from));
if (line.length) ranges.push(otherLineHeight.range(line.from, line.to));
}
return false;
}
@@ -283,6 +363,7 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
const pendingList = node.name === "SetextHeading2" && state.doc.lineAt(node.to).text.trim() === "-";
if (/^(?:ATX|Setext)Heading[1-6]$/.test(node.name) && !pendingList) {
ranges.push(Decoration.line({ class: `writer-heading writer-h${node.name.at(-1)}` }).range(line.from));
if (line.length) ranges.push(otherLineHeight.range(line.from, line.to));
}
if (node.name === "InlineCode") codeRanges.push({ from: node.from, to: node.to });
if (node.name === "TaskMarker") {
@@ -366,6 +447,36 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
filter: (_from, _to, decoration) => decoration.spec.atomic === true,
}))],
});
// Give each preview that is not drawn a height, after the document opens, changes, or gets another width.
const previewMeasuring = ViewPlugin.fromClass(class {
frame = 0;
width = -1;
constructor(readonly view: EditorView) { this.schedule(); }
update(update: ViewUpdate) {
if (update.geometryChanged || update.startState.field(decorations) !== update.state.field(decorations)) this.schedule();
}
schedule() {
this.frame ||= requestAnimationFrame(() => { this.frame = 0; this.measure(); });
}
measure() {
const { view } = this, width = textColumnWidth(view);
// The editor has no width while another view or tab covers it.
if (width < 50) return;
const resized = Math.abs(width - this.width) > 1;
this.width = width;
const { from: drawnFrom, to: drawnTo } = view.viewport;
const widgets: Preview[] = [];
view.state.field(decorations).between(0, view.state.doc.length, (from, to, decoration) => {
const widget = decoration.spec.widget;
if (!(widget instanceof Preview) || (from < drawnTo && to > drawnFrom)) return;
if ((resized || widget.height.value < 0) && measuredHeights.get(widget.html)?.width !== width) widgets.push(widget);
});
if (!widgets.length) return;
measurePreviews(view, widgets, width);
view.dispatch({ effects: refreshImages.of() });
}
destroy() { cancelAnimationFrame(this.frame); }
});
const mousePreview = ViewPlugin.define(view => {
const finish = () => {
if (!view.state.field(mouseSelecting)) return;
@@ -400,6 +511,6 @@ export function liveMarkdown(urls: Map<string, string>, actions: TableContextAct
window.removeEventListener("blur", finish);
} };
});
return [imageSource, linkTooltips, bodyFocused, mouseSelecting, decorations, mousePreview, syncBodyFocus,
return [imageSource, linkTooltips, bodyFocused, mouseSelecting, decorations, previewMeasuring, mousePreview, syncBodyFocus,
EditorView.focusChangeEffect.of((_state, focusing) => focusBody.of(focusing))];
}
+4 -1
View File
@@ -4,6 +4,7 @@
import { tick, type Snippet } from "svelte";
import { workspaceReadDataUrl } from "$lib/workspace/api";
import { markdownImages, renderMarkdownHtml, renderMarkdownSections, type MarkdownSection } from "$lib/workspace/noteHtml";
import { loadImageSize } from "$lib/workspace/imageSizes";
import { renderDiagrams } from "$lib/workspace/diagrams";
import { isRemoteImage, resolveImageRel, markdownTitle } from "$lib/workspace/media";
import { imageControls } from "$lib/editor/imageControls";
@@ -55,7 +56,9 @@
const base = normalized.split("/").pop() ?? path;
for (const candidate of new Set([primary, normalized, base])) {
try {
urls.set(source, await workspaceReadDataUrl(candidate));
const url = await workspaceReadDataUrl(candidate);
await loadImageSize(url);
urls.set(source, url);
return;
} catch { /* Try the workspace-relative attachment next. */ }
}
+44
View File
@@ -0,0 +1,44 @@
/**
* The natural sizes of the images that the app has loaded. The views use them to keep the space of an image before it
* loads. Without this space the text moves when an image loads, and each new height starts a layout pass of the editor.
*/
const sizes = new Map<string, { width: number; height: number }>();
// A data URL can hold megabytes. The key keeps the map from holding the image data.
function key(url: string) {
if (url.length <= 256) return url;
const middle = url.length >> 1;
return `${url.length}:${url.slice(middle, middle + 64)}`;
}
export function imageSize(url: string) {
return sizes.get(key(url));
}
export function rememberImageSize(url: string, width: number, height: number) {
if (width > 0 && height > 0) sizes.set(key(url), { width, height });
}
/** Read the size of an image that the app holds as data. A remote image gives its size when it loads in a view. */
export function loadImageSize(url: string): Promise<void> {
if (!url.startsWith("data:image/") || imageSize(url)) return Promise.resolve();
return new Promise(resolve => {
const image = new Image();
image.onload = () => { rememberImageSize(url, image.naturalWidth, image.naturalHeight); resolve(); };
image.onerror = () => resolve();
image.src = url;
});
}
/** The width of the text column at its largest. It gives an estimate before the editor can measure an image. */
const columnWidth = 740;
/** The margins of an image frame, from `.md-image-frame`. */
const frameMargins = 45;
/** The estimated height of an image in Write, from the size attributes of its HTML. A negative value means that the size is not known. */
export function estimatedImageHeight(html: string) {
const match = /\bwidth="(\d+)" height="(\d+)"/.exec(html);
if (!match) return -1;
const width = Number(match[1]), height = Number(match[2]);
return Math.round(height * Math.min(1, columnWidth / width)) + frameMargins;
}
+3 -1
View File
@@ -5,6 +5,7 @@ import { inlineMathEnd } from "./inlineMath.ts";
import { activeTableFormulas } from "../formulas/index.ts";
import { hasTableDelimiter } from "../editor/markdownTable.ts";
import { footnotes, renderFootnotes, type FootnoteEnvironment } from "../editor/footnotes.ts";
import { imageSize } from "./imageSizes.ts";
const markdown = new MarkdownIt({ html: false, linkify: true, breaks: false });
markdown.use(footnotes);
@@ -162,7 +163,8 @@ markdown.renderer.rules.image = (tokens, index, _options, env, renderer) => {
const alt = renderer.renderInlineAsText(token.children || [], markdown.options, env);
// Only app-resolved image data or HTTP(S) URLs become image sources.
if (!/^(?:https?:\/\/|data:image\/)/i.test(resolved)) return `<span class="missing-image" data-md-src="${escapeHtml(original)}" data-md-kind="${token.attrGet("data-md-kind") === "wiki" ? "wiki" : "md"}" alt="${escapeHtml(alt)}">Image unavailable: ${escapeHtml(alt || original)}</span>`;
return `<img src="${escapeHtml(resolved)}" alt="${escapeHtml(alt)}" data-md-src="${escapeHtml(original)}" data-md-kind="${token.attrGet("data-md-kind") === "wiki" ? "wiki" : "md"}" loading="lazy">`;
const size = imageSize(resolved);
return `<img src="${escapeHtml(resolved)}" alt="${escapeHtml(alt)}" data-md-src="${escapeHtml(original)}" data-md-kind="${token.attrGet("data-md-kind") === "wiki" ? "wiki" : "md"}"${size ? ` width="${size.width}" height="${size.height}"` : ""} loading="lazy">`;
};
markdown.renderer.rules.table_open = () => '<div class="md-table-scroll"><table>\n';
markdown.renderer.rules.table_close = () => '</table></div>\n';