From 8a4015722dc59812344b02d6dfbfebfcfb348073 Mon Sep 17 00:00:00 2001 From: Rozstone <42225395+wststone@users.noreply.github.com> Date: Fri, 15 Mar 2024 13:19:06 +0800 Subject: [PATCH] prevent auto scrolling down to bottom when user already scrolled up (#2813) --- web/app/components/base/chat/chat/index.tsx | 28 +++++++++++++++------ 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/web/app/components/base/chat/chat/index.tsx b/web/app/components/base/chat/chat/index.tsx index 2f3ae501314ab1..2e46f1e8697620 100644 --- a/web/app/components/base/chat/chat/index.tsx +++ b/web/app/components/base/chat/chat/index.tsx @@ -4,6 +4,7 @@ import type { } from 'react' import { memo, + useCallback, useEffect, useRef, } from 'react' @@ -76,19 +77,20 @@ const Chat: FC = ({ const chatContainerInnerRef = useRef(null) const chatFooterRef = useRef(null) const chatFooterInnerRef = useRef(null) + const userScrolledRef = useRef(false) - const handleScrolltoBottom = () => { - if (chatContainerRef.current) + const handleScrolltoBottom = useCallback(() => { + if (chatContainerRef.current && !userScrolledRef.current) chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight - } + }, []) - const handleWindowResize = () => { + const handleWindowResize = useCallback(() => { if (chatContainerRef.current && chatFooterRef.current) chatFooterRef.current.style.width = `${chatContainerRef.current.clientWidth}px` if (chatContainerInnerRef.current && chatFooterInnerRef.current) chatFooterInnerRef.current.style.width = `${chatContainerInnerRef.current.clientWidth}px` - } + }, []) useThrottleEffect(() => { handleScrolltoBottom() @@ -98,7 +100,7 @@ const Chat: FC = ({ useEffect(() => { window.addEventListener('resize', debounce(handleWindowResize)) return () => window.removeEventListener('resize', handleWindowResize) - }, []) + }, [handleWindowResize]) useEffect(() => { if (chatFooterRef.current && chatContainerRef.current) { @@ -117,7 +119,19 @@ const Chat: FC = ({ resizeObserver.disconnect() } } - }, [chatFooterRef, chatContainerRef]) + }, [handleScrolltoBottom]) + + useEffect(() => { + const chatContainer = chatContainerRef.current + if (chatContainer) { + const setUserScrolled = () => { + if (chatContainer) + userScrolledRef.current = chatContainer.scrollHeight - chatContainer.scrollTop >= chatContainer.clientHeight + 300 + } + chatContainer.addEventListener('scroll', setUserScrolled) + return () => chatContainer.removeEventListener('scroll', setUserScrolled) + } + }, []) const hasTryToAsk = config?.suggested_questions_after_answer?.enabled && !!suggestedQuestions?.length && onSend