From 21dc9c5b2f246622c27fc66decd3222396a809d0 Mon Sep 17 00:00:00 2001 From: 7w1 Date: Wed, 18 Mar 2026 01:09:43 -0500 Subject: [PATCH] pull out scroll logic --- src/app/hooks/useScrollManager.ts | 79 +++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 src/app/hooks/useScrollManager.ts diff --git a/src/app/hooks/useScrollManager.ts b/src/app/hooks/useScrollManager.ts new file mode 100644 index 00000000..0cf0dcb5 --- /dev/null +++ b/src/app/hooks/useScrollManager.ts @@ -0,0 +1,79 @@ +import { useCallback, useRef, useState, useLayoutEffect } from 'react'; +import { scrollToBottom as domScrollToBottom, getScrollInfo } from '$utils/dom'; + +type ScrollBehavior = 'auto' | 'instant' | 'smooth'; + +export const useScrollManager = (scrollRef: React.RefObject) => { + const [isAtBottom, setIsAtBottom] = useState(true); + const isAtBottomRef = useRef(true); + const autoScrollRef = useRef(false); + + const checkAtBottom = useCallback(() => { + const el = scrollRef.current; + if (!el) return; + + const { top, height, viewHeight } = getScrollInfo(el); + const distanceToBottom = height - top - viewHeight; + + const atBottom = distanceToBottom <= 5; + + if (atBottom !== isAtBottomRef.current) { + isAtBottomRef.current = atBottom; + setIsAtBottom(atBottom); + } + }, [scrollRef]); + + const scrollToBottom = useCallback( + (behavior: ScrollBehavior = 'instant') => { + const el = scrollRef.current; + if (el) { + autoScrollRef.current = true; + domScrollToBottom(el, behavior); + + if (behavior === 'instant') { + setTimeout(() => { + if (scrollRef.current) domScrollToBottom(scrollRef.current, 'instant'); + }, 50); + } + } + }, + [scrollRef] + ); + + const onScroll = useCallback(() => { + if (autoScrollRef.current) { + autoScrollRef.current = false; + return; + } + checkAtBottom(); + }, [checkAtBottom]); + + useLayoutEffect(() => { + const el = scrollRef.current; + + if (!el) { + return undefined; + } + + const resizeObserver = new ResizeObserver(() => { + if (isAtBottomRef.current) { + scrollToBottom('instant'); + } + }); + + if (el.firstElementChild) { + resizeObserver.observe(el.firstElementChild); + } + + return () => { + resizeObserver.disconnect(); + }; + }, [scrollRef, scrollToBottom]); + + return { + isAtBottom, + onScroll, + scrollToBottom, + checkAtBottom, + }; +};