|
| 1 | +import { useState, useRef, useEffect } from "react" |
| 2 | + |
| 3 | +type Message = { |
| 4 | + role: "user" | "assistant" |
| 5 | + content: string |
| 6 | +} |
| 7 | + |
| 8 | +type ChatProps = { |
| 9 | + title?: string |
| 10 | + endpoint?: string |
| 11 | + placeholder?: string |
| 12 | + emptyState?: string |
| 13 | +} |
| 14 | + |
| 15 | +export default function Chat({ |
| 16 | + title = "Chat", |
| 17 | + endpoint = "/chat/stream", |
| 18 | + placeholder = "Type a message...", |
| 19 | + emptyState = "Send a message to start chatting.", |
| 20 | +}: ChatProps) { |
| 21 | + const [messages, setMessages] = useState<Message[]>([]) |
| 22 | + const [input, setInput] = useState("") |
| 23 | + const [loading, setLoading] = useState(false) |
| 24 | + const bottomRef = useRef<HTMLDivElement>(null) |
| 25 | + |
| 26 | + useEffect(() => { |
| 27 | + bottomRef.current?.scrollIntoView({ behavior: "smooth" }) |
| 28 | + }, [messages]) |
| 29 | + |
| 30 | + const handleSubmit = async (e: { preventDefault(): void }) => { |
| 31 | + e.preventDefault() |
| 32 | + if (!input.trim() || loading) return |
| 33 | + |
| 34 | + const userMessage = input.trim() |
| 35 | + setInput("") |
| 36 | + setMessages(prev => [...prev, { role: "user", content: userMessage }]) |
| 37 | + setLoading(true) |
| 38 | + setMessages(prev => [...prev, { role: "assistant", content: "" }]) |
| 39 | + |
| 40 | + try { |
| 41 | + const response = await fetch(endpoint, { |
| 42 | + method: "POST", |
| 43 | + headers: { "Content-Type": "application/json" }, |
| 44 | + body: JSON.stringify({ message: userMessage }), |
| 45 | + }) |
| 46 | + |
| 47 | + const reader = response.body?.getReader() |
| 48 | + const decoder = new TextDecoder() |
| 49 | + if (!reader) return |
| 50 | + |
| 51 | + while (true) { |
| 52 | + const { done, value } = await reader.read() |
| 53 | + if (done) break |
| 54 | + const chunk = decoder.decode(value, { stream: true }) |
| 55 | + setMessages(prev => { |
| 56 | + const updated = [...prev] |
| 57 | + updated[updated.length - 1] = { |
| 58 | + role: "assistant", |
| 59 | + content: updated[updated.length - 1].content + chunk, |
| 60 | + } |
| 61 | + return updated |
| 62 | + }) |
| 63 | + } |
| 64 | + } finally { |
| 65 | + setLoading(false) |
| 66 | + } |
| 67 | + } |
| 68 | + |
| 69 | + return ( |
| 70 | + <div className="flex flex-col h-screen max-w-2xl mx-auto p-4"> |
| 71 | + <h1 className="text-xl font-bold mb-4">{title}</h1> |
| 72 | + |
| 73 | + <div className="flex-1 overflow-y-auto space-y-3 mb-4"> |
| 74 | + {messages.length === 0 && ( |
| 75 | + <p className="text-center text-gray-400 mt-8">{emptyState}</p> |
| 76 | + )} |
| 77 | + {messages.map((msg, i) => ( |
| 78 | + <div key={i} className={`flex ${msg.role === "user" ? "justify-end" : "justify-start"}`}> |
| 79 | + <div className={`max-w-sm px-4 py-2 rounded-2xl whitespace-pre-wrap ${ |
| 80 | + msg.role === "user" |
| 81 | + ? "bg-blue-500 text-white" |
| 82 | + : "bg-gray-100 text-gray-800" |
| 83 | + }`}> |
| 84 | + {msg.content || (loading && i === messages.length - 1 ? "▋" : "")} |
| 85 | + </div> |
| 86 | + </div> |
| 87 | + ))} |
| 88 | + <div ref={bottomRef} /> |
| 89 | + </div> |
| 90 | + |
| 91 | + <form onSubmit={handleSubmit} className="flex gap-2"> |
| 92 | + <input |
| 93 | + className="flex-1 border rounded-xl px-4 py-2 outline-none focus:ring-2 focus:ring-blue-400" |
| 94 | + type="text" |
| 95 | + value={input} |
| 96 | + onChange={e => setInput(e.target.value)} |
| 97 | + placeholder={placeholder} |
| 98 | + disabled={loading} |
| 99 | + /> |
| 100 | + <button |
| 101 | + type="submit" |
| 102 | + disabled={loading || !input.trim()} |
| 103 | + className="bg-blue-500 text-white px-5 py-2 rounded-xl disabled:opacity-50 hover:bg-blue-600 transition-colors" |
| 104 | + > |
| 105 | + Send |
| 106 | + </button> |
| 107 | + </form> |
| 108 | + </div> |
| 109 | + ) |
| 110 | +} |
0 commit comments