u: this is a chatgpt like interface. please add a chat indicator when loading is true…
- User
u: this is a chatgpt like interface. please add a chat indicator when loading is true (dancing dots): "use client";
import { useState, useRef, useEffect } from "react"; import ReactMarkdown from "react-markdown"; import { PaperPlaneIcon } from "@radix-ui/react-icons";
export default function Home() { const [prompt, setPrompt] = useState(""); const [response, setResponse] = useState(""); const [chatHistory, setChatHistory] = useState< { prompt: string; response: string }[]
([]); const [loading, setLoading] = useState(false); const bottomRef = useRef(null);
useEffect(() => { bottomRef.current?.scrollIntoView({ behavior: "smooth" }); }, [chatHistory]);
async function handleSubmit() { if (!prompt.trim()) return;
setResponse(""); setLoading(true); const res = await fetch("/api/chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt, history: chatHistory }), }); const reader = res.body?.getReader(); const decoder = new TextDecoder(); let fullText = ""; if (reader) { while (true) { const { done, value } = await reader.read(); if (done) break; const textChunks = decoder.decode(value, { stream: true }) || ""; const text = textChunks.trim().split("<<EOM>>").at(-2) || ""; setResponse(text); fullText = text; } } if (fullText) { setChatHistory((prev) => [...prev, { prompt, response: fullText }]); setPrompt(""); } setLoading(false);}
function handleKeyDown(e: React.KeyboardEvent) { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); handleSubmit(); } }
return ( {chatHistory.map(({ prompt, response }, i) => ( {prompt} {response} ))}
<form onSubmit={(e) => { e.preventDefault(); handleSubmit(); }} className="border-t border-zinc-700 p-4 flex items-end gap-2 bg-zinc-900" > <textarea className="flex-1 bg-zinc-800 text-white rounded-xl p-3 resize-none h-24 focus:outline-none" placeholder="Ask a question..." value={prompt} onChange={(e) => setPrompt(e.target.value)} onKeyDown={handleKeyDown} /> <button type="submit" disabled={loading} className="p-3 rounded-xl bg-blue-600 hover:bg-blue-700 disabled:opacity-50 text-white" > <PaperPlaneIcon className="h-5 w-5" /> </button> </form> </main>); }
- Assistant