From 2040092c83ceb36fb5f40a4434cb083f6edbf471 Mon Sep 17 00:00:00 2001 From: hfdem Date: Sat, 10 Aug 2024 06:05:51 +0800 Subject: [PATCH] fix: pointer always pops up when sending and receiving messages The "New Messages" pointer pops up both when sending messages continuously and receiving messages. https://github.com/muke1908/chat-e2ee/issues/77#issuecomment-2277770989 --- .../components/Messaging/ScrollWrapper.tsx | 51 ++++++++++--------- 1 file changed, 27 insertions(+), 24 deletions(-) diff --git a/client/src/components/Messaging/ScrollWrapper.tsx b/client/src/components/Messaging/ScrollWrapper.tsx index 0d8a8d8..74fe4db 100644 --- a/client/src/components/Messaging/ScrollWrapper.tsx +++ b/client/src/components/Messaging/ScrollWrapper.tsx @@ -8,48 +8,51 @@ type ScrollWrapperProps = { export const ScrollWrapper = ({ children, messageCount }: ScrollWrapperProps) => { const wrapperRef = useRef(null); + const [isAtBottom, setIsAtBottom] = useState(true); const [showPopup, setShowPopup] = useState(false); - const [scrollAtBottom, setScrollAtBottom] = useState(true); useEffect(() => { - if (wrapperRef.current) { + const handleScroll = () => { const wrapper = wrapperRef.current; - const isScrolledToBottom = wrapper.scrollHeight - wrapper.scrollTop === wrapper.clientHeight; - setScrollAtBottom(isScrolledToBottom); - if (isScrolledToBottom) { - wrapper.scrollTop = wrapper.scrollHeight; - } else { - setShowPopup(true); + if (!wrapper) return; + setIsAtBottom(wrapper.scrollTop + wrapper.clientHeight >= wrapper.scrollHeight); + }; + + const wrapperElement = wrapperRef.current; + if (wrapperElement) { + wrapperElement.addEventListener('scroll', handleScroll); + } + + return () => { + if (wrapperElement) { + wrapperElement.removeEventListener('scroll', handleScroll); } + }; + }, []); + + useEffect(() => { + if (isAtBottom && messageCount > 0) { + scrollToBottom(); } - }, [messageCount]); + }, [messageCount, isAtBottom]); useEffect(() => { - if (scrollAtBottom && wrapperRef.current) { - wrapperRef.current.scrollTop = wrapperRef.current.scrollHeight; + if (!isAtBottom && messageCount > 0) { + setShowPopup(true); } - }, [scrollAtBottom, messageCount]); + }, [messageCount]); const scrollToBottom = () => { if (wrapperRef.current) { wrapperRef.current.scrollTop = wrapperRef.current.scrollHeight; - setShowPopup(false); - } - }; - - const handleScroll = () => { - if (wrapperRef.current) { - const wrapper = wrapperRef.current; - const isScrolledToBottom = wrapper.scrollHeight - wrapper.scrollTop === wrapper.clientHeight; - setScrollAtBottom(isScrolledToBottom); - setShowPopup(false); } + setShowPopup(false); }; return ( -
+
{children} - {showPopup && !scrollAtBottom && ( + {showPopup && (
New Messages