Skip to content

Commit c667bdd

Browse files
author
吴顶峰
committed
fix: fixed scroll when model is answering
1 parent 500b34f commit c667bdd

File tree

1 file changed

+37
-3
lines changed

1 file changed

+37
-3
lines changed

components/use-scroll-to-bottom.ts

+37-3
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,63 @@
1-
import { useEffect, useRef, type RefObject } from 'react';
1+
import { useEffect, useRef, type RefObject } from "react";
22

33
export function useScrollToBottom<T extends HTMLElement>(): [
44
RefObject<T>,
55
RefObject<T>,
66
] {
77
const containerRef = useRef<T>(null);
88
const endRef = useRef<T>(null);
9+
const userScrolledRef = useRef(false);
10+
const autoScrollInProgress = useRef(false);
911

1012
useEffect(() => {
1113
const container = containerRef.current;
1214
const end = endRef.current;
1315

1416
if (container && end) {
1517
const observer = new MutationObserver(() => {
16-
end.scrollIntoView({ behavior: 'instant', block: 'end' });
18+
if (!userScrolledRef.current) {
19+
autoScrollInProgress.current = true;
20+
end.scrollIntoView({ behavior: "smooth", block: "end" });
21+
22+
// 处理滚动结束事件
23+
const handleScrollEnd = () => {
24+
autoScrollInProgress.current = false;
25+
container.removeEventListener("scrollend", handleScrollEnd);
26+
};
27+
28+
if ("onscrollend" in window) {
29+
container.addEventListener("scrollend", handleScrollEnd);
30+
} else {
31+
// 回退:假设滚动动画在1秒内完成
32+
setTimeout(() => {
33+
autoScrollInProgress.current = false;
34+
}, 1000);
35+
}
36+
}
1737
});
1838

39+
const handleScroll = () => {
40+
if (autoScrollInProgress.current) return;
41+
42+
// 检查是否滚动到底部
43+
const { scrollTop, scrollHeight, clientHeight } = container;
44+
const isAtBottom = scrollHeight - (scrollTop + clientHeight) < 1;
45+
46+
userScrolledRef.current = !isAtBottom;
47+
};
48+
49+
container.addEventListener("scroll", handleScroll);
1950
observer.observe(container, {
2051
childList: true,
2152
subtree: true,
2253
attributes: true,
2354
characterData: true,
2455
});
2556

26-
return () => observer.disconnect();
57+
return () => {
58+
observer.disconnect();
59+
container.removeEventListener("scroll", handleScroll);
60+
};
2761
}
2862
}, []);
2963

0 commit comments

Comments
 (0)