SPB Git

Repository Public

ImportPanel.tsx 11.0 KB 99 lines tsx

1"use client";2import { useState } from "react";3import { api, fmtDate, useLoad } from "./client";4import { Uploader } from "./Uploader";5import { Badge, Confirm, Loading, Notice, PageTitle, Panel, useAction } from "./ui";67interface Change { key: string; label: string; kind: "update" | "conflict" | "add" | "remove"; base: string | null; local: string | null; incoming: string | null }8interface SessionDiff { id: string; title: string; kind: "added" | "removed" | "changed" | "unchanged"; changes: Change[] }9interface Diff { sourceHash: string; course: Change[]; sessions: SessionDiff[]; counts: { added: number; removed: number; changed: number; unchanged: number; updates: number; conflicts: number } }10interface ImportRecord { id: string; source: string; sourceHash: string; status: "pending" | "applied" | "discarded"; warnings: string[]; summary: string | null; createdAt: string; createdBy: string; appliedAt: string | null }11interface Data { imports: ImportRecord[]; pending: { record: ImportRecord; diff: Diff } | null; repo: { configured: boolean; readable: boolean } }12const KIND = { update: ["Mise à jour", "blue"], conflict: ["Conflit", "coral"], add: ["Ajout", "teal"], remove: ["Absent du dépôt", "amber"] } as const;13const SESSION_KIND = { added: "Nouvelle séance", removed: "Absente du dépôt", changed: "Modifiée", unchanged: "Inchangée" } as const;14const STATUS = { pending: "En attente", applied: "Appliquée", discarded: "Abandonnée" } as const;15const clip = (v: string | null) => (v === null ? "—" : v.length > 260 ? `${v.slice(0, 260)}…` : v);1617export function ImportPanel() {18  const { data, error, reload } = useLoad<Data>("imports"), read = useAction(), discard = useAction();19  const [decisions, setDecisions] = useState<Record<string, "local" | "incoming">>({}), [confirm, setConfirm] = useState(false), [result, setResult] = useState("");20  if (!data) return <><PageTitle eyebrow="Studio" title="Importation du dépôt du cours" /><Loading error={error} what="les importations" /></>;21  const p = data.pending, d = p?.diff, empty = d ? !d.course.length && d.sessions.every((s) => s.kind === "unchanged") : false;22  const after = async () => { setDecisions({}); setResult(""); await reload(); };23  const apply = async () => { const r = await api<{ applied: number; kept: number; added: number }>(`imports/${p!.record.id}/apply`, { body: { confirm: p!.record.id, decisions } }); setResult(`${r.applied} changement(s) appliqué(s) à la copie de travail, dont ${r.added} séance(s) ajoutée(s) en brouillon ; ${r.kept} conflit(s) résolu(s) en gardant votre version. Rien n’a été publié.`); setDecisions({}); await reload(); };24  const row = (c: Change) => (25    <tr key={c.key} data-change={c.key} data-kind={c.kind}>26      <td><Badge tone={KIND[c.kind][1]}>{KIND[c.kind][0]}</Badge><p className="mt-1 font-medium">{c.label}</p></td>27      <td className="text-muted">{c.kind === "conflict" ? <><span className="st-label !mb-0">Votre version (studio)</span>{clip(c.local)}</> : clip(c.local ?? c.base)}</td>28      <td>{c.kind === "remove" ? <span className="text-muted">N’est plus fourni par le dépôt. Votre copie est conservée.</span> : <><span className="st-label !mb-0">Version du dépôt</span>{clip(c.incoming)}</>}</td>29      <td>{c.kind === "conflict" ? (30        <fieldset className="grid gap-1 text-[0.9rem]"><legend className="sr-only">Résolution du conflit — {c.label}</legend>31          <label className="flex items-center gap-2"><input type="radio" name={c.key} className="size-4 accent-(--blue)" checked={(decisions[c.key] ?? "local") === "local"} onChange={() => setDecisions({ ...decisions, [c.key]: "local" })} />Garder ma version</label>32          <label className="flex items-center gap-2"><input type="radio" name={c.key} className="size-4 accent-(--blue)" checked={decisions[c.key] === "incoming"} onChange={() => setDecisions({ ...decisions, [c.key]: "incoming" })} data-testid={`take-${c.key}`} />Prendre celle du dépôt</label>33        </fieldset>34      ) : c.kind === "remove" ? <span className="text-sm text-faint">aucune action</span> : <span className="text-sm text-faint">sera appliqué</span>}</td>35    </tr>36  );37  return (38    <div data-testid="import-panel">39      <PageTitle eyebrow="Studio" title="Importation du dépôt du cours">40        <p>Le dépôt du cours est lu comme du contenu, jamais exécuté. L’importation compare ce qu’il contient à la copie de travail, vous montre les différences, et n’applique que ce que vous confirmez — toujours en brouillon. <strong>Une importation ne publie jamais rien.</strong></p>41      </PageTitle>42      <div className="grid gap-4">43        {result && <Notice tone="teal" title="Importation appliquée." testid="import-result"><p>{result}</p></Notice>}44        {!p && (45          <Panel title="Lire le dépôt" id="lire">46            <div className="grid gap-5 md:grid-cols-2">47              <div>48                <h3>Depuis le serveur</h3>49                {data.repo.configured ? (50                  <><p className="mt-1 text-[0.93rem] text-muted">Un dossier du dépôt est configuré sur ce serveur (ATLAS_COURSE_REPO){data.repo.readable ? "." : ", mais il est introuvable ou sans course.yaml."}</p>51                    <button type="button" className="btn btn-accent mt-3" disabled={!data.repo.readable || read.busy} onClick={() => read.run(async () => { await api("imports", { body: {} }); await after(); })} data-testid="read-repo">{read.busy ? "Lecture du dépôt…" : "Lire le dépôt et comparer"}</button></>52                ) : <p className="mt-1 text-[0.93rem] text-muted">Aucun dossier n’est configuré sur ce serveur (variable ATLAS_COURSE_REPO). Téléversez plutôt une archive.</p>}53                {read.feedback}54              </div>55              <div>56                <h3>Depuis une archive</h3>57                <p className="mt-1 text-[0.93rem] text-muted">Un instantané du dépôt en <code>.zip</code> ou <code>.tar.gz</code> (par exemple <code>git archive --format=tar.gz -o cours.tar.gz HEAD</code>). L’archive est extraite dans un dossier isolé, avec des limites de taille ; les liens symboliques et les chemins dangereux sont refusés.</p>58                <div className="mt-3"><Uploader purpose="archive" accept={["zip", "tar.gz", "tgz"]} label="Choisir l’archive du dépôt" hint=".zip ou .tar.gz" testid="archive-upload" context={() => ({})} onDone={after} /></div>59              </div>60            </div>61          </Panel>62        )}6364        {p && d && (65          <Panel title="Différences à examiner" id="diff" testid="import-diff" actions={<button type="button" className="btn btn-ghost btn-sm" disabled={discard.busy} onClick={() => discard.run(async () => { await api(`imports/${p.record.id}/discard`, { body: {} }); await after(); })} data-testid="discard-import">Abandonner cette importation</button>}>66            <p className="text-[0.93rem] text-muted">Source : {p.record.source} · lue le {fmtDate(p.record.createdAt)} · empreinte <span className="st-mono">{p.record.sourceHash.slice(0, 12)}</span></p>67            <ul className="mt-3 flex flex-wrap gap-2" data-testid="diff-counts">68              <li className="chip chip-teal">{d.counts.added} séance(s) nouvelle(s)</li><li className="chip chip-blue">{d.counts.changed} modifiée(s)</li><li className="chip chip-amber">{d.counts.removed} absente(s) du dépôt</li><li className="chip">{d.counts.unchanged} inchangée(s)</li><li className={`chip ${d.counts.conflicts ? "chip-coral" : ""}`}>{d.counts.conflicts} conflit(s)</li>69            </ul>70            {discard.feedback}71            {p.record.warnings.length > 0 && <details className="mt-3"><summary className="font-medium text-amber">{p.record.warnings.length} avertissement(s) de lecture (séances incomplètes ou en cours d’écriture)</summary><ul className="st-pre mt-2 list-none">{p.record.warnings.map((w, i) => <li key={i}>{w}</li>)}</ul></details>}72            {empty ? (73              <div className="mt-4"><Notice tone="teal" title="Aucun changement." testid="import-empty"><p>La copie de travail est déjà à jour avec ce dépôt. Il n’y a rien à appliquer.</p></Notice></div>74            ) : (75              <>76                {d.counts.conflicts > 0 && <div className="mt-4"><Notice tone="coral" title={`${d.counts.conflicts} conflit(s) : ces éléments ont été modifiés ici ET dans le dépôt.`}><p>Par défaut, votre version est conservée. Choisissez « Prendre celle du dépôt » là où vous voulez la remplacer. Rien n’est jamais écrasé en silence.</p></Notice></div>}77                {d.course.length > 0 && <div className="st-scroll mt-4"><table className="st-table"><caption className="pb-1 text-left font-semibold">Cours</caption><thead><tr><th scope="col">Élément</th><th scope="col">Ici</th><th scope="col">Dans le dépôt</th><th scope="col">Décision</th></tr></thead><tbody>{d.course.map(row)}</tbody></table></div>}78                {d.sessions.filter((s) => s.kind !== "unchanged").map((s) => (79                  <div key={s.id} className="st-scroll mt-4" data-diff-session={s.id}><table className="st-table"><caption className="pb-1 text-left font-semibold"><span className="st-mono text-faint">{s.id}</span> {s.title} <span className="chip ml-2">{SESSION_KIND[s.kind]}</span></caption><thead><tr><th scope="col">Élément</th><th scope="col">Ici</th><th scope="col">Dans le dépôt</th><th scope="col">Décision</th></tr></thead><tbody>{s.changes.map(row)}</tbody></table></div>80                ))}81                <div className="mt-5 flex flex-wrap items-center gap-3 border-t border-line pt-4"><button type="button" className="btn btn-primary" onClick={() => setConfirm(true)} data-testid="apply-import">Appliquer à la copie de travail…</button><span className="text-sm text-muted">Les nouvelles séances arrivent en brouillon ; rien ne devient public.</span></div>82              </>83            )}84          </Panel>85        )}8687        <Panel title="Importations précédentes" id="historique">88          <div className="st-scroll"><table className="st-table"><thead><tr><th scope="col">Date</th><th scope="col">Source</th><th scope="col">État</th><th scope="col">Résultat</th></tr></thead>89            <tbody>{data.imports.map((i) => <tr key={i.id}><td>{fmtDate(i.createdAt)}</td><td>{i.source}<br /><span className="st-mono text-faint">{i.sourceHash.slice(0, 12)}</span></td><td>{STATUS[i.status]}</td><td className="text-muted">{i.summary ?? "—"}</td></tr>)}</tbody></table></div>90        </Panel>91      </div>92      <Confirm open={confirm} onClose={() => setConfirm(false)} title="Appliquer cette importation à la copie de travail ?" confirmLabel="Appliquer en brouillon" action={apply} testid="confirm-import">93        <p>{d?.counts.updates ?? 0} mise(s) à jour et {d?.counts.added ?? 0} nouvelle(s) séance(s) seront appliquées. Pour les {d?.counts.conflicts ?? 0} conflit(s), {Object.values(decisions).filter((v) => v === "incoming").length} prendront la version du dépôt ; les autres gardent la vôtre.</p>94        <p><strong>Le site public ne change pas.</strong> Chaque séance devra être relue puis publiée séparément.</p>95      </Confirm>96    </div>97  );98}99
Files main
Menu

Theme