Skip to content

Commit e6b9c07

Browse files
committed
feat: support more user-friendly scrolling
1 parent 819d249 commit e6b9c07

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

app/components/chat.tsx

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -960,9 +960,29 @@ function _Chat() {
960960
(scrollRef.current.scrollTop + scrollRef.current.clientHeight),
961961
) <= 1
962962
: false;
963+
const isAttachWithTop = useCallback(() => {
964+
// if user is typing, should scroll
965+
if (!scrollRef.current) return false;
966+
// get lastMessageId
967+
const lastMessageId = session.messages[session.messages.length - 1]?.id;
968+
if (!lastMessageId) return false;
969+
const lastMessage = document.getElementById(lastMessageId);
970+
if (!lastMessage) return false;
971+
972+
const topDistance =
973+
lastMessage.getBoundingClientRect().top -
974+
scrollRef.current.getBoundingClientRect().top;
975+
// leave some space for user question
976+
return topDistance < 100;
977+
}, [session.messages, scrollRef]);
978+
979+
const isTyping = userInput !== "";
980+
981+
// if user is typing, should auto scroll to bottom
982+
// if user is not typing, should auto scroll to bottom only if already at bottom
963983
const { setAutoScroll, scrollDomToBottom } = useScrollToBottom(
964984
scrollRef,
965-
isScrolledToBottom,
985+
(isScrolledToBottom || isAttachWithTop()) && !isTyping,
966986
);
967987
const [hitBottom, setHitBottom] = useState(true);
968988
const isMobileScreen = useMobileScreen();
@@ -1717,6 +1737,7 @@ function _Chat() {
17171737
? styles["chat-message-user"]
17181738
: styles["chat-message"]
17191739
}
1740+
id={message.id}
17201741
>
17211742
<div className={styles["chat-message-container"]}>
17221743
<div className={styles["chat-message-header"]}>

0 commit comments

Comments
 (0)