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

useThreadFindNavigation.ts

309 lines10.3 KB

1import type { LegendListRef } from "@legendapp/list/react";
2import { useEffect, useEffectEvent, useRef, type RefObject } from "react";
3import type { ThreadFindMatch } from "./threadFind";
4import { useThreadFindHighlights } from "./threadFindHighlights";
5​
6const FIND_MATCH_VIEW_MARGIN = 96;
7​
8type FindEntries = readonly { readonly id: string }[];
9​
10interface RevealInputs {
11 readonly matchKey: string | null;
12 readonly rowIndex: number;
13 readonly entries: FindEntries;
14 readonly listReady: boolean;
15 readonly historyLoading: boolean;
16 readonly historyError: string | null;
17 readonly contentInsetEndAdjustment: number;
18 readonly container: HTMLElement | null;
20​
21/** Positioning bookkeeping that outlives a render: pending jumps and the pinned match during paging. */
22interface RevealState {
23 positioning: { key: string; rowIndex: number; entries: FindEntries } | null;
24 settledMatch: string | null;
25 activeRange: Range | null;
26 pagingPosition: { key: string; entries: FindEntries; top: number } | null;
27 revealedMatch: string | null;
28 positionedEntries: FindEntries | null;
30​
31/**
32 * Brings the active match into view. Async continuations re-enter with the
33 * inputs current by then, and stop once the match changes or the list unmounts.
34 */
35function revealThreadFindMatch(
36 range: Range | null,
37 inputs: RevealInputs,
38 context: {
39 readonly state: RevealState;
40 readonly listRef: RefObject<LegendListRef | null>;
41 readonly readInputs: () => RevealInputs;
42 },
43): void {
44 const { state, listRef, readInputs } = context;
45 const {
46 matchKey,
47 rowIndex,
48 entries,
49 listReady,
50 historyLoading,
51 historyError,
52 contentInsetEndAdjustment,
53 container,
54 } = inputs;
55 state.activeRange = range;
56 if (!matchKey) {
57 state.positioning = null;
58 state.settledMatch = null;
59 state.revealedMatch = null;
60 state.pagingPosition = null;
61 return;
62 }
63 const list = listRef.current;
64 const stillCurrent = () =>
65 list !== null && listRef.current === list && readInputs().matchKey === matchKey;
66 const revealAgain = () => revealThreadFindMatch(state.activeRange, readInputs(), context);
67 const pagingPosition = state.pagingPosition;
68 if (pagingPosition && pagingPosition.key !== matchKey) state.pagingPosition = null;
69 if (
70 range?.startContainer.isConnected &&
71 pagingPosition?.key === matchKey &&
72 pagingPosition.entries !== entries
73 ) {
74 const restore = () => {
75 const pinned = state.pagingPosition;
76 const currentRange = state.activeRange;
77 if (!stillCurrent() || !pinned || !currentRange?.startContainer.isConnected) return;
78 const delta = currentRange.getBoundingClientRect().top - pinned.top;
79 const scroll = listRef.current?.getState?.().scroll;
80 if (Math.abs(delta) >= 1 && typeof scroll === "number")
81 listRef.current?.scrollToOffset({ offset: scroll + delta, animated: false });
82 };
83 pagingPosition.entries = entries;
84 restore();
85 // The list measures newly inserted activity after the first layout pass.
86 requestAnimationFrame(() =>
87 requestAnimationFrame(() => {
88 restore();
89 if (!readInputs().historyLoading && state.pagingPosition === pagingPosition)
90 state.pagingPosition = null;
91 }),
92 );
93 }
94 if (historyError) state.pagingPosition = null;
95 if (state.revealedMatch === matchKey) return;
96 if (!listReady || rowIndex < 0) return;
97 const materialize = () => {
98 const previous = state.positioning;
99 if (
100 !list ||
101 (previous?.key === matchKey && previous.rowIndex === rowIndex && previous.entries === entries)
102 )
103 return;
104 // Activity can insert rows during LegendList layout; retarget pending jumps.
105 const request = { key: matchKey, rowIndex, entries };
106 state.positioning = request;
107​
108 void list
109 .scrollToIndex({
110 index: rowIndex,
111 animated: false,
112 viewOffset: FIND_MATCH_VIEW_MARGIN,
113 })
114 .then(() => {
115 if (state.positioning !== request || !stillCurrent()) return;
116​
117 state.positionedEntries = entries;
118 state.settledMatch = matchKey;
119 revealAgain();
120 });
121 };
122 if (!range) {
123 if (container) materialize();
124 return;
125 }
126​
127 const codeScroller = range.startContainer.parentElement?.closest("pre");
128 if (codeScroller) {
129 const rect = range.getBoundingClientRect();
130 const viewport = codeScroller.getBoundingClientRect();
131 if (rect.left < viewport.left) codeScroller.scrollLeft += rect.left - viewport.left - 16;
132 else if (rect.right > viewport.right)
133 codeScroller.scrollLeft += rect.right - viewport.right + 16;
134 }
135 const rect = range.getBoundingClientRect();
136 const viewport = container?.getBoundingClientRect();
137 if (!viewport || rect.height === 0) return;
138 const margin = Math.min(
139 FIND_MATCH_VIEW_MARGIN,
140 Math.max(0, (viewport.height - contentInsetEndAdjustment - rect.height) / 2),
141 );
142 const top = viewport.top + margin;
143 const bottom = viewport.bottom - margin - contentInsetEndAdjustment;
144 const delta = rect.top < top ? rect.top - top : rect.bottom > bottom ? rect.bottom - bottom : 0;
145 // DOM text can precede settled row sizes; wait before measuring offscreen matches.
146 if (
147 Math.abs(delta) >= 1 &&
148 state.positionedEntries !== entries &&
149 state.settledMatch !== matchKey
150 ) {
151 materialize();
152 return;
153 }
154 const scroll = list?.getState?.().scroll;
155 state.positionedEntries = entries;
156​
157 state.revealedMatch = matchKey;
158 if (historyLoading) state.pagingPosition = { key: matchKey, entries, top: rect.top - delta };
159 if (Math.abs(delta) >= 1 && typeof scroll === "number") {
160 list?.scrollToOffset({ offset: scroll + delta, animated: false });
161 requestAnimationFrame(() => {
162 if (!stillCurrent()) return;
163 if (
164 listRef.current?.getState?.().scroll === scroll &&
165 range.getBoundingClientRect().top === rect.top
166 )
167 return;
168 state.revealedMatch = null;
169 revealAgain();
170 });
171 }
173​
174export function useThreadFindNavigation({
175 container,
176 query,
177 match,
178 navigationId,
179 rowIndex,
180 entries,
181 listRef,
182 contentInsetEndAdjustment,
183 listReady,
184 historyControls,
185}: {
186 container: HTMLElement | null;
187 query: string;
188 match: ThreadFindMatch | null;
189 navigationId: number;
190 rowIndex: number;
191 entries: FindEntries;
192 listRef: RefObject<LegendListRef | null>;
193 contentInsetEndAdjustment: number;
194 listReady: boolean;
195 historyControls?:
196 | {
197 readonly hasMoreHistory: boolean;
198 readonly loading: boolean;
199 readonly error: string | null;
200 readonly onLoadEarlier: (throughEntryId?: string) => void;
201 }
202 | undefined;
203}) {
204 const matchKey = match ? `${navigationId}:${query}:${match.entryId}:${match.occurrence}` : null;
205 const historyLoading = historyControls?.loading ?? false;
206 const historyError = historyControls?.error ?? null;
207 const stateRef = useRef<RevealState>({
208 positioning: null,
209 settledMatch: null,
210 activeRange: null,
211 pagingPosition: null,
212 revealedMatch: null,
213 positionedEntries: null,
214 });
215 const readInputs = useEffectEvent((): RevealInputs => ({
216 matchKey,
217 rowIndex,
218 entries,
219 listReady,
220 historyLoading,
221 historyError,
222 contentInsetEndAdjustment,
223 container,
224 }));
225 // H/Z: stays an effect. The listener compares against the entries rendered at
226 // scroll time; the viewport ref callback in MessagesTimeline cannot read
227 // them without a latest-ref mirror, and capturing them would re-attach the
228 // viewport (observers, citation dismissal) on every streamed entry.
229 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- attaches a scroll listener to the timeline container to track the active match position
230 useEffect(() => {
231 if (!container) return;
232 const onScroll = () => {
233 const state = stateRef.current;
234 const position = state.pagingPosition;
235 const range = state.activeRange;
236 if (
237 !position ||
238 position.entries !== readInputs().entries ||
239 !range?.startContainer.isConnected
240 )
241 return;
242 const rect = range.getBoundingClientRect();
243 const viewport = container.getBoundingClientRect();
244 if (rect.bottom < viewport.top || rect.top > viewport.bottom) state.pagingPosition = null;
245 else position.top = rect.top;
246 };
247 container.addEventListener("scroll", onScroll, { passive: true });
248 return () => container.removeEventListener("scroll", onScroll);
249 }, [container]);
250 const requestedPagesRef = useRef<{ key: string | null; pages: Set<string> }>({
251 key: null,
252 pages: new Set(),
253 });
254 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- requests earlier history pages until the active match's entry is loaded
255 useEffect(() => {
256 if (requestedPagesRef.current.key !== matchKey)
257 requestedPagesRef.current = { key: matchKey, pages: new Set() };
258 if (
259 !match ||
260 !listReady ||
261 rowIndex >= 0 ||
262 entries.some((entry) => entry.id === match.entryId)
263 )
264 return;
265 if (!historyControls?.hasMoreHistory || historyControls.loading || historyControls.error)
266 return;
267 const cursor = entries[0]?.id ?? "first";
268 if (requestedPagesRef.current.pages.has(cursor)) return;
269 requestedPagesRef.current.pages.add(cursor);
270​
271 historyControls.onLoadEarlier(match.entryId);
272 }, [entries, historyControls, listReady, match, matchKey, rowIndex]);
273 const reveal = useEffectEvent((range: Range | null, inputs: RevealInputs) =>
274 revealThreadFindMatch(range, inputs, { state: stateRef.current, listRef, readInputs }),
275 );
276​
277 useThreadFindHighlights({
278 container,
279 query,
280 activeRowId: match?.entryId ?? null,
281 activeOccurrence: match?.occurrence ?? 0,
282 onActiveRange: (range) => reveal(range, readInputs()),
283 });
284 // Positioning also depends on the list: a loaded page or a shifted row must
285 // retry the jump for the same selection. Declared after the highlight
286 // effects so it reuses the range they just resolved.
287 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- scrolls the list to the active match after commit when rows or the loaded page change
288 useEffect(() => {
289 reveal(stateRef.current.activeRange, {
290 matchKey,
291 rowIndex,
292 entries,
293 listReady,
294 historyLoading,
295 historyError,
296 contentInsetEndAdjustment,
297 container,
298 });
299 }, [
300 container,
301 matchKey,
302 rowIndex,
303 entries,
304 listReady,
305 historyLoading,
306 historyError,
307 contentInsetEndAdjustment,
308 ]);