339 lines
14 KiB
TypeScript
339 lines
14 KiB
TypeScript
import { useState, useEffect, useRef } from 'react';
|
|
import { X, Upload, Image as ImageIcon, Trash2, CheckCircle2, Clipboard } from 'lucide-react';
|
|
import { toast } from 'react-hot-toast';
|
|
import api, { BASE_DOMAIN } from '../../services/api';
|
|
import Spinner from './Spinner';
|
|
import Pagination from './Pagination';
|
|
import ConfirmModal from './ConfirmModal';
|
|
|
|
interface Media {
|
|
id: string;
|
|
url: string;
|
|
filename: string;
|
|
createdAt: string;
|
|
}
|
|
|
|
interface MediaSelectorProps {
|
|
isOpen: boolean;
|
|
onClose: () => void;
|
|
onSelect: (url: string) => void;
|
|
multiple?: boolean;
|
|
selectedUrl?: string;
|
|
}
|
|
|
|
export default function MediaSelector({ isOpen, onClose, onSelect, multiple = false, selectedUrl }: MediaSelectorProps) {
|
|
const [mediaList, setMediaList] = useState<Media[]>([]);
|
|
const [isLoading, setIsLoading] = useState(false);
|
|
const [isUploading, setIsUploading] = useState(false);
|
|
const [page, setPage] = useState(1);
|
|
const limit = 10;
|
|
const [pasteStatus, setPasteStatus] = useState<string | null>(null);
|
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
|
const pasteTimerRef = useRef<ReturnType<typeof setTimeout>>(null);
|
|
const [deleteTargetId, setDeleteTargetId] = useState<string | null>(null);
|
|
|
|
const fetchMedia = useCallback(async () => {
|
|
try {
|
|
const res = await api.get('/admin/media');
|
|
if (res.data?.data) {
|
|
setMediaList(res.data.data);
|
|
} else if (Array.isArray(res.data)) {
|
|
setMediaList(res.data);
|
|
}
|
|
} catch (error) {
|
|
console.error('Failed to fetch media:', error);
|
|
}
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
if (!isOpen) return;
|
|
let isSubscribed = true;
|
|
api.get('/admin/media').then(res => {
|
|
if (!isSubscribed) return;
|
|
if (res.data?.data) {
|
|
setMediaList(res.data.data);
|
|
} else if (Array.isArray(res.data)) {
|
|
setMediaList(res.data);
|
|
}
|
|
}).catch(err => {
|
|
console.error('Failed to fetch media:', err);
|
|
}).finally(() => {
|
|
if (isSubscribed) setIsLoading(false);
|
|
});
|
|
return () => {
|
|
isSubscribed = false;
|
|
};
|
|
}, [isOpen]);
|
|
|
|
useEffect(() => {
|
|
if (!isOpen) return;
|
|
|
|
const handlePaste = (e: ClipboardEvent) => {
|
|
const clipboardText = e.clipboardData?.getData('text');
|
|
if (clipboardText && (clipboardText.startsWith('http://') || clipboardText.startsWith('https://'))) {
|
|
e.preventDefault();
|
|
setPasteStatus('لینک تصویر چسبانده شد!');
|
|
onSelect(clipboardText);
|
|
if (!multiple) onClose();
|
|
if (pasteTimerRef.current) clearTimeout(pasteTimerRef.current);
|
|
pasteTimerRef.current = setTimeout(() => setPasteStatus(null), 3000);
|
|
return;
|
|
}
|
|
|
|
const items = e.clipboardData?.items;
|
|
if (!items) return;
|
|
|
|
for (const item of Array.from(items)) {
|
|
if (item.type.startsWith('image/')) {
|
|
e.preventDefault();
|
|
setPasteStatus('در حال آپلود از کلیپبورد...');
|
|
const file = item.getAsFile();
|
|
if (!file) continue;
|
|
const formData = new FormData();
|
|
formData.append('file', file, `clipboard-${Date.now()}.png`);
|
|
api.post('/admin/media/upload', formData, {
|
|
headers: { 'Content-Type': 'multipart/form-data' }
|
|
}).then(() => {
|
|
setPasteStatus('آپلود موفق!');
|
|
fetchMedia();
|
|
}).catch(() => {
|
|
setPasteStatus('خطا در آپلود');
|
|
}).finally(() => {
|
|
if (pasteTimerRef.current) clearTimeout(pasteTimerRef.current);
|
|
pasteTimerRef.current = setTimeout(() => setPasteStatus(null), 3000);
|
|
});
|
|
break;
|
|
}
|
|
}
|
|
};
|
|
|
|
document.addEventListener('paste', handlePaste);
|
|
return () => {
|
|
document.removeEventListener('paste', handlePaste);
|
|
if (pasteTimerRef.current) clearTimeout(pasteTimerRef.current);
|
|
};
|
|
}, [isOpen, multiple, onClose, onSelect, fetchMedia]);
|
|
|
|
const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
|
if (!e.target.files || e.target.files.length === 0) return;
|
|
const file = e.target.files[0];
|
|
const formData = new FormData();
|
|
formData.append('file', file);
|
|
|
|
try {
|
|
setIsUploading(true);
|
|
await api.post('/admin/media/upload', formData, {
|
|
headers: { 'Content-Type': 'multipart/form-data' }
|
|
});
|
|
toast.success('تصویر با موفقیت آپلود شد');
|
|
fetchMedia();
|
|
} catch (error) {
|
|
console.error('Upload failed', error);
|
|
toast.error('خطا در آپلود تصویر');
|
|
} finally {
|
|
setIsUploading(false);
|
|
if (fileInputRef.current) fileInputRef.current.value = '';
|
|
}
|
|
};
|
|
|
|
const confirmDelete = async () => {
|
|
if (!deleteTargetId) return;
|
|
try {
|
|
await api.delete(`/admin/media/${deleteTargetId}`);
|
|
toast.success('تصویر با موفقیت حذف شد');
|
|
setMediaList(mediaList.filter(m => m.id !== deleteTargetId));
|
|
} catch (error) {
|
|
console.error('Delete failed', error);
|
|
toast.error('خطا در حذف تصویر');
|
|
} finally {
|
|
setDeleteTargetId(null);
|
|
}
|
|
};
|
|
|
|
const [isDragOver, setIsDragOver] = useState(false);
|
|
|
|
const handleDragOver = (e: React.DragEvent) => {
|
|
e.preventDefault();
|
|
setIsDragOver(true);
|
|
};
|
|
|
|
const handleDragLeave = (e: React.DragEvent) => {
|
|
e.preventDefault();
|
|
setIsDragOver(false);
|
|
};
|
|
|
|
const handleDrop = async (e: React.DragEvent) => {
|
|
e.preventDefault();
|
|
setIsDragOver(false);
|
|
if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
|
|
const file = e.dataTransfer.files[0];
|
|
if (file.type.startsWith('image/')) {
|
|
const formData = new FormData();
|
|
formData.append('file', file);
|
|
try {
|
|
setIsUploading(true);
|
|
await api.post('/admin/media/upload', formData, {
|
|
headers: { 'Content-Type': 'multipart/form-data' }
|
|
});
|
|
toast.success('تصویر با موفقیت آپلود شد');
|
|
fetchMedia();
|
|
} catch {
|
|
toast.error('خطا در آپلود تصویر');
|
|
} finally {
|
|
setIsUploading(false);
|
|
}
|
|
}
|
|
}
|
|
};
|
|
|
|
if (!isOpen) return null;
|
|
|
|
return (
|
|
<div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-gray-900/60 backdrop-blur-sm transition-opacity">
|
|
<div
|
|
onDragOver={handleDragOver}
|
|
onDragLeave={handleDragLeave}
|
|
onDrop={handleDrop}
|
|
className={`bg-white rounded-2xl shadow-2xl w-full max-w-4xl max-h-[85vh] flex flex-col overflow-hidden animate-in fade-in zoom-in duration-200 relative transition-all ${isDragOver ? 'ring-4 ring-purple-500 scale-[1.01]' : ''}`}
|
|
>
|
|
{isDragOver && (
|
|
<div className="absolute inset-0 z-50 bg-purple-600/90 backdrop-blur-xs flex flex-col items-center justify-center text-white pointer-events-none animate-in fade-in">
|
|
<Upload className="w-16 h-16 mb-2 animate-bounce" />
|
|
<p className="text-xl font-bold">تصویر را اینجا رها کنید تا آپلود شود</p>
|
|
</div>
|
|
)}
|
|
|
|
{/* Header */}
|
|
<div className="px-6 py-4 border-b border-gray-100 flex items-center justify-between bg-gray-50/50">
|
|
<div className="flex items-center gap-3">
|
|
<div className="w-10 h-10 rounded-xl bg-purple-100 text-purple-600 flex items-center justify-center">
|
|
<ImageIcon className="w-5 h-5" />
|
|
</div>
|
|
<div>
|
|
<h3 className="text-lg font-bold text-gray-900">گالری رسانه</h3>
|
|
<p className="text-xs text-gray-500 font-medium">تصویر مورد نظر را انتخاب یا آپلود کنید</p>
|
|
</div>
|
|
</div>
|
|
<button onClick={onClose} className="p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors">
|
|
<X className="w-5 h-5" />
|
|
</button>
|
|
</div>
|
|
|
|
{/* Toolbar */}
|
|
<div className="p-4 border-b border-gray-100 flex justify-between items-center bg-white">
|
|
<div className="flex items-center gap-3">
|
|
<p className="text-sm font-bold text-gray-600">{mediaList.length} فایل موجود</p>
|
|
{pasteStatus && (
|
|
<span className={`text-xs px-2 py-1 rounded-full font-medium ${pasteStatus.includes('موفق') ? 'bg-green-100 text-green-700' : pasteStatus.includes('خطا') ? 'bg-red-100 text-red-700' : 'bg-blue-100 text-blue-700'}`}>
|
|
{pasteStatus}
|
|
</span>
|
|
)}
|
|
</div>
|
|
<div className="flex items-center gap-3">
|
|
<span className="text-xs text-gray-400 hidden sm:flex items-center gap-1">
|
|
<Clipboard className="w-3.5 h-3.5" />
|
|
Ctrl+V برای چسباندن تصویر
|
|
</span>
|
|
<input
|
|
type="file"
|
|
ref={fileInputRef}
|
|
onChange={handleFileUpload}
|
|
accept="image/*"
|
|
className="hidden"
|
|
/>
|
|
<button
|
|
onClick={() => fileInputRef.current?.click()}
|
|
disabled={isUploading}
|
|
className="bg-purple-600 hover:bg-purple-700 disabled:opacity-70 text-white px-4 py-2 rounded-xl flex items-center gap-2 text-sm font-bold transition-colors"
|
|
>
|
|
{isUploading ? <Spinner size="sm" /> : <Upload className="w-4 h-4" />}
|
|
آپلود تصویر جدید
|
|
</button>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Grid */}
|
|
<div className="p-6 overflow-y-auto flex-1 bg-gray-50/30">
|
|
{isLoading ? (
|
|
<div className="flex justify-center items-center h-40">
|
|
<Spinner size="lg" className="text-purple-600" />
|
|
</div>
|
|
) : mediaList.length === 0 ? (
|
|
<div className="flex flex-col items-center justify-center h-60 text-gray-400">
|
|
<ImageIcon className="w-16 h-16 mb-4 opacity-20" />
|
|
<p className="font-medium text-gray-500">گالری خالی است. اولین عکس را آپلود کنید!</p>
|
|
</div>
|
|
) : (() => {
|
|
const totalPages = Math.ceil(mediaList.length / limit) || 1;
|
|
const paginatedList = mediaList.slice((page - 1) * limit, page * limit);
|
|
return (
|
|
<div className="space-y-4">
|
|
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4">
|
|
{paginatedList.map((media) => {
|
|
const imgUrl = media.url.startsWith('http') ? media.url : `${BASE_DOMAIN}${media.url}`;
|
|
const isSelected = selectedUrl && imgUrl === selectedUrl;
|
|
return (
|
|
<div
|
|
key={media.id}
|
|
onClick={() => {
|
|
onSelect(imgUrl);
|
|
if (!multiple) onClose();
|
|
}}
|
|
className={`group relative bg-gray-100 rounded-xl overflow-hidden border-2 cursor-pointer transition-all hover:shadow-lg hover:shadow-purple-100 ${isSelected ? 'border-purple-600 ring-2 ring-purple-300' : 'border-transparent hover:border-purple-500'}`}
|
|
>
|
|
<div className="aspect-square bg-white p-2 flex items-center justify-center border-b border-gray-100">
|
|
<img
|
|
src={imgUrl}
|
|
alt={media.filename}
|
|
className="max-w-full max-h-full object-contain object-center"
|
|
/>
|
|
<div className="absolute inset-0 bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center gap-3">
|
|
<button
|
|
onClick={(e) => { e.stopPropagation(); setDeleteTargetId(media.id); }}
|
|
className="w-8 h-8 rounded-full bg-red-500 text-white flex items-center justify-center hover:bg-red-600 transform hover:scale-110 transition-transform"
|
|
>
|
|
<Trash2 className="w-4 h-4" />
|
|
</button>
|
|
<button
|
|
className="w-8 h-8 rounded-full bg-purple-500 text-white flex items-center justify-center hover:bg-purple-600 transform hover:scale-110 transition-transform"
|
|
>
|
|
<CheckCircle2 className="w-4 h-4" />
|
|
</button>
|
|
</div>
|
|
{isSelected && (
|
|
<div className="absolute top-2 left-2 bg-purple-600 text-white text-[10px] font-bold px-2 py-0.5 rounded-full shadow-lg">
|
|
انتخاب شده
|
|
</div>
|
|
)}
|
|
</div>
|
|
<div className="p-2 border-t border-gray-100 bg-white" dir="ltr">
|
|
<p className="text-[11px] text-gray-500 truncate font-medium" title={media.filename}>
|
|
{media.filename}
|
|
</p>
|
|
<p className="text-[10px] text-gray-400 mt-0.5">
|
|
{new Date(media.createdAt).toLocaleDateString('fa-IR')}
|
|
</p>
|
|
</div>
|
|
</div>
|
|
);
|
|
})}
|
|
</div>
|
|
<Pagination currentPage={page} totalPages={totalPages} onPageChange={setPage} />
|
|
</div>
|
|
);
|
|
})()}
|
|
</div>
|
|
|
|
</div>
|
|
|
|
<ConfirmModal
|
|
isOpen={!!deleteTargetId}
|
|
title="حذف تصویر"
|
|
message="آیا از حذف این تصویر مطمئن هستید؟ این عملیات قابل بازگشت نیست."
|
|
onConfirm={confirmDelete}
|
|
onCancel={() => setDeleteTargetId(null)}
|
|
/>
|
|
</div>
|
|
);
|
|
}
|