File size: 10,451 Bytes
057576a | 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 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 | import React, { useState, useRef, useCallback } from 'react';
import { Send, Paperclip, Smile, X, Image, Music, FileText } from 'lucide-react';
import { useWebSocket } from '../../hooks/useWebSocket';
import { useFileUpload } from '../../hooks/useFileUpload';
import { validateFile, formatFileSize } from '../../utils/fileValidation';
const MessageInput = ({ conversation, onSendMessage }) => {
const [message, setMessage] = useState('');
const [isTyping, setIsTyping] = useState(false);
const [filePreview, setFilePreview] = useState(null);
const fileInputRef = useRef();
const { sendMessage } = useWebSocket();
const { uploadFile, uploading, progress, error: uploadError, reset: resetUpload } = useFileUpload();
const typingTimeoutRef = useRef();
const handleSubmit = async (e) => {
e.preventDefault();
if (!message.trim() && !filePreview) return;
// توقف تایپینگ
stopTyping();
if (filePreview) {
// ارسال فایل
await sendFileMessage();
} else {
// ارسال پیام متنی
sendTextMessage();
}
// بازنشانی حالت
setMessage('');
setFilePreview(null);
resetUpload();
};
const sendTextMessage = () => {
if (!message.trim()) return;
const messageData = {
conversationId: conversation._id,
content: message.trim(),
type: 'text'
};
// ارسال از طریق سوکت
if (sendMessage) {
sendMessage('message:send', messageData);
}
// بهروزرسانی لیست پیامها
onSendMessage({
...messageData,
_id: `temp-${Date.now()}`,
sender: { _id: 'current-user' },
createdAt: new Date(),
status: 'sending'
});
};
const sendFileMessage = async () => {
if (!filePreview) return;
try {
setLoading(true);
// آپلود فایل
const response = await uploadFile(filePreview.file);
// آمادهسازی داده پیام
const fileName = filePreview.file.name;
const messageData = {
conversationId: conversation._id,
content: message.trim() || `Sent ${getFileTypeDescription(filePreview.file.type)}`,
type: getMessageType(filePreview.file.type),
attachment: {
url: response.file.url,
filename: response.file.fileName,
originalName: fileName,
mimeType: filePreview.file.type,
size: filePreview.file.size,
thumbnail: response.file.thumbnail
}
};
// ارسال از طریق سوکت
if (sendMessage) {
sendMessage('message:send', messageData);
}
// بهروزرسانی لیست پیامها
onSendMessage({
...messageData,
_id: `temp-${Date.now()}`,
sender: { _id: 'current-user' },
createdAt: new Date(),
status: 'sending'
});
} catch (error) {
console.error('Failed to send file message:', error);
alert('Failed to send file. Please try again.');
} finally {
setLoading(false);
}
};
const handleInputChange = (e) => {
setMessage(e.target.value);
if (!isTyping) {
startTyping();
}
// بازنشانی تایمر تایپینگ
clearTimeout(typingTimeoutRef.current);
typingTimeoutRef.current = setTimeout(stopTyping, 1000);
};
const startTyping = () => {
if (!isTyping && sendMessage) {
setIsTyping(true);
sendMessage('typing:start', { conversationId: conversation._id });
}
};
const stopTyping = () => {
if (isTyping && sendMessage) {
setIsTyping(false);
sendMessage('typing:stop', { conversationId: conversation._id });
}
};
const handleFileSelect = (e) => {
const file = e.target.files[0];
if (!file) return;
try {
validateFile(file);
const previewUrl = URL.createObjectURL(file);
setFilePreview({
file,
previewUrl,
name: file.name,
size: file.size,
type: file.type
});
// بازنشانی input
fileInputRef.current.value = '';
} catch (error) {
alert(error.message);
}
};
const removeFile = () => {
if (filePreview?.previewUrl) {
URL.revokeObjectURL(filePreview.previewUrl);
}
setFilePreview(null);
resetUpload();
};
const getFileTypeDescription = (mimeType) => {
if (mimeType.startsWith('image/')) return 'an image';
if (mimeType.startsWith('audio/')) return 'an audio file';
if (mimeType === 'application/pdf') return 'a PDF';
if (mimeType.startsWith('text/')) return 'a text file';
return 'a file';
};
const getMessageType = (mimeType) => {
if (mimeType.startsWith('image/')) return 'image';
if (mimeType.startsWith('audio/')) return 'audio';
return 'file';
};
const getFileIcon = (mimeType) => {
if (mimeType.startsWith('image/')) return <Image className="w-4 h-4 text-gray-500" />;
if (mimeType.startsWith('audio/')) return <Music className="w-4 h-4 text-gray-500" />;
return <FileText className="w-4 h-4 text-gray-500" />;
};
const handleKeyPress = (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSubmit(e);
}
};
const handleEmojiSelect = (emojiObject) => {
setMessage(prev => prev + emojiObject.emoji);
if (fileInputRef.current) {
fileInputRef.current.focus();
}
};
return (
<div className="border-t border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-4">
{/* Preview فایل */}
{filePreview && (
<div className="mb-4 flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-200 dark:border-gray-600">
<div className="flex items-center space-x-3 flex-1 min-w-0">
<div className="text-primary-500">
{getFileIcon(filePreview.type)}
</div>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-gray-900 dark:text-white truncate">
{filePreview.name}
</p>
<div className="flex items-center space-x-2 text-xs text-gray-500 dark:text-gray-400">
<span>{formatFileSize(filePreview.size)}</span>
{uploading && (
<div className="flex items-center space-x-1">
<div className="w-16 bg-gray-200 dark:bg-gray-600 rounded-full h-1.5">
<div
className="bg-primary-500 h-1.5 rounded-full transition-all duration-300"
style={{ width: `${progress}%` }}
></div>
</div>
<span>{progress}%</span>
</div>
)}
</div>
</div>
</div>
<button
onClick={removeFile}
className="p-1 text-gray-500 hover:text-red-500 dark:text-gray-400 dark:hover:text-red-400 hover:bg-gray-200 dark:hover:bg-gray-600 rounded transition-colors"
>
<X size={16} />
</button>
</div>
)}
{uploadError && (
<div className="mb-4 p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg text-sm text-red-600 dark:text-red-400">
{uploadError}
</div>
)}
{/* Input مخفی فایل */}
<input
type="file"
ref={fileInputRef}
onChange={handleFileSelect}
accept="image/*,audio/*,.pdf,.txt,.md"
className="hidden"
/>
<form onSubmit={handleSubmit} className="flex items-end space-x-2">
{/* دکمه ضمیمه */}
<button
type="button"
onClick={() => fileInputRef.current?.click()}
disabled={uploading}
className="p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors disabled:opacity-50"
title="Attach file"
>
<Paperclip size={20} />
</button>
{/* Input پیام */}
<div className="flex-1 min-w-0">
<textarea
value={message}
onChange={handleInputChange}
onKeyPress={handleKeyPress}
placeholder="Type a message..."
className="w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-2xl focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent bg-white dark:bg-gray-700 text-gray-900 dark:text-white placeholder-gray-500 dark:placeholder-gray-400 resize-none max-h-32"
rows={1}
disabled={uploading}
/>
</div>
{/* دکمه ارسال */}
<button
type="submit"
disabled={(!message.trim() && !filePreview) || uploading}
className="p-3 bg-primary-500 text-white rounded-full hover:bg-primary-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex-shrink-0"
title="Send message"
>
{uploading ? (
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
) : (
<Send size={20} />
)}
</button>
</form>
{/* نشانگر تایپینگ */}
{isTyping && (
<div className="text-xs text-gray-500 dark:text-gray-400 mt-2 flex items-center">
<span className="mr-2">Typing</span>
<div className="flex space-x-1">
<div className="w-1.5 h-1.5 bg-gray-500 rounded-full animate-bounce" style={{ animationDelay: '0s' }}></div>
<div className="w-1.5 h-1.5 bg-gray-500 rounded-full animate-bounce" style={{ animationDelay: '0.1s' }}></div>
<div className="w-1.5 h-1.5 bg-gray-500 rounded-full animate-bounce" style={{ animationDelay: '0.2s' }}></div>
</div>
</div>
)}
</div>
);
};
export default MessageInput; |