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 const handleScroll = () => {
121 if (
122 scrolledUp({
123 top: scrollNode.scrollTop,
124 height: scrollNode.scrollHeight,
125 programmatic: programmaticHolds > 0,
126 }) &&
127 // LegendList updates its scroll state on the next animation frame.
128 resolveTimelineIsAtEnd({
129 contentLength: scrollNode.scrollHeight,
130 scroll: scrollNode.scrollTop,
131 scrollLength: scrollNode.clientHeight,
132 }) === false
133 ) {
134 emit({ source: "scroll" });
135 }
136 };
137 scrollNode.addEventListener("scroll", handleScroll, { passive: true });
138 scrollNode.addEventListener("wheel", handleWheel, { passive: true });
139 scrollNode.addEventListener("touchmove", handleTouchMove, { passive: true });
140 scrollNode.addEventListener("pointerdown", handlePointerDown, { passive: true });
141 const unregisterKeyDown = registerCommands({}, { observe: handleKeyDown });
142 return {
143 scrollNode,
144 subscribe: (listener) => {
145 listeners.add(listener);
146 return () => listeners.delete(listener);
147 },
148 navigate: ({ releasesFollow }) => emit({ source: "command", releasesFollow }),
149 holdProgrammaticScroll: () => {
150 programmaticHolds += 1;
151 let released = false;
152 return () => {
153 if (released) return;
154 released = true;
155 programmaticHolds -= 1;
156 };
157 },
158 followReleased: () => {
159 for (const listener of followReleasedListeners) listener();
160 },
161 onFollowReleased: (listener) => {
162 followReleasedListeners.add(listener);
163 return () => followReleasedListeners.delete(listener);
164 },
165 dispose: () => {
166 listeners.clear();
167 followReleasedListeners.clear();
168 scrollNode.removeEventListener("scroll", handleScroll);
169 scrollNode.removeEventListener("wheel", handleWheel);
170 scrollNode.removeEventListener("touchmove", handleTouchMove);
171 scrollNode.removeEventListener("pointerdown", handlePointerDown);
172 unregisterKeyDown();
173 },
174 };
175}
176
177/**
178 * Whether a navigation can carry the viewport away from the live edge. A spurious
179 * release while pinned never re-arms, so streaming stops following. Downward input
180 * counts only outside the end band: streaming growth makes isAtEnd flicker false
181 * for a frame, and a gesture then must not release follow.
182 */
183export function navigationReleasesFollow(
184 navigation: TimelineNavigation,
185 viewport: { readonly contentScrollsUp: () => boolean; readonly awayFromEnd: () => boolean },
186): boolean {
187 switch (navigation.source) {
188 case "wheel":
189 return navigation.direction === "up" && viewport.contentScrollsUp();
190 case "key":
191 return navigation.direction === "up" ? viewport.contentScrollsUp() : viewport.awayFromEnd();
192 case "pointer":
193 return navigation.onScrollbar ? viewport.contentScrollsUp() : viewport.awayFromEnd();
194 case "touch":
195 // Touch direction is not observable; an upward flick leaves the end
196 // band within its first few events.
197 return viewport.awayFromEnd();
198 case "scroll":
199 return true;
200 case "command":
201 return navigation.releasesFollow;
202 }
203}
204
205/**
206 * Whether the timeline keeps the live end in view. An anchored new turn is
207 * following with an anchor present (the anchor lives with the thread's
208 * timeline state). `atEnd` only matters once released: while following, the
209 * list is at its end by definition.
210 */
211export type TimelineFollow =
212 | { readonly mode: "following" }
213 | { readonly mode: "released"; readonly atEnd: boolean };
214
215export type TimelineFollowEvent =
216 | { readonly type: "navigated" }
217 | { readonly type: "followEnd" }
218 | { readonly type: "reachedEnd" }
219 | { readonly type: "leftEnd" };
220
221export const FOLLOWING: TimelineFollow = { mode: "following" };
222
223export function initialTimelineFollow(followEnd: boolean): TimelineFollow {
224 return followEnd ? FOLLOWING : { mode: "released", atEnd: false };
225}
226
227export function transitionTimelineFollow(
228 state: TimelineFollow,
229 event: TimelineFollowEvent,
230): TimelineFollow {
231 switch (event.type) {
232 case "navigated":
233 return state.mode === "released" ? state : { mode: "released", atEnd: true };
234 case "followEnd":
235 return FOLLOWING;
236 case "reachedEnd":
237 // Navigating away while still at the end stays released until the list
238 // reports leaving and returning, so a scroll key at the end cannot re-arm.
239 return state.mode === "released" && !state.atEnd ? FOLLOWING : state;
240 case "leftEnd":
241 // While following, the list leaves the end band for a frame on every
242 // streamed chunk before the follow scroll catches up.
243 return state.mode === "released" && state.atEnd ? { mode: "released", atEnd: false } : state;
244 }
245}