Commit e98a509a by 李伟康

fix(chat): 修复聊天组件自动滚动和样式问题

- 添加 shouldAutoScroll 状态控制自动滚动行为
- 实现用户手动滚动时暂停自动滚动功能
- 添加滚动事件监听器检测用户交互
- 优化 MutationObserver 回调延迟执行滚动
- 修复 Markdown 组件内容更新时的滚动逻辑
- 调整 Toast 组件定位和布局样式
- 为聊天容器添加触摸移动事件处理
1 parent 6e558d29
......@@ -6,7 +6,7 @@
* @FilePath: \ai-assistant\app\components\base\chat\chat\index.tsx
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
import React, { FC, memo, useCallback, useEffect, useRef } from 'react'
import React, { FC, memo, useCallback, useEffect, useRef, useState } from 'react'
import cn from '@/utils/classnames'
import InitQuestions from '@/app/components/base/chat/chat/question/init-questions'
import ChatFooter from './footer'
......@@ -25,25 +25,78 @@ const Chat: FC<ChatProps> = () => {
const chatFooterRef = useRef<HTMLDivElement>(null)
const chatFooterInnerRef = useRef<HTMLDivElement>(null)
const lastScrollHeightRef = useRef(0)
const [shouldAutoScroll, setShouldAutoScroll] = useState(true)
const scrollTimeoutRef = useRef<NodeJS.Timeout | null>(null)
// const answerIcon = <AnswerIcon imageUrl={AVATAR_AI_URL} />
// const questionIcon = <AnswerIcon imageUrl={AVATAR_USER_URL} />
const isMobile = useBreakpoints() === MediaType.mobile
const handleScrollToBottom = useCallback(() => {
if (!shouldAutoScroll) return // 如果不应自动滚动,则直接返回
const container = chatContainerRef.current
if (!container) return
const curScrollHeight = container.scrollHeight
const lastScrollHeigh = lastScrollHeightRef.current
if (curScrollHeight !== lastScrollHeigh) {
lastScrollHeightRef.current = curScrollHeight
requestAnimationFrame(() => {
// 添加平滑滚动效果
container.scrollTo({
top: container.scrollHeight,
behavior: 'smooth',
})
})
// 使用 requestAnimationFrame 确保 DOM 更新完成后再滚动
requestAnimationFrame(() => {
const curScrollHeight = container.scrollHeight
const lastScrollHeigh = lastScrollHeightRef.current
// 只有当高度发生变化时才滚动
if (curScrollHeight !== lastScrollHeigh) {
lastScrollHeightRef.current = curScrollHeight
// 立即滚动到底部
container.scrollTop = container.scrollHeight
// 同时也尝试平滑滚动(作为备选)
setTimeout(() => {
container.scrollTo({
top: container.scrollHeight,
behavior: 'smooth'
})
}, 100)
}
})
}, [shouldAutoScroll])
// 检测用户是否正在手动滚动
useEffect(() => {
const handleUserScroll = () => {
// 用户手动滚动时,暂时禁用自动滚动
setShouldAutoScroll(false)
// 清除之前的定时器
if (scrollTimeoutRef.current) {
clearTimeout(scrollTimeoutRef.current)
}
// 设置一个新的定时器,在一段时间没有用户交互后重新启用自动滚动
scrollTimeoutRef.current = setTimeout(() => {
setShouldAutoScroll(true)
}, 2000) // 2秒后重新启用自动滚动
}
const container = chatContainerRef.current
if (container) {
// 添加滚动事件监听器到聊天容器
container.addEventListener('wheel', handleUserScroll, { passive: true })
container.addEventListener('touchmove', handleUserScroll, { passive: true })
container.addEventListener('scroll', handleUserScroll, { passive: true })
}
return () => {
// 清理事件监听器和定时器
if (container) {
container.removeEventListener('wheel', handleUserScroll)
container.removeEventListener('touchmove', handleUserScroll)
container.removeEventListener('scroll', handleUserScroll)
}
if (scrollTimeoutRef.current) {
clearTimeout(scrollTimeoutRef.current)
}
}
}, [])
......@@ -53,20 +106,31 @@ const Chat: FC<ChatProps> = () => {
const container = chatContainerRef.current
if (!container) return
const observer = new MutationObserver(handleScrollToBottom)
const observer = new MutationObserver(() => {
// 延迟一点时间确保内容完全渲染
setTimeout(handleScrollToBottom, 50)
})
observer.observe(container, {
childList: true,
subtree: true,
characterData: true,
})
return () => observer.disconnect()
}, [handleScrollToBottom])
useEffect(() => {
const container = chatContainerRef.current
const footer = chatFooterRef.current
if (!container || !footer) return
container.style.paddingBottom = `${footer.clientHeight}px`
handleScrollToBottom()
// 初始化时也滚动到底部
setTimeout(handleScrollToBottom, 100)
}, [handleScrollToBottom])
return (
<div className="relative h-full">
<div
......@@ -86,4 +150,4 @@ const Chat: FC<ChatProps> = () => {
)
}
export default memo(Chat)
export default memo(Chat)
\ No newline at end of file
......@@ -21,7 +21,7 @@ import {
Video,
Chart,
} from './blocks'
import { useMemo } from 'react'
import { useMemo, useEffect, useRef, useState } from 'react'
/**
* @fileoverview Main Markdown rendering component.
......@@ -111,9 +111,71 @@ export function Markdown(props: MarkdownProps) {
return filtered.trim()
}, [latexContent])
// 创建 ref 来引用 markdown 容器
const markdownRef = useRef<HTMLDivElement>(null)
const [shouldAutoScroll, setShouldAutoScroll] = useState(true)
const scrollTimeoutRef = useRef<NodeJS.Timeout | null>(null)
// 检测用户是否正在手动滚动
useEffect(() => {
const handleUserScroll = () => {
// 用户手动滚动时,暂时禁用自动滚动
setShouldAutoScroll(false)
// 清除之前的定时器
if (scrollTimeoutRef.current) {
clearTimeout(scrollTimeoutRef.current)
}
// 设置一个新的定时器,在一段时间没有用户交互后重新启用自动滚动
scrollTimeoutRef.current = setTimeout(() => {
setShouldAutoScroll(true)
}, 2000) // 2秒后重新启用自动滚动
}
// 添加滚动事件监听器
window.addEventListener('wheel', handleUserScroll, { passive: true })
window.addEventListener('touchmove', handleUserScroll, { passive: true })
window.addEventListener('scroll', handleUserScroll, { passive: true })
return () => {
// 清理事件监听器和定时器
window.removeEventListener('wheel', handleUserScroll)
window.removeEventListener('touchmove', handleUserScroll)
window.removeEventListener('scroll', handleUserScroll)
if (scrollTimeoutRef.current) {
clearTimeout(scrollTimeoutRef.current)
}
}
}, [])
// 当内容更新时,自动滚动到底部(仅在允许自动滚动时)
useEffect(() => {
if (markdownRef.current && shouldAutoScroll) {
// 找到最近的滚动容器并滚动到底部
let scrollContainer = markdownRef.current.parentElement
while (scrollContainer && scrollContainer.scrollHeight <= scrollContainer.clientHeight) {
scrollContainer = scrollContainer.parentElement
}
if (scrollContainer) {
requestAnimationFrame(() => {
scrollContainer.scrollTo({
top: scrollContainer.scrollHeight,
behavior: 'smooth'
})
})
}
}
}, [filteredContent, contentObj.jsonContent, shouldAutoScroll])
return (
<>
<div className={cn('markdown-body ', '!text-text-primary', props.className)}>
<div
ref={markdownRef}
className={cn('markdown-body ', '!text-text-primary', props.className)}>
<ReactMarkdown
remarkPlugins={[RemarkGfm, [RemarkMath, { singleDollarTextMath: false }], RemarkBreaks]}
rehypePlugins={[
......@@ -171,4 +233,4 @@ export function Markdown(props: MarkdownProps) {
) : null}
</>
)
}
}
\ No newline at end of file
......@@ -31,9 +31,21 @@ const Toast = ({ type = 'info', size = 'md', message, children, className, custo
if (typeof message !== 'string') return null
return (
<div style={{ left: '50%', transform: 'translateX(-50%)', maxWidth: 'min(343px, 91vw)', borderRadius: '54px' }} className={classNames(className, 'fixed my-4 flex-grow z-[9999] overflow-hidden', size === 'md' ? 'p-3' : 'p-2', 'top-0', 'right-0')}>
<div
className={classNames(
className,
'fixed top-4 left-1/2 z-[9999] overflow-hidden',
'flex flex-col items-center',
size === 'md' ? 'p-3' : 'p-2'
)}
style={{
transform: 'translateX(-50%)',
maxWidth: '91vw',
borderRadius: '54px'
}}
>
<div className="absolute inset-0 -z-10" style={{ backgroundColor: 'rgba(0, 0, 0, 0.5)' }} />
<div className={`flex ${size === 'md' ? 'gap-1' : 'gap-0.5'}`}>
<div className={`flex ${size === 'md' ? 'gap-1' : 'gap-0.5'} w-full`}>
<div className={`flex items-center justify-center ${size === 'md' ? 'p-0.5' : 'p-1'}`}>
{type === 'success' && <RiCheckboxCircleFill className={`${size === 'md' ? 'h-5 w-5' : 'h-4 w-4'} text-white`} aria-hidden="true" />}
{type === 'error' && <RiErrorWarningFill className={`${size === 'md' ? 'h-5 w-5' : 'h-4 w-4'} text-white`} aria-hidden="true" />}
......@@ -122,4 +134,4 @@ Toast.notify = ({ type, size = 'md', message, duration, className, customCompone
}
}
export default Toast
export default Toast
\ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!