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