@tacoshell/shell 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/LICENSE +28 -0
  2. package/README.md +6 -2
  3. package/package.json +40 -4
  4. package/src/background.ts +41 -0
  5. package/src/core/bus.ts +210 -0
  6. package/src/core/cards.ts +33 -0
  7. package/src/core/contrib.ts +70 -0
  8. package/src/core/cron.ts +63 -0
  9. package/src/core/cronfriendly.ts +70 -0
  10. package/src/core/csv.ts +36 -0
  11. package/src/core/csvfeature.ts +57 -0
  12. package/src/core/datasets.ts +367 -0
  13. package/src/core/domshot.ts +81 -0
  14. package/src/core/guards.ts +36 -0
  15. package/src/core/hosts.ts +15 -0
  16. package/src/core/hotkeys.ts +44 -0
  17. package/src/core/indicators.ts +62 -0
  18. package/src/core/jobs.ts +37 -0
  19. package/src/core/localdata.ts +88 -0
  20. package/src/core/log.ts +91 -0
  21. package/src/core/markdown.ts +57 -0
  22. package/src/core/nav.ts +105 -0
  23. package/src/core/notifyrules.ts +31 -0
  24. package/src/core/page.ts +91 -0
  25. package/src/core/prefs.ts +119 -0
  26. package/src/core/router.ts +78 -0
  27. package/src/core/search.ts +65 -0
  28. package/src/core/services.ts +178 -0
  29. package/src/core/sessions.ts +93 -0
  30. package/src/core/startpage.ts +28 -0
  31. package/src/core/storage.ts +54 -0
  32. package/src/core/systemtools.ts +85 -0
  33. package/src/core/tabfit.ts +30 -0
  34. package/src/core/templates.ts +48 -0
  35. package/src/core/text.ts +6 -0
  36. package/src/core/toasts.ts +13 -0
  37. package/src/core/vault.ts +208 -0
  38. package/src/env.d.ts +2 -0
  39. package/src/index.ts +58 -0
  40. package/src/styles.css +391 -0
  41. package/src/types.ts +133 -0
  42. package/src/ui/ActionModal.tsx +22 -0
  43. package/src/ui/App.tsx +241 -0
  44. package/src/ui/ClearableInput.tsx +23 -0
  45. package/src/ui/CsvFeature.tsx +151 -0
  46. package/src/ui/Icon.tsx +8 -0
  47. package/src/ui/ItemFeature.tsx +39 -0
  48. package/src/ui/Markdown.tsx +24 -0
  49. package/src/ui/Rail.tsx +135 -0
  50. package/src/ui/RelatedMenu.tsx +57 -0
  51. package/src/ui/Search.tsx +111 -0
  52. package/src/ui/Sessions.tsx +76 -0
  53. package/src/ui/SidePanel.tsx +150 -0
  54. package/src/ui/TabBar.tsx +56 -0
  55. package/src/ui/ViewHost.tsx +142 -0
  56. package/src/ui/hooks.ts +28 -0
  57. package/src/ui/settings/Datasets.tsx +172 -0
  58. package/src/ui/settings/ReleaseNotes.tsx +96 -0
  59. package/src/ui/settings/ScheduleEditor.tsx +57 -0
  60. package/src/ui/settings/Settings.tsx +339 -0
  61. package/src/ui/settings/SettingsTabs.tsx +63 -0
  62. package/src/ui/settings/Templates.tsx +52 -0
  63. package/src/ui/useContrib.ts +36 -0
@@ -0,0 +1,339 @@
1
+ import { useRef, useState } from 'react';
2
+ import { clash, comboOf, effective, formatCombo, FRAMEWORK_HOTKEYS, type HotkeyDef } from '../../core/hotkeys.ts';
3
+ import { clearAll, collections, download, exportSetup, importSetup } from '../../core/localdata.ts';
4
+ import * as log from '../../core/log.ts';
5
+ import { settings, updateSettings } from '../../core/prefs.ts';
6
+ import { href } from '../../core/router.ts';
7
+ import * as services from '../../core/services.ts';
8
+ import { toast } from '../../core/toasts.ts';
9
+ import * as vault from '../../core/vault.ts';
10
+ import { appDefaultOf, START_AUTO, startHash } from '../../core/startpage.ts';
11
+ import { firstFeatured, buildNav, pageTitle, hasReports } from '../../core/nav.ts';
12
+ import { serviceKey, viewKey, type AuthMode, type RegistryService, type RegistryView } from '../../types.ts';
13
+ import { useShell, useStore } from '../hooks.ts';
14
+ import { Markdown } from '../Markdown.tsx';
15
+
16
+ const MODE_LABEL: Record<AuthMode, string> = { session: 'Browser session', apikey: 'API key', basic: 'HTTP Basic', none: 'No sign-in', oauth: 'OAuth (PKCE)' };
17
+ const vaultStore = { get: vault.status, subscribe: (fn: () => void) => vault.subscribe(fn) };
18
+
19
+ export function GettingStarted() {
20
+ const { registry } = useShell();
21
+ const status = useStore(vaultStore);
22
+ const [pass, setPass] = useState('');
23
+ const [again, setAgain] = useState('');
24
+ const [busy, setBusy] = useState(false);
25
+ const min = registry.settings.vault.minPassphraseLength;
26
+ const create = async () => {
27
+ if (pass !== again) return toast("The passphrases don't match.", 'error');
28
+ setBusy(true);
29
+ try { await vault.create(pass, { minLength: min, iterations: registry.settings.vault.kdf.iterations }); log.add('info', 'Vault created', undefined, 'Settings'); toast('Vault created.'); }
30
+ catch (e) { toast((e as Error).message, 'error'); }
31
+ finally { setBusy(false); }
32
+ };
33
+ return (
34
+ <div className="page">
35
+ <h1>Getting Started</h1>
36
+ <div className="card">
37
+ <h2>1 · Create the vault</h2>
38
+ {status === 'uninitialized' ? (
39
+ <>
40
+ <p className="muted">The vault encrypts every token and password on this computer. There is no recovery if you forget the passphrase.</p>
41
+ <div className="form-row"><input type="password" placeholder={`Passphrase (at least ${min} characters)`} value={pass} onChange={(e) => setPass(e.target.value)} /></div>
42
+ <div className="form-row"><input type="password" placeholder="Repeat passphrase" value={again} onChange={(e) => setAgain(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && void create()} /></div>
43
+ <button className="primary" disabled={busy || !pass} onClick={() => void create()}>{busy ? 'Creating…' : 'Create vault'}</button>
44
+ </>
45
+ ) : <p>✓ The vault exists ({status}).</p>}
46
+ </div>
47
+ <div className="card">
48
+ <h2>2 · Set up services</h2>
49
+ <p className="muted">Open <a href={href.settings('services')}>Settings → Services</a> and fill in each service you use.</p>
50
+ </div>
51
+ {registry.gettingStartedText && <div className="card"><Markdown text={registry.gettingStartedText} /></div>}
52
+ </div>
53
+ );
54
+ }
55
+
56
+ function statusOf(s: RegistryService) {
57
+ const st = services.stateOf(s);
58
+ if (!st.enabled) return { cls: 'off', text: 'Off' };
59
+ if (!services.isConfigured(s)) return { cls: 'warn', text: 'Not set up' };
60
+ if (st.lastTest && !st.lastTest.ok) return { cls: 'bad', text: 'Test failed' };
61
+ if (st.lastTest?.status === 'warn') return { cls: 'warn', text: 'Warning' };
62
+ return { cls: 'ok', text: st.lastTest?.ok ? 'Connected' : 'Set up' };
63
+ }
64
+
65
+ /** Settings → Services: uniform tiles; each opens the service's own page (ADR-032). */
66
+ export function ServicesList() {
67
+ const { registry } = useShell();
68
+ useStore(services.states);
69
+ useStore(vaultStore);
70
+ return (
71
+ <div className="page">
72
+ <h1>Services</h1>
73
+ {!registry.services.length && <p className="muted">This app has no services yet. Add one with <code>taco-cli add component --type=service</code>.</p>}
74
+ <div className="tiles">
75
+ {registry.services.map((s) => { const st = statusOf(s); return (
76
+ <a key={serviceKey(s)} className="tile" href={href.settings('services', s.type, s.name)}>
77
+ <strong>{s.label}</strong><span className="muted small">{serviceKey(s)} · {s.module}</span><span className={`pill ${st.cls}`}>{st.text}</span>
78
+ </a>
79
+ ); })}
80
+ </div>
81
+ </div>
82
+ );
83
+ }
84
+
85
+ /** Level 3: Settings → Services → <service>, generated from the declaration (ADR-032). */
86
+ export function ServicePage({ type, name }: { type: string; name: string }) {
87
+ const { registry } = useShell();
88
+ useStore(services.states);
89
+ useStore(vaultStore);
90
+ const s = services.find(type, name);
91
+ const [busy, setBusy] = useState(false);
92
+ // What the user has typed since the last Save; nothing is stored until Save (secrets go to the vault, the rest to the service's config).
93
+ const [draft, setDraft] = useState<Record<string, string>>({});
94
+ if (!s) return <div className="page"><h1>Not found</h1><p className="muted">No service {type}/{name} in this app.</p></div>;
95
+ const st = services.stateOf(s);
96
+ const status = statusOf(s);
97
+ const fields = services.fieldsFor(s, st.mode);
98
+ const val = (f: (typeof fields)[number]) => draft[f.key] ?? (f.secret ? '' : st.config[f.key] ?? '');
99
+ const dirty = fields.some((f) => f.key in draft && (f.secret ? draft[f.key] !== '' : draft[f.key].trim() !== (st.config[f.key] ?? '')));
100
+ const save = async () => {
101
+ const config = { ...services.stateOf(s).config };
102
+ for (const f of fields) {
103
+ if (!(f.key in draft)) continue;
104
+ if (f.secret) { if (draft[f.key]) await vault.put(services.secretId(s, f.key), draft[f.key]); } else config[f.key] = draft[f.key].trim();
105
+ }
106
+ // A new configuration hasn't been tested yet.
107
+ await services.update(s, { config, lastTest: undefined });
108
+ setDraft({});
109
+ toast(`${s.label} settings saved.`);
110
+ };
111
+ const run = async (what: () => Promise<unknown>) => { setBusy(true); try { await what(); } catch (e) { toast((e as Error).message, 'error'); } finally { setBusy(false); } };
112
+ return (
113
+ <div className="page">
114
+ <p className="crumbs"><a href={href.settings('services')}>Services</a> › {s.label}</p>
115
+ <h1>{s.label} <span className={`pill ${status.cls}`}>{status.text}</span></h1>
116
+ <p className="muted">{serviceKey(s)} · from {s.module} · hosts: {s.hosts.join(', ') || 'none'}</p>
117
+ <div className="card">
118
+ <div className="form-row"><label>Enabled</label><input type="checkbox" checked={st.enabled} onChange={(e) => void services.update(s, { enabled: e.target.checked })} /></div>
119
+ {s.auth.length > 1 && (
120
+ <div className="form-row"><label>Sign-in</label>
121
+ <div className="segmented">{s.auth.map((m) => <button key={m} className={st.mode === m ? 'on' : ''} onClick={() => void services.update(s, { mode: m })}>{MODE_LABEL[m]}</button>)}</div>
122
+ </div>
123
+ )}
124
+ {fields.map((f) => (
125
+ <div className="form-row" key={f.key} data-field={f.key}>
126
+ <label>{f.label ?? f.key}{f.required !== false && <span className="req" title="Required"> *</span>}</label>
127
+ <input
128
+ type={f.secret ? 'password' : 'text'} autoComplete="off" value={val(f)} disabled={busy}
129
+ placeholder={f.secret ? (vault.has(services.secretId(s, f.key)) ? '•••• saved (type to replace)' : 'Not set') : f.default !== undefined ? `default: ${f.default}` : f.placeholder}
130
+ onChange={(e) => setDraft({ ...draft, [f.key]: e.target.value })} />
131
+ {f.secret && vault.has(services.secretId(s, f.key)) && !(f.key in draft) && <span className="muted small">stored encrypted</span>}
132
+ {f.help && <span className="muted small field-help">{f.help}</span>}
133
+ </div>
134
+ ))}
135
+ {st.mode === 'session' && (
136
+ <>
137
+ <p className="muted small">Uses your signed-in browser session for {s.hosts.join(', ')}. Sign in there first.</p>
138
+ <div className="form-row"><label>Show in Sessions</label><input type="checkbox" checked={!st.hideFromSessions} onChange={(e) => void services.update(s, { hideFromSessions: !e.target.checked })} />
139
+ <span className="muted small">The header's Sessions menu lists this service and warns when its session is missing. Hide it once it is connected and you don't need the reminder.</span></div>
140
+ </>
141
+ )}
142
+ {st.mode === 'oauth' && (
143
+ <div className="oauth">
144
+ <div className="form-row"><label>Redirect URL</label><code className="copy">{services.redirectUrl(s, registry.app.extensionId)}</code></div>
145
+ <p className="muted small">Register this exact URL with the provider as a <strong>public</strong> client (no secret), then Connect.</p>
146
+ <button disabled={busy} onClick={() => void run(() => services.connectOAuth(s))}>{vault.has(services.secretId(s, 'accessToken')) ? 'Reconnect' : 'Connect'}</button>
147
+ </div>
148
+ )}
149
+ <div className="actions">
150
+ <button className={dirty ? 'primary' : ''} disabled={busy || !dirty} onClick={() => void run(save)}>Save</button>
151
+ <button className={dirty ? '' : 'primary'} disabled={busy || !st.enabled || dirty || !services.isConfigured(s)} title={dirty ? 'Save your changes first' : !services.isConfigured(s) ? 'Fill in the required fields and Save first' : undefined}
152
+ onClick={() => void run(async () => { const r = await services.test(s); toast(r.detail, r.ok ? 'info' : 'error', r.status === 'warn' ? 'Warning' : undefined); })}>Test</button>
153
+ {dirty && <span className="muted small">Unsaved changes</span>}
154
+ {st.lastTest && !dirty && <span className={`muted small test-${st.lastTest.status ?? (st.lastTest.ok ? 'ok' : 'error')}`} data-test-status={st.lastTest.status ?? (st.lastTest.ok ? 'ok' : 'error')}>Last test {new Date(st.lastTest.at).toLocaleString()}: {st.lastTest.detail}</span>}
155
+ </div>
156
+ </div>
157
+ <div className="card"><h2>How to set it up</h2><Markdown text={s.howToText} /></div>
158
+ </div>
159
+ );
160
+ }
161
+
162
+ const Section = ({ title, children, intro }: { title: string; intro?: string; children: React.ReactNode }) => (
163
+ <div className="card"><h2>{title}</h2>{intro && <p className="muted small">{intro}</p>}{children}</div>
164
+ );
165
+
166
+ function HotkeyRow({ def }: { def: HotkeyDef }) {
167
+ const cfg = useStore(settings);
168
+ const [recording, setRecording] = useState(false);
169
+ const combo = effective(def, cfg.hotkeys.map);
170
+ const save = (next: string) => void updateSettings({ hotkeys: { ...cfg.hotkeys, map: { ...cfg.hotkeys.map, [def.id]: next } } });
171
+ const record = (e: React.KeyboardEvent) => {
172
+ e.preventDefault();
173
+ if (e.key === 'Escape') return setRecording(false);
174
+ const c = comboOf(e.nativeEvent);
175
+ if (!c) return;
176
+ const other = clash(def.id, c, cfg.hotkeys.map);
177
+ if (other) { toast(`${formatCombo(c)} is already "${other.label}".`, 'error'); return; }
178
+ save(c);
179
+ setRecording(false);
180
+ };
181
+ return (
182
+ <tr>
183
+ <td>{def.label}</td>
184
+ <td>{recording ? <input autoFocus className="hotkey-rec" placeholder="Press keys… (Esc cancels)" onKeyDown={record} onBlur={() => setRecording(false)} readOnly /> : <kbd>{formatCombo(combo)}</kbd>}</td>
185
+ <td><button onClick={() => setRecording(true)}>Change</button> <button onClick={() => save('')}>None</button> {def.id in cfg.hotkeys.map && <button onClick={() => { const { [def.id]: _, ...rest } = cfg.hotkeys.map; void updateSettings({ hotkeys: { ...cfg.hotkeys, map: rest } }); }}>Default ({formatCombo(def.default)})</button>}</td>
186
+ </tr>
187
+ );
188
+ }
189
+
190
+ /** Settings → Configuration: the user's platform preferences (from v2 Settings › User Configuration). */
191
+ /** What a start-page value is called in Settings: "Auto", "Home", "Reports" or a view's page title. */
192
+ function startLabel(reg: ReturnType<typeof useShell>['registry'], value: string): string {
193
+ if (value === START_AUTO) return 'Auto (the first Featured action)';
194
+ if (value === 'home') return 'Home';
195
+ if (value === 'reports') return 'Reports';
196
+ const v = reg.views.find((x) => viewKey(x) === value);
197
+ return v ? pageTitle(reg, v) : `${value} (no longer in this app)`;
198
+ }
199
+
200
+ /** Settings → Configuration → Start page (ADR-064): the developer's default is in taco.json; the user may pick another page or go back to the app's default. */
201
+ function StartPage() {
202
+ const { registry } = useShell();
203
+ const cfg = useStore(settings);
204
+ const appDefault = appDefaultOf(registry);
205
+ const nav = buildNav(registry, () => true);
206
+ const byBucket = (label: string, views: RegistryView[]) => views.length ? <optgroup key={label} label={label}>{views.map((v) => <option key={viewKey(v)} value={viewKey(v)}>{pageTitle(registry, v)}</option>)}</optgroup> : null;
207
+ const home = registry.views.filter((v) => (v.nav.section ?? 'home') === 'home');
208
+ const opens = startHash(registry, firstFeatured(nav), cfg.startPage, appDefault);
209
+ const where = (() => { const r = opens.match(/^#\/v\/([^/]+)\/([^/]+)$/); const v = r && registry.views.find((x) => x.module === decodeURIComponent(r[1]) && x.name === decodeURIComponent(r[2])); return v ? pageTitle(registry, v) : opens === '#/reports' ? 'Reports' : 'Home'; })();
210
+ return (
211
+ <Section title="Start page" intro="The page the app opens on (after the vault is unlocked). The app ships a default; choose another here, or go back to the app's default.">
212
+ <div className="form-row"><label>Open on</label>
213
+ <select value={cfg.startPage ?? ''} onChange={(e) => void updateSettings({ startPage: e.target.value || null })}>
214
+ <option value="">App default: {startLabel(registry, appDefault)}</option>
215
+ <option value={START_AUTO}>{startLabel(registry, START_AUTO)}</option>
216
+ <option value="home">Home</option>
217
+ {hasReports(nav) && <option value="reports">Reports</option>}
218
+ {byBucket('Featured actions', home.filter((v) => v.nav.bucket === 'featured'))}
219
+ {byBucket('Tools', home.filter((v) => v.nav.bucket === 'tools'))}
220
+ {byBucket('Services', home.filter((v) => v.nav.bucket === 'services'))}
221
+ {byBucket('Reports', registry.views.filter((v) => (v.nav.section ?? 'home') === 'reports'))}
222
+ </select>
223
+ {cfg.startPage !== null && <button onClick={() => void updateSettings({ startPage: null })}>Use the app default</button>}
224
+ </div>
225
+ <p className="muted small">Opens on: <strong>{where}</strong>{cfg.startPage === null ? ' (the app default)' : ' (your choice)'}. Until you create a vault, the app always opens on Getting Started.</p>
226
+ </Section>
227
+ );
228
+ }
229
+
230
+ export function Configuration() {
231
+ const { registry } = useShell();
232
+ const cfg = useStore(settings);
233
+ const n = cfg.notifications;
234
+ const setN = (patch: Partial<typeof n>) => void updateSettings({ notifications: { ...n, ...patch } });
235
+ const setItem = (key: string, on: boolean) => setN({ items: { ...n.items, [key]: on } });
236
+ const test = () => {
237
+ if (typeof chrome !== 'undefined' && chrome.notifications?.create) chrome.notifications.create(`taco:test:${Date.now()}`, { type: 'basic', iconUrl: 'icons/icon-128.png', title: registry.app.displayName, message: 'This is how notifications look.', requireInteraction: n.sticky });
238
+ toast('This is how notifications look.', 'info', 'Test notification');
239
+ };
240
+ return (
241
+ <div className="page">
242
+ <h1>Configuration</h1>
243
+ <Section title="Appearance">
244
+ <div className="form-row"><label>Color theme</label>
245
+ <div className="segmented">{(['dark', 'light', 'system'] as const).map((t) => <button key={t} className={cfg.theme === t ? 'on' : ''} onClick={() => void updateSettings({ theme: t })}>{t === 'dark' ? <><i className="fa-solid fa-moon" /> Dark</> : t === 'light' ? <><i className="fa-solid fa-sun" /> Light</> : <><i className="fa-solid fa-circle-half-stroke" /> System</>}</button>)}</div>
246
+ </div>
247
+ <p className="muted small">Applies immediately. An app theme's colors apply on top of either mode.</p>
248
+ </Section>
249
+ <StartPage />
250
+ <Section title="Vault">
251
+ <div className="form-row"><label>Confirm before locking</label><input type="checkbox" checked={cfg.confirmLock} onChange={(e) => void updateSettings({ confirmLock: e.target.checked })} /><span className="muted small">Ask "Lock the vault?" when you press the Vault button in the header.</span></div>
252
+ </Section>
253
+ <Section title="Notifications" intro="Every notification is also listed in the Activity Log (Levels ▾ → Notifications only). Nothing notifies while the vault is locked.">
254
+ <div className="form-row"><label>All notifications</label><input type="checkbox" checked={n.enabled} onChange={(e) => setN({ enabled: e.target.checked })} /></div>
255
+ <div className="form-row"><label>Only when I'm away</label><input type="checkbox" checked={n.onlyWhenAway} onChange={(e) => setN({ onlyWhenAway: e.target.checked })} /><span className="muted small">Chrome notifications only while this app isn't the window in front (the in-app message always shows).</span></div>
256
+ <div className="form-row"><label>Quiet hours</label><input type="time" value={n.quietFrom} onChange={(e) => setN({ quietFrom: e.target.value })} /> to <input type="time" value={n.quietTo} onChange={(e) => setN({ quietTo: e.target.value })} />{(n.quietFrom || n.quietTo) && <button onClick={() => setN({ quietFrom: '', quietTo: '' })}>Clear</button>}</div>
257
+ <div className="form-row"><label>Keep on screen</label><input type="checkbox" checked={n.sticky} onChange={(e) => setN({ sticky: e.target.checked })} /><span className="muted small">Until dismissed (on macOS, Chrome's notification style must be "Alerts").</span></div>
258
+ <div className="form-row"><label>Toolbar badge</label><input type="checkbox" checked={n.badge} onChange={(e) => setN({ badge: e.target.checked })} /><span className="muted small">Count unseen notifications on the toolbar icon.</span></div>
259
+ <div className="actions"><button onClick={test}><i className="fa-regular fa-bell" /> Send a test notification</button></div>
260
+ <h3>Per notification</h3>
261
+ {!registry.notifications.length && <p className="muted small">No module declares notifications.</p>}
262
+ {registry.notifications.map((d) => { const key = `${d.module}/${d.id}`; return (
263
+ <div className="form-row" key={key}><label>{d.label}</label>
264
+ <input type="checkbox" disabled={!n.enabled} checked={n.items[key] ?? d.default === 'enabled'} onChange={(e) => setItem(key, e.target.checked)} />
265
+ <span className="muted small">{d.description ?? ''} ({d.module}, {d.delivery})</span></div>
266
+ ); })}
267
+ </Section>
268
+ <Section title="HotKeys" intro="⌘ is Ctrl outside macOS. Click Change, then press the new combination.">
269
+ <div className="form-row"><label>HotKeys on</label><input type="checkbox" checked={cfg.hotkeys.enabled} onChange={(e) => void updateSettings({ hotkeys: { ...cfg.hotkeys, enabled: e.target.checked } })} /></div>
270
+ <table className="keys"><tbody>{FRAMEWORK_HOTKEYS.map((d) => <HotkeyRow key={d.id} def={d} />)}</tbody></table>
271
+ </Section>
272
+ <Section title="Activity Log">
273
+ <p className="muted small">Levels shown by default are chosen in the log itself (Levels ▾); the choice is remembered here: {cfg.visibleLevels.join(', ') || 'none'}.</p>
274
+ </Section>
275
+ </div>
276
+ );
277
+ }
278
+
279
+ /** Settings → Vault & Data (from v2's Vault Configuration, Share setup, Manage Local Data, Clear All Local Data). */
280
+ export function VaultAndData() {
281
+ const { registry } = useShell();
282
+ const status = useStore(vaultStore);
283
+ const cfg = useStore(settings);
284
+ const [cur, setCur] = useState(''); const [next, setNext] = useState(''); const [again, setAgain] = useState('');
285
+ const [confirming, setConfirming] = useState<string | null>(null);
286
+ const [changing, setChanging] = useState(false);
287
+ const inv = vault.inventory();
288
+ const change = async () => {
289
+ if (next !== again) return toast("The new passphrases don't match.", 'error');
290
+ setChanging(true);
291
+ try { if (await vault.changePassphrase(cur, next, { minLength: registry.settings.vault.minPassphraseLength })) { toast('Passphrase changed.'); log.add('info', 'Vault passphrase changed', undefined, 'Settings'); setCur(''); setNext(''); setAgain(''); } else toast("The current passphrase isn't right.", 'error'); }
292
+ catch (e) { toast((e as Error).message, 'error'); }
293
+ finally { setChanging(false); }
294
+ };
295
+ const fileInput = useRef<HTMLInputElement>(null);
296
+ const importFile = async (f: File | undefined) => {
297
+ if (!f) return;
298
+ try { const applied = await importSetup(registry, JSON.parse(await f.text())); toast(`Imported: ${applied.join(', ') || 'nothing matched this app'}.`); }
299
+ catch (e) { toast(`Import failed: ${(e as Error).message}`, 'error'); }
300
+ if (fileInput.current) fileInput.current.value = '';
301
+ };
302
+ const danger = async (what: string, run: () => Promise<void>) => { if (confirming !== what) return setConfirming(what); setConfirming(null); await run(); };
303
+ return (
304
+ <div className="page">
305
+ <h1>Vault &amp; Data</h1>
306
+ <Section title="Vault" intro="AES-GCM 256 with a key derived from your passphrase (PBKDF2, 600,000 rounds). The passphrase is never stored; if you forget it, reset the vault and re-enter your secrets.">
307
+ <p>Status: <strong>{status}</strong> · {inv.secrets.length} secret(s) · {inv.moduleData.length} module data item(s)</p>
308
+ {inv.secrets.length > 0 && <p className="muted small">{inv.secrets.join(', ')}</p>}
309
+ <div className="form-row"><label>Lock after no activity</label>
310
+ <select value={cfg.idleLockMinutes} onChange={(e) => void updateSettings({ idleLockMinutes: Number(e.target.value) })}>{[5, 10, 15, 30, 60, 0].map((m) => <option key={m} value={m}>{m ? `${m} minutes` : 'Never'}</option>)}</select>
311
+ {status === 'unlocked' && <button disabled={changing} onClick={() => void vault.lock()}><i className="fa-solid fa-lock" /> Lock now</button>}
312
+ </div>
313
+ {status !== 'uninitialized' && (<>
314
+ <h3>Change passphrase</h3>
315
+ <div className="form-row"><input type="password" placeholder="Current passphrase" value={cur} onChange={(e) => setCur(e.target.value)} /></div>
316
+ <div className="form-row"><input type="password" placeholder="New passphrase" value={next} onChange={(e) => setNext(e.target.value)} /></div>
317
+ <div className="form-row"><input type="password" placeholder="Repeat new passphrase" value={again} onChange={(e) => setAgain(e.target.value)} /><button disabled={!cur || !next || changing} onClick={() => void change()}>{changing ? 'Changing…' : 'Change passphrase'}</button></div>
318
+ <div className="actions"><button className="danger" onClick={() => void danger('vault', async () => { await vault.destroy(); log.add('warn', 'Vault reset', undefined, 'Settings'); toast('Vault reset.'); })}>{confirming === 'vault' ? 'Click again to delete every secret and module data' : 'Reset vault…'}</button></div>
319
+ </>)}
320
+ </Section>
321
+ <Section title="Share setup" intro="Export your service settings (sign-in modes, site names, which services are on) and configuration for a teammate. Secrets are never exported.">
322
+ <div className="actions">
323
+ <button onClick={() => download(`${registry.app.name}-setup.json`, exportSetup(registry))}><i className="fa-solid fa-file-export" /> Export setup</button>
324
+ <button onClick={() => fileInput.current?.click()}><i className="fa-solid fa-file-import" /> Import setup</button>
325
+ <input ref={fileInput} type="file" accept="application/json" hidden onChange={(e) => void importFile(e.target.files?.[0])} />
326
+ </div>
327
+ </Section>
328
+ <Section title="Manage local data" intro="What this app keeps in this browser besides the vault. Clearing one collection leaves the others alone.">
329
+ <table className="keys"><tbody>{collections.map((c) => (
330
+ <tr key={c.id}><td><strong>{c.label}</strong><div className="muted small">{c.description}</div></td>
331
+ <td><button className={c.caution ? 'danger' : ''} onClick={() => void danger(c.id, async () => { await c.clear(); toast(`${c.label} cleared.`); log.add('info', `Local data cleared: ${c.label}`, undefined, 'Settings'); })}>{confirming === c.id ? 'Click again to clear' : 'Clear'}</button></td></tr>
332
+ ))}</tbody></table>
333
+ </Section>
334
+ <Section title="Clear all local data" intro="Removes everything this app stored in this browser: the vault (secrets and module data), service settings, configuration, favorites and the Activity Log. The app starts over at Getting Started.">
335
+ <button className="danger" onClick={() => void danger('all', async () => { await clearAll(); location.hash = '#/settings/getting-started'; location.reload(); })}>{confirming === 'all' ? 'Click again to clear everything' : 'Clear all local data…'}</button>
336
+ </Section>
337
+ </div>
338
+ );
339
+ }
@@ -0,0 +1,63 @@
1
+ import { useMemo, type ReactNode } from 'react';
2
+ import { createFramework } from '../../core/bus.ts';
3
+ import { unmet } from '../../core/nav.ts';
4
+ import { createPage } from '../../core/page.ts';
5
+ import * as services from '../../core/services.ts';
6
+ import type { RegistrySettingsTab, RegistryView } from '../../types.ts';
7
+ import { useShell, useStore } from '../hooks.ts';
8
+ import { Icon } from '../Icon.tsx';
9
+ import { Boundary } from '../ViewHost.tsx';
10
+
11
+ /** The address of a module's tab on a core Settings page: `#/settings/<page>/<module>/<tab>` with the pair as one encoded segment. */
12
+ export const tabHref = (page: string, t: Pick<RegistrySettingsTab, 'module' | 'name'>) => `#/settings/${page}/${encodeURIComponent(`${t.module}/${t.name}`)}`;
13
+ export const tabKey = (t: Pick<RegistrySettingsTab, 'module' | 'name'>) => `${t.module}/${t.name}`;
14
+
15
+ /** The tabs modules added to a core Settings page (ADR-072), in order; one whose services aren't usable stays out, like a panel. */
16
+ export function useContributedTabs(page: string): RegistrySettingsTab[] {
17
+ const { registry } = useShell();
18
+ useStore(services.states);
19
+ return (registry.settingsTabs ?? [])
20
+ .filter((t) => t.into === page && !unmet({ requires: t.requires } as unknown as RegistryView, services.isUsable).length)
21
+ .sort((a, b) => a.order - b.order || a.module.localeCompare(b.module) || a.name.localeCompare(b.name));
22
+ }
23
+
24
+ /** The tab strip above a Settings page's title (like a view's bar): the page's own tab(s) first, then the modules'. Not shown when there is only the page's own tab. */
25
+ export function TabStrip({ core, contributed, active, page, coreHref }: { core: { id: string; label: string; href: string }[]; contributed: RegistrySettingsTab[]; active: string; page: string; coreHref?: string }) {
26
+ void coreHref;
27
+ if (!contributed.length && core.length < 2) return null;
28
+ return (
29
+ <nav className="page-tabs settings-tabs" aria-label="Sections">
30
+ {core.map((c) => <a key={c.id} className={active === c.id ? 'on' : ''} href={c.href} data-tab={c.id}>{c.label}</a>)}
31
+ {contributed.map((t) => <a key={tabKey(t)} className={active === tabKey(t) ? 'on' : ''} href={tabHref(page, t)} data-tab={tabKey(t)}><Icon icon={t.icon} />{t.label}</a>)}
32
+ </nav>
33
+ );
34
+ }
35
+
36
+ /** A module's tab, rendered with the module's own framework (datasets, send, storage, log…). */
37
+ export function ContributedTab({ tab }: { tab: RegistrySettingsTab }) {
38
+ const input = useShell();
39
+ const page = useMemo(() => createPage(`${tab.module}/settings:${tab.name}`), [tab.module, tab.name]);
40
+ const framework = useMemo(() => createFramework(tab.module, page), [tab.module, page]);
41
+ const Tab = input.settingsTabs?.[tabKey(tab)];
42
+ return (
43
+ <div className="page" data-settings-tab={tabKey(tab)}>
44
+ <h1>{tab.label}</h1>
45
+ {Tab ? <Boundary name={`Settings tab ${tab.label} (${tab.module})`}><Tab framework={framework} /></Boundary> : <p className="muted">This tab has no component.</p>}
46
+ </div>
47
+ );
48
+ }
49
+
50
+ /**
51
+ * Wraps a core Settings page that modules may add tabs to. With no contributed tab nothing changes. With some, a strip appears above the page: its own tab
52
+ * ("Datasets") then each contributed one; the address picks the tab (`#/settings/datasets/<module>%2F<tab>`).
53
+ */
54
+ export function SettingsTabbed({ page, coreLabel, tab, children }: { page: string; coreLabel: string; tab?: string; children: ReactNode }) {
55
+ const contributed = useContributedTabs(page);
56
+ const current = contributed.find((t) => tabKey(t) === tab);
57
+ return (
58
+ <>
59
+ <TabStrip page={page} core={[{ id: 'core', label: coreLabel, href: `#/settings/${page}` }]} contributed={contributed} active={current ? tabKey(current) : 'core'} />
60
+ {current ? <ContributedTab tab={current} /> : children}
61
+ </>
62
+ );
63
+ }
@@ -0,0 +1,52 @@
1
+ import { useEffect, useState } from 'react';
2
+ import { href } from '../../core/router.ts';
3
+ import * as templates from '../../core/templates.ts';
4
+ import { toast } from '../../core/toasts.ts';
5
+ import * as vault from '../../core/vault.ts';
6
+ import type { RegistryTemplate } from '../../types.ts';
7
+ import { useShell, useStore } from '../hooks.ts';
8
+
9
+ const vaultStore = { get: vault.status, subscribe: (fn: () => void) => vault.subscribe(fn) };
10
+
11
+ function TemplateCard({ t }: { t: RegistryTemplate }) {
12
+ const [cur, setCur] = useState<templates.Resolved | null>(null);
13
+ const [text, setText] = useState('');
14
+ const [busy, setBusy] = useState(false);
15
+ useEffect(() => { void templates.get(t).then((r) => { setCur(r); setText(r.value); }); }, [t]);
16
+ if (!cur) return <details className="card"><summary><strong>{t.label}</strong></summary></details>;
17
+ const err = templates.validateEdit(t, text);
18
+ const run = async (what: () => Promise<void>) => { setBusy(true); try { await what(); } catch (e) { toast((e as Error).message, 'error'); } finally { setBusy(false); } };
19
+ const save = () => run(async () => { await templates.save(t, text); setCur(await templates.get(t)); toast(`${t.label} saved`); });
20
+ const reset = () => run(async () => { await templates.reset(t); setCur({ value: t.value, edited: false }); setText(t.value); toast(`${t.label} reset to the default`); });
21
+ return (
22
+ <details className="card template">
23
+ <summary><strong>{t.label}</strong> <span className="muted small">{t.module}/{t.name}</span> <span className={`pill ${cur.edited ? 'warn' : ''}`}>{cur.edited ? 'Edited' : 'Default'}</span></summary>
24
+ {t.description && <p className="muted small">{t.description}</p>}
25
+ <p className="small"><span className="muted">Tokens:</span> {t.tokens.length ? t.tokens.map((k) => <code key={k} className="token">{'${' + k + '}'}</code>) : <span className="muted">none</span>}</p>
26
+ <textarea value={text} rows={Math.min(14, Math.max(3, text.split('\n').length + 1))} spellCheck onChange={(e) => setText(e.target.value)} />
27
+ {err && <p className="error small">{err}</p>}
28
+ <div className="actions">
29
+ <button className="primary" disabled={busy || !!err || text === cur.value} onClick={() => void save()}>Save</button>
30
+ {cur.edited && <button disabled={busy} onClick={() => void reset()}>Reset to default</button>}
31
+ {cur.edited && cur.updatedAt && <span className="muted small">edited {new Date(cur.updatedAt).toLocaleString()}</span>}
32
+ </div>
33
+ </details>
34
+ );
35
+ }
36
+
37
+ /** Settings → Templates (v2 FR-TPL-1): reword the developer-shipped texts. Edits are stored encrypted in the vault; nothing can be added or deleted. */
38
+ export function TemplatesPage() {
39
+ const { registry } = useShell();
40
+ const status = useStore(vaultStore);
41
+ const list = registry.templates ?? [];
42
+ return (
43
+ <div className="page">
44
+ <h1>Templates</h1>
45
+ <p className="muted">Templates are shipped with the app; change the wording here. Use only the <code>{'${tokens}'}</code> each one lists: you can re-use or leave them out, but not invent new ones.</p>
46
+ {!list.length && <p className="muted">No module in this app declares a template. Add one with <code>taco-cli add component --type=template</code>.</p>}
47
+ {status === 'uninitialized' && list.length > 0 && <div className="card">Create the vault first: <a href={href.settings('getting-started')}>Getting Started</a>.</div>}
48
+ {status === 'locked' && list.length > 0 && <div className="card">Unlock the vault to edit templates: your edits are stored encrypted inside it. <button className="primary" onClick={() => void vault.whenUnlocked()}><i className="fa-solid fa-lock-open" /> Unlock</button></div>}
49
+ {status === 'unlocked' && list.map((t) => <TemplateCard key={templates.idOf(t)} t={t} />)}
50
+ </div>
51
+ );
52
+ }
@@ -0,0 +1,36 @@
1
+ import { useEffect, useState } from 'react';
2
+ import { createFramework } from '../core/bus.ts';
3
+ import * as log from '../core/log.ts';
4
+ import { collect, type Collected, type ContribKind } from '../core/contrib.ts';
5
+ import { NO_CONTEXT, type Page } from '../core/page.ts';
6
+ import * as services from '../core/services.ts';
7
+ import { unmet } from '../core/nav.ts';
8
+ import type { RegistryView } from '../types.ts';
9
+ import { useShell, useStore } from './hooks.ts';
10
+
11
+ const noExposed = { get: () => NO_CONTEXT, subscribe: () => () => {} };
12
+
13
+ /**
14
+ * What other features contribute (Related or Actions) for the page being viewed. Starts as soon as the page opens and again whenever the feature
15
+ * changes what it exposes; the list fills in as contributors answer.
16
+ */
17
+ export function useContributions(kind: ContribKind, page: Page | null | undefined) {
18
+ const { registry, handlers } = useShell();
19
+ useStore(services.states);
20
+ const exposed = useStore(page?.exposed ?? noExposed);
21
+ const [items, setItems] = useState<Collected[]>([]);
22
+ const key = JSON.stringify(exposed);
23
+ useEffect(() => {
24
+ setItems([]);
25
+ const current = page ? registry.views.find((v) => `${v.module}/${v.name}` === page.key) : undefined;
26
+ if (!page || !current) return;
27
+ let stop = false;
28
+ void collect({
29
+ reg: registry, kind, current, context: exposed, handlers: handlers ?? {}, cancelled: () => stop, onItems: (all) => { if (!stop) setItems(all); },
30
+ usable: (v: RegistryView) => !unmet(v, services.isUsable).length,
31
+ env: (v: RegistryView) => ({ framework: createFramework(v.module, undefined, v.name), log: log.logger(`${v.label} › contribute`) }),
32
+ });
33
+ return () => { stop = true; };
34
+ }, [page, kind, key, registry]);
35
+ return { items, exposed };
36
+ }