SPB Git

Repository Public

Sections.tsx 30.0 KB 280 lines tsx

1"use client";2import { useEffect, useState } from "react";3import { QuizRunner } from "@/components/quiz/QuizRunner";4import { Icon } from "@/components/ui/Icon";5import { Markdown } from "@/components/ui/Markdown";6import type { Bibliography, Figures, Glossary, Question, Quiz } from "@/modules/content-schema/schema";7import { api, useLoad } from "../client";8import type { PanelProps } from "../SessionEditor";9import type { SectionRow, SessionDetail, Visibility } from "../types";10import { Uploader } from "../Uploader";11import { Confirm, Field, Loading, Notice, Panel, VisibilitySelect, useAction } from "../ui";1213const KEYS = ["slides", "lesson", "lab", "quiz", "glossary", "bibliography", "script", "figures"] as const;14type Key = (typeof KEYS)[number];15const LABEL: Record<Key, string> = { slides: "Diapositives", lesson: "Leçon interactive", lab: "Laboratoire", quiz: "Quiz", glossary: "Glossaire", bibliography: "Références", script: "Scénario de narration", figures: "Figures" };16const UNIT: Record<Key, string> = { slides: "diapositive(s)", lesson: "section(s)", lab: "", quiz: "question(s)", glossary: "terme(s)", bibliography: "référence(s)", script: "", figures: "figure(s)" };17const slugify = (t: string) => t.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");1819export function SectionsPanel({ s, apply, reload }: PanelProps) {20  const [packNote, setPackNote] = useState(""), [lessonNote, setLessonNote] = useState(""), [open, setOpen] = useState<Key | null>(null), [remove, setRemove] = useState<Key | null>(null), vis = useAction();21  const rows = new Map(s.sectionRows.map((r) => [r.key as Key, r]));22  const setVisibility = (key: Key, visibility: Visibility) => vis.run(async () => apply(await api<SessionDetail>(`sessions/${s.id}/sections/${key}`, { method: "PUT", body: { visibility } })));23  return (24    <div className="grid gap-4" data-testid="sections-panel">25      <Notice tone="blue"><p><strong>Privé</strong> : visible dans cet éditeur seulement. <strong>Aperçu seulement</strong> : visible aussi dans l’aperçu privé. <strong>Public à la publication</strong> : fera partie de la prochaine publication de la séance — pas avant.</p></Notice>26      {vis.feedback}27      <div className="card st-scroll">28        <table className="st-table">29          <thead><tr><th scope="col">Section</th><th scope="col">Contenu</th><th scope="col">Visibilité</th><th scope="col"><span className="sr-only">Actions</span></th></tr></thead>30          <tbody>31            {KEYS.map((key) => { const r = rows.get(key); return (32              <tr key={key} data-section={key}>33                <th scope="row" className="!normal-case !tracking-normal !text-[0.93rem] !text-fg">{LABEL[key]}</th>34                <td className="text-muted">{r ? <>{r.count !== null ? `${r.count} ${UNIT[key]}` : "texte"}{r.baseSha && r.baseSha !== r.sha256 ? <span className="chip chip-amber ml-2">Modifié dans le studio</span> : null}{!r.baseSha ? <span className="chip ml-2">Absent du dépôt</span> : null}</> : <span className="text-faint">— absent —</span>}</td>35                <td>{r ? <VisibilitySelect value={r.visibility} onChange={(v) => setVisibility(key, v)} label={`Visibilité — ${LABEL[key]}`} /> : null}</td>36                <td><div className="flex justify-end gap-1.5">37                  {key === "lesson" ? (r ? <a href={`/admin/apercu/seances/${s.slug}#lecon`} target="_blank" rel="noopener" className="btn btn-ghost btn-sm">Voir dans l’aperçu</a> : <span className="text-sm text-faint">paquet à importer ci-dessous</span>)38                    : key === "slides" ? (r ? <a href={`/admin/apercu/seances/${s.slug}#diapositives`} target="_blank" rel="noopener" className="btn btn-ghost btn-sm">Voir dans l’aperçu</a> : <span className="text-sm text-faint">paquet à importer ci-dessous</span>)39                    : key === "figures" && !r ? <span className="text-sm text-faint">importées du dépôt</span> : <button type="button" className="btn btn-ghost btn-sm" onClick={() => setOpen(open === key ? null : key)} aria-expanded={open === key} data-testid={`edit-${key}`}>{r ? (key === "figures" ? "Voir" : "Modifier") : "Créer"}</button>}40                  {r && key !== "figures" && key !== "slides" && key !== "lesson" && <button type="button" className="btn btn-quiet btn-sm !px-2" onClick={() => setRemove(key)} aria-label={`Supprimer la section ${LABEL[key]}`}><Icon name="trash" size={16} /></button>}41                </div></td>42              </tr>43            ); })}44          </tbody>45        </table>46      </div>47      <Panel title="Diapositives" id="paquet-diapositives" testid="slides-pack">48        <p className="text-[0.93rem] text-muted">Les diapositives s’importent comme un <strong>paquet</strong> produit à partir des deux PDF web du cours (thème sombre et thème clair) par la commande <code>pnpm slides:build</code>, sur un poste qui a poppler. Le paquet est vérifié fichier par fichier ; les diapositives arrivent <strong>privées</strong>. Pour les mettre en ligne seules — « Diapositives en ligne, vidéos à venir » —, marquez-les « Public à la publication », puis publiez la séance : rien d’autre ne part si rien d’autre n’est public.</p>49        <div className="mt-3"><Uploader<{ slides: number; changed: boolean; warnings: string[] }> purpose="slides" accept={["tar.gz", "tgz"]} compact label={rows.get("slides") ? "Remplacer par un nouveau paquet" : "Importer un paquet de diapositives"} hint="SXX-slides.tar.gz" testid="slides-upload" context={() => ({ sessionId: s.id })} onDone={async (r) => { setPackNote(`${r.slides} diapositives ${r.changed ? "importées" : "déjà à jour"}.${r.warnings.length ? ` Avertissements : ${r.warnings.join(" ; ")}` : ""}`); await reload(); }} /></div>50        {packNote && <div className="mt-2"><Notice tone="teal" testid="slides-pack-note"><p>{packNote}</p></Notice></div>}51      </Panel>52      <Panel title="Leçon interactive" id="paquet-lecon" testid="lesson-pack">53        <p className="text-[0.93rem] text-muted">La leçon interactive s’importe comme un <strong>paquet</strong> (<code>SXX-lesson.json</code>) produit à partir du dépôt du cours par <code>pnpm lessons:build</code>. Il contient la leçon, le quiz avec ses renvois aux diapositives, le glossaire et les consignes du laboratoire ; tout arrive <strong>privé</strong>. Un quiz, un glossaire ou des consignes modifiés ici sont conservés. Pour mettre la leçon en ligne : réglez « Leçon interactive », « Quiz », « Glossaire » et « Laboratoire » sur « Public à la publication », puis publiez la séance — ou, en ligne de commande, <code>pnpm studio lessons-publish {s.id}</code>.</p>54        <div className="mt-3 flex flex-wrap items-center gap-3">55          <label className="btn btn-ghost btn-sm">{rows.get("lesson") ? "Remplacer par un nouveau paquet" : "Importer un paquet de leçon"}56            <input type="file" accept=".json,application/json" className="sr-only" data-testid="lesson-upload" onChange={(e) => { const f = e.target.files?.[0]; e.target.value = ""; if (!f) return; void vis.run(async () => { const text = await f.text(); if (text.length > 1_800_000) throw new Error("Fichier trop volumineux pour être un paquet de leçon."); const r = await api<{ session: SessionDetail; result: { sections: number; questions: number; changed: string[]; kept: string[]; warnings: string[] } }>(`sessions/${s.id}/lesson-pack`, { method: "POST", body: { pack: text } }); apply(r.session); setLessonNote(`${r.result.sections} sections, ${r.result.questions} questions — ${r.result.changed.length ? `mis à jour : ${r.result.changed.join(", ")}` : "aucun changement"}${r.result.kept.length ? ` ; conservé du studio : ${r.result.kept.join(", ")}` : ""}.${r.result.warnings.length ? ` Avertissements : ${r.result.warnings.join(" ; ")}` : ""}`); }); }} />57          </label>58        </div>59        {lessonNote && <div className="mt-2"><Notice tone="teal" testid="lesson-pack-note"><p>{lessonNote}</p></Notice></div>}60      </Panel>61      {open && <SectionEditor key={open} sessionId={s.id} sectionKey={open} row={rows.get(open) ?? null} onSaved={apply} onClose={() => setOpen(null)} />}62      <Confirm open={remove !== null} onClose={() => setRemove(null)} title={`Supprimer la section « ${remove ? LABEL[remove] : ""} » ?`} confirmLabel="Supprimer la section" danger63        action={async () => { apply(await api<SessionDetail>(`sessions/${s.id}/sections/${remove}`, { method: "DELETE" })); if (open === remove) setOpen(null); }}>64        <p>Le contenu disparaît de la copie de travail. Une publication déjà en ligne n’est pas touchée, et une prochaine importation du dépôt proposera de nouveau la section si elle y figure.</p>65      </Confirm>66    </div>67  );68}6970function SectionEditor({ sessionId, sectionKey, row, onSaved, onClose }: { sessionId: string; sectionKey: Key; row: SectionRow | null; onSaved: (s: SessionDetail) => void; onClose: () => void }) {71  const { data, error } = useLoad<{ row: SectionRow; body: string; baseBody: string | null }>(row ? `sessions/${sessionId}/sections/${sectionKey}` : null);72  const save = useAction();73  if (row && !data) return <Loading error={error} what="la section" />;74  const initial = data?.body ?? "";75  const put = (body: unknown) => save.run(async () => onSaved(await api<SessionDetail>(`sessions/${sessionId}/sections/${sectionKey}`, { method: "PUT", body: { body, expectSha: row?.sha256 ?? null } })), "Section enregistrée dans la copie de travail.");76  const common = { save: put, busy: save.busy, feedback: save.feedback, onClose };77  const parsed = <T,>(fallback: T): T => { try { return initial ? JSON.parse(initial) as T : fallback; } catch { return fallback; } };78  return (79    <Panel title={`${row ? "Modifier" : "Créer"} — ${LABEL[sectionKey]}`} id={`ed-${sectionKey}`} testid={`editor-${sectionKey}`} actions={<button type="button" className="btn btn-ghost btn-sm" onClick={onClose}>Fermer</button>}>80      {sectionKey === "lab" || sectionKey === "script" ? <MarkdownEditor initial={initial} {...common} />81        : sectionKey === "quiz" ? <QuizEditor initial={parsed<Quiz>({ id: `${sessionId.toLowerCase()}-quiz`, title: "Quiz de la séance", questions: [] as unknown as Quiz["questions"] })} {...common} />82        : sectionKey === "glossary" ? <GlossaryEditor initial={parsed<Glossary>({ terms: [] })} sessionId={sessionId} {...common} />83        : sectionKey === "bibliography" ? <BibliographyEditor initial={parsed<Bibliography>({ entries: [] })} {...common} />84        : <FiguresView figures={parsed<Figures>({ figures: [] })} sessionId={sessionId} />}85    </Panel>86  );87}8889interface EditorProps { save: (body: unknown) => Promise<boolean>; busy: boolean; feedback: React.ReactNode; onClose: () => void }90function SaveBar({ onSave, busy, feedback, dirty, disabled, testid }: { onSave: () => void; busy: boolean; feedback: React.ReactNode; dirty: boolean; disabled?: boolean; testid?: string }) {91  return <div className="mt-4 flex flex-wrap items-center gap-3 border-t border-line pt-3"><button type="button" className="btn btn-accent" onClick={onSave} disabled={busy || !dirty || disabled} data-testid={testid}>{busy ? "Enregistrement…" : "Enregistrer"}</button>{dirty && !busy && <span className="text-sm text-amber">Modifications non enregistrées</span>}{feedback}</div>;92}9394/* ---- Markdown ---- */9596const CHEAT = "**gras** · *italique* · `code` · [lien](https://…) · # Titre · - liste · 1. liste numérotée · > citation · ```python … ``` · | tableau | … | · $$ formule $$";9798function MarkdownEditor({ initial, save, busy, feedback }: EditorProps & { initial: string }) {99  const [text, setText] = useState(initial), [shown, setShown] = useState(initial);100  // The preview follows the text with a short delay, so typing stays fluid in long documents.101  useEffect(() => { const t = setTimeout(() => setShown(text), 250); return () => clearTimeout(t); }, [text]);102  return (103    <>104      <p className="st-help !mt-0 mb-3">Markdown : {CHEAT}. Le HTML brut n’est jamais interprété ; les images ne sont pas affichées ; les liens doivent commencer par http(s).</p>105      <div className="st-split">106        <Field label="Texte (Markdown)">{(id) => <textarea id={id} className="field st-mono min-h-[28rem]" value={text} onChange={(e) => setText(e.target.value)} spellCheck lang="fr-CA" data-testid="markdown-source" />}</Field>107        <div><p className="st-label">Aperçu — rendu exact de la page publique</p><div className="card max-h-[32rem] min-h-[28rem] overflow-auto p-4" data-testid="markdown-preview" tabIndex={0} role="region" aria-label="Aperçu du texte">{shown.trim() ? <Markdown source={shown} headingOffset={2} /> : <p className="text-faint">L’aperçu paraît ici.</p>}</div></div>108      </div>109      <SaveBar onSave={() => void save(text)} busy={busy} feedback={feedback} dirty={text !== initial && text.trim().length > 0} testid="save-markdown" />110    </>111  );112}113114/* ---- Quiz ---- */115116const TYPE_LABEL: Record<string, string> = { single: "Choix unique", multiple: "Choix multiple", "true-false": "Vrai ou faux", numeric: "Réponse numérique" };117const FORM_TYPES = Object.keys(TYPE_LABEL);118const letter = (i: number) => String.fromCharCode(65 + i);119function blank(type: string, id: string): Question {120  const base = { id, prompt: "", explanation: "" };121  if (type === "multiple") return { ...base, type: "multiple", options: [{ id: "A", text: "" }, { id: "B", text: "" }], answers: ["A"] };122  if (type === "true-false") return { ...base, type: "true-false", answer: true };123  if (type === "numeric") return { ...base, type: "numeric", answer: 0, tolerance: 0 };124  return { ...base, type: "single", options: [{ id: "A", text: "" }, { id: "B", text: "" }], answer: "A" };125}126127function QuizEditor({ initial, save, busy, feedback }: EditorProps & { initial: Quiz }) {128  const [quiz, setQuiz] = useState<Quiz>(initial), [mode, setMode] = useState<"form" | "json">("form"), [json, setJson] = useState(""), [jsonError, setJsonError] = useState(""), [preview, setPreview] = useState(false), [drop, setDrop] = useState<number | null>(null);129  const dirty = JSON.stringify(quiz) !== JSON.stringify(initial);130  const setQ = (i: number, q: Question) => setQuiz({ ...quiz, questions: quiz.questions.map((x, j) => (j === i ? q : x)) as Quiz["questions"] });131  const move = (i: number, d: number) => { const next = [...quiz.questions]; const [x] = next.splice(i, 1); next.splice(i + d, 0, x!); setQuiz({ ...quiz, questions: next as Quiz["questions"] }); };132  const add = () => { const ids = new Set(quiz.questions.map((q) => q.id)); let n = quiz.questions.length + 1; while (ids.has(`Q${n}`)) n++; setQuiz({ ...quiz, questions: [...quiz.questions, blank("single", `Q${n}`)] as Quiz["questions"] }); };133  const toJson = () => { setJson(JSON.stringify(quiz, null, 2)); setJsonError(""); setMode("json"); };134  const fromJson = () => { try { const v = JSON.parse(json) as Quiz; if (!v || !Array.isArray(v.questions)) throw new Error("questions manquantes"); setQuiz(v); setMode("form"); setJsonError(""); } catch (e) { setJsonError(`JSON invalide : ${(e as Error).message}`); } };135  const valid = quiz.questions.length > 0 && quiz.questions.every((q) => q.prompt.trim() && q.explanation.trim());136  return (137    <div data-testid="quiz-editor">138      <div className="mb-4 flex flex-wrap items-end gap-3">139        <Field label="Titre du quiz" className="min-w-[14rem] grow">{(id) => <input id={id} className="field" value={quiz.title} onChange={(e) => setQuiz({ ...quiz, title: e.target.value })} />}</Field>140        <Field label="Seuil suggéré (bonnes réponses)" className="w-56">{(id) => <input id={id} type="number" min={0} max={quiz.questions.length} className="field" value={quiz.passingScore ?? ""} onChange={(e) => setQuiz({ ...quiz, passingScore: e.target.value === "" ? undefined : Math.max(0, Number(e.target.value)) })} />}</Field>141        <button type="button" className="btn btn-ghost" onClick={() => setPreview(!preview)} disabled={!valid} aria-pressed={preview} data-testid="quiz-preview-toggle">{preview ? "Masquer l’aperçu" : "Essayer le quiz"}</button>142        <button type="button" className="btn btn-ghost" onClick={mode === "form" ? toJson : fromJson}>{mode === "form" ? "Édition JSON (avancé)" : "Revenir au formulaire"}</button>143      </div>144      <p className="st-help !mt-0 mb-3">Quiz formatif : les réponses sont corrigées dans le navigateur et chaque question doit être expliquée. L’ordre des choix est mélangé à l’affichage, de façon stable pour chaque personne.</p>145      {mode === "json" ? (146        <><Field label="Quiz au format JSON" help="Tous les types d’exercices du moteur sont acceptés ici : single, multiple, true-false, ordering, matching, numeric, fill-blank, debug, reflection.">{(id) => <textarea id={id} className="field st-mono min-h-[26rem]" value={json} onChange={(e) => setJson(e.target.value)} spellCheck={false} />}</Field>{jsonError && <div className="mt-2"><Notice tone="coral"><p>{jsonError}</p></Notice></div>}</>147      ) : (148        <ol className="grid gap-4">149          {quiz.questions.map((q, i) => (150            <li key={i} className="rounded-xl border border-line p-3.5" data-question-editor={q.id}>151              <div className="flex flex-wrap items-center gap-2">152                <span className="st-mono text-faint">{i + 1}.</span>153                <input className="field st-mono !w-24" aria-label={`Identifiant de la question ${i + 1}`} value={q.id} onChange={(e) => setQ(i, { ...q, id: e.target.value.replace(/\s+/g, "") })} />154                {FORM_TYPES.includes(q.type)155                  ? <select className="field !w-auto" aria-label={`Type de la question ${i + 1}`} value={q.type} onChange={(e) => setQ(i, { ...blank(e.target.value, q.id), prompt: q.prompt, explanation: q.explanation })}>{FORM_TYPES.map((t) => <option key={t} value={t}>{TYPE_LABEL[t]}</option>)}</select>156                  : <span className="chip chip-violet">{q.type} — modifiable en JSON</span>}157                <span className="grow" />158                <button type="button" className="btn btn-quiet btn-sm !px-2" disabled={i === 0} onClick={() => move(i, -1)} aria-label={`Monter la question ${i + 1}`}><Icon name="up" size={16} /></button>159                <button type="button" className="btn btn-quiet btn-sm !px-2" disabled={i === quiz.questions.length - 1} onClick={() => move(i, 1)} aria-label={`Descendre la question ${i + 1}`}><Icon name="down" size={16} /></button>160                <button type="button" className="btn btn-quiet btn-sm !px-2" onClick={() => setDrop(i)} aria-label={`Supprimer la question ${i + 1}`}><Icon name="trash" size={16} /></button>161              </div>162              <div className="mt-3 grid gap-3">163                <Field label="Énoncé">{(id) => <textarea id={id} className="field" rows={2} value={q.prompt} onChange={(e) => setQ(i, { ...q, prompt: e.target.value })} />}</Field>164                {(q.type === "single" || q.type === "multiple") && (165                  <fieldset><legend className="st-label">Choix — cocher {q.type === "single" ? "la bonne réponse" : "les bonnes réponses"}</legend>166                    <div className="grid gap-2">167                      {q.options.map((o, k) => { const right = q.type === "single" ? q.answer === o.id : q.answers.includes(o.id); return (168                        <div key={k} className="grid grid-cols-[auto_1fr] items-start gap-2 sm:grid-cols-[auto_1fr_1fr_auto]">169                          <label className="flex items-center gap-1.5 pt-2"><input type={q.type === "single" ? "radio" : "checkbox"} name={`r-${i}`} className="size-4 accent-(--teal)" checked={right} aria-label={`Le choix ${o.id} est une bonne réponse`}170                            onChange={(e) => setQ(i, q.type === "single" ? { ...q, answer: o.id } : { ...q, answers: e.target.checked ? [...q.answers, o.id] : q.answers.filter((a) => a !== o.id) })} /><span className="st-mono">{o.id}</span></label>171                          <input className="field" aria-label={`Texte du choix ${o.id}`} value={o.text} placeholder="Texte du choix" onChange={(e) => setQ(i, { ...q, options: q.options.map((x, j) => (j === k ? { ...x, text: e.target.value } : x)) })} />172                          <input className="field max-sm:col-start-2" aria-label={`Rétroaction du choix ${o.id}`} value={o.feedback ?? ""} placeholder="Rétroaction si ce choix est retenu (facultatif)" onChange={(e) => setQ(i, { ...q, options: q.options.map((x, j) => (j === k ? { ...x, feedback: e.target.value || undefined } : x)) })} />173                          <button type="button" className="btn btn-quiet btn-sm !px-2 max-sm:col-start-2 max-sm:justify-self-start" disabled={q.options.length <= 2} aria-label={`Retirer le choix ${o.id}`}174                            onClick={() => { const options = q.options.filter((_, j) => j !== k); setQ(i, q.type === "single" ? { ...q, options, answer: q.answer === o.id ? options[0]!.id : q.answer } : { ...q, options, answers: q.answers.filter((a) => a !== o.id) }); }}><Icon name="trash" size={16} /></button>175                        </div>176                      ); })}177                    </div>178                    <button type="button" className="btn btn-ghost btn-sm mt-2" disabled={q.options.length >= 8} onClick={() => { const ids = new Set(q.options.map((o) => o.id)); let n = 0; while (ids.has(letter(n))) n++; setQ(i, { ...q, options: [...q.options, { id: letter(n), text: "" }] }); }}>Ajouter un choix</button>179                  </fieldset>180                )}181                {q.type === "true-false" && (182                  <div className="grid gap-3 sm:grid-cols-2">183                    <Field label="Bonne réponse">{(id) => <select id={id} className="field" value={String(q.answer)} onChange={(e) => setQ(i, { ...q, answer: e.target.value === "true" })}><option value="true">Vrai</option><option value="false">Faux</option></select>}</Field>184                    <Field label="Rétroaction en cas d’erreur (facultatif)">{(id) => <input id={id} className="field" value={q.feedbackWrong ?? ""} onChange={(e) => setQ(i, { ...q, feedbackWrong: e.target.value || undefined })} />}</Field>185                  </div>186                )}187                {q.type === "numeric" && (188                  <div className="grid gap-3 sm:grid-cols-3">189                    <Field label="Réponse">{(id) => <input id={id} type="number" step="any" className="field" value={q.answer} onChange={(e) => setQ(i, { ...q, answer: Number(e.target.value) })} />}</Field>190                    <Field label="Tolérance (±)">{(id) => <input id={id} type="number" step="any" min={0} className="field" value={q.tolerance} onChange={(e) => setQ(i, { ...q, tolerance: Math.max(0, Number(e.target.value)) })} />}</Field>191                    <Field label="Unité (facultatif)">{(id) => <input id={id} className="field" value={q.unit ?? ""} onChange={(e) => setQ(i, { ...q, unit: e.target.value || undefined })} />}</Field>192                  </div>193                )}194                <Field label="Explication (affichée après la réponse)">{(id) => <textarea id={id} className="field" rows={2} value={q.explanation} onChange={(e) => setQ(i, { ...q, explanation: e.target.value })} />}</Field>195              </div>196            </li>197          ))}198        </ol>199      )}200      {mode === "form" && <button type="button" className="btn btn-ghost mt-3" onClick={add} data-testid="add-question">Ajouter une question</button>}201      {!valid && quiz.questions.length > 0 && <p className="st-help text-amber">Chaque question doit avoir un énoncé et une explication.</p>}202      {preview && valid && <div className="mt-5 rounded-xl border border-violet p-4" data-testid="quiz-preview"><p className="eyebrow mb-3">Aperçu — moteur d’exercices du site public</p><QuizRunner key={JSON.stringify(quiz)} quiz={{ ...quiz, id: `apercu-studio-${quiz.id}` }} /></div>}203      <SaveBar onSave={() => void save(quiz)} busy={busy} feedback={feedback} dirty={dirty} disabled={!valid || mode === "json"} testid="save-quiz" />204      <Confirm open={drop !== null} onClose={() => setDrop(null)} title="Supprimer cette question ?" confirmLabel="Supprimer la question" danger action={async () => { setQuiz({ ...quiz, questions: quiz.questions.filter((_, j) => j !== drop) as Quiz["questions"] }); }}>205        <p>La question disparaît du formulaire ; rien n’est enregistré tant que vous n’avez pas cliqué « Enregistrer ».</p>206      </Confirm>207    </div>208  );209}210211/* ---- Glossary ---- */212213function GlossaryEditor({ initial, sessionId, save, busy, feedback }: EditorProps & { initial: Glossary; sessionId: string }) {214  const [terms, setTerms] = useState(initial.terms);215  const set = (i: number, patch: Partial<Glossary["terms"][number]>) => setTerms(terms.map((t, j) => (j === i ? { ...t, ...patch } : t)));216  const out = () => { const seen = new Set<string>(); return { terms: terms.filter((t) => t.term.trim() && t.definition.trim()).map((t) => { let id = t.id || slugify(t.term) || "terme"; for (let n = 2; seen.has(id); n++) id = `${t.id || slugify(t.term)}-${n}`; seen.add(id); return { ...t, id, term: t.term.trim(), english: t.english?.trim() || null, definition: t.definition.trim(), session: sessionId }; }) }; };217  return (218    <div data-testid="glossary-editor">219      <div className="grid gap-3">220        {terms.map((t, i) => (221          <div key={i} className="grid gap-2 rounded-xl border border-line p-3 md:grid-cols-[1fr_1fr_auto]">222            <Field label="Terme français">{(id) => <input id={id} className="field" value={t.term} onChange={(e) => set(i, { term: e.target.value })} />}</Field>223            <Field label="Terme anglais (facultatif)">{(id) => <input id={id} className="field" lang="en" value={t.english ?? ""} onChange={(e) => set(i, { english: e.target.value })} />}</Field>224            <button type="button" className="btn btn-quiet btn-sm self-end !px-2" onClick={() => setTerms(terms.filter((_, j) => j !== i))} aria-label={`Retirer le terme ${t.term || i + 1}`}><Icon name="trash" size={16} /></button>225            <Field label="Définition" className="md:col-span-3">{(id) => <textarea id={id} className="field" rows={2} value={t.definition} onChange={(e) => set(i, { definition: e.target.value })} />}</Field>226          </div>227        ))}228        {!terms.length && <p className="text-muted">Aucun terme pour l’instant.</p>}229      </div>230      <button type="button" className="btn btn-ghost mt-3" onClick={() => setTerms([...terms, { id: "", term: "", english: null, definition: "", session: sessionId }])} data-testid="add-term">Ajouter un terme</button>231      <SaveBar onSave={() => void save(out())} busy={busy} feedback={feedback} dirty={JSON.stringify(terms) !== JSON.stringify(initial.terms)} disabled={!out().terms.length} testid="save-glossary" />232    </div>233  );234}235236/* ---- Bibliography ---- */237238function BibliographyEditor({ initial, save, busy, feedback }: EditorProps & { initial: Bibliography }) {239  const [entries, setEntries] = useState(initial.entries);240  const set = (i: number, patch: Partial<Bibliography["entries"][number]>) => setEntries(entries.map((e, j) => (j === i ? { ...e, ...patch } : e)));241  const out = () => ({ entries: entries.filter((e) => e.title.trim()).map((e, i) => ({ ...e, key: e.key.trim() || `ref${i + 1}`, type: e.type || "misc", venue: e.venue?.trim() || null, url: e.url?.trim() || null })) });242  return (243    <div data-testid="bibliography-editor">244      <div className="grid gap-3">245        {entries.map((e, i) => (246          <div key={i} className="grid gap-2 rounded-xl border border-line p-3 md:grid-cols-6">247            <Field label="Auteurs" className="md:col-span-3">{(id) => <input id={id} className="field" value={e.authors} onChange={(ev) => set(i, { authors: ev.target.value })} />}</Field>248            <Field label="Année" className="md:col-span-1">{(id) => <input id={id} className="field" value={e.year} onChange={(ev) => set(i, { year: ev.target.value })} />}</Field>249            <Field label="Clé" className="md:col-span-2">{(id) => <input id={id} className="field st-mono" value={e.key} onChange={(ev) => set(i, { key: ev.target.value.replace(/\s+/g, "") })} />}</Field>250            <Field label="Titre" className="md:col-span-6">{(id) => <input id={id} className="field" value={e.title} onChange={(ev) => set(i, { title: ev.target.value })} />}</Field>251            <Field label="Revue, éditeur ou site" className="md:col-span-3">{(id) => <input id={id} className="field" value={e.venue ?? ""} onChange={(ev) => set(i, { venue: ev.target.value })} />}</Field>252            <Field label="Adresse (https://…)" className="md:col-span-2">{(id) => <input id={id} type="url" className="field" value={e.url ?? ""} onChange={(ev) => set(i, { url: ev.target.value })} />}</Field>253            <button type="button" className="btn btn-quiet btn-sm self-end justify-self-end !px-2" onClick={() => setEntries(entries.filter((_, j) => j !== i))} aria-label={`Retirer la référence ${e.title || i + 1}`}><Icon name="trash" size={16} /></button>254          </div>255        ))}256        {!entries.length && <p className="text-muted">Aucune référence pour l’instant.</p>}257      </div>258      <button type="button" className="btn btn-ghost mt-3" onClick={() => setEntries([...entries, { key: "", type: "misc", authors: "", title: "", year: String(new Date().getFullYear()), venue: null, url: null }])}>Ajouter une référence</button>259      <SaveBar onSave={() => void save(out())} busy={busy} feedback={feedback} dirty={JSON.stringify(entries) !== JSON.stringify(initial.entries)} disabled={!out().entries.length} testid="save-bibliography" />260    </div>261  );262}263264function FiguresView({ figures, sessionId }: { figures: Figures; sessionId: string }) {265  return (266    <>267      <p className="st-help !mt-0 mb-3">Les figures sont exportées de leur source vectorielle dans le dépôt du cours ; elles se mettent à jour par l’importation. Ici se règle seulement leur visibilité.</p>268      <ul className="grid gap-3 sm:grid-cols-2">269        {figures.figures.map((f) => (270          <li key={f.id} className="overflow-hidden rounded-xl border border-line">271            {/* eslint-disable-next-line @next/next/no-img-element -- SVG served by the editor-only route */}272            <div className="bg-[#0b1426] p-2"><img src={`/admin/api/figures/${sessionId}/${f.sha256}`} alt={f.alt} className="mx-auto h-auto max-h-48 w-auto" loading="lazy" /></div>273            <div className="p-3 text-sm"><p><span className="st-mono text-faint">{f.id}</span> {f.caption}</p></div>274          </li>275        ))}276      </ul>277    </>278  );279}280
Files main
Menu

Theme