@bazariodev/scrollback 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,3929 @@
1
+ 'use client';
2
+ import { useRef, useState, useLayoutEffect, useEffect, useCallback, useMemo } from 'react';
3
+
4
+ const DEFAULT_LIMITS = Object.freeze({
5
+ pageSize: 30,
6
+ initialPageSize: 60,
7
+ maxRenderedItems: 150,
8
+ });
9
+
10
+ const DEFAULT_THRESHOLDS = Object.freeze({
11
+ atBottom: 56,
12
+ prefetchMin: 480,
13
+ prefetchMax: 1200,
14
+ });
15
+
16
+ const DEFAULT_NAVIGATION = Object.freeze({
17
+ maxOlderPages: 5,
18
+ highlightDuration: 1400,
19
+ });
20
+
21
+ const SCROLL = Object.freeze({
22
+ PAGE_PREFETCH_VIEWPORT_MULTIPLIER: 1.5,
23
+ MEMORY_FLUSH_DELAY_MS: 80,
24
+ OFFSET_ROUNDING_TOLERANCE_PX: 0.5,
25
+ TOP_REAPPLY_TOLERANCE_PX: 1,
26
+ ITEM_WAIT_TIMEOUT_MS: 5000,
27
+ PAGE_COMMIT_TIMEOUT_MS: 5000,
28
+ });
29
+
30
+ const PAGE_LOAD_DIRECTION = Object.freeze({
31
+ NEWER: 'newer',
32
+ OLDER: 'older',
33
+ });
34
+
35
+ const RESTORE_REASON = Object.freeze({
36
+ OLDER_PAGE: 'older-page',
37
+ NEWER_PAGE: 'newer-page',
38
+ });
39
+
40
+ const NAVIGATION_TRIGGER = Object.freeze({
41
+ OPEN: 'open',
42
+ NAVIGATE: 'navigate',
43
+ });
44
+
45
+ const NAVIGATION_OUTCOME = Object.freeze({
46
+ SCROLLED: 'scrolled',
47
+ NOT_FOUND: 'not-found',
48
+ FAR_BACK: 'far-back',
49
+ SUPERSEDED: 'superseded',
50
+ });
51
+
52
+ const OPEN_TARGET_STATE = Object.freeze({
53
+ IDLE: 'idle',
54
+ LOADING: 'loading',
55
+ REACHED: 'reached',
56
+ });
57
+
58
+ const SCROLL_BEHAVIOR = Object.freeze({
59
+ AUTO: 'auto',
60
+ INSTANT: 'instant',
61
+ SMOOTH: 'smooth',
62
+ });
63
+
64
+ const WINDOW_ERRORS = Object.freeze({
65
+ ANCHOR_OUTSIDE: 'Scroll window anchor is outside the item collection',
66
+ });
67
+
68
+ const VALUE_TYPE = Object.freeze({
69
+ FUNCTION: 'function',
70
+ NUMBER: 'number',
71
+ UNDEFINED: 'undefined',
72
+ });
73
+
74
+ const SCROLL_EVENT = Object.freeze({
75
+ END: 'scrollend',
76
+ });
77
+
78
+ // Each registry exists only after its first use, so this module has no import
79
+ // side effects.
80
+
81
+ class ResizeObserverRegistry {
82
+ #listenersByElement = new Map();
83
+ #observer = null;
84
+
85
+ // Duplicate subscriptions share one delivery and keep separate cleanup.
86
+ observe(element, listener) {
87
+ const observer = this.#getObserver();
88
+ if (!observer) return null;
89
+
90
+ const listenersByElement = this.#listenersByElement;
91
+ let listenerCounts = listenersByElement.get(element);
92
+ if (!listenerCounts) {
93
+ listenerCounts = new Map();
94
+ listenersByElement.set(element, listenerCounts);
95
+ observer.observe(element);
96
+ }
97
+
98
+ listenerCounts.set(listener, (listenerCounts.get(listener) ?? 0) + 1);
99
+
100
+ let isActive = true;
101
+ return () => {
102
+ if (!isActive) return;
103
+
104
+ isActive = false;
105
+ this.#unsubscribe(element, listener);
106
+ };
107
+ }
108
+
109
+ #getObserver() {
110
+ const observer = this.#observer;
111
+ if (observer) return observer;
112
+ if (typeof ResizeObserver === VALUE_TYPE.UNDEFINED) return null;
113
+
114
+ const nextObserver = new ResizeObserver((entries) => this.#notify(entries));
115
+ this.#observer = nextObserver;
116
+ return nextObserver;
117
+ }
118
+
119
+ #notify(entries) {
120
+ let caughtError = null;
121
+
122
+ for (const { target } of entries) {
123
+ const listenerCounts = this.#listenersByElement.get(target);
124
+ if (!listenerCounts) continue;
125
+
126
+ const listeners = [...listenerCounts.keys()];
127
+ for (const listener of listeners) {
128
+ if (!listenerCounts.has(listener)) continue;
129
+
130
+ try {
131
+ listener();
132
+ } catch (error) {
133
+ caughtError ??= { value: error };
134
+ }
135
+ }
136
+ }
137
+
138
+ if (caughtError) throw caughtError.value;
139
+ }
140
+
141
+ #unsubscribe(element, listener) {
142
+ const listenersByElement = this.#listenersByElement;
143
+ const listenerCounts = listenersByElement.get(element);
144
+ const subscriptionCount = listenerCounts?.get(listener);
145
+ if (!listenerCounts || !subscriptionCount) return;
146
+
147
+ if (subscriptionCount > 1) {
148
+ listenerCounts.set(listener, subscriptionCount - 1);
149
+ return;
150
+ }
151
+
152
+ listenerCounts.delete(listener);
153
+ if (listenerCounts.size > 0) return;
154
+
155
+ listenersByElement.delete(element);
156
+ const observer = this.#observer;
157
+ if (!observer) return;
158
+
159
+ if (listenersByElement.size > 0) {
160
+ observer.unobserve(element);
161
+ return;
162
+ }
163
+
164
+ observer.disconnect();
165
+ this.#observer = null;
166
+ }
167
+ }
168
+
169
+ class LayoutMeasurementScheduler {
170
+ #isFlushScheduled = false;
171
+ #pendingByKey = new Map();
172
+
173
+ // A new schedule for `key` replaces the queued work. A flush completes all
174
+ // reads before it starts any write.
175
+ schedule(key, read) {
176
+ const pendingByKey = this.#pendingByKey;
177
+ const previousMeasurement = pendingByKey.get(key);
178
+ if (previousMeasurement) previousMeasurement.isActive = false;
179
+
180
+ const measurement = { isActive: true, read };
181
+ pendingByKey.set(key, measurement);
182
+ this.#scheduleFlush();
183
+
184
+ return () => {
185
+ if (!measurement.isActive) return;
186
+
187
+ measurement.isActive = false;
188
+ if (pendingByKey.get(key) === measurement) pendingByKey.delete(key);
189
+ };
190
+ }
191
+
192
+ flush() {
193
+ this.#isFlushScheduled = false;
194
+ const pendingByKey = this.#pendingByKey;
195
+ const measurements = Array.from(pendingByKey.entries());
196
+ const writes = [];
197
+ let caughtError = null;
198
+
199
+ for (const [, measurement] of measurements) {
200
+ if (!measurement.isActive) continue;
201
+
202
+ try {
203
+ writes.push({ measurement, write: measurement.read() });
204
+ } catch (error) {
205
+ measurement.isActive = false;
206
+ caughtError ??= { value: error };
207
+ }
208
+ }
209
+
210
+ for (const { measurement, write } of writes) {
211
+ if (!measurement.isActive) continue;
212
+
213
+ try {
214
+ write();
215
+ } catch (error) {
216
+ caughtError ??= { value: error };
217
+ }
218
+
219
+ measurement.isActive = false;
220
+ }
221
+
222
+ for (const [key, measurement] of measurements) {
223
+ if (pendingByKey.get(key) === measurement) pendingByKey.delete(key);
224
+ }
225
+
226
+ if (caughtError) throw caughtError.value;
227
+ }
228
+
229
+ #scheduleFlush() {
230
+ if (this.#isFlushScheduled) return;
231
+
232
+ this.#isFlushScheduled = true;
233
+ queueMicrotask(() => this.flush());
234
+ }
235
+ }
236
+
237
+ let resizeObserverRegistry = null;
238
+ let layoutMeasurementScheduler = null;
239
+
240
+ function observeResize(element, listener) {
241
+ resizeObserverRegistry ??= new ResizeObserverRegistry();
242
+ return resizeObserverRegistry.observe(element, listener);
243
+ }
244
+
245
+ function scheduleMeasurement(key, read) {
246
+ layoutMeasurementScheduler ??= new LayoutMeasurementScheduler();
247
+ return layoutMeasurementScheduler.schedule(key, read);
248
+ }
249
+
250
+ const DEFAULT_PLATFORM = Object.freeze({
251
+ observeResize,
252
+ scheduleMeasurement,
253
+ });
254
+
255
+ const OPTION_NAMES = Object.freeze({
256
+ LIMITS: 'limits',
257
+ THRESHOLDS: 'thresholds',
258
+ NAVIGATION: 'navigation',
259
+ PREFETCH_MIN: 'prefetchMin',
260
+ });
261
+
262
+ const ERRORS = Object.freeze({
263
+ INVALID_OPTION: (group, name, rule) =>
264
+ `Scrollback option ${group}.${name} must be ${rule}.`,
265
+ });
266
+
267
+ const RULES = Object.freeze({
268
+ POSITIVE_INTEGER: {
269
+ isValid: (value) => Number.isInteger(value) && value > 0,
270
+ description: 'a positive integer',
271
+ },
272
+ COUNT: {
273
+ isValid: (value) => Number.isInteger(value) && value >= 0,
274
+ description: 'an integer that is 0 or more',
275
+ },
276
+ DISTANCE: {
277
+ isValid: (value) => Number.isFinite(value) && value >= 0,
278
+ description: 'a finite number that is 0 or more',
279
+ },
280
+ PREFETCH_RANGE: 'not more than thresholds.prefetchMax',
281
+ });
282
+
283
+ function fail(group, name, rule) {
284
+ throw new RangeError(ERRORS.INVALID_OPTION(group, name, rule));
285
+ }
286
+
287
+ function resolveValues(group, values, defaults, rules) {
288
+ const resolved = {};
289
+ for (const [name, fallback] of Object.entries(defaults)) {
290
+ const value = values[name] ?? fallback;
291
+ const rule = rules[name];
292
+ if (!rule.isValid(value)) fail(group, name, rule.description);
293
+ resolved[name] = value;
294
+ }
295
+ return resolved;
296
+ }
297
+
298
+ function resolveLimits({ pageSize, initialPageSize, maxRenderedItems }) {
299
+ const resolved = resolveValues(
300
+ OPTION_NAMES.LIMITS,
301
+ { pageSize, initialPageSize, maxRenderedItems },
302
+ DEFAULT_LIMITS,
303
+ {
304
+ pageSize: RULES.POSITIVE_INTEGER,
305
+ initialPageSize: RULES.POSITIVE_INTEGER,
306
+ maxRenderedItems: RULES.POSITIVE_INTEGER,
307
+ },
308
+ );
309
+ return {
310
+ // A reveal step of at most half the cap keeps the reading anchor rendered.
311
+ pageSize: Math.min(
312
+ resolved.pageSize,
313
+ Math.max(1, Math.floor(resolved.maxRenderedItems / 2)),
314
+ ),
315
+ initialPageSize: Math.min(
316
+ resolved.initialPageSize,
317
+ resolved.maxRenderedItems,
318
+ ),
319
+ maxRenderedItems: resolved.maxRenderedItems,
320
+ };
321
+ }
322
+
323
+ function resolveThresholds({ atBottom, prefetchMin, prefetchMax }) {
324
+ const resolved = resolveValues(
325
+ OPTION_NAMES.THRESHOLDS,
326
+ { atBottom, prefetchMin, prefetchMax },
327
+ DEFAULT_THRESHOLDS,
328
+ {
329
+ atBottom: RULES.DISTANCE,
330
+ prefetchMin: RULES.DISTANCE,
331
+ prefetchMax: RULES.DISTANCE,
332
+ },
333
+ );
334
+ if (resolved.prefetchMin > resolved.prefetchMax) {
335
+ fail(
336
+ OPTION_NAMES.THRESHOLDS,
337
+ OPTION_NAMES.PREFETCH_MIN,
338
+ RULES.PREFETCH_RANGE,
339
+ );
340
+ }
341
+ return resolved;
342
+ }
343
+
344
+ function resolveNavigationSettings({
345
+ maxOlderPages,
346
+ highlightDuration,
347
+ }) {
348
+ return resolveValues(
349
+ OPTION_NAMES.NAVIGATION,
350
+ { maxOlderPages, highlightDuration },
351
+ DEFAULT_NAVIGATION,
352
+ {
353
+ maxOlderPages: RULES.COUNT,
354
+ highlightDuration: RULES.DISTANCE,
355
+ },
356
+ );
357
+ }
358
+
359
+ function createTimelineWindowAnchor(messages, anchorIndex) {
360
+ const anchor = messages[anchorIndex];
361
+ if (!anchor) return undefined;
362
+
363
+ return {
364
+ anchorMessageId: anchor.id,
365
+ anchorSuccessorMessageId: messages[anchorIndex + 1]?.id,
366
+ anchorTime: anchor.time,
367
+ };
368
+ }
369
+
370
+ function findTimelineWindowAnchorIndex(messages, state) {
371
+ const exactIndex = messages.findIndex(
372
+ (message) => message.id === state.anchorMessageId,
373
+ );
374
+ if (exactIndex !== -1) return exactIndex;
375
+
376
+ const successorIndex = state.anchorSuccessorMessageId
377
+ ? messages.findIndex(
378
+ (message) => message.id === state.anchorSuccessorMessageId,
379
+ )
380
+ : -1;
381
+ if (successorIndex !== -1) return successorIndex;
382
+
383
+ const nextIndex = messages.findIndex(
384
+ (message) => message.time >= state.anchorTime,
385
+ );
386
+ return nextIndex === -1 ? messages.length - 1 : nextIndex;
387
+ }
388
+
389
+ const POSITION_KEYS = Object.freeze({
390
+ LATEST: 'latest',
391
+ ITEM: (id) => `item:${id}`,
392
+
393
+ FOCUS: (id) => `focus:${id}`,
394
+
395
+ SCROLL: (id) => `scroll:${id}`,
396
+ });
397
+
398
+ function cappedSize(size, limits) {
399
+ return Math.min(size, limits.maxRenderedItems);
400
+ }
401
+
402
+ function createTimelineWindowAtIndex(messages, anchorIndex, size) {
403
+ const lastPageStart = Math.max(0, messages.length - size);
404
+ const centeredStart = Math.max(0, anchorIndex - Math.floor(size / 2));
405
+ const pageStart = Math.min(centeredStart, lastPageStart);
406
+ const pageEnd = Math.min(messages.length, pageStart + size);
407
+ const anchor = createTimelineWindowAnchor(messages, anchorIndex);
408
+
409
+ if (!anchor) throw new Error(WINDOW_ERRORS.ANCHOR_OUTSIDE);
410
+
411
+ return {
412
+ ...anchor,
413
+ startOffset: pageStart - anchorIndex,
414
+ endOffset: pageEnd - anchorIndex,
415
+ followLatest: pageEnd === messages.length,
416
+ navigationVersion: 0,
417
+ };
418
+ }
419
+
420
+ function createTimelineWindowAtMessage(messages, anchorMessageId, size) {
421
+ const anchorIndex = messages.findIndex(
422
+ (message) => message.id === anchorMessageId,
423
+ );
424
+ if (anchorIndex === -1) return undefined;
425
+ return createTimelineWindowAtIndex(messages, anchorIndex, size);
426
+ }
427
+
428
+ function createTimelineWindowAtTail(messages, size) {
429
+ if (messages.length === 0) return undefined;
430
+ return createTimelineWindowAtIndex(messages, messages.length - 1, size);
431
+ }
432
+
433
+ function createLatestTimelineWindow(messages, limits) {
434
+ return createTimelineWindowAtTail(
435
+ messages,
436
+ cappedSize(limits.pageSize, limits),
437
+ );
438
+ }
439
+
440
+ function createAnchoredTimelineWindow(
441
+ messages,
442
+ anchorMessageId,
443
+ limits,
444
+ ) {
445
+ return createTimelineWindowAtMessage(
446
+ messages,
447
+ anchorMessageId,
448
+ cappedSize(limits.pageSize, limits),
449
+ );
450
+ }
451
+
452
+ // The opening window has the size of the whole first request. Then no fetched
453
+ // item stays unrendered. A window of one reveal step makes the scroller only
454
+ // a little taller than its viewport. That oversizes the scrollbar and puts the
455
+ // older boundary in the prefetch zone before the user scrolls. A jump keeps
456
+ // the ordinary step, because it lands in the middle of the history, where the
457
+ // scroller is already tall.
458
+ // An initial target is hard: the window waits for its item. A focus item is
459
+ // soft: when it is not cached, the saved scroll position or the latest items
460
+ // open the window.
461
+ function createInitialTimelineWindow(messages, position, limits) {
462
+ const { initialId, focusId, scrollAnchorId } = position ?? {};
463
+ const size = cappedSize(limits.initialPageSize, limits);
464
+ if (initialId)
465
+ return createTimelineWindowAtMessage(messages, initialId, size);
466
+
467
+ const anchorId = [focusId, scrollAnchorId].find(
468
+ (id) => id && messages.some((message) => message.id === id),
469
+ );
470
+ if (anchorId) return createTimelineWindowAtMessage(messages, anchorId, size);
471
+
472
+ return createTimelineWindowAtTail(messages, size);
473
+ }
474
+
475
+ function getTimelineInitialPositionKey(position) {
476
+ const { initialId, focusId, scrollAnchorId } = position ?? {};
477
+ if (initialId) return POSITION_KEYS.ITEM(initialId);
478
+ if (focusId) return POSITION_KEYS.FOCUS(focusId);
479
+ if (scrollAnchorId) return POSITION_KEYS.SCROLL(scrollAnchorId);
480
+ return POSITION_KEYS.LATEST;
481
+ }
482
+
483
+ function getTimelineWindowBounds(messages, state, limits) {
484
+ const { maxRenderedItems } = limits;
485
+ const anchorIndex = findTimelineWindowAnchorIndex(messages, state);
486
+ let startIndex = Math.min(
487
+ messages.length,
488
+ Math.max(0, anchorIndex + state.startOffset),
489
+ );
490
+ const desiredEndIndex = state.followLatest
491
+ ? messages.length
492
+ : anchorIndex + state.endOffset;
493
+ let endIndex = Math.max(
494
+ startIndex,
495
+ Math.min(messages.length, desiredEndIndex),
496
+ );
497
+
498
+ if (endIndex - startIndex > maxRenderedItems) {
499
+ if (state.followLatest) {
500
+ startIndex = endIndex - maxRenderedItems;
501
+ } else {
502
+ endIndex = startIndex + maxRenderedItems;
503
+ }
504
+ }
505
+
506
+ return { anchorIndex, startIndex, endIndex };
507
+ }
508
+
509
+ function selectTimelineWindow(messages, state, limits) {
510
+ if (!state || messages.length === 0) {
511
+ return {
512
+ messages: [],
513
+ hasCachedOlder: false,
514
+ hasCachedNewer: messages.length > 0,
515
+ };
516
+ }
517
+
518
+ const { startIndex, endIndex } = getTimelineWindowBounds(
519
+ messages,
520
+ state,
521
+ limits,
522
+ );
523
+
524
+ return {
525
+ messages: messages.slice(startIndex, endIndex),
526
+ hasCachedOlder: startIndex > 0,
527
+ hasCachedNewer: endIndex < messages.length,
528
+ };
529
+ }
530
+
531
+ function revealOlderTimelineWindowPage(messages, state, limits) {
532
+ const { anchorIndex, startIndex, endIndex } = getTimelineWindowBounds(
533
+ messages,
534
+ state,
535
+ limits,
536
+ );
537
+ const nextAnchor = createTimelineWindowAnchor(messages, startIndex);
538
+ if (!nextAnchor) return state;
539
+
540
+ const desiredEndIndex = Math.max(endIndex, anchorIndex + state.endOffset);
541
+
542
+ return {
543
+ ...state,
544
+ ...nextAnchor,
545
+ startOffset: -limits.pageSize,
546
+ endOffset: desiredEndIndex - startIndex,
547
+ followLatest: false,
548
+ };
549
+ }
550
+
551
+ function revealNewerTimelineWindowPage(
552
+ messages,
553
+ state,
554
+ followLatest,
555
+ limits,
556
+ ) {
557
+ const { maxRenderedItems, pageSize } = limits;
558
+ const { anchorIndex, startIndex, endIndex } = getTimelineWindowBounds(
559
+ messages,
560
+ state,
561
+ limits,
562
+ );
563
+ const tailOffset = messages.length - anchorIndex;
564
+ const visibleEndOffset = Math.min(
565
+ tailOffset,
566
+ endIndex - anchorIndex + pageSize,
567
+ );
568
+ const currentStartOffset = startIndex - anchorIndex;
569
+ const startOffset = Math.max(
570
+ currentStartOffset,
571
+ visibleEndOffset - maxRenderedItems,
572
+ );
573
+ const endOffset =
574
+ visibleEndOffset === tailOffset
575
+ ? startOffset + maxRenderedItems
576
+ : visibleEndOffset;
577
+ const nextStartIndex = Math.min(
578
+ messages.length - 1,
579
+ Math.max(0, anchorIndex + startOffset),
580
+ );
581
+ const nextAnchor = createTimelineWindowAnchor(messages, nextStartIndex);
582
+ if (!nextAnchor) return state;
583
+
584
+ return {
585
+ ...state,
586
+ ...nextAnchor,
587
+ startOffset: 0,
588
+ endOffset: anchorIndex + endOffset - nextStartIndex,
589
+ followLatest,
590
+ };
591
+ }
592
+
593
+ function pauseTimelineWindowFollowingLatest(messages, state, limits) {
594
+ if (!state.followLatest) return state;
595
+
596
+ const { anchorIndex, startIndex } = getTimelineWindowBounds(
597
+ messages,
598
+ state,
599
+ limits,
600
+ );
601
+ const startOffset = startIndex - anchorIndex;
602
+ return {
603
+ ...state,
604
+ startOffset,
605
+ endOffset: startOffset + limits.maxRenderedItems,
606
+ followLatest: false,
607
+ };
608
+ }
609
+
610
+ function resumeTimelineWindowFollowingLatest(messages, state, limits) {
611
+ if (state.followLatest) return state;
612
+
613
+ const { anchorIndex, startIndex, endIndex } = getTimelineWindowBounds(
614
+ messages,
615
+ state,
616
+ limits,
617
+ );
618
+ return {
619
+ ...state,
620
+ startOffset: startIndex - anchorIndex,
621
+ endOffset: endIndex - anchorIndex,
622
+ followLatest: true,
623
+ navigationVersion: state.navigationVersion + 1,
624
+ };
625
+ }
626
+
627
+ function supersedeTimelineWindow(nextState, currentState) {
628
+ if (!nextState) return undefined;
629
+ return {
630
+ ...nextState,
631
+ navigationVersion:
632
+ (currentState?.navigationVersion ?? nextState.navigationVersion) + 1,
633
+ };
634
+ }
635
+
636
+ function isTimelineMessageBeforeWindow(
637
+ sourceMessages,
638
+ renderedMessages,
639
+ messageId,
640
+ ) {
641
+ const firstRenderedMessageId = renderedMessages[0]?.id;
642
+ if (
643
+ !messageId ||
644
+ !firstRenderedMessageId ||
645
+ messageId === firstRenderedMessageId
646
+ ) {
647
+ return false;
648
+ }
649
+
650
+ for (const message of sourceMessages) {
651
+ if (message.id === messageId) return true;
652
+ if (message.id === firstRenderedMessageId) return false;
653
+ }
654
+
655
+ return false;
656
+ }
657
+
658
+ function readTimelineScrollMetrics(element) {
659
+ return {
660
+ clientHeight: element.clientHeight,
661
+ scrollHeight: element.scrollHeight,
662
+ scrollTop: element.scrollTop,
663
+ };
664
+ }
665
+
666
+ function getMaximumScrollTop({ scrollHeight, clientHeight }) {
667
+ return Math.max(0, scrollHeight - clientHeight);
668
+ }
669
+
670
+ function getBoundedScrollTop(metrics, top) {
671
+ return Math.min(getMaximumScrollTop(metrics), Math.max(0, top));
672
+ }
673
+
674
+ function getItemOffsetFromContainerTop(container, item) {
675
+ return (
676
+ item.getBoundingClientRect().top - container.getBoundingClientRect().top
677
+ );
678
+ }
679
+
680
+ // This function takes metrics, not the element. A caller that just wrote
681
+ // `scrollTop` can then answer from the geometry it measured. It does not read
682
+ // the value back and does not force a synchronous layout.
683
+ function isTimelineAtRenderedBottom(
684
+ { clientHeight, scrollHeight, scrollTop },
685
+ threshold,
686
+ ) {
687
+ return scrollHeight - scrollTop - clientHeight <= threshold;
688
+ }
689
+
690
+ function areTimelineScrollMemoriesEqual(first, second) {
691
+ return Boolean(
692
+ first &&
693
+ second &&
694
+ first.scrollTop === second.scrollTop &&
695
+ first.atBottom === second.atBottom &&
696
+ first.anchorItemId === second.anchorItemId &&
697
+ first.anchorOffsetFromViewportTop === second.anchorOffsetFromViewportTop,
698
+ );
699
+ }
700
+
701
+ function isTimelineMessageReached(container, messageElement) {
702
+ const containerRect = container.getBoundingClientRect();
703
+ const messageRect = messageElement.getBoundingClientRect();
704
+
705
+ return messageRect.top <= containerRect.bottom;
706
+ }
707
+
708
+ // Gives the scroll offset that centers an element in the container. The
709
+ // result stays inside the scroll range. The write moves only this container,
710
+ // not its ancestors or the page.
711
+ function getCenteredScrollTop(container, element) {
712
+ const containerRect = container.getBoundingClientRect();
713
+ const elementRect = element.getBoundingClientRect();
714
+ const offsetInViewport =
715
+ elementRect.top - containerRect.top - container.clientTop;
716
+ const target =
717
+ container.scrollTop +
718
+ offsetInViewport -
719
+ (container.clientHeight - elementRect.height) / 2;
720
+ return getBoundedScrollTop(container, target);
721
+ }
722
+
723
+ // Opens the view at the initial target. A cached target gets its position
724
+ // before paint. An uncached target loads through a navigation.
725
+ function useInitialTarget({
726
+ attachVersion,
727
+ initialMessageId,
728
+ initialMessageTime,
729
+ isLoading,
730
+ scrollCommandRef,
731
+ onNavigationRef,
732
+ runNavigation,
733
+ scrollToBottom,
734
+ scrollToLoadedMessage,
735
+ startNavigation,
736
+ }) {
737
+ // A comparison resets this value on a target change. A cleanup does not.
738
+ // Then StrictMode replay of effects keeps the state.
739
+ const openTargetRef = useRef({ state: OPEN_TARGET_STATE.IDLE });
740
+ const [completedInitialMessageId, setCompletedInitialMessageId] = useState();
741
+ const initialTargetPending = Boolean(
742
+ initialMessageId && completedInitialMessageId !== initialMessageId,
743
+ );
744
+
745
+ useLayoutEffect(() => {
746
+ if (openTargetRef.current.messageId === initialMessageId) return;
747
+
748
+ openTargetRef.current = {
749
+ messageId: initialMessageId,
750
+ state: OPEN_TARGET_STATE.IDLE,
751
+ };
752
+ scrollCommandRef.current = undefined;
753
+ }, [initialMessageId, scrollCommandRef]);
754
+ // biome-ignore lint/correctness/useExhaustiveDependencies: attachVersion is a trigger: the effect runs again when a DOM ref attaches after mount
755
+ useLayoutEffect(() => {
756
+ if (
757
+ !initialMessageId ||
758
+ isLoading ||
759
+ completedInitialMessageId === initialMessageId
760
+ ) {
761
+ return;
762
+ }
763
+ // StrictMode replays this effect before the completion below commits.
764
+ if (openTargetRef.current.state === OPEN_TARGET_STATE.REACHED) return;
765
+ const ownerBefore = scrollCommandRef.current;
766
+ if (!scrollToLoadedMessage(initialMessageId, { highlight: true })) return;
767
+
768
+ // A callback inside the write started a newer navigation. That navigation
769
+ // owns the view. Mark this target as reached and report nothing.
770
+ if (scrollCommandRef.current !== ownerBefore) {
771
+ openTargetRef.current.state = OPEN_TARGET_STATE.REACHED;
772
+ setCompletedInitialMessageId(initialMessageId);
773
+ return;
774
+ }
775
+
776
+ // This ends a navigation that still loads the target. That navigation
777
+ // then changes nothing when it settles.
778
+ const isCurrent = startNavigation();
779
+ openTargetRef.current.state = OPEN_TARGET_STATE.REACHED;
780
+ const complete = onNavigationRef.current?.({
781
+ trigger: NAVIGATION_TRIGGER.OPEN,
782
+ id: initialMessageId,
783
+ time: initialMessageTime,
784
+ });
785
+ if (isCurrent()) complete?.(NAVIGATION_OUTCOME.SCROLLED);
786
+ // This completion gates the read state. It must update with the position
787
+ // correction before paint.
788
+ setCompletedInitialMessageId(initialMessageId);
789
+ }, [
790
+ attachVersion,
791
+ completedInitialMessageId,
792
+ initialMessageId,
793
+ initialMessageTime,
794
+ isLoading,
795
+ scrollCommandRef,
796
+ onNavigationRef,
797
+ scrollToLoadedMessage,
798
+ startNavigation,
799
+ ]);
800
+ useEffect(() => {
801
+ if (!initialMessageId) return;
802
+ if (completedInitialMessageId === initialMessageId) return;
803
+ if (isLoading || openTargetRef.current.state !== OPEN_TARGET_STATE.IDLE) {
804
+ return;
805
+ }
806
+
807
+ const timeoutId = window.setTimeout(() => {
808
+ openTargetRef.current.state = OPEN_TARGET_STATE.LOADING;
809
+ const isCurrent = startNavigation();
810
+ const complete = onNavigationRef.current?.({
811
+ trigger: NAVIGATION_TRIGGER.OPEN,
812
+ id: initialMessageId,
813
+ time: initialMessageTime,
814
+ });
815
+ const options = { highlight: true, time: initialMessageTime };
816
+ void runNavigation(initialMessageId, options, isCurrent).then(
817
+ (result) => {
818
+ if (result === NAVIGATION_OUTCOME.SUPERSEDED || !isCurrent()) return;
819
+
820
+ if (result !== NAVIGATION_OUTCOME.SCROLLED) {
821
+ scrollToBottom(undefined, isCurrent);
822
+ }
823
+ setCompletedInitialMessageId(initialMessageId);
824
+ complete?.(result);
825
+ },
826
+ );
827
+ }, 0);
828
+
829
+ return () => window.clearTimeout(timeoutId);
830
+ }, [
831
+ completedInitialMessageId,
832
+ initialMessageId,
833
+ initialMessageTime,
834
+ isLoading,
835
+ onNavigationRef,
836
+ runNavigation,
837
+ scrollToBottom,
838
+ startNavigation,
839
+ ]);
840
+
841
+ return { initialTargetPending, setCompletedInitialMessageId };
842
+ }
843
+
844
+ // Makes the waiter of one navigation. `step` is the only code that moves the
845
+ // view for a navigation. The caller runs it now, after each engine commit,
846
+ // after a row registers, after a page settles, and when a newer command
847
+ // takes the view. Each run looks at the current state and does the
848
+ // next thing that is due.
849
+ function createArrivalWaiter({ id, options, isCurrent, env, onFinish }) {
850
+ let hasRevealed = false;
851
+ let hasStartedFill = false;
852
+ let isFinished = false;
853
+ let isLoadingPage = false;
854
+ let isStalled = false;
855
+ let pagesWalked = 0;
856
+ let timeoutId;
857
+ let versionBefore;
858
+ let resolveArrival = () => {};
859
+ const promise = new Promise((resolve) => {
860
+ resolveArrival = resolve;
861
+ });
862
+
863
+ const finish = (outcome) => {
864
+ if (isFinished) return;
865
+
866
+ isFinished = true;
867
+ window.clearTimeout(timeoutId);
868
+ onFinish();
869
+ resolveArrival(outcome);
870
+ };
871
+
872
+ const finishWithoutPages = () =>
873
+ finish(
874
+ env.hasMoreOlder()
875
+ ? NAVIGATION_OUTCOME.FAR_BACK
876
+ : NAVIGATION_OUTCOME.NOT_FOUND,
877
+ );
878
+
879
+ // A failsafe for a row that never registers, or an item that never reaches
880
+ // the source.
881
+ const armTimeout = (outcome) => {
882
+ window.clearTimeout(timeoutId);
883
+ timeoutId = window.setTimeout(() => {
884
+ finish(isCurrent() ? outcome : NAVIGATION_OUTCOME.SUPERSEDED);
885
+ }, SCROLL.ITEM_WAIT_TIMEOUT_MS);
886
+ };
887
+
888
+ const fill = () => {
889
+ hasStartedFill = true;
890
+ let request;
891
+ try {
892
+ request = Promise.resolve(env.loadThrough({ id, time: options.time }));
893
+ } catch {
894
+ request = Promise.resolve(false);
895
+ }
896
+ // A rejected load counts as a load that found nothing.
897
+ void request
898
+ .then(Boolean, () => false)
899
+ .then((didFill) => {
900
+ if (isFinished) return;
901
+ if (!isCurrent()) return finish(NAVIGATION_OUTCOME.SUPERSEDED);
902
+ if (!didFill) return finish(NAVIGATION_OUTCOME.NOT_FOUND);
903
+
904
+ armTimeout(NAVIGATION_OUTCOME.NOT_FOUND);
905
+ step();
906
+ });
907
+ };
908
+
909
+ // Without a time, there is nothing to fill through (for example a link
910
+ // with only an id). Walk a limited number of older pages. Each page is one
911
+ // call of the paging operation: it starts a request or joins the open one,
912
+ // such as a prefetch.
913
+ const walk = () => {
914
+ if (options.time !== undefined) {
915
+ if (!hasStartedFill) fill();
916
+ return;
917
+ }
918
+ if (isLoadingPage) return;
919
+ if (isStalled || pagesWalked >= env.maxOlderPages || !env.hasMoreOlder()) {
920
+ return finishWithoutPages();
921
+ }
922
+
923
+ pagesWalked += 1;
924
+ isLoadingPage = true;
925
+ void env
926
+ .loadOlderPage(() => !isFinished && isCurrent())
927
+ .then((didCommit) => {
928
+ isLoadingPage = false;
929
+ // A page that did not commit leaves nothing more to walk.
930
+ if (!didCommit) isStalled = true;
931
+ step();
932
+ });
933
+ };
934
+
935
+ function step() {
936
+ if (isFinished) return;
937
+ if (!isCurrent()) return finish(NAVIGATION_OUTCOME.SUPERSEDED);
938
+
939
+ if (env.scrollTo(id, options)) {
940
+ // A consumer callback inside the write can start a newer navigation.
941
+ return finish(
942
+ isCurrent()
943
+ ? NAVIGATION_OUTCOME.SCROLLED
944
+ : NAVIGATION_OUTCOME.SUPERSEDED,
945
+ );
946
+ }
947
+ if (!hasRevealed) {
948
+ const version = env.getNavigationVersion();
949
+ // The item is not in the source yet.
950
+ if (!env.reveal(id)) return walk();
951
+
952
+ hasRevealed = true;
953
+ versionBefore = version;
954
+ armTimeout(NAVIGATION_OUTCOME.FAR_BACK);
955
+ return;
956
+ }
957
+
958
+ const didCommit = env.getNavigationVersion() !== versionBefore;
959
+ if (didCommit && !env.isRendered(id)) {
960
+ finish(NAVIGATION_OUTCOME.FAR_BACK);
961
+ }
962
+ }
963
+
964
+ return { promise, step };
965
+ }
966
+
967
+ // Runs the active navigation after each engine commit and row registration.
968
+ function useItemArrival({
969
+ hasMoreOlder,
970
+ loadOlderPage,
971
+ loadThroughRef,
972
+ maxOlderPages,
973
+ messages,
974
+ navigationVersion,
975
+ revealCachedItemRef,
976
+ scrollToLoadedMessage,
977
+ }) {
978
+ const stateRef = useRef({ hasMoreOlder, messages, navigationVersion });
979
+ const stepRef = useRef(null);
980
+ const isRunQueuedRef = useRef(false);
981
+
982
+ const runWaiter = useCallback(() => {
983
+ stepRef.current?.();
984
+ }, []);
985
+
986
+ useLayoutEffect(() => {
987
+ stateRef.current = { hasMoreOlder, messages, navigationVersion };
988
+ }, [hasMoreOlder, messages, navigationVersion]);
989
+ // This effect has no dependency list. It runs after every engine commit,
990
+ // after the rows of that commit registered.
991
+ useLayoutEffect(() => {
992
+ runWaiter();
993
+ });
994
+
995
+ // A row can register outside a commit. Run the waiter once after it.
996
+ const notifyRegistered = useCallback(() => {
997
+ if (!stepRef.current || isRunQueuedRef.current) return;
998
+
999
+ isRunQueuedRef.current = true;
1000
+ queueMicrotask(() => {
1001
+ isRunQueuedRef.current = false;
1002
+ runWaiter();
1003
+ });
1004
+ }, [runWaiter]);
1005
+
1006
+ const env = useMemo(
1007
+ () => ({
1008
+ getNavigationVersion: () => stateRef.current.navigationVersion,
1009
+ hasMoreOlder: () => stateRef.current.hasMoreOlder,
1010
+ isRendered: (id) =>
1011
+ stateRef.current.messages.some((item) => item.id === id),
1012
+ loadOlderPage,
1013
+ loadThrough: (target) => loadThroughRef.current(target),
1014
+ maxOlderPages,
1015
+ reveal: (id) => revealCachedItemRef.current(id),
1016
+ scrollTo: scrollToLoadedMessage,
1017
+ }),
1018
+ [
1019
+ loadOlderPage,
1020
+ loadThroughRef,
1021
+ maxOlderPages,
1022
+ revealCachedItemRef,
1023
+ scrollToLoadedMessage,
1024
+ ],
1025
+ );
1026
+ // Returns a promise of the outcome. `isCurrent` shows if the navigation
1027
+ // still owns the view.
1028
+ const navigate = useCallback(
1029
+ (id, options, isCurrent) => {
1030
+ // An onNavigation callback can start a newer command before this call.
1031
+ if (!isCurrent()) return Promise.resolve(NAVIGATION_OUTCOME.SUPERSEDED);
1032
+
1033
+ const { promise, step } = createArrivalWaiter({
1034
+ id,
1035
+ options,
1036
+ isCurrent,
1037
+ env,
1038
+ onFinish: () => {
1039
+ if (stepRef.current === step) stepRef.current = null;
1040
+ },
1041
+ });
1042
+ stepRef.current = step;
1043
+ step();
1044
+ return promise;
1045
+ },
1046
+ [env],
1047
+ );
1048
+
1049
+ return { navigate, notifyRegistered, runWaiter };
1050
+ }
1051
+
1052
+ function useItemHighlight(
1053
+ highlightDuration = DEFAULT_NAVIGATION.highlightDuration,
1054
+ ) {
1055
+ const highlightDurationRef = useRef(highlightDuration);
1056
+ highlightDurationRef.current = highlightDuration;
1057
+ const highlightTimeoutRef = useRef(undefined);
1058
+ const [highlightedMessageId, setHighlightedMessageId] = useState(undefined);
1059
+ const setHighlight = useCallback((id) => {
1060
+ setHighlightedMessageId(id);
1061
+ if (highlightTimeoutRef.current !== undefined) {
1062
+ window.clearTimeout(highlightTimeoutRef.current);
1063
+ }
1064
+ highlightTimeoutRef.current = window.setTimeout(() => {
1065
+ setHighlightedMessageId((current) =>
1066
+ current === id ? undefined : current,
1067
+ );
1068
+ }, highlightDurationRef.current);
1069
+ }, []);
1070
+
1071
+ useEffect(
1072
+ () => () => {
1073
+ if (highlightTimeoutRef.current !== undefined) {
1074
+ window.clearTimeout(highlightTimeoutRef.current);
1075
+ }
1076
+ },
1077
+ [],
1078
+ );
1079
+
1080
+ return { highlightedMessageId, setHighlight };
1081
+ }
1082
+
1083
+ function useTimelineMessageNavigation({
1084
+ didRestoreRef,
1085
+ hasMoreOlder,
1086
+ loadOlderPage,
1087
+ messageElementsRef,
1088
+ messages,
1089
+ navigationVersion,
1090
+ initialMessageId,
1091
+ initialMessageTime,
1092
+ isLoading,
1093
+ scrollCommandRef,
1094
+ scrollContainerRef,
1095
+ loadThroughMessage,
1096
+ maxOlderPages = DEFAULT_NAVIGATION.maxOlderPages,
1097
+ highlightDuration = DEFAULT_NAVIGATION.highlightDuration,
1098
+ revealCachedItem,
1099
+ scrollToBottom,
1100
+ startScrollCommand,
1101
+ onNavigation,
1102
+ readingPosition,
1103
+ rowDetach,
1104
+ viewport,
1105
+ attachVersion = 0,
1106
+ }) {
1107
+ const revealCachedItemRef = useRef(revealCachedItem);
1108
+ const loadThroughRef = useRef(loadThroughMessage);
1109
+ const onNavigationRef = useRef(onNavigation);
1110
+ const { highlightedMessageId, setHighlight } =
1111
+ useItemHighlight(highlightDuration);
1112
+ const scrollToLoadedMessage = useCallback(
1113
+ (id, options) => {
1114
+ const element = messageElementsRef.current.get(id);
1115
+ const container = scrollContainerRef.current;
1116
+ if (!element || !container) return false;
1117
+
1118
+ // The write can run a consumer callback that starts a newer navigation.
1119
+ // Set the highlight first, so the newer navigation sets the last one.
1120
+ if (options.highlight) setHighlight(id);
1121
+ didRestoreRef.current = true;
1122
+ // The target row is the reading position. Its offset after the write
1123
+ // follows from the numbers before the write.
1124
+ const target = getCenteredScrollTop(container, element);
1125
+ const metrics = readTimelineScrollMetrics(container);
1126
+ const rowTop = getItemOffsetFromContainerTop(container, element);
1127
+ readingPosition.anchorTo(
1128
+ id,
1129
+ rowTop - (target - metrics.scrollTop),
1130
+ target,
1131
+ metrics.scrollHeight,
1132
+ );
1133
+ viewport.write(container, target, { persist: true });
1134
+ return true;
1135
+ },
1136
+ [
1137
+ didRestoreRef,
1138
+ messageElementsRef,
1139
+ readingPosition,
1140
+ scrollContainerRef,
1141
+ setHighlight,
1142
+ viewport,
1143
+ ],
1144
+ );
1145
+ const { navigate, notifyRegistered, runWaiter } = useItemArrival({
1146
+ hasMoreOlder,
1147
+ loadOlderPage,
1148
+ loadThroughRef,
1149
+ maxOlderPages,
1150
+ messages,
1151
+ navigationVersion,
1152
+ revealCachedItemRef,
1153
+ scrollToLoadedMessage,
1154
+ });
1155
+ // When a row renders again, React calls its previous inline ref with null.
1156
+ // takeRecords() clears the removal records. Check once per commit to
1157
+ // prevent a later ref from forcing layout after a removal.
1158
+ const didPrepareDetachRef = useRef(false);
1159
+ useLayoutEffect(() => {
1160
+ didPrepareDetachRef.current = false;
1161
+ rowDetach.finish();
1162
+ });
1163
+
1164
+ const registerItemElement = useCallback(
1165
+ (id, element) => {
1166
+ const elements = messageElementsRef.current;
1167
+ if (element) {
1168
+ // A child can replace rows without rendering this hook. React
1169
+ // attaches the new refs after it removes the old rows.
1170
+ if (didPrepareDetachRef.current) {
1171
+ didPrepareDetachRef.current = false;
1172
+ rowDetach.finish();
1173
+ }
1174
+ elements.set(id, element);
1175
+ notifyRegistered();
1176
+ return;
1177
+ }
1178
+ if (!didPrepareDetachRef.current) {
1179
+ const row = elements.get(id);
1180
+ if (row) didPrepareDetachRef.current = rowDetach.prepare(row);
1181
+ }
1182
+ elements.delete(id);
1183
+ },
1184
+ [messageElementsRef, notifyRegistered, rowDetach],
1185
+ );
1186
+
1187
+ // Takes the scroll command token. The returned check stays true until a
1188
+ // newer command (a navigation or a jump to the latest items), a target
1189
+ // change, or an unmount replaces the token. The older waiter ends now.
1190
+ const startNavigation = useCallback(() => {
1191
+ const isCurrent = startScrollCommand();
1192
+ runWaiter();
1193
+ return isCurrent;
1194
+ }, [runWaiter, startScrollCommand]);
1195
+ useLayoutEffect(() => {
1196
+ revealCachedItemRef.current = revealCachedItem;
1197
+ loadThroughRef.current = loadThroughMessage;
1198
+ onNavigationRef.current = onNavigation;
1199
+ }, [loadThroughMessage, onNavigation, revealCachedItem]);
1200
+
1201
+ const { initialTargetPending, setCompletedInitialMessageId } =
1202
+ useInitialTarget({
1203
+ attachVersion,
1204
+ initialMessageId,
1205
+ initialMessageTime,
1206
+ isLoading,
1207
+ onNavigationRef,
1208
+ scrollCommandRef,
1209
+ runNavigation: navigate,
1210
+ scrollToBottom,
1211
+ scrollToLoadedMessage,
1212
+ startNavigation,
1213
+ });
1214
+ // The user takes over. A target that the view still opens at is released,
1215
+ // and the command that owns the view ends.
1216
+ const takeOver = useCallback(() => {
1217
+ if (initialMessageId) setCompletedInitialMessageId(initialMessageId);
1218
+ return startNavigation();
1219
+ }, [initialMessageId, setCompletedInitialMessageId, startNavigation]);
1220
+
1221
+ const navigateTo = useCallback(
1222
+ ({ id, time }) => {
1223
+ const isCurrent = takeOver();
1224
+ const complete = onNavigationRef.current?.({
1225
+ trigger: NAVIGATION_TRIGGER.NAVIGATE,
1226
+ id,
1227
+ time,
1228
+ });
1229
+ void navigate(id, { highlight: true, time }, isCurrent).then((result) => {
1230
+ // Check the token, not the result. A navigation can end after it
1231
+ // returns and before this callback runs.
1232
+ if (result === NAVIGATION_OUTCOME.SUPERSEDED || !isCurrent()) return;
1233
+
1234
+ complete?.(result);
1235
+ });
1236
+ },
1237
+ [navigate, takeOver],
1238
+ );
1239
+
1240
+ const scrollToLatest = useCallback(
1241
+ (options) => scrollToBottom(options, takeOver()),
1242
+ [scrollToBottom, takeOver],
1243
+ );
1244
+
1245
+ useEffect(
1246
+ () => () => {
1247
+ scrollCommandRef.current = undefined;
1248
+ runWaiter();
1249
+ },
1250
+ [runWaiter, scrollCommandRef],
1251
+ );
1252
+
1253
+ return {
1254
+ highlightedMessageId,
1255
+ initialTargetPending,
1256
+ navigateTo,
1257
+ registerItemElement,
1258
+ scrollToLatest,
1259
+ };
1260
+ }
1261
+
1262
+ function useTimelineMessageReach({
1263
+ isMessageBeforeWindow,
1264
+ messageId,
1265
+ messages,
1266
+ messageElementsRef,
1267
+ scrollContainerRef,
1268
+ }) {
1269
+ const [reachedMessageId, setReachedMessageId] = useState();
1270
+ const isMessageReached = Boolean(messageId && reachedMessageId === messageId);
1271
+ const updateMessageReach = useCallback(() => {
1272
+ if (!messageId || reachedMessageId === messageId) return;
1273
+ if (isMessageBeforeWindow) {
1274
+ setReachedMessageId(messageId);
1275
+ return;
1276
+ }
1277
+
1278
+ const container = scrollContainerRef.current;
1279
+ const messageElement = messageElementsRef.current.get(messageId);
1280
+ if (
1281
+ !container ||
1282
+ !messageElement ||
1283
+ !isTimelineMessageReached(container, messageElement)
1284
+ ) {
1285
+ return;
1286
+ }
1287
+
1288
+ setReachedMessageId(messageId);
1289
+ }, [
1290
+ isMessageBeforeWindow,
1291
+ messageElementsRef,
1292
+ messageId,
1293
+ reachedMessageId,
1294
+ scrollContainerRef,
1295
+ ]);
1296
+
1297
+ // biome-ignore lint/correctness/useExhaustiveDependencies: `messages` is a trigger. The reach check must run again after each change to the rendered items.
1298
+ useLayoutEffect(() => {
1299
+ // Check again after page commits and layout corrections, before read
1300
+ // effects can run.
1301
+ updateMessageReach();
1302
+ }, [messages, updateMessageReach]);
1303
+
1304
+ return { isMessageReached, updateMessageReach };
1305
+ }
1306
+
1307
+ const NO_LAYOUT_WRITE = () => {};
1308
+
1309
+ // Restores the reading position after the container or the item list changed
1310
+ // size. A pending post-paint correction runs first, because the offset is not
1311
+ // reliable before it paints.
1312
+ function useTimelineViewportStability({
1313
+ attachVersion = 0,
1314
+ didRestoreRef,
1315
+ isMessageListRendered,
1316
+ itemListRef,
1317
+ platform,
1318
+ readingPosition,
1319
+ scrollContainerRef,
1320
+ scrollCorrection,
1321
+ viewport,
1322
+ }) {
1323
+ const { observeResize, scheduleMeasurement } = platform;
1324
+
1325
+ // biome-ignore lint/correctness/useExhaustiveDependencies: `isMessageListRendered` and `attachVersion` are triggers. The observers attach when the item list mounts or a DOM ref attaches after mount.
1326
+ useLayoutEffect(() => {
1327
+ const elements = [scrollContainerRef.current, itemListRef.current].filter(
1328
+ (element) => element !== null,
1329
+ );
1330
+ if (elements.length === 0) return;
1331
+
1332
+ const measurementKey = {};
1333
+ let isActive = true;
1334
+ let cancelScheduledCorrection = null;
1335
+ const readCorrection = () => {
1336
+ const element = scrollContainerRef.current;
1337
+ if (!element || !didRestoreRef.current) return NO_LAYOUT_WRITE;
1338
+
1339
+ if (scrollCorrection.hasPendingScrollCorrection()) {
1340
+ void scrollCorrection.waitForSettledScrollTop().then(() => {
1341
+ if (isActive) scheduleViewportCorrection();
1342
+ });
1343
+ return NO_LAYOUT_WRITE;
1344
+ }
1345
+
1346
+ const restore = readingPosition.planRestore(element, viewport);
1347
+ return () => {
1348
+ if (scrollContainerRef.current === element) restore();
1349
+ };
1350
+ };
1351
+
1352
+ const scheduleViewportCorrection = () => {
1353
+ cancelScheduledCorrection = scheduleMeasurement(
1354
+ measurementKey,
1355
+ readCorrection,
1356
+ );
1357
+ };
1358
+ const stopResizeObservations = elements.map((element) =>
1359
+ observeResize(element, scheduleViewportCorrection),
1360
+ );
1361
+
1362
+ return () => {
1363
+ isActive = false;
1364
+ cancelScheduledCorrection?.();
1365
+ for (const stopResizeObservation of stopResizeObservations) {
1366
+ stopResizeObservation?.();
1367
+ }
1368
+ };
1369
+ }, [
1370
+ attachVersion,
1371
+ didRestoreRef,
1372
+ isMessageListRendered,
1373
+ itemListRef,
1374
+ observeResize,
1375
+ readingPosition,
1376
+ scheduleMeasurement,
1377
+ scrollContainerRef,
1378
+ scrollCorrection,
1379
+ viewport,
1380
+ ]);
1381
+ }
1382
+
1383
+ const WEBKIT_CSS_SUPPORT_QUERY = '(-webkit-backdrop-filter: none)';
1384
+
1385
+ function useTimelineMessageLayout({
1386
+ attachVersion = 0,
1387
+ containerAttachVersion = 0,
1388
+ bottomInset,
1389
+ commitRender,
1390
+ followsAppend,
1391
+ initialMessageId,
1392
+ isLoading,
1393
+ messages,
1394
+ sourceMessages,
1395
+ itemListRef,
1396
+ olderPageVersion,
1397
+ navigationVersion,
1398
+ onAnchorLost,
1399
+ platform,
1400
+ previousScrollTopRef,
1401
+ readingPosition,
1402
+ scrollContainerRef,
1403
+ scrollCorrection,
1404
+ scrollMemory,
1405
+ updateScrollState,
1406
+ updateScrollPosition,
1407
+ viewport,
1408
+ wasAtBottomRef,
1409
+ }) {
1410
+ const didRestoreRef = useRef(false);
1411
+ const previousSourceLastIdRef = useRef(undefined);
1412
+ const previousContainerRef = useRef(null);
1413
+ const rowDetachObserverRef = useRef(null);
1414
+ // biome-ignore lint/correctness/useExhaustiveDependencies: containerAttachVersion tracks a new container element
1415
+ useLayoutEffect(() => {
1416
+ const element = scrollContainerRef.current;
1417
+ const view = element?.ownerDocument.defaultView;
1418
+ if (
1419
+ !view?.MutationObserver ||
1420
+ !view.CSS?.supports(WEBKIT_CSS_SUPPORT_QUERY)
1421
+ ) {
1422
+ return;
1423
+ }
1424
+
1425
+ // Read pending removals during ref cleanup. The callback needs no records.
1426
+ const observer = new view.MutationObserver(() => {});
1427
+ observer.observe(element, { childList: true, subtree: true });
1428
+ rowDetachObserverRef.current = observer;
1429
+ return () => {
1430
+ rowDetachObserverRef.current = null;
1431
+ observer.disconnect();
1432
+ };
1433
+ }, [containerAttachVersion, scrollContainerRef]);
1434
+
1435
+ const rowDetach = useMemo(
1436
+ () => ({
1437
+ prepare(row) {
1438
+ const observer = rowDetachObserverRef.current;
1439
+ const element = scrollContainerRef.current;
1440
+ if (
1441
+ !observer ||
1442
+ !didRestoreRef.current ||
1443
+ !wasAtBottomRef.current ||
1444
+ !element ||
1445
+ element !== previousContainerRef.current ||
1446
+ !element.contains(row) ||
1447
+ scrollCorrection.hasPendingScrollCorrection()
1448
+ ) {
1449
+ return false;
1450
+ }
1451
+
1452
+ // WebKit can clamp the offset while React replaces rows. Read before
1453
+ // removal to update layout. A read after removal can cause a clamp.
1454
+ const records = observer.takeRecords();
1455
+ if (!records.some(({ removedNodes }) => removedNodes.length)) {
1456
+ void element.scrollTop;
1457
+ }
1458
+ return true;
1459
+ },
1460
+
1461
+ finish() {
1462
+ rowDetachObserverRef.current?.takeRecords();
1463
+ },
1464
+ }),
1465
+ [scrollContainerRef, scrollCorrection, wasAtBottomRef],
1466
+ );
1467
+
1468
+ const applyInitialPosition = useCallback(
1469
+ (element) => {
1470
+ didRestoreRef.current = true;
1471
+ if (scrollMemory?.atBottom !== false) {
1472
+ viewport.write(element, element.scrollHeight);
1473
+ return;
1474
+ }
1475
+
1476
+ // The saved position decides, not a state that an empty list set.
1477
+ wasAtBottomRef.current = false;
1478
+ const isSeeded = readingPosition.seed(scrollMemory);
1479
+ const result = isSeeded
1480
+ ? readingPosition.restore(element, viewport)
1481
+ : undefined;
1482
+ if (result && !result.lost) return;
1483
+
1484
+ // The saved row is not rendered. Use the saved offset.
1485
+ viewport.write(element, scrollMemory.scrollTop);
1486
+ readingPosition.measure(element);
1487
+ },
1488
+ [readingPosition, scrollMemory, viewport, wasAtBottomRef],
1489
+ );
1490
+
1491
+ const scrollToBottom = useCallback(
1492
+ (options = {}) => {
1493
+ const element = scrollContainerRef.current;
1494
+ if (!element) return;
1495
+
1496
+ didRestoreRef.current = true;
1497
+ if (
1498
+ options.behavior === SCROLL_BEHAVIOR.SMOOTH &&
1499
+ typeof element.scrollTo === VALUE_TYPE.FUNCTION &&
1500
+ element.scrollTop <
1501
+ getMaximumScrollTop(element) - SCROLL.OFFSET_ROUNDING_TOLERANCE_PX
1502
+ ) {
1503
+ viewport.scrollSmoothly(element, element.scrollHeight);
1504
+ return;
1505
+ }
1506
+
1507
+ viewport.write(element, element.scrollHeight, { persist: true });
1508
+ },
1509
+ [scrollContainerRef, viewport],
1510
+ );
1511
+
1512
+ // biome-ignore lint/correctness/useExhaustiveDependencies: containerAttachVersion and bottomInset are triggers: the position is restored when the scroll container attaches after mount and when the bottom inset changes
1513
+ useLayoutEffect(() => {
1514
+ const element = scrollContainerRef.current;
1515
+ if (!element) return;
1516
+
1517
+ // A consumer commit can run before the browser delivers the scroll event.
1518
+ // Read that movement before restoring the old anchor. A new container and
1519
+ // an unpainted correction still use the saved reading position.
1520
+ if (
1521
+ previousContainerRef.current === element &&
1522
+ didRestoreRef.current &&
1523
+ !scrollCorrection.hasPendingScrollCorrection() &&
1524
+ Math.abs(element.scrollTop - previousScrollTopRef.current) >
1525
+ SCROLL.OFFSET_ROUNDING_TOLERANCE_PX
1526
+ ) {
1527
+ updateScrollPosition();
1528
+ }
1529
+ previousContainerRef.current = element;
1530
+
1531
+ const lastMessage = messages.at(-1);
1532
+ const lastId = sourceMessages.at(-1)?.id;
1533
+ const isTailAddition =
1534
+ Boolean(lastId) &&
1535
+ lastMessage?.id === lastId &&
1536
+ lastId !== previousSourceLastIdRef.current;
1537
+ const isOwnSend = isTailAddition && followsAppend(lastMessage);
1538
+ const followsTail =
1539
+ isOwnSend ||
1540
+ (isTailAddition && didRestoreRef.current && wasAtBottomRef.current);
1541
+ // A followed append can first change the window. Record it only after
1542
+ // the new last item renders, so its position and follow state change together.
1543
+ if (isTailAddition) previousSourceLastIdRef.current = lastId;
1544
+
1545
+ const reason = commitRender({
1546
+ messages,
1547
+ sourceMessages,
1548
+ olderPageVersion,
1549
+ navigationVersion,
1550
+ isTailFollowed: followsTail,
1551
+ });
1552
+
1553
+ if (!didRestoreRef.current && !isOwnSend) {
1554
+ if (messages.length === 0 || isLoading) {
1555
+ updateScrollState(element, undefined, { measure: true });
1556
+ } else if (!initialMessageId) {
1557
+ applyInitialPosition(element);
1558
+ }
1559
+ return;
1560
+ }
1561
+
1562
+ if (isOwnSend) {
1563
+ wasAtBottomRef.current = true;
1564
+ didRestoreRef.current = true;
1565
+ }
1566
+ const result = readingPosition.restore(element, viewport, {
1567
+ persist: followsTail,
1568
+ reason,
1569
+ });
1570
+ if (!result.written) updateScrollState(element);
1571
+ // The anchor row left the rendered window, or the browser must clamp the
1572
+ // restore offset so the anchor row moves. Stop automatic paging.
1573
+ if (reason && (result.lost || result.clamped)) onAnchorLost();
1574
+ }, [
1575
+ bottomInset,
1576
+ containerAttachVersion,
1577
+ applyInitialPosition,
1578
+ commitRender,
1579
+ followsAppend,
1580
+ initialMessageId,
1581
+ isLoading,
1582
+ messages,
1583
+ navigationVersion,
1584
+ olderPageVersion,
1585
+ onAnchorLost,
1586
+ previousScrollTopRef,
1587
+ readingPosition,
1588
+ scrollContainerRef,
1589
+ scrollCorrection,
1590
+ sourceMessages,
1591
+ updateScrollState,
1592
+ updateScrollPosition,
1593
+ viewport,
1594
+ wasAtBottomRef,
1595
+ ]);
1596
+
1597
+ useTimelineViewportStability({
1598
+ attachVersion,
1599
+ didRestoreRef,
1600
+ isMessageListRendered: messages.length > 0,
1601
+ itemListRef,
1602
+ platform,
1603
+ readingPosition,
1604
+ scrollContainerRef,
1605
+ scrollCorrection,
1606
+ viewport,
1607
+ });
1608
+
1609
+ return { didRestoreRef, rowDetach, scrollToBottom };
1610
+ }
1611
+
1612
+ const NO_PAGE_COMMIT = Object.freeze({
1613
+ didCommit: false,
1614
+ shouldRestoreOffset: false,
1615
+ });
1616
+ const PAGE_COMMIT_WITHOUT_OFFSET_RESTORE = Object.freeze({
1617
+ didCommit: true,
1618
+ shouldRestoreOffset: false,
1619
+ });
1620
+ const PAGE_COMMIT_WITH_OFFSET_RESTORE = Object.freeze({
1621
+ didCommit: true,
1622
+ shouldRestoreOffset: true,
1623
+ });
1624
+
1625
+ function getTimelinePageCommit({
1626
+ olderPageVersion,
1627
+ pendingPageLoad,
1628
+ renderedMessages,
1629
+ sourceMessages,
1630
+ }) {
1631
+ const didChangeFirstMessage =
1632
+ renderedMessages[0]?.id !== pendingPageLoad.renderedFirstMessageId;
1633
+ const didChangeLastMessage =
1634
+ renderedMessages.at(-1)?.id !== pendingPageLoad.renderedLastMessageId;
1635
+ const didCommitOlderPageVersion =
1636
+ olderPageVersion !== pendingPageLoad.olderPageVersion;
1637
+ const didCommitVisiblePageBoundary =
1638
+ didChangeFirstMessage &&
1639
+ (!pendingPageLoad.requiresOlderPageVersion || didCommitOlderPageVersion);
1640
+ if (didCommitVisiblePageBoundary) return PAGE_COMMIT_WITH_OFFSET_RESTORE;
1641
+
1642
+ if (pendingPageLoad.direction === PAGE_LOAD_DIRECTION.NEWER) {
1643
+ return didChangeLastMessage
1644
+ ? PAGE_COMMIT_WITHOUT_OFFSET_RESTORE
1645
+ : NO_PAGE_COMMIT;
1646
+ }
1647
+
1648
+ const mayHaveCommittedNoVisibleOlderPage =
1649
+ pendingPageLoad.requiresOlderPageVersion &&
1650
+ didCommitOlderPageVersion &&
1651
+ !didChangeFirstMessage;
1652
+ if (!mayHaveCommittedNoVisibleOlderPage) return NO_PAGE_COMMIT;
1653
+
1654
+ const renderedFirstMessageId = renderedMessages[0]?.id;
1655
+ const hasCachedOlderSourceMessages = renderedFirstMessageId
1656
+ ? sourceMessages.findIndex(
1657
+ (message) => message.id === renderedFirstMessageId,
1658
+ ) > 0
1659
+ : false;
1660
+ return hasCachedOlderSourceMessages
1661
+ ? NO_PAGE_COMMIT
1662
+ : PAGE_COMMIT_WITHOUT_OFFSET_RESTORE;
1663
+ }
1664
+
1665
+ function settlePage(page) {
1666
+ if (!page.didFinishLoad || page.didCommit === undefined) return;
1667
+
1668
+ page.resolve(page.didCommit);
1669
+ }
1670
+
1671
+ function useTimelinePageLoading({
1672
+ messages,
1673
+ sourceMessages,
1674
+ hasMoreOlder,
1675
+ hasMoreNewer,
1676
+ olderPageVersion,
1677
+ navigationVersion,
1678
+ isLoadingOlder,
1679
+ loadOlder,
1680
+ loadNewer,
1681
+ scrollContainerRef,
1682
+ updateScrollState,
1683
+ }) {
1684
+ const pendingCommitRef = useRef(null);
1685
+ const loadingPagesRef = useRef({ older: null, newer: null });
1686
+ const inputs = {
1687
+ messages,
1688
+ sourceMessages,
1689
+ hasMoreOlder,
1690
+ hasMoreNewer,
1691
+ olderPageVersion,
1692
+ navigationVersion,
1693
+ isLoadingOlder,
1694
+ loadOlder,
1695
+ loadNewer,
1696
+ };
1697
+ const inputsRef = useRef(inputs);
1698
+ useLayoutEffect(() => {
1699
+ inputsRef.current = inputs;
1700
+ });
1701
+
1702
+ const finishCommit = useCallback((page, didCommit) => {
1703
+ if (pendingCommitRef.current !== page) return;
1704
+
1705
+ window.clearTimeout(page.timeoutId);
1706
+ page.didCommit = didCommit;
1707
+ pendingCommitRef.current = null;
1708
+ settlePage(page);
1709
+ }, []);
1710
+
1711
+ const startPage = useCallback(
1712
+ (direction) => {
1713
+ const loadingPages = loadingPagesRef.current;
1714
+ if (pendingCommitRef.current || loadingPages[direction]) return null;
1715
+
1716
+ const current = inputsRef.current;
1717
+ const element = scrollContainerRef.current;
1718
+ const isOlder = direction === PAGE_LOAD_DIRECTION.OLDER;
1719
+ if (
1720
+ isOlder
1721
+ ? !element || !current.hasMoreOlder || current.isLoadingOlder
1722
+ : !current.hasMoreNewer
1723
+ ) {
1724
+ return null;
1725
+ }
1726
+
1727
+ const renderedFirstMessageId = current.messages[0]?.id;
1728
+ const firstSourceIndex = isOlder
1729
+ ? current.sourceMessages.findIndex(
1730
+ (message) => message.id === renderedFirstMessageId,
1731
+ )
1732
+ : -1;
1733
+ let resolve;
1734
+ const settled = new Promise((finish) => {
1735
+ resolve = finish;
1736
+ });
1737
+ const page = {
1738
+ direction,
1739
+ requiresOlderPageVersion: isOlder && firstSourceIndex <= 0,
1740
+ navigationVersion: current.navigationVersion,
1741
+ renderedFirstMessageId,
1742
+ renderedLastMessageId: current.messages.at(-1)?.id,
1743
+ olderPageVersion: current.olderPageVersion,
1744
+ settled,
1745
+ resolve,
1746
+ };
1747
+ pendingCommitRef.current = page;
1748
+ loadingPages[direction] = page;
1749
+
1750
+ const load = isOlder ? current.loadOlder : current.loadNewer;
1751
+ const loaded = (async () => {
1752
+ let didLoad = false;
1753
+ try {
1754
+ didLoad = await load();
1755
+ } catch {
1756
+ // A failed source load leaves the page available to retry.
1757
+ }
1758
+
1759
+ loadingPages[direction] = null;
1760
+ page.didFinishLoad = true;
1761
+ if (page.didCommit !== undefined) {
1762
+ settlePage(page);
1763
+ } else if (didLoad) {
1764
+ page.timeoutId = window.setTimeout(() => {
1765
+ finishCommit(page, false);
1766
+ }, SCROLL.PAGE_COMMIT_TIMEOUT_MS);
1767
+ } else {
1768
+ finishCommit(page, false);
1769
+ }
1770
+
1771
+ // An older load can pause the window's follow state before it fails.
1772
+ if (!didLoad && isOlder && scrollContainerRef.current === element) {
1773
+ updateScrollState(element);
1774
+ }
1775
+ return didLoad;
1776
+ })();
1777
+ return { loaded, settled };
1778
+ },
1779
+ [finishCommit, scrollContainerRef, updateScrollState],
1780
+ );
1781
+
1782
+ const requestLoadOlder = useCallback(
1783
+ async () => startPage(PAGE_LOAD_DIRECTION.OLDER)?.loaded ?? false,
1784
+ [startPage],
1785
+ );
1786
+
1787
+ const requestLoadNewer = useCallback(
1788
+ async () => startPage(PAGE_LOAD_DIRECTION.NEWER)?.loaded ?? false,
1789
+ [startPage],
1790
+ );
1791
+
1792
+ const loadOlderPage = useCallback(
1793
+ async (isCurrent) => {
1794
+ while (isCurrent()) {
1795
+ const pending = pendingCommitRef.current;
1796
+ if (pending?.direction === PAGE_LOAD_DIRECTION.OLDER)
1797
+ return pending.settled;
1798
+
1799
+ // A newer page or an older page that already committed does not count
1800
+ // toward this search. Wait until an older request can start.
1801
+ const blockingPage = pending ?? loadingPagesRef.current.older;
1802
+ if (!blockingPage)
1803
+ return startPage(PAGE_LOAD_DIRECTION.OLDER)?.settled ?? false;
1804
+
1805
+ await blockingPage.settled;
1806
+ }
1807
+ return false;
1808
+ },
1809
+ [startPage],
1810
+ );
1811
+
1812
+ const commitRender = useCallback(
1813
+ ({
1814
+ messages,
1815
+ sourceMessages,
1816
+ olderPageVersion,
1817
+ navigationVersion,
1818
+ isTailFollowed,
1819
+ }) => {
1820
+ const page = pendingCommitRef.current;
1821
+ if (!page) return undefined;
1822
+
1823
+ if (isTailFollowed || navigationVersion !== page.navigationVersion) {
1824
+ finishCommit(page, false);
1825
+ return undefined;
1826
+ }
1827
+
1828
+ const { didCommit, shouldRestoreOffset } = getTimelinePageCommit({
1829
+ olderPageVersion,
1830
+ pendingPageLoad: page,
1831
+ renderedMessages: messages,
1832
+ sourceMessages,
1833
+ });
1834
+ if (!didCommit) return undefined;
1835
+
1836
+ finishCommit(page, true);
1837
+ if (!shouldRestoreOffset) return undefined;
1838
+
1839
+ return page.direction === PAGE_LOAD_DIRECTION.OLDER
1840
+ ? RESTORE_REASON.OLDER_PAGE
1841
+ : RESTORE_REASON.NEWER_PAGE;
1842
+ },
1843
+ [finishCommit],
1844
+ );
1845
+
1846
+ useEffect(
1847
+ () => () => {
1848
+ const page = pendingCommitRef.current;
1849
+ if (page) finishCommit(page, false);
1850
+ },
1851
+ [finishCommit],
1852
+ );
1853
+
1854
+ return { commitRender, loadOlderPage, requestLoadNewer, requestLoadOlder };
1855
+ }
1856
+
1857
+ function getTimelinePagePrefetchDistance(
1858
+ clientHeight,
1859
+ { prefetchMin, prefetchMax } = DEFAULT_THRESHOLDS,
1860
+ ) {
1861
+ const viewportDistance = Math.round(
1862
+ clientHeight * SCROLL.PAGE_PREFETCH_VIEWPORT_MULTIPLIER,
1863
+ );
1864
+ return Math.min(prefetchMax, Math.max(prefetchMin, viewportDistance));
1865
+ }
1866
+
1867
+ // Both distances use viewport coordinates, so the scroller does not need to
1868
+ // be the offset parent of the list. `older` is how far the viewport top is
1869
+ // below the list top. `newer` is how far the list bottom is below the
1870
+ // viewport bottom. A list that is not measured has no height. Then use the
1871
+ // extent of the scroller.
1872
+ function getListBoundaryDistances(container, list) {
1873
+ const { clientHeight, scrollHeight, scrollTop } = container;
1874
+ const listRect = list?.getBoundingClientRect();
1875
+ if (!listRect || listRect.height <= 0) {
1876
+ return { older: scrollTop, newer: scrollHeight - scrollTop - clientHeight };
1877
+ }
1878
+ const viewportTop =
1879
+ container.getBoundingClientRect().top + container.clientTop;
1880
+ return {
1881
+ older: viewportTop - listRect.top,
1882
+ newer: listRect.bottom - (viewportTop + clientHeight),
1883
+ };
1884
+ }
1885
+
1886
+ function getTimelineInitialPageLoadDirection({
1887
+ clientHeight,
1888
+ hasMoreNewer,
1889
+ hasMoreOlder,
1890
+ primeRestoredWindow,
1891
+ scrollHeight,
1892
+ scrollTop,
1893
+ }) {
1894
+ const isMeasurableShortTimeline =
1895
+ clientHeight > 0 && scrollHeight <= clientHeight;
1896
+ if (!primeRestoredWindow && !isMeasurableShortTimeline) return null;
1897
+ if (!hasMoreOlder) return hasMoreNewer ? PAGE_LOAD_DIRECTION.NEWER : null;
1898
+ if (!hasMoreNewer) return PAGE_LOAD_DIRECTION.OLDER;
1899
+
1900
+ const distanceFromBottom = scrollHeight - scrollTop - clientHeight;
1901
+ return distanceFromBottom < scrollTop
1902
+ ? PAGE_LOAD_DIRECTION.NEWER
1903
+ : PAGE_LOAD_DIRECTION.OLDER;
1904
+ }
1905
+
1906
+ const OBSERVER_OPTIONS = Object.freeze({
1907
+ ROOT_MARGIN: (distance) => `${distance}px 0px`,
1908
+ });
1909
+
1910
+ // Watches the two page boundaries with an IntersectionObserver. Entries that
1911
+ // the observer computed after the last measurement, while the zone is not
1912
+ // stale, set the boundary flags. Any other entry only wakes
1913
+ // `checkPagePrefetch`, which measures. Without IntersectionObserver, the
1914
+ // check runs once.
1915
+ function useTimelinePageBoundaryObserver({
1916
+ attachVersion = 0,
1917
+ checkPagePrefetch,
1918
+ didRestoreRef,
1919
+ prefetchZone,
1920
+ isReady,
1921
+ itemListRef,
1922
+ newerPageSentinelRef,
1923
+ observeResize,
1924
+ olderPageSentinelRef,
1925
+ prefetchMax,
1926
+ prefetchMin,
1927
+ requestEligiblePage,
1928
+ scrollContainerRef,
1929
+ }) {
1930
+ // biome-ignore lint/correctness/useExhaustiveDependencies: attachVersion is a trigger: the effect runs again when a DOM ref attaches after mount
1931
+ useEffect(() => {
1932
+ const element = scrollContainerRef.current;
1933
+ const newerPageSentinel = newerPageSentinelRef.current;
1934
+ const olderPageSentinel = olderPageSentinelRef.current;
1935
+ const supportsIntersectionObserver =
1936
+ typeof IntersectionObserver !== VALUE_TYPE.UNDEFINED;
1937
+ if (
1938
+ !element ||
1939
+ !newerPageSentinel ||
1940
+ !olderPageSentinel ||
1941
+ !isReady ||
1942
+ !didRestoreRef.current
1943
+ ) {
1944
+ return;
1945
+ }
1946
+ if (!supportsIntersectionObserver) {
1947
+ checkPagePrefetch();
1948
+ return;
1949
+ }
1950
+
1951
+ let observer = null;
1952
+ let appliedPrefetchDistance = null;
1953
+ const observePageBoundaries = () => {
1954
+ const prefetchDistance = getTimelinePagePrefetchDistance(
1955
+ element.clientHeight,
1956
+ { prefetchMin, prefetchMax },
1957
+ );
1958
+ if (prefetchDistance === appliedPrefetchDistance) return;
1959
+
1960
+ observer?.disconnect();
1961
+ prefetchZone.invalidate();
1962
+ prefetchZone.clearBoundaries();
1963
+ appliedPrefetchDistance = prefetchDistance;
1964
+ const nextObserver = new IntersectionObserver(
1965
+ (entries, notifyingObserver) => {
1966
+ if (observer !== notifyingObserver) return;
1967
+
1968
+ if (
1969
+ !prefetchZone.acceptEntries(
1970
+ entries,
1971
+ olderPageSentinel,
1972
+ newerPageSentinel,
1973
+ )
1974
+ ) {
1975
+ checkPagePrefetch({ measure: true });
1976
+ return;
1977
+ }
1978
+
1979
+ requestEligiblePage();
1980
+ },
1981
+ {
1982
+ root: element,
1983
+ rootMargin: OBSERVER_OPTIONS.ROOT_MARGIN(prefetchDistance),
1984
+ threshold: 0,
1985
+ },
1986
+ );
1987
+ observer = nextObserver;
1988
+ nextObserver.observe(olderPageSentinel);
1989
+ nextObserver.observe(newerPageSentinel);
1990
+ };
1991
+
1992
+ observePageBoundaries();
1993
+ const handleResize = () => {
1994
+ prefetchZone.invalidate();
1995
+ observePageBoundaries();
1996
+ checkPagePrefetch();
1997
+ };
1998
+ const itemList = itemListRef.current;
1999
+ const stopObservingResize = observeResize(element, handleResize);
2000
+ const stopObservingItemListResize = itemList
2001
+ ? observeResize(itemList, handleResize)
2002
+ : null;
2003
+ return () => {
2004
+ stopObservingResize?.();
2005
+ stopObservingItemListResize?.();
2006
+ observer?.disconnect();
2007
+ observer = null;
2008
+ appliedPrefetchDistance = null;
2009
+ prefetchZone.clearBoundaries();
2010
+ };
2011
+ }, [
2012
+ attachVersion,
2013
+ checkPagePrefetch,
2014
+ didRestoreRef,
2015
+ prefetchZone,
2016
+ isReady,
2017
+ itemListRef,
2018
+ newerPageSentinelRef,
2019
+ observeResize,
2020
+ olderPageSentinelRef,
2021
+ prefetchMax,
2022
+ prefetchMin,
2023
+ requestEligiblePage,
2024
+ scrollContainerRef,
2025
+ ]);
2026
+ }
2027
+
2028
+ function waitForTimelineLayout() {
2029
+ return new Promise((resolve) => {
2030
+ if (typeof window.requestAnimationFrame === VALUE_TYPE.FUNCTION) {
2031
+ window.requestAnimationFrame(() => resolve());
2032
+ return;
2033
+ }
2034
+
2035
+ window.setTimeout(resolve, 0);
2036
+ });
2037
+ }
2038
+
2039
+ function useTimelinePagePrefetchPump({
2040
+ isLoadingOlder,
2041
+ isReady,
2042
+ renderedFirstMessageId,
2043
+ renderedLastMessageId,
2044
+ requestPageIfEligible,
2045
+ }) {
2046
+ const generationRef = useRef(0);
2047
+ const isPendingRef = useRef(false);
2048
+ const previousBoundaryRef = useRef({
2049
+ firstMessageId: renderedFirstMessageId,
2050
+ lastMessageId: renderedLastMessageId,
2051
+ });
2052
+ const schedulePageRequest = useCallback(() => {
2053
+ const generation = ++generationRef.current;
2054
+ void waitForTimelineLayout().then(() => {
2055
+ if (generation !== generationRef.current) return;
2056
+ requestPageIfEligible();
2057
+ });
2058
+ }, [requestPageIfEligible]);
2059
+
2060
+ useEffect(() => {
2061
+ const previousBoundary = previousBoundaryRef.current;
2062
+ const didBoundaryChange =
2063
+ previousBoundary.firstMessageId !== renderedFirstMessageId ||
2064
+ previousBoundary.lastMessageId !== renderedLastMessageId;
2065
+ if (didBoundaryChange) {
2066
+ previousBoundaryRef.current = {
2067
+ firstMessageId: renderedFirstMessageId,
2068
+ lastMessageId: renderedLastMessageId,
2069
+ };
2070
+ isPendingRef.current = isReady;
2071
+ }
2072
+ if (!isReady) {
2073
+ isPendingRef.current = false;
2074
+ return;
2075
+ }
2076
+ if (!isPendingRef.current || isLoadingOlder) return;
2077
+
2078
+ isPendingRef.current = false;
2079
+ schedulePageRequest();
2080
+ }, [
2081
+ isLoadingOlder,
2082
+ isReady,
2083
+ renderedFirstMessageId,
2084
+ renderedLastMessageId,
2085
+ schedulePageRequest,
2086
+ ]);
2087
+ useEffect(
2088
+ () => () => {
2089
+ generationRef.current += 1;
2090
+ },
2091
+ [],
2092
+ );
2093
+ }
2094
+
2095
+ function useTimelinePagePrefetch({
2096
+ attachVersion = 0,
2097
+ autoPagingPausedRef,
2098
+ didRestoreRef,
2099
+ hasMoreNewer,
2100
+ hasMoreOlder,
2101
+ isLoadingOlder,
2102
+ isReady,
2103
+ itemListRef,
2104
+ newerPageSentinelRef,
2105
+ observeResize,
2106
+ olderPageSentinelRef,
2107
+ primeRestoredWindow = false,
2108
+ preferredDirectionRef,
2109
+ prefetchMin = DEFAULT_THRESHOLDS.prefetchMin,
2110
+ prefetchMax = DEFAULT_THRESHOLDS.prefetchMax,
2111
+ renderedFirstMessageId,
2112
+ renderedLastMessageId,
2113
+ requestLoadNewer,
2114
+ requestLoadOlder,
2115
+ scrollContainerRef,
2116
+ scrollCorrection,
2117
+ prefetchZone,
2118
+ }) {
2119
+ const inputs = {
2120
+ hasMoreNewer,
2121
+ hasMoreOlder,
2122
+ isLoadingOlder,
2123
+ isReady,
2124
+ primeRestoredWindow,
2125
+ requestLoadNewer,
2126
+ requestLoadOlder,
2127
+ scrollCorrection,
2128
+ };
2129
+ const inputsRef = useRef(inputs);
2130
+ useLayoutEffect(() => {
2131
+ inputsRef.current = inputs;
2132
+ });
2133
+ // A rendered boundary change moves the list ends.
2134
+ // biome-ignore lint/correctness/useExhaustiveDependencies: the boundary ids are the trigger
2135
+ useLayoutEffect(() => {
2136
+ prefetchZone.invalidate();
2137
+ }, [prefetchZone, renderedFirstMessageId, renderedLastMessageId]);
2138
+ const measureZone = useCallback(() => {
2139
+ const element = scrollContainerRef.current;
2140
+ if (!element || !inputsRef.current.isReady || !didRestoreRef.current) {
2141
+ return false;
2142
+ }
2143
+
2144
+ prefetchZone.measure(element, itemListRef.current, {
2145
+ prefetchMin,
2146
+ prefetchMax,
2147
+ });
2148
+ return true;
2149
+ }, [
2150
+ didRestoreRef,
2151
+ itemListRef,
2152
+ prefetchMax,
2153
+ prefetchMin,
2154
+ prefetchZone,
2155
+ scrollContainerRef,
2156
+ ]);
2157
+
2158
+ const requestEligiblePage = useCallback(() => {
2159
+ const current = inputsRef.current;
2160
+ if (
2161
+ !current.isReady ||
2162
+ !didRestoreRef.current ||
2163
+ autoPagingPausedRef.current
2164
+ ) {
2165
+ return;
2166
+ }
2167
+
2168
+ const isOlderPageEligible =
2169
+ current.hasMoreOlder && prefetchZone.isOlderWithinZone;
2170
+ const isNewerPageEligible =
2171
+ current.hasMoreNewer && prefetchZone.isNewerWithinZone;
2172
+ const element = scrollContainerRef.current;
2173
+ const preferredDirection =
2174
+ preferredDirectionRef.current ??
2175
+ (element
2176
+ ? getTimelineInitialPageLoadDirection({
2177
+ clientHeight: element.clientHeight,
2178
+ hasMoreNewer: current.hasMoreNewer,
2179
+ hasMoreOlder: current.hasMoreOlder,
2180
+ primeRestoredWindow: current.primeRestoredWindow,
2181
+ scrollHeight: element.scrollHeight,
2182
+ scrollTop: element.scrollTop,
2183
+ })
2184
+ : null);
2185
+ if (preferredDirectionRef.current === null && preferredDirection !== null) {
2186
+ preferredDirectionRef.current = preferredDirection;
2187
+ }
2188
+ if (preferredDirection === PAGE_LOAD_DIRECTION.OLDER) {
2189
+ if (!isOlderPageEligible || current.isLoadingOlder) return;
2190
+
2191
+ void current.requestLoadOlder();
2192
+ return;
2193
+ }
2194
+ if (preferredDirection === PAGE_LOAD_DIRECTION.NEWER) {
2195
+ if (!isNewerPageEligible) return;
2196
+
2197
+ void current.requestLoadNewer();
2198
+ }
2199
+ }, [
2200
+ autoPagingPausedRef,
2201
+ didRestoreRef,
2202
+ prefetchZone,
2203
+ preferredDirectionRef,
2204
+ scrollContainerRef,
2205
+ ]);
2206
+
2207
+ // The single entry point for "should another page load?". It measures the
2208
+ // list only when the zone is stale or the caller asks for it. Otherwise the
2209
+ // flags that the observer entries set are current. A programmatic write, a
2210
+ // rendered boundary change, a resize and a new observer make the zone stale.
2211
+ const decideAfterMeasure = useCallback(() => {
2212
+ if (!measureZone()) return;
2213
+ requestEligiblePage();
2214
+ }, [measureZone, requestEligiblePage]);
2215
+
2216
+ const checkPagePrefetch = useCallback(
2217
+ ({ measure = false } = {}) => {
2218
+ const shouldMeasure =
2219
+ measure ||
2220
+ prefetchZone.isStale ||
2221
+ typeof IntersectionObserver === VALUE_TYPE.UNDEFINED;
2222
+ if (!shouldMeasure) {
2223
+ requestEligiblePage();
2224
+ return;
2225
+ }
2226
+ // A correction that is written but not painted makes `scrollTop` return
2227
+ // the offset from before the correction. That offset looks like a
2228
+ // viewport that is still near the top. In that case, decide after the
2229
+ // correction lands. Every other trigger decides at once, so the
2230
+ // direction that it receives is the direction that it uses.
2231
+ const { scrollCorrection } = inputsRef.current;
2232
+ if (!scrollCorrection.hasPendingScrollCorrection()) {
2233
+ decideAfterMeasure();
2234
+ return;
2235
+ }
2236
+
2237
+ void scrollCorrection.waitForSettledScrollTop().then(decideAfterMeasure);
2238
+ },
2239
+ [decideAfterMeasure, prefetchZone, requestEligiblePage],
2240
+ );
2241
+
2242
+ useTimelinePageBoundaryObserver({
2243
+ attachVersion,
2244
+ checkPagePrefetch,
2245
+ didRestoreRef,
2246
+ itemListRef,
2247
+ prefetchZone,
2248
+ isReady,
2249
+ newerPageSentinelRef,
2250
+ observeResize,
2251
+ olderPageSentinelRef,
2252
+ prefetchMax,
2253
+ prefetchMin,
2254
+ requestEligiblePage,
2255
+ scrollContainerRef,
2256
+ });
2257
+ useTimelinePagePrefetchPump({
2258
+ isLoadingOlder,
2259
+ isReady,
2260
+ renderedFirstMessageId,
2261
+ renderedLastMessageId,
2262
+ requestPageIfEligible: checkPagePrefetch,
2263
+ });
2264
+
2265
+ return { checkPagePrefetch };
2266
+ }
2267
+
2268
+ function findTimelineScrollAnchor(container, messageElements, messages) {
2269
+ const containerTop = container.getBoundingClientRect().top;
2270
+ const renderedMessages = [];
2271
+ for (const message of messages) {
2272
+ const element = messageElements.get(message.id);
2273
+ if (element) renderedMessages.push({ element, messageId: message.id });
2274
+ }
2275
+ let start = 0;
2276
+ let end = renderedMessages.length;
2277
+
2278
+ while (start < end) {
2279
+ const middle = Math.floor((start + end) / 2);
2280
+ const candidate = renderedMessages[middle];
2281
+ if (candidate.element.getBoundingClientRect().bottom <= containerTop) {
2282
+ start = middle + 1;
2283
+ } else {
2284
+ end = middle;
2285
+ }
2286
+ }
2287
+
2288
+ const anchor = renderedMessages[start];
2289
+ if (!anchor) return undefined;
2290
+
2291
+ return {
2292
+ anchorItemId: anchor.messageId,
2293
+ anchorOffsetFromViewportTop:
2294
+ anchor.element.getBoundingClientRect().top - containerTop,
2295
+ };
2296
+ }
2297
+
2298
+ const NOT_WRITTEN = Object.freeze({
2299
+ written: false,
2300
+ clamped: false,
2301
+ lost: false,
2302
+ });
2303
+
2304
+ // The one owner of the reading position: the row that the user reads and
2305
+ // its offset from the container top. Scroll events move the offset. A layout
2306
+ // change moves the row. `planRestore` puts the row back to its offset.
2307
+ class ReadingPosition {
2308
+ #getElements;
2309
+ #getItems;
2310
+ #hasPendingCorrection;
2311
+ #isPinned;
2312
+ #anchorId;
2313
+ #isStale = true;
2314
+ #hasReaderMoved = false;
2315
+ #offset;
2316
+ #scrollHeight;
2317
+ #scrollTop;
2318
+
2319
+ constructor({ getElements, getItems, hasPendingCorrection, isPinned }) {
2320
+ this.#getElements = getElements;
2321
+ this.#getItems = getItems;
2322
+ this.#hasPendingCorrection = hasPendingCorrection;
2323
+ this.#isPinned = isPinned;
2324
+ }
2325
+
2326
+ get anchor() {
2327
+ if (this.#anchorId === undefined) return undefined;
2328
+
2329
+ return {
2330
+ anchorItemId: this.#anchorId,
2331
+ anchorOffsetFromViewportTop: this.#offset,
2332
+ };
2333
+ }
2334
+
2335
+ seed(memory) {
2336
+ if (!memory?.anchorItemId) return false;
2337
+ if (memory.anchorOffsetFromViewportTop === undefined) return false;
2338
+
2339
+ this.#anchorId = memory.anchorItemId;
2340
+ this.#offset = memory.anchorOffsetFromViewportTop;
2341
+ this.#scrollTop = undefined;
2342
+ this.#scrollHeight = undefined;
2343
+ this.#isStale = false;
2344
+ this.#hasReaderMoved = false;
2345
+ return true;
2346
+ }
2347
+
2348
+ anchorTo(id, offset, scrollTop, scrollHeight) {
2349
+ this.#anchorId = id;
2350
+ this.#offset = offset;
2351
+ this.#scrollTop = scrollTop;
2352
+ this.#scrollHeight = scrollHeight;
2353
+ this.#isStale = false;
2354
+ this.#hasReaderMoved = false;
2355
+ }
2356
+
2357
+ // Reads the first visible row from the DOM.
2358
+ measure(element, metrics = readTimelineScrollMetrics(element)) {
2359
+ const anchor = findTimelineScrollAnchor(
2360
+ element,
2361
+ this.#getElements(),
2362
+ this.#getItems(),
2363
+ );
2364
+ this.#anchorId = anchor?.anchorItemId;
2365
+ this.#offset = anchor?.anchorOffsetFromViewportTop;
2366
+ this.#scrollTop = metrics.scrollTop;
2367
+ this.#scrollHeight = metrics.scrollHeight;
2368
+ this.#isStale = false;
2369
+ this.#hasReaderMoved = false;
2370
+ }
2371
+
2372
+ // Read at rest only after movement since the last measurement. The rest
2373
+ // event of a restore can arrive after another resize moved the row.
2374
+ settle(element) {
2375
+ if (
2376
+ !this.#hasReaderMoved ||
2377
+ this.#isPinned() ||
2378
+ this.#hasPendingCorrection()
2379
+ ) {
2380
+ return;
2381
+ }
2382
+
2383
+ this.measure(element);
2384
+ }
2385
+
2386
+ // Runs for each scroll event. It does not read the DOM when the anchor
2387
+ // is current.
2388
+ track(element, metrics, { preserveOffset = false } = {}) {
2389
+ // A write echo or a layout clamp keeps the reading row offset. Only the
2390
+ // baseline that later scroll events move from is new.
2391
+ if (preserveOffset) {
2392
+ this.#scrollTop = metrics.scrollTop;
2393
+ this.#scrollHeight = metrics.scrollHeight;
2394
+ return;
2395
+ }
2396
+ // WebKit can report the offset from before a correction. This event
2397
+ // cannot be trusted, so the next restore reads the position again.
2398
+ if (this.#hasPendingCorrection()) {
2399
+ this.#isStale = true;
2400
+ return;
2401
+ }
2402
+
2403
+ // Keep the row after reader movement, even inside the follow threshold.
2404
+ // An older page can move the rendered window away from the tail.
2405
+ if (
2406
+ this.#isStale ||
2407
+ this.#anchorId === undefined ||
2408
+ this.#scrollTop === undefined
2409
+ ) {
2410
+ this.measure(element, metrics);
2411
+ return;
2412
+ }
2413
+
2414
+ if (
2415
+ Math.abs(metrics.scrollTop - this.#scrollTop) >
2416
+ SCROLL.OFFSET_ROUNDING_TOLERANCE_PX
2417
+ ) {
2418
+ this.#hasReaderMoved = true;
2419
+ }
2420
+ this.#offset -= metrics.scrollTop - this.#scrollTop;
2421
+ this.#scrollTop = metrics.scrollTop;
2422
+ this.#scrollHeight = metrics.scrollHeight;
2423
+ // The tracked row left the viewport by more than one viewport height. A
2424
+ // reveal can evict a row that far away, so read the reading row again.
2425
+ if (Math.abs(this.#offset) > metrics.clientHeight) {
2426
+ this.measure(element, metrics);
2427
+ }
2428
+ }
2429
+
2430
+ restore(element, viewport, options) {
2431
+ return this.planRestore(element, viewport, options)();
2432
+ }
2433
+
2434
+ // Reads the layout now. The returned function writes the viewport and
2435
+ // returns what happened. Callers can run all reads before any write.
2436
+ planRestore(element, viewport, { reason, persist = false } = {}) {
2437
+ const metrics = readTimelineScrollMetrics(element);
2438
+ if (this.#isPinned()) {
2439
+ return () => this.#pin(element, viewport, metrics, persist);
2440
+ }
2441
+
2442
+ if (this.#isStale) return () => this.#remeasure(element, metrics);
2443
+
2444
+ const row =
2445
+ this.#anchorId === undefined
2446
+ ? undefined
2447
+ : this.#getElements().get(this.#anchorId);
2448
+ if (!row) return () => this.#recover(element, viewport, metrics, reason);
2449
+
2450
+ const rowOffset = getItemOffsetFromContainerTop(element, row);
2451
+ const delta = rowOffset - this.#offset;
2452
+ if (Math.abs(delta) < SCROLL.OFFSET_ROUNDING_TOLERANCE_PX) {
2453
+ return () => {
2454
+ this.#scrollTop = metrics.scrollTop;
2455
+ this.#scrollHeight = metrics.scrollHeight;
2456
+ return NOT_WRITTEN;
2457
+ };
2458
+ }
2459
+
2460
+ const target = metrics.scrollTop + delta;
2461
+ const bounded = getBoundedScrollTop(metrics, target);
2462
+ return () => {
2463
+ viewport.write(element, bounded, { settle: true });
2464
+ // After a clamp, the row sits closer to its old place than planned.
2465
+ this.#offset -= bounded - target;
2466
+ this.#scrollTop = bounded;
2467
+ this.#scrollHeight = metrics.scrollHeight;
2468
+ return { written: true, clamped: bounded !== target, lost: false };
2469
+ };
2470
+ }
2471
+
2472
+ #pin(element, viewport, metrics, persist) {
2473
+ const bottom = getMaximumScrollTop(metrics);
2474
+ this.#isStale = true;
2475
+ this.#scrollTop = bottom;
2476
+ this.#scrollHeight = metrics.scrollHeight;
2477
+ // A pending correction can hide the real offset, so write then.
2478
+ if (
2479
+ metrics.scrollTop === bottom &&
2480
+ !persist &&
2481
+ !this.#hasPendingCorrection()
2482
+ ) {
2483
+ return NOT_WRITTEN;
2484
+ }
2485
+
2486
+ viewport.write(element, metrics.scrollHeight, { metrics, persist });
2487
+ return { written: true, clamped: false, lost: false };
2488
+ }
2489
+
2490
+ #remeasure(element, metrics) {
2491
+ this.measure(element, metrics);
2492
+ return NOT_WRITTEN;
2493
+ }
2494
+
2495
+ // The anchor row is not rendered. An older page keeps its distance from
2496
+ // the end of the content. Then the position is read again from the DOM.
2497
+ #recover(element, viewport, metrics, reason) {
2498
+ const lost = this.#anchorId !== undefined;
2499
+ const growth =
2500
+ reason === RESTORE_REASON.OLDER_PAGE && this.#scrollHeight !== undefined
2501
+ ? metrics.scrollHeight - this.#scrollHeight
2502
+ : 0;
2503
+ if (growth <= 0) {
2504
+ this.measure(element, metrics);
2505
+ return { written: false, clamped: false, lost };
2506
+ }
2507
+
2508
+ const bounded = getBoundedScrollTop(metrics, metrics.scrollTop + growth);
2509
+ viewport.write(element, bounded, { settle: true });
2510
+ this.measure(element, { ...metrics, scrollTop: bounded });
2511
+ return { written: true, clamped: false, lost };
2512
+ }
2513
+ }
2514
+
2515
+ // Creates the one reading position owner. It reads the rendered rows and the
2516
+ // pinned flag through refs, so its identity never changes.
2517
+ function useReadingPosition({
2518
+ messageElementsRef,
2519
+ messages,
2520
+ scrollCorrection,
2521
+ wasAtBottomRef,
2522
+ }) {
2523
+ const messagesRef = useRef(messages);
2524
+ messagesRef.current = messages;
2525
+ const positionRef = useRef(null);
2526
+ positionRef.current ??= new ReadingPosition({
2527
+ getElements: () => messageElementsRef.current,
2528
+ getItems: () => messagesRef.current,
2529
+ hasPendingCorrection: scrollCorrection.hasPendingScrollCorrection,
2530
+ isPinned: () => wasAtBottomRef.current,
2531
+ });
2532
+ return positionRef.current;
2533
+ }
2534
+
2535
+ function useTimelineScrollHandler({
2536
+ autoPagingPausedRef,
2537
+ preferredPageLoadDirectionRef,
2538
+ previousScrollTopRef,
2539
+ hasWriteEchoRef,
2540
+ readingPosition,
2541
+ scrollContainerRef,
2542
+ scrollCorrection,
2543
+ updateScrollState,
2544
+ }) {
2545
+ return useCallback(() => {
2546
+ const element = scrollContainerRef.current;
2547
+ if (!element) return;
2548
+
2549
+ const metrics = readTimelineScrollMetrics(element);
2550
+ const previousScrollTop = previousScrollTopRef.current;
2551
+ const currentScrollTop = metrics.scrollTop;
2552
+ const tolerance = SCROLL.OFFSET_ROUNDING_TOLERANCE_PX;
2553
+ const isWriteEcho =
2554
+ hasWriteEchoRef.current &&
2555
+ Math.abs(currentScrollTop - previousScrollTop) <= tolerance;
2556
+ hasWriteEchoRef.current = false;
2557
+ const maxScrollTop = getMaximumScrollTop(metrics);
2558
+ const isLayoutClamp =
2559
+ previousScrollTop > maxScrollTop + tolerance &&
2560
+ Math.abs(currentScrollTop - maxScrollTop) <= tolerance;
2561
+ // A write echo or a layout clamp keeps the reader's direction and
2562
+ // follow intent. The browser can round an offset in the scroll event.
2563
+ const isUserMovement =
2564
+ currentScrollTop !== previousScrollTop && !isLayoutClamp && !isWriteEcho;
2565
+ if (isUserMovement) {
2566
+ preferredPageLoadDirectionRef.current =
2567
+ currentScrollTop < previousScrollTop
2568
+ ? PAGE_LOAD_DIRECTION.OLDER
2569
+ : PAGE_LOAD_DIRECTION.NEWER;
2570
+ autoPagingPausedRef.current = false;
2571
+ }
2572
+ previousScrollTopRef.current = currentScrollTop;
2573
+ const { memory, atBottomToggled } = updateScrollState(element, metrics, {
2574
+ measure: isUserMovement,
2575
+ });
2576
+ scrollCorrection.confirmOnScroll(metrics.scrollTop);
2577
+ readingPosition.track(element, metrics, {
2578
+ preserveOffset: isWriteEcho || isLayoutClamp,
2579
+ });
2580
+ return { memory, atBottomToggled };
2581
+ }, [
2582
+ autoPagingPausedRef,
2583
+ preferredPageLoadDirectionRef,
2584
+ previousScrollTopRef,
2585
+ readingPosition,
2586
+ scrollContainerRef,
2587
+ scrollCorrection,
2588
+ updateScrollState,
2589
+ hasWriteEchoRef,
2590
+ ]);
2591
+ }
2592
+
2593
+ // Runs the two layout effects that follow the other scroll hooks. A jump to
2594
+ // the latest items waits here until the newer items are rendered. A new
2595
+ // navigation version resets the preferred page load direction. These effects
2596
+ // must stay after the layout and prefetch hooks, so their order is the same
2597
+ // as in the engine.
2598
+ function useScrollIntents({
2599
+ hasMoreNewer,
2600
+ messages,
2601
+ navigationVersion,
2602
+ pendingJumpToLatestRef,
2603
+ preferredPageLoadDirectionRef,
2604
+ scrollRenderedToBottom,
2605
+ }) {
2606
+ // biome-ignore lint/correctness/useExhaustiveDependencies: `messages` is a trigger. A pending jump completes after the latest items render.
2607
+ useLayoutEffect(() => {
2608
+ const pendingJump = pendingJumpToLatestRef.current;
2609
+ if (!pendingJump || hasMoreNewer) return;
2610
+
2611
+ pendingJumpToLatestRef.current = null;
2612
+ // A newer command (a navigation) ended this jump.
2613
+ if (pendingJump.isCurrent()) scrollRenderedToBottom(pendingJump.options);
2614
+ }, [hasMoreNewer, messages, pendingJumpToLatestRef, scrollRenderedToBottom]);
2615
+ // biome-ignore lint/correctness/useExhaustiveDependencies: `navigationVersion` is a trigger. A new navigation clears the preferred page direction.
2616
+ useLayoutEffect(() => {
2617
+ preferredPageLoadDirectionRef.current = null;
2618
+ }, [navigationVersion, preferredPageLoadDirectionRef]);
2619
+ }
2620
+
2621
+ function useTimelineScrollMemory({
2622
+ attachVersion = 0,
2623
+ initialMemory,
2624
+ atBottomThreshold = DEFAULT_THRESHOLDS.atBottom,
2625
+ hasMoreNewer,
2626
+ readingPosition,
2627
+ scrollContainerRef,
2628
+ onScrollMemoryChange,
2629
+ pauseFollowingLatest,
2630
+ resumeFollowingLatest,
2631
+ wasAtBottomRef,
2632
+ }) {
2633
+ const hasMoreNewerRef = useRef(hasMoreNewer);
2634
+ hasMoreNewerRef.current = hasMoreNewer;
2635
+ const atBottomThresholdRef = useRef(atBottomThreshold);
2636
+ atBottomThresholdRef.current = atBottomThreshold;
2637
+ const supportsScrollEnd =
2638
+ typeof window !== VALUE_TYPE.UNDEFINED && 'onscrollend' in window;
2639
+ const initialAtBottom = wasAtBottomRef.current;
2640
+ const latestMemoryRef = useRef(initialMemory);
2641
+ const lastPersistedMemoryRef = useRef(initialMemory);
2642
+ const onScrollMemoryChangeRef = useRef(onScrollMemoryChange);
2643
+ const flushTimerRef = useRef(undefined);
2644
+ const [isAtBottom, setIsAtBottom] = useState(initialAtBottom);
2645
+
2646
+ useEffect(() => {
2647
+ onScrollMemoryChangeRef.current = onScrollMemoryChange;
2648
+ }, [onScrollMemoryChange]);
2649
+
2650
+ // `atBottom` is the follow intent: true while the reader follows the end.
2651
+ // Only reader movement and scroll commands measure it (`measure`). A layout
2652
+ // change keeps it, also when the browser clamps the offset to the end. It
2653
+ // ends when the window does not render the latest items (a navigation).
2654
+ // The window renders the latest items while the reader follows them.
2655
+ const updateScrollMemoryState = useCallback(
2656
+ (element, knownMetrics, { measure = false } = {}) => {
2657
+ const previousAtBottom = wasAtBottomRef.current;
2658
+ const metrics = knownMetrics ?? readTimelineScrollMetrics(element);
2659
+ const isFollowing = measure
2660
+ ? isTimelineAtRenderedBottom(metrics, atBottomThresholdRef.current)
2661
+ : previousAtBottom;
2662
+ const memory = {
2663
+ scrollTop: metrics.scrollTop,
2664
+ atBottom: isFollowing && !hasMoreNewerRef.current,
2665
+ };
2666
+
2667
+ latestMemoryRef.current = memory;
2668
+ wasAtBottomRef.current = memory.atBottom;
2669
+ setIsAtBottom((current) =>
2670
+ current === memory.atBottom ? current : memory.atBottom,
2671
+ );
2672
+ if (memory.atBottom) {
2673
+ resumeFollowingLatest();
2674
+ } else {
2675
+ pauseFollowingLatest();
2676
+ }
2677
+
2678
+ return { memory, atBottomToggled: previousAtBottom !== memory.atBottom };
2679
+ },
2680
+ [pauseFollowingLatest, resumeFollowingLatest, wasAtBottomRef],
2681
+ );
2682
+
2683
+ // End following before a layout restore when the window leaves the tail.
2684
+ useLayoutEffect(() => {
2685
+ const element = scrollContainerRef.current;
2686
+ if (hasMoreNewer && wasAtBottomRef.current && element) {
2687
+ updateScrollMemoryState(element);
2688
+ }
2689
+ }, [
2690
+ hasMoreNewer,
2691
+ scrollContainerRef,
2692
+ updateScrollMemoryState,
2693
+ wasAtBottomRef,
2694
+ ]);
2695
+
2696
+ const persistScrollMemory = useCallback(
2697
+ (memory = latestMemoryRef.current) => {
2698
+ if (!memory) return;
2699
+ const anchor = memory.atBottom ? undefined : readingPosition.anchor;
2700
+ const previousMemory = lastPersistedMemoryRef.current;
2701
+ const previousAnchor =
2702
+ !memory.atBottom && previousMemory?.anchorItemId
2703
+ ? {
2704
+ anchorItemId: previousMemory.anchorItemId,
2705
+ anchorOffsetFromViewportTop:
2706
+ previousMemory.anchorOffsetFromViewportTop,
2707
+ }
2708
+ : undefined;
2709
+ const persistedMemory = { ...memory, ...(anchor ?? previousAnchor) };
2710
+ if (!onScrollMemoryChangeRef.current) return;
2711
+ if (
2712
+ areTimelineScrollMemoriesEqual(
2713
+ lastPersistedMemoryRef.current,
2714
+ persistedMemory,
2715
+ )
2716
+ ) {
2717
+ return;
2718
+ }
2719
+
2720
+ lastPersistedMemoryRef.current = persistedMemory;
2721
+ onScrollMemoryChangeRef.current(persistedMemory);
2722
+ },
2723
+ [readingPosition],
2724
+ );
2725
+
2726
+ // The reading position is read from the DOM when the scroll comes to rest.
2727
+ const settleScrollMemory = useCallback(() => {
2728
+ const element = scrollContainerRef.current;
2729
+ if (element) readingPosition.settle(element);
2730
+ persistScrollMemory();
2731
+ }, [persistScrollMemory, readingPosition, scrollContainerRef]);
2732
+
2733
+ const scheduleScrollMemoryFlush = useCallback(() => {
2734
+ if (supportsScrollEnd) return;
2735
+ if (flushTimerRef.current !== undefined) {
2736
+ window.clearTimeout(flushTimerRef.current);
2737
+ }
2738
+
2739
+ flushTimerRef.current = window.setTimeout(() => {
2740
+ flushTimerRef.current = undefined;
2741
+ settleScrollMemory();
2742
+ }, SCROLL.MEMORY_FLUSH_DELAY_MS);
2743
+ }, [settleScrollMemory, supportsScrollEnd]);
2744
+
2745
+ useEffect(
2746
+ () => () => {
2747
+ if (flushTimerRef.current !== undefined) {
2748
+ window.clearTimeout(flushTimerRef.current);
2749
+ flushTimerRef.current = undefined;
2750
+ }
2751
+ persistScrollMemory();
2752
+ },
2753
+ [persistScrollMemory],
2754
+ );
2755
+ // biome-ignore lint/correctness/useExhaustiveDependencies: attachVersion is a trigger: the effect runs again when a DOM ref attaches after mount
2756
+ useEffect(() => {
2757
+ const element = scrollContainerRef.current;
2758
+ if (!element || !supportsScrollEnd) return;
2759
+
2760
+ element.addEventListener(SCROLL_EVENT.END, settleScrollMemory);
2761
+ return () =>
2762
+ element.removeEventListener(SCROLL_EVENT.END, settleScrollMemory);
2763
+ }, [
2764
+ attachVersion,
2765
+ scrollContainerRef,
2766
+ settleScrollMemory,
2767
+ supportsScrollEnd,
2768
+ ]);
2769
+
2770
+ return {
2771
+ isAtBottom,
2772
+ persistScrollMemory,
2773
+ scheduleScrollMemoryFlush,
2774
+ updateScrollMemoryState,
2775
+ };
2776
+ }
2777
+
2778
+ // Owns the boundary flags and the rule that makes observer entries current.
2779
+ class PrefetchZone {
2780
+ #isStale = true;
2781
+ #freshSince = Number.NEGATIVE_INFINITY;
2782
+ #isOlderWithinZone = false;
2783
+ #isNewerWithinZone = false;
2784
+
2785
+ get isStale() {
2786
+ return this.#isStale;
2787
+ }
2788
+
2789
+ get isOlderWithinZone() {
2790
+ return this.#isOlderWithinZone;
2791
+ }
2792
+
2793
+ get isNewerWithinZone() {
2794
+ return this.#isNewerWithinZone;
2795
+ }
2796
+
2797
+ invalidate() {
2798
+ this.#isStale = true;
2799
+ }
2800
+
2801
+ clearBoundaries() {
2802
+ this.#isOlderWithinZone = false;
2803
+ this.#isNewerWithinZone = false;
2804
+ }
2805
+
2806
+ measure(container, list, thresholds) {
2807
+ const distance = getTimelinePagePrefetchDistance(
2808
+ container.clientHeight,
2809
+ thresholds,
2810
+ );
2811
+ // Use the row list edges. Container clearance must not change the zone.
2812
+ // An unmeasured list uses the scroll extent, so its ends stay separate.
2813
+ const { older, newer } = getListBoundaryDistances(container, list);
2814
+ this.#isOlderWithinZone = older <= distance;
2815
+ this.#isNewerWithinZone = newer <= distance;
2816
+ this.#isStale = false;
2817
+ this.#freshSince = performance.now();
2818
+ }
2819
+
2820
+ acceptEntries(entries, olderSentinel, newerSentinel) {
2821
+ // A write, boundary change or resize can make entries old. Only entries
2822
+ // from after the last measurement can change a current zone.
2823
+ const isTrusted = (entry) =>
2824
+ !this.#isStale &&
2825
+ typeof entry.time === VALUE_TYPE.NUMBER &&
2826
+ entry.time >= this.#freshSince;
2827
+ if (!entries.every(isTrusted)) return false;
2828
+
2829
+ for (const entry of entries) {
2830
+ if (entry.target === olderSentinel) {
2831
+ this.#isOlderWithinZone = entry.isIntersecting;
2832
+ } else if (entry.target === newerSentinel) {
2833
+ this.#isNewerWithinZone = entry.isIntersecting;
2834
+ }
2835
+ }
2836
+ return true;
2837
+ }
2838
+ }
2839
+
2840
+ // An internal correction must not animate. `scrollTop = value` follows the CSS
2841
+ // `scroll-behavior` of the consumer, so use `scrollTo` with an explicit instant
2842
+ // behavior when it exists.
2843
+ function scrollInstantly(element, top) {
2844
+ if (typeof element.scrollTo === VALUE_TYPE.FUNCTION) {
2845
+ element.scrollTo({ top, behavior: SCROLL_BEHAVIOR.INSTANT });
2846
+ return;
2847
+ }
2848
+
2849
+ element.scrollTop = top;
2850
+ }
2851
+
2852
+ function usePostPaintScrollTopReapply() {
2853
+ const animationFrameRef = useRef(undefined);
2854
+ const settleRef = useRef(undefined);
2855
+ const targetRef = useRef(undefined);
2856
+ const settle = useCallback(() => {
2857
+ const pending = settleRef.current;
2858
+ settleRef.current = undefined;
2859
+ targetRef.current = undefined;
2860
+ pending?.resolve();
2861
+ }, []);
2862
+
2863
+ const cancelScheduledFrames = useCallback(() => {
2864
+ if (animationFrameRef.current === undefined) return;
2865
+
2866
+ window.cancelAnimationFrame(animationFrameRef.current);
2867
+ animationFrameRef.current = undefined;
2868
+ }, []);
2869
+
2870
+ const scheduleScrollTopReapply = useCallback(
2871
+ (element, { fromScrollTop, expectedScrollTop }) => {
2872
+ cancelScheduledFrames();
2873
+ targetRef.current = { fromScrollTop, expectedScrollTop };
2874
+ if (typeof window.requestAnimationFrame !== VALUE_TYPE.FUNCTION) {
2875
+ // No frame will run to settle the correction. Release all waiters now.
2876
+ settle();
2877
+ return;
2878
+ }
2879
+
2880
+ // One barrier covers a replaced correction. If the replaced correction
2881
+ // released its waiters here, they would read the unpainted offset of the
2882
+ // replacement. That is the same stale read, one commit later. Only a
2883
+ // correction that paints breaks the chain.
2884
+ if (settleRef.current === undefined) {
2885
+ let resolve = () => {};
2886
+ const promise = new Promise((resolvePromise) => {
2887
+ resolve = resolvePromise;
2888
+ });
2889
+ settleRef.current = { promise, resolve };
2890
+ }
2891
+ // Two frames, not one. A rAF callback runs before the repaint that it
2892
+ // belongs to. WebKit can report the `scrollTop` from before the
2893
+ // correction until it paints. So the first frame cannot show if a write
2894
+ // is applied. The second frame runs after a paint.
2895
+ animationFrameRef.current = window.requestAnimationFrame(() => {
2896
+ animationFrameRef.current = window.requestAnimationFrame(() => {
2897
+ animationFrameRef.current = undefined;
2898
+ // Only an offset that can still be in the old coordinate needs a
2899
+ // repair. A settled value, or a value that moved closer to the
2900
+ // expected target, is in the corrected coordinate. A rewrite would
2901
+ // cancel momentum that is in progress. Limit the old-coordinate
2902
+ // movement to one viewport. Then a hard fling cannot pass the
2903
+ // midpoint and look like a stale `scrollTop`.
2904
+ const observedScrollTop = element.scrollTop;
2905
+ const movementFromUncorrectedScrollTop = Math.abs(
2906
+ observedScrollTop - fromScrollTop,
2907
+ );
2908
+ const isSettled =
2909
+ Math.abs(observedScrollTop - expectedScrollTop) <=
2910
+ SCROLL.TOP_REAPPLY_TOLERANCE_PX;
2911
+ const isStillInUncorrectedCoordinate =
2912
+ !isSettled &&
2913
+ movementFromUncorrectedScrollTop <= element.clientHeight &&
2914
+ movementFromUncorrectedScrollTop <
2915
+ Math.abs(observedScrollTop - expectedScrollTop);
2916
+ if (isStillInUncorrectedCoordinate) {
2917
+ scrollInstantly(
2918
+ element,
2919
+ expectedScrollTop + observedScrollTop - fromScrollTop,
2920
+ );
2921
+ // This repair has not painted yet. Keep the shared barrier for the
2922
+ // next frame. Then queued prefetch checks cannot read the old
2923
+ // coordinate again.
2924
+ animationFrameRef.current = window.requestAnimationFrame(() => {
2925
+ animationFrameRef.current = undefined;
2926
+ settle();
2927
+ });
2928
+ return;
2929
+ }
2930
+ settle();
2931
+ });
2932
+ });
2933
+ },
2934
+ [cancelScheduledFrames, settle],
2935
+ );
2936
+
2937
+ const hasPendingScrollCorrection = useCallback(
2938
+ () => settleRef.current !== undefined,
2939
+ [],
2940
+ );
2941
+
2942
+ // Resolves when a correction in progress has painted. Resolves at once when
2943
+ // there is none. Any decision from `scrollTop` after a page commit must wait
2944
+ // for this. Before it resolves, WebKit can return the offset from before the
2945
+ // correction, and that offset looks like a viewport near the top.
2946
+ const waitForSettledScrollTop = useCallback(
2947
+ () => settleRef.current?.promise ?? Promise.resolve(),
2948
+ [],
2949
+ );
2950
+
2951
+ // A newer programmatic write owns the offset. The pending repair of an older
2952
+ // write must not move it again.
2953
+ const cancelScrollTopReapply = useCallback(() => {
2954
+ cancelScheduledFrames();
2955
+ settle();
2956
+ }, [cancelScheduledFrames, settle]);
2957
+
2958
+ // A scroll event at the corrected offset shows that the browser applied the
2959
+ // write. The repair is not needed then, and a later movement of the user
2960
+ // must not look like the old offset that the repair exists for.
2961
+ const confirmOnScroll = useCallback(
2962
+ (scrollTop) => {
2963
+ const target = targetRef.current;
2964
+ if (!target) return;
2965
+
2966
+ const distance = Math.abs(scrollTop - target.expectedScrollTop);
2967
+ if (distance <= SCROLL.TOP_REAPPLY_TOLERANCE_PX) cancelScrollTopReapply();
2968
+ },
2969
+ [cancelScrollTopReapply],
2970
+ );
2971
+
2972
+ useEffect(() => cancelScrollTopReapply, [cancelScrollTopReapply]);
2973
+
2974
+ return useMemo(
2975
+ () => ({
2976
+ cancelScrollTopReapply,
2977
+ hasPendingScrollCorrection,
2978
+ confirmOnScroll,
2979
+ scheduleScrollTopReapply,
2980
+ waitForSettledScrollTop,
2981
+ }),
2982
+ [
2983
+ cancelScrollTopReapply,
2984
+ hasPendingScrollCorrection,
2985
+ confirmOnScroll,
2986
+ scheduleScrollTopReapply,
2987
+ waitForSettledScrollTop,
2988
+ ],
2989
+ );
2990
+ }
2991
+
2992
+ const SCROLL_STYLE = Object.freeze({
2993
+ OVERFLOW_ANCHOR: 'none',
2994
+ });
2995
+
2996
+ // A stable ref object. React assigns `.current` when the element attaches. The
2997
+ // setter only stores the value and asks for a check. A composed inline ref
2998
+ // detaches and attaches the same node on every render, so the setter must not
2999
+ // change state.
3000
+ function useAttachableRef(scheduleCheck) {
3001
+ const valueRef = useRef(null);
3002
+ return useMemo(
3003
+ () => ({
3004
+ get current() {
3005
+ return valueRef.current;
3006
+ },
3007
+
3008
+ set current(value) {
3009
+ if (valueRef.current === value) return;
3010
+
3011
+ valueRef.current = value;
3012
+ scheduleCheck();
3013
+ },
3014
+ }),
3015
+ [scheduleCheck],
3016
+ );
3017
+ }
3018
+
3019
+ // Owns the refs that all scroll hooks share, the scroll correction, and the
3020
+ // baseline of the scroll direction.
3021
+ function useScrollRuntime() {
3022
+ const mountedRef = useRef(false);
3023
+ // `attachVersion` counts late attaches of any shared element (observers use
3024
+ // it). `containerAttachVersion` counts only the scroll container (the
3025
+ // position effects use it, so a late list does not run them again).
3026
+ const [attachVersion, setAttachVersion] = useState(0);
3027
+ const [containerAttachVersion, setContainerAttachVersion] = useState(0);
3028
+ // The last element of each ref that the engine acted on.
3029
+ const acknowledgedRef = useRef({
3030
+ container: null,
3031
+ list: null,
3032
+ older: null,
3033
+ newer: null,
3034
+ });
3035
+ const isCheckQueuedRef = useRef(false);
3036
+ const refsRef = useRef(null);
3037
+ const checkAttachments = useCallback(() => {
3038
+ isCheckQueuedRef.current = false;
3039
+ if (!mountedRef.current) return;
3040
+
3041
+ const refs = refsRef.current;
3042
+ const acknowledged = acknowledgedRef.current;
3043
+ const current = {
3044
+ container: refs.container.current,
3045
+ list: refs.list.current,
3046
+ older: refs.older.current,
3047
+ newer: refs.newer.current,
3048
+ };
3049
+ const didContainerChange = current.container !== acknowledged.container;
3050
+ const didOtherChange =
3051
+ current.list !== acknowledged.list ||
3052
+ current.older !== acknowledged.older ||
3053
+ current.newer !== acknowledged.newer;
3054
+ acknowledgedRef.current = current;
3055
+ if (didContainerChange) {
3056
+ setAttachVersion((version) => version + 1);
3057
+ setContainerAttachVersion((version) => version + 1);
3058
+ } else if (didOtherChange) {
3059
+ setAttachVersion((version) => version + 1);
3060
+ }
3061
+ }, []);
3062
+
3063
+ // One microtask checks after React assigned the final value of every ref.
3064
+ const scheduleCheck = useCallback(() => {
3065
+ if (isCheckQueuedRef.current) return;
3066
+
3067
+ isCheckQueuedRef.current = true;
3068
+ queueMicrotask(checkAttachments);
3069
+ }, [checkAttachments]);
3070
+ const scrollContainerRef = useAttachableRef(scheduleCheck);
3071
+ const itemListRef = useAttachableRef(scheduleCheck);
3072
+ const olderPageSentinelRef = useAttachableRef(scheduleCheck);
3073
+ const newerPageSentinelRef = useAttachableRef(scheduleCheck);
3074
+ refsRef.current = {
3075
+ container: scrollContainerRef,
3076
+ list: itemListRef,
3077
+ older: olderPageSentinelRef,
3078
+ newer: newerPageSentinelRef,
3079
+ };
3080
+ // Refs attach before the first layout effects run, so the first commit
3081
+ // acknowledges them and does not bump the versions.
3082
+ useLayoutEffect(() => {
3083
+ mountedRef.current = true;
3084
+ acknowledgedRef.current = {
3085
+ container: scrollContainerRef.current,
3086
+ list: itemListRef.current,
3087
+ older: olderPageSentinelRef.current,
3088
+ newer: newerPageSentinelRef.current,
3089
+ };
3090
+ return () => {
3091
+ mountedRef.current = false;
3092
+ };
3093
+ }, [
3094
+ itemListRef,
3095
+ newerPageSentinelRef,
3096
+ olderPageSentinelRef,
3097
+ scrollContainerRef,
3098
+ ]);
3099
+ // After a ref assignment, a commit of this component checks the final refs
3100
+ // before paint, so a late container gets its position in the same frame. The
3101
+ // microtask covers a ref that attaches in the commit of another component.
3102
+ useLayoutEffect(() => {
3103
+ if (isCheckQueuedRef.current) checkAttachments();
3104
+ });
3105
+ // True after a page commit lost the reading anchor. Automatic paging waits
3106
+ // for the next user scroll.
3107
+ const autoPagingPausedRef = useRef(false);
3108
+ const pauseAutoPaging = useCallback(() => {
3109
+ autoPagingPausedRef.current = true;
3110
+ }, []);
3111
+ const messageElementsRef = useRef(new Map());
3112
+ const preferredPageLoadDirectionRef = useRef(null);
3113
+ const previousScrollTopRef = useRef(0);
3114
+ // A moving programmatic write leaves an echo at the direction baseline.
3115
+ // Its scroll event is not a reader action.
3116
+ const hasWriteEchoRef = useRef(false);
3117
+ const pendingJumpToLatestRef = useRef(null);
3118
+ // One scroll command owns the view at a time: a navigation or a jump to the
3119
+ // latest items. A newer command ends the older one.
3120
+ const scrollCommandRef = useRef(undefined);
3121
+ const startScrollCommand = useCallback(() => {
3122
+ const command = {};
3123
+ scrollCommandRef.current = command;
3124
+ return () => scrollCommandRef.current === command;
3125
+ }, []);
3126
+ const prefetchZoneRef = useRef(null);
3127
+ prefetchZoneRef.current ??= new PrefetchZone();
3128
+ const prefetchZone = prefetchZoneRef.current;
3129
+ const markPrefetchZoneStale = useCallback(() => {
3130
+ prefetchZone.invalidate();
3131
+ }, [prefetchZone]);
3132
+ // The engine owns scroll anchoring. Native anchoring would move the view a
3133
+ // second time when older rows are added.
3134
+ useLayoutEffect(() => {
3135
+ const element = scrollContainerRef.current;
3136
+ if (
3137
+ element &&
3138
+ element.style.overflowAnchor !== SCROLL_STYLE.OVERFLOW_ANCHOR
3139
+ ) {
3140
+ element.style.overflowAnchor = SCROLL_STYLE.OVERFLOW_ANCHOR;
3141
+ }
3142
+ });
3143
+ const scrollCorrection = usePostPaintScrollTopReapply();
3144
+ return {
3145
+ attachVersion,
3146
+ autoPagingPausedRef,
3147
+ containerAttachVersion,
3148
+ itemListRef,
3149
+ markPrefetchZoneStale,
3150
+ messageElementsRef,
3151
+ newerPageSentinelRef,
3152
+ olderPageSentinelRef,
3153
+ pauseAutoPaging,
3154
+ pendingJumpToLatestRef,
3155
+ prefetchZone,
3156
+ preferredPageLoadDirectionRef,
3157
+ previousScrollTopRef,
3158
+ hasWriteEchoRef,
3159
+ scrollCommandRef,
3160
+ scrollContainerRef,
3161
+ scrollCorrection,
3162
+ startScrollCommand,
3163
+ };
3164
+ }
3165
+
3166
+ const ALWAYS_CURRENT = () => true;
3167
+
3168
+ // Scrolls the rendered items to the bottom. When newer items are not
3169
+ // rendered, the window jumps to the latest items first. The jump ends in
3170
+ // `useScrollIntents`, only while its command still owns the view.
3171
+ function useScrollToBottom({
3172
+ hasMoreNewer,
3173
+ jumpToLatest,
3174
+ pendingJumpToLatestRef,
3175
+ scrollRenderedToBottom,
3176
+ }) {
3177
+ return useCallback(
3178
+ (options = {}, isCurrent = ALWAYS_CURRENT) => {
3179
+ if (hasMoreNewer) {
3180
+ pendingJumpToLatestRef.current = {
3181
+ options: { ...options, behavior: SCROLL_BEHAVIOR.AUTO },
3182
+ isCurrent,
3183
+ };
3184
+ jumpToLatest();
3185
+ return;
3186
+ }
3187
+
3188
+ scrollRenderedToBottom(options);
3189
+ },
3190
+ [
3191
+ hasMoreNewer,
3192
+ jumpToLatest,
3193
+ pendingJumpToLatestRef,
3194
+ scrollRenderedToBottom,
3195
+ ],
3196
+ );
3197
+ }
3198
+
3199
+ const NO_OPTIONS$1 = Object.freeze({});
3200
+
3201
+ // The one owner of programmatic scroll writes. Each write sets the direction
3202
+ // baseline and the scroll state in a fixed order, so no caller can forget one.
3203
+ // A restore write (`metrics` or `settle`) keeps the follow intent. A plain
3204
+ // write is a command and measures it.
3205
+ function useViewportWriter({
3206
+ previousScrollTopRef,
3207
+ hasWriteEchoRef,
3208
+ scrollCorrection,
3209
+ updateScrollState,
3210
+ persistScrollMemory,
3211
+ onViewportChange,
3212
+ }) {
3213
+ const { cancelScrollTopReapply, scheduleScrollTopReapply } = scrollCorrection;
3214
+
3215
+ return useMemo(() => {
3216
+ // A write that does not move the offset fires no scroll event, so only a
3217
+ // moving write leaves an echo for the scroll handler.
3218
+ const markEcho = (fromScrollTop, toScrollTop) => {
3219
+ hasWriteEchoRef.current =
3220
+ Math.abs(fromScrollTop - toScrollTop) >=
3221
+ SCROLL.OFFSET_ROUNDING_TOLERANCE_PX;
3222
+ };
3223
+
3224
+ const write = (element, top, options = NO_OPTIONS$1) => {
3225
+ const { metrics, settle } = options;
3226
+ // A newer write owns the offset, so a pending repair must not undo it.
3227
+ if (settle !== true) cancelScrollTopReapply();
3228
+ let update;
3229
+ if (metrics) {
3230
+ const fromScrollTop = metrics.scrollTop;
3231
+ scrollInstantly(element, top);
3232
+ const bounded = getBoundedScrollTop(metrics, top);
3233
+ previousScrollTopRef.current = bounded;
3234
+ markEcho(fromScrollTop, bounded);
3235
+ update = updateScrollState(element, { ...metrics, scrollTop: bounded });
3236
+ } else if (settle === true) {
3237
+ const fromScrollTop = element.scrollTop;
3238
+ // The browser clamps the offset. The baseline and the repair use the
3239
+ // clamped value, so its scroll event does not look like user movement.
3240
+ const known = {
3241
+ scrollHeight: element.scrollHeight,
3242
+ clientHeight: element.clientHeight,
3243
+ };
3244
+ const bounded = getBoundedScrollTop(known, top);
3245
+ previousScrollTopRef.current = bounded;
3246
+ markEcho(fromScrollTop, bounded);
3247
+ if (fromScrollTop !== bounded) {
3248
+ scrollInstantly(element, bounded);
3249
+ scheduleScrollTopReapply(element, {
3250
+ fromScrollTop,
3251
+ expectedScrollTop: bounded,
3252
+ });
3253
+ }
3254
+ // An unpainted offset can read as the old one. Use the known value.
3255
+ update = updateScrollState(element, { ...known, scrollTop: bounded });
3256
+ } else {
3257
+ const fromScrollTop = element.scrollTop;
3258
+ scrollInstantly(element, top);
3259
+ previousScrollTopRef.current = element.scrollTop;
3260
+ markEcho(fromScrollTop, element.scrollTop);
3261
+ // A command write (jump, navigation, opening position) sets the
3262
+ // follow intent from where it landed.
3263
+ update = updateScrollState(element, undefined, { measure: true });
3264
+ }
3265
+ const { memory } = update;
3266
+ if (options.persist === true) persistScrollMemory(memory);
3267
+ onViewportChange();
3268
+ };
3269
+
3270
+ const scrollSmoothly = (element, top) => {
3271
+ cancelScrollTopReapply();
3272
+ element.scrollTo({ top, behavior: SCROLL_BEHAVIOR.SMOOTH });
3273
+ onViewportChange();
3274
+ };
3275
+ return { write, scrollSmoothly };
3276
+ }, [
3277
+ cancelScrollTopReapply,
3278
+ onViewportChange,
3279
+ persistScrollMemory,
3280
+ previousScrollTopRef,
3281
+ scheduleScrollTopReapply,
3282
+ hasWriteEchoRef,
3283
+ updateScrollState,
3284
+ ]);
3285
+ }
3286
+
3287
+ const REVEAL_NO_CACHED_ITEM = () => false;
3288
+
3289
+ const LOAD_THROUGH_NO_ITEM = () => Promise.resolve(false);
3290
+
3291
+ const NO_WINDOW_ACTION = () => {};
3292
+
3293
+ const NEVER_FOLLOWS_APPEND = () => false;
3294
+
3295
+ function useTimelineScroll({
3296
+ messages,
3297
+ sourceMessages = messages,
3298
+ bottomInset,
3299
+ isLoading,
3300
+ isLoadingOlder,
3301
+ hasMoreOlder,
3302
+ hasMoreNewer,
3303
+ olderPageVersion,
3304
+ navigationVersion = 0,
3305
+ loadOlder,
3306
+ loadNewer,
3307
+ jumpToLatest,
3308
+ pauseFollowingLatest = NO_WINDOW_ACTION,
3309
+ resumeFollowingLatest = NO_WINDOW_ACTION,
3310
+ revealCachedItem = REVEAL_NO_CACHED_ITEM,
3311
+ loadThroughMessage = LOAD_THROUGH_NO_ITEM,
3312
+ initialMessageId,
3313
+ initialMessageTime,
3314
+ readTargetMessageId,
3315
+ readTargetBeforeWindow = false,
3316
+ scrollMemory,
3317
+ onScrollMemoryChange,
3318
+ followsAppend = NEVER_FOLLOWS_APPEND,
3319
+ onNavigation,
3320
+ thresholds = DEFAULT_THRESHOLDS,
3321
+ navigationSettings = DEFAULT_NAVIGATION,
3322
+ platform = DEFAULT_PLATFORM,
3323
+ }) {
3324
+ const {
3325
+ attachVersion,
3326
+ autoPagingPausedRef,
3327
+ containerAttachVersion,
3328
+ itemListRef,
3329
+ markPrefetchZoneStale,
3330
+ messageElementsRef,
3331
+ newerPageSentinelRef,
3332
+ olderPageSentinelRef,
3333
+ pauseAutoPaging,
3334
+ pendingJumpToLatestRef,
3335
+ prefetchZone,
3336
+ preferredPageLoadDirectionRef,
3337
+ previousScrollTopRef,
3338
+ hasWriteEchoRef,
3339
+ scrollCommandRef,
3340
+ scrollContainerRef,
3341
+ scrollCorrection,
3342
+ startScrollCommand,
3343
+ } = useScrollRuntime();
3344
+ const wasAtBottomRef = useRef(
3345
+ (scrollMemory?.atBottom ?? true) && !hasMoreNewer,
3346
+ );
3347
+ const readingPosition = useReadingPosition({
3348
+ messageElementsRef,
3349
+ messages,
3350
+ scrollCorrection,
3351
+ wasAtBottomRef,
3352
+ });
3353
+ const {
3354
+ isAtBottom,
3355
+ persistScrollMemory,
3356
+ scheduleScrollMemoryFlush,
3357
+ updateScrollMemoryState: updateScrollState,
3358
+ } = useTimelineScrollMemory({
3359
+ attachVersion: containerAttachVersion,
3360
+ initialMemory: scrollMemory,
3361
+ atBottomThreshold: thresholds.atBottom,
3362
+ hasMoreNewer,
3363
+ readingPosition,
3364
+ scrollContainerRef,
3365
+ onScrollMemoryChange,
3366
+ pauseFollowingLatest,
3367
+ resumeFollowingLatest,
3368
+ wasAtBottomRef,
3369
+ });
3370
+ const updateScrollPosition = useTimelineScrollHandler({
3371
+ autoPagingPausedRef,
3372
+ preferredPageLoadDirectionRef,
3373
+ previousScrollTopRef,
3374
+ hasWriteEchoRef,
3375
+ readingPosition,
3376
+ scrollContainerRef,
3377
+ scrollCorrection,
3378
+ updateScrollState,
3379
+ });
3380
+ const viewport = useViewportWriter({
3381
+ previousScrollTopRef,
3382
+ hasWriteEchoRef,
3383
+ scrollCorrection,
3384
+ updateScrollState,
3385
+ persistScrollMemory,
3386
+ onViewportChange: markPrefetchZoneStale,
3387
+ });
3388
+ const { commitRender, loadOlderPage, requestLoadNewer, requestLoadOlder } =
3389
+ useTimelinePageLoading({
3390
+ messages,
3391
+ sourceMessages,
3392
+ hasMoreOlder,
3393
+ hasMoreNewer,
3394
+ olderPageVersion,
3395
+ navigationVersion,
3396
+ isLoadingOlder,
3397
+ loadOlder,
3398
+ loadNewer,
3399
+ scrollContainerRef,
3400
+ updateScrollState,
3401
+ });
3402
+ const {
3403
+ didRestoreRef,
3404
+ rowDetach,
3405
+ scrollToBottom: scrollRenderedToBottom,
3406
+ } = useTimelineMessageLayout({
3407
+ attachVersion,
3408
+ containerAttachVersion,
3409
+ bottomInset,
3410
+ commitRender,
3411
+ followsAppend,
3412
+ initialMessageId,
3413
+ isLoading,
3414
+ messages,
3415
+ sourceMessages,
3416
+ itemListRef,
3417
+ olderPageVersion,
3418
+ navigationVersion,
3419
+ onAnchorLost: pauseAutoPaging,
3420
+ platform,
3421
+ previousScrollTopRef,
3422
+ readingPosition,
3423
+ scrollContainerRef,
3424
+ scrollCorrection,
3425
+ scrollMemory,
3426
+ updateScrollState,
3427
+ updateScrollPosition,
3428
+ viewport,
3429
+ wasAtBottomRef,
3430
+ });
3431
+ const { isMessageReached: isReadTargetReached, updateMessageReach } =
3432
+ useTimelineMessageReach({
3433
+ isMessageBeforeWindow: readTargetBeforeWindow,
3434
+ messageId: readTargetMessageId,
3435
+ messages,
3436
+ messageElementsRef,
3437
+ scrollContainerRef,
3438
+ });
3439
+ const scrollToBottom = useScrollToBottom({
3440
+ hasMoreNewer,
3441
+ jumpToLatest,
3442
+ pendingJumpToLatestRef,
3443
+ scrollRenderedToBottom,
3444
+ });
3445
+ const {
3446
+ highlightedMessageId,
3447
+ initialTargetPending,
3448
+ navigateTo,
3449
+ registerItemElement,
3450
+ scrollToLatest,
3451
+ } = useTimelineMessageNavigation({
3452
+ attachVersion: containerAttachVersion,
3453
+ didRestoreRef,
3454
+ hasMoreOlder,
3455
+ loadOlderPage,
3456
+ messageElementsRef,
3457
+ initialMessageId,
3458
+ initialMessageTime,
3459
+ isLoading,
3460
+ messages,
3461
+ navigationVersion,
3462
+ loadThroughMessage,
3463
+ maxOlderPages: navigationSettings.maxOlderPages,
3464
+ highlightDuration: navigationSettings.highlightDuration,
3465
+ revealCachedItem,
3466
+ scrollCommandRef,
3467
+ scrollContainerRef,
3468
+ scrollToBottom,
3469
+ startScrollCommand,
3470
+ onNavigation,
3471
+ readingPosition,
3472
+ rowDetach,
3473
+ viewport,
3474
+ });
3475
+ const { checkPagePrefetch } = useTimelinePagePrefetch({
3476
+ attachVersion,
3477
+ autoPagingPausedRef,
3478
+ didRestoreRef,
3479
+ hasMoreNewer,
3480
+ hasMoreOlder,
3481
+ isLoadingOlder,
3482
+ isReady: !isLoading && messages.length > 0 && !initialTargetPending,
3483
+ itemListRef,
3484
+ newerPageSentinelRef,
3485
+ observeResize: platform.observeResize,
3486
+ olderPageSentinelRef,
3487
+ primeRestoredWindow: scrollMemory?.atBottom === false,
3488
+ preferredDirectionRef: preferredPageLoadDirectionRef,
3489
+ prefetchMin: thresholds.prefetchMin,
3490
+ prefetchMax: thresholds.prefetchMax,
3491
+ renderedFirstMessageId: messages[0]?.id,
3492
+ renderedLastMessageId: messages.at(-1)?.id,
3493
+ requestLoadNewer,
3494
+ requestLoadOlder,
3495
+ scrollContainerRef,
3496
+ scrollCorrection,
3497
+ prefetchZone,
3498
+ });
3499
+ useScrollIntents({
3500
+ hasMoreNewer,
3501
+ messages,
3502
+ navigationVersion,
3503
+ pendingJumpToLatestRef,
3504
+ preferredPageLoadDirectionRef,
3505
+ scrollRenderedToBottom,
3506
+ });
3507
+ const handleScroll = useCallback(() => {
3508
+ const update = updateScrollPosition();
3509
+ if (!update) return;
3510
+
3511
+ updateMessageReach();
3512
+ if (update.atBottomToggled) {
3513
+ persistScrollMemory(update.memory);
3514
+ } else {
3515
+ scheduleScrollMemoryFlush();
3516
+ }
3517
+ checkPagePrefetch();
3518
+ }, [
3519
+ checkPagePrefetch,
3520
+ persistScrollMemory,
3521
+ scheduleScrollMemoryFlush,
3522
+ updateMessageReach,
3523
+ updateScrollPosition,
3524
+ ]);
3525
+
3526
+ return {
3527
+ scrollContainerRef,
3528
+ itemListRef,
3529
+ highlightedMessageId,
3530
+ isAtBottom,
3531
+ isReadTargetReached,
3532
+ initialTargetPending,
3533
+ newerPageSentinelRef,
3534
+ olderPageSentinelRef,
3535
+ registerItemElement,
3536
+ handleScroll,
3537
+ requestLoadOlder,
3538
+ navigateTo,
3539
+ scrollToBottom: scrollToLatest,
3540
+ };
3541
+ }
3542
+
3543
+ function useTimelineMessageWindowLifecycle({
3544
+ sourceMessages,
3545
+ position,
3546
+ windowState,
3547
+ windowView,
3548
+ setWindowState,
3549
+ followsAppend,
3550
+ limits,
3551
+ }) {
3552
+ const positionKey = getTimelineInitialPositionKey(position);
3553
+ const positionKeyRef = useRef(positionKey);
3554
+ const previousSourceLastIdRef = useRef(sourceMessages.at(-1)?.id);
3555
+ const previousWindowMessageIdsRef = useRef(
3556
+ new Set(windowView.messages.map((message) => message.id)),
3557
+ );
3558
+
3559
+ useLayoutEffect(() => {
3560
+ const previousWindowMessageIds = previousWindowMessageIdsRef.current;
3561
+ const hasPreviousWindowOverlap = sourceMessages.some((message) =>
3562
+ previousWindowMessageIds.has(message.id),
3563
+ );
3564
+ if (
3565
+ windowState &&
3566
+ (sourceMessages.length === 0 ||
3567
+ (previousWindowMessageIds.size > 0 && !hasPreviousWindowOverlap))
3568
+ ) {
3569
+ setWindowState(
3570
+ supersedeTimelineWindow(
3571
+ createInitialTimelineWindow(sourceMessages, position, limits),
3572
+ windowState,
3573
+ ),
3574
+ );
3575
+ return;
3576
+ }
3577
+
3578
+ const lastMessage = sourceMessages.at(-1);
3579
+ const previousLastId = previousSourceLastIdRef.current;
3580
+ previousSourceLastIdRef.current = lastMessage?.id;
3581
+ const shouldFollowOptimisticSend =
3582
+ Boolean(previousLastId) &&
3583
+ lastMessage?.id !== previousLastId &&
3584
+ Boolean(lastMessage) &&
3585
+ followsAppend(lastMessage) &&
3586
+ windowView.hasCachedNewer;
3587
+ if (shouldFollowOptimisticSend) {
3588
+ setWindowState(
3589
+ supersedeTimelineWindow(
3590
+ createLatestTimelineWindow(sourceMessages, limits),
3591
+ windowState,
3592
+ ),
3593
+ );
3594
+ return;
3595
+ }
3596
+
3597
+ const positionChanged = positionKeyRef.current !== positionKey;
3598
+ if (!positionChanged && windowState) return;
3599
+
3600
+ // A focus item that is not cached does not replace the window.
3601
+ if (
3602
+ windowState &&
3603
+ position.focusId &&
3604
+ !position.initialId &&
3605
+ !sourceMessages.some((message) => message.id === position.focusId)
3606
+ ) {
3607
+ positionKeyRef.current = positionKey;
3608
+ return;
3609
+ }
3610
+
3611
+ const nextWindow = supersedeTimelineWindow(
3612
+ createInitialTimelineWindow(sourceMessages, position, limits),
3613
+ windowState,
3614
+ );
3615
+ if (!positionChanged && !nextWindow) return;
3616
+
3617
+ positionKeyRef.current = positionKey;
3618
+ setWindowState(nextWindow);
3619
+ }, [
3620
+ followsAppend,
3621
+ limits,
3622
+ position,
3623
+ positionKey,
3624
+ setWindowState,
3625
+ sourceMessages,
3626
+ windowState,
3627
+ windowView.hasCachedNewer,
3628
+ ]);
3629
+
3630
+ useLayoutEffect(() => {
3631
+ previousWindowMessageIdsRef.current = new Set(
3632
+ windowView.messages.map((message) => message.id),
3633
+ );
3634
+ }, [windowView.messages]);
3635
+ }
3636
+
3637
+ function useTimelineMessageWindow({
3638
+ sourceMessages,
3639
+ initialMessageId,
3640
+ focusMessageId,
3641
+ initialScrollAnchorId,
3642
+ hasMoreOlderFromServer,
3643
+ isLoadingOlderFromServer,
3644
+ loadOlderFromServer,
3645
+ followsAppend,
3646
+ limits,
3647
+ }) {
3648
+ const position = useMemo(
3649
+ () => ({
3650
+ initialId: initialMessageId,
3651
+ focusId: focusMessageId,
3652
+ scrollAnchorId: initialScrollAnchorId,
3653
+ }),
3654
+ [initialMessageId, focusMessageId, initialScrollAnchorId],
3655
+ );
3656
+ const [windowState, setWindowState] = useState(() =>
3657
+ createInitialTimelineWindow(sourceMessages, position, limits),
3658
+ );
3659
+ const windowView = useMemo(
3660
+ () => selectTimelineWindow(sourceMessages, windowState, limits),
3661
+ [limits, sourceMessages, windowState],
3662
+ );
3663
+ const sourceMessagesRef = useRef(sourceMessages);
3664
+ const followLatestRef = useRef(windowState?.followLatest ?? false);
3665
+ // Sync command inputs before the lifecycle effect on each commit.
3666
+ useLayoutEffect(() => {
3667
+ followLatestRef.current = windowState?.followLatest ?? false;
3668
+ sourceMessagesRef.current = sourceMessages;
3669
+ });
3670
+ useTimelineMessageWindowLifecycle({
3671
+ sourceMessages,
3672
+ position,
3673
+ windowState,
3674
+ windowView,
3675
+ setWindowState,
3676
+ followsAppend,
3677
+ limits,
3678
+ });
3679
+
3680
+ const loadOlder = useCallback(async () => {
3681
+ const hasCachedOlder = windowView.hasCachedOlder;
3682
+ if (
3683
+ !hasCachedOlder &&
3684
+ (!hasMoreOlderFromServer || isLoadingOlderFromServer)
3685
+ ) {
3686
+ return false;
3687
+ }
3688
+
3689
+ setWindowState((current) =>
3690
+ current
3691
+ ? revealOlderTimelineWindowPage(
3692
+ sourceMessagesRef.current,
3693
+ current,
3694
+ limits,
3695
+ )
3696
+ : current,
3697
+ );
3698
+ if (hasCachedOlder) return true;
3699
+
3700
+ return loadOlderFromServer();
3701
+ }, [
3702
+ hasMoreOlderFromServer,
3703
+ isLoadingOlderFromServer,
3704
+ limits,
3705
+ loadOlderFromServer,
3706
+ windowView.hasCachedOlder,
3707
+ ]);
3708
+
3709
+ const loadNewer = useCallback(() => {
3710
+ if (!windowState || !windowView.hasCachedNewer) {
3711
+ return Promise.resolve(false);
3712
+ }
3713
+
3714
+ setWindowState((current) =>
3715
+ current
3716
+ ? revealNewerTimelineWindowPage(
3717
+ sourceMessagesRef.current,
3718
+ current,
3719
+ false,
3720
+ limits,
3721
+ )
3722
+ : current,
3723
+ );
3724
+ return Promise.resolve(true);
3725
+ }, [limits, windowState, windowView.hasCachedNewer]);
3726
+
3727
+ const pauseFollowingLatest = useCallback(() => {
3728
+ if (!followLatestRef.current) return;
3729
+ followLatestRef.current = false;
3730
+ setWindowState((current) =>
3731
+ current
3732
+ ? pauseTimelineWindowFollowingLatest(
3733
+ sourceMessagesRef.current,
3734
+ current,
3735
+ limits,
3736
+ )
3737
+ : current,
3738
+ );
3739
+ }, [limits]);
3740
+
3741
+ const resumeFollowingLatest = useCallback(() => {
3742
+ if (followLatestRef.current) return;
3743
+ followLatestRef.current = true;
3744
+ setWindowState((current) =>
3745
+ current
3746
+ ? resumeTimelineWindowFollowingLatest(
3747
+ sourceMessagesRef.current,
3748
+ current,
3749
+ limits,
3750
+ )
3751
+ : current,
3752
+ );
3753
+ }, [limits]);
3754
+
3755
+ const jumpToLatest = useCallback(() => {
3756
+ setWindowState((current) =>
3757
+ supersedeTimelineWindow(
3758
+ createLatestTimelineWindow(sourceMessagesRef.current, limits),
3759
+ current,
3760
+ ),
3761
+ );
3762
+ }, [limits]);
3763
+
3764
+ const revealCachedItem = useCallback(
3765
+ (messageId) => {
3766
+ const nextWindow = createAnchoredTimelineWindow(
3767
+ sourceMessagesRef.current,
3768
+ messageId,
3769
+ limits,
3770
+ );
3771
+ if (!nextWindow) return false;
3772
+
3773
+ setWindowState((current) => supersedeTimelineWindow(nextWindow, current));
3774
+ return true;
3775
+ },
3776
+ [limits],
3777
+ );
3778
+
3779
+ return {
3780
+ messages: windowView.messages,
3781
+ isLoadingOlder: isLoadingOlderFromServer,
3782
+ isWaitingForInitialMessage: Boolean(
3783
+ initialMessageId &&
3784
+ !windowState &&
3785
+ (hasMoreOlderFromServer || sourceMessages.length > 0),
3786
+ ),
3787
+ hasMoreOlder: windowView.hasCachedOlder || hasMoreOlderFromServer,
3788
+ hasMoreNewer: windowView.hasCachedNewer,
3789
+ navigationVersion: windowState?.navigationVersion ?? 0,
3790
+ loadOlder,
3791
+ loadNewer,
3792
+ jumpToLatest,
3793
+ pauseFollowingLatest,
3794
+ resumeFollowingLatest,
3795
+ revealCachedItem,
3796
+ };
3797
+ }
3798
+
3799
+ const NO_OPTIONS = Object.freeze({});
3800
+
3801
+ function useScrollback({
3802
+ source,
3803
+ targets = NO_OPTIONS,
3804
+ memory = NO_OPTIONS,
3805
+ layout = NO_OPTIONS,
3806
+ followsAppend,
3807
+ limits,
3808
+ thresholds,
3809
+ navigation,
3810
+ platform,
3811
+ onNavigation,
3812
+ }) {
3813
+ const { older } = source;
3814
+ const { pageSize, initialPageSize, maxRenderedItems } = limits ?? NO_OPTIONS;
3815
+ const { atBottom, prefetchMin, prefetchMax } = thresholds ?? NO_OPTIONS;
3816
+ const { maxOlderPages, highlightDuration } = navigation ?? NO_OPTIONS;
3817
+ const observeResize =
3818
+ platform?.observeResize ?? DEFAULT_PLATFORM.observeResize;
3819
+ const scheduleMeasurement =
3820
+ platform?.scheduleMeasurement ?? DEFAULT_PLATFORM.scheduleMeasurement;
3821
+ // Resolve the options once. Effects depend on these identities.
3822
+ const resolvedLimits = useMemo(
3823
+ () => resolveLimits({ pageSize, initialPageSize, maxRenderedItems }),
3824
+ [pageSize, initialPageSize, maxRenderedItems],
3825
+ );
3826
+ const resolvedThresholds = useMemo(
3827
+ () => resolveThresholds({ atBottom, prefetchMin, prefetchMax }),
3828
+ [atBottom, prefetchMin, prefetchMax],
3829
+ );
3830
+ const resolvedNavigation = useMemo(
3831
+ () => resolveNavigationSettings({ maxOlderPages, highlightDuration }),
3832
+ [maxOlderPages, highlightDuration],
3833
+ );
3834
+ const resolvedPlatform = useMemo(
3835
+ () => ({ observeResize, scheduleMeasurement }),
3836
+ [observeResize, scheduleMeasurement],
3837
+ );
3838
+ // The callbacks keep one identity. A caller can pass a new function on
3839
+ // every render, and that must not run the effects again.
3840
+ const followsAppendRef = useRef(followsAppend);
3841
+ followsAppendRef.current = followsAppend;
3842
+ const onNavigationRef = useRef(onNavigation);
3843
+ onNavigationRef.current = onNavigation;
3844
+ const stableFollowsAppend = useCallback((item) => {
3845
+ const followsAppend = followsAppendRef.current;
3846
+ return followsAppend?.(item) ?? false;
3847
+ }, []);
3848
+
3849
+ const stableOnNavigation = useCallback(
3850
+ (navigation) => onNavigationRef.current?.(navigation),
3851
+ [],
3852
+ );
3853
+
3854
+ const view = useTimelineMessageWindow({
3855
+ sourceMessages: source.items,
3856
+ initialMessageId: targets.initialId,
3857
+ focusMessageId: targets.focusId,
3858
+ initialScrollAnchorId:
3859
+ memory.initial?.atBottom === false
3860
+ ? memory.initial.anchorItemId
3861
+ : undefined,
3862
+ hasMoreOlderFromServer: older.hasMore,
3863
+ isLoadingOlderFromServer: older.isLoading,
3864
+ loadOlderFromServer: older.load,
3865
+ followsAppend: stableFollowsAppend,
3866
+ limits: resolvedLimits,
3867
+ });
3868
+ const readTargetBeforeWindow = useMemo(
3869
+ () =>
3870
+ isTimelineMessageBeforeWindow(
3871
+ source.items,
3872
+ view.messages,
3873
+ targets.readId,
3874
+ ),
3875
+ [source.items, view.messages, targets.readId],
3876
+ );
3877
+ const scroll = useTimelineScroll({
3878
+ messages: view.messages,
3879
+ sourceMessages: source.items,
3880
+ bottomInset: layout.bottomInset,
3881
+ isLoading: source.isLoading ?? false,
3882
+ isLoadingOlder: view.isLoadingOlder,
3883
+ hasMoreOlder: view.hasMoreOlder,
3884
+ hasMoreNewer: view.hasMoreNewer,
3885
+ olderPageVersion: older.version,
3886
+ navigationVersion: view.navigationVersion,
3887
+ loadOlder: view.loadOlder,
3888
+ loadNewer: view.loadNewer,
3889
+ jumpToLatest: view.jumpToLatest,
3890
+ pauseFollowingLatest: view.pauseFollowingLatest,
3891
+ resumeFollowingLatest: view.resumeFollowingLatest,
3892
+ revealCachedItem: view.revealCachedItem,
3893
+ loadThroughMessage: source.loadThrough,
3894
+ initialMessageId: targets.initialId,
3895
+ initialMessageTime: targets.initialTime,
3896
+ readTargetMessageId: targets.readId,
3897
+ readTargetBeforeWindow,
3898
+ scrollMemory: memory.initial,
3899
+ onScrollMemoryChange: memory.onChange,
3900
+ followsAppend: stableFollowsAppend,
3901
+ onNavigation: stableOnNavigation,
3902
+ thresholds: resolvedThresholds,
3903
+ navigationSettings: resolvedNavigation,
3904
+ platform: resolvedPlatform,
3905
+ });
3906
+
3907
+ return {
3908
+ items: view.messages,
3909
+ isWaitingForInitialItem: view.isWaitingForInitialMessage,
3910
+ isLoadingOlder: view.isLoadingOlder,
3911
+ hasMoreOlder: view.hasMoreOlder,
3912
+ hasMoreNewer: view.hasMoreNewer,
3913
+ isAtBottom: scroll.isAtBottom,
3914
+ isReadTargetReached: scroll.isReadTargetReached,
3915
+ isInitialTargetPending: scroll.initialTargetPending,
3916
+ highlightedId: scroll.highlightedMessageId,
3917
+ scrollContainerRef: scroll.scrollContainerRef,
3918
+ itemListRef: scroll.itemListRef,
3919
+ olderSentinelRef: scroll.olderPageSentinelRef,
3920
+ newerSentinelRef: scroll.newerPageSentinelRef,
3921
+ onScroll: scroll.handleScroll,
3922
+ registerItemElement: scroll.registerItemElement,
3923
+ navigateTo: scroll.navigateTo,
3924
+ scrollToBottom: scroll.scrollToBottom,
3925
+ };
3926
+ }
3927
+
3928
+ export { useScrollback };
3929
+ //# sourceMappingURL=index.js.map