From 124fb578be66298e5a00783cfed9abb9b0966563 Mon Sep 17 00:00:00 2001 From: "Pierre N." Date: Mon, 23 Nov 2026 17:01:21 +0700 Subject: [PATCH] fix(docx): past the scroll cap, the pages move once and as far as the scroll A document longer than a browser lets a box scroll (12,000,000 px) mapped the scroll position to the place shown by a factor. Every scroll then went that factor too far: the wheel and Page Down skipped pages, the caret brought into view by the browser overshot, and a native scroll moved the pages twice (by the browser, then by the next render). The pages now stay in the scrolled content, drawn an offset higher than they are in the document (ScrollMap, src/react/docx/longscroll.ts): - a step (wheel, keys, the caret, a selection dragged past an edge) leaves the offset alone: the browser moves the pages by itself, pixel for pixel; - a jump to where no page is drawn (the scrollbar's thumb, Home, End) goes where the thumb says; a long scroll that ends on a page that is drawn is the browser's own (focus, scrollIntoView) and is kept pixel for pixel; - at rest, or when the box reaches an end of its range before the document does, the box is put where its thumb belongs and the offset changes by as much, in one frame: nothing moves on screen. A document that grows past the cap while it loads stays where the reader is, and another zoom keeps the place. Fixes #50 Co-Authored-By: Claude Fable 5.2 --- docs/development.md | 3 + e2e/docx-longscroll.spec.ts | 277 +++++++++++++++++++++++++++++++++++ src/react/docx/DocxView.tsx | 37 ++--- src/react/docx/longscroll.ts | 258 ++++++++++++++++++++++++++++++++ test/docx-longscroll.test.ts | 259 ++++++++++++++++++++++++++++++++ 5 files changed, 816 insertions(+), 18 deletions(-) create mode 100644 e2e/docx-longscroll.spec.ts create mode 100644 src/react/docx/longscroll.ts create mode 100644 test/docx-longscroll.test.ts diff --git a/docs/development.md b/docs/development.md index 747b960..1080cac 100644 --- a/docs/development.md +++ b/docs/development.md @@ -44,6 +44,8 @@ src/collab real-time collaboration (hub, session, per-format adapters) `DocxView` measures the blocks off screen in time slices (`src/react/docx/measure.ts`: a block's height, where a paragraph's lines and a table's rows are), `paginate()` cuts them into pages (`paginate.ts`: pure, lines and rows given, keep rules; unit tests in `test/docx-paginate.test.ts`) and only the pages in view render. The browser breaks the lines; the offset each line starts at is read (`lineStarts`) only for the paragraphs a page in view or an edit cuts. A paragraph split across pages renders as one element per part, each with the paragraph's `data-pa` address and the offsets it holds (`data-from`, `data-to`): `paraEl()` / `posFromDom()` / `domFromPos()` in `src/react/edit/input.ts` map DOM places to paragraph offsets over the parts, so the caret, selections, find and comments need nothing else. Header rows repeated on the following pages of a table are copies without an address (`.de-head-copy`). +A document longer than a browser lets a box scroll (12,000,000 px) is scrolled through `ScrollMap` (`src/react/docx/longscroll.ts`, unit tests in `test/docx-longscroll.test.ts`): the place shown is the scroll position plus an offset the pages are drawn by. A step of the reader or of the browser leaves the offset alone, so the browser moves the pages by itself; a jump of the scrollbar's thumb sets it; at rest the box is put where its thumb belongs, pages and scroll position in one frame. + ## Browser tests `e2e/*.spec.ts` drive a fixture app (`e2e/app`, served by Vite with `vite.e2e.config.ts`) in headless Chromium through `playwright-core`, one browser and server per file (`e2e/harness.ts`). @@ -56,6 +58,7 @@ The app reads `DocViewer` props from the query string (`?src=samples/sample.docx | `docx.spec.ts` | typing, formatting, styles, lists, colors, fonts, links, tables, images, find & replace, undo | | `docx-page.spec.ts` | page setup: size, orientation, margins, columns; refused values; numbers typed in a locale | | `docx-split.spec.ts` | paragraphs and tables split across pages: layout, caret, editing, header rows | +| `docx-longscroll.spec.ts` | a document past the scroll cap: wheel, Page Down, the caret, the last page by steps, the box at rest, zoom | | `docx-hf.spec.ts` | headers and footers: page numbers, text, different first page, saved and undone | | `docx-table.spec.ts` | table editing: cell selection, merges, colors, borders, alignment, column widths | | `docx-tabs.spec.ts` | tab stops: left / center / right / decimal, leaders, stops of a style, absolute position tabs, typing, HTML export | diff --git a/e2e/docx-longscroll.spec.ts b/e2e/docx-longscroll.spec.ts new file mode 100644 index 0000000..0710e1f --- /dev/null +++ b/e2e/docx-longscroll.spec.ts @@ -0,0 +1,277 @@ +import { expect, test } from 'bun:test' +import { parasToDocx } from '../src/core/convert' +import { BlobSource } from '../src/core/source' +import { ZipArchive } from '../src/core/zip' +import { rebuildZip } from '../src/core/zipwrite' +import { useBrowser, viewer, type Params, type Viewer } from './harness' + +// A document longer than the browser lets a box scroll (https://github.com/p10node/office-engine/issues/50): what the +// reader or the browser scrolls moves the pages once and as far as it goes, and every page is still reached. + +useBrowser() + +const PAGES = 200 +/** the page that holds lines of text, for the caret */ +const LINES_PAGE = 100 +const LINES = 60 + +/** helpers of the page, set by `open` */ +interface Long { + sc(): HTMLElement + frames(n: number): Promise + /** the place of the document at the top of the box, counted from the first page, read from the pages as they are drawn */ + place(): number + /** how far the last page ends above the bottom of the box (24: the end of the document) */ + end(): number | null +} +declare const L: Long + +let file: Promise | undefined +/** 200 pages, each well over 100,000 px tall (two to three times what a box scrolls over); page 100 holds 60 lines */ +function longDocx() { + return (file ??= (async () => { + const paras = Array.from({ length: PAGES }, (_, i) => [ + { runs: [{ text: `Page ${i + 1}` }] }, + ...(i + 1 === LINES_PAGE ? Array.from({ length: LINES }, (_, k) => ({ runs: [{ text: `Line ${k + 1}` }] })) : []), + ]).flat() + const blob = await parasToDocx(paras) + const zip = await ZipArchive.open(new BlobSource(blob)) + const xml = (await zip.text('word/document.xml')) + .replace(/]*\/>/, '') + .replaceAll('Page ', 'Page ') + return [...new Uint8Array(await (await rebuildZip(zip, new Map([['word/document.xml', xml]]), blob.type)).arrayBuffer())] + })()) +} + +async function open(params: Params = {}): Promise { + const v = await viewer({ onSave: true, ...params }) + await v.page.evaluate((bytes) => window.__setProps({ src: new Uint8Array(bytes), name: 'long.docx' }), await longDocx()) + await v.ready('docx') + await v.page.waitForFunction((n) => document.querySelector('.de-bar')?.textContent?.includes(`of ${n}`), PAGES) + await v.page.evaluate((pages) => { + const sc = () => document.querySelector('.de-scroll')! + const all = () => [...document.querySelectorAll('.de-page')] + ;(window as unknown as { L: Long }).L = { + sc, + frames: async (n) => { + for (let i = 0; i < n; i++) await new Promise((r) => requestAnimationFrame(r)) + }, + place() { + const box = sc().getBoundingClientRect() + // the first page that ends below the top of the box (16: the gap between two pages) + const p = all().find((x) => x.getBoundingClientRect().bottom + 16 > box.top) + if (!p) return NaN + const r = p.getBoundingClientRect() + return (Number(p.dataset.page) - 1) * (r.height + 16) + box.top - r.top + }, + end() { + const p = all().find((x) => Number(x.dataset.page) === pages) + return p ? sc().getBoundingClientRect().bottom - p.getBoundingClientRect().bottom : null + }, + } + }, PAGES) + // the document is longer than its box scrolls over + expect(await v.page.evaluate(() => L.sc().scrollHeight)).toBeLessThanOrEqual(12_000_000) + return v +} + +/** the thumb dragged to `top`: the place shown there, once its page is drawn */ +async function jump(v: Viewer, top: number): Promise { + await v.page.evaluate((t) => void (L.sc().scrollTop = t), top) + await v.page.waitForFunction(() => { + const box = L.sc().getBoundingClientRect() + return [...document.querySelectorAll('.de-page')].some((p) => p.getBoundingClientRect().top < box.bottom && p.getBoundingClientRect().bottom > box.top) + }) + await v.page.waitForTimeout(400) + return v.page.evaluate(() => L.place()) +} + +/** by the find bar to the page of lines: a place the view itself asks for */ +async function findLine20(v: Viewer) { + await v.btn('Find & replace').click() + const input = v.page.locator('.de-find input[aria-label="Find"]') + await input.fill('Line 20') + await input.press('Enter') + await v.page.waitForFunction(() => { + const box = L.sc().getBoundingClientRect() + const p = [...document.querySelectorAll('.de-page [data-pa]')].find((x) => x.textContent === 'Line 20')?.getBoundingClientRect() + return !!p && p.top >= box.top && p.bottom <= box.bottom + }) + await input.press('Escape') +} + +test('past the cap, the wheel moves the pages as far as it scrolls, and the box at rest is put where its thumb belongs', async () => { + const v = await open() + const y0 = await jump(v, 5_000_000) + // (a jump is not pixel for pixel: the document is more than twice as long as the box's range) + expect(y0).toBeGreaterThan(9_000_000) + const box = (await v.page.locator('.de-scroll').boundingBox())! + await v.page.mouse.move(box.x + box.width / 2, box.y + box.height / 2) + await v.page.mouse.wheel(0, 300) + await v.page.waitForFunction((y) => Math.abs(L.place() - y - 300) < 1.5, y0) + // at rest: the box is scrolled back to where its thumb belongs for the place it shows (less far than the step), and nothing moved on screen + await v.page.waitForFunction(() => L.sc().scrollTop < 5_000_290) + await v.page.waitForTimeout(300) + const rest = await v.page.evaluate(() => ({ y: L.place(), top: L.sc().scrollTop })) + expect(Math.abs(rest.y - y0 - 300)).toBeLessThan(1.5) + expect(rest.top).toBeGreaterThan(5_000_050) + expect(rest.top).toBeLessThan(5_000_290) + // and back, by the wheel again + await v.page.mouse.wheel(0, -300) + await v.page.waitForFunction((y) => Math.abs(L.place() - y) < 1.5, y0) + expect(v.errors).toEqual([]) +}) + +test('past the cap, Page Down moves by one box, not by several', async () => { + const v = await open() + const y0 = await jump(v, 5_000_000) + const h = await v.page.evaluate(() => L.sc().clientHeight) + await v.page.locator('.de-scroll').focus() + await v.page.keyboard.press('PageDown') + await v.page.waitForFunction((y) => L.place() - y > 100, y0) + await v.page.waitForTimeout(600) + const moved = (await v.page.evaluate(() => L.place())) - y0 + expect(moved).toBeGreaterThan(h * 0.5) + expect(moved).toBeLessThanOrEqual(h + 1) + expect(v.errors).toEqual([]) +}) + +test('past the cap, steps that reach the end of the box before the end of the document go on to the last page', async () => { + const v = await open() + // just before the last 1,000,000 px, which scroll pixel for pixel: the document has more left than the box + const max = await v.page.evaluate(() => L.sc().scrollHeight - L.sc().clientHeight) + const y0 = await jump(v, max - 1_050_000) + const out = await v.page.evaluate(async () => { + const s = L.sc() + let y = L.place() + let worst = 0 + let settled = 0 + let steps = 0 + for (; steps < 2000; steps++) { + const top = s.scrollTop + s.scrollTop = top + 1900 + const d = s.scrollTop - top + if (d === 0) break + await L.frames(1) + // the box was put back where it has room: only when it could not go on + if (s.scrollTop < top) settled++ + // (a step past a whole box can end below the pages drawn so far: the next one is drawn a frame later) + if (Number.isNaN(L.place())) await L.frames(2) + const now = L.place() + worst = Math.max(worst, Math.abs(now - y - d)) + y = now + } + await L.frames(2) + return { y, worst, settled, steps, end: L.end(), top: s.scrollTop, max: s.scrollHeight - s.clientHeight } + }) + // every step moved the document as far as the box, also the ones at which the box was put back + expect(out.worst).toBeLessThan(1.5) + expect(out.settled).toBeGreaterThan(0) + expect(out.settled).toBeLessThan(10) + // more of the document was scrolled than the box had left + expect(out.y - y0).toBeGreaterThan(1_100_000) + // the end of the last page, 24 px above the bottom of the box + expect(Math.abs(out.end! - 24)).toBeLessThan(1.5) + expect(Math.abs(out.top - out.max)).toBeLessThan(1.5) + expect(await v.page.locator(`.de-page[data-page="${PAGES}"]`).textContent()).toContain(`Page ${PAGES}`) + expect(v.errors).toEqual([]) +}) + +test('past the cap, the caret moved below the box by the arrow keys is followed line by line', async () => { + const v = await open({ editable: true }) + await findLine20(v) + // the last line that is whole in the box + const start = await v.page.evaluate(() => { + const box = L.sc().getBoundingClientRect() + const lines = [...document.querySelectorAll('.de-page [data-pa]')].filter((x) => /^Line \d+$/.test(x.textContent ?? '')) + const whole = lines.filter((x) => x.getBoundingClientRect().bottom <= box.bottom) + return { n: Number(whole.at(-1)!.textContent!.slice(5)), lineH: lines[1].getBoundingClientRect().top - lines[0].getBoundingClientRect().top } + }) + expect(start.n).toBeGreaterThan(20) + expect(start.n).toBeLessThan(LINES - 12) + // the caret at the end of that line, by a click to the right of its text + const at = await v.page.evaluate((n) => { + const line = [...document.querySelectorAll('.de-page [data-pa]')].find((x) => x.textContent === `Line ${n}`)! + const r = line.getBoundingClientRect() + return { x: r.left + 300, y: r.top + r.height / 2 } + }, start.n) + await v.page.mouse.click(at.x, at.y) + await v.page.waitForFunction((t) => (getSelection()?.anchorNode as Node | null)?.parentElement?.closest('[data-pa]')?.textContent === t, `Line ${start.n}`) + const y0 = await v.page.evaluate(() => L.place()) + let y = y0 + for (let k = 1; k <= 10; k++) { + await v.page.keyboard.press('ArrowDown') + await v.page.waitForTimeout(60) + const now = await v.page.evaluate(() => { + const box = L.sc().getBoundingClientRect() + const line = (getSelection()!.anchorNode as Node).parentElement!.closest('[data-pa]')! + // the caret itself (the paragraph also has space after its text) + const r = getSelection()!.getRangeAt(0).getBoundingClientRect() + return { y: L.place(), text: line.textContent, h: r.height, above: r.top - box.top, below: box.bottom - r.bottom } + }) + // the caret is on the next line and in the box: scrolled to by no more than it took + expect(now.h).toBeGreaterThan(0) + expect(now.text).toBe(`Line ${start.n + k}`) + expect(now.above).toBeGreaterThanOrEqual(0) + expect(now.below).toBeGreaterThanOrEqual(-1) + expect(now.y - y).toBeGreaterThanOrEqual(0) + expect(now.y - y).toBeLessThan(start.lineH * 1.6) + y = now.y + } + // (the first line down may still have been in the box) + expect(y - y0).toBeGreaterThan(start.lineH * 7) + expect(y - y0).toBeLessThan(start.lineH * 10.5) + // at rest the box is put where its thumb belongs: the caret and the lines stay where they are + await v.page.waitForTimeout(500) + const rest = await v.page.evaluate(() => ({ y: L.place(), text: (getSelection()!.anchorNode as Node).parentElement!.closest('[data-pa]')!.textContent })) + expect(Math.abs(rest.y - y)).toBeLessThan(1.5) + expect(rest.text).toBe(`Line ${start.n + 10}`) + await v.page.keyboard.type('!') + await v.page.waitForFunction((t) => [...document.querySelectorAll('.de-page [data-pa]')].some((x) => x.textContent === t), `Line ${start.n + 10}!`) + expect(Math.abs((await v.page.evaluate(() => L.place())) - y)).toBeLessThan(start.lineH * 3) + expect(v.errors).toEqual([]) +}) + +test('past the cap, a long scroll the browser makes to something on a page that is drawn shows it', async () => { + const v = await open({ editable: true }) + await findLine20(v) + await v.page.waitForTimeout(400) + const y0 = await v.page.evaluate(() => L.place()) + // the first line of the page before, more than 100,000 px up: as a host's own scrollIntoView, or the browser for what takes the focus + const title = `.de-page[data-page="${LINES_PAGE - 1}"] [data-pa]` + await v.page.locator(title).first().waitFor({ state: 'attached' }) + await v.page.evaluate((sel) => document.querySelector(sel)!.scrollIntoView({ block: 'center' }), title) + await v.page.waitForFunction((y) => L.place() < y - 100_000, y0) + await v.page.waitForTimeout(500) + const shown = await v.page.evaluate((sel) => { + const box = L.sc().getBoundingClientRect() + const r = document.querySelector(sel)!.getBoundingClientRect() + return { text: document.querySelector(sel)!.textContent, mid: (r.top + r.bottom) / 2 - (box.top + box.bottom) / 2 } + }, title) + expect(shown.text).toBe(`Page ${LINES_PAGE - 1}`) + // in the middle of the box, also once the box has rested + expect(Math.abs(shown.mid)).toBeLessThan(2) + expect(v.errors).toEqual([]) +}) + +test('past the cap, another zoom shows the same page', async () => { + const v = await open() + const y0 = await jump(v, 6_000_000) + const page = async () => Number(/(\d+) of 200/.exec((await v.page.locator('.de-bar').textContent()) ?? '')?.[1]) + const n = await page() + expect(n).toBeGreaterThan(50) + const h0 = await v.page.evaluate(() => document.querySelector('.de-page')!.getBoundingClientRect().height) + await v.btn('Zoom out').click() + await v.page.waitForFunction((h) => document.querySelector('.de-page')!.getBoundingClientRect().height < h - 1, h0) + await v.page.waitForTimeout(400) + const h1 = await v.page.evaluate(() => document.querySelector('.de-page')!.getBoundingClientRect().height) + expect(await page()).toBe(n) + // as far down the shorter pages as it was down the taller ones + const y1 = await v.page.evaluate(() => L.place()) + expect(Math.abs(y1 / y0 - h1 / h0)).toBeLessThan(0.002) + await v.btn('Zoom in').click() + await v.page.waitForFunction((h) => document.querySelector('.de-page')!.getBoundingClientRect().height > h + 1, h1) + await v.page.waitForTimeout(400) + expect(await page()).toBe(n) + expect(v.errors).toEqual([]) +}) diff --git a/src/react/docx/DocxView.tsx b/src/react/docx/DocxView.tsx index 1fe6dbc..e28d5a6 100644 --- a/src/react/docx/DocxView.tsx +++ b/src/react/docx/DocxView.tsx @@ -4,7 +4,7 @@ import { DEFAULT_PAGE } from '../../core/docx/types' import { registerHost } from '../../collab/hosts' import { safeHref } from '../../core/url' import type { DocumentClient } from '../../core/worker/client' -import { claimFocus, lowerIndex, useForceUpdate, useIsoLayoutEffect, useScroll, useSize } from '../common/hooks' +import { claimFocus, lowerIndex, useForceUpdate, useIsoLayoutEffect, useSize } from '../common/hooks' import { useFileOps, useSelectAll, useViewer } from '../common/Slots' import { Status } from '../common/Status' import { ZoomControl, type Zoom } from '../common/ZoomControl' @@ -28,6 +28,7 @@ import { docxBodyHtml, docxToHtml, docxToMarkdown, docxToText, pictureData } fro import { BlockView, contextual, type RenderCtx } from './render' import { columnsOf, headOf, pageAt, pageHF, pagesOf, paginate, pieceOf, type Lines, type PageSlice } from './paginate' import { lineStarts, paraLines, tableLines } from './measure' +import { useLongScroll } from './longscroll' import { layoutTabs } from './tabs' import { formatCount, formatNumber, useStrings } from '../strings' import { docxFonts, docxPageFonts } from '../../core/fonts' @@ -96,7 +97,7 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp const [done, setDone] = useState<{ error?: string } | null>(null) const [zoom, setZoom] = useState(initialZoom) const [scrollRef, size] = useSize() - const scroll = useScroll(scrollRef) + const scroll = useLongScroll(scrollRef, '.de-page') const pagesRef = useRef(null) const [domSel, setDomSel] = useState([]) const editor = useMemo(() => new DocxEditor(client, st, bump), [client, st, bump]) @@ -225,18 +226,17 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp const totalH = acc + skeleton * (pageH * z + GAP) + PAD - GAP const spacerH = Math.min(totalH, MAX_SCROLL_PX) const maxLogicalY = Math.max(0, totalH - size.h) - const maxScrollY = Math.max(0, spacerH - size.h) - const scrollScale = maxScrollY > 0 ? Math.max(1, maxLogicalY / maxScrollY) : 1 - const scrollY = Math.min(maxLogicalY, scroll.y * scrollScale) - const scrollOffset = scrollY - scroll.y - const scrollToY = (y: number) => { - if (scrollRef.current) scrollRef.current.scrollTop = Math.max(0, Math.min(maxLogicalY, y)) / scrollScale - } - /** the logical position (in `tops`) of a physical `scrollTop` */ - const logicalY = (top: number) => Math.min(maxLogicalY, top * scrollScale) - const scrollByY = (delta: number) => { - if (scrollRef.current) scrollRef.current.scrollTop += delta / scrollScale - } + // Past the cap the box scrolls over less than the document is long. `scroll.map` says which place of the document + // (a position in `tops`) a scroll position shows, and the pages are drawn `scrollOffset` higher in the box than they + // are in the document. That only changes on a jump (the scrollbar) or when the box rests: a step of the reader, or of + // the browser for the caret, scrolls the pages by itself, once and as far as it goes, like in a short document. + scroll.map.fit(maxLogicalY, Math.max(0, spacerH - size.h), size.h, z) + const capped = scroll.map.capped + const scrollOffset = capped ? scroll.off : 0 + /** the place of the document at the top of the box, as drawn */ + const scrollY = Math.max(0, Math.min(maxLogicalY, scroll.y + scrollOffset)) + const scrollToY = scroll.to + const scrollByY = scroll.by const renderedScroll = useRef(scroll.y) useIsoLayoutEffect(() => { renderedScroll.current = scroll.y }) // A native scroll changes the viewport before useScroll's frame-batched @@ -282,18 +282,18 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp } if (again.current.next === 0 && a?.gen !== fonts.gen) { // (nothing measured again yet: these are the pages the reader sees) - const y = logicalY(sc.scrollTop) + const y = scroll.now() const pi = lowerIndex(tops, y) let bi = pages[pi].start while (bi < pages[pi].end - 1 && blockTop(pi, bi + 1) <= y) bi++ anchor.current = { gen: fonts.gen, bi, dy: blockTop(pi, bi) - y, y } - } else if (a && Math.abs(sc.scrollTop - a.y) <= 1) { + } else if (a && Math.abs(scroll.now() - a.y) <= 1) { const pi = pages.findIndex((p) => a.bi >= p.start && a.bi < p.end) // the first part of the block as drawn; not there while where its lines start is read, or when its page is out of view const el = root.querySelector(`[data-pa="${a.bi}"]:not([data-from])`) if (el) scrollByY(el.getBoundingClientRect().top - sc.getBoundingClientRect().top - a.dy) else if (pi >= 0) scrollToY(blockTop(pi, a.bi) - a.dy) - a.y = sc.scrollTop + a.y = scroll.now() // (released once the block is placed by what is drawn) if (again.current.next < 0 && el) anchor.current = null } else anchor.current = null @@ -1087,7 +1087,8 @@ export function DocxView({ client, onStatus, initialZoom = 'fit' }: DocxViewProp
1 ? 'clip' : undefined }} + // (capped: a page drawn past the end of the box's range must not lengthen it, and the box is scrolled by `ScrollMap` alone when pages move in it) + style={{ height: spacerH, width: totalW, overflow: capped ? 'clip' : undefined, overflowAnchor: capped ? 'none' : undefined }} contentEditable={isEditing || undefined} suppressContentEditableWarning spellCheck={false} diff --git a/src/react/docx/longscroll.ts b/src/react/docx/longscroll.ts new file mode 100644 index 0000000..36c74f4 --- /dev/null +++ b/src/react/docx/longscroll.ts @@ -0,0 +1,258 @@ +import { useEffect, useMemo, useState } from 'react' +import { flushSync } from 'react-dom' +import { useIsoLayoutEffect } from '../common/hooks' + +const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v)) + +/** + * A scroll farther than this in one event (and than the box is high) may be a jump, not a step. Past the cap the + * scrollbar's thumb moves the box by thousands of pixels for each of its own; the wheel and the keys stay under it. + */ +const JUMP = 2000 +/** at each end of a long document, this much scrolls pixel for pixel: the box's range ends where the document does */ +const EDGE = 1_000_000 +/** the box rests after this long without a scroll (ms) */ +const REST = 150 + +/** + * Where a document taller than a browser lets a box scroll is, by the box's scroll position. + * + * The box scrolls over `maxTop` pixels, the document over `maxY`: more, past the cap. The place shown is the scroll + * position plus `off`, and the pages are drawn `off` higher in the box than they are in the document. + * + * - A step (the wheel, a key, a selection dragged past an edge) leaves `off` alone: the browser moves the pages as far + * as it scrolls the box, once, as in a short document. So does a scroll of any length that ends on a page that is + * drawn: the browser brought something of it into view (the caret, what took the focus, `scrollIntoView`). + * - A jump to where nothing is drawn (the scrollbar's thumb, Home, End) goes where the thumb says: `place()`. + * - Steps add up to a box that is not where its thumb belongs for the place it shows, and that can reach an end of + * its range before the document ends. So when it rests, or cannot go on, it is scrolled to `home()` and `off` + * changed by as much (`settle`): nothing moves on screen. + * + * Pure numbers: the element is scrolled, and the pages are drawn, by `useLongScroll`. + */ +export class ScrollMap { + /** the place shown minus the scroll position */ + off = 0 + /** the scroll position last seen or set */ + top = 0 + /** how far the document scrolls */ + maxY = 0 + /** how far the box scrolls */ + maxTop = 0 + private view = 0 + private zoom = 0 + /** a place to go to once the pages are drawn for the new range: the same one at another zoom, or in a document that fits the box again */ + private pending: number | null = null + + /** true when the document is longer than the box scrolls over */ + get capped(): boolean { + return this.maxTop > 0 && this.maxY > this.maxTop + } + + /** the last whole scroll position */ + private get last(): number { + return Math.floor(this.maxTop) + } + + private get edge(): number { + return Math.min(EDGE, this.maxTop / 4) + } + + /** The range, as the pages are laid out now. Called while rendering: what follows from a change of it is done by `refit`. */ + fit(maxY: number, maxTop: number, view: number, zoom: number) { + const was = this.capped + const y = this.top + (was ? this.off : 0) + this.maxY = maxY + this.maxTop = maxTop + this.view = view + // at another zoom, the place is as much farther down as the pages are taller; a shorter document keeps its scroll position, as it always did + if (this.zoom && zoom !== this.zoom && (was || this.capped)) this.pending = ((this.pending ?? y) * zoom) / this.zoom + // no longer capped (pages removed): the place it showed, by the scroll position alone + else if (was && !this.capped && this.off) this.pending ??= y + this.zoom = zoom + if (!this.capped && this.pending === null) this.off = 0 + } + + /** the scroll position to set after a change of range, null when the place did not move */ + refit(): number | null { + const y = this.pending + this.pending = null + return y === null ? null : this.to(y, true) + } + + /** the place shown at the scroll position `top` */ + at(top = this.top): number { + return this.capped ? clamp(top + this.off, 0, this.maxY) : top + } + + /** + * Where the box belongs for the place `y`: pixel for pixel near both ends of the document, in between as far along + * its range as `y` is along the document's. One line through both, so `place` is its inverse. + */ + home(y: number): number { + const { edge, last, maxY } = this + if (y <= edge) return Math.max(0, y) + if (y >= maxY - edge) return Math.min(last, last - (maxY - y)) + return edge + ((y - edge) * (last - 2 * edge)) / (maxY - 2 * edge) + } + + /** the place a box scrolled to `top` by a jump shows */ + place(top: number): number { + const { edge, last, maxY } = this + if (top <= edge) return Math.max(0, top) + if (top >= last - edge) return Math.min(maxY, maxY - (last - top)) + return edge + ((top - edge) * (maxY - 2 * edge)) / (last - 2 * edge) + } + + /** + * The box was scrolled to `top` by the reader or the browser; `end`: it is as far down as it goes; `drawn`: it + * shows a page that is drawn (asked after a long scroll only). + * True when it cannot go on where the document does: it has to be settled now. + */ + scrolled(top: number, end = top >= this.last, drawn: () => boolean = () => false): boolean { + const d = top - this.top + this.top = top + if (!this.capped) return false + // (a whole pixel of the document: the pages are not drawn at a fraction of one for it) + if (Math.abs(d) > Math.max(this.view, JUMP) && !drawn()) this.off = (end ? this.maxY : Math.round(this.place(top))) - top + const y = top + this.off + return (top <= 0 && y > 0.5) || (end && y < this.maxY - 0.5) + } + + /** + * The scroll position to set for the place `y`. A place close by and in the box's reach is a step: the pages stay + * where they are in the box. Any other one (and every one with `far`) is where the box belongs for it. + */ + to(y: number, far = false): number { + if (!this.capped) { + this.off = 0 + return (this.top = clamp(y, 0, this.maxY)) + } + y = clamp(y, 0, this.maxY) + const step = y - this.off + if (!far && Math.abs(y - this.at()) <= Math.max(this.view, JUMP) && step >= 0 && step <= this.last) return (this.top = step) + this.top = Math.round(this.home(y)) + this.off = y - this.top + return this.top + } + + /** The scroll position the element took, after it was set: the place stays the one asked for. */ + landed(top: number) { + if (this.capped && Math.abs(top - this.top) >= 1) this.off += this.top - top + this.top = top + } + + /** The scroll position that puts the box where it belongs for the place it shows; null when it is there. */ + settle(): number | null { + if (!this.capped) return null + const y = clamp(this.top + this.off, 0, this.maxY) + const top = Math.round(this.home(y)) + // (a place out of the document, after pages were removed, is put back in it even when the box stays) + if (Math.abs(top - this.top) < 1 && y === this.top + this.off) return null + this.top = top + this.off = y - top + return top + } +} + +export interface LongScroll { + x: number + /** the scroll position the view was last drawn for */ + y: number + /** how much higher the pages are drawn in the box than they are in the document: 0 until the document is longer than the box scrolls over */ + off: number + map: ScrollMap + /** scrolls to the place `y` of the document */ + to(y: number): void + /** scrolls by `delta` pixels of the document */ + by(delta: number): void + /** the place shown now, by the element's own scroll position (the view may not be drawn for it yet) */ + now(): number +} + +/** + * The scroll position of the box a document is paged in, batched to animation frames like `useScroll`, and the place + * of the document it shows: the same number until the document is longer than a browser lets a box scroll (`ScrollMap`). + * `pages`: a selector of the pages drawn in the box. + */ +export function useLongScroll(ref: React.RefObject, pages: string): LongScroll { + const map = useMemo(() => new ScrollMap(), []) + const [pos, setPos] = useState({ x: 0, y: 0, off: 0 }) + const [el, setEl] = useState(null) + const read = () => { + const e = ref.current + if (e) setPos((p) => (p.x === e.scrollLeft && p.y === map.top && p.off === map.off ? p : { x: e.scrollLeft, y: map.top, off: map.off })) + } + /** scrolls the element to `top`, a position the map gave */ + const set = (e: HTMLElement, top: number) => { + if (e.scrollTop !== top) e.scrollTop = top + map.landed(e.scrollTop) + } + useIsoLayoutEffect(() => { + const e = ref.current + if (e !== el) setEl(e) + // the range changed under the place shown (another zoom): the pages were drawn for it, the box follows before they are painted + const top = e && map.refit() + if (e && top !== null) { + set(e, top) + read() + } + }) + useEffect(() => { + if (!el) return + let raf = 0 + let rest: ReturnType | undefined + const settle = () => { + const top = map.settle() + if (top === null) return + // the box first, then the pages, drawn at once: both before the next paint, and nothing moves on screen + set(el, top) + flushSync(read) + } + /** true when a page that is drawn is in the box */ + const drawn = () => { + const box = el.getBoundingClientRect() + for (const p of el.querySelectorAll(pages)) { + const r = p.getBoundingClientRect() + if (r.bottom > box.top && r.top < box.bottom) return true + } + return false + } + const on = () => { + const stuck = map.scrolled(el.scrollTop, el.scrollTop >= el.scrollHeight - el.clientHeight - 1, drawn) + clearTimeout(rest) + if (stuck) settle() + else if (map.capped) rest = setTimeout(settle, REST) + if (raf) return + raf = requestAnimationFrame(() => { + raf = 0 + read() + }) + } + map.scrolled(el.scrollTop) + read() + el.addEventListener('scroll', on, { passive: true }) + return () => { + el.removeEventListener('scroll', on) + cancelAnimationFrame(raf) + clearTimeout(rest) + } + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [el, map]) + const to = (y: number) => { + const e = ref.current + if (!e) return + // a short document: the scroll position is the place, and the view follows the scroll event + if (!map.capped) return void (e.scrollTop = clamp(y, 0, map.maxY)) + set(e, map.to(y)) + read() + } + const now = () => map.at(ref.current?.scrollTop ?? map.top) + const by = (delta: number) => { + const e = ref.current + if (!e) return + if (!map.capped) e.scrollTop += delta + else to(now() + delta) + } + return { ...pos, map, to, by, now } +} diff --git a/test/docx-longscroll.test.ts b/test/docx-longscroll.test.ts new file mode 100644 index 0000000..e5d1842 --- /dev/null +++ b/test/docx-longscroll.test.ts @@ -0,0 +1,259 @@ +import { describe, expect, test } from 'bun:test' +import { ScrollMap } from '../src/react/docx/longscroll' + +// a box 800 px high that scrolls over 12,000,000 px of spacer, and a document of 26,400,800 px: 2.2 times as far +const VIEW = 800 +const MAX_TOP = 12_000_000 - VIEW +const MAX_Y = 26_400_800 - VIEW + +function capped() { + const m = new ScrollMap() + m.fit(MAX_Y, MAX_TOP, VIEW, 1) + return m +} + +/** the reader scrolls by `d`, `n` times; a box that cannot go on is settled, as the view does */ +function steps(m: ScrollMap, d: number, n: number) { + let settled = 0 + for (let i = 0; i < n; i++) { + const top = Math.min(MAX_TOP, Math.max(0, m.top + d)) + if (m.scrolled(top) && m.settle() !== null) settled++ + } + return settled +} + +describe('a document no longer than its box scrolls over', () => { + test('the scroll position is the place', () => { + const m = new ScrollMap() + m.fit(5000, 5000, VIEW, 1) + expect(m.capped).toBe(false) + expect(m.scrolled(1234)).toBe(false) + expect(m.at()).toBe(1234) + expect(m.scrolled(5000)).toBe(false) + expect(m.at(4000)).toBe(4000) + expect(m.to(300)).toBe(300) + expect(m.to(9000)).toBe(5000) + expect(m.settle()).toBeNull() + expect(m.off).toBe(0) + }) +}) + +describe('a document longer than its box scrolls over', () => { + test('a step moves the document as far as the box: the pages stay where they are in it', () => { + const m = capped() + expect(m.capped).toBe(true) + m.scrolled(5_000_000) + const { off } = m + const y = m.at() + for (const d of [300, 120, -40, VIEW, -VIEW, 2000]) { + const before = m.at() + expect(m.scrolled(m.top + d)).toBe(false) + expect(m.at() - before).toBe(d) + } + expect(m.off).toBe(off) + expect(m.at()).toBe(y + 300 + 120 - 40 + 2000) + }) + + test('a jump goes where the thumb says: both ends, and as far along the document as the box is along its range', () => { + const m = capped() + m.scrolled(MAX_TOP) + expect(m.at()).toBe(MAX_Y) + m.scrolled(0) + expect(m.at()).toBe(0) + m.scrolled(MAX_TOP / 2) + expect(m.at()).toBeCloseTo(MAX_Y / 2, 0) + // a box that ends a little before its spacer says (`end`): still the end of the document + m.scrolled(100) + m.scrolled(MAX_TOP - 3, true) + expect(m.at()).toBe(MAX_Y) + }) + + test('a long scroll that ends on a page that is drawn is the browser’s (the caret, the focus): the pages stay where they are', () => { + const m = capped() + m.scrolled(5_000_000) + const y = m.at() + const { off } = m + // a page up, to what took the focus there + expect(m.scrolled(5_000_000 - 167_000, false, () => true)).toBe(false) + expect(m.off).toBe(off) + expect(m.at()).toBe(y - 167_000) + // the same scroll to where nothing is drawn: the thumb + m.scrolled(5_000_000, false, () => true) + m.scrolled(5_000_000 - 167_000, false, () => false) + expect(m.at()).toBe(Math.round(m.place(5_000_000 - 167_000))) + // a step does not ask + m.scrolled(m.top + 300, false, () => { + throw new Error('asked') + }) + }) + + test('near both ends the document scrolls pixel for pixel', () => { + const m = capped() + expect(m.place(500)).toBe(500) + expect(m.home(500)).toBe(500) + expect(m.place(999_999)).toBe(999_999) + expect(m.place(MAX_TOP - 500)).toBe(MAX_Y - 500) + expect(m.home(MAX_Y - 500)).toBe(MAX_TOP - 500) + // from the top, by the wheel: no offset, as in a short document + steps(m, 100, 50) + expect(m.at()).toBe(5000) + expect(m.off).toBe(0) + expect(m.settle()).toBeNull() + }) + + test('where the box belongs for a place, and the place a jump shows, are each other’s inverse and never go back', () => { + const m = capped() + let last = -1 + for (let top = 0; top <= MAX_TOP; top += 37_337) { + const y = m.place(top) + expect(y).toBeGreaterThan(last) + expect(y).toBeLessThanOrEqual(MAX_Y) + expect(m.home(y)).toBeCloseTo(top, 3) + last = y + } + expect(m.place(MAX_TOP)).toBe(MAX_Y) + expect(m.home(MAX_Y)).toBe(MAX_TOP) + }) + + test('a box that rests is put where its thumb belongs, and shows the same place', () => { + const m = capped() + m.scrolled(6_000_000) + expect(m.settle()).toBeNull() + steps(m, 300, 100) + const y = m.at() + const top = m.settle() + expect(top).toBe(Math.round(m.home(y))) + // 30,000 px of the document are less than half as many of the box's range + expect(top! - 6_000_000).toBeGreaterThan(12_000) + expect(top! - 6_000_000).toBeLessThan(12_600) + expect(m.at()).toBe(y) + expect(m.top).toBe(top!) + expect(m.settle()).toBeNull() + // the scroll event of that position is a step of nothing + expect(m.scrolled(top!)).toBe(false) + expect(m.at()).toBe(y) + }) + + test('steps that reach an end of the box before the end of the document go on: the last page is reached by the wheel', () => { + const m = capped() + // 3,000,000 px before the end of the box's range, where the document has more than twice that left + m.scrolled(MAX_TOP - 3_000_000) + const left = MAX_Y - m.at() + expect(left).toBeGreaterThan(5_000_000) + const settled = steps(m, 500, Math.ceil(left / 500) + 5) + expect(m.at()).toBe(MAX_Y) + expect(m.top).toBe(MAX_TOP) + // settled a few times on the way, not at every step + expect(settled).toBeGreaterThan(0) + expect(settled).toBeLessThan(12) + // and back up to the first page + m.scrolled(3_000_000) + const down = m.at() + const up = steps(m, -500, Math.ceil(down / 500) + 5) + expect(m.at()).toBe(0) + expect(m.top).toBe(0) + expect(up).toBeLessThan(12) + }) + + test('a box settled at an end where the document goes on has room again', () => { + const m = capped() + m.scrolled(2_000_000) + // as steps left it: the box 1500 px from its start, the document 101,500 + m.top = 1500 + m.off = 100_000 + expect(m.scrolled(0)).toBe(true) + expect(m.at()).toBe(100_000) + expect(m.settle()).toBe(100_000) + expect(m.off).toBe(0) + expect(m.at()).toBe(100_000) + }) + + test('a place asked for: a step when it is close and in reach, else where the box belongs for it', () => { + const m = capped() + m.scrolled(6_000_000) + const y = m.at() + const { off } = m + // close by: the pages stay where they are + expect(m.to(y + 400)).toBe(6_000_400) + expect(m.off).toBe(off) + expect(m.at()).toBe(y + 400) + // far: the box where the thumb belongs + expect(m.to(20_000_000)).toBe(Math.round(m.home(20_000_000))) + expect(m.at()).toBe(20_000_000) + // the scroll event of a position that was set is no jump + const top = m.top + m.scrolled(top) + expect(m.at()).toBe(20_000_000) + // out of the document + m.to(MAX_Y + 5000) + expect(m.at()).toBe(MAX_Y) + expect(m.top).toBe(MAX_TOP) + m.to(-10) + expect(m.at()).toBe(0) + expect(m.top).toBe(0) + // close, but out of the box's reach: no step + m.off = 500 + m.top = 0 + expect(m.to(300)).toBe(300) + expect(m.off).toBe(0) + }) + + test('the position the element took is the one the place is counted from', () => { + const m = capped() + m.to(13_000_000.4) + const y = m.at() + // a fraction of a pixel: the pages stay + const { off } = m + m.landed(m.top + 0.5) + expect(m.off).toBe(off) + // the element stopped short: the place asked for is still the one shown + m.landed(m.top - 40) + expect(m.at()).toBeCloseTo(y + 0.5, 3) + }) + + test('another zoom: the same place of the taller or shorter pages', () => { + const m = capped() + m.scrolled(6_000_000) + const y = m.at() + expect(m.refit()).toBeNull() + m.fit(MAX_Y * 2, MAX_TOP, VIEW, 2) + const top = m.refit() + expect(top).not.toBeNull() + expect(m.at()).toBeCloseTo(y * 2, 0) + expect(m.refit()).toBeNull() + // down to a size at which the document fits the box's range: the place by the scroll position alone + m.fit(MAX_Y / 4, MAX_Y / 4, VIEW, 0.25) + expect(m.capped).toBe(false) + expect(m.refit()).toBeCloseTo(y / 4, 0) + expect(m.off).toBe(0) + expect(m.at()).toBeCloseTo(y / 4, 0) + }) + + test('a document that grows past the cap while it is read stays where it is', () => { + const m = new ScrollMap() + m.fit(8_000_000, 8_000_000, VIEW, 1) + m.scrolled(7_000_000) + // more pages laid out: the same box position, the same place + m.fit(MAX_Y, MAX_TOP, VIEW, 1) + expect(m.capped).toBe(true) + expect(m.refit()).toBeNull() + expect(m.at()).toBe(7_000_000) + // resting, the box goes to where its thumb belongs for that place + const top = m.settle() + expect(top).toBe(Math.round(m.home(7_000_000))) + expect(m.at()).toBe(7_000_000) + }) + + test('pages removed: a place past the new end is put back in the document', () => { + const m = capped() + m.scrolled(MAX_TOP) + m.fit(20_000_000, MAX_TOP, VIEW, 1) + expect(m.at()).toBe(20_000_000) + expect(m.settle()).toBe(MAX_TOP) + expect(m.top + m.off).toBe(20_000_000) + // shorter than the box's range: no longer capped, the place it showed (now the end) + m.fit(9_000_000, 9_000_000, VIEW, 1) + expect(m.refit()).toBe(9_000_000) + expect(m.off).toBe(0) + }) +})