SPB Git

Repository Public

templates.tsx 10.9 KB 173 lines tsx

1"use client";2import Link from "next/link";3import { useRouter } from "next/navigation";4import { useState } from "react";5import type { Locale, Sheet } from "@/schema";6import { useLocale } from "@/i18n/client";7import { dict, fill, formatDateTime } from "@/i18n/dict";8import { api } from "@/lib/client-api";9import { Dialog, Notice, PageHeader, Spinner, useApi } from "@/components/admin/ui";10import type { listCustomTemplates } from "@/server/misc";11import { apiMessage, Confirm, Loading, Segments, SheetPreview } from "./common";1213type Custom = Awaited<ReturnType<typeof listCustomTemplates>>[number];14interface Builtin { id: string; title: Record<Locale, string>; description: Record<Locale, string>; category: string }15interface TemplateList { builtin: Builtin[]; custom: Custom[] }16/** What the dialogs need: the key the API takes, a title, and the language when it is fixed (the author's own templates). */17interface Pick { key: string; title: string; fixedLocale: Locale | null }1819const T = dict({20  title: ["Modèles", "Templates"], lead: ["Partez d’une fiche complète et remplacez son contenu. Les modèles fournis existent en français et en anglais.", "Start from a complete sheet and replace its content. Built-in templates exist in French and English."],21  loading: ["Chargement…", "Loading…"], retry: ["Réessayer", "Retry"],22  builtin: ["Modèles fournis", "Built-in templates"], custom: ["Mes modèles", "My templates"],23  customEmpty: ["Aucun modèle personnel. Dans l’éditeur d’une fiche, « Enregistrer comme modèle » en crée un.", "No template of your own. In a sheet’s editor, “Save as template” creates one."],24  ai: ["Intelligence artificielle", "Artificial intelligence"], finance: ["Finance", "Finance"], infrastructure: ["Infrastructure", "Infrastructure"], method: ["Méthode", "Method"], other: ["Autres", "Other"],25  preview: ["Aperçu", "Preview"], use: ["Utiliser ce modèle", "Use this template"], del: ["Supprimer", "Delete"], cancel: ["Annuler", "Cancel"],26  previewTitle: ["Aperçu : {t}", "Preview: {t}"], lang: ["Langue", "Language"], fr: ["Français", "French"], en: ["Anglais", "English"],27  fixedLang: ["Ce modèle est en {l} : la fiche créée sera dans cette langue.", "This template is in {l}: the sheet will be created in that language."],28  useTitle: ["Créer une fiche à partir du modèle", "Create a sheet from the template"], useLead: ["Une nouvelle fiche en brouillon est créée à partir de « {t} », puis ouverte dans l’éditeur.", "A new draft sheet is created from “{t}”, then opened in the editor."],29  sheetLang: ["Langue de la fiche", "Language of the sheet"], create: ["Créer la fiche", "Create the sheet"],30  delTitle: ["Supprimer ce modèle ?", "Delete this template?"], delBody: ["Le modèle « {t} » sera supprimé. Les fiches déjà créées à partir de lui ne changent pas.", "The template “{t}” will be deleted. Sheets already created from it do not change."],31  deleted: ["Modèle supprimé.", "Template deleted."], created: ["Créé le {d}", "Created {d}"], blank: ["Fiche vierge", "Blank sheet"],32});3334function PreviewBody({ pick }: { pick: Pick }) {35  const ui = useLocale(), t = T(ui);36  const [lang, setLang] = useState<Locale>(pick.fixedLocale ?? ui);37  const { data, error, loading, reload } = useApi<{ doc: Sheet }>(`/api/admin/templates/${encodeURIComponent(pick.key)}/preview?locale=${lang}`);38  return (39    <>40      {pick.fixedLocale41        ? <p className="text-sm text-muted">{fill(t.fixedLang, { l: (pick.fixedLocale === "fr" ? t.fr : t.en).toLowerCase() })}</p>42        : <Segments label={t.lang} options={[["fr", t.fr], ["en", t.en]] as const} value={lang} onChange={setLang} />}43      <div className="mt-3" aria-live="polite" aria-busy={loading}>44        {loading && !data && <Loading label={t.loading} />}45        {error && <Notice tone="bad">{error} <button type="button" className="ml-2 min-h-11 font-semibold underline" onClick={() => { void reload(); }}>{t.retry}</button></Notice>}46        {data && !error && <div className={loading ? "opacity-60" : undefined}><SheetPreview doc={data.doc} locale={data.doc.metadata.locale} /></div>}47      </div>48    </>49  );50}5152function UseBody({ pick, onCancel }: { pick: Pick; onCancel: () => void }) {53  const ui = useLocale(), fr = ui === "fr", t = T(ui), router = useRouter();54  const [lang, setLang] = useState<Locale>(pick.fixedLocale ?? ui);55  const [busy, setBusy] = useState(false), [error, setError] = useState<string | null>(null);56  const create = async () => {57    setBusy(true); setError(null);58    try { const r = await api<{ id: string }>("/api/admin/sheets", { body: { template: pick.key, locale: lang } }); router.push(`/admin/sheets/${r.id}/edit`); }59    catch (e) { setError(apiMessage(e, fr)); setBusy(false); }60  };61  return (62    <>63      <p className="text-[0.9375rem] leading-relaxed text-muted">{fill(t.useLead, { t: pick.title })}</p>64      {pick.fixedLocale65        ? <p className="mt-3 text-sm text-muted">{fill(t.fixedLang, { l: (pick.fixedLocale === "fr" ? t.fr : t.en).toLowerCase() })}</p>66        : (67          <fieldset className="mt-4">68            <legend className="text-sm font-medium">{t.sheetLang}</legend>69            <div className="mt-1 grid gap-2 xs:grid-cols-2">70              {(["fr", "en"] as const).map((l) => (71                <label key={l} className={`flex min-h-11 cursor-pointer items-center gap-3 rounded-xl border px-4 font-medium ${lang === l ? "border-accent bg-accent-soft" : "border-line"}`}>72                  <input type="radio" name="tpl-lang" value={l} checked={lang === l} onChange={() => setLang(l)} className="h-4 w-4 accent-[var(--ui-accent)]" />{l === "fr" ? t.fr : t.en}73                </label>74              ))}75            </div>76          </fieldset>77        )}78      <div aria-live="assertive" className="mt-4">{error && <Notice tone="bad">{error}</Notice>}</div>79      <div className="mt-5 flex flex-wrap justify-end gap-2">80        <button type="button" className="btn" onClick={onCancel} disabled={busy}>{t.cancel}</button>81        <button type="button" className="btn btn-primary" onClick={() => { void create(); }} disabled={busy}>{busy && <Spinner />}{t.create}</button>82      </div>83    </>84  );85}8687export function TemplatesPage() {88  const locale = useLocale(), fr = locale === "fr", t = T(locale);89  const { data, error, loading, reload } = useApi<TemplateList>("/api/admin/templates");90  const [previewing, setPreviewing] = useState<Pick | null>(null), [using, setUsing] = useState<Pick | null>(null), [deleting, setDeleting] = useState<Custom | null>(null);91  const [delBusy, setDelBusy] = useState(false), [delError, setDelError] = useState<string | null>(null), [flash, setFlash] = useState<string | null>(null);9293  const categoryLabel = (c: string) => (c === "ai" ? t.ai : c === "finance" ? t.finance : c === "infrastructure" ? t.infrastructure : c === "method" ? t.method : c || t.other);94  const groups = new Map<string, Builtin[]>();95  for (const b of data?.builtin ?? []) groups.set(b.category, [...(groups.get(b.category) ?? []), b]);9697  const remove = async () => {98    if (!deleting) return;99    setDelBusy(true); setDelError(null);100    try { await api(`/api/admin/templates/${deleting.id}`, { method: "DELETE" }); setDeleting(null); setFlash(t.deleted); void reload(); }101    catch (e) { setDelError(apiMessage(e, fr)); }102    setDelBusy(false);103  };104105  const card = (pick: Pick, description: string, extra: React.ReactNode, actions: React.ReactNode) => (106    <li key={pick.key} className="card flex min-w-0 flex-col gap-2 p-4">107      <h3 className="break-words font-display text-lg font-semibold leading-snug">{pick.title}</h3>108      {description && <p className="text-[0.9375rem] leading-relaxed text-muted">{description}</p>}109      {extra}110      <div className="mt-auto flex flex-wrap gap-2 pt-2">111        <button type="button" className="btn" onClick={() => setPreviewing(pick)}>{t.preview}</button>112        <button type="button" className="btn btn-primary" onClick={() => setUsing(pick)}>{t.use}</button>113        {actions}114      </div>115    </li>116  );117118  return (119    <>120      <PageHeader title={t.title} lead={t.lead} actions={<Link href="/admin/sheets/new" className="btn">{t.blank}</Link>} />121      <div aria-live="polite">122        {flash && <div className="mb-4"><Notice tone="ok">{flash}</Notice></div>}123        {loading && !data && <Loading label={t.loading} />}124        {error && <Notice tone="bad">{error} <button type="button" className="ml-2 min-h-11 font-semibold underline" onClick={() => { void reload(); }}>{t.retry}</button></Notice>}125      </div>126127      {data && (128        <>129          <section aria-labelledby="tpl-custom">130            <h2 id="tpl-custom" className="font-display text-2xl font-semibold">{t.custom}</h2>131            {data.custom.length === 0 ? <p className="mt-2 text-muted">{t.customEmpty}</p> : (132              <ul className="mt-3 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">133                {data.custom.map((c) => card({ key: c.key, title: c.title, fixedLocale: c.locale }, c.description,134                  <p className="text-sm text-faint"><span className="font-mono uppercase">{c.locale}</span> · {fill(t.created, { d: formatDateTime(c.createdAt, locale) })}</p>,135                  <button type="button" className="btn btn-danger" onClick={() => { setDelError(null); setDeleting(c); }}>{t.del}</button>))}136              </ul>137            )}138          </section>139140          <section aria-labelledby="tpl-builtin" className="mt-10">141            <h2 id="tpl-builtin" className="font-display text-2xl font-semibold">{t.builtin}</h2>142            {[...groups.entries()].map(([category, items]) => (143              <div key={category} className="mt-5">144                <p className="eyebrow" id={`tpl-cat-${category}`}>{categoryLabel(category)}</p>145                <ul className="mt-2 grid gap-3 sm:grid-cols-2 lg:grid-cols-3" aria-labelledby={`tpl-cat-${category}`}>146                  {items.map((b) => card({ key: b.id, title: b.title[locale], fixedLocale: null }, b.description[locale], null, null))}147                </ul>148              </div>149            ))}150          </section>151        </>152      )}153154      <Dialog open={!!previewing} onClose={() => setPreviewing(null)} title={fill(t.previewTitle, { t: previewing?.title ?? "" })} wide>155        {previewing && (156          <>157            <PreviewBody key={previewing.key} pick={previewing} />158            <div className="mt-5 flex flex-wrap justify-end gap-2">159              <button type="button" className="btn btn-primary" onClick={() => { setUsing(previewing); setPreviewing(null); }}>{t.use}</button>160            </div>161          </>162        )}163      </Dialog>164      <Dialog open={!!using} onClose={() => setUsing(null)} title={t.useTitle}>165        {using && <UseBody key={using.key} pick={using} onCancel={() => setUsing(null)} />}166      </Dialog>167      <Confirm open={!!deleting} title={t.delTitle} confirmLabel={t.del} cancelLabel={t.cancel} busy={delBusy} error={delError} onConfirm={() => { void remove(); }} onClose={() => { if (!delBusy) setDeleting(null); }}>168        {fill(t.delBody, { t: deleting?.title ?? "" })}169      </Confirm>170    </>171  );172}173
Files main
Menu

Theme