Repository Public
1"use client";2import { useRef, useState, type DragEvent, type FormEvent } from "react";3import { useLocale } from "@/i18n/client";4import { dict, fill, formatDateTime } from "@/i18n/dict";5import { api } from "@/lib/client-api";6import { Dialog, Notice, PageHeader, Spinner, useApi } from "@/components/admin/ui";7import type { listAssets, datasetRows } from "@/server/assets";8import { apiMessage, Confirm, CopyButton, formatBytes, formatNumber, Loading, Pager, Segments } from "./common";910type AssetList = Awaited<ReturnType<typeof listAssets>>;11type Asset = AssetList["items"][number];12type Dataset = Awaited<ReturnType<typeof datasetRows>>;13type KindFilter = "all" | "image" | "svg" | "pdf" | "text" | "csv" | "json";14interface Upload { key: number; name: string; size: number; state: "waiting" | "uploading" | "done" | "error"; message?: string }1516const T = dict({17 title: ["Médias et données", "Media & data"], lead: ["Images, SVG, PDF, textes et jeux de données utilisés par les fiches.", "Images, SVG, PDF, text and datasets used by the sheets."],18 loading: ["Chargement…", "Loading…"], retry: ["Réessayer", "Retry"],19 quota: ["Stockage utilisé", "Storage used"], quotaLine: ["{u} sur {q} ({p} %)", "{u} of {q} ({p}%)"],20 upload: ["Téléverser", "Upload"], drop: ["Déposez des fichiers ici, ou", "Drop files here, or"], choose: ["Choisir des fichiers", "Choose files"],21 accepted: ["PNG, JPEG, WebP, GIF, SVG, PDF, CSV, JSON, texte brut.", "PNG, JPEG, WebP, GIF, SVG, PDF, CSV, JSON, plain text."],22 meta: ["Informations appliquées aux fichiers téléversés (facultatif)", "Details applied to the uploaded files (optional)"],23 alt: ["Texte de remplacement", "Alternative text"], altHelp: ["Décrit l’image pour les lecteurs d’écran.", "Describes the image for screen readers."], credit: ["Crédit", "Credit"], license: ["Licence", "Licence"],24 queue: ["Téléversements", "Uploads"], waiting: ["En attente", "Waiting"], uploading: ["Envoi en cours…", "Uploading…"], done: ["Téléversé", "Uploaded"], failed: ["Refusé", "Refused"], clear: ["Effacer la liste", "Clear the list"],25 filter: ["Filtrer par type", "Filter by type"], all: ["Tous", "All"], image: ["Images", "Images"], svg: ["SVG", "SVG"], pdf: ["PDF", "PDF"], text: ["Texte", "Text"], csv: ["CSV", "CSV"], json: ["JSON", "JSON"],26 empty: ["Aucun fichier pour l’instant. Téléversez-en un ci-dessus.", "No file yet. Upload one above."], emptyKind: ["Aucun fichier de ce type.", "No file of this type."],27 unscanned: ["Non analysé", "Unscanned"], unscannedHelp: ["Aucun antivirus n’a vérifié ce fichier.", "No antivirus checked this file."], noAlt: ["Sans texte de remplacement", "No alternative text"],28 rows: ["{n} lignes, {c} colonnes", "{n} rows, {c} columns"], edit: ["Modifier", "Edit"], del: ["Supprimer", "Delete"], data: ["Voir les données", "View data"], open: ["Télécharger", "Download"],29 copyId: ["Copier l’identifiant", "Copy id"], copied: ["Copié", "Copied"],30 editTitle: ["Modifier les informations", "Edit details"], save: ["Enregistrer", "Save"], cancel: ["Annuler", "Cancel"], saved: ["Informations enregistrées.", "Details saved."],31 delTitle: ["Supprimer ce fichier ?", "Delete this file?"], delBody: ["« {f} » sera supprimé définitivement. Un fichier utilisé par une fiche ne peut pas être supprimé.", "“{f}” will be deleted for good. A file used by a sheet cannot be deleted."],32 deleted: ["Fichier supprimé.", "File deleted."], dataTitle: ["Données : {n}", "Data: {n}"], first: ["{n} premières lignes sur {t}.", "First {n} rows of {t}."], noRows: ["Ce jeu de données est vide.", "This dataset is empty."],33});3435const isPicture = (a: Asset) => a.kind === "image" || a.kind === "svg";36const fileUrl = (id: string) => `/api/admin/assets/${id}/file`;37const PAGE = 24;38let uploadKey = 0;3940function EditForm({ asset, onDone, onCancel }: { asset: Asset; onDone: (a: Asset) => void; onCancel: () => void }) {41 const locale = useLocale(), fr = locale === "fr", t = T(locale);42 const [alt, setAlt] = useState(asset.alt), [credit, setCredit] = useState(asset.credit), [license, setLicense] = useState(asset.license);43 const [busy, setBusy] = useState(false), [error, setError] = useState<string | null>(null);44 const submit = async (ev: FormEvent) => {45 ev.preventDefault(); setBusy(true); setError(null);46 const patch: { alt?: string; credit?: string; license?: string } = {};47 if (alt !== asset.alt) patch.alt = alt;48 if (credit !== asset.credit) patch.credit = credit;49 if (license !== asset.license) patch.license = license;50 try {51 const r = Object.keys(patch).length ? await api<Omit<Asset, "dataset">>(`/api/admin/assets/${asset.id}`, { method: "PATCH", body: patch }) : asset;52 onDone({ ...r, dataset: asset.dataset });53 } catch (e) { setError(apiMessage(e, fr)); setBusy(false); }54 };55 return (56 <form onSubmit={submit} className="grid gap-4">57 <p className="break-all font-mono text-sm text-muted">{asset.filename}</p>58 <label className="grid gap-1 text-sm font-medium" htmlFor="as-alt">{t.alt}59 <textarea id="as-alt" className="field" rows={3} maxLength={400} value={alt} onChange={(e) => setAlt(e.target.value)} />60 <span className="font-normal text-faint">{t.altHelp}</span></label>61 <label className="grid gap-1 text-sm font-medium" htmlFor="as-credit">{t.credit}62 <input id="as-credit" className="field" maxLength={300} value={credit} onChange={(e) => setCredit(e.target.value)} autoComplete="off" /></label>63 <label className="grid gap-1 text-sm font-medium" htmlFor="as-license">{t.license}64 <input id="as-license" className="field" maxLength={120} value={license} onChange={(e) => setLicense(e.target.value)} autoComplete="off" placeholder="CC BY 4.0" /></label>65 <div aria-live="assertive">{error && <Notice tone="bad">{error}</Notice>}</div>66 <div className="flex flex-wrap justify-end gap-2">67 <button type="button" className="btn" onClick={onCancel} disabled={busy}>{t.cancel}</button>68 <button className="btn btn-primary" disabled={busy}>{busy && <Spinner />}{t.save}</button>69 </div>70 </form>71 );72}7374function DatasetView({ asset }: { asset: Asset }) {75 const locale = useLocale(), fr = locale === "fr", t = T(locale);76 const { data, error, loading, reload } = useApi<Dataset>(`/api/admin/assets/${asset.id}/dataset`);77 if (loading && !data) return <Loading label={t.loading} />;78 if (error) return <Notice tone="bad">{error} <button type="button" className="ml-2 min-h-11 font-semibold underline" onClick={() => { void reload(); }}>{t.retry}</button></Notice>;79 if (!data) return null;80 if (data.rows.length === 0) return <p className="text-muted">{t.noRows}</p>;81 const shown = data.rows.slice(0, 50);82 return (83 <>84 <p className="text-sm text-muted">{fill(t.first, { n: shown.length, t: formatNumber(data.rows.length, fr) })}</p>85 <div className="mt-3 max-h-[55dvh] overflow-auto rounded-xl border border-line" tabIndex={0} role="region" aria-label={fill(t.dataTitle, { n: data.name })}>86 <table className="w-max min-w-full border-collapse text-sm">87 <thead className="sticky top-0 bg-raised">88 <tr>{data.columns.map((c, i) => <th key={i} scope="col" className={`whitespace-nowrap border-b border-line px-3 py-2 font-semibold ${c.type === "number" ? "text-right" : "text-left"}`}>{c.name}</th>)}</tr>89 </thead>90 <tbody>91 {shown.map((row, r) => (92 <tr key={r} className="border-b border-line last:border-0">93 {data.columns.map((c, i) => <td key={i} className={`max-w-[18rem] truncate px-3 py-1.5 ${c.type === "number" ? "text-right font-mono tabular-nums" : ""}`}>{String(row[i] ?? "")}</td>)}94 </tr>95 ))}96 </tbody>97 </table>98 </div>99 </>100 );101}102103export function AssetsPage() {104 const locale = useLocale(), fr = locale === "fr", t = T(locale);105 const [kind, setKind] = useState<KindFilter>("all"), [offset, setOffset] = useState(0);106 const list = useApi<AssetList>(`/api/admin/assets?limit=${PAGE}&offset=${offset}${kind !== "all" ? `&kind=${kind}` : ""}`);107 const [uploads, setUploads] = useState<Upload[]>([]), [uploading, setUploading] = useState(false), [over, setOver] = useState(false);108 const [alt, setAlt] = useState(""), [credit, setCredit] = useState(""), [license, setLicense] = useState("");109 const [editing, setEditing] = useState<Asset | null>(null), [viewing, setViewing] = useState<Asset | null>(null), [deleting, setDeleting] = useState<Asset | null>(null);110 const [delBusy, setDelBusy] = useState(false), [delError, setDelError] = useState<string | null>(null), [flash, setFlash] = useState<string | null>(null);111 const inputRef = useRef<HTMLInputElement>(null);112 const pending = useRef<{ key: number; file: File }[]>([]), running = useRef(false);113114 const patchUpload = (key: number, p: Partial<Upload>) => setUploads((u) => u.map((x) => (x.key === key ? { ...x, ...p } : x)));115 const drain = async () => {116 if (running.current) return;117 running.current = true; setUploading(true);118 for (let next = pending.current.shift(); next; next = pending.current.shift()) {119 patchUpload(next.key, { state: "uploading" });120 const form = new FormData();121 form.set("file", next.file);122 if (alt.trim()) form.set("alt", alt.trim());123 if (credit.trim()) form.set("credit", credit.trim());124 if (license.trim()) form.set("license", license.trim());125 try { await api("/api/admin/assets", { form }); patchUpload(next.key, { state: "done" }); }126 catch (e) { patchUpload(next.key, { state: "error", message: apiMessage(e, fr) }); }127 }128 running.current = false; setUploading(false);129 if (offset !== 0) setOffset(0); else void list.reload();130 };131 const addFiles = (files: FileList | null) => {132 if (!files || files.length === 0) return;133 const added = Array.from(files).map((file) => ({ key: ++uploadKey, file }));134 pending.current.push(...added);135 setUploads((u) => [...u, ...added.map(({ key, file }) => ({ key, name: file.name, size: file.size, state: "waiting" as const }))]);136 setFlash(null);137 void drain();138 };139 const onDrop = (e: DragEvent) => { e.preventDefault(); setOver(false); addFiles(e.dataTransfer.files); };140141 const remove = async () => {142 if (!deleting) return;143 setDelBusy(true); setDelError(null);144 try {145 await api(`/api/admin/assets/${deleting.id}`, { method: "DELETE" });146 setDeleting(null); setFlash(t.deleted);147 if (list.data && list.data.items.length === 1 && offset > 0) setOffset(Math.max(0, offset - PAGE)); else void list.reload();148 } catch (e) { setDelError(apiMessage(e, fr)); }149 setDelBusy(false);150 };151152 const d = list.data;153 const pct = d && d.quotaBytes > 0 ? Math.min(100, (d.usedBytes / d.quotaBytes) * 100) : 0;154 const kinds = [["all", t.all], ["image", t.image], ["svg", t.svg], ["pdf", t.pdf], ["text", t.text], ["csv", t.csv], ["json", t.json]] as const;155 const stateLabel = { waiting: t.waiting, uploading: t.uploading, done: t.done, error: t.failed };156157 return (158 <>159 <PageHeader title={t.title} lead={t.lead} />160161 {d && (162 <section aria-labelledby="as-quota" className="card p-4">163 <div className="flex flex-wrap items-baseline justify-between gap-2">164 <h2 id="as-quota" className="eyebrow">{t.quota}</h2>165 <p className="text-sm tabular-nums text-muted">{fill(t.quotaLine, { u: formatBytes(d.usedBytes, fr), q: formatBytes(d.quotaBytes, fr), p: pct.toFixed(pct < 10 ? 1 : 0) })}</p>166 </div>167 <div className="mt-2 h-2 overflow-hidden rounded-full bg-raised" role="progressbar" aria-labelledby="as-quota" aria-valuemin={0} aria-valuemax={100} aria-valuenow={Math.round(pct)}>168 <div className={`h-full rounded-full ${pct >= 95 ? "bg-bad" : pct >= 80 ? "bg-warn" : "bg-accent"}`} style={{ width: `${pct}%` }} />169 </div>170 </section>171 )}172173 <section aria-labelledby="as-upload" className="mt-6">174 <h2 id="as-upload" className="font-display text-2xl font-semibold">{t.upload}</h2>175 <div onDragOver={(e) => { e.preventDefault(); setOver(true); }} onDragLeave={() => setOver(false)} onDrop={onDrop}176 className={`mt-3 grid justify-items-center gap-3 rounded-2xl border-2 border-dashed px-4 py-8 text-center ${over ? "border-accent bg-accent-soft" : "border-line bg-surface"}`}>177 <p className="text-muted">{t.drop}</p>178 <button type="button" className="btn btn-primary" onClick={() => inputRef.current?.click()}>{t.choose}</button>179 <input ref={inputRef} type="file" multiple className="sr-only" tabIndex={-1} aria-label={t.choose}180 accept="image/png,image/jpeg,image/webp,image/gif,image/svg+xml,application/pdf,text/csv,application/json,text/plain,.csv,.json,.txt,.md,.svg"181 onChange={(e) => { addFiles(e.target.files); e.target.value = ""; }} />182 <p className="text-sm text-faint">{t.accepted}</p>183 </div>184 <details className="card mt-3 px-4">185 <summary className="flex min-h-11 cursor-pointer items-center text-sm font-semibold">{t.meta}</summary>186 <div className="grid gap-3 pb-4 sm:grid-cols-3">187 <label className="grid gap-1 text-sm font-medium" htmlFor="up-alt">{t.alt}<input id="up-alt" className="field" maxLength={400} value={alt} onChange={(e) => setAlt(e.target.value)} autoComplete="off" /></label>188 <label className="grid gap-1 text-sm font-medium" htmlFor="up-credit">{t.credit}<input id="up-credit" className="field" maxLength={300} value={credit} onChange={(e) => setCredit(e.target.value)} autoComplete="off" /></label>189 <label className="grid gap-1 text-sm font-medium" htmlFor="up-license">{t.license}<input id="up-license" className="field" maxLength={120} value={license} onChange={(e) => setLicense(e.target.value)} autoComplete="off" placeholder="CC BY 4.0" /></label>190 </div>191 </details>192 {uploads.length > 0 && (193 <div className="card mt-3 p-4">194 <div className="flex flex-wrap items-center justify-between gap-2">195 <h3 className="eyebrow">{t.queue} ({uploads.filter((u) => u.state === "done" || u.state === "error").length}/{uploads.length})</h3>196 <button type="button" className="btn btn-ghost btn-sm !min-h-11" disabled={uploading} onClick={() => setUploads([])}>{t.clear}</button>197 </div>198 <ul className="mt-1 divide-y divide-line" aria-live="polite">199 {uploads.map((u) => (200 <li key={u.key} className="py-2.5">201 <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1">202 <span className="min-w-0 break-all text-sm font-medium">{u.name} <span className="font-normal text-faint">· {formatBytes(u.size, fr)}</span></span>203 <span className={`inline-flex shrink-0 items-center gap-2 text-sm font-semibold ${u.state === "done" ? "text-ok" : u.state === "error" ? "text-bad" : "text-muted"}`}>{u.state === "uploading" && <Spinner />}{stateLabel[u.state]}</span>204 </div>205 {u.message && <p role="alert" className="mt-1 text-sm text-bad">{u.message}</p>}206 </li>207 ))}208 </ul>209 </div>210 )}211 </section>212213 <section aria-labelledby="as-list" className="mt-8">214 <h2 id="as-list" className="sr-only">{t.title}</h2>215 <Segments label={t.filter} options={kinds} value={kind} onChange={(v) => { setKind(v); setOffset(0); }} />216 <div aria-live="polite" aria-busy={list.loading} className="mt-3">217 {flash && <div className="mb-3"><Notice tone="ok">{flash}</Notice></div>}218 {list.error && <Notice tone="bad">{list.error} <button type="button" className="ml-2 min-h-11 font-semibold underline" onClick={() => { void list.reload(); }}>{t.retry}</button></Notice>}219 {list.loading && !d && <Loading label={t.loading} />}220 {d && d.items.length === 0 && <p className="py-6 text-muted">{kind === "all" ? t.empty : t.emptyKind}</p>}221 {d && d.items.length > 0 && (222 <ul className={`grid gap-3 sm:grid-cols-2 lg:grid-cols-3 ${list.loading ? "opacity-60" : ""}`}>223 {d.items.map((a) => (224 <li key={a.id} className="card flex min-w-0 flex-col overflow-hidden">225 <div className="grid aspect-[3/2] place-items-center border-b border-line bg-raised">226 {isPicture(a)227 ? <img src={fileUrl(a.id)} alt={a.alt} loading="lazy" decoding="async" className="h-full w-full object-contain" />228 : <span className="font-mono text-2xl font-semibold uppercase text-faint" aria-hidden="true">{a.kind}</span>}229 </div>230 <div className="flex flex-1 flex-col gap-2 p-4">231 <h3 className="break-all text-[0.9375rem] font-semibold leading-snug">{a.filename}</h3>232 <p className="text-sm text-muted">233 <span className="uppercase">{a.kind}</span> · {formatBytes(a.bytes, fr)}{a.width && a.height ? ` · ${a.width} × ${a.height}` : ""}234 {a.dataset ? ` · ${fill(t.rows, { n: formatNumber(a.dataset.row_count, fr), c: Array.isArray(a.dataset.columns) ? a.dataset.columns.length : "?" })}` : ""}235 </p>236 <p className="text-sm text-faint">{formatDateTime(a.createdAt, locale)}</p>237 <div className="flex flex-wrap gap-2">238 {a.scanStatus === "unscanned" && <span className="rounded-full border border-warn/40 px-2.5 py-0.5 text-xs font-semibold text-warn" title={t.unscannedHelp}>{t.unscanned}<span className="sr-only"> : {t.unscannedHelp}</span></span>}239 {a.kind === "image" && !a.alt && <span className="rounded-full border border-line px-2.5 py-0.5 text-xs font-semibold text-muted">{t.noAlt}</span>}240 </div>241 {(a.alt || a.credit || a.license) && (242 <dl className="grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 text-sm">243 {a.alt && <><dt className="text-faint">Alt</dt><dd className="break-words">{a.alt}</dd></>}244 {a.credit && <><dt className="text-faint">{t.credit}</dt><dd className="break-words">{a.credit}</dd></>}245 {a.license && <><dt className="text-faint">{t.license}</dt><dd className="break-words">{a.license}</dd></>}246 </dl>247 )}248 <p className="break-all font-mono text-xs text-faint">{a.id}</p>249 <div className="mt-auto flex flex-wrap gap-2 pt-1">250 <button type="button" className="btn" onClick={() => setEditing(a)}>{t.edit}</button>251 {a.dataset && <button type="button" className="btn" onClick={() => setViewing(a)}>{t.data}</button>}252 <CopyButton text={a.id} label={t.copyId} copiedLabel={t.copied} />253 <a className="btn btn-ghost" href={`${fileUrl(a.id)}?download`} download={a.filename}>{t.open}</a>254 <button type="button" className="btn btn-danger" onClick={() => { setDelError(null); setDeleting(a); }}>{t.del}</button>255 </div>256 </div>257 </li>258 ))}259 </ul>260 )}261 {d && <Pager total={d.total} limit={PAGE} offset={offset} onChange={setOffset} fr={fr} />}262 </div>263 </section>264265 <Dialog open={!!editing} onClose={() => setEditing(null)} title={t.editTitle}>266 {editing && <EditForm key={editing.id} asset={editing} onCancel={() => setEditing(null)}267 onDone={(a) => { list.setData(d ? { ...d, items: d.items.map((x) => (x.id === a.id ? a : x)) } : d); setEditing(null); setFlash(t.saved); }} />}268 </Dialog>269 <Dialog open={!!viewing} onClose={() => setViewing(null)} title={fill(t.dataTitle, { n: viewing?.filename ?? "" })} wide>270 {viewing && <DatasetView key={viewing.id} asset={viewing} />}271 </Dialog>272 <Confirm open={!!deleting} title={t.delTitle} confirmLabel={t.del} cancelLabel={t.cancel} busy={delBusy} error={delError} onConfirm={() => { void remove(); }} onClose={() => { if (!delBusy) setDeleting(null); }}>273 {fill(t.delBody, { f: deleting?.filename ?? "" })}274 </Confirm>275 </>276 );277}278