Repository Public
1"use client";2import { useEffect, useRef, useState } from "react";3import { dict, fill, formatDateTime, KIND_LABEL, LEVEL_LABEL } from "@/i18n/dict";4import { api, idempotencyKey } from "@/lib/client-api";5import { blockText, FORMATS, KINDS, LEVELS, newId, slugify, THEMES, TONES, type Block, type Locale, type Sheet, type SheetDiff, type Source } from "@/schema";6import type { JobView } from "@/server/jobs";7import type { QualityReport } from "@/server/quality";8import type { SheetDetail } from "@/server/sheets";9import type { EditOutput } from "@/ai/pipeline";10import { JobProgress, useJob } from "@/components/admin/job";11import { errorText, money, Notice } from "@/components/admin/ui";12import { IconGlyph } from "@/renderer/icons";13import { BLOCK_CATALOG } from "./forms/defaults";1415const T = dict({16 // Library & outline17 add: ["Ajouter un bloc", "Add a block"], text: ["Texte", "Text"], structure: ["Structure", "Structure"], visual: ["Visuel", "Visual"], data: ["Données", "Data"], interactive: ["Interactif", "Interactive"],18 outline: ["Plan de la fiche", "Sheet outline"], up: ["Monter", "Move up"], down: ["Descendre", "Move down"], locked: ["verrouillé", "locked"],19 // Claude20 claudeLead: ["Demandez une modification. Claude renvoie un changement ciblé, enregistré comme une révision que vous pouvez annuler.", "Ask for a change. Claude returns a targeted change, saved as a revision you can undo."],21 instruction: ["Votre demande", "Your request"], instructionPh: ["Rends le graphique plus lisible sur iPhone", "Make the chart easier to read on a phone"], send: ["Envoyer à Claude", "Send to Claude"],22 scope: ["Limiter aux {n} bloc(s) sélectionné(s)", "Limit to the {n} selected block(s)"], unsaved: ["Vos modifications seront enregistrées avant l’envoi.", "Your changes will be saved before sending."],23 notConfigured: ["Claude n’est pas configuré sur ce serveur (clé API absente).", "Claude is not configured on this server (no API key)."],24 noChange: ["Aucune modification appliquée.", "No change applied."], undoThis: ["Annuler ce changement", "Undo this change"], revision: ["révision {n}", "revision {n}"],25 dAdded: ["{n} ajouté(s)", "{n} added"], dChanged: ["{n} modifié(s)", "{n} changed"], dRemoved: ["{n} retiré(s)", "{n} removed"], dMoved: ["{n} déplacé(s)", "{n} moved"], dMeta: ["métadonnées", "metadata"], dTheme: ["thème", "theme"], dSources: ["sources", "sources"],26 examples: ["Exemples", "Examples"], you: ["Vous", "You"], empty: ["Aucun échange pour l’instant.", "No exchange yet."], show: ["Voir", "Show"],27 // Quality28 qLead: ["Contrôles automatiques : structure, syntaxe, références, accessibilité. Ce rapport n’est pas une validation scientifique — la relecture reste la vôtre.", "Automatic checks: structure, syntax, references, accessibility. This report is not a scientific validation — the review remains yours."],29 errors: ["{n} erreur(s) bloquante(s)", "{n} blocking error(s)"], warnings: ["{n} avertissement(s)", "{n} warning(s)"], infos: ["{n} remarque(s)", "{n} note(s)"], clean: ["Aucun problème détecté par les contrôles automatiques.", "No problem found by the automatic checks."],30 overflow: ["Débordement mesuré dans l’aperçu : le contenu dépasse le format de {px} px.", "Overflow measured in the preview: the content exceeds the format by {px} px."],31 stats: ["{blocks} blocs · {words} mots · {checked}/{sources} sources vérifiées · {unverified} affirmation(s) non vérifiée(s)", "{blocks} blocks · {words} words · {checked}/{sources} sources checked · {unverified} unverified claim(s)"],32 // Sources33 sLead: ["Chaque référence porte un statut. « Trouvée » signifie que le serveur a retrouvé la notice (DOI ou page) ; « Relue » est votre confirmation.", "Every reference carries a status. “Found” means the server located the record (DOI or page); “Reviewed” is your own confirmation."],34 verify: ["Vérifier les sources", "Check the sources"], addSource: ["Ajouter une source", "Add a source"], sTitle: ["Titre", "Title"], authors: ["Auteurs (séparés par ;)", "Authors (separated by ;)"], year: ["Année", "Year"], container: ["Revue / éditeur", "Journal / publisher"],35 type: ["Type", "Type"], note: ["Note", "Note"], markReviewed: ["Marquer comme relue", "Mark as reviewed"], removeSource: ["Retirer", "Remove"], claims: ["Affirmations", "Claims"],36 st_unverified: ["Non vérifiée", "Unverified"], st_resolved: ["Trouvée", "Found"], st_reviewed: ["Relue", "Reviewed"], st_unreachable: ["Injoignable", "Unreachable"],37 cl_sourced: ["sourcée", "sourced"], cl_derived: ["dérivée", "derived"], cl_unverified: ["non vérifiée", "unverified"], checkReport: ["Résultat de la vérification", "Check result"],38 // Meta39 mTitle: ["Titre", "Title"], summary: ["Résumé", "Summary"], topics: ["Thèmes (séparés par des virgules)", "Topics (comma-separated)"], tags: ["Mots-clés (séparés par des virgules)", "Tags (comma-separated)"], level: ["Niveau", "Level"], kind: ["Type", "Kind"],40 objectives: ["Objectifs pédagogiques (un par ligne)", "Learning objectives (one per line)"], theme: ["Style", "Style"], accent: ["Accent", "Accent"], format: ["Format", "Format"], example: ["Afficher le bandeau « exemple non révisé »", "Show the “unreviewed example” banner"],41 publication: ["Publication", "Publication"], slug: ["Adresse (slug)", "Address (slug)"], slugHelp: ["Adresse publique : /s/… Si la fiche a déjà été publique, l’ancienne adresse redirigera (301).", "Public address: /s/… If the sheet has been public, the old address will redirect (301)."],42 seoTitle: ["Titre SEO (facultatif)", "SEO title (optional)"], seoDescription: ["Description SEO (facultative)", "SEO description (optional)"], canonical: ["URL canonique (facultative)", "Canonical URL (optional)"],43 featured: ["Fiche vedette", "Featured sheet"], position: ["Ordre parmi les vedettes", "Order among featured"], download: ["Autoriser le téléchargement PDF aux lecteurs", "Let readers download the PDF"], saveSettings: ["Enregistrer ces réglages", "Save these settings"], saved: ["Réglages enregistrés.", "Settings saved."],44 status: ["Statut", "Status"], draft: ["Brouillon", "Draft"], in_review: ["En révision", "In review"], archived: ["Archivée", "Archived"],45});4647const sel = "field", lab = "grid gap-1.5 text-sm font-medium";4849// ── Block library ───────────────────────────────────────────────────────────────────────────────────5051export function LibraryPanel({ locale, onAdd }: { locale: Locale; onAdd: (type: Block["type"]) => void }) {52 const t = T(locale);53 const groups = ["text", "structure", "visual", "data", "interactive"] as const;54 return (55 <div className="grid gap-4">56 {groups.map((g) => (57 <section key={g} aria-label={t[g]}>58 <h3 className="eyebrow mb-2">{t[g]}</h3>59 <ul className="grid grid-cols-2 gap-2">60 {BLOCK_CATALOG.filter((c) => c.group === g).map((c) => (61 <li key={c.type}>62 <button type="button" className="flex min-h-14 w-full items-center gap-2 rounded-xl border border-line bg-surface px-2.5 py-2 text-left text-sm hover:border-faint" onClick={() => onAdd(c.type)} title={c.description[locale]}>63 <span className="shrink-0 text-accent"><IconGlyph name={c.icon} size={18} /></span><span className="min-w-0 text-[0.8125rem] font-medium leading-tight [overflow-wrap:anywhere]">{c.label[locale]}</span>64 </button>65 </li>66 ))}67 </ul>68 </section>69 ))}70 </div>71 );72}7374export function OutlinePanel({ doc, locale, selected, onSelect, onMove }: { doc: Sheet; locale: Locale; selected: string[]; onSelect: (id: string, additive: boolean) => void; onMove: (id: string, delta: number) => void }) {75 const t = T(locale);76 const label = (type: string) => BLOCK_CATALOG.find((c) => c.type === type)?.label[locale] ?? type;77 return (78 <ol className="grid gap-1" aria-label={t.outline}>79 {doc.blocks.map((b, i) => (80 <li key={b.id} className={`flex items-center gap-1 rounded-lg border ${selected.includes(b.id) ? "border-accent bg-accent-soft" : "border-transparent hover:bg-raised"}`}>81 <button type="button" className="min-h-11 min-w-0 flex-1 px-2 text-left" onClick={(e) => onSelect(b.id, e.shiftKey || e.metaKey || e.ctrlKey)} aria-pressed={selected.includes(b.id)}>82 <span className="block text-[0.6875rem] font-semibold uppercase tracking-wide text-faint">{label(b.type)}{b.locked ? ` · ${t.locked}` : ""}</span>83 <span className="block truncate text-sm">{blockText(b).slice(0, 80) || "—"}</span>84 </button>85 <button type="button" className="btn btn-ghost btn-sm !min-h-11 !px-2" aria-label={`${t.up} — ${label(b.type)}`} disabled={i === 0 || !!b.locked} onClick={() => onMove(b.id, -1)}>▲</button>86 <button type="button" className="btn btn-ghost btn-sm !min-h-11 !px-2" aria-label={`${t.down} — ${label(b.type)}`} disabled={i === doc.blocks.length - 1 || !!b.locked} onClick={() => onMove(b.id, 1)}>▼</button>87 </li>88 ))}89 </ol>90 );91}9293// ── Claude conversation ─────────────────────────────────────────────────────────────────────────────9495interface Message { id: string; role: string; content: string; jobId: string | null; revisionId: string | null; revisionNumber: number | null; diff: SheetDiff | null; createdAt: string }9697export function diffSummary(d: SheetDiff, locale: Locale): string {98 const t = T(locale);99 return [d.added.length && fill(t.dAdded, { n: d.added.length }), d.changed.length && fill(t.dChanged, { n: d.changed.length }), d.removed.length && fill(t.dRemoved, { n: d.removed.length }), d.moved.length && fill(t.dMoved, { n: d.moved.length }),100 d.metadata.length && t.dMeta, d.theme && t.dTheme, (d.sources || d.claims) && t.dSources].filter(Boolean).join(" · ");101}102103const EXAMPLES: [string, string][] = [104 ["Mets les étapes dans l’ordre chronologique", "Put the steps in chronological order"], ["Remplace la palette par un thème sombre", "Switch the palette to a dark theme"],105 ["Ajoute une démonstration mathématique", "Add a mathematical derivation"], ["Rends le diagramme plus lisible sur iPhone", "Make the diagram easier to read on a phone"],106 ["Ajoute une animation qui explique le processus pas à pas", "Add an animation that explains the process step by step"],107];108109export function ClaudePanel({ sheetId, locale, uiLocale, selected, configured, ensureSaved, onApplied, onHighlight, onUndoRevision }: {110 sheetId: string; locale: Locale; uiLocale: Locale; selected: string[]; configured: boolean;111 /** Saves pending edits and returns the version the request is based on. */112 ensureSaved: () => Promise<number>;113 /** A job changed the sheet on the server: reload it. */114 onApplied: (diff: SheetDiff | null) => Promise<void>;115 onHighlight: (ids: string[]) => void;116 /** Restores the revision that preceded `revisionId`. */117 onUndoRevision: (revisionId: string) => Promise<void>;118}) {119 const t = T(uiLocale), fr = uiLocale === "fr";120 const [messages, setMessages] = useState<Message[]>([]), [text, setText] = useState(""), [scoped, setScoped] = useState(true);121 const [jobId, setJobId] = useState<string | null>(null), [error, setError] = useState<string | null>(null), [busy, setBusy] = useState(false);122 const end = useRef<HTMLDivElement>(null);123 const load = async () => { try { const r = await api<{ messages: Message[]; jobs: JobView[] }>(`/api/admin/sheets/${sheetId}/conversation`); setMessages(r.messages); const live = r.jobs.find((j) => (j.status === "queued" || j.status === "running") && j.kind === "edit"); if (live) setJobId((cur) => cur ?? live.id); } catch (e) { setError(errorText(e, fr)); } };124 useEffect(() => { void load(); }, [sheetId]); // eslint-disable-line react-hooks/exhaustive-deps125 useEffect(() => { end.current?.scrollIntoView({ block: "nearest" }); }, [messages.length, jobId]);126127 const job = useJob(jobId, async (j) => {128 if (j.status === "succeeded") { const out = j.output as EditOutput; await onApplied(out.changed ? out.diff : null); }129 await load();130 if (j.status !== "failed") setJobId(null);131 });132 const running = !!job && (job.status === "queued" || job.status === "running");133134 const send = async (ev?: React.FormEvent) => {135 ev?.preventDefault();136 const instruction = text.trim();137 if (instruction.length < 2 || busy || running) return;138 setBusy(true); setError(null);139 try {140 const baseVersion = await ensureSaved();141 const j = await api<JobView>(`/api/admin/sheets/${sheetId}/ai-edit`, { body: { instruction, baseVersion, scope: scoped && selected.length ? selected : null, idempotencyKey: idempotencyKey() } });142 setText(""); setJobId(j.id);143 setMessages((m) => [...m, { id: `pending-${j.id}`, role: "user", content: instruction, jobId: j.id, revisionId: null, revisionNumber: null, diff: null, createdAt: new Date().toISOString() }]);144 } catch (e) { setError(errorText(e, fr)); }145 setBusy(false);146 };147148 if (!configured) return <Notice tone="warn">{t.notConfigured}</Notice>;149 return (150 <div className="flex h-full min-h-0 flex-col gap-3">151 <p className="text-sm text-muted">{t.claudeLead}</p>152 <ol className="grid min-h-0 flex-1 content-start gap-2 overflow-y-auto" aria-live="polite">153 {messages.length === 0 && <li className="text-sm text-faint">{t.empty}</li>}154 {messages.map((m) => (155 <li key={m.id} className={`rounded-xl border px-3 py-2 text-sm leading-relaxed ${m.role === "user" ? "ml-6 border-line bg-raised" : "mr-6 border-accent/30 bg-accent-soft"}`}>156 <p className="eyebrow mb-1">{m.role === "user" ? t.you : "Claude"} · {formatDateTime(m.createdAt, uiLocale)}</p>157 <p className="whitespace-pre-wrap" lang={m.role === "assistant" ? locale : undefined}>{m.content}</p>158 {m.role === "assistant" && m.diff && (159 <div className="mt-2 flex flex-wrap items-center gap-2 border-t border-accent/20 pt-2 text-xs">160 <span className="font-semibold">{m.revisionNumber ? fill(t.revision, { n: m.revisionNumber }) + " · " : ""}{diffSummary(m.diff, uiLocale)}</span>161 <button type="button" className="btn btn-sm !min-h-9" onClick={() => onHighlight([...m.diff!.added, ...m.diff!.changed])}>{t.show}</button>162 {m.revisionId && <button type="button" className="btn btn-sm !min-h-9" onClick={() => void onUndoRevision(m.revisionId!).then(load).catch((e) => setError(errorText(e, fr)))}>{t.undoThis}</button>}163 </div>164 )}165 {m.role === "assistant" && !m.diff && !m.revisionId && m.jobId && <p className="mt-1 text-xs text-faint">{t.noChange}</p>}166 </li>167 ))}168 {job && (running || job.status === "failed") && <li><JobProgress job={job} /></li>}169 <div ref={end} />170 </ol>171 {error && <Notice tone="bad">{error}</Notice>}172 <form onSubmit={send} className="grid gap-2 border-t border-line pt-3">173 <label className="sr-only" htmlFor="ai-instruction">{t.instruction}</label>174 <textarea id="ai-instruction" className="field min-h-20" value={text} onChange={(e) => setText(e.target.value)} placeholder={t.instructionPh} maxLength={4000} disabled={running}175 onKeyDown={(e) => { if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) void send(); }} />176 {selected.length > 0 && <label className="flex min-h-11 items-center gap-2 text-sm"><input type="checkbox" className="h-5 w-5" checked={scoped} onChange={(e) => setScoped(e.target.checked)} />{fill(t.scope, { n: selected.length })}</label>}177 <details className="text-sm"><summary className="flex min-h-9 cursor-pointer items-center text-faint">{t.examples}</summary>178 <ul className="grid gap-1 pb-1">{EXAMPLES.map(([a, b]) => <li key={a}><button type="button" className="min-h-9 text-left text-accent" onClick={() => setText(fr ? a : b)}>{fr ? a : b}</button></li>)}</ul></details>179 <button className="btn btn-primary" disabled={busy || running || text.trim().length < 2}>{t.send}</button>180 {job && !running && job.usage.costUsd > 0 && <p className="text-xs text-faint">{money(job.usage.costUsd)}</p>}181 </form>182 </div>183 );184}185186// ── Quality report ──────────────────────────────────────────────────────────────────────────────────187188export function QualityPanel({ report, locale, overflowPx, onSelect }: { report: QualityReport | null; locale: Locale; overflowPx: number; onSelect: (id: string) => void }) {189 const t = T(locale);190 if (!report) return <p className="text-sm text-faint">…</p>;191 const tone = { error: "border-bad/40 bg-bad/10", warning: "border-warn/40 bg-warn/10", info: "border-line bg-raised" };192 return (193 <div className="grid gap-3">194 <p className="text-sm text-muted">{t.qLead}</p>195 <p className="flex flex-wrap gap-2 text-sm font-semibold">196 <span className={report.errors ? "text-bad" : "text-faint"}>{fill(t.errors, { n: report.errors })}</span>197 <span className={report.warnings ? "text-warn" : "text-faint"}>{fill(t.warnings, { n: report.warnings })}</span>198 <span className="text-faint">{fill(t.infos, { n: report.infos })}</span>199 </p>200 <p className="text-xs text-faint">{fill(t.stats, { blocks: report.stats.blocks, words: report.stats.words, checked: report.stats.sourcesChecked, sources: report.stats.sources, unverified: report.stats.claimsUnverified })}</p>201 {overflowPx > 0 && <div className={`rounded-xl border px-3 py-2 text-sm ${tone.warning}`}>{fill(t.overflow, { px: overflowPx })}</div>}202 {report.items.length === 0 && overflowPx === 0 && <Notice tone="ok">{t.clean}</Notice>}203 <ul className="grid gap-2">204 {report.items.map((i, k) => (205 <li key={k}>206 {i.blockId207 ? <button type="button" className={`w-full rounded-xl border px-3 py-2 text-left text-sm leading-snug ${tone[i.severity]}`} onClick={() => onSelect(i.blockId!)}>{locale === "fr" ? i.fr : i.en}<span className="mt-0.5 block font-mono text-xs text-faint">{i.blockId}</span></button>208 : <div className={`rounded-xl border px-3 py-2 text-sm leading-snug ${tone[i.severity]}`}>{locale === "fr" ? i.fr : i.en}</div>}209 </li>210 ))}211 </ul>212 </div>213 );214}215216// ── Sources and claims ──────────────────────────────────────────────────────────────────────────────217218interface CheckOutput { checks: { id: string; status: Source["status"]; detail: string }[] }219220export function SourcesPanel({ sheetId, doc, locale, onChange, ensureSaved, onApplied }: { sheetId: string; doc: Sheet; locale: Locale; onChange: (next: Sheet) => void; ensureSaved: () => Promise<number>; onApplied: () => Promise<void> }) {221 const t = T(locale), fr = locale === "fr";222 const [jobId, setJobId] = useState<string | null>(null), [error, setError] = useState<string | null>(null), [checks, setChecks] = useState<CheckOutput["checks"] | null>(null);223 const job = useJob(jobId, async (j) => { if (j.status === "succeeded") { setChecks((j.output as CheckOutput).checks); await onApplied(); } if (j.status !== "failed") setJobId(null); });224 const running = !!job && (job.status === "queued" || job.status === "running");225 const set = (id: string, patch: Partial<Source>) => onChange({ ...doc, sources: doc.sources.map((s) => (s.id === id ? { ...s, ...patch, ...(("doi" in patch || "url" in patch || "title" in patch) && s.status !== "reviewed" ? { status: "unverified" as const, checkedAt: undefined } : {}) } : s)) });226 const remove = (id: string) => onChange({ ...doc, sources: doc.sources.filter((s) => s.id !== id), claims: doc.claims.map((c) => ({ ...c, sourceIds: c.sourceIds.filter((x) => x !== id) })),227 blocks: doc.blocks.map((b) => (b.sourceIds ? { ...b, sourceIds: b.sourceIds.filter((x) => x !== id) } : b)) });228 const add = () => onChange({ ...doc, sources: [...doc.sources, { id: newId("s"), type: "article", title: fr ? "Titre de la référence" : "Reference title", authors: [], status: "unverified" }] });229 const verify = async () => { setError(null); setChecks(null); try { await ensureSaved(); const j = await api<JobView>(`/api/admin/sheets/${sheetId}/verify-sources`, { method: "POST", body: {} }); setJobId(j.id); } catch (e) { setError(errorText(e, fr)); } };230 const pill = { unverified: "text-warn border-warn/40", resolved: "text-ok border-ok/40", reviewed: "text-ok border-ok/40", unreachable: "text-bad border-bad/40" };231 return (232 <div className="grid gap-3">233 <p className="text-sm text-muted">{t.sLead}</p>234 <div className="flex flex-wrap gap-2"><button type="button" className="btn btn-sm" onClick={verify} disabled={running || doc.sources.length === 0}>{t.verify}</button><button type="button" className="btn btn-sm" onClick={add} disabled={doc.sources.length >= 60}>{t.addSource}</button></div>235 {job && (running || job.status === "failed") && <JobProgress job={job} />}236 {error && <Notice tone="bad">{error}</Notice>}237 {checks && <Notice><strong>{t.checkReport}</strong><ul className="mt-1 grid gap-1">{checks.map((c) => <li key={c.id}><span className="font-mono text-xs">{c.id}</span> — {t[`st_${c.status}`]} : {c.detail}</li>)}</ul></Notice>}238 <ul className="grid gap-3">239 {doc.sources.map((s, n) => (240 <li key={s.id} className="card grid gap-2 p-3">241 <div className="flex items-center justify-between gap-2">242 <span className="font-mono text-xs text-faint">[{n + 1}] {s.id}</span>243 <span className={`rounded-full border px-2 py-0.5 text-xs font-semibold ${pill[s.status]}`}>{t[`st_${s.status}`]}</span>244 </div>245 <label className={lab}>{t.sTitle}<textarea className="field min-h-16" defaultValue={s.title} key={s.title} maxLength={400} onBlur={(e) => e.target.value.trim() && set(s.id, { title: e.target.value.trim() })} /></label>246 <label className={lab}>{t.authors}<input className="field" defaultValue={s.authors.join("; ")} key={s.authors.join()} onBlur={(e) => set(s.id, { authors: e.target.value.split(";").map((a) => a.trim().slice(0, 120)).filter(Boolean).slice(0, 30) })} /></label>247 <div className="grid grid-cols-2 gap-2">248 <label className={lab}>{t.year}<input className="field" type="number" inputMode="numeric" min={1500} max={2100} defaultValue={s.year ?? ""} key={s.year} onBlur={(e) => set(s.id, { year: e.target.value ? Math.min(2100, Math.max(1500, Math.round(Number(e.target.value)))) : undefined })} /></label>249 <label className={lab}>{t.type}<select className={sel} value={s.type} onChange={(e) => set(s.id, { type: e.target.value as Source["type"] })}>{["article", "book", "preprint", "documentation", "dataset", "web", "report", "upload"].map((x) => <option key={x}>{x}</option>)}</select></label>250 </div>251 <label className={lab}>{t.container}<input className="field" defaultValue={s.container ?? ""} key={s.container} maxLength={300} onBlur={(e) => set(s.id, { container: e.target.value.trim() || undefined })} /></label>252 <label className={lab}>DOI<input className="field font-mono text-sm" defaultValue={s.doi ?? ""} key={s.doi} placeholder="10.xxxx/…" autoCapitalize="none" spellCheck={false} onBlur={(e) => { const v = e.target.value.trim().replace(/^https?:\/\/(dx\.)?doi\.org\//, ""); if (!v) set(s.id, { doi: undefined }); else if (/^10\.\d{4,9}\/\S+$/.test(v)) set(s.id, { doi: v }); else e.target.value = s.doi ?? ""; }} /></label>253 <label className={lab}>URL<input className="field font-mono text-sm" type="url" inputMode="url" defaultValue={s.url ?? ""} key={s.url} placeholder="https://" autoCapitalize="none" spellCheck={false} onBlur={(e) => { const v = e.target.value.trim(); if (!v) set(s.id, { url: undefined }); else if (/^https:\/\/\S+$/.test(v)) set(s.id, { url: v }); else e.target.value = s.url ?? ""; }} /></label>254 <div className="flex flex-wrap gap-2">255 {s.status !== "reviewed" && <button type="button" className="btn btn-sm" onClick={() => set(s.id, { status: "reviewed", checkedAt: new Date().toISOString() })}>{t.markReviewed}</button>}256 <button type="button" className="btn btn-sm btn-danger" onClick={() => remove(s.id)}>{t.removeSource}</button>257 </div>258 </li>259 ))}260 </ul>261 {doc.claims.length > 0 && (262 <section>263 <h3 className="eyebrow mb-2">{t.claims}</h3>264 <ul className="grid gap-2">{doc.claims.map((c) => (265 <li key={c.id} className="rounded-xl border border-line px-3 py-2 text-sm leading-snug">266 {c.text}267 <span className="mt-1 flex flex-wrap items-center gap-2 text-xs">268 <select aria-label={t.status} className="rounded-md border border-line bg-surface px-2 py-1.5" value={c.status} onChange={(e) => onChange({ ...doc, claims: doc.claims.map((x) => (x.id === c.id ? { ...x, status: e.target.value as typeof c.status } : x)) })}>269 <option value="sourced">{t.cl_sourced}</option><option value="derived">{t.cl_derived}</option><option value="unverified">{t.cl_unverified}</option></select>270 <span className="font-mono text-faint">{c.sourceIds.join(", ")}</span>271 </span>272 </li>))}</ul>273 </section>274 )}275 </div>276 );277}278279// ── Metadata, theme and publication settings ────────────────────────────────────────────────────────280281const THEME_LABEL: Record<(typeof THEMES)[number], [string, string]> = { "scientific-light": ["Scientifique clair", "Scientific light"], "scientific-dark": ["Scientifique sombre", "Scientific dark"], editorial: ["Éditorial", "Editorial"], blueprint: ["Plan technique", "Blueprint"], finance: ["Finance", "Finance"] };282const FORMAT_LABEL: Record<(typeof FORMATS)[number], [string, string]> = { article: ["Article responsive", "Responsive article"], a4: ["A4 (794 × 1123)", "A4 (794 × 1123)"], "slide-16-9": ["Présentation 16:9 (1600 × 900)", "Slide 16:9 (1600 × 900)"], square: ["Carré (1080 × 1080)", "Square (1080 × 1080)"], "portrait-4-5": ["Vertical 4:5 (1080 × 1350)", "Portrait 4:5 (1080 × 1350)"] };283284export function MetaPanel({ detail, doc, locale, onChange, onSettingsSaved }: { detail: SheetDetail; doc: Sheet; locale: Locale; onChange: (next: Sheet, key?: string) => void; onSettingsSaved: () => Promise<void> }) {285 const t = T(locale), fr = locale === "fr", m = doc.metadata;286 const meta = (patch: Partial<Sheet["metadata"]>, key: string) => onChange({ ...doc, metadata: { ...m, ...patch } }, `meta:${key}`);287 const list = (v: string, max: number, len: number) => v.split(",").map((s) => s.trim().slice(0, len)).filter(Boolean).slice(0, max);288 const [s, setS] = useState({ slug: detail.slug, status: detail.status === "published" ? "draft" : detail.status, seoTitle: detail.seoTitle ?? "", seoDescription: detail.seoDescription ?? "", canonicalUrl: detail.canonicalUrl ?? "", featured: detail.featured, featuredPosition: detail.featuredPosition, allowDownload: detail.allowDownload });289 const [msg, setMsg] = useState<{ tone: "ok" | "bad"; text: string } | null>(null), [busy, setBusy] = useState(false);290 const save = async (ev: React.FormEvent) => {291 ev.preventDefault(); setBusy(true); setMsg(null);292 try {293 await api(`/api/admin/sheets/${detail.id}`, { method: "PATCH", body: { settings: { slug: s.slug, ...(detail.status === "published" ? {} : { status: s.status }), seoTitle: s.seoTitle.trim() || null, seoDescription: s.seoDescription.trim() || null, canonicalUrl: s.canonicalUrl.trim() || null, featured: s.featured, featuredPosition: s.featuredPosition, allowDownload: s.allowDownload } } });294 await onSettingsSaved(); setMsg({ tone: "ok", text: t.saved });295 } catch (e) { setMsg({ tone: "bad", text: errorText(e, fr) }); }296 setBusy(false);297 };298 return (299 <div className="grid gap-4">300 <label className={lab}>{t.mTitle}<input className="field" value={m.title} maxLength={160} onChange={(e) => e.target.value && meta({ title: e.target.value }, "title")} /></label>301 <label className={lab}>{t.summary}<textarea className="field min-h-24" value={m.summary} maxLength={400} onChange={(e) => meta({ summary: e.target.value }, "summary")} /></label>302 <label className={lab}>{t.topics}<input className="field" defaultValue={m.topics.join(", ")} key={m.topics.join()} onBlur={(e) => meta({ topics: list(e.target.value, 6, 60) }, "topics")} /></label>303 <label className={lab}>{t.tags}<input className="field" defaultValue={m.tags.join(", ")} key={m.tags.join()} onBlur={(e) => meta({ tags: list(e.target.value, 12, 40) }, "tags")} /></label>304 <div className="grid grid-cols-2 gap-2">305 <label className={lab}>{t.level}<select className={sel} value={m.level} onChange={(e) => meta({ level: e.target.value as typeof m.level }, "level")}>{LEVELS.map((x) => <option key={x} value={x}>{LEVEL_LABEL(locale)[x]}</option>)}</select></label>306 <label className={lab}>{t.kind}<select className={sel} value={m.kind} onChange={(e) => meta({ kind: e.target.value as typeof m.kind }, "kind")}>{KINDS.map((x) => <option key={x} value={x}>{KIND_LABEL(locale)[x]}</option>)}</select></label>307 </div>308 <label className={lab}>{t.objectives}<textarea className="field min-h-24" defaultValue={m.objectives.join("\n")} key={m.objectives.join("|")} onBlur={(e) => meta({ objectives: e.target.value.split("\n").map((x) => x.trim().slice(0, 300)).filter(Boolean).slice(0, 6) }, "objectives")} /></label>309 <div className="grid grid-cols-2 gap-2">310 <label className={lab}>{t.theme}<select className={sel} value={doc.theme.preset} onChange={(e) => onChange({ ...doc, theme: { ...doc.theme, preset: e.target.value as typeof doc.theme.preset } })}>{THEMES.map((x) => <option key={x} value={x}>{THEME_LABEL[x][fr ? 0 : 1]}</option>)}</select></label>311 <label className={lab}>{t.accent}<select className={sel} value={doc.theme.accent} onChange={(e) => onChange({ ...doc, theme: { ...doc.theme, accent: e.target.value as typeof doc.theme.accent } })}>{TONES.map((x) => <option key={x}>{x}</option>)}</select></label>312 </div>313 <label className={lab}>{t.format}<select className={sel} value={doc.layout.format} onChange={(e) => onChange({ ...doc, layout: { ...doc.layout, format: e.target.value as typeof doc.layout.format } })}>{FORMATS.map((x) => <option key={x} value={x}>{FORMAT_LABEL[x][fr ? 0 : 1]}</option>)}</select></label>314 <label className="flex min-h-11 items-center gap-2 text-sm"><input type="checkbox" className="h-5 w-5" checked={!!m.example} onChange={(e) => meta({ example: e.target.checked || undefined }, "example")} />{t.example}</label>315316 <form onSubmit={save} className="grid gap-3 border-t border-line pt-4">317 <h3 className="eyebrow">{t.publication}</h3>318 <label className={lab}>{t.slug}319 <input className="field font-mono text-sm" value={s.slug} maxLength={96} autoCapitalize="none" spellCheck={false} onChange={(e) => setS({ ...s, slug: e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, "-") })} onBlur={() => setS((x) => ({ ...x, slug: slugify(x.slug) }))} required />320 <span className="font-normal text-faint">{t.slugHelp}</span></label>321 {detail.status !== "published" && <label className={lab}>{t.status}<select className={sel} value={s.status} onChange={(e) => setS({ ...s, status: e.target.value as typeof s.status })}><option value="draft">{t.draft}</option><option value="in_review">{t.in_review}</option><option value="archived">{t.archived}</option></select></label>}322 <label className={lab}>{t.seoTitle}<input className="field" value={s.seoTitle} maxLength={120} onChange={(e) => setS({ ...s, seoTitle: e.target.value })} /></label>323 <label className={lab}>{t.seoDescription}<textarea className="field min-h-20" value={s.seoDescription} maxLength={300} onChange={(e) => setS({ ...s, seoDescription: e.target.value })} /></label>324 <label className={lab}>{t.canonical}<input className="field font-mono text-sm" type="url" inputMode="url" placeholder="https://" value={s.canonicalUrl} maxLength={500} onChange={(e) => setS({ ...s, canonicalUrl: e.target.value })} /></label>325 <label className="flex min-h-11 items-center gap-2 text-sm"><input type="checkbox" className="h-5 w-5" checked={s.featured} onChange={(e) => setS({ ...s, featured: e.target.checked })} />{t.featured}</label>326 {s.featured && <label className={lab}>{t.position}<input className="field" type="number" inputMode="numeric" min={0} max={999} value={s.featuredPosition} onChange={(e) => setS({ ...s, featuredPosition: Math.max(0, Math.min(999, Math.round(Number(e.target.value) || 0))) })} /></label>}327 <label className="flex min-h-11 items-center gap-2 text-sm"><input type="checkbox" className="h-5 w-5" checked={s.allowDownload} onChange={(e) => setS({ ...s, allowDownload: e.target.checked })} />{t.download}</label>328 {msg && <Notice tone={msg.tone}>{msg.text}</Notice>}329 <button className="btn" disabled={busy}>{t.saveSettings}</button>330 </form>331 </div>332 );333}334