@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 284 lines 11.4 KB
Raw
1 import { readHtmlRenderContentHeight } from "@t3tools/shared/htmlRender";
2
3 import { isInSideChatPane } from "../../lib/sideChatPane";
4 import { registerCommands } from "../../shortcuts/dispatcher";
5 import {
6 eventPathContainsSelector,
7 TYPE_TO_FOCUS_EDITABLE_SELECTOR,
8 TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR,
9 } from "./composerFocusRedirect";
10 import { resolveTimelineIsAtEnd } from "./MessagesTimeline.logic";
11 import { createUpwardScrollDetector, isTimelineScrollTarget } from "./timelineScrollTarget";
12
13 /**
14 * Which thread the mounted timeline list opened on. LegendList's
15 * initialScrollAtEnd only measures for that thread; once the same list shows
16 * another thread the opening no longer applies, even if it later returns.
17 */
18 export type TimelineListOpening =
19 | { readonly mounted: false }
20 | { readonly mounted: true; readonly identity: string | null };
21
22 export function nextListOpening(
23 current: TimelineListOpening,
24 listMounted: boolean,
25 identity: string,
26 ): TimelineListOpening {
27 if (!listMounted) return current.mounted ? { mounted: false } : current;
28 if (!current.mounted) return { mounted: true, identity };
29 if (current.identity !== null && current.identity !== identity) {
30 return { mounted: true, identity: null };
31 }
32 return current;
33 }
34
35 export type TimelineScrollDirection = "up" | "down";
36
37 /**
38 * One user attempt to move the timeline. Gestures come from the viewport's own
39 * listeners; "command" is a UI action that is about to move it (minimap,
40 * citation, composer page keys, scroll to end).
41 */
42 export type TimelineNavigation =
43 | { readonly source: "wheel"; readonly direction: TimelineScrollDirection }
44 | { readonly source: "touch" }
45 | { readonly source: "pointer"; readonly onScrollbar: boolean }
46 | { readonly source: "key"; readonly key: string; readonly direction: TimelineScrollDirection }
47 | { readonly source: "scroll" }
48 | { readonly source: "command"; readonly releasesFollow: boolean };
49
50 export interface TimelineViewport {
51 readonly scrollNode: HTMLElement;
52 /** Every consumer hears the same navigation, in subscription order. */
53 readonly subscribe: (listener: (navigation: TimelineNavigation) => void) => () => void;
54 readonly navigate: (options: { readonly releasesFollow: boolean }) => void;
55 /**
56 * Marks our own scrolling (anchoring a turn, restoring a position) so the
57 * upward scroll it causes is not read as the user's. Returns the release.
58 */
59 readonly holdProgrammaticScroll: () => () => void;
60 /** Follow announces letting go, so the list can remember it is reading history. */
61 readonly followReleased: () => void;
62 readonly onFollowReleased: (listener: () => void) => () => void;
63 }
64
65 const UP_KEYS = new Set(["PageUp", "Home", "ArrowUp"]);
66 const DOWN_KEYS = new Set(["PageDown", "End", "ArrowDown", " "]);
67 // Wide enough for an overlay scrollbar, which takes no layout space (macOS Firefox).
68 const SCROLLBAR_HIT_PX = 16;
69
70 /**
71 * Owns the timeline scroll node's input listeners for as long as the node is
72 * mounted, and turns them into one navigation signal.
73 */
74 export function attachTimelineViewport(
75 scrollNode: HTMLElement,
76 onFrameResize?: (frame: HTMLIFrameElement) => void,
77 ): TimelineViewport & {
78 readonly dispose: () => void;
79 } {
80 const listeners = new Set<(navigation: TimelineNavigation) => void>();
81 const followReleasedListeners = new Set<() => void>();
82 let programmaticHolds = 0;
83 const emit = (navigation: TimelineNavigation) => {
84 for (const listener of listeners) listener(navigation);
85 };
86 const handleWheel = (event: WheelEvent) => {
87 if (event.ctrlKey || !isTimelineScrollTarget(event.target, scrollNode, event.deltaY, event))
88 return;
89 emit({ source: "wheel", direction: event.deltaY < 0 ? "up" : "down" });
90 };
91 const handleTouchMove = () => emit({ source: "touch" });
92 // Scrollbar drags produce no wheel/touch events. The scroll node's own padding
93 // also targets it, so only a press at its trailing edge counts.
94 const handlePointerDown = (event: PointerEvent) =>
95 emit({
96 source: "pointer",
97 onScrollbar:
98 event.target === scrollNode &&
99 scrollNode.getBoundingClientRect().right - event.clientX <=
100 Math.max(SCROLLBAR_HIT_PX, scrollNode.offsetWidth - scrollNode.clientWidth),
101 });
102 // Clicking message text can leave DOM focus on body, and keyboard scrolling
103 // bypasses wheel and pointer events, so scroll keys are heard app-wide.
104 // Body keys belong to the main timeline; a side chat's hears only its own.
105 const handleKeyDown = (event: KeyboardEvent, consumed: boolean) => {
106 const direction = UP_KEYS.has(event.key) ? "up" : DOWN_KEYS.has(event.key) ? "down" : null;
107 if (
108 direction === null ||
109 consumed ||
110 !(event.target instanceof Node) ||
111 (!scrollNode.contains(event.target) &&
112 ((event.target !== document.body && event.target !== document.documentElement) ||
113 isInSideChatPane(scrollNode))) ||
114 event.isComposing ||
115 event.altKey ||
116 event.ctrlKey ||
117 event.metaKey ||
118 event.shiftKey ||
119 eventPathContainsSelector(event, TYPE_TO_FOCUS_EDITABLE_SELECTOR) ||
120 document.querySelector(TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR) ||
121 (scrollNode.contains(event.target) &&
122 !isTimelineScrollTarget(event.target, scrollNode, direction === "up" ? -1 : 1))
123 ) {
124 return;
125 }
126 emit({ source: "key", key: event.key, direction });
127 };
128 // Input inside an embedded frame reaches none of the listeners above, but
129 // its scroll still chains out to the timeline.
130 const scrolledUp = createUpwardScrollDetector({
131 top: scrollNode.scrollTop,
132 height: scrollNode.scrollHeight,
133 });
134 // Only a frame's input reaches the timeline unseen. Any other unexplained upward move is not
135 // the reader's: the browser clamps scrollTop when content briefly shrinks.
136 const frameHasInput = () =>
137 scrollNode.querySelector("iframe:hover") !== null ||
138 (document.activeElement instanceof HTMLIFrameElement &&
139 scrollNode.contains(document.activeElement));
140 const handleScroll = () => {
141 if (
142 scrolledUp({
143 top: scrollNode.scrollTop,
144 height: scrollNode.scrollHeight,
145 programmatic: programmaticHolds > 0,
146 }) &&
147 frameHasInput() &&
148 // LegendList updates its scroll state on the next animation frame.
149 resolveTimelineIsAtEnd({
150 contentLength: scrollNode.scrollHeight,
151 scroll: scrollNode.scrollTop,
152 scrollLength: scrollNode.clientHeight,
153 }) === false
154 ) {
155 emit({ source: "scroll" });
156 }
157 };
158 const frameHeights = new WeakMap<HTMLIFrameElement, number>();
159 const handleFrameResize = (event: MessageEvent) => {
160 const height = readHtmlRenderContentHeight(event.data);
161 if (height === undefined) return;
162 const frame = [...scrollNode.querySelectorAll("iframe")].find(
163 (frame) => frame.contentWindow === event.source,
164 );
165 if (!frame) return;
166 const previous = frameHeights.get(frame);
167 frameHeights.set(frame, height);
168 if (previous !== undefined && previous !== height && document.activeElement === frame) {
169 emit({ source: "command", releasesFollow: true });
170 onFrameResize?.(frame);
171 }
172 };
173 // Run before frame listeners resize rows, so an accordion cannot drag the reader to the end.
174 window.addEventListener("message", handleFrameResize, true);
175 scrollNode.addEventListener("scroll", handleScroll, { passive: true });
176 scrollNode.addEventListener("wheel", handleWheel, { passive: true });
177 scrollNode.addEventListener("touchmove", handleTouchMove, { passive: true });
178 scrollNode.addEventListener("pointerdown", handlePointerDown, { passive: true });
179 const unregisterKeyDown = registerCommands({}, { observe: handleKeyDown });
180 return {
181 scrollNode,
182 subscribe: (listener) => {
183 listeners.add(listener);
184 return () => listeners.delete(listener);
185 },
186 navigate: ({ releasesFollow }) => emit({ source: "command", releasesFollow }),
187 holdProgrammaticScroll: () => {
188 programmaticHolds += 1;
189 let released = false;
190 return () => {
191 if (released) return;
192 released = true;
193 programmaticHolds -= 1;
194 };
195 },
196 followReleased: () => {
197 for (const listener of followReleasedListeners) listener();
198 },
199 onFollowReleased: (listener) => {
200 followReleasedListeners.add(listener);
201 return () => followReleasedListeners.delete(listener);
202 },
203 dispose: () => {
204 window.removeEventListener("message", handleFrameResize, true);
205 listeners.clear();
206 followReleasedListeners.clear();
207 scrollNode.removeEventListener("scroll", handleScroll);
208 scrollNode.removeEventListener("wheel", handleWheel);
209 scrollNode.removeEventListener("touchmove", handleTouchMove);
210 scrollNode.removeEventListener("pointerdown", handlePointerDown);
211 unregisterKeyDown();
212 },
213 };
214 }
215
216 /**
217 * Whether a navigation can carry the viewport away from the live edge. A spurious
218 * release while pinned never re-arms, so streaming stops following. Downward input
219 * counts only outside the end band: streaming growth makes isAtEnd flicker false
220 * for a frame, and a gesture then must not release follow.
221 */
222 export function navigationReleasesFollow(
223 navigation: TimelineNavigation,
224 viewport: { readonly contentScrollsUp: () => boolean; readonly awayFromEnd: () => boolean },
225 ): boolean {
226 switch (navigation.source) {
227 case "wheel":
228 return navigation.direction === "up" && viewport.contentScrollsUp();
229 case "key":
230 return navigation.direction === "up" ? viewport.contentScrollsUp() : viewport.awayFromEnd();
231 case "pointer":
232 return navigation.onScrollbar ? viewport.contentScrollsUp() : viewport.awayFromEnd();
233 case "touch":
234 // Touch direction is not observable; an upward flick leaves the end
235 // band within its first few events.
236 return viewport.awayFromEnd();
237 case "scroll":
238 return true;
239 case "command":
240 return navigation.releasesFollow;
241 }
242 }
243
244 /**
245 * Whether the timeline keeps the live end in view. An anchored new turn is
246 * following with an anchor present (the anchor lives with the thread's
247 * timeline state). `atEnd` only matters once released: while following, the
248 * list is at its end by definition.
249 */
250 export type TimelineFollow =
251 | { readonly mode: "following" }
252 | { readonly mode: "released"; readonly atEnd: boolean };
253
254 export type TimelineFollowEvent =
255 | { readonly type: "navigated" }
256 | { readonly type: "followEnd" }
257 | { readonly type: "reachedEnd" }
258 | { readonly type: "leftEnd" };
259
260 export const FOLLOWING: TimelineFollow = { mode: "following" };
261
262 export function initialTimelineFollow(followEnd: boolean): TimelineFollow {
263 return followEnd ? FOLLOWING : { mode: "released", atEnd: false };
264 }
265
266 export function transitionTimelineFollow(
267 state: TimelineFollow,
268 event: TimelineFollowEvent,
269 ): TimelineFollow {
270 switch (event.type) {
271 case "navigated":
272 return state.mode === "released" ? state : { mode: "released", atEnd: true };
273 case "followEnd":
274 return FOLLOWING;
275 case "reachedEnd":
276 // Navigating away while still at the end stays released until the list
277 // reports leaving and returning, so a scroll key at the end cannot re-arm.
278 return state.mode === "released" && !state.atEnd ? FOLLOWING : state;
279 case "leftEnd":
280 // While following, the list leaves the end band for a frame on every
281 // streamed chunk before the follow scroll catches up.
282 return state.mode === "released" && state.atEnd ? { mode: "released", atEnd: false } : state;
283 }
284 }