| 1 | import { useRef, useCallback } from 'react'; |
| 2 | |
| 3 | export function useSnapScroll() { |
| 4 | const autoScrollRef = useRef(true); |
| 5 | const scrollNodeRef = useRef<HTMLDivElement>(); |
| 6 | const onScrollRef = useRef<() => void>(); |
| 7 | const observerRef = useRef<ResizeObserver>(); |
| 8 | |
| 9 | const messageRef = useCallback((node: HTMLDivElement | null) => { |
| 10 | if (node) { |
| 11 | const observer = new ResizeObserver(() => { |
| 12 | if (autoScrollRef.current && scrollNodeRef.current) { |
| 13 | const { scrollHeight, clientHeight } = scrollNodeRef.current; |
| 14 | const scrollTarget = scrollHeight - clientHeight; |
| 15 | |
| 16 | scrollNodeRef.current.scrollTo({ |
| 17 | top: scrollTarget, |
| 18 | }); |
| 19 | } |
| 20 | }); |
| 21 | |
| 22 | observer.observe(node); |
| 23 | } else { |
| 24 | observerRef.current?.disconnect(); |
| 25 | observerRef.current = undefined; |
| 26 | } |
| 27 | }, []); |
| 28 | |
| 29 | const scrollRef = useCallback((node: HTMLDivElement | null) => { |
| 30 | if (node) { |
| 31 | onScrollRef.current = () => { |
| 32 | const { scrollTop, scrollHeight, clientHeight } = node; |
| 33 | const scrollTarget = scrollHeight - clientHeight; |
| 34 | |
| 35 | autoScrollRef.current = Math.abs(scrollTop - scrollTarget) <= 10; |
| 36 | }; |
| 37 | |
| 38 | node.addEventListener('scroll', onScrollRef.current); |
| 39 | |
| 40 | scrollNodeRef.current = node; |
| 41 | } else { |
| 42 | if (onScrollRef.current) { |
| 43 | scrollNodeRef.current?.removeEventListener('scroll', onScrollRef.current); |
| 44 | } |
| 45 | |
| 46 | scrollNodeRef.current = undefined; |
| 47 | onScrollRef.current = undefined; |
| 48 | } |
| 49 | }, []); |
| 50 | |
| 51 | return [messageRef, scrollRef]; |
| 52 | } |