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

useThreadFind.ts

413 lines13.6 KB

1import type { InlineSkill } from "@t3tools/shared/inlineSkills";
2import type { OrchestrationV2SearchThreadResult, ScopedThreadRef } from "@t3tools/contracts";
3import { scopedThreadKey } from "@t3tools/client-runtime/environment";
4import { useEffect, useLayoutEffect, useRef, useState, type RefObject } from "react";
5import { useStableCallback } from "~/hooks/useStableCallback";
6import { orchestrationEnvironment } from "~/state/orchestration";
7import { useThreadProjection } from "~/state/entities";
8import { useEnvironmentQuery } from "~/state/query";
9import { useDebouncedValue } from "~/state/queries";
10import {
11 type ThreadFindPositionReader,
12 type ThreadFindStart,
13 stepThreadFindIndex,
14} from "./threadFind";
15import { subscribeThreadFindOpen } from "./threadFindActionBus";
16import { toastManager } from "../ui/toast";
17​
18const EMPTY_SKILLS: readonly InlineSkill[] = [];
19​
20const CLOSED_FIND = {
21 threadKey: null as string | null,
22 query: "",
23 offset: 0,
24 start: undefined as ThreadFindStart | undefined,
25 focusRequestId: 0,
26 navigationId: 0,
27 requestId: 0,
28 localSelection: null as {
29 base: OrchestrationV2SearchThreadResult;
30 baseNavigationId: number;
31 activeIndex: number;
32 match: NonNullable<OrchestrationV2SearchThreadResult["match"]>;
33 navigationId: number;
34 } | null,
35};
36​
37export function useThreadFind({
38 thread,
39 enabled,
40 progressive = false,
41 skills = EMPTY_SKILLS,
42}: {
43 thread: ScopedThreadRef | null;
44 enabled: boolean;
45 progressive?: boolean;
46 skills?: readonly InlineSkill[];
47}) {
48 // Read here rather than passed in: a streamed delta re-renders only the find
49 // provider, which refreshes open results from it.
50 const content = useThreadProjection(enabled ? thread : null)?.projection;
51 // Held in state so the timeline props that carry it can be stored in state too.
52 const [positionReader] = useState<RefObject<ThreadFindPositionReader | null>>(() => ({
53 current: null,
54 }));
55 const lastContentRef = useRef(content);
56 const refreshTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
57 const refreshAfterSearchRef = useRef(false);
58 const threadKey = thread ? scopedThreadKey(thread) : null;
59 const [state, setState] = useState(CLOSED_FIND);
60 if (state.threadKey !== null && (!enabled || state.threadKey !== threadKey))
61 setState(CLOSED_FIND);
62 const isOpen = enabled && threadKey !== null && state.threadKey === threadKey;
63 const open = useStableCallback(() => {
64 if (threadKey === null) return;
65 if (!enabled) {
66 toastManager.add({
67 id: "thread-find-unavailable",
68 title: "Thread search is unavailable on this server.",
69 description: "Update the server to enable it.",
70 });
71 return;
72 }
73 const start =
74 state.threadKey === threadKey && state.query.trim()
75 ? positionReader.current?.(state.query.trim())
76 : undefined;
77 setState((previous) => {
78 const current = previous.threadKey === threadKey ? previous : CLOSED_FIND;
79 return {
80 ...current,
81 threadKey,
82 focusRequestId: previous.focusRequestId + 1,
83 ...(current.query.trim()
84 ? {
85 start,
86 offset: 0,
87 localSelection: null,
88 navigationId: current.navigationId + 1,
89 requestId: current.navigationId + 1,
90 }
91 : {}),
92 };
93 });
94 });
95 const close = useStableCallback(() => setState(CLOSED_FIND));
96 useEffect(() => subscribeThreadFindOpen(open), [open]);
97​
98 const remote = useServerResults(
99 isOpen ? thread : null,
100 state.query,
101 state.offset,
102 state.requestId,
103 state.start,
104 skills,
105 progressive,
106 );
107 const status: "loading" | "error" | null = remote.error
108 ? "error"
109 : remote.isPending && remote.data === null
110 ? "loading"
111 : null;
112 const localSelection = rebaseLocalSelection(
113 state.localSelection,
114 remote.data,
115 remote.navigationId,
116 );
117 const count = remote.data?.totalMatches ?? 0;
118 const activeIndex = localSelection?.activeIndex ?? remote.data?.activeIndex ?? 0;
119 const selectedMatch = localSelection?.match ?? remote.data?.match;
120 const entryId = selectedMatch?.entryId;
121 const runId = selectedMatch?.runId;
122 const occurrence = selectedMatch?.occurrence;
123 const counting = remote.data?.complete === false;
124 const navigationId = localSelection?.navigationId ?? remote.navigationId;
125 const findExpanded = isOpen && state.query.trim().length > 0;
126 const findQuery = isOpen && remote.data?.match ? state.query : "";
127 const nextTimeline = {
128 findOpen: isOpen,
129 findExpanded,
130 findQuery,
131 activeFindMatch:
132 entryId !== undefined && occurrence !== undefined
133 ? { entryId, runId: runId ?? null, occurrence }
134 : null,
135 findNavigationId: navigationId,
136 };
137 // Finishing the count or a pending response must not rerender the timeline or
138 // request another jump, so these keep their identity until a field changes.
139 const [storedTimeline, setTimeline] = useState(() => ({
140 fields: nextTimeline,
141 props: { ...nextTimeline, findPositionReaderRef: positionReader },
142 }));
143 let timeline = storedTimeline;
144 if (!sameTimeline(timeline.fields, nextTimeline)) {
145 timeline = {
146 fields: nextTimeline,
147 props: { ...nextTimeline, findPositionReaderRef: positionReader },
148 };
149 setTimeline(timeline);
150 }
151 const match = timeline.fields.activeFindMatch;
152 const step = (delta: number) => {
153 if (count === 0 || counting) return;
154 setState((previous) => {
155 const local = rebaseLocalSelection(previous.localSelection, remote.data, remote.navigationId);
156 const pending = previous.navigationId !== (local?.navigationId ?? remote.navigationId);
157 const selected = local?.match ?? remote.data?.match;
158 const nextIndex = stepThreadFindIndex(
159 local?.activeIndex ?? remote.data?.activeIndex ?? 0,
160 count,
161 delta,
162 );
163 const entry = remote.data?.navigation?.find(
164 (entry) => nextIndex >= entry.startIndex && nextIndex < entry.startIndex + entry.count,
165 );
166 const nextNavigationId = previous.navigationId + 1;
167 if (
168 !pending &&
169 !remote.isPending &&
170 entry &&
171 remote.data &&
172 (!local ||
173 local.base === remote.data ||
174 remote.data.navigation?.some(
175 (entry) =>
176 entry.entryId === local.match.entryId && local.match.occurrence < entry.count,
177 )) &&
178 refreshTimerRef.current === null &&
179 lastContentRef.current === content
180 ) {
181 return {
182 ...previous,
183 navigationId: nextNavigationId,
184 localSelection: {
185 base: remote.data,
186 baseNavigationId: remote.navigationId,
187 activeIndex: nextIndex,
188 match: {
189 entryId: entry.entryId,
190 runId: entry.runId,
191 occurrence: nextIndex - entry.startIndex,
192 },
193 navigationId: nextNavigationId,
194 },
195 };
196 }
197 return {
198 ...previous,
199 start:
200 pending || !selected
201 ? previous.start
202 : { entryId: selected.entryId, occurrence: selected.occurrence },
203 offset: pending ? previous.offset + delta : delta,
204 navigationId: nextNavigationId,
205 requestId: nextNavigationId,
206 };
207 });
208 };
209​
210 const refreshLiveResultsRef = useRef(() => {});
211 useLayoutEffect(() => {
212 refreshLiveResultsRef.current = () => {
213 if (!isOpen || !state.query.trim()) return;
214 // Paging can change client content while the server is still counting.
215 // Coalesce those updates instead of repeatedly restarting the scan.
216 if (progressive && remote.isPending) {
217 refreshAfterSearchRef.current = true;
218 return;
219 }
220 if (!match || state.navigationId !== navigationId) {
221 remote.refresh();
222 return;
223 }
224 const start = { entryId: match.entryId, occurrence: match.occurrence };
225 if (
226 state.offset === 0 &&
227 state.start?.entryId === start.entryId &&
228 state.start.occurrence === start.occurrence &&
229 state.requestId === state.navigationId
230 ) {
231 remote.refresh();
232 } else {
233 setState((previous) => ({
234 ...previous,
235 start,
236 offset: 0,
237 requestId: previous.navigationId,
238 }));
239 }
240 };
241 });
242 useEffect(() => {
243 if (!refreshAfterSearchRef.current || remote.isPending) return;
244 refreshAfterSearchRef.current = false;
245 if (!remote.error) refreshLiveResultsRef.current();
246 }, [remote.isPending, remote.error]);
247 useEffect(() => {
248 if (lastContentRef.current === content) return;
249 lastContentRef.current = content;
250 if (!isOpen || !state.query.trim() || refreshTimerRef.current !== null) return;
251 refreshTimerRef.current = setTimeout(() => {
252 refreshTimerRef.current = null;
253 refreshLiveResultsRef.current();
254 }, 300);
255 }, [content, isOpen, state.query]);
256 useEffect(() => {
257 if (!isOpen || threadKey === null || !state.query.trim()) return;
258 return () => {
259 if (refreshTimerRef.current !== null) clearTimeout(refreshTimerRef.current);
260 refreshTimerRef.current = null;
261 refreshAfterSearchRef.current = false;
262 };
263 }, [threadKey, isOpen, state.query]);
264​
265 return {
266 isOpen,
267 open,
268 close,
269 barProps: {
270 open: isOpen,
271 query: state.query,
272 matchCount: count,
273 counting,
274 activeIndex,
275 status,
276 focusRequestId: state.focusRequestId,
277 onRetry: remote.refresh,
278 onQueryChange: (query: string) => {
279 const start = positionReader.current?.(query.trim());
280 setState((previous) => ({
281 ...previous,
282 query,
283 offset: 0,
284 start,
285 localSelection: null,
286 navigationId: previous.navigationId + 1,
287 requestId: previous.navigationId + 1,
288 }));
289 },
290 onNext: () => step(1),
291 onPrevious: () => step(-1),
292 onClose: close,
293 },
294 timelineProps: timeline.props,
295 };
297​
298type TimelineFields = Omit<
299 ReturnType<typeof useThreadFind>["timelineProps"],
300 "findPositionReaderRef"
301>;
302​
303function sameTimeline(a: TimelineFields, b: TimelineFields) {
304 const aMatch = a.activeFindMatch;
305 const bMatch = b.activeFindMatch;
306 return (
307 a.findOpen === b.findOpen &&
308 a.findExpanded === b.findExpanded &&
309 a.findQuery === b.findQuery &&
310 a.findNavigationId === b.findNavigationId &&
311 (aMatch === null || bMatch === null
312 ? aMatch === bMatch
313 : aMatch.entryId === bMatch.entryId &&
314 aMatch.runId === bMatch.runId &&
315 aMatch.occurrence === bMatch.occurrence)
316 );
318​
319function rebaseLocalSelection(
320 selection: typeof CLOSED_FIND.localSelection,
321 data: OrchestrationV2SearchThreadResult | null,
322 navigationId: number,
323) {
324 if (!selection || !data) return null;
325 if (selection.base === data && selection.baseNavigationId === navigationId) return selection;
326 if (navigationId >= selection.navigationId) return null;
327 const entry = data.navigation?.find((entry) => entry.entryId === selection.match.entryId);
328 if (!entry || selection.match.occurrence >= entry.count) return selection;
329 const activeIndex = entry.startIndex + selection.match.occurrence;
330 return activeIndex === selection.activeIndex ? selection : { ...selection, activeIndex };
332​
333function useServerResults(
334 thread: ScopedThreadRef | null,
335 query: string,
336 offset: number,
337 navigationId: number,
338 start: ThreadFindStart | undefined,
339 skills: readonly InlineSkill[],
340 progressive: boolean,
341) {
342 const skillLabels = skills.map(({ name, displayName }) => ({ name, displayName }));
343 const normalizedQuery = query.trim();
344 const debouncedQuery = useDebouncedValue(normalizedQuery, 100);
345 const environmentId = thread?.environmentId;
346 const threadId = thread?.threadId;
347 const target =
348 environmentId && threadId && debouncedQuery && normalizedQuery === debouncedQuery
349 ? {
350 environmentId,
351 input: {
352 threadId,
353 query: debouncedQuery,
354 ...(start ? { start } : {}),
355 ...(offset !== 0 ? { offset } : {}),
356 skills: skillLabels,
357 },
358 }
359 : null;
360 const targetKey = target ? JSON.stringify([progressive, target]) : null;
361 // Resolving the atom only when the request changes keeps unrelated renders from
362 // touching the atom family.
363 const [storedAtom, setStoredAtom] = useState(() => ({
364 key: targetKey,
365 atom: resolveThreadFindAtom(target, progressive),
366 }));
367 let atom = storedAtom.atom;
368 if (storedAtom.key !== targetKey) {
369 atom = resolveThreadFindAtom(target, progressive);
370 setStoredAtom({ key: targetKey, atom });
371 }
372 const result = useEnvironmentQuery(atom);
373 const key = thread
374 ? JSON.stringify([thread.environmentId, thread.threadId, normalizedQuery, skillLabels])
375 : null;
376 const [previous, setPrevious] = useState({
377 key,
378 data: result.data,
379 navigationId,
380 });
381 if (
382 previous.key !== key ||
383 (result.data !== null &&
384 (!result.isPending || (progressive && previous.data !== result.data)) &&
385 (previous.data !== result.data || previous.navigationId !== navigationId))
386 ) {
387 const response = result.data;
388 setPrevious({
389 key,
390 data: response,
391 navigationId,
392 });
393 }
394 return {
395 ...result,
396 data: key === previous.key && !result.error ? previous.data : null,
397 navigationId: previous.navigationId,
398 isPending:
399 thread !== null &&
400 normalizedQuery.length > 0 &&
401 (normalizedQuery !== debouncedQuery || result.isPending),
402 };
404​
405function resolveThreadFindAtom(
406 target: Parameters<typeof orchestrationEnvironment.threadFind>[0] | null,
407 progressive: boolean,
408) {
409 if (!target) return null;
410 return progressive
411 ? orchestrationEnvironment.threadFindProgressive(target)
412 : orchestrationEnvironment.threadFind(target);