feat(admin): file manager — search, type tabs (image/video/AE), library picker

- FileManager: type tabs (همه/تصاویر/ویدیوها/صدا/پروژه‌های AE و سایر) + name
  search (uses file_type + search params the file svc already supports; type
  values capitalized to match the enum), video thumbnails via <video>, AE/zip
  shown under "AE و سایر"; delete + copy-URL retained
- FilePicker: reusable modal to re-choose an existing file from the library
  (search + filter + click to pick)
- FileUploadField: new "از کتابخانه" button on every upload field → pick from
  library instead of re-uploading; picker auto-filters by the field's accept
- shared src/lib/admin-files.ts helpers (fileUrl/isImage/isVideo/fetchFiles)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
soroush.asadi
2026-06-03 01:11:47 +03:30
parent ffc0c5d6d5
commit e5812488eb
4 changed files with 193 additions and 37 deletions
+29 -37
View File
@@ -2,56 +2,31 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { MINIO_PUBLIC_URL } from "@/lib/files";
interface FileItem {
id: string;
name: string;
mime_type?: string;
file_type?: string;
size_bytes?: number;
minio_bucket?: string;
minio_key?: string;
created_at?: string;
}
import { FILE_TYPE_TABS, fetchFiles, fileUrl, humanSize, isImage, isVideo, type FileItem } from "@/lib/admin-files";
const card = "rounded-xl border border-[#1e2235] bg-[#0f1120]";
const btn = "rounded-lg bg-indigo-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-indigo-500 disabled:opacity-50";
function fileUrl(f: FileItem): string | null {
if (!f.minio_key) return null;
return `${MINIO_PUBLIC_URL}/${f.minio_bucket ?? "user-uploads"}/${f.minio_key}`;
}
function isImage(f: FileItem): boolean {
return (f.mime_type ?? "").startsWith("image/") || /\.(png|jpe?g|gif|webp|svg|avif)$/i.test(f.name);
}
function humanSize(n?: number): string {
if (!n) return "—";
const u = ["B", "KB", "MB", "GB"]; let i = 0; let v = n;
while (v >= 1024 && i < u.length - 1) { v /= 1024; i++; }
return `${v.toFixed(v < 10 && i > 0 ? 1 : 0)} ${u[i]}`;
}
export function FileManager() {
const [files, setFiles] = useState<FileItem[]>([]);
const [loading, setLoading] = useState(true);
const [uploading, setUploading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [copied, setCopied] = useState<string | null>(null);
const [search, setSearch] = useState("");
const [type, setType] = useState("");
const inputRef = useRef<HTMLInputElement>(null);
const reload = useCallback(async () => {
setLoading(true);
try {
const res = await fetch("/api/admin/resource/files", { cache: "no-store" });
const data = await res.json();
setFiles(data?.data ?? data?.items ?? (Array.isArray(data) ? data : []));
setFiles(await fetchFiles(search, type));
} catch {
setError("بارگذاری فایل‌ها ناموفق بود");
} finally {
setLoading(false);
}
}, []);
}, [search, type]);
useEffect(() => { reload(); }, [reload]);
@@ -85,16 +60,31 @@ export function FileManager() {
};
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<div className="space-y-4" dir="rtl">
<div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 className="text-xl font-semibold text-white">کتابخانه رسانه</h1>
<p className="mt-1 text-sm text-gray-400">آپلود و مدیریت تصاویر و فایلها. نشانیهای عمومی را میتوان در هر فیلدی کپی کرد.</p>
<p className="mt-1 text-sm text-gray-400">آپلود و مدیریت تصاویر، ویدیوها و پروژههای افترافکت. نشانی هر فایل را میتوان در فرمها استفاده کرد.</p>
</div>
<button className={btn} onClick={() => inputRef.current?.click()} disabled={uploading}>
{uploading ? "در حال آپلود…" : "+ آپلود فایل"}
</button>
<input ref={inputRef} type="file" multiple className="hidden" onChange={(e) => e.target.files && uploadFiles(e.target.files)} />
<input ref={inputRef} type="file" multiple className="hidden" accept="image/*,video/*,audio/*,.aep,.aepx,.zip" onChange={(e) => e.target.files && uploadFiles(e.target.files)} />
</div>
<div className="flex flex-wrap items-center gap-2">
<div className="flex flex-wrap gap-1">
{FILE_TYPE_TABS.map((t) => (
<button key={t.v} onClick={() => setType(t.v)}
className={`rounded-lg px-3 py-1.5 text-xs ${type === t.v ? "bg-indigo-600 text-white" : "border border-[#262b40] text-gray-400 hover:bg-[#161a2e]"}`}>
{t.l}
</button>
))}
</div>
<input
className="ms-auto w-56 rounded-lg border border-[#262b40] bg-[#0c0e1a] px-3 py-2 text-sm text-gray-100 outline-none focus:border-indigo-500"
placeholder="جستجوی نام فایل…" value={search} onChange={(e) => setSearch(e.target.value)}
/>
</div>
{error && <p className="rounded-lg bg-red-500/10 px-3 py-2 text-sm text-red-300">{error}</p>}
@@ -107,7 +97,7 @@ export function FileManager() {
{loading ? (
<p className="py-10 text-center text-sm text-gray-500">در حال بارگذاری</p>
) : files.length === 0 ? (
<p className="py-10 text-center text-sm text-gray-500">هنوز فایلی وجود ندارد. فایل را اینجا بکشید و رها کنید یا روی آپلود بزنید.</p>
<p className="py-10 text-center text-sm text-gray-500">فایلی یافت نشد. فایل را اینجا بکشید و رها کنید یا روی آپلود بزنید.</p>
) : (
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6">
{files.map((f) => {
@@ -118,12 +108,14 @@ export function FileManager() {
{url && isImage(f) ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={url} alt={f.name} className="h-full w-full object-cover" />
) : url && isVideo(f) ? (
<video src={url} className="h-full w-full object-cover" muted preload="metadata" />
) : (
<span className="text-[10px] uppercase text-gray-600">{(f.name.split(".").pop() ?? "file").slice(0, 5)}</span>
<span className="text-[10px] uppercase text-gray-500">{(f.name.split(".").pop() ?? "file").slice(0, 5)}</span>
)}
</div>
<p className="mt-1.5 truncate text-[11px] text-gray-300" title={f.name}>{f.name}</p>
<p className="text-[10px] text-gray-600">{humanSize(f.size_bytes)}</p>
<p className="text-[10px] text-gray-600">{f.file_type ?? "—"} · {humanSize(f.size_bytes)}</p>
<div className="mt-1 flex gap-1">
{url && (
<button className="flex-1 rounded border border-[#262b40] px-1 py-0.5 text-[10px] text-gray-400 hover:bg-[#161a2e]" onClick={() => copy(url)}>
+85
View File
@@ -0,0 +1,85 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { FILE_TYPE_TABS, fetchFiles, fileUrl, humanSize, isImage, isVideo, type FileItem } from "@/lib/admin-files";
/** Modal to pick an existing file from the media library (search + type filter). */
export function FilePicker({
open,
onClose,
onSelect,
initialType = "",
}: {
open: boolean;
onClose: () => void;
onSelect: (url: string, file: FileItem) => void;
initialType?: string;
}) {
const [files, setFiles] = useState<FileItem[]>([]);
const [search, setSearch] = useState("");
const [type, setType] = useState(initialType);
const [loading, setLoading] = useState(false);
const load = useCallback(async () => {
setLoading(true);
setFiles(await fetchFiles(search, type));
setLoading(false);
}, [search, type]);
useEffect(() => { if (open) load(); }, [open, load]);
if (!open) return null;
return (
<div className="fixed inset-0 z-[60] flex items-stretch justify-center bg-black/70 p-2 sm:p-6" dir="rtl" onClick={onClose}>
<div className="flex max-h-full w-full max-w-4xl flex-col rounded-xl border border-[#1e2235] bg-[#0f1120]" onClick={(e) => e.stopPropagation()}>
<div className="flex flex-wrap items-center gap-2 border-b border-[#1e2235] px-4 py-3">
<h2 className="text-sm font-semibold text-white">انتخاب از کتابخانه</h2>
<input
className="ms-auto w-48 rounded-lg border border-[#262b40] bg-[#0c0e1a] px-3 py-1.5 text-sm text-gray-100 outline-none focus:border-indigo-500"
placeholder="جستجو…" value={search} onChange={(e) => setSearch(e.target.value)}
/>
<button className="rounded-lg px-2 py-1 text-gray-400 hover:bg-[#161a2e] hover:text-white" onClick={onClose}></button>
</div>
<div className="flex flex-wrap gap-1 border-b border-[#1e2235] px-4 py-2">
{FILE_TYPE_TABS.map((t) => (
<button key={t.v} onClick={() => setType(t.v)}
className={`rounded-lg px-2.5 py-1 text-xs ${type === t.v ? "bg-indigo-600 text-white" : "border border-[#262b40] text-gray-400 hover:bg-[#161a2e]"}`}>
{t.l}
</button>
))}
</div>
<div className="flex-1 overflow-y-auto p-4">
{loading ? (
<p className="py-10 text-center text-sm text-gray-500">در حال بارگذاری</p>
) : files.length === 0 ? (
<p className="py-10 text-center text-sm text-gray-500">فایلی یافت نشد.</p>
) : (
<div className="grid grid-cols-3 gap-3 sm:grid-cols-4 md:grid-cols-6">
{files.map((f) => {
const url = fileUrl(f);
return (
<button key={f.id} type="button" onClick={() => url && onSelect(url, f)}
className="group rounded-lg border border-[#262b40] bg-[#0c0e1a] p-2 text-start hover:border-indigo-500">
<div className="flex aspect-square items-center justify-center overflow-hidden rounded-md bg-[#070811]">
{url && isImage(f) ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={url} alt={f.name} className="h-full w-full object-cover" />
) : url && isVideo(f) ? (
<video src={url} className="h-full w-full object-cover" muted />
) : (
<span className="text-[10px] uppercase text-gray-500">{(f.name.split(".").pop() ?? "file").slice(0, 5)}</span>
)}
</div>
<p className="mt-1.5 truncate text-[11px] text-gray-300" title={f.name}>{f.name}</p>
<p className="text-[10px] text-gray-600">{humanSize(f.size_bytes)}</p>
</button>
);
})}
</div>
)}
</div>
</div>
</div>
);
}
+21
View File
@@ -2,6 +2,8 @@
import { useRef, useState } from "react";
import { FilePicker } from "@/components/admin/FilePicker";
/** Upload-or-clear field that replaces a raw URL text input. Stores the public URL. */
export function FileUploadField({
value,
@@ -17,6 +19,12 @@ export function FileUploadField({
const inputRef = useRef<HTMLInputElement>(null);
const [uploading, setUploading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [pickOpen, setPickOpen] = useState(false);
// Map the accept hint to a library type filter (image / video / AE-and-other).
const pickerType = accept.includes("image") && !accept.includes("video") ? "Image"
: accept.includes("video") ? "Video"
: /\.aep|\.zip/.test(accept) ? "Other" : "";
const isImage = value && /\.(png|jpe?g|gif|webp|svg|avif)$/i.test(value);
@@ -75,6 +83,13 @@ export function FileUploadField({
>
{uploading ? "در حال بارگذاری…" : value ? "تعویض" : "بارگذاری"}
</button>
<button
type="button"
onClick={() => setPickOpen(true)}
className="rounded-lg border border-[#262b40] px-3 py-1.5 text-xs text-gray-300 hover:bg-[#161a2e]"
>
از کتابخانه
</button>
{value && (
<button
type="button"
@@ -87,6 +102,12 @@ export function FileUploadField({
</div>
</div>
{error && <p className="mt-1 text-xs text-red-400">{error}</p>}
<FilePicker
open={pickOpen}
initialType={pickerType}
onClose={() => setPickOpen(false)}
onSelect={(url) => { onChange(url); setPickOpen(false); }}
/>
</div>
);
}
+58
View File
@@ -0,0 +1,58 @@
import { MINIO_PUBLIC_URL } from "@/lib/files";
export interface FileItem {
id: string;
name: string;
mime_type?: string;
file_type?: string; // Image | Video | Audio | Voiceover | Document | Other
size_bytes?: number;
minio_bucket?: string;
minio_key?: string;
cdn_url?: string | null;
file_address?: string | null;
thumbnail_url?: string | null;
created_at?: string;
}
/** Type filter tabs — values are the exact (capitalized) FileKind enum the API expects. */
export const FILE_TYPE_TABS: { v: string; l: string }[] = [
{ v: "", l: "همه" },
{ v: "Image", l: "تصاویر" },
{ v: "Video", l: "ویدیوها" },
{ v: "Audio", l: "صدا" },
{ v: "Other", l: "پروژه‌های AE و سایر" },
];
export function fileUrl(f: FileItem): string | null {
if (f.cdn_url) return f.cdn_url;
if (f.file_address) return f.file_address;
if (f.minio_key) return `${MINIO_PUBLIC_URL}/${f.minio_bucket ?? "user-uploads"}/${f.minio_key}`;
return null;
}
export function isImage(f: FileItem): boolean {
return f.file_type === "Image" || (f.mime_type ?? "").startsWith("image/") || /\.(png|jpe?g|gif|webp|svg|avif)$/i.test(f.name);
}
export function isVideo(f: FileItem): boolean {
return f.file_type === "Video" || (f.mime_type ?? "").startsWith("video/") || /\.(mp4|webm|mov|m4v|mkv)$/i.test(f.name);
}
export function isAep(f: FileItem): boolean {
return /\.(aep|aepx|zip)$/i.test(f.name);
}
export function humanSize(n?: number): string {
if (!n) return "—";
const u = ["B", "KB", "MB", "GB"];
let i = 0, v = n;
while (v >= 1024 && i < u.length - 1) { v /= 1024; i++; }
return `${v.toFixed(v < 10 && i > 0 ? 1 : 0)} ${u[i]}`;
}
/** Fetch files from the admin gateway with optional search + type filter. */
export async function fetchFiles(search: string, fileType: string, page = 1, pageSize = 60): Promise<FileItem[]> {
const qs = new URLSearchParams({ page: String(page), pageSize: String(pageSize), page_size: String(pageSize) });
if (search) qs.set("search", search);
if (fileType) qs.set("file_type", fileType);
const r = await fetch(`/api/admin/resource/files?${qs.toString()}`, { cache: "no-store" }).then((x) => x.json()).catch(() => null);
return r?.items ?? r?.data ?? (Array.isArray(r) ? r : []);
}