diff love/epi/src/components/ChatUI/ChatUI.tsx @ 38:cf9caa4abc3e

[Love] FE and BE. Can chat and render images. Also created MCP for powerpoint generations.
author MrJuneJune <me@mrjunejune.com>
date Mon, 01 Dec 2025 20:35:56 -0800
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/love/epi/src/components/ChatUI/ChatUI.tsx	Mon Dec 01 20:35:56 2025 -0800
@@ -0,0 +1,67 @@
+import { MessageContainer } from './MessageContainer';
+import { Composer } from './Composer';
+import { useChat } from '@/hooks/useChat';
+import { useEffect, useRef, useState } from 'react';
+import { apiUrl } from '@/utils';
+import { currentChatId } from '@/atoms/chatAtoms';
+import { useAtom } from 'jotai';
+
+export function ChatUI({ chatId }: {chatId: string}) {
+  const [loading, setLoading] = useState(false);
+  const { messages, setMessages } = useChat(chatId);
+  const scrollRef = useRef<HTMLDivElement>(null);
+  const setCurrentChatId = useAtom(currentChatId)[1];
+  setCurrentChatId(chatId);
+
+  // Ignore warning since I want to render once.
+  useEffect(() => {
+    const loadHistory = async () => {
+      if (!chatId || chatId === 'new') return;
+      setLoading(true);
+      try {
+        const res = await fetch(apiUrl(`/chats/${chatId}/messages`));
+        if (!res.ok) throw new Error(`HTTP ${res.status}`);
+        const data = await res.json();
+        if (data.messages.length > 0) {
+          setMessages(data.messages);
+        }
+      } catch (err) {
+        console.error('Error from loading history: ', err);
+        setMessages([]);
+      } finally {
+        setLoading(false);
+      }
+    };
+    console.log('loadhistory');
+    loadHistory();
+  }, [chatId]);
+
+  useEffect(() => {
+    // This is not ideal, but couldnt' get CSS to work. 
+    const timer = setTimeout(() => {
+      scrollRef.current?.scrollTo({
+        top: scrollRef.current.scrollHeight,
+        behavior: 'smooth',
+      });
+    }, 100);
+  
+    return () => clearTimeout(timer);
+  }, [messages]);
+
+  return (
+    <div className="flex flex-col bg-gray-100 dark:bg-black h-screen">
+      <div
+        ref={scrollRef}
+        className="flex-1 overflow-y-scroll"
+      >
+        {loading && (
+          <div className="flex justify-center items-center h-full">
+            <span>Loading messages...</span>
+          </div>
+        )}
+        <MessageContainer messages={messages} />
+      </div>
+      <Composer chatId={chatId} />
+    </div>
+  );
+}