2024-09-08 11:53:15 +05:30
|
|
|
import { useRef, useEffect, useState } from "react"
|
2024-07-14 23:13:48 +05:30
|
|
|
|
|
|
|
|
export const useSmartScroll = (messages: any[], streaming: boolean) => {
|
2024-09-08 11:53:15 +05:30
|
|
|
const containerRef = useRef<HTMLDivElement>(null)
|
|
|
|
|
const [isAtBottom, setIsAtBottom] = useState(true)
|
2024-07-14 23:13:48 +05:30
|
|
|
|
|
|
|
|
useEffect(() => {
|
2024-09-08 11:53:15 +05:30
|
|
|
const container = containerRef.current
|
|
|
|
|
if (!container) return
|
2024-07-14 23:13:48 +05:30
|
|
|
|
|
|
|
|
const handleScroll = () => {
|
2024-09-08 11:53:15 +05:30
|
|
|
const { scrollTop, scrollHeight, clientHeight } = container
|
|
|
|
|
setIsAtBottom(scrollHeight - scrollTop - clientHeight < 50)
|
|
|
|
|
}
|
2024-07-14 23:13:48 +05:30
|
|
|
|
2024-09-08 11:53:15 +05:30
|
|
|
container.addEventListener("scroll", handleScroll)
|
|
|
|
|
return () => container.removeEventListener("scroll", handleScroll)
|
|
|
|
|
}, [])
|
2024-07-14 23:13:48 +05:30
|
|
|
|
|
|
|
|
useEffect(() => {
|
2024-09-08 11:53:15 +05:30
|
|
|
if (messages.length === 0) {
|
|
|
|
|
setIsAtBottom(true)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2024-07-14 23:13:48 +05:30
|
|
|
if (isAtBottom && containerRef.current) {
|
|
|
|
|
const scrollOptions: ScrollIntoViewOptions = streaming
|
2024-09-08 11:53:15 +05:30
|
|
|
? { behavior: "smooth", block: "end" }
|
|
|
|
|
: { behavior: "auto", block: "end" }
|
|
|
|
|
containerRef.current.lastElementChild?.scrollIntoView(scrollOptions)
|
2024-07-14 23:13:48 +05:30
|
|
|
}
|
2024-09-08 11:53:15 +05:30
|
|
|
}, [messages, streaming, isAtBottom])
|
2024-07-14 23:13:48 +05:30
|
|
|
|
|
|
|
|
const scrollToBottom = () => {
|
2024-09-08 11:53:15 +05:30
|
|
|
containerRef.current?.lastElementChild?.scrollIntoView({
|
|
|
|
|
behavior: "smooth",
|
|
|
|
|
block: "end"
|
|
|
|
|
})
|
|
|
|
|
}
|
2024-07-14 23:13:48 +05:30
|
|
|
|
2024-09-08 11:53:15 +05:30
|
|
|
return { containerRef, isAtBottom, scrollToBottom }
|
|
|
|
|
}
|