@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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