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; /** * Optional inner content element. Streamed Markdown, clarification cards * and expandable tool steps can change height without replacing the outer * message array; observing this node keeps bottom-following reliable. */ contentRef?: RefObject; } = {}, ): { /** 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; /** Immediately jump to the bottom and resume auto-follow (for phase transitions). */ forceScrollToBottom: () => void; } { const threshold = options.threshold ?? 32; const contentRef = options.contentRef; // 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 完全不会触发。 // Keep the expected destination rather than a boolean. Setting scrollTop to // its current value emits no event; a boolean would remain set and swallow // the user's next real upward scroll. const programmaticScrollTargetRef = useRef(null); // 自动跟随 effect 和 onScroll 共享的"上次观察到的 scrollTop"。 // 用来在 effect 里区分两种 distance 暴涨的情况: // - currentScrollTop < lastObservedScrollTopRef → 用户主动向上滚 → 退出跟随 // - currentScrollTop 不变,但 scrollHeight 暴涨(如澄清卡片渲染) → 继续跟随 const lastObservedScrollTopRef = useRef(0); // 思考块 / Markdown 代码块完成重排时,浏览器可能在没有用户输入的情况下 // clamp scrollTop。记录高度后可把这种布局变化与真实向上滚动区分开。 const lastObservedScrollHeightRef = useRef(0); useEffect(() => { const el = ref.current; if (!el) return; let prevScrollTop = el.scrollTop; lastObservedScrollTopRef.current = prevScrollTop; lastObservedScrollHeightRef.current = el.scrollHeight; const onScroll = () => { const currentScrollTop = el.scrollTop; const currentScrollHeight = el.scrollHeight; const distanceFromBottom = el.scrollHeight - currentScrollTop - el.clientHeight; const isAtBottom = distanceFromBottom <= threshold; const layoutChanged = currentScrollHeight !== lastObservedScrollHeightRef.current; const programmaticTarget = programmaticScrollTargetRef.current; if ( programmaticTarget !== null && Math.abs(currentScrollTop - programmaticTarget) <= 1 ) { // 这是我们刚 scrollTop=scrollHeight 触发的回调,跳过,但仍刷新 prev 用于下次比较。 programmaticScrollTargetRef.current = null; prevScrollTop = currentScrollTop; lastObservedScrollTopRef.current = currentScrollTop; lastObservedScrollHeightRef.current = currentScrollHeight; // 程序滚动后通常落在底部,把 atBottom 维持 true。 if (!atBottomRef.current && isAtBottom) { atBottomRef.current = true; setAtBottom(true); } return; } if (programmaticTarget !== null) { programmaticScrollTargetRef.current = null; } // 用户主动滚动:**任何向上滚的 scrollTop 减少都立刻退出自动跟随**, // 不等位置算到底部 32px 之外才翻。这是按钮"滚动一点点就显示"的核心。 if (currentScrollTop < prevScrollTop && atBottomRef.current && !layoutChanged) { 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; lastObservedScrollHeightRef.current = currentScrollHeight; }; 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 currentScrollHeight = el.scrollHeight; const distanceFromBottom = el.scrollHeight - currentScrollTop - el.clientHeight; // 1px 容忍滚动条像素抖动 / 浏览器自身的次像素回弹。 const userScrolledUp = currentScrollTop < lastObservedScrollTopRef.current - 1; const layoutChanged = currentScrollHeight !== lastObservedScrollHeightRef.current; if (userScrolledUp && !layoutChanged && distanceFromBottom > threshold) { // 用户主动向上滚 → 退出自动跟随 (兜底 ref 滞后于刚刚的拖动事件)。 if (atBottomRef.current) { atBottomRef.current = false; setAtBottom(false); } lastObservedScrollTopRef.current = currentScrollTop; lastObservedScrollHeightRef.current = currentScrollHeight; return; } if (!atBottomRef.current) { // 之前已退出自动跟随,不要因为内容增长又把用户拽回去。 lastObservedScrollTopRef.current = currentScrollTop; lastObservedScrollHeightRef.current = currentScrollHeight; return; } // 在底部 (或仅是内容刚增长) → 同步拉到新底部。 programmaticScrollTargetRef.current = Math.max( 0, el.scrollHeight - el.clientHeight, ); el.scrollTop = el.scrollHeight; lastObservedScrollTopRef.current = el.scrollTop; lastObservedScrollHeightRef.current = el.scrollHeight; // eslint-disable-next-line react-hooks/exhaustive-deps }, deps); // Some message UI grows after the React state update that triggered the // dependency effect (Markdown layout, clarification cards, collapsed step // details). Follow the actual content height as well, but only while the // user has not intentionally scrolled upward. useEffect(() => { const el = ref.current; const content = contentRef?.current; if (!el || !content || typeof ResizeObserver === "undefined") return; let frameId: number | null = null; const observer = new ResizeObserver(() => { if (!atBottomRef.current) return; if (frameId !== null) window.cancelAnimationFrame(frameId); frameId = window.requestAnimationFrame(() => { frameId = null; if (!atBottomRef.current) return; programmaticScrollTargetRef.current = Math.max( 0, el.scrollHeight - el.clientHeight, ); el.scrollTop = el.scrollHeight; lastObservedScrollTopRef.current = el.scrollTop; lastObservedScrollHeightRef.current = el.scrollHeight; }); }); observer.observe(content); return () => { observer.disconnect(); if (frameId !== null) window.cancelAnimationFrame(frameId); }; }, [contentRef, ref]); // 按钮点击是用户主动行为,保留 smooth 给视觉反馈;期间用户若立刻又拖动, // onScroll 的方向检测仍会把 atBottom 翻回 false,不会卡住。 const scrollToBottom = useCallback(() => { const el = ref.current; if (!el) return; // 标记程序滚动:smooth 动画过程中浏览器派发的 scroll 事件不应被误判为用户主动滚动。 programmaticScrollTargetRef.current = Math.max( 0, el.scrollHeight - el.clientHeight, ); el.scrollTo({ top: el.scrollHeight, behavior: "smooth" }); lastObservedScrollHeightRef.current = el.scrollHeight; atBottomRef.current = true; setAtBottom(true); }, [ref]); // 阶段切换/用户刚发送消息时不能依赖 smooth 动画:下一帧可能还会插入校验卡、 // Markdown 或工具步骤,动画目标会停在旧高度。这里直接写入 scrollTop,由内容 // ResizeObserver 继续接管后续增高,保证关键阶段始终落在最新底部。 const forceScrollToBottom = useCallback(() => { const el = ref.current; if (!el) return; programmaticScrollTargetRef.current = Math.max( 0, el.scrollHeight - el.clientHeight, ); el.scrollTop = el.scrollHeight; lastObservedScrollTopRef.current = el.scrollTop; lastObservedScrollHeightRef.current = el.scrollHeight; atBottomRef.current = true; setAtBottom(true); }, [ref]); return { atBottom, scrollToBottom, forceScrollToBottom }; }