Open History to see the last commit
1import { useLayoutEffect, useRef } from "react";
2import type { LegendListRef } from "@legendapp/list/react";
3import type { AssistantCitationRequest } from "./AssistantCitationSource";
4import type { MessagesTimelineRow } from "./MessagesTimeline.logic";
5import type { RememberedTimelinePosition } from "./timelineScrollAnchoring";
6
7/**
8 * Scrolls a newly shown thread back to where the user left it, or to its end,
9 * and reports the thread positioned once the saved row settles.
10 */
11export function useTimelinePositionRestore({
12 listRef,
13 listIdentityKey,
14 restoringThreadPosition,
15 rememberedPosition,
16 rows,
17 citationRequest,
18 cancelPositionRestoreRef,
19 onManualNavigation,
20 onPositioned,
21}: {
22 readonly listRef: React.RefObject<LegendListRef | null>;
23 readonly listIdentityKey: string;
24 readonly restoringThreadPosition: boolean;
25 readonly rememberedPosition: RememberedTimelinePosition | undefined;
26 readonly rows: MessagesTimelineRow[];
27 readonly citationRequest: AssistantCitationRequest | null;
28 readonly cancelPositionRestoreRef: React.RefObject<(() => void) | null> | undefined;
29 readonly onManualNavigation: () => void;
30 readonly onPositioned: (identity: string) => void;
31}) {
32 // Preserve initialScrollAtEnd's measured target until the list is reused
33 // for another thread; scrollToEnd would replace it with an estimated offset.
34 const listOpenedOnRef = useRef<{
35 readonly list: LegendListRef;
36 identity: string | null;
37 } | null>(null);
38 useLayoutEffect(() => {
39 const list = listRef.current;
40 const opened = listOpenedOnRef.current;
41 if (!list) return;
42 if (opened?.list !== list) {
43 listOpenedOnRef.current = { list, identity: listIdentityKey };
44 } else if (opened.identity !== listIdentityKey) {
45 opened.identity = null;
46 }
47 });
48 useLayoutEffect(() => {
49 if (!restoringThreadPosition || rows.length === 0) return;
50 const list = listRef.current;
51 if (!list) return;
52 if (citationRequest !== null) {
53 // The citation scroll owns positioning once the list has mounted.
54 onPositioned(listIdentityKey);
55 return;
56 }
57 let cancelled = false;
58 let settleFrame: number | null = null;
59 const viewport: HTMLElement | null = list.getScrollableNode();
60 const cancelRestoration = () => {
61 if (cancelled) return;
62 cancelled = true;
63 if (settleFrame !== null) cancelAnimationFrame(settleFrame);
64 if (viewport) void list.scrollToOffset({ offset: viewport.scrollTop, animated: false });
65 onPositioned(listIdentityKey);
66 };
67 const cancelForNavigation = () => {
68 cancelRestoration();
69 onManualNavigation();
70 };
71 const onScrollKey = (event: globalThis.KeyboardEvent) => {
72 if (
73 ["ArrowUp", "ArrowDown", "PageUp", "PageDown", "Home", "End", " "].includes(event.key) &&
74 !(
75 event.target instanceof Element &&
76 event.target.closest("input, textarea, [contenteditable=true]")
77 )
78 )
79 cancelForNavigation();
80 };
81 viewport?.addEventListener("wheel", cancelForNavigation, { passive: true });
82 viewport?.addEventListener("touchmove", cancelForNavigation, { passive: true });
83 viewport?.addEventListener("pointerdown", cancelForNavigation, { passive: true });
84 viewport?.ownerDocument.addEventListener("keydown", onScrollKey);
85 const position = rememberedPosition;
86 const index = position ? rows.findIndex((row) => row.id === position.rowId) : -1;
87 if (position?.atEnd === false) onManualNavigation();
88 if (cancelPositionRestoreRef) cancelPositionRestoreRef.current = cancelRestoration;
89 const scrolling =
90 position?.atEnd === false
91 ? index >= 0
92 ? list.scrollToIndex({
93 index,
94 animated: false,
95 viewPosition: 0,
96 viewOffset: -position.offsetWithinRow,
97 })
98 : list.scrollToOffset({ offset: position.scrollOffset, animated: false })
99 : listOpenedOnRef.current?.identity === listIdentityKey
100 ? undefined
101 : list.scrollToEnd({ animated: false });
102 void Promise.resolve(scrolling).then(() => {
103 if (cancelled) return;
104 if (position?.atEnd !== false || index < 0) {
105 onPositioned(listIdentityKey);
106 return;
107 }
108 // Index scrolling starts from estimates. Keep the saved row mounted
109 // until its measured position and the DOM agree for two layout frames.
110 let stableFrames = 0;
111 const reconcile = () => {
112 if (cancelled) return;
113 const state = list.getState();
114 const rowIndex = state.indexByKey(position.rowId);
115 const row = rowIndex === undefined ? undefined : state.elementAtIndex(rowIndex);
116 const element = list.getScrollableNode();
117 if (!row || !element) return;
118 const offset = Math.max(
119 0,
120 Math.min(
121 element.scrollTop +
122 row.getBoundingClientRect().top -
123 element.getBoundingClientRect().top +
124 position.offsetWithinRow,
125 element.scrollHeight - element.clientHeight,
126 ),
127 );
128 if (Math.abs(element.scrollTop - offset) > 1) {
129 stableFrames = 0;
130 void list.scrollToOffset({ offset, animated: false }).then(() => {
131 if (!cancelled) settleFrame = requestAnimationFrame(reconcile);
132 });
133 return;
134 }
135 stableFrames += 1;
136 if (stableFrames >= 2) {
137 onPositioned(listIdentityKey);
138 } else {
139 settleFrame = requestAnimationFrame(reconcile);
140 }
141 };
142 settleFrame = requestAnimationFrame(reconcile);
143 });
144 return () => {
145 cancelled = true;
146 if (cancelPositionRestoreRef?.current === cancelRestoration) {
147 cancelPositionRestoreRef.current = null;
148 }
149 if (settleFrame !== null) cancelAnimationFrame(settleFrame);
150 viewport?.removeEventListener("wheel", cancelForNavigation);
151 viewport?.removeEventListener("touchmove", cancelForNavigation);
152 viewport?.removeEventListener("pointerdown", cancelForNavigation);
153 viewport?.ownerDocument.removeEventListener("keydown", onScrollKey);
154 };
155 }, [
156 citationRequest,
157 cancelPositionRestoreRef,
158 listIdentityKey,
159 listRef,
160 onManualNavigation,
161 onPositioned,
162 rememberedPosition,
163 restoringThreadPosition,
164 rows,
165 ]);
166}