diff --git a/app/components/ChatBubbles.tsx b/app/components/ChatBubbles.tsx index 94d7da6..b38e496 100644 --- a/app/components/ChatBubbles.tsx +++ b/app/components/ChatBubbles.tsx @@ -12,6 +12,9 @@ export default function ChatBubbles() { const activeServer = useAtomValue(activeServerStore); const [chatStore, setChatStore] = useState([]); const chatStoreRef = useRef([]); + const chatBoxAreaRef = useRef( + null + ) as unknown as React.MutableRefObject; async function getInitChat() { const allMessages = await getServerMessages(activeServer); if ('error' in allMessages) { @@ -45,11 +48,15 @@ export default function ChatBubbles() { }; }, [activeServer]); return ( -
+
{chatStore.map((message) => ( @@ -102,16 +109,20 @@ export function ChatBubble({ message }: { message: dbReturnAllMessages[0] }) { export function OlderMessagesButton({ setChatStore, - chatStoreRef + chatStoreRef, + chatBoxAreaRef }: { setChatStore: React.Dispatch>; chatStoreRef: React.MutableRefObject; + chatBoxAreaRef: React.MutableRefObject; }) { const activeServer = useAtomValue(activeServerStore); const [firstMessageId, setFirstMessageId] = useState( { error: true } ); const [isLoading, setIsLoading] = useState(false); + const deBounce = useRef(); + const loadMoreButtonRef = useRef(null); const shouldLoadButton = chatStoreRef.current[0]?.id != firstMessageId; async function updateOlderMessages() { if (isLoading) return; @@ -126,10 +137,28 @@ export function OlderMessagesButton({ setChatStore(chatStoreRef.current); setIsLoading(false); } + function updateOnScroll() { + if (deBounce.current) clearTimeout(deBounce.current); + deBounce.current = setTimeout(() => { + if ( + chatBoxAreaRef.current.scrollHeight + + (chatBoxAreaRef.current.scrollTop - + chatBoxAreaRef.current.clientHeight) === + 0 && + loadMoreButtonRef.current + ) { + updateOlderMessages(); + } + }, 150); + } useEffect(() => { (async () => { setFirstMessageId(await getFirstMessageId(activeServer)); })(); + chatBoxAreaRef.current?.addEventListener('scroll', updateOnScroll); + return () => { + chatBoxAreaRef.current?.removeEventListener('scroll', updateOnScroll); + }; }, [activeServer]); if ( typeof firstMessageId == 'object' || @@ -140,6 +169,7 @@ export function OlderMessagesButton({ <> {shouldLoadButton && !isLoading && (