Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : UQO Éval — Le Grand Défi Immobilier8 * File : apps/web/src/admin/ui.tsx9 * Module : admin10 * Repository : https://git.spboucher.ai/uqo-eval-jeux11 * Project Website : https://jeux.uqo-eval.app12 * Created : 2026-11-2513 * Last Modified : 2026-11-2514 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243/** Composants partagés de l'espace d'administration. */44import { createContext, useCallback, useContext, useEffect, useId, useRef, useState, type ReactNode, type SVGProps } from "react";45import { formatInt } from "@jeux/engine/format";46import { IconCross } from "../components/Icons";47import { errorMessage, exportUrl, formatClock, nb, type Loaded, type Tally } from "./lib";4849/* ---------- Icônes fonctionnelles ---------- */5051function Glyph({ children, size = 18, ...rest }: SVGProps<SVGSVGElement> & { size?: number }) {52 return (53 <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.7} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true" focusable="false" {...rest}>54 {children}55 </svg>56 );57}58export const IconRefresh = ({ size }: { size?: number }) => <Glyph size={size}><path d="M20 11a8 8 0 10-2.3 5.7M20 5v6h-6" /></Glyph>;59export const IconCopy = ({ size }: { size?: number }) => <Glyph size={size}><rect x="9" y="9" width="11" height="11" rx="2" /><path d="M5 15V6a2 2 0 012-2h9" /></Glyph>;60export const IconDownload = ({ size }: { size?: number }) => <Glyph size={size}><path d="M12 4v11M7 11l5 5 5-5M5 20h14" /></Glyph>;61export const IconLock = ({ size }: { size?: number }) => <Glyph size={size}><rect x="5" y="11" width="14" height="9" rx="2" /><path d="M8 11V8a4 4 0 018 0v3" /></Glyph>;62export const IconAlert = ({ size }: { size?: number }) => <Glyph size={size}><path d="M12 4l9 16H3zM12 10v4M12 17h.01" /></Glyph>;63export const IconInfo = ({ size }: { size?: number }) => <Glyph size={size}><circle cx="12" cy="12" r="9" /><path d="M12 11v5M12 8h.01" /></Glyph>;6465/* ---------- Retours d'action (aria-live) ---------- */6667interface Notice {68 id: number;69 kind: "ok" | "error";70 text: string;71}7273const NotifyContext = createContext<(text: string, kind?: Notice["kind"]) => void>(() => {});7475export function useNotify(): (text: string, kind?: Notice["kind"]) => void {76 return useContext(NotifyContext);77}7879export function NotifyProvider({ children }: { children: ReactNode }) {80 const [notice, setNotice] = useState<Notice | null>(null);81 const notify = useCallback((text: string, kind: Notice["kind"] = "ok") => setNotice({ id: Date.now(), kind, text }), []);82 useEffect(() => {83 if (!notice) return;84 const timer = window.setTimeout(() => setNotice(null), notice.kind === "error" ? 9000 : 5000);85 return () => window.clearTimeout(timer);86 }, [notice]);87 return (88 <NotifyContext.Provider value={notify}>89 {children}90 <div className="adm-live" role="status" aria-live="polite" aria-atomic="true">91 {notice && (92 <div className={`adm-toast${notice.kind === "error" ? " is-error" : ""}`} key={notice.id}>93 <span><strong>{notice.kind === "error" ? "Échec : " : "Fait : "}</strong>{notice.text}</span>94 <button type="button" className="adm-toast-close" onClick={() => setNotice(null)} aria-label="Fermer le message"><IconCross size={18} /></button>95 </div>96 )}97 </div>98 </NotifyContext.Provider>99 );100}101102/* ---------- Structure de page ---------- */103104export function PageHead({ title, lede, actions, back }: { title: string; lede?: ReactNode; actions?: ReactNode; back?: ReactNode }) {105 return (106 <header className="adm-head">107 <div className="adm-head-text">108 {back ?? <p className="kicker">Administration</p>}109 <h1 className="title" tabIndex={-1} id="adm-titre">{title}</h1>110 {lede && <p className="adm-lede">{lede}</p>}111 </div>112 {actions && <div className="adm-head-actions">{actions}</div>}113 </header>114 );115}116117export function Section({ title, aside, note, children, id }: { title: string; aside?: ReactNode; note?: ReactNode; children: ReactNode; id?: string }) {118 const auto = useId();119 const headingId = id ?? auto;120 return (121 <section className="adm-section" aria-labelledby={headingId}>122 <div className="adm-section-head">123 <h2 id={headingId}>{title}</h2>124 {aside && <div className="adm-section-aside">{aside}</div>}125 </div>126 {note && <p className="adm-section-note">{note}</p>}127 {children}128 </section>129 );130}131132export function RefreshButton({ state, label = "Actualiser" }: { state: Pick<Loaded<unknown>, "reload" | "loading" | "refreshing" | "loadedAt">; label?: string }) {133 const busy = state.loading || state.refreshing;134 return (135 <div className="adm-refresh">136 {state.loadedAt !== null && <span className="small muted">Mis à jour à {formatClock(state.loadedAt)}</span>}137 <button type="button" className="btn btn-ghost" onClick={() => void state.reload()} disabled={busy}>138 <span className={busy ? "adm-spin" : undefined}><IconRefresh /></span>139 {busy ? "Actualisation…" : label}140 </button>141 </div>142 );143}144145/** États de chargement, d'erreur et de contenu d'une ressource. */146export function LoadState<T>({ state, children, label = "Chargement des données…" }: { state: Loaded<T>; children: (data: T) => ReactNode; label?: string }) {147 if (state.data === null) {148 if (state.error) return <ErrorBox message={state.error} onRetry={() => void state.reload()} />;149 return (150 <div className="adm-loading" role="status">151 <span className="spinner" aria-hidden="true" />152 <span>{label}</span>153 </div>154 );155 }156 return (157 <>158 {state.error && <ErrorBox message={`${state.error} Les données affichées peuvent dater.`} onRetry={() => void state.reload()} />}159 {children(state.data)}160 </>161 );162}163164export function ErrorBox({ message, onRetry }: { message: string; onRetry?: () => void }) {165 return (166 <div className="adm-note is-error" role="alert">167 <IconAlert />168 <div>169 <p><strong>Erreur.</strong> {message}</p>170 {onRetry && <button type="button" className="adm-textbtn" onClick={onRetry}>Réessayer</button>}171 </div>172 </div>173 );174}175176export function Empty({ title, children }: { title: string; children?: ReactNode }) {177 return (178 <div className="adm-empty">179 <p className="adm-empty-title">{title}</p>180 {children && <div className="small muted">{children}</div>}181 </div>182 );183}184185export function Note({ tone = "info", title, children }: { tone?: "info" | "lock" | "warn" | "error"; title?: string; children: ReactNode }) {186 return (187 <div className={`adm-note is-${tone}`}>188 {tone === "lock" ? <IconLock /> : tone === "info" ? <IconInfo /> : <IconAlert />}189 <div>{title && <strong>{title} </strong>}{children}</div>190 </div>191 );192}193194/** Conteneur défilant : le tableau défile, jamais la page. */195export function TableScroll({ label, children }: { label: string; children: ReactNode }) {196 return (197 <div className="adm-scroll" role="region" aria-label={label} tabIndex={0}>198 {children}199 </div>200 );201}202203/** Chiffres clés composés en ligne, séparés par des filets. */204export function Figures({ items, label }: { items: { label: string; value: ReactNode; note?: ReactNode }[]; label: string }) {205 return (206 <dl className="adm-figures" aria-label={label}>207 {items.map((item) => (208 <div key={item.label}>209 <dt>{item.label}</dt>210 <dd>211 <span className="num adm-figure-value">{item.value}</span>212 {item.note && <span className="adm-figure-note">{item.note}</span>}213 </dd>214 </div>215 ))}216 </dl>217 );218}219220/** Liste de barres horizontales (effectifs), valeurs toujours écrites. */221export function TallyBars({ rows, label, total }: { rows: Tally[]; label: string; total?: number }) {222 if (rows.length === 0) return <p className="small muted">Aucune donnée.</p>;223 const max = Math.max(1, ...rows.map((r) => r.n));224 const sum = total ?? rows.reduce((acc, r) => acc + r.n, 0);225 return (226 <ul role="list" className="adm-tally" aria-label={label}>227 {rows.map((r) => (228 <li key={r.label}>229 <span className="adm-tally-label">{nb(r.label)}</span>230 <span className="adm-tally-track" aria-hidden="true"><span style={{ width: `${(100 * r.n) / max}%` }} /></span>231 <span className="adm-tally-value tabular">{formatInt(r.n)}<span className="muted"> · {sum ? Math.round((100 * r.n) / sum) : 0} %</span></span>232 </li>233 ))}234 </ul>235 );236}237238/** Histogramme en colonnes : valeurs écrites au-dessus de chaque colonne. */239export function Histogram({ data, label, unit }: { data: Tally[]; label: string; unit: string }) {240 const max = Math.max(1, ...data.map((d) => d.n));241 const total = data.reduce((acc, d) => acc + d.n, 0);242 return (243 <figure className="adm-histo">244 <div className="adm-histo-plot" role="img" aria-label={`${label} : ${total === 0 ? "aucune donnée" : data.map((d) => `${d.label} : ${d.n}`).join(", ")}`}>245 {data.map((d) => (246 <div className="adm-histo-col" key={d.label} aria-hidden="true">247 <span className="adm-histo-stack">248 <span className="adm-histo-n tabular">{d.n > 0 ? d.n : ""}</span>249 <span className="adm-histo-bar" style={{ height: `calc(${d.n / max} * (100% - 1.6em))` }} data-empty={d.n === 0 || undefined} />250 </span>251 <span className="adm-histo-x tabular"><span className="adm-histo-long">{d.label}</span><span className="adm-histo-short">{d.label.split("–")[0]}</span></span>252 </div>253 ))}254 </div>255 <figcaption className="small muted">{unit}</figcaption>256 </figure>257 );258}259260/* ---------- Dialogues natifs ---------- */261262export function Modal({ title, onClose, children, size = "md", footer, locked = false }: { title: string; onClose: () => void; children: ReactNode; size?: "md" | "lg" | "xl"; footer?: ReactNode; locked?: boolean }) {263 const ref = useRef<HTMLDialogElement>(null);264 const titleId = useId();265 useEffect(() => {266 const dialog = ref.current;267 if (!dialog) return;268 if (!dialog.open) dialog.showModal();269 return () => {270 if (dialog.open) dialog.close();271 };272 }, []);273 return (274 <dialog275 ref={ref}276 className={`adm-dialog adm-dialog-${size}`}277 aria-labelledby={titleId}278 onCancel={(event) => {279 if (locked) event.preventDefault();280 }}281 onClose={() => {282 if (!ref.current?.open) onClose();283 }}284 onClick={(event) => {285 if (event.target === ref.current && !locked) ref.current?.close();286 }}287 >288 <div className="adm-dialog-box">289 <header className="adm-dialog-head">290 <h2 id={titleId} className="title">{title}</h2>291 <button type="button" className="icon-btn" onClick={() => ref.current?.close()} disabled={locked} aria-label="Fermer"><IconCross /></button>292 </header>293 <div className="adm-dialog-body">{children}</div>294 {footer && <footer className="adm-dialog-foot">{footer}</footer>}295 </div>296 </dialog>297 );298}299300/** Demande de confirmation d'une action, avec justification et case à cocher facultatives. */301export interface Ask {302 title: string;303 body: ReactNode;304 confirmLabel: string;305 danger?: boolean;306 /** Exige une justification saisie (min. 5 caractères, validée aussi par l'API). */307 reason?: boolean;308 /** Libellé d'un champ de note facultatif. */309 noteLabel?: string;310 /** Case à cocher obligatoire avant de confirmer. */311 check?: string;312 /** Exécute l'action ; renvoie le message de succès. */313 run: (text: string) => Promise<string>;314}315316export function ActionDialog({ ask, onClose, onDone }: { ask: Ask; onClose: () => void; onDone?: () => void }) {317 const notify = useNotify();318 const [text, setText] = useState("");319 const [checked, setChecked] = useState(false);320 const [busy, setBusy] = useState(false);321 const [error, setError] = useState<string | null>(null);322 const fieldId = useId();323 const reasonOk = !ask.reason || text.trim().length >= 5;324 const ready = reasonOk && (!ask.check || checked);325326 const submit = async (): Promise<void> => {327 if (!ready || busy) return;328 setBusy(true);329 setError(null);330 try {331 const message = await ask.run(text.trim());332 notify(message);333 onDone?.();334 onClose();335 } catch (e) {336 setError(errorMessage(e));337 setBusy(false);338 }339 };340341 return (342 <Modal343 title={ask.title}344 onClose={onClose}345 locked={busy}346 footer={347 <>348 <button type="button" className="btn btn-ghost" onClick={onClose} disabled={busy}>Annuler</button>349 <button type="submit" form={`${fieldId}-form`} className={`btn ${ask.danger ? "btn-danger" : "btn-dark"}`} disabled={!ready || busy}>350 {busy ? "En cours…" : ask.confirmLabel}351 </button>352 </>353 }354 >355 <form356 id={`${fieldId}-form`}357 className="stack"358 onSubmit={(event) => {359 event.preventDefault();360 void submit();361 }}362 >363 <div className="adm-ask-body">{ask.body}</div>364 {(ask.reason || ask.noteLabel) && (365 <div className="field">366 <label htmlFor={fieldId}>{ask.reason ? "Justification (obligatoire, 5 caractères au minimum)" : ask.noteLabel}</label>367 <textarea id={fieldId} className="input adm-textarea" rows={3} maxLength={500} value={text} onChange={(e) => setText(e.target.value)} required={ask.reason} minLength={ask.reason ? 5 : undefined} aria-describedby={ask.reason ? `${fieldId}-aide` : undefined} />368 {ask.reason && <p id={`${fieldId}-aide`} className="small muted">La justification est consignée au journal avec l'action.</p>}369 </div>370 )}371 {ask.check && (372 <label className="adm-check">373 <input type="checkbox" checked={checked} onChange={(e) => setChecked(e.target.checked)} />374 <span>{ask.check}</span>375 </label>376 )}377 {error && <p className="error-text" role="alert"><strong>Action refusée.</strong> {error}</p>}378 </form>379 </Modal>380 );381}382383/* ---------- Exports ---------- */384385const FORMATS = [386 { key: "csv", label: "CSV" },387 { key: "xlsx", label: "Excel" },388 { key: "json", label: "JSON" },389 { key: "pdf", label: "PDF" },390] as const;391392export function ExportLinks({ competitionId }: { competitionId: string }) {393 const scopes = [394 { key: "results", label: "Résultats", note: "Classement, scores, erreurs et biais de chaque partie terminée." },395 { key: "questions", label: "Questions", note: "Analyse de chaque question : réussite, répartition, discrimination." },396 ] as const;397 return (398 <div className="adm-exports">399 {scopes.map((scope) => (400 <div key={scope.key} className="adm-export-row">401 <div>402 <p className="adm-export-title">{scope.label}</p>403 <p className="small muted">{scope.note}</p>404 </div>405 <ul role="list" className="adm-export-links">406 {FORMATS.map((f) => (407 <li key={f.key}>408 <a className="btn btn-ghost" href={exportUrl(competitionId, scope.key, f.key)} download aria-label={`Télécharger les ${scope.label.toLowerCase()} au format ${f.label}`}>409 <IconDownload />{f.label}410 </a>411 </li>412 ))}413 </ul>414 </div>415 ))}416 <p className="small muted">Chaque téléchargement est consigné au journal.</p>417 </div>418 );419}420