/** * Keeps a scrolling chat list at its newest (bottom) line. It reacts to what is actually in the list (a DOM * observer), not to a message count: the room chat keeps only the last 100 lines, so once full the count stopped * changing and the list stopped following new messages. If the reader scrolls up to read older lines it stays put * until they come back near the bottom (or `pin()` is called, e.g. after sending a message). */ import { useCallback, useLayoutEffect, useRef } from 'react'; const NEAR_PX = 48; export function useStickToBottom() { const ref = useRef(null); const pinned = useRef(true); const toBottom = useCallback(() => { const el = ref.current; if (el) el.scrollTop = el.scrollHeight; }, []); useLayoutEffect(() => { const el = ref.current; if (!el) return; pinned.current = true; toBottom(); const onScroll = () => { pinned.current = el.scrollHeight - el.scrollTop - el.clientHeight <= NEAR_PX; }; const stick = () => { if (pinned.current) toBottom(); }; el.addEventListener('scroll', onScroll, { passive: true }); const mo = new MutationObserver(stick); mo.observe(el, { childList: true, subtree: true, characterData: true }); // The list itself changing size (sheet opening, phone rotating, the input row growing) keeps the bottom too. const ro = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(stick); ro?.observe(el); return () => { el.removeEventListener('scroll', onScroll); mo.disconnect(); ro?.disconnect(); }; }, [toBottom]); const pin = useCallback(() => { pinned.current = true; toBottom(); }, [toBottom]); return { ref, pin }; }