File size: 3,101 Bytes
3bb94b1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 |
import React, { useState, useEffect, useRef } from 'react';
import { useAuth } from '../services/AuthContext';
import { useNavigate } from 'react-router-dom';
const processMessages = (messageObject) => {
return (previousMessages) => {
if (previousMessages.length > 0 && previousMessages[previousMessages.length - 1].sender === messageObject.sender) {
const newMessage = {text:previousMessages[previousMessages.length - 1].text+ ' ' + messageObject.text, sender: messageObject.sender};
return [...previousMessages.slice(0, -1), newMessage];
} else {
return [...previousMessages, messageObject];
}
}
}
const ChatApi = () => {
const { token, logout } = useAuth();
const navigate = useNavigate();
const [messages, setMessages] = useState([]);
const [input, setInput] = useState('');
const sendMessage = (e) => {
e.preventDefault();
if (!input.trim()) return;
const message = {
type: 'message',
content: input
};
setMessages(processMessages({
text: input,
sender: 'user'
}));
fetch('http://localhost:8000/api/message', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
message: input
})
}).then(response => response.json()).then(data => {
setMessages(processMessages({
text: data.message?.content,
sender: 'ai'
}));
});
setInput('');
};
// Rest of your component (file upload handler, UI rendering, etc.)
return (
<div className="flex flex-col bg-gray-100 h-[90vh]">
{/* Messages area */}
<div className="flex-1 overflow-y-auto p-4 space-y-4" >
{(messages || []).map((message, index) => (
<div
key={index}
className={`p-3 rounded-lg max-w-[80%] ${message.sender === 'user'
? 'ml-auto bg-blue-500 text-white'
: message.sender === 'ai'
? 'bg-gray-200'
: 'bg-yellow-100 mx-auto'
}`}
>
{message.text}
</div>
))}
</div>
{/* Input area */}
<div className="p-4 bg-white border-t">
<form onSubmit={sendMessage} className="flex gap-4">
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Type your message..."
className="flex-1 p-2 border rounded"
/>
<button
type="submit"
className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:bg-gray-400"
>
Send
</button>
<button
onClick={() => {
logout();
navigate('/login');
}}
className="px-4 py-2 text-white bg-red-500 rounded hover:bg-red-600"
>
Logout
</button>
</form>
</div>
</div>
);
};
export default ChatApi;
|