( scrollRef: React.RefObject<ScrollBoxRenderable | null>, messages: any[], isUserCollapsing: () => boolean, )
| 29 | * @returns Scroll management functions and state |
| 30 | */ |
| 31 | export const useChatScrollbox = ( |
| 32 | scrollRef: React.RefObject<ScrollBoxRenderable | null>, |
| 33 | messages: any[], |
| 34 | isUserCollapsing: () => boolean, |
| 35 | ) => { |
| 36 | const autoScrollEnabledRef = useRef<boolean>(true) |
| 37 | const programmaticScrollRef = useRef<boolean>(false) |
| 38 | const animationFrameRef = useRef<number | null>(null) |
| 39 | const [isAtBottom, setIsAtBottom] = useState<boolean>(true) |
| 40 | |
| 41 | const cancelAnimation = useCallback(() => { |
| 42 | if (animationFrameRef.current !== null) { |
| 43 | clearTimeout(animationFrameRef.current) |
| 44 | animationFrameRef.current = null |
| 45 | } |
| 46 | }, []) |
| 47 | |
| 48 | const animateScrollTo = useCallback( |
| 49 | (targetScroll: number, duration = DEFAULT_SCROLL_ANIMATION_DURATION_MS) => { |
| 50 | const scrollbox = scrollRef.current |
| 51 | if (!scrollbox) return |
| 52 | |
| 53 | cancelAnimation() |
| 54 | |
| 55 | const startScroll = scrollbox.scrollTop |
| 56 | const distance = targetScroll - startScroll |
| 57 | const startTime = Date.now() |
| 58 | const frameInterval = ANIMATION_FRAME_INTERVAL_MS |
| 59 | |
| 60 | const animate = () => { |
| 61 | const elapsed = Date.now() - startTime |
| 62 | const progress = Math.min(elapsed / duration, 1) |
| 63 | const easedProgress = easeOutCubic(progress) |
| 64 | const newScroll = startScroll + distance * easedProgress |
| 65 | |
| 66 | programmaticScrollRef.current = true |
| 67 | scrollbox.scrollTop = newScroll |
| 68 | |
| 69 | if (progress < 1) { |
| 70 | animationFrameRef.current = setTimeout(animate, frameInterval) as any |
| 71 | } else { |
| 72 | animationFrameRef.current = null |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | animate() |
| 77 | }, |
| 78 | [scrollRef, cancelAnimation], |
| 79 | ) |
| 80 | |
| 81 | const scrollToLatest = useCallback((): void => { |
| 82 | const scrollbox = scrollRef.current |
| 83 | if (!scrollbox) return |
| 84 | |
| 85 | const maxScroll = Math.max( |
| 86 | 0, |
| 87 | scrollbox.scrollHeight - scrollbox.viewport.height, |
| 88 | ) |
no test coverage detected