Skip to content

Commit

Permalink
prefetch messages on load
Browse files Browse the repository at this point in the history
  • Loading branch information
LoV432 committed Feb 29, 2024
1 parent 35f75c6 commit 2a5539f
Show file tree
Hide file tree
Showing 4 changed files with 129 additions and 23 deletions.
62 changes: 40 additions & 22 deletions app/components/ChatWindowPanel/MessagesBox/ChatBubbles.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use client';
import { useEffect, useRef, useState } from 'react';
import { useAtomValue } from 'jotai';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useAtomValue, useAtom } from 'jotai';
import { activeServerStore } from '../../../store/active-server-store';
import {
getServerMessages,
Expand All @@ -9,11 +9,19 @@ import {
} from '../../../lib/get-server-messages';
import SendMessage from './SendMessage';
import Image from 'next/image';
import {
prefetchedMessagesAtom,
isHydrated as isHydratedAtom
} from '../../Misc/PrefetchedMessagesStore';

export default function ChatBubbles() {
const [prefetchedMessages, setPrefetchedMessages] = useAtom(
prefetchedMessagesAtom
);
const activeServer = useAtomValue(activeServerStore);
const [chatStore, setChatStore] = useState<dbReturnAllMessages>([]);
const chatStoreRef = useRef<dbReturnAllMessages>([]);
const [chatStore, setChatStore] =
useState<dbReturnAllMessages>(prefetchedMessages);
const chatStoreRef = useRef<dbReturnAllMessages>(prefetchedMessages);
const chatBoxAreaRef = useRef(
null
) as unknown as React.MutableRefObject<HTMLDivElement>;
Expand All @@ -26,6 +34,7 @@ export default function ChatBubbles() {
}
chatStoreRef.current = allMessages;
setChatStore(chatStoreRef.current);
setPrefetchedMessages([]); // Clear prefetched messages or otherwise they will be shown when switching servers
}
async function updateChat() {
const lastMessageId =
Expand Down Expand Up @@ -70,6 +79,25 @@ export default function ChatBubbles() {
}

export function ChatBubble({ message }: { message: dbReturnAllMessages[0] }) {
const isHydrated = useAtomValue(isHydratedAtom);
const time = useMemo(() => {
if (!isHydrated)
return message.time.toLocaleString('en-US', {
year: '2-digit',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
timeZone: 'UTC'
});
return message.time.toLocaleString('en-US', {
year: '2-digit',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric'
});
}, [isHydrated]);
if (message.team == 'CONSOLE') {
return (
<>
Expand All @@ -91,15 +119,10 @@ export function ChatBubble({ message }: { message: dbReturnAllMessages[0] }) {
<a href={`admin.jpg`} target={'_blank'} className="text-rose-600">
Console
</a>
<time className="text-xs opacity-50">
{' '}
{message.time.toLocaleString('en-US', {
year: '2-digit',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric'
})}
<time
className={`pl-2 text-xs opacity-50 ${isHydrated ? '' : 'invisible'}}`}
>
{time}
</time>
</div>
<div className="chat-bubble mb-2 mt-1 break-all">
Expand Down Expand Up @@ -135,15 +158,10 @@ export function ChatBubble({ message }: { message: dbReturnAllMessages[0] }) {
>
{message.author_name}
</a>
<time className="text-xs opacity-50">
{' '}
{message.time.toLocaleString('en-US', {
year: '2-digit',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric'
})}
<time
className={`pl-2 text-xs opacity-50 ${isHydrated ? '' : 'invisible'}`}
>
{time}
</time>
</div>
<div className="chat-bubble mb-2 mt-1 break-all">{message.message}</div>
Expand Down
59 changes: 59 additions & 0 deletions app/components/ChatWindowPanel/PrefetchMessages.server.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { db } from '@/app/lib/db';
import { getServersConfig } from '@/app/lib/configParse';
import type { dbReturnAllMessages } from '@/app/lib/get-server-messages';
import PrefetchedMessagesStore from '../Misc/PrefetchedMessagesStore';

export default async function PrefetchMessages({
searchParams,
children
}: {
searchParams: { [key: string]: string | string[] | undefined };
children: React.ReactNode;
}) {
const serverIndex = Number(searchParams['SelectedServer']) || 0;
const allMessages = await getServerMessages(serverIndex);
if ('error' in allMessages) {
console.log('Error loading messages');
return (
<PrefetchedMessagesStore prefetchedMessages={[]}>
{children}
</PrefetchedMessagesStore>
);
}
return (
<PrefetchedMessagesStore prefetchedMessages={allMessages}>
{children}
</PrefetchedMessagesStore>
);
}

async function getServerMessages(
selectedServerIndex: number,
olderThan = 0,
newerThan = 0
) {
const config = getServersConfig();
if ('err' in config || config.global.chatLogger != true) {
return { error: true };
}
try {
if (olderThan === 0) {
const allMessages = (
await db.query(
`SELECT * FROM server_messages WHERE server_id=${config.servers[selectedServerIndex].chatLoggerId} AND id > ${newerThan} ORDER BY id DESC LIMIT 30`
)
)[0] as dbReturnAllMessages;
return allMessages.reverse();
} else {
const allMessages = (
await db.query(
`SELECT * FROM server_messages WHERE server_id=${config.servers[selectedServerIndex].chatLoggerId} AND id < ${olderThan} ORDER BY id DESC LIMIT 30`
)
)[0] as dbReturnAllMessages;
return allMessages.reverse();
}
} catch (err) {
console.log(err);
return { error: true };
}
}
26 changes: 26 additions & 0 deletions app/components/Misc/PrefetchedMessagesStore.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
'use client';
import { atom, useSetAtom } from 'jotai';
import { dbReturnAllMessages } from '@/app/lib/get-server-messages';
import { useEffect } from 'react';

export const prefetchedMessagesAtom = atom<dbReturnAllMessages>(
{} as dbReturnAllMessages
);

export const isHydrated = atom(false);

export default function PrefetchedMessagesStore({
children,
prefetchedMessages
}: {
children: React.ReactNode;
prefetchedMessages: dbReturnAllMessages;
}) {
const setIsHydrated = useSetAtom(isHydrated);
const setPrefetchedMessages = useSetAtom(prefetchedMessagesAtom);
setPrefetchedMessages(prefetchedMessages);
useEffect(() => {
setIsHydrated(true);
});
return children;
}
5 changes: 4 additions & 1 deletion app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Provider } from 'jotai';
import Loading from './components/Misc/Loading';
import ActiveServerURLSync from './components/Misc/ActiveServerURLSync';
import { getServersConfig } from './lib/configParse';
import PrefetchMessages from './components/ChatWindowPanel/PrefetchMessages.server';
export const dynamic = 'force-dynamic';

export default function Home({
Expand Down Expand Up @@ -49,7 +50,9 @@ export default function Home({
featureFlags={featureFlags}
serverNames={serverNames}
/>
<ChatWindowPanel featureFlags={featureFlags} />
<PrefetchMessages searchParams={searchParams}>
<ChatWindowPanel featureFlags={featureFlags} />
</PrefetchMessages>
</ActiveServerURLSync>
</Provider>
</div>
Expand Down

0 comments on commit 2a5539f

Please sign in to comment.