Open History to see the last commit
1import { observeResize } from "./observeResize";
2
3/** Native anchoring keeps a paragraph's start fixed, losing the visible line in a long paragraph. */
4export function preserveReadingPosition(
5 scroller: HTMLElement,
6 enabled: () => boolean = () => true,
7): () => void {
8 // Seeded by the observer's first report or an earlier scroll, never read here: that would force
9 // a layout mid-commit. A resize before either is not corrected.
10 let width: number | null = null;
11 let anchor: { range: Range; top: number } | null = null;
12 let frame: number | null = null;
13
14 const capture = () => {
15 width ??= scroller.clientWidth;
16 if (frame !== null || scroller.clientWidth !== width) return;
17 anchor = null;
18 if (!enabled() || scroller.scrollTop === 0) return;
19 const box = scroller.getBoundingClientRect();
20 const selection =
21 scroller.isContentEditable && document.activeElement === scroller
22 ? document.getSelection()
23 : null;
24 if (selection?.isCollapsed && selection.rangeCount > 0) {
25 const range = selection.getRangeAt(0).cloneRange();
26 const rect = range.getBoundingClientRect();
27 if (
28 scroller.contains(range.startContainer) &&
29 rect.top >= box.top &&
30 rect.bottom <= box.bottom
31 ) {
32 anchor = { range, top: rect.top - box.top };
33 return;
34 }
35 }
36 // A point near the top captures text rather than the paragraph's bounding box.
37 const x = box.left + box.width / 2;
38 // The first point can land in paragraph spacing. Look only within the first few lines.
39 for (let inset = Math.min(24, box.height / 2); inset < Math.min(64, box.height); inset += 8) {
40 const y = box.top + inset;
41 const position = document.caretPositionFromPoint?.(x, y);
42 const fallback = position ? null : document.caretRangeFromPoint?.(x, y);
43 // Inside an <input> or <textarea> the caret node is the element and the offset indexes its value.
44 const node = position?.offsetNode ?? fallback?.startContainer;
45 if (!node || node.nodeType !== Node.TEXT_NODE || !scroller.contains(node)) continue;
46 const range = document.createRange();
47 range.setStart(node, position?.offset ?? fallback?.startOffset ?? 0);
48 range.collapse(true);
49 const top = range.getBoundingClientRect().top - box.top;
50 if (top >= 0 && top < scroller.clientHeight) {
51 anchor = { range, top };
52 break;
53 }
54 }
55 };
56 const restore = () => {
57 if (
58 !enabled() ||
59 !anchor ||
60 anchor.range.startContainer.nodeType !== Node.TEXT_NODE ||
61 !scroller.contains(anchor.range.startContainer)
62 )
63 return;
64 const delta =
65 anchor.range.getBoundingClientRect().top - scroller.getBoundingClientRect().top - anchor.top;
66 if (Math.abs(delta) > 0.5) scroller.scrollTop += delta;
67 };
68 const stop = observeResize(scroller, () => {
69 const nextWidth = scroller.clientWidth;
70 if (width === null) width = nextWidth;
71 if (nextWidth === width) {
72 capture();
73 return;
74 }
75 width = nextWidth;
76 restore();
77 if (frame !== null) cancelAnimationFrame(frame);
78 // Virtualized rows can finish measuring in the next frame. Keep the same text anchor then.
79 frame = requestAnimationFrame(() => {
80 restore();
81 frame = null;
82 capture();
83 });
84 });
85 scroller.addEventListener("scroll", capture, { passive: true });
86 scroller.addEventListener("input", capture);
87 const captureSelection = () => {
88 if (document.activeElement === scroller) capture();
89 };
90 if (scroller.isContentEditable) document.addEventListener("selectionchange", captureSelection);
91 const interrupt = () => {
92 if (frame !== null) cancelAnimationFrame(frame);
93 anchor = null;
94 // Scrolling wins over a pending resize correction; the next frame captures the reader's new place.
95 frame = requestAnimationFrame(() => {
96 frame = null;
97 width = scroller.clientWidth;
98 capture();
99 });
100 };
101 scroller.addEventListener("wheel", interrupt, { passive: true });
102 scroller.addEventListener("touchmove", interrupt, { passive: true });
103 return () => {
104 stop();
105 if (frame !== null) cancelAnimationFrame(frame);
106 scroller.removeEventListener("scroll", capture);
107 scroller.removeEventListener("input", capture);
108 document.removeEventListener("selectionchange", captureSelection);
109 scroller.removeEventListener("wheel", interrupt);
110 scroller.removeEventListener("touchmove", interrupt);
111 };
112}