Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : KA Maps Engine8 * File : studio/web/src/ThemeEditor.tsx9 * Module : studio10 * Repository : https://git.spboucher.ai/ka-maps-engine11 * Created : 2026-12-0112 * Last Modified : 2026-12-0113 *14 * Author : Simon-Pierre Boucher15 * Position : Professor of Finance16 * Institution : Université du Québec en Outaouais (UQO)17 * Organization : SP Boucher18 * Website : https://spboucher.ai19 * Git : https://git.spboucher.ai20 *21 * Preferred Contact: support@spboucher.ai22 * Development : dev@spboucher.ai23 * Support : support@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142import { useCallback, useEffect, useMemo, useState } from 'react';43import { api, APP_LABEL, fmtBytes, fmtDate, PLATFORM_LABEL } from './api.ts';44import { looksLikeColor, resolveColor } from './color.ts';45import { Link, type Meta } from './main.tsx';46import { Preview } from './Preview.tsx';47import { ColorField, Issues, Notice, Num, ObjEditor, Ratio, StopsEditor, Swatch, Tabs } from './ui.tsx';4849type Tab = 'palette' | 'routes' | 'batiments' | 'couches' | 'etiquettes' | 'marqueurs' | 'json' | 'versions';50const TABS: [Tab, string][] = [['palette', 'Palette'], ['routes', 'Routes'], ['batiments', 'Bâtiments et lumière'], ['couches', 'Couches'], ['etiquettes', 'Étiquettes'], ['marqueurs', 'Marqueurs'], ['json', 'JSON'], ['versions', 'Versions et diffusion']];51const INKY = /ink|text|label/;52const PAIRS: [string, string][] = [['ink', 'land'], ['ink-soft', 'land'], ['ink-faint', 'land'], ['ink', 'paper'], ['accent-ink', 'accent'], ['shield-ink', 'shield'], ['water-ink', 'water'], ['park-ink', 'park']];5354export function DiffTable({ changes, palette }: { changes: any[]; palette: Record<string, unknown> }) {55 if (!changes.length) return <p className="muted">Aucune différence.</p>;56 const val = (v: unknown) => v === undefined ? <span className="faint">—</span> : (57 <span className="val">{looksLikeColor(v) ? <Swatch color={resolveColor(v, palette)} /> : null}<span>{typeof v === 'string' ? v : JSON.stringify(v)?.slice(0, 400)}</span></span>58 );59 const KIND: Record<string, [string, string]> = { added: ['ajouté', 'ok'], removed: ['retiré', 'bad'], changed: ['modifié', 'warn'], moved: ['ordre', ''] };60 return (61 <div className="table-wrap">62 <table className="diff" data-testid="diff">63 <thead><tr><th>Propriété</th><th></th><th>Avant</th><th>Après</th></tr></thead>64 <tbody>65 {changes.slice(0, 300).map((c, i) => (66 <tr key={i}>67 <td className="path">{c.path || '(racine)'}</td>68 <td><span className={`tag ${KIND[c.kind][1]}`}>{KIND[c.kind][0]}</span></td>69 <td>{c.kind === 'moved' ? <span className="faint">ordre des couches</span> : val(c.before)}</td>70 <td>{c.kind === 'moved' ? <span className="faint">modifié</span> : val(c.after)}</td>71 </tr>72 ))}73 </tbody>74 </table>75 {changes.length > 300 ? <p className="small faint" style={{ padding: 8 }}>… {changes.length - 300} autres différences</p> : null}76 </div>77 );78}7980export function ThemeEditor({ id, meta }: { id: string; meta: Meta }) {81 const [detail, setDetail] = useState<any>(null);82 const [doc, setDocRaw] = useState<any>(null);83 const [dirty, setDirty] = useState(false);84 const [tab, setTab] = useState<Tab>('palette');85 const [note, setNote] = useState('');86 const [saving, setSaving] = useState(false);87 const [issues, setIssues] = useState<any[] | null>(null);88 const [msg, setMsg] = useState<{ kind: 'ok' | 'bad' | 'warn'; text: string } | null>(null);89 const [loadErr, setLoadErr] = useState<string | null>(null);9091 const load = useCallback(async (keepDoc = false) => {92 try {93 const d = await api.get(`/api/themes/${id}`);94 setDetail(d);95 if (!keepDoc) {96 setDocRaw(d.doc);97 setDirty(false);98 }99 } catch (e: any) {100 setLoadErr(e.message);101 }102 }, [id]);103 useEffect(() => void load(), [load]);104 const setDoc = useCallback((d: any) => { setDocRaw(d); setDirty(true); setMsg(null); }, []);105106 const save = useCallback(async () => {107 if (!doc || saving) return;108 setSaving(true);109 setIssues(null);110 setMsg(null);111 try {112 const r = await api.post(`/api/themes/${id}/drafts`, { doc, note });113 setDirty(false);114 setNote('');115 setMsg({ kind: 'ok', text: `Brouillon enregistré (révision ${r.draftId}).${r.warnings?.length ? ` Avertissements : ${r.warnings.join(' ; ')}` : ''}` });116 await load(true);117 } catch (e: any) {118 if (e.detail?.errors) setIssues(e.detail.errors);119 else setMsg({ kind: 'bad', text: e.message });120 } finally {121 setSaving(false);122 }123 }, [doc, id, note, saving, load]);124 useEffect(() => {125 const f = (e: KeyboardEvent) => { if ((e.metaKey || e.ctrlKey) && e.key === 's') { e.preventDefault(); save(); } };126 addEventListener('keydown', f);127 return () => removeEventListener('keydown', f);128 }, [save]);129 useEffect(() => {130 const f = (e: BeforeUnloadEvent) => { if (dirty) e.preventDefault(); };131 addEventListener('beforeunload', f);132 return () => removeEventListener('beforeunload', f);133 }, [dirty]);134135 if (loadErr) return <Notice kind="bad">{loadErr} — <Link to="/themes">retour aux thèmes</Link></Notice>;136 if (!detail || !doc) return <p className="muted">Chargement…</p>;137 const palette: Record<string, unknown> = doc.palette ?? {};138 const land = resolveColor('@land', palette) ?? resolveColor(doc.background, palette);139 const setLayer = (i: number, patch: (l: any) => any) => setDoc({ ...doc, layers: doc.layers.map((l: any, j: number) => (j === i ? patch(l) : l)) });140 const setPaint = (i: number, k: string, v: any) => setLayer(i, (l) => ({ ...l, paint: { ...l.paint, [k]: v } }));141142 return (143 <>144 <div className="head">145 <div>146 <p className="small muted" style={{ margin: 0 }}><Link to="/themes">Thèmes</Link> /</p>147 <h1>{detail.theme.title} <code style={{ fontSize: 14 }}>{id}</code></h1>148 <p className="muted small">149 {detail.latestVersion ? `Dernière version publiée : v${detail.latestVersion}.` : 'Jamais publié.'} Document de travail : {detail.docSource?.kind === 'draft' ? `brouillon nº ${detail.docSource.id}` : `version ${detail.docSource?.version}`}150 {dirty ? <> · <span className="tag warn" data-testid="dirty">modifications non enregistrées</span></> : null}151 </p>152 </div>153 <div className="row">154 <input type="text" placeholder="Note de révision (facultative)" aria-label="Note de révision" value={note} onChange={(e) => setNote(e.target.value)} style={{ width: 240 }} />155 <button className="btn primary" onClick={save} disabled={saving || !dirty} data-testid="save">{saving ? 'Validation…' : 'Enregistrer le brouillon'}</button>156 </div>157 </div>158 {msg ? <Notice kind={msg.kind}>{msg.text}</Notice> : null}159 {issues ? <Issues title="Document refusé : rien n'a été enregistré." errors={issues} /> : null}160 <Tabs tabs={TABS} value={tab} onChange={setTab} />161 <div className={tab === 'versions' ? '' : 'editor'}>162 <div>163 {tab === 'palette' ? (164 <>165 <h2 style={{ marginTop: 0, borderTop: 0, paddingTop: 0 }}>Paires de lecture — contraste</h2>166 <div className="row" style={{ gap: 14 }}>167 {PAIRS.filter(([a, b]) => a in palette && b in palette).map(([a, b]) => (168 <span key={a + b} className="small"><Swatch color={resolveColor(`@${a}`, palette)} /> <span className="mono">{a}</span> sur <Swatch color={resolveColor(`@${b}`, palette)} /> <span className="mono">{b}</span> <Ratio fg={resolveColor(`@${a}`, palette)} bg={resolveColor(`@${b}`, palette)} /></span>169 ))}170 </div>171 <h2>Couleurs nommées <span className="faint" style={{ textTransform: 'none', letterSpacing: 0 }}>— contraste par rapport au sol (land) ; jugé (vert ≥ 4,5, rouge sous 3) pour les encres seulement</span></h2>172 <div className="kv" style={{ gridTemplateColumns: 'minmax(120px, 170px) 1fr auto' }}>173 {Object.entries(palette).filter(([k]) => !k.startsWith('_')).map(([k, v]) => [174 <label key={k + 'l'} className="mono">{k}</label>,175 <div key={k + 'v'}><ColorField label={`palette ${k}`} value={v} palette={palette} against={k === 'land' ? undefined : land} judge={INKY.test(k)} onChange={(c) => setDoc({ ...doc, palette: { ...palette, [k]: c } })} /></div>,176 <button key={k + 'x'} className="btn small" aria-label={`Retirer ${k}`} onClick={() => { const { [k]: _, ...rest } = palette; setDoc({ ...doc, palette: rest }); }}>×</button>,177 ])}178 </div>179 <AddEntry onAdd={(k) => setDoc({ ...doc, palette: { ...palette, [k]: '#888888' } })} />180 <h3>Fond</h3>181 {typeof doc.background === 'string' || Array.isArray(doc.background) ? <ColorField label="background" value={doc.background} palette={palette} onChange={(c) => setDoc({ ...doc, background: c })} /> : <span className="muted small">défini par zoom (onglet JSON)</span>}182 </>183 ) : null}184185 {tab === 'routes' ? <Roads doc={doc} palette={palette} setLayer={setLayer} setDoc={setDoc} /> : null}186187 {tab === 'batiments' ? (188 <>189 {doc.layers.map((l: any, i: number) => l.type !== 'extrusion' ? null : (190 <fieldset key={l.id}>191 <legend>Couche {l.id} — volumes (3D) et empreintes (2D)</legend>192 <div className="kv">193 {(['roof-color', 'wall-color', 'flat-color', 'flat-outline-color'] as const).map((k) => [194 <label key={k + 'l'}>{k}</label>,195 <div key={k}>{l.paint?.[k] && typeof l.paint[k] === 'object' && !Array.isArray(l.paint[k]) ? <span className="small muted">par zoom (JSON)</span> : <ColorField label={`${l.id} ${k}`} value={l.paint?.[k] ?? '#ffffff'} palette={palette} onChange={(c) => setPaint(i, k, c)} />}</div>,196 ])}197 <label>opacity</label><div><StopsEditor label={`${l.id} opacity`} unit="" value={l.paint?.opacity ?? 1} onChange={(v) => setPaint(i, 'opacity', v)} /></div>198 <label>flat-outline-width</label><div><StopsEditor label={`${l.id} flat-outline-width`} value={l.paint?.['flat-outline-width'] ?? 1} onChange={(v) => setPaint(i, 'flat-outline-width', v)} /></div>199 {(['min-height', 'default-height', 'vertical-gradient'] as const).map((k) => [<label key={k + 'l'}>{k}</label>, <div key={k}><Num label={`${l.id} ${k}`} value={l.paint?.[k]} onChange={(v) => setPaint(i, k, v)} /> <span className="faint small">{k === 'vertical-gradient' ? '0 à 1' : 'm'}</span></div>])}200 <label>minzoom</label><div><Num label={`${l.id} minzoom`} value={l.minzoom ?? 0} step={0.5} min={0} max={24} onChange={(v) => setLayer(i, (x) => ({ ...x, minzoom: v }))} /></div>201 </div>202 </fieldset>203 ))}204 <fieldset><legend>Lumière des volumes</legend><ObjEditor value={doc.light ?? {}} palette={palette} path="light" onChange={(v) => setDoc({ ...doc, light: v })} /><p className="small faint">azimuth : direction d'où vient la lumière (degrés depuis le nord) · altitude 1–90° · ambient 0–1 · intensity 0–2 · shadow-strength 0–1</p></fieldset>205 <fieldset><legend>Relief</legend><ObjEditor value={doc.terrain ?? {}} palette={palette} path="terrain" onChange={(v) => setDoc({ ...doc, terrain: v })} /></fieldset>206 <fieldset><legend>Ouverture du thème</legend><ObjEditor value={doc.defaults ?? { mode: '2d', pitch: 0, bearing: 0 }} palette={palette} path="defaults" onChange={(v) => setDoc({ ...doc, defaults: v })} /></fieldset>207 </>208 ) : null}209210 {tab === 'couches' ? <Layers doc={doc} setLayer={setLayer} /> : null}211212 {tab === 'etiquettes' ? (213 <div className="table-wrap">214 <table>215 <thead><tr><th>Couche</th><th>Taille du texte (px par zoom)</th><th>Couleur</th><th>Halo</th><th>Police</th><th>Priorité</th></tr></thead>216 <tbody>217 {doc.layers.map((l: any, i: number) => l.type !== 'symbol' ? null : (218 <tr key={l.id}>219 <td className="mono small">{l.id}<br /><span className="faint">{l.paint?.['text-field'] ?? 'icône'}</span></td>220 <td>{l.paint?.['text-field'] ? <StopsEditor label={`${l.id} text-size`} value={l.paint?.['text-size'] ?? 12} onChange={(v) => setPaint(i, 'text-size', v)} /> : <span className="faint">—</span>}</td>221 <td>{typeof l.paint?.color === 'object' && !Array.isArray(l.paint.color) ? <span className="small muted">par zoom</span> : <ColorField label={`${l.id} color`} value={l.paint?.color ?? 'black'} palette={palette} against={land} onChange={(c) => setPaint(i, 'color', c)} />}</td>222 <td>{l.paint?.['halo-color'] !== undefined && !(typeof l.paint['halo-color'] === 'object' && !Array.isArray(l.paint['halo-color'])) ? <ColorField label={`${l.id} halo-color`} value={l.paint['halo-color']} palette={palette} onChange={(c) => setPaint(i, 'halo-color', c)} /> : <span className="faint">—</span>}</td>223 <td><select aria-label={`${l.id} police`} value={l.paint?.font ?? 'regular'} onChange={(e) => setPaint(i, 'font', e.target.value)}><option>regular</option><option>medium</option><option>semibold</option></select></td>224 <td><Num label={`${l.id} priority`} value={l.paint?.priority ?? 50} step={1} onChange={(v) => setPaint(i, 'priority', v)} /></td>225 </tr>226 ))}227 </tbody>228 </table>229 </div>230 ) : null}231232 {tab === 'marqueurs' ? (233 <>234 <p className="muted small">Règles des couches d'application : pastilles de prix (états, natures, genres), grappes, points, sélection, chaleur, colonnes, outils. Une nature change la forme, pas seulement la teinte ; le moteur refuse deux natures de même forme.</p>235 <ObjEditor value={doc.markers ?? {}} palette={palette} path="markers" bg={resolveColor('@accent', palette)} onChange={(v) => setDoc({ ...doc, markers: v })} />236 <h2>Échelles de couleur</h2>237 <ObjEditor value={doc.scales ?? {}} palette={palette} path="scales" onChange={(v) => setDoc({ ...doc, scales: v })} />238 </>239 ) : null}240241 {tab === 'json' ? <JsonTab doc={doc} setDoc={setDoc} /> : null}242243 {tab === 'versions' ? <Versions id={id} detail={detail} meta={meta} dirty={dirty} palette={palette} reload={() => load(true)} loadDoc={(d) => { setDoc(d); setTab('palette'); }} /> : null}244 </div>245 {tab !== 'versions' ? <Preview doc={doc} presets={meta.presets} apps={meta.apps} sdkVersions={meta.sdk} /> : null}246 </div>247 </>248 );249}250251function AddEntry({ onAdd }: { onAdd: (k: string) => void }) {252 const [k, setK] = useState('');253 const ok = /^[A-Za-z_][A-Za-z0-9_-]*$/.test(k);254 return <p className="row"><input type="text" aria-label="Nom de la nouvelle couleur" placeholder="nouvelle-couleur" value={k} onChange={(e) => setK(e.target.value)} /><button className="btn small" disabled={!ok} onClick={() => { onAdd(k); setK(''); }}>Ajouter une couleur</button></p>;255}256257function Roads({ doc, palette, setLayer, setDoc }: { doc: any; palette: Record<string, unknown>; setLayer: (i: number, p: (l: any) => any) => void; setDoc: (d: any) => void }) {258 const [group, setGroup] = useState('road');259 const [linked, setLinked] = useState(true);260 const rows = doc.layers.map((l: any, i: number) => [l, i] as [any, number]).filter(([l]: [any, number]) => l.type === 'line' && l.source === 'road' && (group === 'autres' ? !l.group : l.group === group));261 const set = (i: number, l: any, k: string, v: any) => {262 // Les largeurs d'une classe sont les mêmes au sol, sur les ponts et dans les tunnels : option de report.263 if (linked && group === 'road' && (k === 'width' || k === 'minzoom')) {264 const twins = new Set([`${l.id}-bridge`, `${l.id}-tunnel`, l.id]);265 setDoc({ ...doc, layers: doc.layers.map((x: any) => (twins.has(x.id) ? (k === 'minzoom' ? { ...x, minzoom: v } : { ...x, paint: { ...x.paint, [k]: v } }) : x)) });266 } else setLayer(i, (x) => (k === 'minzoom' ? { ...x, minzoom: v } : { ...x, paint: { ...x.paint, [k]: v } }));267 };268 return (269 <>270 <div className="row" style={{ marginBottom: 10 }}>271 <label className="c">Groupe <select aria-label="Groupe de routes" value={group} onChange={(e) => setGroup(e.target.value)}><option value="road">au sol</option><option value="bridge">ponts</option><option value="tunnel">tunnels</option><option value="autres">hors groupe (traversier…)</option></select></label>272 {group === 'road' ? <label className="c small"><input type="checkbox" checked={linked} onChange={(e) => setLinked(e.target.checked)} /> reporter largeur et zoom d'apparition sur les ponts et tunnels de la même classe</label> : null}273 </div>274 {rows.map(([l, i]: [any, number]) => (275 <fieldset key={l.id}>276 <legend>{l.id}</legend>277 <div className="kv">278 <label>Couleur</label><div>{typeof l.paint?.color === 'object' && !Array.isArray(l.paint.color) ? <span className="small muted">par zoom (JSON)</span> : <ColorField label={`${l.id} couleur`} value={l.paint?.color ?? 'black'} palette={palette} onChange={(c) => set(i, l, 'color', c)} />}</div>279 <label>Largeur par zoom</label><div><StopsEditor label={`${l.id} largeur`} value={l.paint?.width ?? 1} onChange={(v) => set(i, l, 'width', v)} /></div>280 <label>Liseré — couleur</label><div>{l.paint?.['casing-color'] !== undefined ? <ColorField label={`${l.id} liseré`} value={l.paint['casing-color']} palette={palette} onChange={(c) => set(i, l, 'casing-color', c)} /> : <button className="btn small" onClick={() => setLayer(i, (x) => ({ ...x, paint: { ...x.paint, 'casing-color': '@casing', 'casing-width': 0.8 } }))}>Ajouter un liseré</button>}</div>281 {l.paint?.['casing-color'] !== undefined ? [<label key="l">Liseré — largeur de chaque côté</label>, <div key="v"><StopsEditor label={`${l.id} largeur du liseré`} value={l.paint?.['casing-width'] ?? 0} onChange={(v) => set(i, l, 'casing-width', v)} /></div>] : null}282 <label>Apparaît au zoom</label><div><Num label={`${l.id} minzoom`} value={l.minzoom ?? 0} step={0.5} min={0} max={24} onChange={(v) => set(i, l, 'minzoom', v)} /></div>283 </div>284 </fieldset>285 ))}286 {!rows.length ? <p className="muted">Aucune couche de route dans ce groupe.</p> : null}287 </>288 );289}290291function Layers({ doc, setLayer }: { doc: any; setLayer: (i: number, p: (l: any) => any) => void }) {292 const [q, setQ] = useState('');293 const hidden = (l: any) => (l.minzoom ?? 0) >= 24;294 const toggle = (i: number, l: any) => setLayer(i, (x) => {295 if (hidden(l)) {296 const { _minzoom, ...rest } = x;297 const back = typeof _minzoom === 'number' ? _minzoom : 0;298 const { minzoom, ...noMin } = rest;299 return back > 0 ? { ...rest, minzoom: back } : noMin;300 }301 return { ...x, _minzoom: x.minzoom ?? 0, minzoom: 24 };302 });303 return (304 <>305 <p className="row"><input type="text" placeholder="Filtrer (identifiant, type, source)" aria-label="Filtrer les couches" value={q} onChange={(e) => setQ(e.target.value)} style={{ width: 280 }} /><span className="small muted">{doc.layers.length} couches, du dessous vers le dessus. Visible si minzoom ≤ zoom < maxzoom.</span></p>306 <div className="table-wrap">307 <table>308 <thead><tr><th>#</th><th>Couche</th><th>Type</th><th>Source</th><th>Visible</th><th>minzoom</th><th>maxzoom</th></tr></thead>309 <tbody>310 {doc.layers.map((l: any, i: number) => !`${l.id} ${l.type} ${l.source ?? ''}`.includes(q.toLowerCase()) ? null : (311 <tr key={l.id} style={hidden(l) ? { opacity: 0.55 } : undefined}>312 <td className="num faint">{i + 1}</td><td className="mono small">{l.id}</td><td>{l.type}</td><td>{l.source ?? '—'}</td>313 <td><input type="checkbox" aria-label={`${l.id} visible`} checked={!hidden(l)} onChange={() => toggle(i, l)} /></td>314 <td>{hidden(l) ? <span className="faint">masquée</span> : <Num label={`${l.id} minzoom`} value={l.minzoom ?? 0} step={0.5} min={0} max={24} onChange={(v) => setLayer(i, (x) => ({ ...x, minzoom: v }))} />}</td>315 <td><Num label={`${l.id} maxzoom`} value={l.maxzoom ?? 24} step={0.5} min={0} max={24} onChange={(v) => setLayer(i, (x) => ({ ...x, maxzoom: v }))} /></td>316 </tr>317 ))}318 </tbody>319 </table>320 </div>321 </>322 );323}324325function JsonTab({ doc, setDoc }: { doc: any; setDoc: (d: any) => void }) {326 const [text, setText] = useState(() => JSON.stringify(doc, null, 2));327 const [res, setRes] = useState<any>(null);328 const [parseErr, setParseErr] = useState<string | null>(null);329 const [busy, setBusy] = useState(false);330 const parse = () => {331 try {332 setParseErr(null);333 return JSON.parse(text);334 } catch (e: any) {335 setParseErr(e.message);336 return null;337 }338 };339 const validate = async () => {340 const d = parse();341 if (!d) return;342 setBusy(true);343 try {344 setRes(await api.post('/api/validate', { doc: d }));345 } finally {346 setBusy(false);347 }348 };349 return (350 <>351 <div className="row" style={{ marginBottom: 8 }}>352 <button className="btn" onClick={validate} disabled={busy}>Valider (schéma + moteur)</button>353 <button className="btn" onClick={() => { const d = parse(); if (d) setDoc(d); }}>Appliquer au brouillon et à l'aperçu</button>354 <button className="btn" onClick={() => setText(JSON.stringify(doc, null, 2))}>Recharger depuis l'éditeur</button>355 <a className="small" href="/api/schema/kastyle-1.json" target="_blank" rel="noreferrer">Schéma JSON kastyle/1</a>356 </div>357 {parseErr ? <Notice kind="bad">JSON illisible : {parseErr}</Notice> : null}358 {res ? (res.ok ? <Notice kind="ok">Document valide — {res.summary?.layers} couches.{res.warnings?.length ? ` Avertissements : ${res.warnings.join(' ; ')}` : ''}</Notice> : <Issues title={`${res.errors.length} erreur(s)`} errors={res.errors} />) : null}359 <textarea className="code" aria-label="Document JSON du thème" spellCheck={false} rows={34} value={text} onChange={(e) => setText(e.target.value)} />360 </>361 );362}363364function Versions({ id, detail, meta, dirty, palette, reload, loadDoc }: { id: string; detail: any; meta: Meta; dirty: boolean; palette: Record<string, unknown>; reload: () => Promise<void>; loadDoc: (d: any) => void }) {365 const head = detail.drafts[0];366 const publishedDraft = detail.versions[0]?.draft_id ?? 0;367 const pending = head && head.id > publishedDraft ? head : null;368 const [diff, setDiff] = useState<{ title: string; changes: any[] } | null>(null);369 const [pnote, setPnote] = useState('');370 const [percent, setPercent] = useState(10);371 const all = useMemo(() => meta.apps.flatMap((app) => meta.platforms.map((platform) => `${app}/${platform}`)), [meta]);372 const [sel, setSel] = useState<Set<string>>(() => new Set(all));373 const [msg, setMsg] = useState<{ kind: 'ok' | 'bad'; text: string; errors?: any[] } | null>(null);374 const [busy, setBusy] = useState(false);375 const [rv, setRv] = useState<number>(detail.latestVersion ?? 1);376 const [rp, setRp] = useState(50);377 useEffect(() => { if (detail.latestVersion) setRv(detail.latestVersion); }, [detail.latestVersion]);378 const targets = () => (sel.size === all.length ? 'all' : [...sel].map((s) => ({ app: s.split('/')[0], platform: s.split('/')[1] })));379 const run = async (label: string, fn: () => Promise<any>) => {380 setBusy(true);381 setMsg(null);382 try {383 const r = await fn();384 setMsg({ kind: 'ok', text: `${label}${r?.version ? ` — version ${r.version}` : ''}${r?.channels ? ` (${r.channels.length} canal${r.channels.length > 1 ? 'aux' : ''} modifié${r.channels.length > 1 ? 's' : ''})` : ''}.` });385 await reload();386 } catch (e: any) {387 setMsg({ kind: 'bad', text: e.message, errors: e.detail?.errors });388 } finally {389 setBusy(false);390 }391 };392 useEffect(() => {393 if (!pending) return setDiff(null);394 api.get(`/api/themes/${id}/diff?from=${detail.latestVersion ? `v${detail.latestVersion}` : 'none'}&to=d${pending.id}`).then((d) => setDiff({ title: `Brouillon nº ${pending.id} par rapport à ${detail.latestVersion ? `la version ${detail.latestVersion}` : 'rien'}`, changes: d.changes }), () => {});395 }, [id, pending?.id, detail.latestVersion]);396 const ch = (app: string, platform: string) => detail.channels.find((c: any) => c.app === app && c.platform === platform);397 const showDiff = async (from: string, to: string, title: string) => setDiff({ title, changes: (await api.get(`/api/themes/${id}/diff?from=${from}&to=${to}`)).changes });398399 return (400 <>401 {msg ? (msg.errors ? <Issues title={msg.text} errors={msg.errors} /> : <Notice kind={msg.kind}>{msg.text}</Notice>) : null}402 <h2 style={{ marginTop: 0 }}>Publier</h2>403 <div className="panel">404 {dirty ? <Notice kind="warn">Des modifications ne sont pas enregistrées : enregistrez le brouillon avant de publier.</Notice> : null}405 {pending ? (406 <>407 <p>Le brouillon nº {pending.id} ({pending.author_name}, {fmtDate(pending.created_at)}) deviendra la <strong>version {(detail.latestVersion ?? 0) + 1}</strong>, immuable.</p>408 <div className="row">409 <label className="f" style={{ flex: 1, minWidth: 220 }}>Note de publication<input type="text" data-testid="publish-note" value={pnote} onChange={(e) => setPnote(e.target.value)} /></label>410 <label className="f">Diffusion initiale411 <select data-testid="publish-percent" value={percent} onChange={(e) => setPercent(Number(e.target.value))}>412 <option value={0}>0 % — publier sans diffuser</option><option value={10}>10 %</option><option value={25}>25 %</option><option value={50}>50 %</option><option value={100}>100 % — version stable</option>413 </select>414 </label>415 <button className="btn primary" data-testid="publish" disabled={busy || dirty || sel.size === 0} style={{ alignSelf: 'flex-end' }} onClick={() => run('Publié', () => api.post(`/api/themes/${id}/publish`, { draftId: pending.id, note: pnote, percent, targets: targets() }))}>Publier la version {(detail.latestVersion ?? 0) + 1}</button>416 </div>417 </>418 ) : <p className="muted">Aucun brouillon plus récent que la dernière version : rien à publier.</p>}419 </div>420421 <h2>Canaux de diffusion</h2>422 <p className="small muted">Par application et plateforme : la version stable, et la version candidate servie à un pourcentage des installations (tranche anonyme 0–99 tirée par l'application ; décalage de ce thème : {meta.salts[id] ?? '—'}). Les cases cochées sont les cibles des actions de cette page.</p>423 <div className="table-wrap">424 <table className="matrix" data-testid="channels">425 <thead><tr><th>Application</th>{meta.platforms.map((p) => <th key={p}>{PLATFORM_LABEL[p]}</th>)}</tr></thead>426 <tbody>427 {meta.apps.map((a) => (428 <tr key={a}>429 <td><label className="c"><input type="checkbox" aria-label={`Toutes les plateformes de ${APP_LABEL[a]}`} checked={meta.platforms.every((p) => sel.has(`${a}/${p}`))} onChange={(e) => { const n = new Set(sel); meta.platforms.forEach((p) => (e.target.checked ? n.add(`${a}/${p}`) : n.delete(`${a}/${p}`))); setSel(n); }} /> <strong>{APP_LABEL[a]}</strong></label></td>430 {meta.platforms.map((p) => {431 const c = ch(a, p);432 return (433 <td key={p} data-testid={`ch-${a}-${p}`}>434 <label className="c"><input type="checkbox" aria-label={`${APP_LABEL[a]} ${PLATFORM_LABEL[p]}`} checked={sel.has(`${a}/${p}`)} onChange={(e) => { const n = new Set(sel); e.target.checked ? n.add(`${a}/${p}`) : n.delete(`${a}/${p}`); setSel(n); }} />435 {c?.stable_version ? <span>stable v{c.stable_version}</span> : <span className="faint">non diffusé</span>}</label>436 {c?.candidate_version ? <div><span className="tag warn">v{c.candidate_version} à {c.candidate_percent} %</span></div> : null}437 </td>438 );439 })}440 </tr>441 ))}442 </tbody>443 </table>444 </div>445 <div className="row" style={{ marginTop: 10 }}>446 <span>Diffuser la version</span>447 <select aria-label="Version à diffuser" data-testid="rollout-version" value={rv} onChange={(e) => setRv(Number(e.target.value))}>{detail.versions.map((v: any) => <option key={v.version} value={v.version}>v{v.version}</option>)}</select>448 <span>à</span>449 <select aria-label="Pourcentage" data-testid="rollout-percent" value={rp} onChange={(e) => setRp(Number(e.target.value))}>{[0, 1, 5, 10, 25, 50, 75, 100].map((x) => <option key={x} value={x}>{x === 0 ? '0 % — annuler la diffusion' : x === 100 ? '100 % — stable' : `${x} %`}</option>)}</select>450 <span>sur {sel.size === all.length ? 'tous les canaux' : `${sel.size} canal${sel.size > 1 ? 'aux' : ''} coché${sel.size > 1 ? 's' : ''}`}</span>451 <button className="btn" data-testid="rollout" disabled={busy || sel.size === 0 || !detail.versions.length} onClick={() => run('Diffusion mise à jour', () => api.post(`/api/themes/${id}/rollout`, { version: rv, percent: rp, targets: targets() }))}>Appliquer</button>452 </div>453454 {diff ? <><h2>Différences — {diff.title}</h2><DiffTable changes={diff.changes} palette={palette} /></> : null}455456 <h2>Versions publiées</h2>457 <div className="table-wrap">458 <table data-testid="versions">459 <thead><tr><th>Version</th><th>Publiée</th><th>Auteur</th><th>Note</th><th>Moteur min.</th><th>Taille</th><th>Condensé</th><th></th></tr></thead>460 <tbody>461 {detail.versions.map((v: any) => (462 <tr key={v.version}>463 <td><strong>v{v.version}</strong></td><td>{fmtDate(v.created_at)}</td><td>{v.author_name}</td><td>{v.note || <span className="faint">—</span>}</td><td>{v.min_engine}</td><td className="num">{fmtBytes(v.bytes)}</td>464 <td className="mono small" title={v.sha256}>{v.sha256.slice(0, 12)}</td>465 <td className="row">466 {v.version > 1 ? <button className="btn small" onClick={() => showDiff(`v${v.version - 1}`, `v${v.version}`, `version ${v.version} par rapport à la version ${v.version - 1}`)}>Différences</button> : null}467 <button className="btn small" onClick={async () => loadDoc((await api.get(`/api/themes/${id}/versions/${v.version}`)).doc)}>Reprendre dans l'éditeur</button>468 <button className="btn small danger" data-testid={`rollback-${v.version}`} disabled={busy} onClick={() => { if (confirm(`Revenir à la version ${v.version} sur ${sel.size === all.length ? 'tous les canaux' : `${sel.size} canal(aux) coché(s)`} ? Toute diffusion en cours y sera annulée.`)) run(`Retour à la version ${v.version}`, () => api.post(`/api/themes/${id}/rollback`, { version: v.version, targets: targets() })); }}>Revenir à cette version</button>469 </td>470 </tr>471 ))}472 </tbody>473 </table>474 </div>475476 <h2>Révisions de brouillon</h2>477 <div className="table-wrap" style={{ maxHeight: 300, overflowY: 'auto' }}>478 <table>479 <thead><tr><th>Nº</th><th>Enregistré</th><th>Auteur</th><th>Note</th><th>Base</th><th></th></tr></thead>480 <tbody>{detail.drafts.map((d: any) => (481 <tr key={d.id}><td>{d.id}</td><td>{fmtDate(d.created_at)}</td><td>{d.author_name}</td><td>{d.note || <span className="faint">—</span>}</td><td>{d.base_version ? `v${d.base_version}` : '—'}</td>482 <td><button className="btn small" onClick={async () => loadDoc((await api.get(`/api/themes/${id}/drafts/${d.id}`)).doc)}>Reprendre</button></td></tr>483 ))}</tbody>484 </table>485 </div>486487 <h2>Historique de diffusion</h2>488 <div className="table-wrap" style={{ maxHeight: 320, overflowY: 'auto' }}>489 <table>490 <thead><tr><th>Date</th><th>Canal</th><th>Action</th><th>Version</th><th>%</th><th>Avant</th><th>Auteur</th><th>Note</th></tr></thead>491 <tbody>{detail.events.map((e: any) => (492 <tr key={e.id}><td>{fmtDate(e.at)}</td><td>{APP_LABEL[e.app]} {PLATFORM_LABEL[e.platform]}</td><td>{({ publish: 'publication', rollout: 'diffusion', promote: 'passage en stable', rollback: 'retour arrière', seed: 'import initial', cancel: 'annulation' } as any)[e.action]}</td><td>v{e.version}</td><td className="num">{e.percent}</td>493 <td className="small muted">stable {e.prev_stable ? `v${e.prev_stable}` : '—'}{e.prev_candidate ? `, candidate v${e.prev_candidate} à ${e.prev_percent} %` : ''}</td><td>{e.author_name}</td><td>{e.note}</td></tr>494 ))}</tbody>495 </table>496 </div>497 </>498 );499}500