chatbot-template/lib/hooks/use-follow-scroll.ts

44 lines
1,017 B
TypeScript
Raw Normal View History

2023-06-02 15:33:48 -04:00
import { useEffect, useRef } from 'react'
2023-05-19 12:33:56 -04:00
const scrollToEnd = () => {
window.scrollTo({
top: document.body.scrollHeight,
2023-06-02 15:33:48 -04:00
left: 0
})
}
2023-05-19 12:33:56 -04:00
export function useFollowScroll(shouldFollow: boolean) {
2023-06-02 15:33:48 -04:00
const shouldFollowRef = useRef(shouldFollow)
const scrollRef = useRef(false)
const triggeredBySelfRef = useRef(false)
2023-05-19 12:33:56 -04:00
useEffect(() => {
const handleScroll = () => {
if (triggeredBySelfRef.current) {
2023-06-02 15:33:48 -04:00
triggeredBySelfRef.current = false
return
2023-05-19 12:33:56 -04:00
}
2023-06-02 15:33:48 -04:00
scrollRef.current = true
}
window.addEventListener('scroll', handleScroll)
return () => window.removeEventListener('scroll', handleScroll)
}, [])
2023-05-19 12:33:56 -04:00
useEffect(() => {
if (!scrollRef.current && shouldFollowRef.current) {
setTimeout(() => {
2023-06-02 15:33:48 -04:00
triggeredBySelfRef.current = true
scrollToEnd()
})
2023-05-19 12:33:56 -04:00
}
2023-06-02 15:33:48 -04:00
})
2023-05-19 12:33:56 -04:00
useEffect(() => {
2023-06-02 15:33:48 -04:00
shouldFollowRef.current = shouldFollow
2023-05-19 12:33:56 -04:00
if (!shouldFollow) {
// Reset scrollRef
2023-06-02 15:33:48 -04:00
scrollRef.current = false
2023-05-19 12:33:56 -04:00
}
2023-06-02 15:33:48 -04:00
}, [shouldFollow])
2023-05-19 12:33:56 -04:00
}