Mercurial
comparison 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 |
comparison
equal
deleted
inserted
replaced
| 37:fb9bcd3145cb | 38:cf9caa4abc3e |
|---|---|
| 1 import { MessageContainer } from './MessageContainer'; | |
| 2 import { Composer } from './Composer'; | |
| 3 import { useChat } from '@/hooks/useChat'; | |
| 4 import { useEffect, useRef, useState } from 'react'; | |
| 5 import { apiUrl } from '@/utils'; | |
| 6 import { currentChatId } from '@/atoms/chatAtoms'; | |
| 7 import { useAtom } from 'jotai'; | |
| 8 | |
| 9 export function ChatUI({ chatId }: {chatId: string}) { | |
| 10 const [loading, setLoading] = useState(false); | |
| 11 const { messages, setMessages } = useChat(chatId); | |
| 12 const scrollRef = useRef<HTMLDivElement>(null); | |
| 13 const setCurrentChatId = useAtom(currentChatId)[1]; | |
| 14 setCurrentChatId(chatId); | |
| 15 | |
| 16 // Ignore warning since I want to render once. | |
| 17 useEffect(() => { | |
| 18 const loadHistory = async () => { | |
| 19 if (!chatId || chatId === 'new') return; | |
| 20 setLoading(true); | |
| 21 try { | |
| 22 const res = await fetch(apiUrl(`/chats/${chatId}/messages`)); | |
| 23 if (!res.ok) throw new Error(`HTTP ${res.status}`); | |
| 24 const data = await res.json(); | |
| 25 if (data.messages.length > 0) { | |
| 26 setMessages(data.messages); | |
| 27 } | |
| 28 } catch (err) { | |
| 29 console.error('Error from loading history: ', err); | |
| 30 setMessages([]); | |
| 31 } finally { | |
| 32 setLoading(false); | |
| 33 } | |
| 34 }; | |
| 35 console.log('loadhistory'); | |
| 36 loadHistory(); | |
| 37 }, [chatId]); | |
| 38 | |
| 39 useEffect(() => { | |
| 40 // This is not ideal, but couldnt' get CSS to work. | |
| 41 const timer = setTimeout(() => { | |
| 42 scrollRef.current?.scrollTo({ | |
| 43 top: scrollRef.current.scrollHeight, | |
| 44 behavior: 'smooth', | |
| 45 }); | |
| 46 }, 100); | |
| 47 | |
| 48 return () => clearTimeout(timer); | |
| 49 }, [messages]); | |
| 50 | |
| 51 return ( | |
| 52 <div className="flex flex-col bg-gray-100 dark:bg-black h-screen"> | |
| 53 <div | |
| 54 ref={scrollRef} | |
| 55 className="flex-1 overflow-y-scroll" | |
| 56 > | |
| 57 {loading && ( | |
| 58 <div className="flex justify-center items-center h-full"> | |
| 59 <span>Loading messages...</span> | |
| 60 </div> | |
| 61 )} | |
| 62 <MessageContainer messages={messages} /> | |
| 63 </div> | |
| 64 <Composer chatId={chatId} /> | |
| 65 </div> | |
| 66 ); | |
| 67 } |