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 range = document.createRange();
43 if (position) {
44 range.setStart(position.offsetNode, position.offset);
45 } else {
46 const fallback = document.caretRangeFromPoint?.(x, y);
47 if (!fallback) continue;
48 range.setStart(fallback.startContainer, fallback.startOffset);
49 }
50 range.collapse(true);
51 if (
52 !scroller.contains(range.startContainer) ||
53 range.startContainer.nodeType !== Node.TEXT_NODE
54 )
55 continue;
56 const top = range.getBoundingClientRect().top - box.top;
57 if (top >= 0 && top < scroller.clientHeight) {
58 anchor = { range, top };
59 break;
60 }
61 }
62 };
63 const restore = () => {
64 if (
65 !enabled() ||
66 !anchor ||
67 anchor.range.startContainer.nodeType !== Node.TEXT_NODE ||
68 !scroller.contains(anchor.range.startContainer)
69 )
70 return;
71 const delta =
72 anchor.range.getBoundingClientRect().top - scroller.getBoundingClientRect().top - anchor.top;
73 if (Math.abs(delta) > 0.5) scroller.scrollTop += delta;
74 };
75 const stop = observeResize(scroller, () => {
76 const nextWidth = scroller.clientWidth;
77 if (width === null) width = nextWidth;
78 if (nextWidth === width) {
79 capture();
80 return;
81 }
82 width = nextWidth;
83 restore();
84 if (frame !== null) cancelAnimationFrame(frame);
85 // Virtualized rows can finish measuring in the next frame. Keep the same text anchor then.
86 frame = requestAnimationFrame(() => {
87 restore();
88 frame = null;
89 capture();
90 });
91 });
92 scroller.addEventListener("scroll", capture, { passive: true });
93 scroller.addEventListener("input", capture);
94 const captureSelection = () => {
95 if (document.activeElement === scroller) capture();
96 };
97 if (scroller.isContentEditable) document.addEventListener("selectionchange", captureSelection);
98 const interrupt = () => {
99 if (frame !== null) cancelAnimationFrame(frame);
100 anchor = null;
101 // Scrolling wins over a pending resize correction; the next frame captures the reader's new place.
102 frame = requestAnimationFrame(() => {
103 frame = null;
104 width = scroller.clientWidth;
105 capture();
106 });
107 };
108 scroller.addEventListener("wheel", interrupt, { passive: true });
109 scroller.addEventListener("touchmove", interrupt, { passive: true });
110 return () => {
111 stop();
112 if (frame !== null) cancelAnimationFrame(frame);
113 scroller.removeEventListener("scroll", capture);
114 scroller.removeEventListener("input", capture);
115 document.removeEventListener("selectionchange", captureSelection);
116 scroller.removeEventListener("wheel", interrupt);
117 scroller.removeEventListener("touchmove", interrupt);
118 };
119}