| 1 | import { useEffect, useMemo, useState } from "react"; |
| 2 | import { ChatHistoryItemWithMessageId } from "../../redux/slices/sessionSlice"; |
| 3 | |
| 4 | /** |
| 5 | * Only reset scroll state when a new user message is added to the chat. |
| 6 | * We don't want to auto-scroll on new tool response messages. |
| 7 | */ |
| 8 | function getNumUserMsgs(history: ChatHistoryItemWithMessageId[]) { |
| 9 | return history.filter((msg) => msg.message.role === "user").length; |
| 10 | } |
| 11 | |
| 12 | export const useAutoScroll = ( |
| 13 | ref: React.RefObject<HTMLDivElement>, |
| 14 | history: ChatHistoryItemWithMessageId[], |
| 15 | ) => { |
| 16 | const [userHasScrolled, setUserHasScrolled] = useState(false); |
| 17 | const numUserMsgs = useMemo(() => getNumUserMsgs(history), [history.length]); |
| 18 | |
| 19 | useEffect(() => { |
| 20 | setUserHasScrolled(false); |
| 21 | }, [numUserMsgs]); |
| 22 | |
| 23 | useEffect(() => { |
| 24 | if (!ref.current || history.length === 0) return; |
| 25 | |
| 26 | const handleScroll = () => { |
| 27 | const elem = ref.current; |
| 28 | if (!elem) return; |
| 29 | |
| 30 | const isAtBottom = |
| 31 | Math.abs(elem.scrollHeight - elem.scrollTop - elem.clientHeight) < 1; |
| 32 | |
| 33 | /** |
| 34 | * We stop auto scrolling if a user manually scrolled up. |
| 35 | * We resume auto scrolling if a user manually scrolled to the bottom. |
| 36 | */ |
| 37 | setUserHasScrolled(!isAtBottom); |
| 38 | }; |
| 39 | |
| 40 | const resizeObserver = new ResizeObserver(() => { |
| 41 | const elem = ref.current; |
| 42 | if (!elem || userHasScrolled) return; |
| 43 | elem.scrollTop = elem.scrollHeight; |
| 44 | }); |
| 45 | |
| 46 | ref.current.addEventListener("scroll", handleScroll); |
| 47 | |
| 48 | // Observe the container |
| 49 | resizeObserver.observe(ref.current); |
| 50 | |
| 51 | // Observe all immediate children |
| 52 | Array.from(ref.current.children).forEach((child) => { |
| 53 | resizeObserver.observe(child); |
| 54 | }); |
| 55 | |
| 56 | return () => { |
| 57 | resizeObserver.disconnect(); |
| 58 | ref.current?.removeEventListener("scroll", handleScroll); |
| 59 | }; |
| 60 | }, [ref, history.length, userHasScrolled]); |
| 61 | }; |