From 6dfee8e11a8c837d5353fe5b6aa74c75bbabea28 Mon Sep 17 00:00:00 2001 From: Sherlock <1075773551@qq.com> Date: Wed, 13 Nov 2024 20:17:53 +0800 Subject: [PATCH] feat: support more user-friendly scrolling --- app/components/chat.tsx | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/app/components/chat.tsx b/app/components/chat.tsx index 5669cc9a3147..d7dfb38beb0b 100644 --- a/app/components/chat.tsx +++ b/app/components/chat.tsx @@ -960,9 +960,28 @@ function _Chat() { (scrollRef.current.scrollTop + scrollRef.current.clientHeight), ) <= 1 : false; + const isAttachWithTop = useCallback(() => { + // if user is typing, should scroll + if (!scrollRef.current) return false; + // get lastMessageId + const lastMessageId = session.messages[session.messages.length - 1]?.id; + const lastMessage = document.getElementById(lastMessageId); + if (!lastMessage) return false; + + const topDistance = + lastMessage.getBoundingClientRect().top - + scrollRef.current.getBoundingClientRect().top; + // leave some space for user question + return topDistance < 100; + }, [session.messages, scrollRef]); + + const isTyping = userInput !== ""; + + // if user is typing, should auto scroll to bottom + // if user is not typing, should auto scroll to bottom only if already at bottom const { setAutoScroll, scrollDomToBottom } = useScrollToBottom( scrollRef, - isScrolledToBottom, + (isScrolledToBottom || isAttachWithTop()) && !isTyping, ); const [hitBottom, setHitBottom] = useState(true); const isMobileScreen = useMobileScreen(); @@ -1717,6 +1736,7 @@ function _Chat() { ? styles["chat-message-user"] : styles["chat-message"] } + id={message.id} >