feat(admin): media library + upload component (replace URL fields)
- /admin/files Media Library: drag-drop multi-upload, thumbnails, copy-URL, delete - FileUploadField replaces raw URL inputs; new "image" field type in AdminResource; wired into category image - upload proxy /api/admin/files/upload: browser → Next → presigned PUT (server-side, reaches minio:9000) → confirm → returns public URL - user-uploads bucket is public-read; public base via NEXT_PUBLIC_MINIO_URL Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -2,10 +2,12 @@
|
||||
|
||||
import { useCallback, useEffect, useState, type ReactNode } from "react";
|
||||
|
||||
import { FileUploadField } from "@/components/admin/FileUploadField";
|
||||
|
||||
export interface FieldDef {
|
||||
key: string;
|
||||
label: string;
|
||||
type?: "text" | "textarea" | "number" | "checkbox" | "select";
|
||||
type?: "text" | "textarea" | "number" | "checkbox" | "select" | "image" | "file";
|
||||
options?: { value: string; label: string }[];
|
||||
required?: boolean;
|
||||
placeholder?: string;
|
||||
@@ -215,6 +217,12 @@ export function AdminResource({ config }: { config: ResourceConfig }) {
|
||||
<input type="checkbox" checked={!!form[f.key]} onChange={(e) => setForm({ ...form, [f.key]: e.target.checked })} />
|
||||
{f.label}
|
||||
</label>
|
||||
) : f.type === "image" || f.type === "file" ? (
|
||||
<FileUploadField
|
||||
value={String(form[f.key] ?? "")}
|
||||
onChange={(url) => setForm({ ...form, [f.key]: url })}
|
||||
accept={f.type === "image" ? "image/*" : "*/*"}
|
||||
/>
|
||||
) : (
|
||||
<input type={f.type === "number" ? "number" : "text"} className={inputCls} placeholder={f.placeholder}
|
||||
value={String(form[f.key] ?? "")}
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
"use client";
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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 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 : []));
|
||||
} catch {
|
||||
setError("Failed to load files");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => { reload(); }, [reload]);
|
||||
|
||||
const uploadFiles = async (list: FileList) => {
|
||||
setUploading(true);
|
||||
setError(null);
|
||||
for (const file of Array.from(list)) {
|
||||
const fd = new FormData();
|
||||
fd.append("file", file);
|
||||
const res = await fetch("/api/admin/files/upload", { method: "POST", body: fd });
|
||||
if (!res.ok) {
|
||||
const d = await res.json().catch(() => null);
|
||||
setError(d?.error ?? `Failed to upload ${file.name}`);
|
||||
}
|
||||
}
|
||||
setUploading(false);
|
||||
if (inputRef.current) inputRef.current.value = "";
|
||||
reload();
|
||||
};
|
||||
|
||||
const remove = async (f: FileItem) => {
|
||||
if (!confirm(`Delete ${f.name}?`)) return;
|
||||
const res = await fetch(`/api/admin/resource/files/${f.id}`, { method: "DELETE" });
|
||||
if (res.ok) reload(); else setError("Delete failed");
|
||||
};
|
||||
|
||||
const copy = (url: string) => {
|
||||
navigator.clipboard?.writeText(url);
|
||||
setCopied(url);
|
||||
setTimeout(() => setCopied(null), 1500);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold text-white">Media Library</h1>
|
||||
<p className="mt-1 text-sm text-gray-400">Upload and manage images & files. Public URLs can be copied into any field.</p>
|
||||
</div>
|
||||
<button className={btn} onClick={() => inputRef.current?.click()} disabled={uploading}>
|
||||
{uploading ? "Uploading…" : "+ Upload files"}
|
||||
</button>
|
||||
<input ref={inputRef} type="file" multiple className="hidden" onChange={(e) => e.target.files && uploadFiles(e.target.files)} />
|
||||
</div>
|
||||
|
||||
{error && <p className="rounded-lg bg-red-500/10 px-3 py-2 text-sm text-red-300">{error}</p>}
|
||||
|
||||
<div
|
||||
className={`${card} p-4`}
|
||||
onDragOver={(e) => e.preventDefault()}
|
||||
onDrop={(e) => { e.preventDefault(); if (e.dataTransfer.files.length) uploadFiles(e.dataTransfer.files); }}
|
||||
>
|
||||
{loading ? (
|
||||
<p className="py-10 text-center text-sm text-gray-500">Loading…</p>
|
||||
) : files.length === 0 ? (
|
||||
<p className="py-10 text-center text-sm text-gray-500">No files yet. Drag & drop here or click Upload.</p>
|
||||
) : (
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6">
|
||||
{files.map((f) => {
|
||||
const url = fileUrl(f);
|
||||
return (
|
||||
<div key={f.id} className="group rounded-lg border border-[#262b40] bg-[#0c0e1a] p-2">
|
||||
<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" />
|
||||
) : (
|
||||
<span className="text-[10px] uppercase text-gray-600">{(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>
|
||||
<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)}>
|
||||
{copied === url ? "Copied!" : "Copy URL"}
|
||||
</button>
|
||||
)}
|
||||
<button className="rounded border border-red-500/30 px-1.5 py-0.5 text-[10px] text-red-300 hover:bg-red-500/10" onClick={() => remove(f)}>Del</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
"use client";
|
||||
|
||||
import { useRef, useState } from "react";
|
||||
|
||||
/** Upload-or-clear field that replaces a raw URL text input. Stores the public URL. */
|
||||
export function FileUploadField({
|
||||
value,
|
||||
onChange,
|
||||
accept = "image/*",
|
||||
label,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (url: string) => void;
|
||||
accept?: string;
|
||||
label?: string;
|
||||
}) {
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const isImage = value && /\.(png|jpe?g|gif|webp|svg|avif)$/i.test(value);
|
||||
|
||||
const upload = async (file: File) => {
|
||||
setUploading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const fd = new FormData();
|
||||
fd.append("file", file);
|
||||
const res = await fetch("/api/admin/files/upload", { method: "POST", body: fd });
|
||||
const data = await res.json();
|
||||
if (!res.ok || !data?.url) throw new Error(data?.error ?? "Upload failed");
|
||||
onChange(data.url);
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : "Upload failed");
|
||||
} finally {
|
||||
setUploading(false);
|
||||
if (inputRef.current) inputRef.current.value = "";
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
{label && <label className="mb-1 block text-xs font-medium text-gray-400">{label}</label>}
|
||||
<div className="flex items-center gap-3">
|
||||
{value ? (
|
||||
isImage ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img src={value} alt="" className="h-14 w-14 rounded-lg border border-[#262b40] object-cover" />
|
||||
) : (
|
||||
<span className="max-w-[160px] truncate rounded-lg border border-[#262b40] bg-[#0c0e1a] px-2 py-1 text-xs text-gray-400">
|
||||
{value.split("/").pop()}
|
||||
</span>
|
||||
)
|
||||
) : (
|
||||
<span className="flex h-14 w-14 items-center justify-center rounded-lg border border-dashed border-[#262b40] text-[10px] text-gray-600">
|
||||
none
|
||||
</span>
|
||||
)}
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept={accept}
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
const f = e.target.files?.[0];
|
||||
if (f) upload(f);
|
||||
}}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
disabled={uploading}
|
||||
onClick={() => inputRef.current?.click()}
|
||||
className="rounded-lg bg-indigo-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-indigo-500 disabled:opacity-50"
|
||||
>
|
||||
{uploading ? "Uploading…" : value ? "Replace" : "Upload"}
|
||||
</button>
|
||||
{value && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onChange("")}
|
||||
className="rounded-lg border border-[#262b40] px-3 py-1.5 text-xs text-gray-400 hover:bg-[#161a2e]"
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{error && <p className="mt-1 text-xs text-red-400">{error}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -51,7 +51,7 @@ export const categoriesConfig: ResourceConfig = {
|
||||
{ key: "name", label: "Name", required: true },
|
||||
{ key: "slug", label: "Slug", required: true },
|
||||
{ key: "description", label: "Description / content", type: "textarea" },
|
||||
{ key: "image_url", label: "Image URL" },
|
||||
{ key: "image_url", label: "Image", type: "image" },
|
||||
{ key: "icon", label: "Icon" },
|
||||
// SEO
|
||||
{ key: "meta_title", label: "SEO · Meta title" },
|
||||
|
||||
Reference in New Issue
Block a user