Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : KA Maps Engine8 * File : studio/web/src/Apps.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, useState } from 'react';43import { api, APP_LABEL, fmtDate } from './api.ts';44import { resolveColor } from './color.ts';45import type { Meta } from './main.tsx';46import { Preview } from './Preview.tsx';47import { ColorField, Issues, JsonInput, Notice, Num, ObjEditor, Tabs } from './ui.tsx';4849export function Apps({ meta }: { meta: Meta }) {50 const [list, setList] = useState<any[] | null>(null);51 const [app, setApp] = useState(meta.apps[0]);52 const [cfg, setCfg] = useState<any>(null);53 const [dirty, setDirty] = useState(false);54 const [note, setNote] = useState('');55 const [themes, setThemes] = useState<any[]>([]);56 const [themeDoc, setThemeDoc] = useState<any>(null);57 const [msg, setMsg] = useState<{ kind: 'ok' | 'bad'; text: string } | null>(null);58 const [issues, setIssues] = useState<any[] | null>(null);59 const [flag, setFlag] = useState('');60 const [pk, setPk] = useState('');6162 const load = useCallback(async () => {63 const [a, t] = await Promise.all([api.get('/api/apps'), api.get('/api/themes')]);64 setList(a.apps);65 setThemes(t.themes.filter((x: any) => !x.archived_at));66 }, []);67 useEffect(() => void load(), [load]);68 const current = list?.find((x) => x.app === app);69 useEffect(() => {70 if (current?.current) {71 setCfg(structuredClone(current.current.config));72 setDirty(false);73 setIssues(null);74 }75 }, [current?.current?.rev, app]);76 useEffect(() => {77 if (!cfg?.defaultTheme) return;78 let live = true;79 api.get(`/api/themes/${cfg.defaultTheme}`).then((d) => live && setThemeDoc(d.doc), () => {});80 return () => { live = false; };81 }, [cfg?.defaultTheme]);82 const brandFor = useCallback(() => cfg?.brand ?? {}, [cfg?.brand]);8384 if (!list || !cfg) return <p className="muted">Chargement…</p>;85 const set = (patch: any) => { setCfg({ ...cfg, ...patch }); setDirty(true); setMsg(null); };86 const brand = cfg.brand ?? {};87 const basePalette = themeDoc?.palette ?? {};88 const merged = { ...basePalette, ...(brand.palette ?? {}) };89 const save = async () => {90 setIssues(null);91 try {92 const r = await api.put(`/api/apps/${app}`, { config: cfg, note });93 setMsg({ kind: 'ok', text: `Configuration enregistrée (révision ${r.rev}) : servie par le manifeste dès maintenant.` });94 setNote('');95 await load();96 } catch (e: any) {97 if (e.detail?.errors) setIssues(e.detail.errors);98 else setMsg({ kind: 'bad', text: e.message });99 }100 };101 return (102 <>103 <div className="head"><div><h1>Applications</h1><p className="muted">Marque, thème par défaut, couches, zooms et drapeaux de chaque produit. Chaque enregistrement est une révision ; la plus récente est en service.</p></div></div>104 <Tabs tabs={meta.apps.map((a) => [a, APP_LABEL[a] ?? a])} value={app} onChange={(a) => { if (!dirty || confirm('Abandonner les modifications non enregistrées ?')) setApp(a); }} />105 {msg ? <Notice kind={msg.kind}>{msg.text}</Notice> : null}106 {issues ? <Issues title="Configuration refusée : rien n'a été enregistré." errors={issues} /> : null}107 <div className="editor">108 <div>109 <fieldset><legend>Thèmes</legend>110 <div className="row">{themes.map((t) => (111 <label key={t.id} className="c"><input type="checkbox" checked={cfg.themes.includes(t.id)} onChange={(e) => set({ themes: e.target.checked ? [...cfg.themes, t.id].sort() : cfg.themes.filter((x: string) => x !== t.id) })} /> {t.title}</label>112 ))}</div>113 <p><label className="c">Thème par défaut <select aria-label="Thème par défaut" value={cfg.defaultTheme} onChange={(e) => set({ defaultTheme: e.target.value })}>{cfg.themes.map((t: string) => <option key={t}>{t}</option>)}</select></label></p>114 </fieldset>115 <fieldset><legend>Marque — couleurs surchargées</legend>116 <p className="small muted">Les couleurs dérivées du thème (mélanges, marqueurs, échelles) suivent. Une marque ne peut ni ajouter ni retirer de couche.</p>117 <div className="kv" style={{ gridTemplateColumns: 'minmax(120px, 170px) 1fr auto' }}>118 {Object.entries(brand.palette ?? {}).map(([k, v]) => [119 <label key={k + 'l'} className="mono">{k}</label>,120 <div key={k}><ColorField label={`marque ${k}`} value={v} palette={merged} against={k.endsWith('-ink') ? resolveColor(`@${k.replace(/-ink$/, '')}`, merged) : resolveColor('@land', merged)} onChange={(c) => set({ brand: { ...brand, palette: { ...brand.palette, [k]: c } } })} /></div>,121 <button key={k + 'x'} className="btn small" aria-label={`Retirer ${k}`} onClick={() => { const { [k]: _, ...rest } = brand.palette; set({ brand: { ...brand, palette: rest } }); }}>×</button>,122 ])}123 </div>124 <p className="row"><select aria-label="Couleur du thème à surcharger" value={pk} onChange={(e) => setPk(e.target.value)}><option value="">— couleur du thème —</option>{Object.keys(basePalette).filter((k) => !k.startsWith('_') && !(k in (brand.palette ?? {}))).map((k) => <option key={k}>{k}</option>)}</select>125 <button className="btn small" disabled={!pk} onClick={() => { set({ brand: { ...brand, palette: { ...(brand.palette ?? {}), [pk]: basePalette[pk] } } }); setPk(''); }}>Surcharger</button></p>126 </fieldset>127 <fieldset><legend>Marque — marqueurs</legend>128 <ObjEditor value={brand.markers ?? {}} palette={merged} path="markers" onChange={(v) => set({ brand: { ...brand, markers: v } })} />129 <p className="small muted">Document complet (fusion profonde avec <code>markers</code> du thème) :</p>130 <JsonInput label="marque markers (JSON)" value={brand.markers ?? {}} onChange={(v) => set({ brand: { ...brand, markers: v } })} />131 <p className="small muted">Peinture surchargée par couche (<code>{'{ "id de couche": { … } }'}</code>) :</p>132 <JsonInput label="marque layers (JSON)" value={brand.layers ?? {}} onChange={(v) => set({ brand: { ...brand, layers: v } })} />133 </fieldset>134 <fieldset><legend>Couches du fond</legend>135 <div className="row">{meta.layerSwitches.map((l) => <label key={l} className="c"><input type="checkbox" checked={cfg.layers[l] !== false} onChange={(e) => set({ layers: { ...cfg.layers, [l]: e.target.checked } })} /> {l}</label>)}</div>136 <p className="small muted">Une couche décochée est retirée du document de thème servi à cette application.</p>137 </fieldset>138 <fieldset><legend>Limites de zoom</legend>139 <label className="c">minimum <Num label="zoom minimum" value={cfg.zoom.min} step={0.5} min={0} max={20} onChange={(v) => set({ zoom: { ...cfg.zoom, min: v } })} /></label>{' '}140 <label className="c">maximum <Num label="zoom maximum" value={cfg.zoom.max} step={0.5} min={0} max={20} onChange={(v) => set({ zoom: { ...cfg.zoom, max: v } })} /></label>141 </fieldset>142 <fieldset><legend>Drapeaux de fonctionnalités</legend>143 <div className="row">{Object.keys(cfg.flags).sort().map((f) => <label key={f} className="c"><input type="checkbox" checked={cfg.flags[f]} onChange={(e) => set({ flags: { ...cfg.flags, [f]: e.target.checked } })} /> {f}</label>)}</div>144 <p className="row"><input type="text" placeholder="nouveauDrapeau" aria-label="Nom du nouveau drapeau" value={flag} onChange={(e) => setFlag(e.target.value)} /><button className="btn small" disabled={!/^[a-z][a-zA-Z0-9]{1,30}$/.test(flag) || flag in cfg.flags} onClick={() => { set({ flags: { ...cfg.flags, [flag]: false } }); setFlag(''); }}>Ajouter</button></p>145 </fieldset>146 <div className="sticky-actions row">147 <input type="text" placeholder="Note de révision" aria-label="Note de révision" value={note} onChange={(e) => setNote(e.target.value)} style={{ flex: 1, minWidth: 180 }} />148 <button className="btn primary" data-testid="save-app" disabled={!dirty} onClick={save}>Enregistrer et mettre en service</button>149 </div>150 <h2>Révisions</h2>151 <div className="table-wrap" style={{ maxHeight: 260, overflowY: 'auto' }}>152 <table><thead><tr><th>Rév.</th><th>Date</th><th>Auteur</th><th>Note</th><th></th></tr></thead>153 <tbody>{current.revisions.map((r: any, i: number) => (154 <tr key={r.rev}><td>{r.rev} {i === 0 ? <span className="tag ok">en service</span> : null}</td><td>{fmtDate(r.created_at)}</td><td>{r.author_name}</td><td>{r.note}</td>155 <td>{i > 0 ? <button className="btn small" onClick={async () => { const x = await api.get(`/api/apps/${app}/revisions/${r.rev}`); setCfg(x.config); setDirty(true); setMsg(null); }}>Reprendre</button> : null}</td></tr>156 ))}</tbody></table>157 </div>158 </div>159 {themeDoc ? <Preview key={app} doc={themeDoc} presets={meta.presets} apps={[app]} sdkVersions={[]} brandFor={brandFor} initialApp={app} /> : null}160 </div>161 </>162 );163}164