@majapisoftwares/ui 6.8.0 → 6.8.2

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.
@@ -0,0 +1,874 @@
1
+ import * as React from "react"
2
+
3
+ import {
4
+ getContentBottom,
5
+ getElementTop,
6
+ getElementViewportTop,
7
+ getFirstVisibleMessageItem,
8
+ getFlexGap,
9
+ getLastScrollAnchor,
10
+ getMessageScrollerItems,
11
+ getMessageScrollerScrollable,
12
+ getMessageScrollerVisibilityState,
13
+ } from "./geometry"
14
+ import {
15
+ DEFAULT_SCROLL_EDGE_THRESHOLD,
16
+ DEFAULT_SCROLL_MARGIN,
17
+ DEFAULT_SCROLL_PREVIOUS_ITEM_PEEK,
18
+ EMPTY_MESSAGE_SCROLLER_VISIBILITY_STATE,
19
+ SCROLL_POSITION_EPSILON,
20
+ } from "./types"
21
+ import type {
22
+ MessageScrollerContextValue,
23
+ MessageScrollerProviderProps,
24
+ MessageScrollerRegisterMessage,
25
+ MessageScrollerScrollable,
26
+ } from "./types"
27
+ import { useMessageScrollerCommands } from "./use-message-scroller-commands"
28
+ import {
29
+ clearPendingDefaultScroll,
30
+ markDefaultScrollPositionApplied,
31
+ useMessageScrollerRefs,
32
+ } from "./use-message-scroller-refs"
33
+
34
+ // Builds a ref callback that stores the node and runs onMount once it attaches.
35
+ function useElementRef(
36
+ elementRef: React.RefObject<HTMLDivElement | null>,
37
+ onMount: () => void
38
+ ) {
39
+ return React.useCallback(
40
+ (element: HTMLDivElement | null) => {
41
+ elementRef.current = element
42
+
43
+ if (element) {
44
+ onMount()
45
+ }
46
+ },
47
+ [elementRef, onMount]
48
+ )
49
+ }
50
+
51
+ // Orchestrator hook. Decides when to scroll and delegates the moves to
52
+ // useMessageScrollerCommands; state and visibility commits are coalesced on a
53
+ // requestAnimationFrame and torn down on cleanup for StrictMode safety.
54
+ function useMessageScrollerController({
55
+ autoScroll = false,
56
+ defaultScrollPosition = "end",
57
+ scrollEdgeThreshold = DEFAULT_SCROLL_EDGE_THRESHOLD,
58
+ scrollPreviousItemPeek = DEFAULT_SCROLL_PREVIOUS_ITEM_PEEK,
59
+ scrollMargin = DEFAULT_SCROLL_MARGIN,
60
+ }: MessageScrollerProviderProps) {
61
+ const refs = useMessageScrollerRefs({
62
+ autoScroll,
63
+ defaultScrollPosition,
64
+ scrollEdgeThreshold,
65
+ scrollMargin,
66
+ scrollPreviousItemPeek,
67
+ })
68
+
69
+ const {
70
+ streamingTurnRef,
71
+ autoScrollRef,
72
+ autoscrollingRef,
73
+ autoscrollingTimeoutRef,
74
+ contentRef,
75
+ defaultScrollPositionAppliedRef,
76
+ firstItemRef,
77
+ itemCountRef,
78
+ lastScrollTopRef,
79
+ messageElementsRef,
80
+ modeRef,
81
+ pendingScrollFrameRef,
82
+ pendingScrollToMessageRef,
83
+ prependRestoreRef,
84
+ preserveScrollOnPrependRef,
85
+ pendingDefaultScrollStore,
86
+ rootRef,
87
+ scrollEdgeThresholdRef,
88
+ scrollMarginRef,
89
+ scrollPreviousItemPeekRef,
90
+ spacerGapRef,
91
+ spacerHeightRef,
92
+ spacerRef,
93
+ stateFrameRef,
94
+ stateStore,
95
+ viewportRef,
96
+ visibilityFrameRef,
97
+ visibilityObserverRef,
98
+ visibilityStore,
99
+ visibleMessageIdsRef,
100
+ handledScrollAnchorsRef,
101
+ } = refs
102
+
103
+ const previousDefaultScrollPositionRef = React.useRef(defaultScrollPosition)
104
+
105
+ if (previousDefaultScrollPositionRef.current !== defaultScrollPosition) {
106
+ previousDefaultScrollPositionRef.current = defaultScrollPosition
107
+ defaultScrollPositionAppliedRef.current = false
108
+ // The pending-scroll hold is mount-only. A live prop change re-applies the
109
+ // opening position in layout; it does not hide the viewport again.
110
+ }
111
+
112
+ const writeStateAttributes = React.useCallback(
113
+ (state: MessageScrollerScrollable) => {
114
+ const root = rootRef.current
115
+ const viewport = viewportRef.current
116
+ const scrollable = [state.start && "start", state.end && "end"]
117
+ .filter(Boolean)
118
+ .join(" ")
119
+ const autoScrolling = autoscrollingRef.current
120
+
121
+ for (const element of [root, viewport]) {
122
+ if (!element) {
123
+ continue
124
+ }
125
+
126
+ if (scrollable) {
127
+ element.setAttribute("data-scrollable", scrollable)
128
+ } else {
129
+ element.removeAttribute("data-scrollable")
130
+ }
131
+
132
+ element.toggleAttribute("data-autoscrolling", autoScrolling)
133
+ }
134
+ },
135
+ []
136
+ )
137
+
138
+ // Owns the one follow-bottom transition: arm at the bottom, release on any
139
+ // scroll away (including a scrollbar drag), suppressed during a programmatic
140
+ // scroll so the auto-scroll animation cannot release itself. Arming also
141
+ // skips the anchored-to-message hold: the tail spacer makes a freshly
142
+ // anchored turn read as "at the end", and re-arming there would let the
143
+ // first streamed chunk yank the reader off the anchor. The hold hands back
144
+ // to following in handleResize, once the reply consumes the tail spacer.
145
+ const reconcileFollowMode = React.useCallback(
146
+ (scrollable: MessageScrollerScrollable) => {
147
+ const scrollTop = viewportRef.current?.scrollTop ?? 0
148
+ // Content growing past the live edge also reads as "not at the end", but
149
+ // only a scrollbar drag moves scrollTop up. Growth must not release
150
+ // follow-output: the resize handler is coalesced onto a frame, so a state
151
+ // commit can observe the grown content before follow catches up.
152
+ const scrolledUp =
153
+ scrollTop < lastScrollTopRef.current - SCROLL_POSITION_EPSILON
154
+
155
+ lastScrollTopRef.current = scrollTop
156
+
157
+ if (
158
+ autoScrollRef.current &&
159
+ !scrollable.end &&
160
+ spacerHeightRef.current === 0 &&
161
+ modeRef.current !== "settling-jump" &&
162
+ modeRef.current !== "anchored-to-message"
163
+ ) {
164
+ modeRef.current = "following-bottom"
165
+ } else if (
166
+ modeRef.current === "following-bottom" &&
167
+ scrollable.end &&
168
+ scrolledUp &&
169
+ !autoscrollingRef.current
170
+ ) {
171
+ modeRef.current = "free-scrolling"
172
+ }
173
+ },
174
+ []
175
+ )
176
+
177
+ const commitScrollState = React.useCallback(() => {
178
+ const nextState = getMessageScrollerScrollable({
179
+ content: contentRef.current,
180
+ scrollEdgeThreshold: scrollEdgeThresholdRef.current,
181
+ spacer: spacerRef.current,
182
+ viewport: viewportRef.current,
183
+ })
184
+
185
+ reconcileFollowMode(nextState)
186
+
187
+ // While follow-output is engaged the scroller is already closing any gap a
188
+ // streamed chunk just opened, so publishing it as scrollable toward the
189
+ // end would strobe the scroll button once per chunk. Reconcile runs on the
190
+ // raw geometry first, so a commit that releases follow still publishes the
191
+ // gap it released over.
192
+ const publishedState =
193
+ modeRef.current === "following-bottom"
194
+ ? { ...nextState, end: false }
195
+ : nextState
196
+
197
+ writeStateAttributes(publishedState)
198
+ stateStore.setSnapshot(publishedState)
199
+ }, [reconcileFollowMode, stateStore, writeStateAttributes])
200
+
201
+ const scheduleStateCommit = React.useCallback(() => {
202
+ if (stateFrameRef.current !== null) {
203
+ return
204
+ }
205
+
206
+ stateFrameRef.current = window.requestAnimationFrame(() => {
207
+ stateFrameRef.current = null
208
+ commitScrollState()
209
+ })
210
+ }, [commitScrollState])
211
+
212
+ const scheduleVisibilitySync = React.useCallback(() => {
213
+ if (!visibilityStore.hasListeners()) {
214
+ return
215
+ }
216
+
217
+ if (visibilityFrameRef.current !== null) {
218
+ return
219
+ }
220
+
221
+ visibilityFrameRef.current = window.requestAnimationFrame(() => {
222
+ visibilityFrameRef.current = null
223
+
224
+ // A frame can outlive the last unsubscribe. Recomputing here would
225
+ // overwrite the EMPTY snapshot that teardown just wrote, leaving a stale
226
+ // value for the next subscriber to read.
227
+ if (!visibilityStore.hasListeners()) {
228
+ return
229
+ }
230
+
231
+ visibilityStore.setSnapshot(
232
+ getMessageScrollerVisibilityState({
233
+ content: contentRef.current,
234
+ scrollMargin: scrollMarginRef.current,
235
+ scrollPreviousItemPeek: scrollPreviousItemPeekRef.current,
236
+ spacer: spacerRef.current,
237
+ viewport: viewportRef.current,
238
+ visibleMessageIds: visibleMessageIdsRef.current,
239
+ })
240
+ )
241
+ })
242
+ }, [visibilityStore])
243
+
244
+ const {
245
+ flushPendingScrollToMessage,
246
+ reanchorToAnchoredMessage,
247
+ scrollToElement,
248
+ scrollToEnd,
249
+ scrollToMessage,
250
+ scrollToStart,
251
+ setTailSpacerHeight,
252
+ } = useMessageScrollerCommands({
253
+ refs,
254
+ commitScrollState,
255
+ scheduleStateCommit,
256
+ scheduleVisibilitySync,
257
+ })
258
+
259
+ const restorePrependedAnchor = React.useCallback(() => {
260
+ const anchor = prependRestoreRef.current
261
+ const viewport = viewportRef.current
262
+
263
+ if (!anchor || !viewport || !anchor.element.isConnected) {
264
+ return false
265
+ }
266
+
267
+ // Compare the anchor relative to the viewport, not to the content. Native
268
+ // scroll anchoring leaves the viewport-relative position unchanged, so this
269
+ // is a no-op where the browser already handled the prepend and only corrects
270
+ // the scroll where it did not (e.g. Safari) — without trusting a capability
271
+ // flag, which some engines report incorrectly.
272
+ const nextViewportTop = getElementViewportTop(anchor.element, viewport)
273
+ const delta = nextViewportTop - anchor.viewportTop
274
+
275
+ if (Math.abs(delta) <= SCROLL_POSITION_EPSILON) {
276
+ return false
277
+ }
278
+
279
+ viewport.scrollTop += delta
280
+ anchor.viewportTop = getElementViewportTop(anchor.element, viewport)
281
+ scheduleStateCommit()
282
+ scheduleVisibilitySync()
283
+
284
+ return true
285
+ }, [scheduleStateCommit, scheduleVisibilitySync])
286
+
287
+ const capturePrependAnchor = React.useCallback(() => {
288
+ const content = contentRef.current
289
+ const viewport = viewportRef.current
290
+
291
+ if (!content || !viewport) {
292
+ prependRestoreRef.current = null
293
+ return
294
+ }
295
+
296
+ const anchor = getFirstVisibleMessageItem({
297
+ content,
298
+ spacer: spacerRef.current,
299
+ viewport,
300
+ })
301
+
302
+ prependRestoreRef.current = anchor
303
+ ? {
304
+ element: anchor,
305
+ viewportTop: getElementViewportTop(anchor, viewport),
306
+ }
307
+ : null
308
+ }, [])
309
+
310
+ const schedulePendingScrollToMessageFlush = React.useCallback(() => {
311
+ if (pendingScrollFrameRef.current !== null) {
312
+ return
313
+ }
314
+
315
+ pendingScrollFrameRef.current = window.requestAnimationFrame(() => {
316
+ pendingScrollFrameRef.current = null
317
+
318
+ if (flushPendingScrollToMessage()) {
319
+ capturePrependAnchor()
320
+ }
321
+ })
322
+ }, [capturePrependAnchor, flushPendingScrollToMessage])
323
+
324
+ const applyDefaultScrollPosition = React.useCallback(() => {
325
+ if (
326
+ !defaultScrollPosition ||
327
+ defaultScrollPositionAppliedRef.current ||
328
+ itemCountRef.current === 0
329
+ ) {
330
+ return false
331
+ }
332
+
333
+ let handled = false
334
+
335
+ if (defaultScrollPosition === "last-anchor") {
336
+ const content = contentRef.current
337
+ const viewport = viewportRef.current
338
+ const anchor =
339
+ content && viewport
340
+ ? getLastScrollAnchor(
341
+ getMessageScrollerItems(content, spacerRef.current)
342
+ )
343
+ : null
344
+
345
+ if (!content || !viewport || !anchor) {
346
+ handled = scrollToEnd({ behavior: "auto" })
347
+ } else {
348
+ const anchorTop = getElementTop(anchor, viewport)
349
+ const contentBottom = getContentBottom({
350
+ content,
351
+ spacer: spacerRef.current,
352
+ viewport,
353
+ })
354
+ // A short last turn already fits below the anchor, so opening at the end
355
+ // shows the whole turn without leaving a blank gap beneath it.
356
+ const lastTurnFits = contentBottom - anchorTop <= viewport.clientHeight
357
+
358
+ handled = lastTurnFits
359
+ ? scrollToEnd({ behavior: "auto" })
360
+ : scrollToElement(
361
+ anchor,
362
+ { align: "start" },
363
+ { keepPreviousPeek: true }
364
+ )
365
+ }
366
+ } else {
367
+ handled =
368
+ defaultScrollPosition === "end"
369
+ ? scrollToEnd({ behavior: "auto" })
370
+ : scrollToStart({ behavior: "auto" })
371
+ }
372
+
373
+ if (!handled) {
374
+ return false
375
+ }
376
+
377
+ markDefaultScrollPositionApplied(refs)
378
+
379
+ return true
380
+ }, [defaultScrollPosition, scrollToElement, scrollToEnd, scrollToStart])
381
+
382
+ const handleContentChange = React.useCallback(() => {
383
+ const content = contentRef.current
384
+
385
+ if (!content) {
386
+ return
387
+ }
388
+
389
+ const items = getMessageScrollerItems(content, spacerRef.current)
390
+ const previousItemCount = itemCountRef.current
391
+ const previousFirstItem = firstItemRef.current
392
+
393
+ itemCountRef.current = items.length
394
+ firstItemRef.current = items[0] ?? null
395
+ // Majapi UI: an anchor is new only when its element was never in the list.
396
+ // Upstream also treated every anchor present at load (or prepended) as
397
+ // unhandled, so a same-count change (a "writing" row replaced by the
398
+ // reply) jumped to the oldest turn.
399
+ const newScrollAnchors = items.filter(
400
+ (item) =>
401
+ item.dataset.scrollAnchor === "true" &&
402
+ !handledScrollAnchorsRef.current.has(item)
403
+ )
404
+
405
+ // Reconcile the scroll position with the new content. Every path re-captures
406
+ // the prepend anchor afterward, so each branch just returns.
407
+ //
408
+ // Branch order is load-bearing: first-content, prepended, appended, updated.
409
+ const reconcileScrollPosition = () => {
410
+ if (flushPendingScrollToMessage()) {
411
+ return
412
+ }
413
+
414
+ if (previousItemCount === 0) {
415
+ if (applyDefaultScrollPosition()) {
416
+ return
417
+ }
418
+
419
+ if (
420
+ items.length > 0 &&
421
+ autoScrollRef.current &&
422
+ scrollToEnd({ behavior: "auto" })
423
+ ) {
424
+ return
425
+ }
426
+
427
+ commitScrollState()
428
+ scheduleVisibilitySync()
429
+ return
430
+ }
431
+
432
+ const previousFirstItemIndex = previousFirstItem
433
+ ? items.indexOf(previousFirstItem)
434
+ : -1
435
+ const didPrepend =
436
+ preserveScrollOnPrependRef.current && previousFirstItemIndex > 0
437
+
438
+ if (didPrepend) {
439
+ // Prepended rows are not new appends. Restore the prior scroll position.
440
+ // The restore is a no-op where native scroll anchoring already did it.
441
+ restorePrependedAnchor()
442
+ return
443
+ }
444
+
445
+ if (items.length > previousItemCount) {
446
+ const anchor = newScrollAnchors[0] ?? null
447
+
448
+ if (anchor) {
449
+ // While the reader is following the live end, a batch of several
450
+ // anchored turns arriving at once should keep following the end — not
451
+ // yank back to anchor the first turn of the batch. A single new anchor
452
+ // still moves to the top as usual.
453
+ if (
454
+ autoScrollRef.current &&
455
+ modeRef.current === "following-bottom" &&
456
+ newScrollAnchors.length > 1
457
+ ) {
458
+ scrollToEnd({ behavior: "auto" })
459
+ return
460
+ }
461
+
462
+ scrollToElement(
463
+ anchor,
464
+ { align: "start" },
465
+ { keepPreviousPeek: true }
466
+ )
467
+ handledScrollAnchorsRef.current.add(anchor)
468
+ return
469
+ }
470
+ }
471
+
472
+ if (items.length === previousItemCount) {
473
+ const anchor = newScrollAnchors[0] ?? null
474
+
475
+ if (anchor) {
476
+ scrollToElement(
477
+ anchor,
478
+ { align: "start" },
479
+ { keepPreviousPeek: true }
480
+ )
481
+ handledScrollAnchorsRef.current.add(anchor)
482
+ return
483
+ }
484
+ }
485
+
486
+ // Appends with no new anchor (and content-only updates) fall through here:
487
+ // keep following the end if we still are, otherwise just recommit state.
488
+ if (modeRef.current === "following-bottom" && autoScrollRef.current) {
489
+ scrollToEnd({ behavior: "auto" })
490
+ } else {
491
+ commitScrollState()
492
+ scheduleVisibilitySync()
493
+ }
494
+ }
495
+
496
+ reconcileScrollPosition()
497
+ for (const anchor of newScrollAnchors) {
498
+ handledScrollAnchorsRef.current.add(anchor)
499
+ }
500
+ capturePrependAnchor()
501
+ }, [
502
+ applyDefaultScrollPosition,
503
+ capturePrependAnchor,
504
+ commitScrollState,
505
+ flushPendingScrollToMessage,
506
+ restorePrependedAnchor,
507
+ scheduleVisibilitySync,
508
+ scrollToElement,
509
+ scrollToEnd,
510
+ ])
511
+
512
+ // A manual scroll during an anchored streaming turn releases the anchor
513
+ // (userScrollIntent -> free-scrolling) and strands the reserved tail spacer.
514
+ // Nothing re-arms follow in that mode, so the spacer would otherwise freeze
515
+ // at its current height and leave dead space below the reply. Drain it: as
516
+ // the reply grows (resize) or as the reader scrolls to the real bottom
517
+ // (scroll), shrink the spacer toward zero so the reserved room is consumed
518
+ // without moving the reader, and hand back to following once the reply fills
519
+ // the viewport (spacer hits zero at the real bottom). Returns true when the
520
+ // spacer drained to zero and the view handed off to following, so callers can
521
+ // skip any further state reconciliation for the frame.
522
+ //
523
+ // The drain is skipped while a programmatic scroll is in flight (autoscrolling
524
+ // or an anchored/settling jump): those paths already consume the spacer via
525
+ // reanchorToAnchoredMessage, and letting the scroll event drain it would yank
526
+ // the anchored turn to the bottom. The remaining room is recomputed from
527
+ // absolute geometry on every event (contentBottom + spacer - viewport bottom)
528
+ // so the drain converges instead of over-draining across inertial scroll
529
+ // events, and the spacer is left untouched while the reader is above the
530
+ // spacer zone entirely.
531
+ const drainReleasedSpacer = React.useCallback(() => {
532
+ if (
533
+ !autoScrollRef.current ||
534
+ spacerHeightRef.current <= 0 ||
535
+ modeRef.current === "following-bottom" ||
536
+ modeRef.current === "anchored-to-message" ||
537
+ modeRef.current === "settling-jump" ||
538
+ autoscrollingRef.current
539
+ ) {
540
+ return false
541
+ }
542
+
543
+ const viewport = viewportRef.current
544
+ const content = contentRef.current
545
+
546
+ if (!viewport || !content) {
547
+ return false
548
+ }
549
+
550
+ const contentBottom = getContentBottom({
551
+ content,
552
+ spacer: spacerRef.current,
553
+ viewport,
554
+ })
555
+
556
+ // How far the reader has scrolled into the reserved spacer zone. When the
557
+ // viewport bottom has not yet reached the content bottom the reader is
558
+ // above the spacer zone entirely, so the spacer must be left untouched.
559
+ const overlap =
560
+ viewport.scrollTop + viewport.clientHeight - contentBottom
561
+
562
+ if (overlap <= 0) {
563
+ return false
564
+ }
565
+
566
+ // Recompute the remaining spacer room from absolute geometry on every event
567
+ // so the drain converges instead of over-draining: the spacer shrinks by
568
+ // the amount of room the reader has already scrolled past, never by a delta
569
+ // that compounds across inertial scroll events.
570
+ const nextSpacerHeight = Math.max(
571
+ 0,
572
+ contentBottom +
573
+ spacerHeightRef.current -
574
+ (viewport.scrollTop + viewport.clientHeight)
575
+ )
576
+
577
+ if (nextSpacerHeight === 0) {
578
+ scrollToEnd({ behavior: "auto" })
579
+ return true
580
+ }
581
+
582
+ setTailSpacerHeight(nextSpacerHeight)
583
+
584
+ return false
585
+ }, [scrollToEnd, setTailSpacerHeight])
586
+
587
+ const handleResize = React.useCallback(() => {
588
+ if (modeRef.current === "following-bottom" && autoScrollRef.current) {
589
+ scrollToEnd({ behavior: "auto" })
590
+ return
591
+ }
592
+
593
+ // Hold the anchored turn in place as content below it resizes (a reply
594
+ // streaming in, or a transient marker collapsing) — otherwise the shrinking
595
+ // content lets the browser clamp scrollTop and the turn drops.
596
+ const previousSpacerHeight = spacerHeightRef.current
597
+
598
+ if (reanchorToAnchoredMessage()) {
599
+ // The reply streaming below the anchor consumes the tail spacer as it
600
+ // grows. Once the last of it is gone the reply has filled the viewport
601
+ // and the reader is genuinely at the live edge, so autoScroll hands off
602
+ // from the anchor hold to following the bottom. Requiring the >0 → 0
603
+ // transition keeps a turn taller than the viewport (placed with no
604
+ // spacer) held instead of yanked to the end.
605
+ if (
606
+ autoScrollRef.current &&
607
+ previousSpacerHeight > 0 &&
608
+ spacerHeightRef.current === 0
609
+ ) {
610
+ scrollToEnd({ behavior: "auto" })
611
+ }
612
+
613
+ return
614
+ }
615
+
616
+ // Drain a stranded spacer as the reply grows below it. Early return when
617
+ // it hit zero so the following hand-off owns the frame.
618
+ if (drainReleasedSpacer()) {
619
+ return
620
+ }
621
+
622
+ scheduleStateCommit()
623
+ scheduleVisibilitySync()
624
+ }, [
625
+ drainReleasedSpacer,
626
+ reanchorToAnchoredMessage,
627
+ scheduleStateCommit,
628
+ scheduleVisibilitySync,
629
+ scrollToEnd,
630
+ ])
631
+
632
+ const observeVisibility = React.useCallback(() => {
633
+ const viewport = viewportRef.current
634
+
635
+ if (!viewport || !visibilityStore.hasListeners()) {
636
+ return
637
+ }
638
+
639
+ if (typeof IntersectionObserver === "undefined") {
640
+ scheduleVisibilitySync()
641
+ return
642
+ }
643
+
644
+ if (!visibilityObserverRef.current) {
645
+ visibilityObserverRef.current = new IntersectionObserver(
646
+ (entries) => {
647
+ for (const entry of entries) {
648
+ const messageId = (entry.target as HTMLElement).dataset.messageId
649
+
650
+ if (!messageId) {
651
+ continue
652
+ }
653
+
654
+ if (entry.isIntersecting) {
655
+ visibleMessageIdsRef.current.add(messageId)
656
+ } else {
657
+ visibleMessageIdsRef.current.delete(messageId)
658
+ }
659
+ }
660
+
661
+ scheduleVisibilitySync()
662
+ },
663
+ {
664
+ root: viewport,
665
+ // Shrink the root's top edge to the anchoring line so a previous turn
666
+ // peeking in the scrollMargin + peek band is not reported as visible,
667
+ // keeping visibleMessageIds consistent with currentAnchorId. Captured
668
+ // at observe time; a prop change rebuilds the observer on resubscribe.
669
+ rootMargin: `${-(
670
+ scrollMarginRef.current + scrollPreviousItemPeekRef.current
671
+ )}px 0px 0px 0px`,
672
+ threshold: [0, 0.01, 0.5, 1],
673
+ }
674
+ )
675
+ }
676
+
677
+ messageElementsRef.current.forEach((element) => {
678
+ visibilityObserverRef.current?.observe(element)
679
+ })
680
+ scheduleVisibilitySync()
681
+ }, [scheduleVisibilitySync, visibilityStore])
682
+
683
+ const unobserveVisibility = React.useCallback(() => {
684
+ if (visibilityFrameRef.current !== null) {
685
+ window.cancelAnimationFrame(visibilityFrameRef.current)
686
+ visibilityFrameRef.current = null
687
+ }
688
+
689
+ visibilityObserverRef.current?.disconnect()
690
+ visibilityObserverRef.current = null
691
+ visibleMessageIdsRef.current.clear()
692
+ visibilityStore.setSnapshot(EMPTY_MESSAGE_SCROLLER_VISIBILITY_STATE)
693
+ }, [visibilityStore])
694
+
695
+ const registerMessage = React.useCallback<MessageScrollerRegisterMessage>(
696
+ (messageId, element, removedElement) => {
697
+ if (element) {
698
+ messageElementsRef.current.set(messageId, element)
699
+ visibilityObserverRef.current?.observe(element)
700
+ scheduleVisibilitySync()
701
+
702
+ if (pendingScrollToMessageRef.current?.messageId === messageId) {
703
+ schedulePendingScrollToMessageFlush()
704
+ }
705
+
706
+ return
707
+ }
708
+
709
+ if (
710
+ removedElement &&
711
+ messageElementsRef.current.get(messageId) === removedElement
712
+ ) {
713
+ messageElementsRef.current.delete(messageId)
714
+ visibleMessageIdsRef.current.delete(messageId)
715
+ visibilityObserverRef.current?.unobserve(removedElement)
716
+ scheduleVisibilitySync()
717
+ }
718
+ },
719
+ [schedulePendingScrollToMessageFlush, scheduleVisibilitySync]
720
+ )
721
+
722
+ const userScrollIntent = React.useCallback(() => {
723
+ if (
724
+ modeRef.current === "following-bottom" ||
725
+ modeRef.current === "anchored-to-message" ||
726
+ modeRef.current === "settling-jump"
727
+ ) {
728
+ // A deliberate gesture releases auto-follow, turn-anchoring, and an in-flight
729
+ // programmatic jump so re-pinning (and re-arming) never fights the reader.
730
+ streamingTurnRef.current = null
731
+ modeRef.current = "free-scrolling"
732
+ }
733
+ }, [])
734
+
735
+ const mirrorStateAttributes = React.useCallback(
736
+ () => writeStateAttributes(stateStore.getSnapshot()),
737
+ [stateStore, writeStateAttributes]
738
+ )
739
+
740
+ const setRootElement = useElementRef(rootRef, mirrorStateAttributes)
741
+ const setViewportElement = useElementRef(viewportRef, mirrorStateAttributes)
742
+
743
+ const setContentElement = React.useCallback(
744
+ (element: HTMLDivElement | null) => {
745
+ contentRef.current = element
746
+ },
747
+ []
748
+ )
749
+
750
+ const setSpacerElement = React.useCallback(
751
+ (element: HTMLDivElement | null) => {
752
+ spacerRef.current = element
753
+ spacerGapRef.current = getFlexGap(element?.parentElement ?? null)
754
+ },
755
+ []
756
+ )
757
+
758
+ const syncAfterScroll = React.useCallback(() => {
759
+ // A released spacer can be stranded if the stream ends before the reply
760
+ // drains it (no more resizes to drive the drain). Let a scroll to the real
761
+ // bottom - contentBottom plus the remaining spacer - finish the job: the
762
+ // reader reclaims the dead space and following re-arms once it hits zero.
763
+ drainReleasedSpacer()
764
+ commitScrollState()
765
+ scheduleVisibilitySync()
766
+ capturePrependAnchor()
767
+ }, [
768
+ capturePrependAnchor,
769
+ commitScrollState,
770
+ drainReleasedSpacer,
771
+ scheduleVisibilitySync,
772
+ ])
773
+
774
+ const context = React.useMemo<MessageScrollerContextValue>(
775
+ () => ({
776
+ handleContentChange,
777
+ handleResize,
778
+ observeVisibility,
779
+ pendingDefaultScrollStore,
780
+ preserveScrollOnPrependRef,
781
+ scrollToEnd,
782
+ scrollToMessage,
783
+ scrollToStart,
784
+ setContentElement,
785
+ setRootElement,
786
+ setSpacerElement,
787
+ setViewportElement,
788
+ stateStore,
789
+ syncAfterScroll,
790
+ unobserveVisibility,
791
+ userScrollIntent,
792
+ viewportRef,
793
+ visibilityStore,
794
+ }),
795
+ [
796
+ handleContentChange,
797
+ handleResize,
798
+ observeVisibility,
799
+ pendingDefaultScrollStore,
800
+ scrollToEnd,
801
+ scrollToMessage,
802
+ scrollToStart,
803
+ setContentElement,
804
+ setRootElement,
805
+ setSpacerElement,
806
+ setViewportElement,
807
+ stateStore,
808
+ syncAfterScroll,
809
+ unobserveVisibility,
810
+ userScrollIntent,
811
+ visibilityStore,
812
+ ]
813
+ )
814
+
815
+ React.useLayoutEffect(() => {
816
+ if (applyDefaultScrollPosition()) {
817
+ return
818
+ }
819
+
820
+ if (itemCountRef.current === 0) {
821
+ clearPendingDefaultScroll(refs)
822
+ }
823
+ }, [applyDefaultScrollPosition])
824
+
825
+ React.useEffect(() => {
826
+ return () => {
827
+ // Reset every ref after cancelling. StrictMode replays effects on the same
828
+ // refs (unmount then remount), so a frame id left non-null here makes the
829
+ // scheduler on remount think a frame is still pending and never reschedule.
830
+ if (stateFrameRef.current !== null) {
831
+ window.cancelAnimationFrame(stateFrameRef.current)
832
+ stateFrameRef.current = null
833
+ }
834
+
835
+ if (visibilityFrameRef.current !== null) {
836
+ window.cancelAnimationFrame(visibilityFrameRef.current)
837
+ visibilityFrameRef.current = null
838
+ }
839
+
840
+ if (autoscrollingTimeoutRef.current !== null) {
841
+ window.clearTimeout(autoscrollingTimeoutRef.current)
842
+ autoscrollingTimeoutRef.current = null
843
+ }
844
+
845
+ if (pendingScrollFrameRef.current !== null) {
846
+ window.cancelAnimationFrame(pendingScrollFrameRef.current)
847
+ pendingScrollFrameRef.current = null
848
+ }
849
+
850
+ visibilityObserverRef.current?.disconnect()
851
+ visibilityObserverRef.current = null
852
+ }
853
+ }, [])
854
+
855
+ React.useLayoutEffect(() => {
856
+ if (
857
+ autoScroll &&
858
+ modeRef.current === "following-bottom" &&
859
+ itemCountRef.current > 0
860
+ ) {
861
+ scrollToEnd({ behavior: "auto" })
862
+ return
863
+ }
864
+
865
+ commitScrollState()
866
+ }, [autoScroll, commitScrollState, scrollToEnd])
867
+
868
+ return {
869
+ context,
870
+ registerMessage,
871
+ }
872
+ }
873
+
874
+ export { useMessageScrollerController }