Repository Public
1"use client";2import { useState } from "react";3import { Icon } from "@/components/ui/Icon";4import { api, fmtBytes, fmtDate, toLocalInput } from "../client";5import type { PanelProps } from "../SessionEditor";6import type { ResourceRow, SessionDetail, Visibility } from "../types";7import { Uploader } from "../Uploader";8import { Confirm, Field, Notice, Panel, VisibilitySelect, useAction } from "../ui";910const KIND: Record<string, string> = { slides: "Diapositives", sources: "Sources (LaTeX…)", lab: "Laboratoire (fichiers de départ)", dataset: "Jeu de données", code: "Code", transcript: "Transcription", captions: "Sous-titres", solution: "Corrigé", script: "Scénario", bibliography: "Bibliographie" };11const ACCEPT = ["pdf", "zip", "tar.gz", "tgz", "tar", "png", "jpg", "jpeg", "txt", "md", "tex", "bib", "csv", "tsv", "json", "yaml", "yml", "py", "ipynb", "r", "sql", "vtt", "srt"];1213export function ResourcesPanel({ s, payload, apply, reload }: PanelProps) {14 const [meta, setMeta] = useState({ kind: "slides", title: "", description: "" });15 return (16 <div className="grid gap-4" data-testid="resources-panel">17 <Notice tone="blue">18 <p>Un fichier n’est offert au public que si la ressource est publique, que la séance est publiée, que le téléchargement est permis <strong>et</strong> qu’une licence est consignée — {payload.license ? <>licence du cours : <strong>{payload.license}</strong>.</> : <>aucune licence n’est consignée pour le cours (onglet « Cours et plan ») : indiquez-en une par ressource, sinon rien ne sera téléchargeable.</>}</p>19 <p>L’adresse publique d’une ressource ne change jamais : remplacer le fichier ajoute une version, sans briser les liens.</p>20 </Notice>21 {s.resourceRows.map((r) => <ResourceCard key={r.id} r={r} sessionId={s.id} apply={apply} reload={reload} />)}22 {!s.resourceRows.length && <p className="text-muted">Aucune ressource pour l’instant.</p>}23 <Panel title="Nouvelle ressource" id="nouvelle-ressource">24 <div className="grid gap-3 md:grid-cols-[14rem_1fr]">25 <Field label="Type">{(id) => <select id={id} className="field" value={meta.kind} onChange={(e) => setMeta({ ...meta, kind: e.target.value })}>{Object.entries(KIND).map(([k, l]) => <option key={k} value={k}>{l}</option>)}</select>}</Field>26 <Field label="Titre">{(id) => <input id={id} className="field" value={meta.title} maxLength={160} onChange={(e) => setMeta({ ...meta, title: e.target.value })} data-testid="resource-title" />}</Field>27 <Field label="Description (facultatif)" className="md:col-span-2">{(id) => <input id={id} className="field" value={meta.description} maxLength={600} onChange={(e) => setMeta({ ...meta, description: e.target.value })} />}</Field>28 </div>29 <div className="mt-3">30 {meta.title.trim() ? (31 <Uploader purpose="resource" accept={ACCEPT} label="Choisir le fichier" hint="PDF, ZIP, données, code, texte" testid="resource-upload"32 context={() => ({ sessionId: s.id, meta: { kind: meta.kind, title: meta.title.trim(), ...(meta.description.trim() ? { description: meta.description.trim() } : {}), visibility: "private", download: false, license: null } })}33 onDone={async () => { setMeta({ kind: "slides", title: "", description: "" }); await reload(); }} />34 ) : <p className="st-help">Donnez un titre à la ressource pour choisir son fichier. Elle sera créée privée.</p>}35 </div>36 </Panel>37 </div>38 );39}4041function ResourceCard({ r, sessionId, apply, reload }: { r: ResourceRow; sessionId: string; apply: (s: SessionDetail) => void; reload: () => Promise<void> }) {42 const base = `sessions/${sessionId}/resources/${r.id}`, act = useAction(), d = r.data, cur = r.versions.find((v) => v.version === r.currentVersion);43 const [title, setTitle] = useState(d.title), [license, setLicense] = useState(d.license ?? ""), [remove, setRemove] = useState(false), [restore, setRestore] = useState<number | null>(null), [note, setNote] = useState("");44 const patch = (body: Record<string, unknown>) => act.run(async () => apply(await api<SessionDetail>(base, { method: "PATCH", body })));45 return (46 <section className="card p-4 md:p-5" aria-label={`Ressource ${d.title}`} data-testid={`resource-${r.id}`}>47 <h2 className="sr-only">Ressource — {d.title}</h2>48 <div className="flex flex-wrap items-center gap-2">49 <input className="field min-w-[12rem] grow !font-medium" aria-label="Titre de la ressource" value={title} maxLength={160} onChange={(e) => setTitle(e.target.value)} onBlur={() => { if (title.trim() && title !== d.title) void patch({ title }); }} />50 <span className="chip">{KIND[d.kind] ?? d.kind}</span>51 <a href={`/admin/apercu/telecharger/${sessionId}/${r.id}`} className="btn btn-ghost btn-sm"><Icon name="download" size={16} />Télécharger</a>52 <button type="button" className="btn btn-quiet btn-sm !px-2" onClick={() => setRemove(true)} aria-label={`Supprimer la ressource ${d.title}`}><Icon name="trash" size={16} /></button>53 </div>54 <p className="st-mono mt-1 text-faint">Adresse publique : /telecharger/{sessionId}/{r.id}</p>55 <div className="mt-3 grid gap-3 md:grid-cols-2 xl:grid-cols-4">56 <div><span className="st-label">Visibilité</span><VisibilitySelect value={d.visibility} onChange={(v: Visibility) => void patch({ visibility: v })} label={`Visibilité de la ressource ${d.title}`} /></div>57 <div><span className="st-label">Téléchargement</span><label className="flex min-h-10 items-center gap-2 text-[0.93rem]"><input type="checkbox" className="size-4 accent-(--blue)" checked={d.download} onChange={(e) => void patch({ download: e.target.checked })} />Permis</label></div>58 <Field label="Licence de ce fichier" help="Vide : la licence du cours s’applique.">{(id) => <input id={id} className="field" value={license} maxLength={120} placeholder="p. ex. CC BY-NC-SA 4.0" onChange={(e) => setLicense(e.target.value)} onBlur={() => { if (license !== (d.license ?? "")) void patch({ license: license.trim() || null }); }} />}</Field>59 <Field label="Diffusion différée" help="Utile pour un corrigé : invisible avant cette date.">{(id) => <input id={id} type="datetime-local" className="field" value={d.releaseAfter ? toLocalInput(new Date(d.releaseAfter)) : ""} onChange={(e) => void patch({ releaseAfter: e.target.value ? new Date(e.target.value).toISOString() : null })} />}</Field>60 </div>61 {act.feedback}62 {cur && <p className="mt-3 text-[0.93rem]">Version actuelle : <strong>v{cur.version}</strong> — {cur.filename}, {fmtBytes(cur.bytes)}, {cur.mime}<br /><span className="st-mono break-all text-faint">SHA-256 {cur.sha256}</span></p>}63 <details className="mt-3">64 <summary className="font-medium text-blue">Remplacer le fichier · historique ({r.versions.length} version{r.versions.length > 1 ? "s" : ""})</summary>65 <div className="mt-3 grid gap-3">66 <Field label="Note de version (facultatif)">{(id) => <input id={id} className="field" value={note} maxLength={300} onChange={(e) => setNote(e.target.value)} />}</Field>67 <Uploader purpose="resource" accept={ACCEPT} compact label="Choisir le fichier de remplacement" testid={`replace-${r.id}`} context={() => ({ sessionId, resourceId: r.id, note: note.trim() || undefined })} onDone={async () => { setNote(""); await reload(); }} />68 <div className="st-scroll"><table className="st-table"><thead><tr><th scope="col">Version</th><th scope="col">Fichier</th><th scope="col">Ajoutée</th><th scope="col">Note</th><th scope="col"><span className="sr-only">Actions</span></th></tr></thead>69 <tbody>{r.versions.map((v) => (70 <tr key={v.version}><td>v{v.version}{v.version === r.currentVersion && <span className="chip chip-teal ml-2">actuelle</span>}</td><td>{v.filename}<br /><span className="text-faint">{fmtBytes(v.bytes)} · <span className="st-mono">{v.sha256.slice(0, 12)}…</span></span></td><td>{fmtDate(v.createdAt)}</td><td>{v.note ?? "—"}</td>71 <td><div className="flex justify-end gap-1.5"><a href={`/admin/apercu/telecharger/${sessionId}/${r.id}?version=${v.version}`} className="btn btn-quiet btn-sm">Télécharger</a>{v.version !== r.currentVersion && <button type="button" className="btn btn-ghost btn-sm" onClick={() => setRestore(v.version)}>Rétablir</button>}</div></td></tr>72 ))}</tbody></table></div>73 </div>74 </details>75 <Confirm open={restore !== null} onClose={() => setRestore(null)} title={`Rétablir la version ${restore} ?`} confirmLabel="Rétablir cette version" action={async () => apply(await api<SessionDetail>(`${base}/restore`, { body: { version: restore } }))}>76 <p>Cette version redevient le fichier de la ressource dans la copie de travail. Le public la recevra à la prochaine publication de la séance.</p>77 </Confirm>78 <Confirm open={remove} onClose={() => setRemove(false)} title={`Supprimer la ressource « ${d.title} » ?`} confirmLabel="Supprimer la ressource" danger action={async () => apply(await api<SessionDetail>(base, { method: "DELETE" }))}>79 <p>La ressource et son historique disparaissent de la copie de travail. Si elle est en ligne, elle le reste jusqu’à la prochaine publication de la séance ; les fichiers restent sur le disque.</p>80 </Confirm>81 </section>82 );83}84