Spaces:
Sleeping
Sleeping
File size: 10,964 Bytes
471f166 c107c22 471f166 |
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 |
import React, { useRef, useState, useCallback, useEffect } from 'react'
import { useDropzone } from 'react-dropzone'
import { Send, Plus, X, ImageIcon, Paperclip, UploadCloud } from 'lucide-react'
const MAX_IMAGES = 5
const ChatInput = ({ onSendMessage, isLoading, onImageClick }) => {
const [input, setInput] = useState(() => sessionStorage.getItem('chat_draft') || '')
const [uploadedImages, setUploadedImages] = useState([])
const [showAttachMenu, setShowAttachMenu] = useState(false)
const [uploadError, setUploadError] = useState('')
const textareaRef = useRef(null)
// Draft persistence
useEffect(() => {
sessionStorage.setItem('chat_draft', input)
}, [input])
// Initial image restoration
useEffect(() => {
const savedImages = sessionStorage.getItem('chat_images')
if (savedImages) {
try {
const parsed = JSON.parse(savedImages)
const restored = parsed.map(img => {
// Convert base64 back to Blob/File if needed, or just use data URL as preview
return {
file: null, // Original file is lost on refresh, but we have the data
preview: img.data,
name: img.name,
type: img.type
}
})
setUploadedImages(restored)
} catch (e) {
console.error('Failed to restore images:', e)
}
}
}, [])
// Image persistence (Base64)
useEffect(() => {
if (uploadedImages.length === 0) {
sessionStorage.removeItem('chat_images')
return
}
// Only save images that have a preview (base64 or blob URL)
// If it's a blob URL, it won't survive refresh, so we need to ensure they are base64 when adding
const persistImages = async () => {
const dataToSave = await Promise.all(uploadedImages.map(async (img) => {
if (img.preview.startsWith('data:')) {
return { name: img.name, type: img.type, data: img.preview }
}
// If it's a blob URL, we should have converted it already on drop
return { name: img.name, type: img.type, data: img.preview }
}))
sessionStorage.setItem('chat_images', JSON.stringify(dataToSave))
}
persistImages()
}, [uploadedImages])
// Auto-resize textarea
useEffect(() => {
if (textareaRef.current) {
textareaRef.current.style.height = 'auto'
textareaRef.current.style.height = Math.min(textareaRef.current.scrollHeight, 200) + 'px'
}
}, [input])
// Clear error after 3 seconds
useEffect(() => {
if (uploadError) {
const timer = setTimeout(() => setUploadError(''), 3000)
return () => clearTimeout(timer)
}
}, [uploadError])
// Close menu when clicking outside
useEffect(() => {
const handleClickOutside = (e) => {
if (showAttachMenu && !e.target.closest('.attach-btn-wrapper')) {
setShowAttachMenu(false)
}
}
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
}, [showAttachMenu])
const handleKeyDown = (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault()
handleSubmit()
}
}
const onDrop = useCallback((acceptedFiles) => {
const processFiles = async () => {
const newImagesPromises = acceptedFiles.map(file => {
return new Promise((resolve) => {
const reader = new FileReader()
reader.onloadend = () => {
resolve({
file,
preview: reader.result,
name: file.name,
type: file.type
})
}
reader.readAsDataURL(file)
})
})
const newImages = await Promise.all(newImagesPromises)
setUploadedImages(prev => {
const remaining = MAX_IMAGES - prev.length
if (remaining <= 0) {
setUploadError(`Bạn chỉ được tải tối đa ${MAX_IMAGES} ảnh`)
return prev
}
if (newImages.length > remaining) {
setUploadError(`Chỉ nhận thêm ${remaining} ảnh cuối cùng`)
}
return [...prev, ...newImages.slice(0, remaining)]
})
}
processFiles()
setShowAttachMenu(false)
}, [])
const { getRootProps, getInputProps, isDragActive, open: openFilePicker } = useDropzone({
onDrop,
accept: { 'image/*': ['.png', '.jpg', '.jpeg', '.gif', '.webp'] },
maxFiles: MAX_IMAGES,
noClick: true,
noKeyboard: true,
disabled: uploadedImages.length >= MAX_IMAGES,
})
const removeImage = (index) => {
setUploadedImages(prev => prev.filter((_, i) => i !== index))
}
const clearAllImages = () => {
setUploadedImages([])
}
const handleSubmit = () => {
if ((!input.trim() && uploadedImages.length === 0) || isLoading) return
onSendMessage(input, uploadedImages)
// Clear persistence
setInput('')
setUploadedImages([])
sessionStorage.removeItem('chat_draft')
sessionStorage.removeItem('chat_images')
if (textareaRef.current) textareaRef.current.style.height = 'auto'
}
return (
<div className="input-container">
{/* Image Previews & Counter */}
{uploadedImages.length > 0 && (
<div className="image-attachment-area">
<div className="attachment-header">
<span className="attachment-counter">
Đã đính kèm: <strong>{uploadedImages.length}/{MAX_IMAGES}</strong> ảnh
</span>
<button type="button" className="clear-all-btn" onClick={clearAllImages}>
Xóa hết
</button>
</div>
<div className="uploaded-images-preview">
{uploadedImages.map((img, idx) => (
<div
key={idx}
className="preview-item clickable"
onClick={() => onImageClick?.(uploadedImages.map(img => img.preview), idx)}
title="Xem ảnh lớn"
>
<img src={img.preview} alt={`Preview ${idx + 1}`} />
<button
type="button"
className="remove-img-btn"
onClick={(e) => {
e.stopPropagation()
removeImage(idx)
}}
title="Xóa ảnh"
>
<X size={12} />
</button>
</div>
))}
</div>
</div>
)}
{/* Upload Error Message */}
{uploadError && (
<div className="upload-error-toast">
{uploadError}
</div>
)}
<div className={`input-wrapper ${isLoading ? 'opacity-50' : ''}`} {...getRootProps()} id="tour-chat-input-area">
<input {...getInputProps()} />
{/* Drag Overlay - Compact & Premium */}
{isDragActive && (
<div className="drag-overlay">
<div className="drag-content">
<UploadCloud size={24} className="drag-icon" />
<span className="drag-text">Thả ảnh vào đây</span>
</div>
</div>
)}
<div className="attach-btn-wrapper">
<button
type="button"
className="attach-btn"
onClick={(e) => {
e.stopPropagation();
setShowAttachMenu(!showAttachMenu);
}}
title="Đính kèm"
id="tour-attach"
>
<Plus size={20} className={showAttachMenu ? 'rotate-45 transition-transform' : 'transition-transform'} />
</button>
{showAttachMenu && (
<div className="attachment-menu">
<button type="button" onClick={(e) => { e.stopPropagation(); openFilePicker(); setShowAttachMenu(false) }}>
<ImageIcon size={18} /> Ảnh/Video
</button>
<button type="button" onClick={(e) => { e.stopPropagation(); setShowAttachMenu(false) }} className="opacity-50 cursor-not-allowed">
<Paperclip size={18} /> Tài liệu (Sắp ra mắt)
</button>
</div>
)}
</div>
<textarea
ref={textareaRef}
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Nhập tin nhắn..."
rows={1}
disabled={isLoading}
id="tour-chat-input"
/>
<button
type="button"
className="send-btn"
onClick={(e) => {
e.stopPropagation(); // Prevent bubbling to dropzone
handleSubmit();
}}
disabled={isLoading || (!input.trim() && uploadedImages.length === 0)}
title="Gửi"
id="tour-send"
>
<Send size={18} />
</button>
</div>
<p className="input-hint">
Pochi không phải lúc nào cũng đúng. Hãy tập thói quen double check nhé!
</p>
</div>
)
}
export default ChatInput
|