@codefast/ui 0.5.0-canary.2 → 0.5.0-canary.3

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.
Files changed (69) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/dist/components/attachment.d.mts +136 -0
  3. package/dist/components/attachment.mjs +112 -0
  4. package/dist/components/avatar.mjs +1 -1
  5. package/dist/components/bubble.d.mts +67 -0
  6. package/dist/components/bubble.mjs +58 -0
  7. package/dist/components/card.mjs +2 -2
  8. package/dist/components/carousel.mjs +12 -3
  9. package/dist/components/empty.mjs +1 -1
  10. package/dist/components/marker.d.mts +49 -0
  11. package/dist/components/marker.mjs +42 -0
  12. package/dist/components/message-scroller.d.mts +89 -0
  13. package/dist/components/message-scroller.mjs +77 -0
  14. package/dist/components/message.d.mts +86 -0
  15. package/dist/components/message.mjs +66 -0
  16. package/dist/components/sidebar.mjs +6 -3
  17. package/dist/hooks/use-message-scroller-commands.d.mts +39 -0
  18. package/dist/hooks/use-message-scroller-commands.mjs +165 -0
  19. package/dist/hooks/use-message-scroller-controller.d.mts +19 -0
  20. package/dist/hooks/use-message-scroller-controller.mjs +382 -0
  21. package/dist/hooks/use-message-scroller-refs.d.mts +60 -0
  22. package/dist/hooks/use-message-scroller-refs.mjs +77 -0
  23. package/dist/index.d.mts +11 -1
  24. package/dist/index.mjs +11 -2
  25. package/dist/lib/message-scroller/geometry.d.mts +136 -0
  26. package/dist/lib/message-scroller/geometry.mjs +199 -0
  27. package/dist/lib/message-scroller/stores.d.mts +21 -0
  28. package/dist/lib/message-scroller/stores.mjs +52 -0
  29. package/dist/lib/message-scroller/types.d.mts +171 -0
  30. package/dist/lib/message-scroller/types.mjs +53 -0
  31. package/dist/lib/message-scroller/utils.d.mts +7 -0
  32. package/dist/lib/message-scroller/utils.mjs +12 -0
  33. package/dist/lib/use-render.d.mts +43 -0
  34. package/dist/lib/use-render.mjs +84 -0
  35. package/dist/primitives/message-scroller.d.mts +88 -0
  36. package/dist/primitives/message-scroller.mjs +240 -0
  37. package/dist/variants/attachment.d.mts +42 -0
  38. package/dist/variants/attachment.mjs +42 -0
  39. package/dist/variants/bubble.d.mts +45 -0
  40. package/dist/variants/bubble.mjs +45 -0
  41. package/dist/variants/marker.d.mts +21 -0
  42. package/dist/variants/marker.mjs +18 -0
  43. package/package.json +52 -6
  44. package/src/components/attachment.tsx +284 -0
  45. package/src/components/avatar.tsx +1 -1
  46. package/src/components/bubble.tsx +116 -0
  47. package/src/components/card.tsx +2 -2
  48. package/src/components/carousel.tsx +12 -3
  49. package/src/components/empty.tsx +1 -1
  50. package/src/components/marker.tsx +94 -0
  51. package/src/components/message-scroller.tsx +213 -0
  52. package/src/components/message.tsx +173 -0
  53. package/src/components/sidebar.tsx +11 -4
  54. package/src/css/foundation/tokens.css +6 -18
  55. package/src/css/foundation/utilities.css +451 -0
  56. package/src/css/preset.css +2 -1
  57. package/src/hooks/use-message-scroller-commands.ts +312 -0
  58. package/src/hooks/use-message-scroller-controller.ts +651 -0
  59. package/src/hooks/use-message-scroller-refs.ts +168 -0
  60. package/src/index.ts +72 -0
  61. package/src/lib/message-scroller/geometry.ts +398 -0
  62. package/src/lib/message-scroller/stores.ts +89 -0
  63. package/src/lib/message-scroller/types.ts +310 -0
  64. package/src/lib/message-scroller/utils.ts +15 -0
  65. package/src/lib/use-render.ts +202 -0
  66. package/src/primitives/message-scroller.tsx +399 -0
  67. package/src/variants/attachment.ts +73 -0
  68. package/src/variants/bubble.ts +81 -0
  69. package/src/variants/marker.ts +38 -0
@@ -0,0 +1,651 @@
1
+ // Vendored from shadcn-ui/ui packages/react/src/message-scroller/use-message-scroller-controller.ts
2
+ // Callbacks read from stable refs; omitting them from deps is intentional and keeps identities stable.
3
+ /* oxlint-disable react-hooks/exhaustive-deps */
4
+ import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react";
5
+ import type { RefObject } from "react";
6
+
7
+ import { useMessageScrollerCommands } from "#/hooks/use-message-scroller-commands";
8
+ import { useMessageScrollerRefs } from "#/hooks/use-message-scroller-refs";
9
+ import type { MessageScrollerRefs } from "#/hooks/use-message-scroller-refs";
10
+ import {
11
+ getContentBottom,
12
+ getElementTop,
13
+ getElementViewportTop,
14
+ getFirstVisibleMessageItem,
15
+ getFlexGap,
16
+ getLastScrollAnchor,
17
+ getMessageScrollerItems,
18
+ getMessageScrollerScrollable,
19
+ getMessageScrollerVisibilityState,
20
+ getNewScrollAnchor,
21
+ getUnanchoredScrollAnchor,
22
+ hasMultipleNewScrollAnchors,
23
+ } from "#/lib/message-scroller/geometry";
24
+ import {
25
+ DEFAULT_SCROLL_EDGE_THRESHOLD,
26
+ DEFAULT_SCROLL_MARGIN,
27
+ DEFAULT_SCROLL_PREVIOUS_ITEM_PEEK,
28
+ EMPTY_MESSAGE_SCROLLER_VISIBILITY_STATE,
29
+ SCROLL_POSITION_EPSILON,
30
+ } from "#/lib/message-scroller/types";
31
+ import type {
32
+ MessageScrollerContextValue,
33
+ MessageScrollerProviderProps,
34
+ MessageScrollerRegisterMessage,
35
+ MessageScrollerScrollable,
36
+ } from "#/lib/message-scroller/types";
37
+
38
+ // Builds a ref callback that stores the node and runs onMount once it attaches.
39
+ function useElementRef(elementRef: RefObject<HTMLDivElement | null>, onMount: () => void) {
40
+ return useCallback(
41
+ (element: HTMLDivElement | null) => {
42
+ elementRef.current = element;
43
+
44
+ if (element) {
45
+ onMount();
46
+ }
47
+ },
48
+ [elementRef, onMount],
49
+ );
50
+ }
51
+
52
+ // Orchestrator hook. Decides when to scroll and delegates the moves to
53
+ // useMessageScrollerCommands; state and visibility commits are coalesced on a
54
+ // requestAnimationFrame and torn down on cleanup for StrictMode safety.
55
+ /**
56
+ * @since 0.5.0-canary.3
57
+ */
58
+ function useMessageScrollerController({
59
+ autoScroll = false,
60
+ defaultScrollPosition = "end",
61
+ scrollEdgeThreshold = DEFAULT_SCROLL_EDGE_THRESHOLD,
62
+ scrollPreviousItemPeek = DEFAULT_SCROLL_PREVIOUS_ITEM_PEEK,
63
+ scrollMargin = DEFAULT_SCROLL_MARGIN,
64
+ }: MessageScrollerProviderProps) {
65
+ const refs = useMessageScrollerRefs({
66
+ autoScroll,
67
+ scrollEdgeThreshold,
68
+ scrollMargin,
69
+ scrollPreviousItemPeek,
70
+ });
71
+
72
+ const {
73
+ streamingTurnRef,
74
+ autoScrollRef,
75
+ autoscrollingRef,
76
+ autoscrollingTimeoutRef,
77
+ contentRef,
78
+ defaultScrollPositionAppliedRef,
79
+ firstItemRef,
80
+ itemCountRef,
81
+ messageElementsRef,
82
+ modeRef,
83
+ pendingScrollFrameRef,
84
+ pendingScrollToMessageRef,
85
+ prependRestoreRef,
86
+ preserveScrollOnPrependRef,
87
+ rootRef,
88
+ scrollEdgeThresholdRef,
89
+ scrollMarginRef,
90
+ scrollPreviousItemPeekRef,
91
+ spacerGapRef,
92
+ spacerRef,
93
+ stateFrameRef,
94
+ stateStore,
95
+ viewportRef,
96
+ visibilityFrameRef,
97
+ visibilityObserverRef,
98
+ visibilityStore,
99
+ visibleMessageIdsRef,
100
+ handledScrollAnchorsRef,
101
+ } = refs;
102
+
103
+ const previousDefaultScrollPositionRef = useRef(defaultScrollPosition);
104
+
105
+ if (previousDefaultScrollPositionRef.current !== defaultScrollPosition) {
106
+ previousDefaultScrollPositionRef.current = defaultScrollPosition;
107
+ defaultScrollPositionAppliedRef.current = false;
108
+ }
109
+
110
+ const writeStateAttributes = useCallback((state: MessageScrollerScrollable) => {
111
+ const root = rootRef.current;
112
+ const viewport = viewportRef.current;
113
+ const scrollable = [state.start && "start", state.end && "end"].filter(Boolean).join(" ");
114
+ const autoScrolling = autoscrollingRef.current;
115
+
116
+ for (const element of [root, viewport]) {
117
+ if (!element) {
118
+ continue;
119
+ }
120
+
121
+ if (scrollable) {
122
+ element.setAttribute("data-scrollable", scrollable);
123
+ } else {
124
+ element.removeAttribute("data-scrollable");
125
+ }
126
+
127
+ element.toggleAttribute("data-autoscrolling", autoScrolling);
128
+ }
129
+ }, []);
130
+
131
+ // Owns the one follow-bottom transition: arm at the bottom, release on any
132
+ // scroll away (including a scrollbar drag), suppressed during a programmatic
133
+ // scroll so the auto-scroll animation cannot release itself.
134
+ const reconcileFollowMode = useCallback((scrollable: MessageScrollerScrollable) => {
135
+ if (autoScrollRef.current && !scrollable.end && modeRef.current !== "settling-jump") {
136
+ modeRef.current = "following-bottom";
137
+ } else if (modeRef.current === "following-bottom" && scrollable.end && !autoscrollingRef.current) {
138
+ modeRef.current = "free-scrolling";
139
+ }
140
+ }, []);
141
+
142
+ const commitScrollState = useCallback(() => {
143
+ const nextState = getMessageScrollerScrollable({
144
+ content: contentRef.current,
145
+ scrollEdgeThreshold: scrollEdgeThresholdRef.current,
146
+ spacer: spacerRef.current,
147
+ viewport: viewportRef.current,
148
+ });
149
+
150
+ reconcileFollowMode(nextState);
151
+ writeStateAttributes(nextState);
152
+ stateStore.setSnapshot(nextState);
153
+ }, [reconcileFollowMode, stateStore, writeStateAttributes]);
154
+
155
+ const scheduleStateCommit = useCallback(() => {
156
+ if (stateFrameRef.current !== null) {
157
+ return;
158
+ }
159
+
160
+ stateFrameRef.current = window.requestAnimationFrame(() => {
161
+ stateFrameRef.current = null;
162
+ commitScrollState();
163
+ });
164
+ }, [commitScrollState]);
165
+
166
+ const scheduleVisibilitySync = useCallback(() => {
167
+ if (!visibilityStore.hasListeners()) {
168
+ return;
169
+ }
170
+
171
+ if (visibilityFrameRef.current !== null) {
172
+ return;
173
+ }
174
+
175
+ visibilityFrameRef.current = window.requestAnimationFrame(() => {
176
+ visibilityFrameRef.current = null;
177
+
178
+ // A frame can outlive the last unsubscribe. Recomputing here would
179
+ // overwrite the EMPTY snapshot that teardown just wrote, leaving a stale
180
+ // value for the next subscriber to read.
181
+ if (!visibilityStore.hasListeners()) {
182
+ return;
183
+ }
184
+
185
+ visibilityStore.setSnapshot(
186
+ getMessageScrollerVisibilityState({
187
+ content: contentRef.current,
188
+ scrollMargin: scrollMarginRef.current,
189
+ scrollPreviousItemPeek: scrollPreviousItemPeekRef.current,
190
+ spacer: spacerRef.current,
191
+ viewport: viewportRef.current,
192
+ visibleMessageIds: visibleMessageIdsRef.current,
193
+ }),
194
+ );
195
+ });
196
+ }, [visibilityStore]);
197
+
198
+ const {
199
+ flushPendingScrollToMessage,
200
+ reanchorToAnchoredMessage,
201
+ scrollToElement,
202
+ scrollToEnd,
203
+ scrollToMessage,
204
+ scrollToStart,
205
+ } = useMessageScrollerCommands({
206
+ refs,
207
+ commitScrollState,
208
+ scheduleStateCommit,
209
+ scheduleVisibilitySync,
210
+ });
211
+
212
+ const restorePrependedAnchor = useCallback(() => {
213
+ const anchor = prependRestoreRef.current;
214
+ const viewport = viewportRef.current;
215
+
216
+ if (!anchor || !viewport || !anchor.element.isConnected) {
217
+ return false;
218
+ }
219
+
220
+ // Compare the anchor relative to the viewport, not to the content. Native
221
+ // scroll anchoring leaves the viewport-relative position unchanged, so this
222
+ // is a no-op where the browser already handled the prepend and only corrects
223
+ // the scroll where it did not (e.g. Safari) — without trusting a capability
224
+ // flag, which some engines report incorrectly.
225
+ const nextViewportTop = getElementViewportTop(anchor.element, viewport);
226
+ const delta = nextViewportTop - anchor.viewportTop;
227
+
228
+ if (Math.abs(delta) <= SCROLL_POSITION_EPSILON) {
229
+ return false;
230
+ }
231
+
232
+ viewport.scrollTop += delta;
233
+ anchor.viewportTop = getElementViewportTop(anchor.element, viewport);
234
+ scheduleStateCommit();
235
+ scheduleVisibilitySync();
236
+
237
+ return true;
238
+ }, [scheduleStateCommit, scheduleVisibilitySync]);
239
+
240
+ const capturePrependAnchor = useCallback(() => {
241
+ const content = contentRef.current;
242
+ const viewport = viewportRef.current;
243
+
244
+ if (!content || !viewport) {
245
+ prependRestoreRef.current = null;
246
+ return;
247
+ }
248
+
249
+ const anchor = getFirstVisibleMessageItem({
250
+ content,
251
+ spacer: spacerRef.current,
252
+ viewport,
253
+ });
254
+
255
+ prependRestoreRef.current = anchor
256
+ ? {
257
+ element: anchor,
258
+ viewportTop: getElementViewportTop(anchor, viewport),
259
+ }
260
+ : null;
261
+ }, []);
262
+
263
+ const schedulePendingScrollToMessageFlush = useCallback(() => {
264
+ if (pendingScrollFrameRef.current !== null) {
265
+ return;
266
+ }
267
+
268
+ pendingScrollFrameRef.current = window.requestAnimationFrame(() => {
269
+ pendingScrollFrameRef.current = null;
270
+
271
+ if (flushPendingScrollToMessage()) {
272
+ capturePrependAnchor();
273
+ }
274
+ });
275
+ }, [capturePrependAnchor, flushPendingScrollToMessage]);
276
+
277
+ const applyDefaultScrollPosition = useCallback(() => {
278
+ if (!defaultScrollPosition || defaultScrollPositionAppliedRef.current || itemCountRef.current === 0) {
279
+ return false;
280
+ }
281
+
282
+ let handled = false;
283
+
284
+ if (defaultScrollPosition === "last-anchor") {
285
+ const content = contentRef.current;
286
+ const viewport = viewportRef.current;
287
+ const anchor =
288
+ content && viewport ? getLastScrollAnchor(getMessageScrollerItems(content, spacerRef.current)) : null;
289
+
290
+ if (!content || !viewport || !anchor) {
291
+ handled = scrollToEnd({ behavior: "auto" });
292
+ } else {
293
+ const anchorTop = getElementTop(anchor, viewport);
294
+ const contentBottom = getContentBottom({
295
+ content,
296
+ spacer: spacerRef.current,
297
+ viewport,
298
+ });
299
+ // A short last turn already fits below the anchor, so opening at the end
300
+ // shows the whole turn without leaving a blank gap beneath it.
301
+ const lastTurnFits = contentBottom - anchorTop <= viewport.clientHeight;
302
+
303
+ handled = lastTurnFits
304
+ ? scrollToEnd({ behavior: "auto" })
305
+ : scrollToElement(anchor, { align: "start" }, { keepPreviousPeek: true });
306
+ }
307
+ } else {
308
+ handled =
309
+ defaultScrollPosition === "end" ? scrollToEnd({ behavior: "auto" }) : scrollToStart({ behavior: "auto" });
310
+ }
311
+
312
+ if (!handled) {
313
+ return false;
314
+ }
315
+
316
+ defaultScrollPositionAppliedRef.current = true;
317
+
318
+ return true;
319
+ }, [defaultScrollPosition, scrollToElement, scrollToEnd, scrollToStart]);
320
+
321
+ const handleContentChange = useCallback(() => {
322
+ const content = contentRef.current;
323
+
324
+ if (!content) {
325
+ return;
326
+ }
327
+
328
+ const items = getMessageScrollerItems(content, spacerRef.current);
329
+ const previousItemCount = itemCountRef.current;
330
+ const previousFirstItem = firstItemRef.current;
331
+
332
+ itemCountRef.current = items.length;
333
+ firstItemRef.current = items[0] ?? null;
334
+
335
+ // Reconcile the scroll position with the new content. Every path re-captures
336
+ // the prepend anchor afterward, so each branch just returns.
337
+ //
338
+ // Branch order is load-bearing: first-content, prepended, appended, updated.
339
+ const reconcileScrollPosition = () => {
340
+ if (flushPendingScrollToMessage()) {
341
+ return;
342
+ }
343
+
344
+ if (previousItemCount === 0) {
345
+ if (applyDefaultScrollPosition()) {
346
+ return;
347
+ }
348
+
349
+ if (items.length > 0 && autoScrollRef.current && scrollToEnd({ behavior: "auto" })) {
350
+ return;
351
+ }
352
+
353
+ commitScrollState();
354
+ scheduleVisibilitySync();
355
+ return;
356
+ }
357
+
358
+ const previousFirstItemIndex = previousFirstItem ? items.indexOf(previousFirstItem) : -1;
359
+ const didPrepend = preserveScrollOnPrependRef.current && previousFirstItemIndex > 0;
360
+
361
+ if (didPrepend) {
362
+ // Prepended rows are not new appends. Restore the prior scroll position.
363
+ // The restore is a no-op where native scroll anchoring already did it.
364
+ restorePrependedAnchor();
365
+ return;
366
+ }
367
+
368
+ if (items.length > previousItemCount) {
369
+ const anchor = getNewScrollAnchor(items, previousItemCount);
370
+
371
+ if (anchor) {
372
+ // While the reader is following the live end, a batch of several
373
+ // anchored turns arriving at once should keep following the end — not
374
+ // yank back to anchor the first turn of the batch. A single new anchor
375
+ // still moves to the top as usual.
376
+ if (
377
+ autoScrollRef.current &&
378
+ modeRef.current === "following-bottom" &&
379
+ hasMultipleNewScrollAnchors(items, previousItemCount)
380
+ ) {
381
+ scrollToEnd({ behavior: "auto" });
382
+ return;
383
+ }
384
+
385
+ scrollToElement(anchor, { align: "start" }, { keepPreviousPeek: true });
386
+ handledScrollAnchorsRef.current.add(anchor);
387
+ return;
388
+ }
389
+ }
390
+
391
+ if (items.length === previousItemCount) {
392
+ const anchor = getUnanchoredScrollAnchor(items, handledScrollAnchorsRef.current);
393
+
394
+ if (anchor) {
395
+ scrollToElement(anchor, { align: "start" }, { keepPreviousPeek: true });
396
+ handledScrollAnchorsRef.current.add(anchor);
397
+ return;
398
+ }
399
+ }
400
+
401
+ // Appends with no new anchor (and content-only updates) fall through here:
402
+ // keep following the end if we still are, otherwise just recommit state.
403
+ if (modeRef.current === "following-bottom" && autoScrollRef.current) {
404
+ scrollToEnd({ behavior: "auto" });
405
+ } else {
406
+ commitScrollState();
407
+ scheduleVisibilitySync();
408
+ }
409
+ };
410
+
411
+ reconcileScrollPosition();
412
+ capturePrependAnchor();
413
+ }, [
414
+ applyDefaultScrollPosition,
415
+ capturePrependAnchor,
416
+ commitScrollState,
417
+ flushPendingScrollToMessage,
418
+ restorePrependedAnchor,
419
+ scheduleVisibilitySync,
420
+ scrollToElement,
421
+ scrollToEnd,
422
+ ]);
423
+
424
+ const handleResize = useCallback(() => {
425
+ if (modeRef.current === "following-bottom" && autoScrollRef.current) {
426
+ scrollToEnd({ behavior: "auto" });
427
+ return;
428
+ }
429
+
430
+ // Hold the anchored turn in place as content below it resizes (a reply
431
+ // streaming in, or a transient marker collapsing) — otherwise the shrinking
432
+ // content lets the browser clamp scrollTop and the turn drops.
433
+ if (reanchorToAnchoredMessage()) {
434
+ return;
435
+ }
436
+
437
+ scheduleStateCommit();
438
+ scheduleVisibilitySync();
439
+ }, [reanchorToAnchoredMessage, scheduleStateCommit, scheduleVisibilitySync, scrollToEnd]);
440
+
441
+ const observeVisibility = useCallback(() => {
442
+ const viewport = viewportRef.current;
443
+
444
+ if (!viewport || !visibilityStore.hasListeners()) {
445
+ return;
446
+ }
447
+
448
+ if (typeof IntersectionObserver === "undefined") {
449
+ scheduleVisibilitySync();
450
+ return;
451
+ }
452
+
453
+ if (!visibilityObserverRef.current) {
454
+ visibilityObserverRef.current = new IntersectionObserver(
455
+ (entries) => {
456
+ for (const entry of entries) {
457
+ const messageId = (entry.target as HTMLElement).dataset.messageId;
458
+
459
+ if (!messageId) {
460
+ continue;
461
+ }
462
+
463
+ if (entry.isIntersecting) {
464
+ visibleMessageIdsRef.current.add(messageId);
465
+ } else {
466
+ visibleMessageIdsRef.current.delete(messageId);
467
+ }
468
+ }
469
+
470
+ scheduleVisibilitySync();
471
+ },
472
+ {
473
+ root: viewport,
474
+ // Shrink the root's top edge to the anchoring line so a previous turn
475
+ // peeking in the scrollMargin + peek band is not reported as visible,
476
+ // keeping visibleMessageIds consistent with currentAnchorId. Captured
477
+ // at observe time; a prop change rebuilds the observer on resubscribe.
478
+ rootMargin: `${-(scrollMarginRef.current + scrollPreviousItemPeekRef.current)}px 0px 0px 0px`,
479
+ threshold: [0, 0.01, 0.5, 1],
480
+ },
481
+ );
482
+ }
483
+
484
+ messageElementsRef.current.forEach((element) => {
485
+ visibilityObserverRef.current?.observe(element);
486
+ });
487
+ scheduleVisibilitySync();
488
+ }, [scheduleVisibilitySync, visibilityStore]);
489
+
490
+ const unobserveVisibility = useCallback(() => {
491
+ if (visibilityFrameRef.current !== null) {
492
+ window.cancelAnimationFrame(visibilityFrameRef.current);
493
+ visibilityFrameRef.current = null;
494
+ }
495
+
496
+ visibilityObserverRef.current?.disconnect();
497
+ visibilityObserverRef.current = null;
498
+ visibleMessageIdsRef.current.clear();
499
+ visibilityStore.setSnapshot(EMPTY_MESSAGE_SCROLLER_VISIBILITY_STATE);
500
+ }, [visibilityStore]);
501
+
502
+ const registerMessage = useCallback<MessageScrollerRegisterMessage>(
503
+ (messageId, element, removedElement) => {
504
+ if (element) {
505
+ messageElementsRef.current.set(messageId, element);
506
+ visibilityObserverRef.current?.observe(element);
507
+ scheduleVisibilitySync();
508
+
509
+ if (pendingScrollToMessageRef.current?.messageId === messageId) {
510
+ schedulePendingScrollToMessageFlush();
511
+ }
512
+
513
+ return;
514
+ }
515
+
516
+ if (removedElement && messageElementsRef.current.get(messageId) === removedElement) {
517
+ messageElementsRef.current.delete(messageId);
518
+ visibleMessageIdsRef.current.delete(messageId);
519
+ visibilityObserverRef.current?.unobserve(removedElement);
520
+ scheduleVisibilitySync();
521
+ }
522
+ },
523
+ [schedulePendingScrollToMessageFlush, scheduleVisibilitySync],
524
+ );
525
+
526
+ const userScrollIntent = useCallback(() => {
527
+ if (
528
+ modeRef.current === "following-bottom" ||
529
+ modeRef.current === "anchored-to-message" ||
530
+ modeRef.current === "settling-jump"
531
+ ) {
532
+ // A deliberate gesture releases auto-follow, turn-anchoring, and an in-flight
533
+ // programmatic jump so re-pinning (and re-arming) never fights the reader.
534
+ streamingTurnRef.current = null;
535
+ modeRef.current = "free-scrolling";
536
+ }
537
+ }, []);
538
+
539
+ const mirrorStateAttributes = useCallback(
540
+ () => writeStateAttributes(stateStore.getSnapshot()),
541
+ [stateStore, writeStateAttributes],
542
+ );
543
+
544
+ const setRootElement = useElementRef(rootRef, mirrorStateAttributes);
545
+ const setViewportElement = useElementRef(viewportRef, mirrorStateAttributes);
546
+
547
+ const setContentElement = useCallback((element: HTMLDivElement | null) => {
548
+ contentRef.current = element;
549
+ }, []);
550
+
551
+ const setSpacerElement = useCallback((element: HTMLDivElement | null) => {
552
+ spacerRef.current = element;
553
+ spacerGapRef.current = getFlexGap(element?.parentElement ?? null);
554
+ }, []);
555
+
556
+ const syncAfterScroll = useCallback(() => {
557
+ commitScrollState();
558
+ scheduleVisibilitySync();
559
+ capturePrependAnchor();
560
+ }, [capturePrependAnchor, commitScrollState, scheduleVisibilitySync]);
561
+
562
+ const context = useMemo<MessageScrollerContextValue>(
563
+ () => ({
564
+ handleContentChange,
565
+ handleResize,
566
+ observeVisibility,
567
+ preserveScrollOnPrependRef,
568
+ scrollToEnd,
569
+ scrollToMessage,
570
+ scrollToStart,
571
+ setContentElement,
572
+ setRootElement,
573
+ setSpacerElement,
574
+ setViewportElement,
575
+ stateStore,
576
+ syncAfterScroll,
577
+ unobserveVisibility,
578
+ userScrollIntent,
579
+ viewportRef,
580
+ visibilityStore,
581
+ }),
582
+ [
583
+ handleContentChange,
584
+ handleResize,
585
+ observeVisibility,
586
+ scrollToEnd,
587
+ scrollToMessage,
588
+ scrollToStart,
589
+ setContentElement,
590
+ setRootElement,
591
+ setSpacerElement,
592
+ setViewportElement,
593
+ stateStore,
594
+ syncAfterScroll,
595
+ unobserveVisibility,
596
+ userScrollIntent,
597
+ visibilityStore,
598
+ ],
599
+ );
600
+
601
+ useLayoutEffect(() => {
602
+ applyDefaultScrollPosition();
603
+ }, [applyDefaultScrollPosition]);
604
+
605
+ useEffect(() => {
606
+ return () => {
607
+ // Reset every ref after cancelling. StrictMode replays effects on the same
608
+ // refs (unmount then remount), so a frame id left non-null here makes the
609
+ // scheduler on remount think a frame is still pending and never reschedule.
610
+ if (stateFrameRef.current !== null) {
611
+ window.cancelAnimationFrame(stateFrameRef.current);
612
+ stateFrameRef.current = null;
613
+ }
614
+
615
+ if (visibilityFrameRef.current !== null) {
616
+ window.cancelAnimationFrame(visibilityFrameRef.current);
617
+ visibilityFrameRef.current = null;
618
+ }
619
+
620
+ if (autoscrollingTimeoutRef.current !== null) {
621
+ window.clearTimeout(autoscrollingTimeoutRef.current);
622
+ autoscrollingTimeoutRef.current = null;
623
+ }
624
+
625
+ if (pendingScrollFrameRef.current !== null) {
626
+ window.cancelAnimationFrame(pendingScrollFrameRef.current);
627
+ pendingScrollFrameRef.current = null;
628
+ }
629
+
630
+ visibilityObserverRef.current?.disconnect();
631
+ visibilityObserverRef.current = null;
632
+ };
633
+ }, []);
634
+
635
+ useLayoutEffect(() => {
636
+ if (autoScroll && modeRef.current === "following-bottom" && itemCountRef.current > 0) {
637
+ scrollToEnd({ behavior: "auto" });
638
+ return;
639
+ }
640
+
641
+ commitScrollState();
642
+ }, [autoScroll, commitScrollState, scrollToEnd]);
643
+
644
+ return {
645
+ context,
646
+ registerMessage,
647
+ };
648
+ }
649
+
650
+ export { useMessageScrollerController };
651
+ export type { MessageScrollerRefs };