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

useThreadFindNavigation.ts

241 lines8.3 KB

1import type { LegendListRef } from "@legendapp/list/react";
2import { useEffect, useLayoutEffect, useRef, type RefObject } from "react";
3import type { ThreadFindMatch } from "./threadFind";
4import { useThreadFindHighlights } from "./threadFindHighlights";
5​
6const FIND_MATCH_VIEW_MARGIN = 96;
7​
8export function useThreadFindNavigation({
9 container,
10 query,
11 match,
12 navigationId,
13 rowIndex,
14 entries,
15 listRef,
16 contentInsetEndAdjustment,
17 listReady,
18 historyControls,
19}: {
20 container: HTMLElement | null;
21 query: string;
22 match: ThreadFindMatch | null;
23 navigationId: number;
24 rowIndex: number;
25 entries: readonly { readonly id: string }[];
26 listRef: RefObject<LegendListRef | null>;
27 contentInsetEndAdjustment: number;
28 listReady: boolean;
29 historyControls?:
30 | {
31 readonly hasMoreHistory: boolean;
32 readonly loading: boolean;
33 readonly error: string | null;
34 readonly onLoadEarlier: (throughEntryId?: string) => void;
35 }
36 | undefined;
37}) {
38 const matchKey = match ? `${navigationId}:${query}:${match.entryId}:${match.occurrence}` : null;
39 const positioningRef = useRef<{
40 key: string;
41 rowIndex: number;
42 entries: typeof entries;
43 } | null>(null);
44 const settledMatchRef = useRef<string | null>(null);
45 const currentMatchKeyRef = useRef(matchKey);
46 const activeRangeRef = useRef<Range | null>(null);
47 const pagingPositionRef = useRef<{ key: string; entries: typeof entries; top: number } | null>(
48 null,
49 );
50 const currentEntriesRef = useRef(entries);
51 useLayoutEffect(() => {
52 currentEntriesRef.current = entries;
53 }, [entries]);
54 useEffect(() => {
55 if (!container) return;
56 const onScroll = () => {
57 const position = pagingPositionRef.current;
58 const range = activeRangeRef.current;
59 if (
60 !position ||
61 position.entries !== currentEntriesRef.current ||
62 !range?.startContainer.isConnected
63 )
64 return;
65 const rect = range.getBoundingClientRect();
66 const viewport = container.getBoundingClientRect();
67 if (rect.bottom < viewport.top || rect.top > viewport.bottom)
68 pagingPositionRef.current = null;
69 else position.top = rect.top;
70 };
71 container.addEventListener("scroll", onScroll, { passive: true });
72 return () => container.removeEventListener("scroll", onScroll);
73 }, [container]);
74 const revealRef = useRef<(range: Range | null) => void>(() => {});
75 useLayoutEffect(() => {
76 currentMatchKeyRef.current = matchKey;
77 return () => {
78 currentMatchKeyRef.current = null;
79 };
80 }, [matchKey]);
81 const revealedMatchRef = useRef<string | null>(null);
82 const positionedEntriesRef = useRef<typeof entries | null>(null);
83 const requestedPagesRef = useRef<{ key: string | null; pages: Set<string> }>({
84 key: null,
85 pages: new Set(),
86 });
87 useEffect(() => {
88 if (requestedPagesRef.current.key !== matchKey)
89 requestedPagesRef.current = { key: matchKey, pages: new Set() };
90 if (
91 !match ||
92 !listReady ||
93 rowIndex >= 0 ||
94 entries.some((entry) => entry.id === match.entryId)
95 )
96 return;
97 if (!historyControls?.hasMoreHistory || historyControls.loading || historyControls.error)
98 return;
99 const cursor = entries[0]?.id ?? "first";
100 if (requestedPagesRef.current.pages.has(cursor)) return;
101 requestedPagesRef.current.pages.add(cursor);
102​
103 historyControls.onLoadEarlier(match.entryId);
104 }, [entries, historyControls, listReady, match, matchKey, rowIndex]);
105 const reveal = (range: Range | null) => {
106 activeRangeRef.current = range;
107 if (!matchKey) {
108 positioningRef.current = null;
109 settledMatchRef.current = null;
110 revealedMatchRef.current = null;
111 pagingPositionRef.current = null;
112 return;
113 }
114 const pagingPosition = pagingPositionRef.current;
115 if (pagingPosition && pagingPosition.key !== matchKey) pagingPositionRef.current = null;
116 if (
117 range?.startContainer.isConnected &&
118 pagingPosition?.key === matchKey &&
119 pagingPosition.entries !== entries
120 ) {
121 const restore = () => {
122 const pinned = pagingPositionRef.current;
123 const currentRange = activeRangeRef.current;
124 if (
125 currentMatchKeyRef.current !== matchKey ||
126 !pinned ||
127 !currentRange?.startContainer.isConnected
128 )
129 return;
130 const delta = currentRange.getBoundingClientRect().top - pinned.top;
131 const scroll = listRef.current?.getState?.().scroll;
132 if (Math.abs(delta) >= 1 && typeof scroll === "number")
133 listRef.current?.scrollToOffset({ offset: scroll + delta, animated: false });
134 };
135 pagingPosition.entries = entries;
136 restore();
137 // The list measures newly inserted activity after the first layout pass.
138 requestAnimationFrame(() =>
139 requestAnimationFrame(() => {
140 restore();
141 if (!historyControls?.loading && pagingPositionRef.current === pagingPosition)
142 pagingPositionRef.current = null;
143 }),
144 );
145 }
146 if (historyControls?.error) pagingPositionRef.current = null;
147 if (revealedMatchRef.current === matchKey) return;
148 if (!listReady || rowIndex < 0) return;
149 const materialize = () => {
150 const list = listRef.current;
151 const previous = positioningRef.current;
152 if (
153 !list ||
154 (previous?.key === matchKey &&
155 previous.rowIndex === rowIndex &&
156 previous.entries === entries)
157 )
158 return;
159 // Activity can insert rows during LegendList layout; retarget pending jumps.
160 const request = { key: matchKey, rowIndex, entries };
161 positioningRef.current = request;
162​
163 void list
164 .scrollToIndex({
165 index: rowIndex,
166 animated: false,
167 viewOffset: FIND_MATCH_VIEW_MARGIN,
168 })
169 .then(() => {
170 if (positioningRef.current !== request || currentMatchKeyRef.current !== matchKey) return;
171​
172 positionedEntriesRef.current = entries;
173 settledMatchRef.current = matchKey;
174 revealRef.current(activeRangeRef.current);
175 });
176 };
177 if (!range) {
178 if (container) materialize();
179 return;
180 }
181​
182 const codeScroller = range.startContainer.parentElement?.closest("pre");
183 if (codeScroller) {
184 const rect = range.getBoundingClientRect();
185 const viewport = codeScroller.getBoundingClientRect();
186 if (rect.left < viewport.left) codeScroller.scrollLeft += rect.left - viewport.left - 16;
187 else if (rect.right > viewport.right)
188 codeScroller.scrollLeft += rect.right - viewport.right + 16;
189 }
190 const rect = range.getBoundingClientRect();
191 const viewport = container?.getBoundingClientRect();
192 if (!viewport || rect.height === 0) return;
193 const margin = Math.min(
194 FIND_MATCH_VIEW_MARGIN,
195 Math.max(0, (viewport.height - contentInsetEndAdjustment - rect.height) / 2),
196 );
197 const top = viewport.top + margin;
198 const bottom = viewport.bottom - margin - contentInsetEndAdjustment;
199 const delta = rect.top < top ? rect.top - top : rect.bottom > bottom ? rect.bottom - bottom : 0;
200 // DOM text can precede settled row sizes; wait before measuring offscreen matches.
201 if (
202 Math.abs(delta) >= 1 &&
203 positionedEntriesRef.current !== entries &&
204 settledMatchRef.current !== matchKey
205 ) {
206 materialize();
207 return;
208 }
209 const scroll = listRef.current?.getState?.().scroll;
210 positionedEntriesRef.current = entries;
211​
212 revealedMatchRef.current = matchKey;
213 if (historyControls?.loading)
214 pagingPositionRef.current = { key: matchKey, entries, top: rect.top - delta };
215 if (Math.abs(delta) >= 1 && typeof scroll === "number") {
216 listRef.current?.scrollToOffset({ offset: scroll + delta, animated: false });
217 requestAnimationFrame(() => {
218 if (currentMatchKeyRef.current !== matchKey) return;
219 if (
220 listRef.current?.getState?.().scroll === scroll &&
221 range.getBoundingClientRect().top === rect.top
222 )
223 return;
224 revealedMatchRef.current = null;
225 revealRef.current(activeRangeRef.current);
226 });
227 }
228 };
229​
230 useLayoutEffect(() => {
231 revealRef.current = reveal;
232 }, [reveal]);
233​
234 useThreadFindHighlights({
235 container,
236 query,
237 activeRowId: match?.entryId ?? null,
238 activeOccurrence: match?.occurrence ?? 0,
239 onActiveRange: reveal,
240 });