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