Files
canina/frontend/admin-panel/src/components/ui/MediaSelector.tsx
T

568 lines
24 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { CheckCircle2,Clipboard,Eye,FileText,Image as ImageIcon,Music,Play,Trash2,Upload,X } from 'lucide-react';
import { useCallback,useEffect,useRef,useState } from 'react';
import { toast } from 'react-hot-toast';
import api,{ BASE_DOMAIN } from '../../services/api';
import ConfirmModal from './ConfirmModal';
import ImagePreviewModal from './ImagePreviewModal';
import Pagination from './Pagination';
import Spinner from './Spinner';
interface Media {
id: string;
url: string;
filename: string;
createdAt: string;
mimetype?: string;
}
interface MediaSelectorProps {
isOpen: boolean;
onClose: () => void;
onSelect: (url: string) => void;
multiple?: boolean;
selectedUrl?: string;
acceptedTypes?: 'all' | 'image' | 'video' | 'audio' | 'document';
}
function getFileType(filename: string, mimetype?: string): 'image' | 'video' | 'audio' | 'pdf' | 'other' {
const ext = filename.split('.').pop()?.toLowerCase() || '';
if (mimetype?.startsWith('video/') || ['mp4', 'webm', 'ogg', 'mov', 'mkv', 'avi'].includes(ext)) return 'video';
if (mimetype?.startsWith('audio/') || ['mp3', 'wav', 'ogg', 'm4a', 'aac'].includes(ext)) return 'audio';
if (mimetype === 'application/pdf' || ext === 'pdf') return 'pdf';
if (mimetype?.startsWith('image/') || ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'].includes(ext)) return 'image';
return 'other';
}
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 = 12;
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 [previewUrl, setPreviewUrl] = useState<string | null>(null);
const [uploadProgress, setUploadProgress] = useState<number | null>(null);
const [filterType, setFilterType] = useState<'all' | 'image' | 'video' | 'audio' | 'pdf'>('all');
const [dragOver, setDragOver] = useState(false);
const [pendingSelectedUrl, setPendingSelectedUrl] = useState<string | null>(selectedUrl || null);
useEffect(() => {
if (selectedUrl) {
setPendingSelectedUrl(selectedUrl);
}
}, [selectedUrl]);
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;
setIsLoading(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>) => {
const files = e.target.files;
if (!files || files.length === 0) return;
setIsUploading(true);
setUploadProgress(10);
let successCount = 0;
try {
const uploadPromises = Array.from(files).map(async (file) => {
const formData = new FormData();
formData.append('file', file);
return api.post('/admin/media/upload', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
onUploadProgress: (progressEvent) => {
const total = progressEvent.total || file.size;
const percent = Math.round((progressEvent.loaded * 100) / total);
setUploadProgress(percent);
}
});
});
const results = await Promise.allSettled(uploadPromises);
results.forEach((res) => {
if (res.status === 'fulfilled') successCount++;
});
if (successCount > 0) {
toast.success(`${successCount} فایل با موفقیت بارگذاری شد`);
await fetchMedia();
}
if (successCount < files.length) {
toast.error(`خطا در بارگذاری ${files.length - successCount} فایل`);
}
} catch (error) {
console.error('Upload failed', error);
toast.error('خطا در بارگذاری فایل‌ها');
} finally {
setIsUploading(false);
setUploadProgress(null);
if (fileInputRef.current) fileInputRef.current.value = '';
}
};
const confirmDelete = async () => {
if (!deleteTargetId) return;
try {
await api.delete(`/admin/media/${deleteTargetId}`);
toast.success('فایل با موفقیت حذف شد');
setMediaList(prev => prev.filter(item => item.id !== deleteTargetId));
} catch (error) {
console.error('Failed to delete media:', error);
toast.error('خطا در حذف فایل');
} finally {
setDeleteTargetId(null);
}
};
const handleDrop = async (e: React.DragEvent) => {
e.preventDefault();
setDragOver(false);
if (!e.dataTransfer.files || e.dataTransfer.files.length === 0) return;
const files = Array.from(e.dataTransfer.files);
if (files.length === 0) return;
const ALLOWED_MIME_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/svg+xml', 'image/gif', 'application/pdf'];
const MAX_FILE_SIZE = 15 * 1024 * 1024; // 15MB
const validFiles = files.filter(f => {
if (!ALLOWED_MIME_TYPES.includes(f.type) && !f.type.startsWith('image/')) {
toast.error(`فرمت فایل ${f.name} مجاز نمی‌باشد.`);
return false;
}
if (f.size > MAX_FILE_SIZE) {
toast.error(`حجم فایل ${f.name} بیش از حد مجاز (حداکثر ۱۵ مگابایت) است.`);
return false;
}
return true;
});
if (validFiles.length === 0) return;
setIsUploading(true);
let successCount = 0;
try {
const uploadPromises = files.map(async (file) => {
const formData = new FormData();
formData.append('file', file);
return api.post('/admin/media/upload', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
onUploadProgress: (progressEvent) => {
const total = progressEvent.total || file.size;
const percent = Math.round((progressEvent.loaded * 100) / total);
setUploadProgress(percent);
}
});
});
const results = await Promise.allSettled(uploadPromises);
results.forEach(res => {
if (res.status === 'fulfilled') successCount++;
});
if (successCount > 0) {
toast.success(`${successCount} فایل با موفقیت بارگذاری شد`);
await fetchMedia();
}
if (successCount < files.length) {
toast.error(`خطا در بارگذاری ${files.length - successCount} فایل`);
}
} catch (error) {
console.error('Drop upload failed', error);
toast.error('خطا در آپلود فایل‌های رها شده');
} finally {
setIsUploading(false);
setUploadProgress(null);
}
};
if (!isOpen) return null;
const filteredMedia = (() => {
const list = mediaList.filter(m => {
if (filterType === 'all') return true;
return getFileType(m.filename, m.mimetype) === filterType;
});
const seen = new Set<string>();
return list.filter(m => {
const key = (m.url || '').trim().toLowerCase();
if (!key) return true;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
})();
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/60 backdrop-blur-xs font-vazir"
onDragOver={(e) => { e.preventDefault(); setDragOver(true); }}
onDragLeave={() => setDragOver(false)}
onDrop={handleDrop}
>
<div className="bg-white rounded-3xl max-w-5xl w-full max-h-[90vh] flex flex-col shadow-2xl overflow-hidden border border-gray-100 relative animate-in fade-in zoom-in-95 duration-200">
{/* Drag overlay */}
{dragOver && (
<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">فایل‌ها (تصویر، ویدئو، پادکست، PDF) را اینجا رها کنید تا آپلود شوند</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">تصویر، ویدئو، پادکست صوتی یا PDF مورد نظر را انتخاب یا آپلود کنید</p>
</div>
</div>
<button onClick={onClose} className="p-2 text-gray-400 hover:text-red-500 hover:bg-red-50 rounded-xl transition-colors cursor-pointer">
<X className="w-5 h-5" />
</button>
</div>
{/* Toolbar & Filter Tabs */}
<div className="p-4 border-b border-gray-100 flex justify-between items-center bg-white flex-wrap gap-3">
<div className="flex items-center gap-2 flex-wrap">
{[
{ id: 'all', label: 'همه فایل‌ها' },
{ id: 'image', label: 'تصاویر' },
{ id: 'video', label: 'ویدئوها' },
{ id: 'audio', label: 'پادکست/صدا' },
{ id: 'pdf', label: 'اسناد PDF' },
].map(tab => (
<button
key={tab.id}
type="button"
onClick={() => { setFilterType(tab.id as any); setPage(1); }}
className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all cursor-pointer ${
filterType === tab.id
? 'bg-purple-600 text-white shadow-xs'
: 'bg-gray-100 text-gray-600 hover:bg-gray-200'
}`}
>
{tab.label}
</button>
))}
{pasteStatus && (
<span className={`text-xs px-2.5 py-1 rounded-full font-medium ${pasteStatus.includes('موفق') ? 'bg-green-100 text-green-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/*,video/*,audio/*,application/pdf"
multiple
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.5 rounded-xl flex items-center gap-2 text-sm font-bold transition-all shadow-md shadow-purple-200 cursor-pointer"
>
{isUploading ? (
<>
<Spinner size="sm" />
<span>در حال آپلود {uploadProgress ? `(${uploadProgress}٪)` : ''}...</span>
</>
) : (
<>
<Upload className="w-4 h-4" />
<span>آپلود فایل جدید</span>
</>
)}
</button>
</div>
</div>
{/* Upload Progress Bar if active */}
{isUploading && uploadProgress !== null && (
<div className="w-full bg-gray-100 h-1.5 overflow-hidden">
<div
className="bg-purple-600 h-full transition-all duration-300"
style={{ width: `${uploadProgress}%` }}
/>
</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>
) : filteredMedia.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(filteredMedia.length / limit) || 1;
const paginatedList = filteredMedia.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-6 gap-4">
{paginatedList.map((media) => {
const fileUrl = media.url.startsWith('http') ? media.url : `${BASE_DOMAIN}${media.url}`;
const isSelected =
(pendingSelectedUrl && (fileUrl === pendingSelectedUrl || media.url === pendingSelectedUrl)) ||
(selectedUrl && (fileUrl === selectedUrl || media.url === selectedUrl));
const fileType = getFileType(media.filename, media.mimetype);
return (
<div
key={media.id}
onClick={() => {
setPendingSelectedUrl(fileUrl);
}}
onDoubleClick={() => {
onSelect(fileUrl);
if (!multiple) onClose();
}}
className={`group relative bg-white rounded-2xl overflow-hidden border-2 cursor-pointer transition-all hover:shadow-lg hover:shadow-purple-100 ${
isSelected ? 'border-purple-600 ring-2 ring-purple-300 shadow-md shadow-purple-100' : 'border-gray-200 hover:border-purple-400'
}`}
>
{/* Top Action Icons */}
<div className="absolute top-2 left-2 right-2 flex items-center justify-between z-10 pointer-events-none">
<button
type="button"
onClick={(e) => {
e.stopPropagation();
setPreviewUrl(fileUrl);
}}
className="pointer-events-auto p-1.5 rounded-lg bg-black/50 hover:bg-black/80 text-white backdrop-blur-xs transition-colors"
title="مشاهده"
>
<Eye className="w-3.5 h-3.5" />
</button>
<button
type="button"
onClick={(e) => {
e.stopPropagation();
setDeleteTargetId(media.id);
}}
className="pointer-events-auto p-1.5 rounded-lg bg-red-600/80 hover:bg-red-600 text-white backdrop-blur-xs transition-colors"
title="حذف فایل"
>
<Trash2 className="w-3.5 h-3.5" />
</button>
</div>
{/* Thumbnail View per File Type */}
<div className="aspect-square bg-gray-50 p-2 flex items-center justify-center border-b border-gray-100 relative overflow-hidden">
{fileType === 'image' ? (
<img
src={fileUrl}
alt={media.filename}
className="max-w-full max-h-full object-contain object-center"
loading="lazy"
/>
) : fileType === 'video' ? (
<div className="relative w-full h-full flex items-center justify-center bg-gray-900 rounded-xl overflow-hidden">
<video
src={fileUrl}
preload="metadata"
className="w-full h-full object-cover opacity-75"
/>
<div className="absolute inset-0 flex items-center justify-center">
<div className="w-8 h-8 rounded-full bg-purple-600/90 text-white flex items-center justify-center shadow-lg">
<Play className="w-4 h-4 fill-white ml-0.5" />
</div>
</div>
<span className="absolute bottom-1 right-1 bg-black/70 text-white text-[9px] px-1.5 py-0.5 rounded font-mono font-bold">
VIDEO
</span>
</div>
) : fileType === 'audio' ? (
<div className="flex flex-col items-center justify-center text-amber-600 gap-1">
<Music className="w-10 h-10" />
<span className="text-[10px] font-black uppercase text-amber-700">Audio / Podcast</span>
</div>
) : fileType === 'pdf' ? (
<div className="flex flex-col items-center justify-center text-rose-600 gap-1">
<FileText className="w-10 h-10" />
<span className="text-[10px] font-black uppercase text-rose-700">PDF Document</span>
</div>
) : (
<div className="flex flex-col items-center justify-center text-gray-400 gap-1">
<FileText className="w-10 h-10" />
<span className="text-[10px] font-black uppercase text-gray-500">File</span>
</div>
)}
{isSelected && (
<div className="absolute bottom-2 right-2 bg-purple-600 text-white text-[10px] font-bold px-2 py-0.5 rounded-full shadow-lg flex items-center gap-1">
<CheckCircle2 className="w-3 h-3" />
انتخاب شده
</div>
)}
</div>
{/* File details footer */}
<div className="p-2.5 border-t border-gray-100 bg-white" dir="ltr">
<p className="text-[11px] text-gray-700 truncate font-medium" title={media.filename}>
{media.filename}
</p>
<p className="text-[10px] text-gray-400 mt-0.5 text-right font-vazir">
{new Date(media.createdAt).toLocaleDateString('fa-IR')}
</p>
</div>
</div>
);
})}
</div>
<Pagination currentPage={page} totalPages={totalPages} onPageChange={setPage} />
</div>
);
})()}
</div>
{/* Modal Action Footer */}
<div className="px-6 py-3.5 border-t border-gray-200 bg-gray-50 flex items-center justify-between shrink-0">
<div className="flex items-center gap-2 text-xs text-gray-500 font-medium">
{pendingSelectedUrl ? (
<span className="flex items-center gap-1.5 text-purple-700 font-bold">
<CheckCircle2 className="w-4 h-4 text-purple-600" />
<span>۱ فایل انتخاب شد (آماده تایید)</span>
</span>
) : (
<span>روی هر کارت کلیک کنید تا انتخاب شود یا با دابل‌کلیک بلافاصله ثبت کنید.</span>
)}
</div>
<div className="flex items-center gap-2">
<button
type="button"
onClick={onClose}
className="px-4 py-2 rounded-xl text-xs font-bold bg-white hover:bg-gray-100 text-gray-700 border border-gray-300 transition cursor-pointer"
>
انصراف
</button>
<button
type="button"
disabled={!pendingSelectedUrl}
onClick={() => {
if (pendingSelectedUrl) {
onSelect(pendingSelectedUrl);
if (!multiple) onClose();
}
}}
className="px-5 py-2 rounded-xl text-xs font-bold bg-purple-600 hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed text-white transition shadow-sm cursor-pointer flex items-center gap-1.5"
>
<CheckCircle2 className="w-4 h-4" />
<span>انتخاب و ثبت فایل</span>
</button>
</div>
</div>
</div>
<ConfirmModal
isOpen={!!deleteTargetId}
title="حذف تصویر"
message="آیا از حذف این تصویر مطمئن هستید؟ این عملیات قابل بازگشت نیست."
onConfirm={confirmDelete}
onCancel={() => setDeleteTargetId(null)}
/>
<ImagePreviewModal
isOpen={!!previewUrl}
imageUrl={previewUrl || ''}
onClose={() => setPreviewUrl(null)}
/>
</div>
);
}