Open History to see the last commit
1import { useEffect, useRef, useState } from "react";
2import { isInSideChatPane } from "../../lib/sideChatPane";
3import type { AssistantCitationRequest, AssistantCitationTarget } from "./AssistantCitationSource";
4import type { CitationPhase } from "./citationProcedure";
5
6const CITATION_SCROLL_KEYS = new Set([
7 "ArrowUp",
8 "ArrowDown",
9 "PageUp",
10 "PageDown",
11 "Home",
12 "End",
13 " ",
14]);
15
16/** One activation of a citation; virtual row remounts and listeners share it. */
17interface CitationNavigation {
18 readonly target: AssistantCitationTarget;
19 /** Takes over from the live follow for this activation. */
20 readonly activate: () => void;
21 /** Stops this activation for good once another one (or none) replaces it. */
22 readonly retire: () => void;
23 /** Listens for user navigation that stops this activation's pending scroll. */
24 readonly attachDismissal: (viewport: HTMLElement | null) => () => void;
25}
26
27interface CitationSettlement {
28 /** Per activation, not per key: Back/Forward can restore an earlier key. */
29 readonly target: AssistantCitationTarget;
30 /** Dismissed citations also drop their highlight; completed ones keep it. */
31 readonly dismissed: boolean;
32}
33
34export function useAssistantCitationTarget({
35 request,
36 phase,
37 viewport,
38 onManualNavigation,
39}: {
40 request: AssistantCitationRequest | null;
41 phase: CitationPhase | null;
42 viewport: HTMLElement | null;
43 onManualNavigation: () => void;
44}) {
45 const [settlement, setSettlement] = useState<CitationSettlement | null>(null);
46 const [listLoaded, setListLoaded] = useState(false);
47 const onListLoad = () => setListLoaded(true);
48
49 // Rows and listeners mutate the activation, so it lives as long as its
50 // request; a target belongs to one request, so returning to an earlier key
51 // never reuses it.
52 const [navigation, setNavigation] = useState<CitationNavigation | null>(null);
53 let current = navigation;
54 if ((request?.key ?? null) !== (navigation?.target.key ?? null)) {
55 current = request ? createCitationNavigation(request) : null;
56 setNavigation(current);
57 }
58 function createCitationNavigation(next: AssistantCitationRequest): CitationNavigation {
59 let done = false;
60 const activationRef: AssistantCitationTarget["activationRef"] = {
61 current: { scrolled: false, dismissed: false },
62 };
63 const target: AssistantCitationTarget = {
64 ...next,
65 activationRef,
66 onComplete: () => {
67 done = true;
68 // The thread-open follow can run after the scroll started.
69 onManualNavigation();
70 setSettlement({ target, dismissed: false });
71 },
72 };
73 const activate = () => {
74 // The follow must yield before the citation row starts scrolling.
75 if (!done) onManualNavigation();
76 };
77 const retire = () => {
78 activationRef.current.dismissed = true;
79 activationRef.current.cancelScroll?.();
80 };
81 const attachDismissal = (citationViewport: HTMLElement | null) => {
82 // User navigation stops a pending citation scroll; Escape dismisses it outright.
83 const dismiss = (onlyPending: boolean) => {
84 const activation = activationRef.current;
85 if (activation.dismissed || (onlyPending && (activation.scrolled || done))) return;
86 activation.dismissed = true;
87 activation.cancelScroll?.();
88 if (!activation.scrolled && !done) onManualNavigation();
89 done = true;
90 setSettlement({ target, dismissed: true });
91 };
92 const onKeyDown = (event: KeyboardEvent) => {
93 if (event.isComposing || event.keyCode === 229) return;
94 if (event.key === "Escape") {
95 // Find in Thread closes on window bubble after this document listener.
96 if (!event.defaultPrevented) {
97 const inSideChat = isInSideChatPane(event.target);
98 const findBars = document.querySelectorAll("[data-thread-find-bar]");
99 if (Array.from(findBars).some((bar) => isInSideChatPane(bar) === inSideChat)) return;
100 }
101 dismiss(false);
102 } else if (
103 CITATION_SCROLL_KEYS.has(event.key) &&
104 event.target instanceof Node &&
105 citationViewport?.contains(event.target)
106 ) {
107 dismiss(true);
108 }
109 };
110 const onWheel = (event: WheelEvent) => {
111 if (event.deltaY !== 0) dismiss(true);
112 };
113 const onNavigation = () => dismiss(true);
114 document.addEventListener("keydown", onKeyDown);
115 document.addEventListener("pointerdown", onNavigation, true);
116 citationViewport?.addEventListener("wheel", onWheel, { passive: true });
117 citationViewport?.addEventListener("touchmove", onNavigation, { passive: true });
118 return () => {
119 document.removeEventListener("keydown", onKeyDown);
120 document.removeEventListener("pointerdown", onNavigation, true);
121 citationViewport?.removeEventListener("wheel", onWheel);
122 citationViewport?.removeEventListener("touchmove", onNavigation);
123 };
124 };
125 return { target, activate, retire, attachDismissal };
126 }
127
128 // Retiring is one-way, so it runs when the activation is replaced rather than
129 // in a cleanup: StrictMode and <Activity> replay cleanups on a live activation.
130 // Unmounting needs no retire; the rows observing it unmount with the list.
131 const activatedRef = useRef<CitationNavigation | null>(null);
132 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- retires the replaced citation scroll and activates the new one, releasing the timeline follow
133 useEffect(() => {
134 if (activatedRef.current === current) return;
135 activatedRef.current?.retire();
136 activatedRef.current = current;
137 current?.activate();
138 }, [current]);
139 // Escape and pointerdown dismiss before the viewport mounts; the viewport
140 // listeners join once it exists.
141 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes document and viewport listeners that dismiss the pending citation scroll
142 useEffect(() => current?.attachDismissal(viewport), [current, viewport]);
143
144 const settled = current !== null && settlement?.target === current.target ? settlement : null;
145 const target =
146 current !== null && phase?._tag === "ready" && listLoaded && settled?.dismissed !== true
147 ? current.target
148 : null;
149 const positioning = current !== null && phase?._tag !== "failed" && settled === null;
150
151 return {
152 target,
153 positioning,
154 onListLoad,
155 alwaysRender:
156 target && positioning && phase?._tag === "ready" ? { keys: [phase.rowId] } : undefined,
157 };
158}