Open History to see the last commit
1import type { LegendListRef } from "@legendapp/list/react";
2import { useCallback, 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 = useCallback(
106 (range: Range | null) => {
107 activeRangeRef.current = range;
108 if (!matchKey) {
109 positioningRef.current = null;
110 settledMatchRef.current = null;
111 revealedMatchRef.current = null;
112 pagingPositionRef.current = null;
113 return;
114 }
115 const pagingPosition = pagingPositionRef.current;
116 if (pagingPosition && pagingPosition.key !== matchKey) pagingPositionRef.current = null;
117 if (
118 range?.startContainer.isConnected &&
119 pagingPosition?.key === matchKey &&
120 pagingPosition.entries !== entries
121 ) {
122 const restore = () => {
123 const pinned = pagingPositionRef.current;
124 const currentRange = activeRangeRef.current;
125 if (
126 currentMatchKeyRef.current !== matchKey ||
127 !pinned ||
128 !currentRange?.startContainer.isConnected
129 )
130 return;
131 const delta = currentRange.getBoundingClientRect().top - pinned.top;
132 const scroll = listRef.current?.getState?.().scroll;
133 if (Math.abs(delta) >= 1 && typeof scroll === "number")
134 listRef.current?.scrollToOffset({ offset: scroll + delta, animated: false });
135 };
136 pagingPosition.entries = entries;
137 restore();
138 // The list measures newly inserted activity after the first layout pass.
139 requestAnimationFrame(() =>
140 requestAnimationFrame(() => {
141 restore();
142 if (!historyControls?.loading && pagingPositionRef.current === pagingPosition)
143 pagingPositionRef.current = null;
144 }),
145 );
146 }
147 if (historyControls?.error) pagingPositionRef.current = null;
148 if (revealedMatchRef.current === matchKey) return;
149 if (!listReady || rowIndex < 0) return;
150 const materialize = () => {
151 const list = listRef.current;
152 const previous = positioningRef.current;
153 if (
154 !list ||
155 (previous?.key === matchKey &&
156 previous.rowIndex === rowIndex &&
157 previous.entries === entries)
158 )
159 return;
160 // Activity can insert rows while LegendList waits for layout. Retarget the
161 // pending jump instead of treating the first requested index as final.
162 const request = { key: matchKey, rowIndex, entries };
163 positioningRef.current = request;
164
165 void list
166 .scrollToIndex({
167 index: rowIndex,
168 animated: false,
169 viewOffset: FIND_MATCH_VIEW_MARGIN,
170 })
171 .then(() => {
172 if (positioningRef.current !== request || currentMatchKeyRef.current !== matchKey)
173 return;
174
175 positionedEntriesRef.current = entries;
176 settledMatchRef.current = matchKey;
177 revealRef.current(activeRangeRef.current);
178 });
179 };
180 if (!range) {
181 if (container) materialize();
182 return;
183 }
184
185 const codeScroller = range.startContainer.parentElement?.closest("pre");
186 if (codeScroller) {
187 const rect = range.getBoundingClientRect();
188 const viewport = codeScroller.getBoundingClientRect();
189 if (rect.left < viewport.left) codeScroller.scrollLeft += rect.left - viewport.left - 16;
190 else if (rect.right > viewport.right)
191 codeScroller.scrollLeft += rect.right - viewport.right + 16;
192 }
193 const rect = range.getBoundingClientRect();
194 const viewport = container?.getBoundingClientRect();
195 if (!viewport || rect.height === 0) return;
196 const margin = Math.min(
197 FIND_MATCH_VIEW_MARGIN,
198 Math.max(0, (viewport.height - contentInsetEndAdjustment - rect.height) / 2),
199 );
200 const top = viewport.top + margin;
201 const bottom = viewport.bottom - margin - contentInsetEndAdjustment;
202 const delta =
203 rect.top < top ? rect.top - top : rect.bottom > bottom ? rect.bottom - bottom : 0;
204 // A new list can expose DOM text before its virtual row sizes settle.
205 // Await row positioning before measuring an offscreen occurrence.
206 if (
207 Math.abs(delta) >= 1 &&
208 positionedEntriesRef.current !== entries &&
209 settledMatchRef.current !== matchKey
210 ) {
211 materialize();
212 return;
213 }
214 const scroll = listRef.current?.getState?.().scroll;
215 positionedEntriesRef.current = entries;
216
217 revealedMatchRef.current = matchKey;
218 if (historyControls?.loading)
219 pagingPositionRef.current = { key: matchKey, entries, top: rect.top - delta };
220 if (Math.abs(delta) >= 1 && typeof scroll === "number") {
221 listRef.current?.scrollToOffset({ offset: scroll + delta, animated: false });
222 requestAnimationFrame(() => {
223 if (currentMatchKeyRef.current !== matchKey) return;
224 if (
225 listRef.current?.getState?.().scroll === scroll &&
226 range.getBoundingClientRect().top === rect.top
227 )
228 return;
229 revealedMatchRef.current = null;
230 revealRef.current(activeRangeRef.current);
231 });
232 }
233 },
234 [
235 container,
236 contentInsetEndAdjustment,
237 entries,
238 historyControls?.loading,
239 historyControls?.error,
240 listRef,
241 listReady,
242 matchKey,
243 rowIndex,
244 ],
245 );
246
247 useLayoutEffect(() => {
248 revealRef.current = reveal;
249 }, [reveal]);
250
251 useThreadFindHighlights({
252 container,
253 query,
254 activeRowId: match?.entryId ?? null,
255 activeOccurrence: match?.occurrence ?? 0,
256 onActiveRange: reveal,
257 });
258}