Skip to content

Commit 6c949be

Browse files
committed
refactor: Update scrolling behavior in MessageList component to improve user experience by changing the scroll detection logic and event handling from scroll to wheel events
1 parent f4bb54f commit 6c949be

File tree

1 file changed

+21
-17
lines changed

1 file changed

+21
-17
lines changed

src/renderer/src/components/pages/chat/MessageList.tsx

Lines changed: 21 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -83,42 +83,46 @@ export default function MessageList({
8383
// 计算当前的流式内容,用于触发滚动
8484
const currentStreamingContent = lastMessageStreaming?.content || ''
8585

86-
// 检查是否已经滚动到底部
87-
const isAtBottom = useCallback(() => {
86+
// 检查是否距离底部较近
87+
const isNearBottom = useCallback(() => {
8888
const container = messagesContainerRef.current
8989
if (!container) return true
9090

91-
const threshold = 20 // 20px 的阈值
91+
const threshold = 100 // 100px 的阈值,仅用于判断是否接近底部以恢复自动滚动
9292
const { scrollTop, scrollHeight, clientHeight } = container
9393
return scrollHeight - scrollTop - clientHeight <= threshold
9494
}, [])
9595

96-
// 处理用户滚动事件
97-
const handleScroll = useCallback(() => {
96+
// 处理鼠标滚轮事件
97+
const handleWheel = useCallback((event: WheelEvent) => {
9898
if (isInitialRender.current) return // 忽略初次渲染时的滚动事件
9999

100-
const atBottom = isAtBottom()
100+
const deltaY = event.deltaY
101101

102-
if (atBottom && !isAutoScrollEnabled) {
103-
// 用户滚动到底部,恢复自动滚动
104-
setIsAutoScrollEnabled(true)
105-
} else if (!atBottom && isAutoScrollEnabled) {
106-
// 用户向上滚动,停止自动滚动
107-
setIsAutoScrollEnabled(false)
102+
if (deltaY < 0) {
103+
// 向上滚动,停止自动滚动
104+
if (isAutoScrollEnabled) {
105+
setIsAutoScrollEnabled(false)
106+
}
107+
} else if (deltaY > 0) {
108+
// 向下滚动,如果接近底部就恢复自动滚动
109+
if (!isAutoScrollEnabled && isNearBottom()) {
110+
setIsAutoScrollEnabled(true)
111+
}
108112
}
109-
}, [isAutoScrollEnabled, isAtBottom])
113+
}, [isAutoScrollEnabled, isNearBottom])
110114

111-
// 添加和移除滚动事件监听器
115+
// 添加和移除滚轮事件监听器
112116
useEffect(() => {
113117
const container = messagesContainerRef.current
114118
if (!container) return
115119

116-
container.addEventListener('scroll', handleScroll, { passive: true })
120+
container.addEventListener('wheel', handleWheel, { passive: true })
117121

118122
return () => {
119-
container.removeEventListener('scroll', handleScroll)
123+
container.removeEventListener('wheel', handleWheel)
120124
}
121-
}, [handleScroll])
125+
}, [handleWheel])
122126

123127
const scrollToBottom = (behavior: 'smooth' | 'instant' = 'smooth') => {
124128
messagesEndRef.current?.scrollIntoView({ behavior })

0 commit comments

Comments
 (0)