|
| 1 | +import { useRef, useEffect, useState, useCallback } from 'react'; |
| 2 | + |
| 3 | +interface UseAutoScrollOptions { |
| 4 | + threshold?: number; // Distance from bottom to consider "at bottom" |
| 5 | + debounceMs?: number; // Debounce time for user interaction detection |
| 6 | + autoScrollDelay?: number; // Delay before auto-scrolling after user stops interacting |
| 7 | + dependencies?: any[]; // Dependencies to trigger auto-scroll (e.g., messages) |
| 8 | +} |
| 9 | + |
| 10 | +interface UseAutoScrollReturn { |
| 11 | + messagesContainerRef: React.RefObject<HTMLDivElement>; |
| 12 | + messagesEndRef: React.RefObject<HTMLDivElement>; |
| 13 | + showScrollToBottom: boolean; |
| 14 | + scrollToBottom: () => void; |
| 15 | + isUserScrolling: boolean; |
| 16 | +} |
| 17 | + |
| 18 | +/** |
| 19 | + * Custom hook for managing intelligent auto-scroll behavior in chat |
| 20 | + * |
| 21 | + * Features: |
| 22 | + * - Auto-scrolls to bottom when new content appears |
| 23 | + * - Detects user manual scrolling and respects it |
| 24 | + * - Shows scroll-to-bottom indicator when user has scrolled up |
| 25 | + * - Automatically resumes auto-scroll after user inactivity |
| 26 | + */ |
| 27 | +export const useAutoScroll = ({ |
| 28 | + threshold = 100, |
| 29 | + debounceMs = 1000, |
| 30 | + autoScrollDelay = 2000, |
| 31 | + dependencies = [], |
| 32 | +}: UseAutoScrollOptions = {}): UseAutoScrollReturn => { |
| 33 | + const messagesContainerRef = useRef<HTMLDivElement>(null); |
| 34 | + const messagesEndRef = useRef<HTMLDivElement>(null); |
| 35 | + const [showScrollToBottom, setShowScrollToBottom] = useState(false); |
| 36 | + const [isUserScrolling, setIsUserScrolling] = useState(false); |
| 37 | + const [isAtBottom, setIsAtBottom] = useState(true); |
| 38 | + |
| 39 | + const userInteractionTimeoutRef = useRef<NodeJS.Timeout | null>(null); |
| 40 | + const lastScrollTopRef = useRef<number>(0); |
| 41 | + const isAutoScrollingRef = useRef(false); |
| 42 | + |
| 43 | + // Check if container is at bottom |
| 44 | + const checkIsAtBottom = useCallback(() => { |
| 45 | + const container = messagesContainerRef.current; |
| 46 | + if (!container) return false; |
| 47 | + |
| 48 | + const { scrollTop, scrollHeight, clientHeight } = container; |
| 49 | + return scrollHeight - scrollTop - clientHeight <= threshold; |
| 50 | + }, [threshold]); |
| 51 | + |
| 52 | + // Smooth scroll to bottom |
| 53 | + const scrollToBottom = useCallback(() => { |
| 54 | + const container = messagesContainerRef.current; |
| 55 | + if (!container) return; |
| 56 | + |
| 57 | + isAutoScrollingRef.current = true; |
| 58 | + container.scrollTo({ |
| 59 | + top: container.scrollHeight, |
| 60 | + behavior: 'smooth' |
| 61 | + }); |
| 62 | + |
| 63 | + // Reset auto-scrolling flag after animation |
| 64 | + setTimeout(() => { |
| 65 | + isAutoScrollingRef.current = false; |
| 66 | + }, 500); |
| 67 | + }, []); |
| 68 | + |
| 69 | + // Handle scroll events |
| 70 | + const handleScroll = useCallback(() => { |
| 71 | + const container = messagesContainerRef.current; |
| 72 | + if (!container || isAutoScrollingRef.current) return; |
| 73 | + |
| 74 | + const currentScrollTop = container.scrollTop; |
| 75 | + const atBottom = checkIsAtBottom(); |
| 76 | + |
| 77 | + setIsAtBottom(atBottom); |
| 78 | + setShowScrollToBottom(!atBottom); |
| 79 | + |
| 80 | + // Detect user scrolling (not programmatic) |
| 81 | + const isUserInitiated = Math.abs(currentScrollTop - lastScrollTopRef.current) > 1; |
| 82 | + |
| 83 | + if (isUserInitiated) { |
| 84 | + setIsUserScrolling(true); |
| 85 | + |
| 86 | + // Clear existing timeout |
| 87 | + if (userInteractionTimeoutRef.current) { |
| 88 | + clearTimeout(userInteractionTimeoutRef.current); |
| 89 | + } |
| 90 | + |
| 91 | + // Set timeout to resume auto-scroll after inactivity |
| 92 | + userInteractionTimeoutRef.current = setTimeout(() => { |
| 93 | + setIsUserScrolling(false); |
| 94 | + // If still at bottom after timeout, hide the indicator |
| 95 | + if (checkIsAtBottom()) { |
| 96 | + setShowScrollToBottom(false); |
| 97 | + } |
| 98 | + }, autoScrollDelay); |
| 99 | + } |
| 100 | + |
| 101 | + lastScrollTopRef.current = currentScrollTop; |
| 102 | + }, [checkIsAtBottom, autoScrollDelay]); |
| 103 | + |
| 104 | + // Immediate scroll handler for real-time updates |
| 105 | + useEffect(() => { |
| 106 | + const container = messagesContainerRef.current; |
| 107 | + if (!container) return; |
| 108 | + |
| 109 | + let scrollTimeout: NodeJS.Timeout; |
| 110 | + |
| 111 | + const immediateHandleScroll = () => { |
| 112 | + handleScroll(); |
| 113 | + }; |
| 114 | + |
| 115 | + const debouncedHandleScroll = () => { |
| 116 | + clearTimeout(scrollTimeout); |
| 117 | + scrollTimeout = setTimeout(handleScroll, debounceMs); |
| 118 | + }; |
| 119 | + |
| 120 | + // Use immediate handler for better responsiveness |
| 121 | + container.addEventListener('scroll', immediateHandleScroll, { passive: true }); |
| 122 | + |
| 123 | + return () => { |
| 124 | + container.removeEventListener('scroll', immediateHandleScroll); |
| 125 | + clearTimeout(scrollTimeout); |
| 126 | + }; |
| 127 | + }, [handleScroll, debounceMs]); |
| 128 | + |
| 129 | + // Auto-scroll to bottom when new content appears (if user hasn't scrolled up) |
| 130 | + useEffect(() => { |
| 131 | + if (!isUserScrolling && isAtBottom) { |
| 132 | + // Use requestAnimationFrame to ensure DOM has updated |
| 133 | + requestAnimationFrame(() => { |
| 134 | + scrollToBottom(); |
| 135 | + }); |
| 136 | + } |
| 137 | + }, [isUserScrolling, isAtBottom, scrollToBottom, ...dependencies]); |
| 138 | + |
| 139 | + // Initial scroll to bottom when component mounts |
| 140 | + useEffect(() => { |
| 141 | + const timer = setTimeout(() => { |
| 142 | + scrollToBottom(); |
| 143 | + }, 100); |
| 144 | + |
| 145 | + return () => clearTimeout(timer); |
| 146 | + }, []); |
| 147 | + |
| 148 | + // Cleanup timeouts on unmount |
| 149 | + useEffect(() => { |
| 150 | + return () => { |
| 151 | + if (userInteractionTimeoutRef.current) { |
| 152 | + clearTimeout(userInteractionTimeoutRef.current); |
| 153 | + } |
| 154 | + }; |
| 155 | + }, []); |
| 156 | + |
| 157 | + return { |
| 158 | + messagesContainerRef, |
| 159 | + messagesEndRef, |
| 160 | + showScrollToBottom, |
| 161 | + scrollToBottom, |
| 162 | + isUserScrolling, |
| 163 | + }; |
| 164 | +}; |
0 commit comments