| 1 | import { useEffect, useRef, type RefObject } from "react"; |
| 2 | |
| 3 | export function useScrollToBottom<T extends HTMLElement>(): [ |
| 4 | RefObject<T>, |
| 5 | RefObject<T>, |
| 6 | ] { |
| 7 | const containerRef = useRef<T>(null); |
| 8 | const endRef = useRef<T>(null); |
| 9 | |
| 10 | useEffect(() => { |
| 11 | const container = containerRef.current; |
| 12 | const end = endRef.current; |
| 13 | |
| 14 | if (container && end) { |
| 15 | const observer = new MutationObserver(() => { |
| 16 | end.scrollIntoView({ behavior: "instant", block: "end" }); |
| 17 | }); |
| 18 | |
| 19 | observer.observe(container, { |
| 20 | childList: true, |
| 21 | subtree: true, |
| 22 | attributes: true, |
| 23 | characterData: true, |
| 24 | }); |
| 25 | |
| 26 | return () => observer.disconnect(); |
| 27 | } |
| 28 | }, []); |
| 29 | |
| 30 | return [containerRef as RefObject<T>, endRef as RefObject<T>]; |
| 31 | } |