From 66bafcf2c5626b92ada8c2aae2ed06e43638282f Mon Sep 17 00:00:00 2001 From: Mamadou DICKO <63923024+mamadoudicko@users.noreply.github.com> Date: Fri, 25 Aug 2023 12:05:04 +0200 Subject: [PATCH] feat(messagesList): auto scroll on new message (#1040) --- .../ChatMessages/hooks/useChatMessages.ts | 21 +++++++++++-------- .../components/ChatMessages/index.tsx | 7 +++++-- frontend/package.json | 2 ++ frontend/yarn.lock | 2 +- 4 files changed, 20 insertions(+), 12 deletions(-) diff --git a/frontend/app/chat/[chatId]/components/ChatMessages/hooks/useChatMessages.ts b/frontend/app/chat/[chatId]/components/ChatMessages/hooks/useChatMessages.ts index 736d5fb56..c6881b7ea 100644 --- a/frontend/app/chat/[chatId]/components/ChatMessages/hooks/useChatMessages.ts +++ b/frontend/app/chat/[chatId]/components/ChatMessages/hooks/useChatMessages.ts @@ -1,3 +1,4 @@ +import _debounce from "lodash/debounce"; import { useCallback, useEffect, useRef } from "react"; import { useChat } from "@/app/chat/[chatId]/hooks/useChat"; @@ -10,15 +11,17 @@ export const useChatMessages = () => { const chatListRef = useRef(null); const { history } = useChat(); - const scrollToBottom = useCallback(() => { - if (chatListRef.current) { - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - chatListRef.current.scrollTo?.({ - top: chatListRef.current.scrollHeight, - behavior: "smooth", - }); - } - }, []); + const scrollToBottom = useCallback( + _debounce(() => { + if (chatListRef.current) { + chatListRef.current.scrollTo({ + top: chatListRef.current.scrollHeight, + behavior: "auto", + }); + } + }, 100), + [] + ); useEffect(() => { const computeCardHeight = () => { diff --git a/frontend/app/chat/[chatId]/components/ChatMessages/index.tsx b/frontend/app/chat/[chatId]/components/ChatMessages/index.tsx index 0fe4cd170..de42cab29 100644 --- a/frontend/app/chat/[chatId]/components/ChatMessages/index.tsx +++ b/frontend/app/chat/[chatId]/components/ChatMessages/index.tsx @@ -4,19 +4,22 @@ import { useTranslation } from "react-i18next"; import { useChatContext } from "@/lib/context"; import { ChatMessage } from "./components/ChatMessage/components/ChatMessage"; +import { useChatMessages } from "./hooks/useChatMessages"; export const ChatMessages = (): JSX.Element => { const { history } = useChatContext(); const { t } = useTranslation(["chat"]); + const { chatListRef } = useChatMessages(); return (
{history.length === 0 ? (