Files
page-assist/src/hooks/useSmartScroll.tsx

42 lines
1.2 KiB
TypeScript
Raw Normal View History

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