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

useAssistantCitationTarget.ts

195 lines6.7 KB

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