Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

preserveReadingPosition.ts

115 lines4.1 KB

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 let width = scroller.clientWidth;
9 let anchor: { range: Range; top: number } | null = null;
10 let frame: number | null = null;
11​
12 const capture = () => {
13 if (frame !== null || scroller.clientWidth !== width) return;
14 anchor = null;
15 if (!enabled() || scroller.scrollTop === 0) return;
16 const box = scroller.getBoundingClientRect();
17 const selection =
18 scroller.isContentEditable && document.activeElement === scroller
19 ? document.getSelection()
20 : null;
21 if (selection?.isCollapsed && selection.rangeCount > 0) {
22 const range = selection.getRangeAt(0).cloneRange();
23 const rect = range.getBoundingClientRect();
24 if (
25 scroller.contains(range.startContainer) &&
26 rect.top >= box.top &&
27 rect.bottom <= box.bottom
28 ) {
29 anchor = { range, top: rect.top - box.top };
30 return;
31 }
32 }
33 // A point near the top captures text rather than the paragraph's bounding box.
34 const x = box.left + box.width / 2;
35 // The first point can land in paragraph spacing. Look only within the first few lines.
36 for (let inset = Math.min(24, box.height / 2); inset < Math.min(64, box.height); inset += 8) {
37 const y = box.top + inset;
38 const position = document.caretPositionFromPoint?.(x, y);
39 const range = document.createRange();
40 if (position) {
41 range.setStart(position.offsetNode, position.offset);
42 } else {
43 const fallback = document.caretRangeFromPoint?.(x, y);
44 if (!fallback) continue;
45 range.setStart(fallback.startContainer, fallback.startOffset);
46 }
47 range.collapse(true);
48 if (
49 !scroller.contains(range.startContainer) ||
50 range.startContainer.nodeType !== Node.TEXT_NODE
51 )
52 continue;
53 const top = range.getBoundingClientRect().top - box.top;
54 if (top >= 0 && top < scroller.clientHeight) {
55 anchor = { range, top };
56 break;
57 }
58 }
59 };
60 const restore = () => {
61 if (
62 !enabled() ||
63 !anchor ||
64 anchor.range.startContainer.nodeType !== Node.TEXT_NODE ||
65 !scroller.contains(anchor.range.startContainer)
66 )
67 return;
68 const delta =
69 anchor.range.getBoundingClientRect().top - scroller.getBoundingClientRect().top - anchor.top;
70 if (Math.abs(delta) > 0.5) scroller.scrollTop += delta;
71 };
72 const stop = observeResize(scroller, () => {
73 const nextWidth = scroller.clientWidth;
74 if (nextWidth === width) {
75 capture();
76 return;
77 }
78 width = nextWidth;
79 restore();
80 if (frame !== null) cancelAnimationFrame(frame);
81 // Virtualized rows can finish measuring in the next frame. Keep the same text anchor then.
82 frame = requestAnimationFrame(() => {
83 restore();
84 frame = null;
85 capture();
86 });
87 });
88 scroller.addEventListener("scroll", capture, { passive: true });
89 scroller.addEventListener("input", capture);
90 const captureSelection = () => {
91 if (document.activeElement === scroller) capture();
92 };
93 if (scroller.isContentEditable) document.addEventListener("selectionchange", captureSelection);
94 const interrupt = () => {
95 if (frame !== null) cancelAnimationFrame(frame);
96 anchor = null;
97 // Scrolling wins over a pending resize correction; the next frame captures the reader's new place.
98 frame = requestAnimationFrame(() => {
99 frame = null;
100 width = scroller.clientWidth;
101 capture();
102 });
103 };
104 scroller.addEventListener("wheel", interrupt, { passive: true });
105 scroller.addEventListener("touchmove", interrupt, { passive: true });
106 return () => {
107 stop();
108 if (frame !== null) cancelAnimationFrame(frame);
109 scroller.removeEventListener("scroll", capture);
110 scroller.removeEventListener("input", capture);
111 document.removeEventListener("selectionchange", captureSelection);
112 scroller.removeEventListener("wheel", interrupt);
113 scroller.removeEventListener("touchmove", interrupt);
114 };