Open History to see the last commit
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 while LegendList waits for layout. Retarget the
160 // pending jump instead of treating the first requested index as final.
161 const request = { key: matchKey, rowIndex, entries };
162 positioningRef.current = request;
163
164 void list
165 .scrollToIndex({
166 index: rowIndex,
167 animated: false,
168 viewOffset: FIND_MATCH_VIEW_MARGIN,
169 })
170 .then(() => {
171 if (positioningRef.current !== request || currentMatchKeyRef.current !== matchKey) return;
172
173 positionedEntriesRef.current = entries;
174 settledMatchRef.current = matchKey;
175 revealRef.current(activeRangeRef.current);
176 });
177 };
178 if (!range) {
179 if (container) materialize();
180 return;
181 }
182
183 const codeScroller = range.startContainer.parentElement?.closest("pre");
184 if (codeScroller) {
185 const rect = range.getBoundingClientRect();
186 const viewport = codeScroller.getBoundingClientRect();
187 if (rect.left < viewport.left) codeScroller.scrollLeft += rect.left - viewport.left - 16;
188 else if (rect.right > viewport.right)
189 codeScroller.scrollLeft += rect.right - viewport.right + 16;
190 }
191 const rect = range.getBoundingClientRect();
192 const viewport = container?.getBoundingClientRect();
193 if (!viewport || rect.height === 0) return;
194 const margin = Math.min(
195 FIND_MATCH_VIEW_MARGIN,
196 Math.max(0, (viewport.height - contentInsetEndAdjustment - rect.height) / 2),
197 );
198 const top = viewport.top + margin;
199 const bottom = viewport.bottom - margin - contentInsetEndAdjustment;
200 const delta = rect.top < top ? rect.top - top : rect.bottom > bottom ? rect.bottom - bottom : 0;
201 // A new list can expose DOM text before its virtual row sizes settle.
202 // Await row positioning before measuring an offscreen occurrence.
203 if (
204 Math.abs(delta) >= 1 &&
205 positionedEntriesRef.current !== entries &&
206 settledMatchRef.current !== matchKey
207 ) {
208 materialize();
209 return;
210 }
211 const scroll = listRef.current?.getState?.().scroll;
212 positionedEntriesRef.current = entries;
213
214 revealedMatchRef.current = matchKey;
215 if (historyControls?.loading)
216 pagingPositionRef.current = { key: matchKey, entries, top: rect.top - delta };
217 if (Math.abs(delta) >= 1 && typeof scroll === "number") {
218 listRef.current?.scrollToOffset({ offset: scroll + delta, animated: false });
219 requestAnimationFrame(() => {
220 if (currentMatchKeyRef.current !== matchKey) return;
221 if (
222 listRef.current?.getState?.().scroll === scroll &&
223 range.getBoundingClientRect().top === rect.top
224 )
225 return;
226 revealedMatchRef.current = null;
227 revealRef.current(activeRangeRef.current);
228 });
229 }
230 };
231
232 useLayoutEffect(() => {
233 revealRef.current = reveal;
234 }, [reveal]);
235
236 useThreadFindHighlights({
237 container,
238 query,
239 activeRowId: match?.entryId ?? null,
240 activeOccurrence: match?.occurrence ?? 0,
241 onActiveRange: reveal,
242 });
243}