SPB Git

Repository Public

common.tsx 8.6 KB 149 lines tsx

1"use client";2import { useEffect, useRef, useState, type ReactNode } from "react";3import { FORMAT_SIZES, type Locale, type Sheet } from "@/schema";4import { SheetView } from "@/renderer/SheetView";5import { ApiClientError } from "@/lib/client-api";6import { Dialog, errorText, Spinner } from "@/components/admin/ui";7import { passkeyMessage } from "@/components/admin/passkey";89/** The server answers in English; the cases an administrator meets every day also exist in French here. */10const FR_BY_CODE: Record<string, string> = {11  unsupported_type: "Type de fichier refusé. Formats acceptés : PNG, JPEG, WebP, GIF, SVG, PDF, CSV, JSON et texte brut.",12  file_too_large: "Fichier trop volumineux.",13  payload_too_large: "Fichier trop volumineux.",14  quota_exceeded: "Le quota de stockage est atteint.",15  infected: "Fichier rejeté par l’antivirus.",16  scanner_unavailable: "L’antivirus ne répond pas ; le fichier n’a pas été conservé.",17  empty_file: "Le fichier est vide.",18  image_too_large: "Image trop grande : 12 000 px par côté au maximum.",19  asset_in_use: "Ce fichier est encore utilisé par une fiche ; il ne peut pas être supprimé.",20  last_passkey: "La dernière clé d’accès ne peut pas être retirée.",21  topic_in_use: "Des fiches utilisent encore ce thème.",22  version_conflict: "La fiche a été modifiée ailleurs entre-temps. Réessayez.",23  unknown_model: "Ce modèle n’est pas disponible pour la clé API configurée.",24  rate_limited: "Trop de requêtes. Patientez avant de réessayer.",25  not_tabular: "Ce fichier n’est pas un tableau.",26  not_found: "Élément introuvable (supprimé entre-temps ?).",27  invalid_input: "Saisie invalide.",28  internal: "Erreur interne du serveur.",29};3031/** `errorText`, with a French sentence for the known error codes and the field-level details of a validation error. */32export function apiMessage(e: unknown, fr: boolean): string {33  if (!(e instanceof ApiClientError)) return errorText(e, fr);34  const base = fr && FR_BY_CODE[e.code] ? (e.code === "file_too_large" || e.code === "asset_in_use" ? `${FR_BY_CODE[e.code]} (${e.message})` : FR_BY_CODE[e.code]) : errorText(e, fr);35  const details = validationDetails(e);36  return details.length ? `${base} ${details.map((d) => `${d.path || "?"} : ${d.message}`).join(" ; ")}` : base;37}3839export function validationDetails(e: unknown): { path: string; message: string }[] {40  if (!(e instanceof ApiClientError) || !Array.isArray(e.details)) return [];41  return (e.details as unknown[]).flatMap((d) => {42    if (!d || typeof d !== "object") return [];43    const x = d as { path?: unknown; message?: unknown };44    return typeof x.message === "string" ? [{ path: typeof x.path === "string" ? x.path : "", message: x.message }] : [];45  });46}4748/** For actions that may go through a passkey ceremony: WebAuthn failures and API errors, both in words. */49export const authMessage = (e: unknown, fr: boolean) => (e instanceof ApiClientError && e.code !== "network" ? apiMessage(e, fr) : passkeyMessage(e, fr));5051export function useDebounced<T>(value: T, ms = 300): T {52  const [v, setV] = useState(value);53  useEffect(() => { const id = setTimeout(() => setV(value), ms); return () => clearTimeout(id); }, [value, ms]);54  return v;55}5657export function formatBytes(n: number, fr: boolean): string {58  const units = fr ? ["o", "ko", "Mo", "Go", "To"] : ["B", "kB", "MB", "GB", "TB"];59  let i = 0, x = n;60  while (x >= 1024 && i < units.length - 1) { x /= 1024; i++; }61  return `${new Intl.NumberFormat(fr ? "fr-CA" : "en-CA", { maximumFractionDigits: x < 10 && i > 0 ? 1 : 0 }).format(x)} ${units[i]}`;62}6364export const formatNumber = (n: number, fr: boolean) => new Intl.NumberFormat(fr ? "fr-CA" : "en-CA").format(n);6566/** Filter chips. The row scrolls inside itself on narrow screens, the page never does. */67export function Segments<V extends string>({ label, options, value, onChange }: { label: string; options: readonly (readonly [V, string])[]; value: V; onChange: (v: V) => void }) {68  return (69    <div role="group" aria-label={label} className="-mx-1 flex gap-2 overflow-x-auto px-1 py-1">70      {options.map(([v, text]) => (71        <button key={v} type="button" aria-pressed={v === value} onClick={() => onChange(v)}72          className={`min-h-11 shrink-0 rounded-full border px-4 text-sm font-semibold ${v === value ? "border-accent bg-accent-soft text-ink" : "border-line bg-surface text-muted"}`}>73          {text}74        </button>75      ))}76    </div>77  );78}7980export function Pager({ total, limit, offset, onChange, fr }: { total: number; limit: number; offset: number; onChange: (offset: number) => void; fr: boolean }) {81  if (total <= limit && offset === 0) return null;82  const from = total === 0 ? 0 : offset + 1, to = Math.min(total, offset + limit);83  return (84    <nav aria-label={fr ? "Pagination" : "Pagination"} className="mt-4 flex flex-wrap items-center justify-between gap-3">85      <p className="text-sm text-muted" aria-live="polite">{fr ? `${from}–${to} sur ${total}` : `${from}–${to} of ${total}`}</p>86      <div className="flex gap-2">87        <button type="button" className="btn" disabled={offset === 0} onClick={() => onChange(Math.max(0, offset - limit))}>{fr ? "Précédent" : "Previous"}</button>88        <button type="button" className="btn" disabled={offset + limit >= total} onClick={() => onChange(offset + limit)}>{fr ? "Suivant" : "Next"}</button>89      </div>90    </nav>91  );92}9394/** Confirmation of a destructive action. The error of the attempt stays in the dialog. */95export function Confirm({ open, title, children, confirmLabel, cancelLabel, busy, error, danger = true, onConfirm, onClose }: {96  open: boolean; title: string; children: ReactNode; confirmLabel: string; cancelLabel: string; busy: boolean; error: string | null; danger?: boolean; onConfirm: () => void; onClose: () => void;97}) {98  return (99    <Dialog open={open} onClose={onClose} title={title}>100      <div className="text-[0.9375rem] leading-relaxed text-muted">{children}</div>101      <div aria-live="assertive">{error && <p role="alert" className="mt-4 rounded-xl border border-bad/40 bg-bad/10 px-4 py-3 text-sm">{error}</p>}</div>102      <div className="mt-5 flex flex-wrap justify-end gap-2">103        <button type="button" className="btn" onClick={onClose} disabled={busy}>{cancelLabel}</button>104        <button type="button" className={`btn ${danger ? "btn-danger" : "btn-primary"}`} onClick={onConfirm} disabled={busy}>{busy && <Spinner />}{confirmLabel}</button>105      </div>106    </Dialog>107  );108}109110export function CopyButton({ text, label, copiedLabel, className = "btn" }: { text: string; label: string; copiedLabel: string; className?: string }) {111  const [state, setState] = useState<"idle" | "copied" | "failed">("idle");112  const copy = async () => {113    try { await navigator.clipboard.writeText(text); setState("copied"); } catch { setState("failed"); }114    setTimeout(() => setState("idle"), 2000);115  };116  return <button type="button" className={className} onClick={copy} aria-live="polite">{state === "copied" ? copiedLabel : state === "failed" ? "✕ " + label : label}</button>;117}118119export function Loading({ label }: { label: string }) {120  return <p className="flex items-center gap-2 py-6 text-muted" role="status"><Spinner />{label}</p>;121}122123const adminAssetUrl = (assetId: string) => `/api/admin/assets/${encodeURIComponent(assetId)}/file`;124125/**126 * A sheet inside a dialog. Fixed formats (A4, slide, square…) are drawn at their real size and scaled down to the127 * width available; an article is responsive and is drawn as is.128 */129export function SheetPreview({ doc, locale }: { doc: Sheet; locale?: Locale }) {130  const outer = useRef<HTMLDivElement>(null), inner = useRef<HTMLDivElement>(null);131  const [box, setBox] = useState<{ scale: number; height: number } | null>(null);132  const format = doc.layout.format, fixed = format !== "article", width = FORMAT_SIZES[format].width;133  useEffect(() => {134    const o = outer.current, i = inner.current;135    if (!fixed || !o || !i) return;136    const measure = () => { const scale = Math.min(1, o.clientWidth / width); setBox({ scale, height: Math.ceil(i.offsetHeight * scale) }); };137    const ro = new ResizeObserver(measure);138    ro.observe(o); ro.observe(i); measure();139    return () => ro.disconnect();140  }, [fixed, width, doc]);141  const view = <SheetView doc={doc} locale={locale} mode="public" assetUrl={adminAssetUrl} />;142  if (!fixed) return <div className="overflow-hidden rounded-xl border border-line">{view}</div>;143  return (144    <div ref={outer} className="overflow-hidden rounded-xl border border-line" style={{ height: box?.height }}>145      <div ref={inner} style={{ width, transform: `scale(${box?.scale ?? 1})`, transformOrigin: "top left", visibility: box ? "visible" : "hidden" }}>{view}</div>146    </div>147  );148}149
Files main
Menu

Theme