diff --git a/src/lib/editor/DocumentEditor.svelte b/src/lib/editor/DocumentEditor.svelte index 3de8de9..e428ac4 100644 --- a/src/lib/editor/DocumentEditor.svelte +++ b/src/lib/editor/DocumentEditor.svelte @@ -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); diff --git a/src/lib/editor/imageControls.ts b/src/lib/editor/imageControls.ts index 0100ff7..e5fb617 100644 --- a/src/lib/editor/imageControls.ts +++ b/src/lib/editor/imageControls.ts @@ -5,6 +5,7 @@ import { attachTooltip } from "../ui/tooltip"; const tooltipCleanups = new WeakMap 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("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"; diff --git a/src/lib/editor/imagePreview.ts b/src/lib/editor/imagePreview.ts index 9e0790d..f914290 100644 --- a/src/lib/editor/imagePreview.ts +++ b/src/lib/editor/imagePreview.ts @@ -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 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"}`; diff --git a/src/lib/editor/liveMarkdown.ts b/src/lib/editor/liveMarkdown.ts index e77ea31..6a0c3e9 100644 --- a/src/lib/editor/liveMarkdown.ts +++ b/src/lib/editor/liveMarkdown.ts @@ -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(); +const previewHtml = new WeakMap(); export const refreshImages = StateEffect.define(); const imageCleanups = new WeakMap 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(); +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 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(); +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, actions: TableContextActions = {}, images: ImageContext = {}) { const selecting = StateEffect.define(); const mouseSelecting = StateField.define({ @@ -256,7 +332,10 @@ export function liveMarkdown(urls: Map, 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, 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, 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, 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, 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))]; } diff --git a/src/lib/layout/MarkdownView.svelte b/src/lib/layout/MarkdownView.svelte index 3e7fdb4..03101b9 100644 --- a/src/lib/layout/MarkdownView.svelte +++ b/src/lib/layout/MarkdownView.svelte @@ -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. */ } } diff --git a/src/lib/workspace/imageSizes.ts b/src/lib/workspace/imageSizes.ts new file mode 100644 index 0000000..9dcb0cb --- /dev/null +++ b/src/lib/workspace/imageSizes.ts @@ -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(); + +// 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 { + 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; +} diff --git a/src/lib/workspace/noteHtml.ts b/src/lib/workspace/noteHtml.ts index 3423dec..64ad639 100644 --- a/src/lib/workspace/noteHtml.ts +++ b/src/lib/workspace/noteHtml.ts @@ -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 `Image unavailable: ${escapeHtml(alt || original)}`; - return `${escapeHtml(alt)}`; + const size = imageSize(resolved); + return `${escapeHtml(alt)}`; }; markdown.renderer.rules.table_open = () => '
\n'; markdown.renderer.rules.table_close = () => '
\n'; diff --git a/tests/smoke/editor/scrollStability.smoke.mjs b/tests/smoke/editor/scrollStability.smoke.mjs new file mode 100644 index 0000000..710147b --- /dev/null +++ b/tests/smoke/editor/scrollStability.smoke.mjs @@ -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(``); + 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 }); diff --git a/tests/unit/editor/imageSizes.spec.ts b/tests/unit/editor/imageSizes.spec.ts new file mode 100644 index 0000000..cb8f61a --- /dev/null +++ b/tests/unit/editor/imageSizes.spec.ts @@ -0,0 +1,32 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { estimatedImageHeight, imageSize, rememberImageSize } from "../../../src/lib/workspace/imageSizes.ts"; +import { renderMarkdownHtml } from "../../../src/lib/workspace/noteHtml.ts"; + +test("a rendered image has size attributes only when its size is known", () => { + const unknown = "data:image/png;base64,AAAA"; + const known = "data:image/png;base64,BBBB"; + rememberImageSize(known, 1400, 700); + const urls = new Map([["a.png", unknown], ["b.png", known]]); + assert.doesNotMatch(renderMarkdownHtml("![a](a.png)", urls), /width=/); + assert.match(renderMarkdownHtml("![b](b.png)", urls), /width="1400" height="700"/); +}); + +test("a large data URL keeps its size without the image data as the key", () => { + const url = `data:image/png;base64,${"A".repeat(5000)}${"B".repeat(100)}${"C".repeat(5000)}`; + const other = `data:image/png;base64,${"A".repeat(5000)}${"D".repeat(100)}${"C".repeat(5000)}`; + rememberImageSize(url, 10, 20); + assert.deepEqual(imageSize(url), { width: 10, height: 20 }); + assert.equal(imageSize(other), undefined); +}); + +test("an image without a real size stays unknown", () => { + rememberImageSize("data:image/svg+xml;base64,AAAA", 0, 0); + assert.equal(imageSize("data:image/svg+xml;base64,AAAA"), undefined); +}); + +test("the estimate scales a wide image to the text column and keeps a small image", () => { + assert.equal(estimatedImageHeight(''), -1); + assert.equal(estimatedImageHeight(''), 370 + 45); + assert.equal(estimatedImageHeight(''), 50 + 45); +});