SPB Git

Repository Public

Editor.tsx 48.7 KB 525 lines tsx

1"use client";2import Link from "next/link";3import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";4import { useLocale } from "@/i18n/client";5import { dict, fill } from "@/i18n/dict";6import { api, ApiClientError, idempotencyKey } from "@/lib/client-api";7import { allBlocks, FORMAT_SIZES, newId, parseSheet, type Block, type BlockOf, type LeafBlock, type Sheet, type SheetDiff } from "@/schema";8import type { QualityReport } from "@/server/quality";9import type { SaveResult, SheetDetail } from "@/server/sheets";10import type { AssetView } from "@/server/assets";11import type { JobView } from "@/server/jobs";12import { SheetView } from "@/renderer/SheetView";13import { Dialog, errorText, Notice, Spinner, StatusPill } from "@/components/admin/ui";14import { JobProgress, useJob } from "@/components/admin/job";15import { BlockForm } from "./forms/BlockForm";16import { BLOCK_CATALOG, duplicateBlock, newBlock } from "./forms/defaults";17import { DiagramEditor } from "./diagram/DiagramEditor";18import { ClaudePanel, LibraryPanel, MetaPanel, OutlinePanel, QualityPanel, SourcesPanel } from "./panels";19import { insertAfter, moveBlock, removeBlocks, replaceBlock, useDocState } from "./state";2021const T = dict({22  back: ["Retour au tableau de bord", "Back to the dashboard"], saved: ["Enregistré", "Saved"], saving: ["Enregistrement…", "Saving…"], unsaved: ["Modifications non enregistrées", "Unsaved changes"], invalid: ["Document invalide — non enregistré", "Invalid document — not saved"],23  conflict: ["La fiche a été modifiée ailleurs (autre onglet ou tâche Claude). Rechargez pour continuer.", "The sheet was changed elsewhere (another tab or a Claude job). Reload to continue."], reload: ["Recharger", "Reload"],24  undo: ["Annuler", "Undo"], redo: ["Rétablir", "Redo"], save: ["Enregistrer", "Save"], preview: ["Aperçu", "Preview"], publish: ["Publier", "Publish"], republish: ["Publier les modifications", "Publish changes"], more: ["Plus", "More"],25  desktop: ["Ordinateur", "Desktop"], tablet: ["Tablette", "Tablet"], phone: ["iPhone", "iPhone"], width: ["Largeur de l’aperçu", "Preview width"],26  blocks: ["Blocs", "Blocks"], outline: ["Plan", "Outline"], props: ["Propriétés", "Properties"], claude: ["Claude", "Claude"], quality: ["Qualité", "Quality"], sources: ["Sources", "Sources"], sheet: ["Fiche", "Sheet"],27  none: ["Sélectionnez un bloc dans la fiche pour le modifier, ou ajoutez-en un.", "Select a block in the sheet to edit it, or add one."], multi: ["{n} blocs sélectionnés", "{n} blocks selected"],28  up: ["Monter", "Move up"], down: ["Descendre", "Move down"], dup: ["Dupliquer", "Duplicate"], del: ["Supprimer", "Delete"], lock: ["Verrouiller", "Lock"], unlock: ["Déverrouiller", "Unlock"], edit: ["Modifier le texte", "Edit text"], ask: ["Demander à Claude", "Ask Claude"], visual: ["Éditeur visuel", "Visual editor"],29  select: ["Sélectionner le bloc {type}", "Select the {type} block"], editing: ["Entrée pour valider, Échap pour annuler", "Enter to confirm, Escape to cancel"],30  pubTitle: ["Publier la fiche", "Publish the sheet"], pubLead: ["La version actuelle deviendra publique à l’adresse ci-dessous. La version publiée ne change plus jusqu’à votre prochaine publication.", "The current version will become public at the address below. The published version does not change until you publish again."],31  pubBlocked: ["La publication est bloquée par {n} erreur(s) du rapport qualité.", "Publication is blocked by {n} error(s) in the quality report."], pubWarn: ["{n} avertissement(s) restent ouverts.", "{n} warning(s) remain open."],32  pubCheck: ["J’ai relu cette fiche (contenu, formules, sources) et j’en autorise la publication.", "I have reviewed this sheet (content, formulas, sources) and authorise its publication."], pubGo: ["Publier maintenant", "Publish now"], pubDone: ["Fiche publiée.", "Sheet published."], view: ["Voir la page publique", "View the public page"],33  unpublish: ["Dépublier", "Unpublish"], unpubLead: ["La fiche ne sera plus accessible au public ni indexée ; elle redevient un brouillon.", "The sheet will no longer be public or indexed; it goes back to draft."], unpubDone: ["Fiche dépubliée.", "Sheet unpublished."],34  previewLink: ["Lien d’aperçu privé", "Private preview link"], previewLead: ["Lien temporaire (24 h), non indexable, qui montre le brouillon actuel à qui le détient.", "Temporary link (24 h), not indexable, showing the current draft to whoever holds it."], create: ["Créer le lien", "Create the link"], revoke: ["Révoquer les liens", "Revoke links"], copy: ["Copier", "Copy"], copied: ["Copié", "Copied"],35  export: ["Exporter", "Export"], exportLead: ["PDF et PNG capturent la fiche telle qu’affichée (les blocs interactifs dans leur état initial). SVG exporte un bloc vectoriel.", "PDF and PNG capture the sheet as displayed (interactive blocks in their initial state). SVG exports one vector block."],36  pdf: ["PDF vectoriel", "Vector PDF"], png: ["PNG", "PNG"], svg: ["SVG du bloc sélectionné", "SVG of the selected block"], json: ["JSON Sheet", "Sheet JSON"], scale: ["Échelle", "Scale"], download: ["Télécharger", "Download"], svgNeeds: ["Sélectionnez un diagramme, un graphique, une matrice, une chronologie ou une illustration.", "Select a diagram, chart, matrix, timeline or illustration."],37  translate: ["Traduire", "Translate"], translateLead: ["Crée une nouvelle fiche liée, dans l’autre langue. Celle-ci n’est pas modifiée.", "Creates a new linked sheet in the other language. This one is not modified."], toEn: ["Traduire en anglais", "Translate to English"], toFr: ["Traduire en français", "Translate to French"], openTr: ["Ouvrir la traduction", "Open the translation"],38  template: ["Enregistrer comme modèle", "Save as template"], tplName: ["Nom du modèle", "Template name"], tplDone: ["Modèle enregistré.", "Template saved."],39  delete: ["Supprimer la fiche", "Delete the sheet"], deleteLead: ["La fiche disparaît du studio. Ses révisions sont conservées pour l’audit.", "The sheet disappears from the studio. Its revisions are kept for the audit trail."], confirmDelete: ["Supprimer définitivement", "Delete for good"],40  history: ["Historique des révisions", "Revision history"], unpublished: ["Modifications non publiées", "Unpublished changes"], close: ["Fermer", "Close"], image: ["Choisir une image", "Choose an image"], dataset: ["Choisir un jeu de données", "Choose a dataset"], upload: ["Téléverser", "Upload"], noAsset: ["Aucun fichier de ce type. Téléversez-en un.", "No file of this kind. Upload one."],41  shortcuts: ["⌘Z annuler · ⇧⌘Z rétablir · ⌘S enregistrer · ⌘D dupliquer · Suppr supprimer · ⌥↑/↓ déplacer · Échap désélectionner", "⌘Z undo · ⇧⌘Z redo · ⌘S save · ⌘D duplicate · Del delete · ⌥↑/↓ move · Esc deselect"],42});4344type Panel = "blocks" | "outline" | "props" | "claude" | "quality" | "sources" | "sheet";45type Device = "desktop" | "tablet" | "phone";46const DEVICE_WIDTH: Record<Device, number | null> = { desktop: null, tablet: 820, phone: 390 };47const INLINE_TEXT = new Set(["heading", "paragraph"]);48const VECTOR = new Set(["diagram", "chart", "matrix", "timeline", "svg"]);4950export function Editor({ initial, aiConfigured }: { initial: SheetDetail; aiConfigured: boolean }) {51  const locale = useLocale(), fr = locale === "fr", t = T(locale);52  const [detail, setDetail] = useState(initial);53  const state = useDocState(initial.doc);54  const { doc } = state;55  const [version, setVersion] = useState(initial.version);56  const [savedDoc, setSavedDoc] = useState(initial.doc);57  const [saveState, setSaveState] = useState<"saved" | "dirty" | "saving" | "invalid" | "conflict" | "error">("saved");58  const [saveError, setSaveError] = useState<string | null>(null);59  const [quality, setQuality] = useState<QualityReport | null>(initial.quality);60  const [selected, setSelected] = useState<string[]>([]);61  const [highlight, setHighlight] = useState<string[]>([]);62  const [panel, setPanel] = useState<Panel>("props");63  const [leftTab, setLeftTab] = useState<"blocks" | "outline">("blocks");64  const [drawer, setDrawer] = useState<Panel | null>(null);65  const [device, setDevice] = useState<Device>("desktop");66  const [inline, setInline] = useState<string | null>(null);67  const [diagramId, setDiagramId] = useState<string | null>(null);68  const [dialog, setDialog] = useState<null | "publish" | "unpublish" | "preview" | "export" | "translate" | "template" | "delete" | "more">(null);69  const [assetPick, setAssetPick] = useState<{ kind: "image" | "dataset"; resolve: (id: string | null) => void } | null>(null);70  const [overflowPx, setOverflowPx] = useState(0);71  const canvas = useRef<HTMLDivElement>(null);72  const docRef = useRef(doc); docRef.current = doc;73  const versionRef = useRef(version); versionRef.current = version;74  const saving = useRef<Promise<number> | null>(null);7576  const dirty = doc !== savedDoc;77  const block = selected.length === 1 ? allBlocks(doc).find((b) => b.id === selected[0]) ?? null : null;78  const typeLabel = useCallback((type: string) => BLOCK_CATALOG.find((c) => c.type === type)?.label[locale] ?? type, [locale]);7980  // ── Saving ────────────────────────────────────────────────────────────────────────────────────────81  /** Saves the working copy if it changed; resolves with the version on the server. One save at a time. */82  const save = useCallback(async (): Promise<number> => {83    if (saving.current) await saving.current.catch(() => {});84    const current = docRef.current;85    if (current === savedDocRef.current) return versionRef.current;86    const parsed = parseSheet(current);87    if (!parsed.ok) { setSaveState("invalid"); setSaveError(parsed.issues.slice(0, 3).map((i) => `${i.path}: ${i.message}`).join(" · ")); throw new Error("invalid"); }88    setSaveState("saving"); setSaveError(null);89    const p = (async () => {90      try {91        const r = await api<SaveResult>(`/api/admin/sheets/${initial.id}`, { method: "PATCH", body: { doc: current, expectedVersion: versionRef.current } });92        versionRef.current = r.version; setVersion(r.version); setSavedDoc(current); savedDocRef.current = current; setQuality(r.quality);93        setSaveState(docRef.current === current ? "saved" : "dirty");94        return r.version;95      } catch (e) {96        if (e instanceof ApiClientError && e.code === "version_conflict") setSaveState("conflict"); else { setSaveState("error"); setSaveError(errorText(e, fr)); }97        throw e;98      } finally { saving.current = null; }99    })();100    saving.current = p;101    return p;102  }, [initial.id, fr]);103  const savedDocRef = useRef(savedDoc); savedDocRef.current = savedDoc;104105  // Autosave: 2.5 s after the last change. Drafts only — nothing here publishes.106  useEffect(() => {107    if (!dirty || saveState === "conflict") return;108    setSaveState((s) => (s === "saving" ? s : "dirty"));109    const id = setTimeout(() => { void save().catch(() => {}); }, 2500);110    return () => clearTimeout(id);111  }, [doc, dirty, save, saveState]);112  useEffect(() => {113    const warn = (e: BeforeUnloadEvent) => { if (docRef.current !== savedDocRef.current) e.preventDefault(); };114    window.addEventListener("beforeunload", warn);115    return () => window.removeEventListener("beforeunload", warn);116  }, []);117118  /** Reloads the sheet from the server after a job (AI edit, source check, revert) changed it. */119  const reloadFromServer = useCallback(async () => {120    const d = await api<SheetDetail>(`/api/admin/sheets/${initial.id}`);121    setDetail(d); versionRef.current = d.version; setVersion(d.version); setSavedDoc(d.doc); savedDocRef.current = d.doc; state.replace(d.doc); setQuality(d.quality); setSaveState("saved");122    return d;123  }, [initial.id, state]);124  const refreshDetail = useCallback(async () => { const d = await api<SheetDetail>(`/api/admin/sheets/${initial.id}`); setDetail(d); }, [initial.id]);125126  // ── Editing operations ────────────────────────────────────────────────────────────────────────────127  const commit = state.commit;128  const select = useCallback((id: string, additive = false) => { setInline(null); setSelected((cur) => (additive ? (cur.includes(id) ? cur.filter((x) => x !== id) : [...cur, id]) : [id])); setPanel((p) => (p === "claude" || p === "quality" ? p : "props")); }, []);129  const topId = (id: string) => doc.blocks.find((b) => b.id === id || (b.type === "tabs" && b.tabs.some((tb) => tb.blocks.some((c) => c.id === id))))?.id ?? id;130  const addBlock = async (type: Block["type"]) => {131    // An image block needs its picture first: a block pointing at nothing would make the document unsaveable.132    let assetRef: string | undefined;133    if (type === "image") { setDrawer(null); const ref = await pickAsset("image"); if (!ref) return; assetRef = ref; }134    const doc = docRef.current;135    const b = newBlock(type, doc.metadata.locale, assetRef ? { assetRef } : undefined);136    const after = selected.length ? topId(selected[selected.length - 1]) : null;137    commit(insertAfter(doc, after, b)); setSelected([b.id]); setPanel("props"); setDrawer(null);138    requestAnimationFrame(() => document.getElementById(b.id)?.scrollIntoView({ block: "center", behavior: "smooth" }));139  };140  const remove = (ids: string[]) => { commit(removeBlocks(doc, ids)); setSelected([]); };141  const duplicate = (ids: string[]) => {142    let next = doc; const made: string[] = [];143    for (const id of ids) { const src = next.blocks.find((b) => b.id === id); if (!src || next.blocks.length >= 80) continue; const copy = duplicateBlock(src) as Block; next = insertAfter(next, id, copy); made.push(copy.id); }144    commit(next); if (made.length) setSelected(made);145  };146  const move = (id: string, delta: number) => { const i = doc.blocks.findIndex((b) => b.id === id); if (i >= 0) commit(moveBlock(doc, id, i + delta)); };147  const patchBlock = (id: string, next: Block | LeafBlock, key?: string) => commit(replaceBlock(doc, id, next), key ?? `block:${id}`);148149  // Keyboard shortcuts (never while typing in a field).150  useEffect(() => {151    const onKey = (e: KeyboardEvent) => {152      const el = e.target as HTMLElement | null;153      const typing = !!el && (el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.tagName === "SELECT" || el.isContentEditable);154      const mod = e.metaKey || e.ctrlKey;155      if (mod && e.key.toLowerCase() === "s") { e.preventDefault(); void save().catch(() => {}); return; }156      if (typing || dialog || diagramId) return;157      if (mod && e.key.toLowerCase() === "z") { e.preventDefault(); if (e.shiftKey) state.redo(); else state.undo(); }158      else if (mod && e.key.toLowerCase() === "y") { e.preventDefault(); state.redo(); }159      else if (mod && e.key.toLowerCase() === "d" && selected.length) { e.preventDefault(); duplicate(selected); }160      else if ((e.key === "Delete" || e.key === "Backspace") && selected.length) { e.preventDefault(); remove(selected); }161      else if (e.altKey && (e.key === "ArrowUp" || e.key === "ArrowDown") && selected.length === 1) { e.preventDefault(); move(selected[0], e.key === "ArrowUp" ? -1 : 1); }162      else if (e.key === "Escape") { setSelected([]); setInline(null); }163    };164    window.addEventListener("keydown", onKey);165    return () => window.removeEventListener("keydown", onKey);166  });167168  // Live quality report for unsaved changes (debounced; the server computes it, the same code as at publication).169  useEffect(() => {170    if (!dirty) return;171    const ctl = new AbortController();172    const id = setTimeout(() => { void api<QualityReport>("/api/admin/quality", { body: { doc }, signal: ctl.signal }).then(setQuality).catch(() => {}); }, 900);173    return () => { clearTimeout(id); ctl.abort(); };174  }, [doc, dirty]);175176  // Fixed formats: measure whether the content exceeds the page, in the real rendering.177  useEffect(() => {178    const h = FORMAT_SIZES[doc.layout.format].height;179    if (!h) { setOverflowPx(0); return; }180    const id = setTimeout(() => { const frame = canvas.current?.querySelector<HTMLElement>(".sh-frame"); setOverflowPx(frame ? Math.max(0, Math.round(frame.scrollHeight - h)) : 0); }, 400);181    return () => clearTimeout(id);182  }, [doc]);183184  useEffect(() => { if (!highlight.length) return; document.getElementById(highlight[0])?.scrollIntoView({ block: "center", behavior: "smooth" }); const id = setTimeout(() => setHighlight([]), 4000); return () => clearTimeout(id); }, [highlight]);185186  // ── Assets ────────────────────────────────────────────────────────────────────────────────────────187  const pickAsset = useCallback((kind: "image" | "dataset") => new Promise<string | null>((resolve) => setAssetPick({ kind, resolve })), []);188  const attachAsset = (a: AssetView) => {189    if (!assetPick) return;190    const existing = docRef.current.assets.find((x) => x.assetId === a.id);191    const ref = existing?.id ?? newId("a");192    if (!existing) commit({ ...docRef.current, assets: [...docRef.current.assets, { id: ref, kind: assetPick.kind, assetId: a.id, alt: a.alt, credit: a.credit || undefined }] });193    assetPick.resolve(ref); setAssetPick(null);194  };195  const loadDataset = useCallback(async (assetRef: string) => {196    const ref = docRef.current.assets.find((a) => a.id === assetRef);197    if (!ref) return null;198    return api<{ columns: { name: string; type: "number" | "string" }[]; rows: (string | number)[][] }>(`/api/admin/assets/${ref.assetId}/dataset`).catch(() => null);199  }, []);200201  // ── Canvas ────────────────────────────────────────────────────────────────────────────────────────202  const wrapBlock = useCallback((b: Block, node: ReactNode) => {203    const isSel = selected.includes(b.id), hl = highlight.includes(b.id);204    const i = doc.blocks.findIndex((x) => x.id === b.id);205    return (206      <div className={`group/blk relative rounded-lg outline-offset-4 ${isSel ? "outline outline-2 outline-[var(--ui-accent)]" : hl ? "outline outline-2 outline-[var(--ui-signal)]" : "hover:outline hover:outline-1 hover:outline-[color-mix(in_srgb,var(--ui-accent)_45%,transparent)]"}`}207        onClickCapture={(e) => {208          // In the editor a click selects; links and block controls inside the sheet stay inert until selected twice.209          const a = (e.target as HTMLElement).closest("a"); if (a) e.preventDefault();210          if (!isSel || selected.length > 1) { select(b.id, e.shiftKey || e.metaKey || e.ctrlKey); if ((e.target as HTMLElement).closest("button, summary, input")) return; }211        }}212        onDoubleClick={() => { if (INLINE_TEXT.has(b.type) && !b.locked) setInline(b.id); else if (b.type === "diagram") setDiagramId(b.id); }}>213        {inline === b.id && (b.type === "heading" || b.type === "paragraph")214          ? <InlineText value={b.text} multiline={b.type === "paragraph"} hint={t.editing} onCancel={() => setInline(null)} onDone={(text) => { setInline(null); if (text.trim() && text !== b.text) patchBlock(b.id, { ...b, text: text.trim().slice(0, b.type === "heading" ? 200 : 4000) }); }} />215          : node}216        {!isSel && <button type="button" className="sr-only focus:not-sr-only focus:absolute focus:left-1 focus:top-1 focus:z-10 btn btn-sm" onClick={() => select(b.id)}>{fill(t.select, { type: typeLabel(b.type) })}</button>}217        {isSel && selected.length === 1 && (218          <div className="no-print absolute -top-12 left-0 z-20 flex max-w-full items-center gap-0.5 overflow-x-auto rounded-xl border border-line bg-surface p-1 text-ink shadow-card" role="toolbar" aria-label={typeLabel(b.type)} style={{ fontFamily: "var(--font-sans)" }}>219            <span className="px-2 text-xs font-semibold text-muted">{typeLabel(b.type)}</span>220            <Tool label={t.up} disabled={i <= 0 || !!b.locked} onClick={() => move(b.id, -1)}>▲</Tool>221            <Tool label={t.down} disabled={i === doc.blocks.length - 1 || !!b.locked} onClick={() => move(b.id, 1)}>▼</Tool>222            {INLINE_TEXT.has(b.type) && <Tool label={t.edit} disabled={!!b.locked} onClick={() => setInline(b.id)}>✎</Tool>}223            {b.type === "diagram" && <Tool label={t.visual} onClick={() => setDiagramId(b.id)}>◇</Tool>}224            <Tool label={t.dup} onClick={() => duplicate([b.id])}>⧉</Tool>225            <Tool label={b.locked ? t.unlock : t.lock} onClick={() => patchBlock(b.id, { ...b, locked: b.locked ? undefined : true })}>{b.locked ? "🔒" : "🔓"}</Tool>226            <Tool label={t.ask} onClick={() => { setPanel("claude"); setDrawer("claude"); }}>✦</Tool>227            <Tool label={t.del} disabled={!!b.locked} onClick={() => remove([b.id])}>✕</Tool>228          </div>229        )}230      </div>231    );232    // eslint-disable-next-line react-hooks/exhaustive-deps233  }, [selected, highlight, inline, doc, locale]);234235  const sheetView = useMemo(() => <SheetView doc={doc} locale={doc.metadata.locale} mode="editor" assetUrl={(id) => `/api/admin/assets/${id}/file`} wrapBlock={wrapBlock} />, [doc, wrapBlock]);236  const diagram = diagramId ? (allBlocks(doc).find((b) => b.id === diagramId && b.type === "diagram") as BlockOf<"diagram"> | undefined) : undefined;237238  // ── Panels ────────────────────────────────────────────────────────────────────────────────────────239  const ensureSaved = useCallback(() => save(), [save]);240  const renderPanel = (p: Panel) => {241    switch (p) {242      case "blocks": return <LibraryPanel locale={locale} onAdd={(type) => void addBlock(type)} />;243      case "outline": return <OutlinePanel doc={doc} locale={locale} selected={selected} onSelect={(id, add) => { select(id, add); document.getElementById(id)?.scrollIntoView({ block: "center", behavior: "smooth" }); }} onMove={move} />;244      case "props": return block245        ? <BlockForm key={block.id} block={block} doc={doc} locale={locale} onChange={(next) => patchBlock(block.id, next)} onOpenDiagramEditor={block.type === "diagram" ? () => setDiagramId(block.id) : undefined} onPickAsset={pickAsset} loadDataset={loadDataset} />246        : <p className="text-sm text-muted">{selected.length > 1 ? fill(t.multi, { n: selected.length }) : t.none}{selected.length > 1 && <span className="mt-3 flex gap-2"><button className="btn btn-sm" onClick={() => duplicate(selected)}>{t.dup}</button><button className="btn btn-sm btn-danger" onClick={() => remove(selected)}>{t.del}</button></span>}</p>;247      case "claude": return <ClaudePanel sheetId={initial.id} locale={doc.metadata.locale} uiLocale={locale} selected={selected} configured={aiConfigured} ensureSaved={ensureSaved}248        onApplied={async (diff: SheetDiff | null) => { await reloadFromServer(); if (diff) setHighlight([...diff.added, ...diff.changed]); }} onHighlight={setHighlight}249        onUndoRevision={async (revisionId) => { const v = await save(); const rev = await api<{ parentId: string | null }>(`/api/admin/sheets/${initial.id}/revisions/${revisionId}`); if (!rev.parentId) return; await api(`/api/admin/sheets/${initial.id}/revert`, { body: { revisionId: rev.parentId, expectedVersion: v } }); await reloadFromServer(); }} />;250      case "quality": return <QualityPanel report={quality} locale={locale} overflowPx={overflowPx} onSelect={(id) => { select(id); setHighlight([topId(id)]); setDrawer(null); }} />;251      case "sources": return <SourcesPanel sheetId={initial.id} doc={doc} locale={locale} onChange={(next) => commit(next, "sources")} ensureSaved={ensureSaved} onApplied={async () => { await reloadFromServer(); }} />;252      case "sheet": return <MetaPanel key={`${detail.slug}:${detail.status}`} detail={detail} doc={doc} locale={locale} onChange={commit} onSettingsSaved={refreshDetail} />;253    }254  };255  const TABS: [Panel, string][] = [["props", t.props], ["claude", t.claude], ["quality", t.quality], ["sources", t.sources], ["sheet", t.sheet]];256  // Between 768 and 1023 px there is no left column: the library and the outline join the right-hand tabs.257  const NARROW_TABS: [Panel, string][] = [["blocks", t.blocks], ["outline", t.outline]];258  const badge = quality ? quality.errors || quality.warnings : 0;259  const saveLabel = { saved: t.saved, dirty: t.unsaved, saving: t.saving, invalid: t.invalid, conflict: t.conflict, error: saveError ?? "" }[saveState];260  const width = DEVICE_WIDTH[device];261262  return (263    <div className="flex h-dvh flex-col bg-raised">264      {/* Top bar */}265      <header className="z-30 flex shrink-0 items-center gap-1.5 border-b border-line bg-surface px-2 sm:px-3" style={{ paddingTop: "env(safe-area-inset-top)", minHeight: "calc(3.25rem + env(safe-area-inset-top))" }}>266        <Link href="/admin" className="btn btn-ghost btn-sm !min-h-11 !px-3" aria-label={t.back}>←</Link>267        <div className="min-w-0 flex-1">268          <p className="truncate text-sm font-semibold" lang={doc.metadata.locale}>{doc.metadata.title}</p>269          <p className="flex items-center gap-2 truncate text-xs text-faint" role="status" aria-live="polite">270            <StatusPill status={detail.status} fr={fr} />271            {detail.status === "published" && (detail.hasUnpublishedChanges || dirty || version !== initial.version) && detail.publishedRevisionId !== detail.currentRevisionId && <span className="hidden text-warn sm:inline">{t.unpublished}</span>}272            <span className={saveState === "invalid" || saveState === "error" || saveState === "conflict" ? "text-bad" : ""}>{saveState === "saving" && <Spinner />} {saveState === "conflict" ? "" : saveLabel}</span>273          </p>274        </div>275        <button type="button" className="btn btn-ghost btn-sm !min-h-11 !px-3" onClick={state.undo} disabled={!state.canUndo} aria-label={t.undo} title={t.undo}>↶</button>276        <button type="button" className="btn btn-ghost btn-sm !min-h-11 !px-3" onClick={state.redo} disabled={!state.canRedo} aria-label={t.redo} title={t.redo}>↷</button>277        <div className="hidden items-center rounded-lg border border-line p-0.5 lg:flex" role="group" aria-label={t.width}>278          {(["desktop", "tablet", "phone"] as const).map((d) => <button key={d} type="button" className={`rounded-md px-2.5 py-1.5 text-xs font-semibold ${device === d ? "bg-accent text-accent-ink" : "text-muted"}`} aria-pressed={device === d} onClick={() => setDevice(d)}>{t[d]}</button>)}279        </div>280        <button type="button" className="btn btn-sm hidden sm:inline-flex" onClick={() => void save().catch(() => {})} disabled={!dirty || saveState === "saving"}>{t.save}</button>281        <button type="button" className="btn btn-sm hidden md:inline-flex" onClick={() => setDialog("preview")}>{t.preview}</button>282        <button type="button" className="btn btn-primary btn-sm hidden sm:inline-flex" onClick={() => setDialog("publish")}>{detail.status === "published" ? t.republish : t.publish}</button>283        <button type="button" className="btn btn-ghost btn-sm !min-h-11 !px-3" onClick={() => setDialog("more")} aria-label={t.more} title={t.more}>⋯</button>284      </header>285      {saveState === "conflict" && <div className="shrink-0 px-3 pt-2"><Notice tone="bad">{t.conflict} <button className="btn btn-sm ml-2" onClick={() => window.location.reload()}>{t.reload}</button></Notice></div>}286      {(saveState === "invalid" || saveState === "error") && saveError && <div className="shrink-0 px-3 pt-2"><Notice tone="bad">{saveLabel}{saveState === "invalid" ? ` : ${saveError}` : ""}</Notice></div>}287288      <div className="flex min-h-0 flex-1">289        {/* Left: library and outline (desktop) */}290        <aside className="hidden w-72 shrink-0 flex-col border-r border-line bg-surface lg:flex">291          <div className="flex border-b border-line" role="tablist">292            {(["blocks", "outline"] as const).map((k) => <button key={k} role="tab" aria-selected={leftTab === k} className={`min-h-11 flex-1 text-sm font-semibold ${leftTab === k ? "border-b-2 border-accent text-ink" : "text-muted"}`} onClick={() => setLeftTab(k)}>{t[k]}</button>)}293          </div>294          <div className="min-h-0 flex-1 overflow-y-auto p-3">{renderPanel(leftTab)}</div>295        </aside>296297        {/* Canvas */}298        <div ref={canvas} className="min-w-0 flex-1 overflow-auto pb-36 pt-14 sm:px-4 lg:pb-10" onClick={(e) => { if (e.target === e.currentTarget) setSelected([]); }}>299          <div className="mx-auto overflow-visible rounded-none border-y border-line shadow-card sm:rounded-2xl sm:border" style={{ maxWidth: width ?? (FORMAT_SIZES[doc.layout.format].height ? FORMAT_SIZES[doc.layout.format].width : doc.layout.maxWidth), width: width ?? undefined }}>300            <div className="overflow-visible sm:rounded-2xl [&>article]:sm:rounded-2xl">{sheetView}</div>301          </div>302          <p className="mx-auto mt-4 hidden max-w-3xl px-4 text-center text-xs text-faint lg:block">{t.shortcuts}</p>303        </div>304305        {/* Right: properties, Claude, quality, sources, sheet (desktop / tablet) */}306        <aside className="hidden w-[22.5rem] shrink-0 flex-col border-l border-line bg-surface md:flex">307          <div className="flex overflow-x-auto border-b border-line" role="tablist">308            {NARROW_TABS.map(([k, label]) => <button key={k} role="tab" aria-selected={panel === k} className={`min-h-11 shrink-0 px-2 text-[0.8125rem] font-semibold lg:hidden ${panel === k ? "border-b-2 border-accent text-ink" : "text-muted"}`} onClick={() => setPanel(k)}>{label}</button>)}309            {TABS.map(([k, label]) => <button key={k} role="tab" aria-selected={panel === k} className={`relative min-h-11 flex-1 px-1 text-[0.8125rem] font-semibold ${panel === k ? "border-b-2 border-accent text-ink" : "text-muted"}`} onClick={() => setPanel(k)}>{label}{k === "quality" && badge > 0 && <span className={`ml-1 rounded-full px-1.5 text-[0.6875rem] text-white ${quality!.errors ? "bg-bad" : "bg-warn"}`}>{badge}</span>}</button>)}310          </div>311          <div className="min-h-0 flex-1 overflow-y-auto p-3">{renderPanel(panel)}</div>312        </aside>313      </div>314315      {/* Phone: fixed action bar (save, preview, publish) + panel tabs, above the home indicator */}316      <div className="fixed inset-x-0 bottom-0 z-30 border-t border-line bg-surface/95 backdrop-blur md:hidden" style={{ paddingBottom: "env(safe-area-inset-bottom)" }}>317        <div className="flex gap-2 px-2 pt-2 sm:hidden">318          <button type="button" className="btn btn-sm flex-1" onClick={() => void save().catch(() => {})} disabled={!dirty || saveState === "saving"}>{t.save}</button>319          <button type="button" className="btn btn-sm flex-1" onClick={() => setDialog("preview")}>{t.preview}</button>320          <button type="button" className="btn btn-primary btn-sm flex-1" onClick={() => setDialog("publish")}>{t.publish}</button>321        </div>322        <nav className="grid grid-cols-6" aria-label={t.more}>323          {([["blocks", t.blocks], ["outline", t.outline], ["props", t.props], ["claude", t.claude], ["quality", t.quality], ["sheet", t.sheet]] as [Panel, string][]).map(([k, label]) => (324            <button key={k} type="button" className="relative min-h-12 text-[0.6875rem] font-semibold text-muted" onClick={() => setDrawer(k)}>{label}{k === "quality" && badge > 0 && <span className={`absolute right-2 top-1.5 h-2 w-2 rounded-full ${quality!.errors ? "bg-bad" : "bg-warn"}`} />}</button>325          ))}326        </nav>327      </div>328      {drawer && (329        <div className="fixed inset-0 z-40 flex flex-col justify-end md:hidden" role="dialog" aria-modal="true">330          <button type="button" className="flex-1 bg-black/40" aria-label={t.close} onClick={() => setDrawer(null)} />331          <div className="flex max-h-[82dvh] min-h-[45dvh] flex-col rounded-t-2xl border-t border-line bg-surface" style={{ paddingBottom: "env(safe-area-inset-bottom)" }}>332            <div className="flex items-center gap-1 overflow-x-auto border-b border-line px-2">333              {([["blocks", t.blocks], ["outline", t.outline], ...TABS] as [Panel, string][]).map(([k, label]) => <button key={k} type="button" className={`min-h-12 shrink-0 px-3 text-sm font-semibold ${drawer === k ? "border-b-2 border-accent text-ink" : "text-muted"}`} onClick={() => setDrawer(k)}>{label}</button>)}334              <button type="button" className="btn btn-ghost btn-sm ml-auto !min-h-11 shrink-0 !px-3" onClick={() => setDrawer(null)} aria-label={t.close}>✕</button>335            </div>336            <div className="min-h-0 flex-1 overflow-y-auto p-3">{renderPanel(drawer)}</div>337          </div>338        </div>339      )}340341      {/* Visual diagram editor */}342      {diagram && (343        <div className="fixed inset-0 z-50 flex flex-col bg-surface" role="dialog" aria-modal="true" aria-label={t.visual}>344          <div className="flex shrink-0 items-center justify-between border-b border-line px-3" style={{ paddingTop: "env(safe-area-inset-top)", minHeight: "calc(3rem + env(safe-area-inset-top))" }}>345            <p className="font-semibold">{t.visual} — {diagram.title ?? diagram.id}</p>346            <button type="button" className="btn btn-primary btn-sm" onClick={() => setDiagramId(null)}>{t.close}</button>347          </div>348          <div className="min-h-0 flex-1"><DiagramEditor block={diagram} locale={locale} theme={doc.theme} onChange={(next) => commit(replaceBlock(docRef.current, diagram.id, next))} /></div>349        </div>350      )}351352      <Dialogs dialog={dialog} setDialog={setDialog} detail={detail} doc={doc} quality={quality} selected={block} save={save} refresh={refreshDetail} aiConfigured={aiConfigured} />353      <AssetPicker pick={assetPick} onClose={() => { assetPick?.resolve(null); setAssetPick(null); }} onChoose={attachAsset} />354    </div>355  );356}357358function Tool({ label, onClick, disabled, children }: { label: string; onClick: () => void; disabled?: boolean; children: ReactNode }) {359  return <button type="button" className="grid h-11 w-11 shrink-0 place-items-center rounded-lg text-base hover:bg-raised disabled:opacity-40" aria-label={label} title={label} disabled={disabled} onClick={(e) => { e.stopPropagation(); onClick(); }}>{children}</button>;360}361362/** In-place text editing on the canvas: the raw inline syntax, in the sheet's own typography. */363function InlineText({ value, multiline, hint, onDone, onCancel }: { value: string; multiline: boolean; hint: string; onDone: (v: string) => void; onCancel: () => void }) {364  const ref = useRef<HTMLTextAreaElement>(null);365  const [v, setV] = useState(value);366  useEffect(() => { const el = ref.current; if (el) { el.focus(); el.setSelectionRange(el.value.length, el.value.length); } }, []);367  useEffect(() => { const el = ref.current; if (el) { el.style.height = "auto"; el.style.height = `${el.scrollHeight}px`; } }, [v]);368  return (369    <div onClick={(e) => e.stopPropagation()}>370      <textarea ref={ref} value={v} onChange={(e) => setV(e.target.value)} rows={1} aria-label={hint} aria-describedby="inline-hint"371        className="block w-full resize-none rounded-lg border-2 border-[var(--ui-accent)] bg-[var(--sh-surface)] p-2 text-[1.0625rem] leading-relaxed text-[var(--sh-ink)]"372        onBlur={() => onDone(v)} onKeyDown={(e) => { if (e.key === "Escape") { e.preventDefault(); onCancel(); } else if (e.key === "Enter" && (!multiline || e.metaKey || e.ctrlKey)) { e.preventDefault(); onDone(v); } }} />373      <p id="inline-hint" className="mt-1 text-xs" style={{ color: "var(--sh-faint)", fontFamily: "var(--font-sans)" }}>{hint}{multiline ? " (⌘↵)" : ""}</p>374    </div>375  );376}377378// ── Asset picker ────────────────────────────────────────────────────────────────────────────────────379380function AssetPicker({ pick, onClose, onChoose }: { pick: { kind: "image" | "dataset" } | null; onClose: () => void; onChoose: (a: AssetView) => void }) {381  const locale = useLocale(), fr = locale === "fr", t = T(locale);382  const [items, setItems] = useState<AssetView[]>([]), [error, setError] = useState<string | null>(null), [busy, setBusy] = useState(false);383  const kinds = pick?.kind === "image" ? ["image"] : ["csv", "json"];384  useEffect(() => {385    if (!pick) return;386    setError(null);387    void Promise.all(kinds.map((k) => api<{ items: (AssetView & { dataset: unknown })[] }>(`/api/admin/assets?kind=${k}&limit=60`))).then((r) => setItems(r.flatMap((x) => x.items).filter((a) => pick.kind === "image" || a.dataset))).catch((e) => setError(errorText(e, fr)));388    // eslint-disable-next-line react-hooks/exhaustive-deps389  }, [pick?.kind]);390  const upload = async (file: File | undefined) => {391    if (!file) return;392    setBusy(true); setError(null);393    const form = new FormData(); form.set("file", file);394    try { onChoose(await api<AssetView>("/api/admin/assets", { form })); } catch (e) { setError(errorText(e, fr)); }395    setBusy(false);396  };397  return (398    <Dialog open={!!pick} onClose={onClose} title={pick?.kind === "image" ? t.image : t.dataset} wide>399      <div className="grid gap-4">400        <label className="btn w-fit cursor-pointer">{busy ? <Spinner /> : t.upload}<input type="file" className="sr-only" accept={pick?.kind === "image" ? "image/png,image/jpeg,image/webp,image/gif" : ".csv,.tsv,.json,text/csv,application/json"} disabled={busy} onChange={(e) => { void upload(e.target.files?.[0]); e.target.value = ""; }} /></label>401        {error && <Notice tone="bad">{error}</Notice>}402        {items.length === 0 && !error && <p className="text-sm text-muted">{t.noAsset}</p>}403        <ul className={pick?.kind === "image" ? "grid grid-cols-2 gap-3 sm:grid-cols-3" : "grid gap-2"}>404          {items.map((a) => (405            <li key={a.id}>406              <button type="button" className="w-full overflow-hidden rounded-xl border border-line text-left hover:border-accent" onClick={() => onChoose(a)}>407                {pick?.kind === "image" && <img src={`/api/admin/assets/${a.id}/file`} alt={a.alt} loading="lazy" className="aspect-video w-full bg-raised object-contain" />}408                <span className="block truncate px-3 py-2 text-sm">{a.filename}</span>409              </button>410            </li>411          ))}412        </ul>413      </div>414    </Dialog>415  );416}417418// ── Dialogs: publish, unpublish, preview link, export, translate, template, delete ──────────────────419420interface ExportView { id: string; status: string; error: string | null; downloadUrl: string | null }421422function Dialogs({ dialog, setDialog, detail, doc, quality, selected, save, refresh, aiConfigured }: {423  dialog: string | null; setDialog: (d: null | "publish" | "unpublish" | "preview" | "export" | "translate" | "template" | "delete" | "more") => void;424  detail: SheetDetail; doc: Sheet; quality: QualityReport | null; selected: Block | LeafBlock | null; save: () => Promise<number>; refresh: () => Promise<void>; aiConfigured: boolean;425}) {426  const locale = useLocale(), fr = locale === "fr", t = T(locale);427  const [busy, setBusy] = useState(false), [error, setError] = useState<string | null>(null), [done, setDone] = useState<string | null>(null);428  const [checked, setChecked] = useState(false), [link, setLink] = useState<string | null>(null), [copied, setCopied] = useState(false);429  const [scale, setScale] = useState<1 | 2 | 4>(2), [exp, setExp] = useState<ExportView | null>(null), [tplName, setTplName] = useState(doc.metadata.title);430  const [jobId, setJobId] = useState<string | null>(null), [trId, setTrId] = useState<string | null>(null);431  const close = () => { setDialog(null); setError(null); setDone(null); setChecked(false); setLink(null); setCopied(false); setExp(null); };432  const run = async (fn: () => Promise<void>) => { setBusy(true); setError(null); try { await fn(); } catch (e) { setError(e instanceof Error && e.message === "invalid" ? T(locale).invalid : errorText(e, fr)); } setBusy(false); };433  const job = useJob(jobId, (j: JobView) => { if (j.status === "succeeded") setTrId((j.output as { sheetId: string }).sheetId); if (j.status !== "failed") setJobId(null); });434435  // Export jobs are rendered by the worker: poll until the file is ready.436  useEffect(() => {437    if (!exp || exp.status === "succeeded" || exp.status === "failed") return;438    const id = setInterval(() => { void api<ExportView>(`/api/admin/exports/${exp.id}`).then(setExp).catch(() => {}); }, 1200);439    return () => clearInterval(id);440  }, [exp]);441  const startExport = (format: "pdf" | "png" | "svg") => run(async () => { await save(); setExp(await api<ExportView>("/api/admin/exports", { body: { sheetId: detail.id, format, scale, ...(format === "svg" ? { blockId: selected!.id } : {}) } })); });442  const other = doc.metadata.locale === "fr" ? "en" : "fr";443  const hasTranslation = detail.translations.find((x) => x.locale === other);444445  return (446    <>447      <Dialog open={dialog === "more"} onClose={close} title={t.more}>448        <ul className="grid gap-2">449          {([["preview", t.previewLink], ["export", t.export], ["translate", t.translate], ["template", t.template]] as const).map(([k, label]) => <li key={k}><button className="btn w-full justify-start" onClick={() => setDialog(k)}>{label}</button></li>)}450          <li><Link className="btn w-full justify-start" href="/admin/revisions">{t.history}</Link></li>451          {detail.status === "published" && <li><a className="btn w-full justify-start" href={`/s/${detail.slug}`} target="_blank" rel="noopener">{t.view}</a></li>}452          {detail.status === "published" && <li><button className="btn w-full justify-start" onClick={() => setDialog("unpublish")}>{t.unpublish}</button></li>}453          {detail.status !== "published" && <li><button className="btn btn-danger w-full justify-start" onClick={() => setDialog("delete")}>{t.delete}</button></li>}454        </ul>455      </Dialog>456457      <Dialog open={dialog === "publish"} onClose={close} title={t.pubTitle}>458        {done ? <div className="grid gap-3"><Notice tone="ok">{done}</Notice><a className="btn btn-primary" href={`/s/${detail.slug}`} target="_blank" rel="noopener">{t.view}</a></div> : (459          <div className="grid gap-3">460            <p className="text-muted">{t.pubLead}</p>461            <p className="rounded-lg border border-line bg-raised px-3 py-2 font-mono text-sm break-all">{typeof window === "undefined" ? "" : window.location.host}/s/{detail.slug}</p>462            {quality && quality.errors > 0 && <Notice tone="bad">{fill(t.pubBlocked, { n: quality.errors })}<ul className="mt-1 list-disc pl-5">{quality.items.filter((i) => i.severity === "error").slice(0, 6).map((i, k) => <li key={k}>{fr ? i.fr : i.en}</li>)}</ul></Notice>}463            {quality && quality.errors === 0 && quality.warnings > 0 && <Notice tone="warn">{fill(t.pubWarn, { n: quality.warnings })}<ul className="mt-1 list-disc pl-5">{quality.items.filter((i) => i.severity === "warning").slice(0, 6).map((i, k) => <li key={k}>{fr ? i.fr : i.en}</li>)}</ul></Notice>}464            <label className="flex min-h-11 items-start gap-3 text-sm"><input type="checkbox" className="mt-0.5 h-5 w-5 shrink-0" checked={checked} onChange={(e) => setChecked(e.target.checked)} />{t.pubCheck}</label>465            {error && <Notice tone="bad">{error}</Notice>}466            <button className="btn btn-primary" disabled={busy || !checked || !quality || quality.errors > 0} onClick={() => run(async () => { const v = await save(); await api(`/api/admin/sheets/${detail.id}/publish`, { body: { expectedVersion: v } }); await refresh(); setDone(t.pubDone); })}>{busy ? <Spinner /> : t.pubGo}</button>467          </div>468        )}469      </Dialog>470471      <Dialog open={dialog === "unpublish"} onClose={close} title={t.unpublish}>472        <div className="grid gap-3"><p className="text-muted">{t.unpubLead}</p>{error && <Notice tone="bad">{error}</Notice>}{done && <Notice tone="ok">{done}</Notice>}473          {!done && <button className="btn btn-danger" disabled={busy} onClick={() => run(async () => { await api(`/api/admin/sheets/${detail.id}/unpublish`, { method: "POST", body: {} }); await refresh(); setDone(t.unpubDone); })}>{t.unpublish}</button>}</div>474      </Dialog>475476      <Dialog open={dialog === "preview"} onClose={close} title={t.previewLink}>477        <div className="grid gap-3"><p className="text-muted">{t.previewLead}</p>{error && <Notice tone="bad">{error}</Notice>}478          {link && <><p className="rounded-lg border border-line bg-raised px-3 py-2 font-mono text-sm break-all">{link}</p>479            <div className="flex flex-wrap gap-2"><button className="btn" onClick={() => { void navigator.clipboard.writeText(link).then(() => setCopied(true)); }}>{copied ? t.copied : t.copy}</button><a className="btn btn-primary" href={link} target="_blank" rel="noopener">{t.preview}</a></div></>}480          <div className="flex flex-wrap gap-2">481            <button className="btn" disabled={busy} onClick={() => run(async () => { await save(); setLink((await api<{ url: string }>(`/api/admin/sheets/${detail.id}/preview-link`, { method: "POST", body: {} })).url); setCopied(false); })}>{t.create}</button>482            <button className="btn btn-ghost" disabled={busy} onClick={() => run(async () => { await api(`/api/admin/sheets/${detail.id}/preview-link`, { method: "DELETE" }); setLink(null); })}>{t.revoke}</button>483          </div></div>484      </Dialog>485486      <Dialog open={dialog === "export"} onClose={close} title={t.export}>487        <div className="grid gap-3"><p className="text-muted">{t.exportLead}</p>488          <label className="grid gap-1.5 text-sm font-medium">{t.scale} (PNG)<select className="field" value={scale} onChange={(e) => setScale(Number(e.target.value) as 1 | 2 | 4)}><option value={1}>1×</option><option value={2}>2×</option><option value={4}>4×</option></select></label>489          <div className="grid grid-cols-2 gap-2">490            <button className="btn" disabled={busy} onClick={() => startExport("pdf")}>{t.pdf}</button>491            <button className="btn" disabled={busy} onClick={() => startExport("png")}>{t.png} {scale}×</button>492            <button className="btn" disabled={busy || !selected || !VECTOR.has(selected.type)} onClick={() => startExport("svg")}>SVG</button>493            <a className="btn" href={`/api/admin/sheets/${detail.id}/export.json`} download>{t.json}</a>494          </div>495          {(!selected || !VECTOR.has(selected.type)) && <p className="text-sm text-faint">{t.svg} : {t.svgNeeds}</p>}496          {error && <Notice tone="bad">{error}</Notice>}497          {exp && (exp.status === "succeeded" && exp.downloadUrl ? <a className="btn btn-primary" href={exp.downloadUrl} download>{t.download}</a>498            : exp.status === "failed" ? <Notice tone="bad">{exp.error}</Notice> : <p className="flex items-center gap-2 text-sm text-muted" role="status"><Spinner /> {exp.status}</p>)}499        </div>500      </Dialog>501502      <Dialog open={dialog === "translate"} onClose={close} title={t.translate}>503        <div className="grid gap-3"><p className="text-muted">{t.translateLead}</p>504          {hasTranslation || trId ? <a className="btn btn-primary" href={`/admin/sheets/${trId ?? hasTranslation!.id}/edit`}>{t.openTr}</a>505            : !aiConfigured ? <Notice tone="warn">{fr ? "Claude n’est pas configuré sur ce serveur (clé API absente) : la traduction automatique est indisponible." : "Claude is not configured on this server (no API key): automatic translation is unavailable."}</Notice>506            : <button className="btn btn-primary" disabled={busy || !!jobId} onClick={() => run(async () => { await save(); setJobId((await api<JobView>(`/api/admin/sheets/${detail.id}/translate`, { body: { targetLocale: other, idempotencyKey: idempotencyKey() } })).id); })}>{other === "en" ? t.toEn : t.toFr}</button>}507          {job && <JobProgress job={job} />}{error && <Notice tone="bad">{error}</Notice>}</div>508      </Dialog>509510      <Dialog open={dialog === "template"} onClose={close} title={t.template}>511        <div className="grid gap-3">512          <label className="grid gap-1.5 text-sm font-medium">{t.tplName}<input className="field" value={tplName} maxLength={120} onChange={(e) => setTplName(e.target.value)} /></label>513          {error && <Notice tone="bad">{error}</Notice>}{done && <Notice tone="ok">{done}</Notice>}514          <button className="btn btn-primary" disabled={busy || !tplName.trim()} onClick={() => run(async () => { await save(); await api(`/api/admin/sheets/${detail.id}/save-as-template`, { body: { title: tplName.trim(), description: doc.metadata.summary.slice(0, 300) } }); setDone(t.tplDone); })}>{t.template}</button>515        </div>516      </Dialog>517518      <Dialog open={dialog === "delete"} onClose={close} title={t.delete}>519        <div className="grid gap-3"><p className="text-muted">{t.deleteLead}</p>{error && <Notice tone="bad">{error}</Notice>}520          <button className="btn btn-danger" disabled={busy} onClick={() => run(async () => { await api(`/api/admin/sheets/${detail.id}`, { method: "DELETE" }); window.location.assign("/admin"); })}>{t.confirmDelete}</button></div>521      </Dialog>522    </>523  );524}525
Files main
Menu

Theme