import { useCallback, useEffect, useRef, useState, type DependencyList, type RefObject } from "react"; /** * Auto-scroll a scrollable container while the user is at (or near) the * bottom; stop following as soon as the user scrolls up, and resume when * the user clicks the floating "回到底部" button (which calls `scrollToBottom`). * * Why a custom hook: the page has two streamed-message lists (Step 1 chat, * Step 2 roundtable) with identical scroll-follow semantics, and reading * `scrollHeight` after every state change inside the component would mean * duplicating the scroll listener / auto-scroll / pause logic per list. */ export function useAutoScroll( ref: RefObject, deps: DependencyList, options: { /** How close to the bottom (px) still counts as "at bottom". */ threshold?: number; } = {}, ): { /** True when the user is at the bottom — drives the button's visibility. */ atBottom: boolean; /** Force-scroll to the bottom and resume auto-follow. */ scrollToBottom: () => void; } { const threshold = options.threshold ?? 32; // Ref mirrors state so the deps-effect can read the latest value without // re-subscribing when atBottom flips. State is for the button's render. const atBottomRef = useRef(true); const [atBottom, setAtBottom] = useState(true); // 自动跟随的"门"。区分**程序触发**和**用户触发**的滚动: // - 程序滚动(`el.scrollTop = el.scrollHeight`)前会临时把 programmaticRef 置 true // → 接下来一次 scroll 事件不修改 atBottom,避免自己把自己关掉。 // - 任何其它 scroll 事件视为用户主动滚动,按位置判定 atBottom。 // 这是修「鼠标拖滚动条没出现按钮」的关键:之前依赖 wheel/touchmove, // 但鼠标拖滚动条**只触发 scroll 事件**,wheel/touchmove 完全不会触发。 const programmaticScrollRef = useRef(false); // 自动跟随 effect 和 onScroll 共享的"上次观察到的 scrollTop"。 // 用来在 effect 里区分两种 distance 暴涨的情况: // - currentScrollTop < lastObservedScrollTopRef → 用户主动向上滚 → 退出跟随 // - currentScrollTop 不变,但 scrollHeight 暴涨(如澄清卡片渲染) → 继续跟随 const lastObservedScrollTopRef = useRef(0); useEffect(() => { const el = ref.current; if (!el) return; let prevScrollTop = el.scrollTop; lastObservedScrollTopRef.current = prevScrollTop; const onScroll = () => { const currentScrollTop = el.scrollTop; const distanceFromBottom = el.scrollHeight - currentScrollTop - el.clientHeight; const isAtBottom = distanceFromBottom <= threshold; if (programmaticScrollRef.current) { // 这是我们刚 scrollTop=scrollHeight 触发的回调,跳过,但仍刷新 prev 用于下次比较。 programmaticScrollRef.current = false; prevScrollTop = currentScrollTop; lastObservedScrollTopRef.current = currentScrollTop; // 程序滚动后通常落在底部,把 atBottom 维持 true。 if (!atBottomRef.current && isAtBottom) { atBottomRef.current = true; setAtBottom(true); } return; } // 用户主动滚动:**任何向上滚的 scrollTop 减少都立刻退出自动跟随**, // 不等位置算到底部 32px 之外才翻。这是按钮"滚动一点点就显示"的核心。 if (currentScrollTop < prevScrollTop && atBottomRef.current) { atBottomRef.current = false; setAtBottom(false); } else if (isAtBottom && !atBottomRef.current) { // 用户自己又滚回底部 → 恢复自动跟随 atBottomRef.current = true; setAtBottom(true); } // **不再**因为「scrollTop 没明显减少但 distance > threshold」就退出自动跟随。 // 这种情况只可能由内容突然增长触发(如澄清卡片一帧渲染 200+ px), // 此时用户并没有滚走,应当继续跟随,由下面的 effect 把视口拉到新底部。 prevScrollTop = currentScrollTop; lastObservedScrollTopRef.current = currentScrollTop; }; el.addEventListener("scroll", onScroll, { passive: true }); // 初次测量 onScroll(); return () => { el.removeEventListener("scroll", onScroll); }; }, [ref, threshold]); // 自动跟随 effect。用 instant 同步赋值,避免 smooth 动画与用户拖动叠加打架。 // 关键:区分「用户向上滚」(scrollTop 变小) 与「内容增长」(scrollTop 不变、 // scrollHeight 变大)。仅前者算作用户离开,后者继续自动跟随 —— // 否则像澄清卡片这种一帧渲染 200+ px 的场景会被误判成"用户滚走了"。 useEffect(() => { const el = ref.current; if (!el) return; const currentScrollTop = el.scrollTop; const distanceFromBottom = el.scrollHeight - currentScrollTop - el.clientHeight; // 1px 容忍滚动条像素抖动 / 浏览器自身的次像素回弹。 const userScrolledUp = currentScrollTop < lastObservedScrollTopRef.current - 1; if (userScrolledUp && distanceFromBottom > threshold) { // 用户主动向上滚 → 退出自动跟随 (兜底 ref 滞后于刚刚的拖动事件)。 if (atBottomRef.current) { atBottomRef.current = false; setAtBottom(false); } lastObservedScrollTopRef.current = currentScrollTop; return; } if (!atBottomRef.current) { // 之前已退出自动跟随,不要因为内容增长又把用户拽回去。 lastObservedScrollTopRef.current = currentScrollTop; return; } // 在底部 (或仅是内容刚增长) → 同步拉到新底部。 programmaticScrollRef.current = true; el.scrollTop = el.scrollHeight; lastObservedScrollTopRef.current = el.scrollTop; // eslint-disable-next-line react-hooks/exhaustive-deps }, deps); // 按钮点击是用户主动行为,保留 smooth 给视觉反馈;期间用户若立刻又拖动, // onScroll 的方向检测仍会把 atBottom 翻回 false,不会卡住。 const scrollToBottom = useCallback(() => { const el = ref.current; if (!el) return; // 标记程序滚动:smooth 动画过程中浏览器派发的 scroll 事件不应被误判为用户主动滚动。 programmaticScrollRef.current = true; el.scrollTo({ top: el.scrollHeight, behavior: "smooth" }); atBottomRef.current = true; setAtBottom(true); }, [ref]); return { atBottom, scrollToBottom }; }