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

useAssistantCitationTarget.ts

190 lines6.6 KB

1import type { LegendListRef } from "@legendapp/list/react";
2import type { RunId } from "@t3tools/contracts";
3import { useCallback, useEffect, useRef, useState, type RefObject } from "react";
4import type { TimelineEntry } from "../../session-logic";
5import type { MessagesTimelineRow } from "./MessagesTimeline.logic";
6import type { AssistantCitationRequest, AssistantCitationTarget } from "./AssistantCitationSource";
7import { toastManager } from "../ui/toast";
8​
9export interface CitationHistoryPage {
10 readonly loading: boolean;
11 readonly cursor?: string | null;
12 readonly onLoadEarlier: () => void;
14​
15export function useAssistantCitationTarget({
16 request,
17 entries,
18 rows,
19 listRef,
20 viewport,
21 historyLoading,
22 loadEarlier,
23 onExpandTurn,
24 onManualNavigation,
25}: {
26 request: AssistantCitationRequest | null;
27 entries: ReadonlyArray<TimelineEntry>;
28 rows: ReadonlyArray<MessagesTimelineRow>;
29 listRef: RefObject<LegendListRef | null>;
30 viewport: HTMLElement | null;
31 historyLoading: boolean;
32 loadEarlier: CitationHistoryPage | null;
33 onExpandTurn: (runId: RunId) => void;
34 onManualNavigation: () => void;
35}) {
36 const [ready, setReady] = useState<AssistantCitationTarget | null>(null);
37 const [finishedKey, setFinishedKey] = useState<string | null>(null);
38 const [listLoaded, setListLoaded] = useState(false);
39 const onListLoad = useCallback(() => setListLoaded(true), []);
40 const navigationRef = useRef<{
41 target: AssistantCitationTarget;
42 requestedPages: Set<string>;
43 done: boolean;
44 } | null>(null);
45​
46 useEffect(() => {
47 if (navigationRef.current && navigationRef.current.target.key !== request?.key) {
48 navigationRef.current.target.activationRef.current.dismissed = true;
49 navigationRef.current.target.activationRef.current.cancelScroll?.();
50 }
51 if (!request) {
52 navigationRef.current = null;
53 setReady(null);
54 setFinishedKey(null);
55 return;
56 }
57 if (navigationRef.current?.target.key !== request.key) {
58 const target: AssistantCitationTarget = {
59 ...request,
60 activationRef: { current: { scrolled: false, dismissed: false } },
61 onComplete: () => {
62 if (navigationRef.current?.target !== target) return;
63 navigationRef.current.done = true;
64 // ChatView's thread-open effect can run after our initial opt-out.
65 onManualNavigation();
66 setFinishedKey(target.key);
67 },
68 };
69 navigationRef.current = {
70 target,
71 requestedPages: new Set(),
72 done: false,
73 };
74 setReady(null);
75 onManualNavigation();
76 }
77 if (!viewport || historyLoading) return;
78 const navigation = navigationRef.current;
79 if (navigation.done || navigation.target.activationRef.current.dismissed) return;
80 const fail = (title: string, description: string) => {
81 navigation.done = true;
82 setFinishedKey(navigation.target.key);
83 toastManager.add({ type: "warning", title, description });
84 };
85 const source = entries.find(
86 (entry) =>
87 entry.kind === "message" && entry.message.id === navigation.target.citation.messageId,
88 );
89 if (!source) {
90 if (loadEarlier) {
91 if (loadEarlier.loading) return;
92 const cursor = loadEarlier.cursor ?? entries[0]?.id ?? "first";
93 if (navigation.requestedPages.has(cursor) || navigation.requestedPages.size >= 20) {
94 fail(
95 "Could not load the cited response",
96 "Load earlier turns, then click the citation to try again. Your saved quote is unchanged.",
97 );
98 return;
99 }
100 navigation.requestedPages.add(cursor);
101 loadEarlier.onLoadEarlier();
102 return;
103 }
104 fail(
105 "The cited response is unavailable",
106 "It may have been removed. The selected text is still saved in your citation.",
107 );
108 return;
109 }
110 if (source.kind !== "message" || source.message.role !== "assistant") {
111 fail(
112 "The citation does not refer to an assistant response",
113 "The selected text is still saved in your citation.",
114 );
115 return;
116 }
117 const index = rows.findIndex(
118 (row) => row.kind === "message" && row.message.id === navigation.target.citation.messageId,
119 );
120 if (index < 0) {
121 if (source.message.runId) onExpandTurn(source.message.runId);
122 return;
123 }
124 if (listLoaded && listRef.current) setReady(navigation.target);
125 }, [
126 entries,
127 historyLoading,
128 listLoaded,
129 listRef,
130 loadEarlier,
131 onExpandTurn,
132 onManualNavigation,
133 request,
134 rows,
135 viewport,
136 ]);
137​
138 useEffect(() => {
139 if (!request) return;
140 const dismiss = (onlyPending: boolean) => {
141 const navigation = navigationRef.current;
142 if (!navigation || navigation.target.key !== request.key) return;
143 const activation = navigation.target.activationRef.current;
144 if (activation.dismissed || (onlyPending && (activation.scrolled || navigation.done))) return;
145 activation.dismissed = true;
146 activation.cancelScroll?.();
147 if (!activation.scrolled && !navigation.done) onManualNavigation();
148 navigation.done = true;
149 setReady(null);
150 setFinishedKey(request.key);
151 };
152 const onKeyDown = (event: KeyboardEvent) => {
153 if (event.key === "Escape") {
154 dismiss(false);
155 } else if (
156 viewport?.contains(event.target as Node) &&
157 ["ArrowUp", "ArrowDown", "PageUp", "PageDown", "Home", "End", " "].includes(event.key)
158 ) {
159 dismiss(true);
160 }
161 };
162 const onWheel = (event: WheelEvent) => {
163 if (event.deltaY !== 0) dismiss(true);
164 };
165 const onNavigation = () => dismiss(true);
166 document.addEventListener("keydown", onKeyDown);
167 document.addEventListener("pointerdown", onNavigation, true);
168 viewport?.addEventListener("wheel", onWheel, { passive: true });
169 viewport?.addEventListener("touchmove", onNavigation, { passive: true });
170 return () => {
171 document.removeEventListener("keydown", onKeyDown);
172 document.removeEventListener("pointerdown", onNavigation, true);
173 viewport?.removeEventListener("wheel", onWheel);
174 viewport?.removeEventListener("touchmove", onNavigation);
175 };
176 }, [onManualNavigation, request, viewport]);
177​
178 const target = ready?.key === request?.key ? ready : null;
179 const positioning = request !== null && finishedKey !== request.key;
180 const sourceRow =
181 target && positioning
182 ? rows.find((row) => row.kind === "message" && row.message.id === target.citation.messageId)
183 : undefined;
184 return {
185 target,
186 positioning,
187 onListLoad,
188 alwaysRender: sourceRow ? { keys: [sourceRow.id] } : undefined,
189 };