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