|
| 1 | +import { useEffect, useRef, useState } from 'react' |
| 2 | + |
| 3 | +import { useChat, useMessages } from '@/hooks/demo.useChat' |
| 4 | + |
| 5 | +import Messages from './demo.messages' |
| 6 | + |
| 7 | +export default function ChatArea() { |
| 8 | + const messagesEndRef = useRef<HTMLDivElement>(null) |
| 9 | + |
| 10 | + const { sendMessage } = useChat() |
| 11 | + |
| 12 | + const messages = useMessages() |
| 13 | + |
| 14 | + const [message, setMessage] = useState('') |
| 15 | + const [user, setUser] = useState('Alice') |
| 16 | + |
| 17 | + useEffect(() => { |
| 18 | + messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }) |
| 19 | + }, [messages]) |
| 20 | + |
| 21 | + const postMessage = () => { |
| 22 | + if (message.trim().length) { |
| 23 | + sendMessage(message, user) |
| 24 | + setMessage('') |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + const handleKeyPress = (e: React.KeyboardEvent) => { |
| 29 | + if (e.key === 'Enter') { |
| 30 | + postMessage() |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + return ( |
| 35 | + <> |
| 36 | + <div className="flex-1 overflow-y-auto px-4 py-6 space-y-4"> |
| 37 | + <Messages messages={messages} user={user} /> |
| 38 | + <div ref={messagesEndRef} /> |
| 39 | + </div> |
| 40 | + |
| 41 | + <div className="bg-white border-t border-gray-200 px-4 py-4"> |
| 42 | + <div className="flex items-center space-x-3"> |
| 43 | + <select |
| 44 | + value={user} |
| 45 | + onChange={(e) => setUser(e.target.value)} |
| 46 | + className="px-3 py-2 border border-gray-300 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" |
| 47 | + > |
| 48 | + <option value="Alice">Alice</option> |
| 49 | + <option value="Bob">Bob</option> |
| 50 | + </select> |
| 51 | + |
| 52 | + <div className="flex-1 relative"> |
| 53 | + <input |
| 54 | + type="text" |
| 55 | + value={message} |
| 56 | + onChange={(e) => setMessage(e.target.value)} |
| 57 | + onKeyDown={handleKeyPress} |
| 58 | + placeholder="Type a message..." |
| 59 | + className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent" |
| 60 | + /> |
| 61 | + </div> |
| 62 | + |
| 63 | + <button |
| 64 | + onClick={postMessage} |
| 65 | + disabled={message.trim() === ''} |
| 66 | + className="px-6 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-colors" |
| 67 | + > |
| 68 | + Send |
| 69 | + </button> |
| 70 | + </div> |
| 71 | + </div> |
| 72 | + </> |
| 73 | + ) |
| 74 | +} |
0 commit comments