// dashboard/src/components/agent/useAutoScroll.ts // 共享自动滚动 hook:检测是否贴底,仅在贴底时自动滚动 import { useState, useRef, useEffect, useCallback } from 'react'; interface UseAutoScrollReturn { chatEndRef: React.RefObject; scrollContainerRef: React.RefObject; shouldAutoScroll: boolean; setShouldAutoScroll: (v: boolean) => void; scrollToBottom: (behavior?: ScrollBehavior) => void; handleScroll: () => void; } export function useAutoScroll(deps: React.DependencyList): UseAutoScrollReturn { const chatEndRef = useRef(null); const scrollContainerRef = useRef(null); const [shouldAutoScroll, setShouldAutoScroll] = useState(true); const scrollToBottom = useCallback((behavior: ScrollBehavior = 'smooth') => { const el = scrollContainerRef.current; if (el) { el.scrollTo({ top: el.scrollHeight, behavior, }); } }, []); useEffect(() => { if (shouldAutoScroll) { scrollToBottom(); } // eslint-disable-next-line react-hooks/exhaustive-deps }, deps); const handleScroll = useCallback(() => { const el = scrollContainerRef.current; if (!el) return; const { scrollTop, scrollHeight, clientHeight } = el; setShouldAutoScroll(scrollHeight - scrollTop - clientHeight < 50); }, []); return { chatEndRef, scrollContainerRef, shouldAutoScroll, setShouldAutoScroll, scrollToBottom, handleScroll, }; }