Open History to see the last commit
1import { describe, expect, it, onTestFinished, vi } from "vite-plus/test";
2
3import { preserveReadingPosition } from "./preserveReadingPosition";
4
5describe("preserveReadingPosition", () => {
6 it("keeps the reader's line through a resize that lands before the first layout report", async () => {
7 const scroller = document.createElement("div");
8 scroller.style.cssText =
9 "width: 600px; height: 300px; overflow-y: auto; font: 16px/20px serif;";
10 // The marker fits one line at both widths, so whichever caret the probe picks shares its top.
11 scroller.innerHTML = Array.from({ length: 30 }, (_, index) =>
12 index === 15
13 ? "<p>Marker line.</p>"
14 : `<p>${"Filler words that wrap across several lines. ".repeat(8)}</p>`,
15 ).join("");
16 document.body.append(scroller);
17 onTestFinished(() => scroller.remove());
18 const markerText = [...scroller.querySelectorAll("p")][15]!.firstChild!;
19 const markerTop = () => {
20 const range = document.createRange();
21 range.setStart(markerText, 0);
22 range.collapse(true);
23 return range.getBoundingClientRect().top - scroller.getBoundingClientRect().top;
24 };
25
26 const stop = preserveReadingPosition(scroller);
27 onTestFinished(stop);
28 scroller.scrollTop += markerTop() - 24;
29 scroller.dispatchEvent(new Event("scroll"));
30 const before = markerTop();
31 scroller.style.width = "300px";
32
33 await vi.waitFor(() => expect(Math.abs(markerTop() - before)).toBeLessThan(2));
34 });
35});