@tacoshell/shell 0.0.0-stage → 0.1.0

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 (52) 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 +186 -0
  6. package/src/core/cards.ts +33 -0
  7. package/src/core/cron.ts +63 -0
  8. package/src/core/cronfriendly.ts +70 -0
  9. package/src/core/csv.ts +36 -0
  10. package/src/core/datasets.ts +276 -0
  11. package/src/core/domshot.ts +81 -0
  12. package/src/core/guards.ts +36 -0
  13. package/src/core/hosts.ts +15 -0
  14. package/src/core/hotkeys.ts +44 -0
  15. package/src/core/localdata.ts +88 -0
  16. package/src/core/log.ts +91 -0
  17. package/src/core/markdown.ts +57 -0
  18. package/src/core/nav.ts +102 -0
  19. package/src/core/notifyrules.ts +31 -0
  20. package/src/core/page.ts +81 -0
  21. package/src/core/prefs.ts +114 -0
  22. package/src/core/router.ts +78 -0
  23. package/src/core/search.ts +65 -0
  24. package/src/core/services.ts +161 -0
  25. package/src/core/sessions.ts +72 -0
  26. package/src/core/startpage.ts +28 -0
  27. package/src/core/storage.ts +54 -0
  28. package/src/core/systemtools.ts +85 -0
  29. package/src/core/tabfit.ts +30 -0
  30. package/src/core/templates.ts +48 -0
  31. package/src/core/toasts.ts +13 -0
  32. package/src/core/vault.ts +208 -0
  33. package/src/env.d.ts +2 -0
  34. package/src/index.ts +56 -0
  35. package/src/styles.css +288 -0
  36. package/src/types.ts +113 -0
  37. package/src/ui/App.tsx +229 -0
  38. package/src/ui/ClearableInput.tsx +23 -0
  39. package/src/ui/Icon.tsx +8 -0
  40. package/src/ui/Markdown.tsx +24 -0
  41. package/src/ui/Rail.tsx +89 -0
  42. package/src/ui/Search.tsx +111 -0
  43. package/src/ui/Sessions.tsx +72 -0
  44. package/src/ui/SidePanel.tsx +148 -0
  45. package/src/ui/TabBar.tsx +56 -0
  46. package/src/ui/ViewHost.tsx +122 -0
  47. package/src/ui/hooks.ts +21 -0
  48. package/src/ui/settings/Datasets.tsx +162 -0
  49. package/src/ui/settings/ReleaseNotes.tsx +19 -0
  50. package/src/ui/settings/ScheduleEditor.tsx +57 -0
  51. package/src/ui/settings/Settings.tsx +328 -0
  52. package/src/ui/settings/Templates.tsx +52 -0
@@ -0,0 +1,72 @@
1
+ import { useEffect, useRef, useState } from 'react';
2
+ import * as services from '../core/services.ts';
3
+ import * as sessions from '../core/sessions.ts';
4
+ import { href } from '../core/router.ts';
5
+ import { serviceKey, type Registry, type RegistryService } from '../types.ts';
6
+ import { Icon } from './Icon.tsx';
7
+ import { useStore } from './hooks.ts';
8
+
9
+ const RECHECK_MS = 5 * 60_000;
10
+
11
+ /**
12
+ * Header Sessions icon for "Current Session" services. Plain while every shown session is active; "Warning" yellow while one is missing.
13
+ * Its menu lists each such service: green = detected and active, yellow = missing. Hidden entirely when no service uses Current Session.
14
+ */
15
+ export function SessionsMenu({ registry }: { registry: Registry }) {
16
+ useStore(services.states);
17
+ const all = useStore(sessions.statuses);
18
+ const list = sessions.shown(registry);
19
+ const [open, setOpen] = useState(false);
20
+ const [busy, setBusy] = useState(false);
21
+ const box = useRef<HTMLDivElement>(null);
22
+ const key = sessions.sessionServices(registry).map((s) => serviceKey(s) + JSON.stringify(services.stateOf(s).config)).join('|'); // re-check when a service is added, switched or reconfigured
23
+
24
+ const recheck = async () => { setBusy(true); try { await sessions.checkAll(registry); } finally { setBusy(false); } };
25
+ // Check on start, when the services change (a mode switch, turned on / off), every few minutes, and when the user comes back to the app.
26
+ useEffect(() => {
27
+ void recheck();
28
+ const t = setInterval(() => void recheck(), RECHECK_MS);
29
+ const onFocus = () => void recheck();
30
+ addEventListener('focus', onFocus);
31
+ return () => { clearInterval(t); removeEventListener('focus', onFocus); };
32
+ }, [key]);
33
+ useEffect(() => {
34
+ const away = (e: MouseEvent) => { if (box.current && !box.current.contains(e.target as Node)) setOpen(false); };
35
+ addEventListener('mousedown', away);
36
+ return () => removeEventListener('mousedown', away);
37
+ }, []);
38
+ if (!sessions.sessionServices(registry).length) return null;
39
+
40
+ const level = sessions.worst(registry, all);
41
+ return (
42
+ <div className="sessions" ref={box}>
43
+ <button className={`bar-btn icon-only${level ? ` st-${level}` : ''}${open ? ' on' : ''}`} onClick={() => { setOpen(!open); if (!open) void recheck(); }} title="Sessions" aria-label="Sessions" aria-expanded={open}>
44
+ <i className="fa-solid fa-id-badge" />
45
+ </button>
46
+ {open && (
47
+ <div className="sessions-list" role="menu">
48
+ <div className="sessions-head"><strong>Current Sessions</strong>
49
+ <button className="bar-btn icon-only" onClick={() => void recheck()} disabled={busy} title="Check again" aria-label="Check sessions again"><i className={`fa-solid fa-rotate${busy ? ' fa-spin' : ''}`} /></button></div>
50
+ {!list.length && <p className="muted small">Every Current Session service is hidden from this menu (Settings → Services).</p>}
51
+ {list.map((s) => <SessionRow key={serviceKey(s)} s={s} st={all[serviceKey(s)]} onClose={() => setOpen(false)} />)}
52
+ </div>
53
+ )}
54
+ </div>
55
+ );
56
+ }
57
+
58
+ function SessionRow({ s, st, onClose }: { s: RegistryService; st?: sessions.SessionStatus; onClose: () => void }) {
59
+ const state = st?.state ?? 'checking';
60
+ const level = sessions.levelOf(s, st);
61
+ const req = sessions.REQUIREMENT_LABEL[s.sessionRequirement ?? 'recommended'];
62
+ const word = state === 'active' ? (st?.who ? `Active · ${st.who}` : 'Active') : state === 'missing' ? 'Missing' : 'Checking…';
63
+ const icon = level === 'bad' ? 'fa-circle-xmark' : level === 'warn' ? 'fa-triangle-exclamation' : 'fa-circle-check';
64
+ return (
65
+ <a className="session-row" href={href.settings('services', s.type, s.name)} onClick={onClose} title={`${req}${state === 'missing' && st?.detail ? `: ${st.detail}` : ''}`}>
66
+ <i className={level ? `fa-solid ${icon} sess-${level}` : 'fa-solid fa-circle-notch fa-spin muted'} />
67
+ <Icon icon={s.icon} />
68
+ <span className="session-name">{s.label} <span className="muted small">{req}</span></span>
69
+ <span className={`${level ? `sess-${level}` : 'muted'} small`}>{word}</span>
70
+ </a>
71
+ );
72
+ }
@@ -0,0 +1,148 @@
1
+ import { useEffect, useRef, useState } from 'react';
2
+ import type { LogLevel, Tool } from '@tacoshell/sdk';
3
+ import * as log from '../core/log.ts';
4
+ import { currentPage } from '../core/page.ts';
5
+ import { toast } from '../core/toasts.ts';
6
+ import { createStore, favorites, settings, sidePanel, toggleFavorite, togglePanel, updateSettings, pref, setPref } from '../core/prefs.ts';
7
+ import { useStore } from './hooks.ts';
8
+ import { ClearableInput } from './ClearableInput.tsx';
9
+ import { Icon } from './Icon.tsx';
10
+ import { TabBar } from './TabBar.tsx';
11
+ import { Markdown } from './Markdown.tsx';
12
+ import type { RegistryIcon } from '../types.ts';
13
+
14
+ const logStore = { get: log.getVersion, subscribe: log.subscribe };
15
+ /** Notification history is a filter on the Activity Log, not a separate UI (ADR-028). */
16
+ const onlyNotifications = createStore<boolean>(pref('log.onlyNotifications', false));
17
+ const setOnlyNotifications = (on: boolean) => { onlyNotifications.set(on); setPref('log.onlyNotifications', on); };
18
+
19
+ /** Text typed in the Activity Log's filter box (not remembered across reloads). */
20
+ const logFilter = createStore<string>('');
21
+ const rowMatches = (e: log.Entry, q: string) => !q || [e.message, e.level, e.source, e.tag].some((v) => v?.toLowerCase().includes(q));
22
+
23
+ // useSyncExternalStore needs a stable snapshot: one shared empty list, not a new [] per call.
24
+ const NO_TOOLS: Tool[] = [];
25
+ const noTools = { get: () => NO_TOOLS, subscribe: () => () => {} };
26
+
27
+ /** Tools ▾ (ADR-051, from v2 FR-TOOLS-1): shown only while the page has tools; cleared when the user navigates away. */
28
+ function ToolsMenu() {
29
+ const page = useStore(currentPage);
30
+ const tools = useStore(page?.tools ?? noTools);
31
+ const [open, setOpen] = useState(false);
32
+ if (!tools.length) return null;
33
+ const run = async (t: (typeof tools)[number]) => {
34
+ setOpen(false);
35
+ try { await t.run(); } catch (e) { log.add('error', `Tool ${t.label} failed: ${(e as Error).message}`); toast(`${t.label} failed: ${(e as Error).message}`, 'error'); }
36
+ };
37
+ return (
38
+ <div className="filter">
39
+ <button className={`bar-btn${open ? ' on' : ''}`} onClick={() => setOpen(!open)} aria-expanded={open}><i className="fa-solid fa-screwdriver-wrench" /> Tools ▾</button>
40
+ {open && <div className="filter-menu" onMouseLeave={() => setOpen(false)}>{tools.map((t) => <button key={t.id} className="menu-item" onClick={() => void run(t)}>{t.icon?.startsWith('fa-') ? <i className={t.icon} /> : t.icon ? `${t.icon} ` : null} {t.label}</button>)}</div>}
41
+ </div>
42
+ );
43
+ }
44
+
45
+ /**
46
+ * The 3rd-level bar (ADR-039): tabs anchored left (they mirror the Level-2 group; overflow goes to "More"), then, on the right, icon-only buttons:
47
+ * Refresh · Tools ▾ (when the page has any) · Favorite · Log · Help. Tooltips carry the names.
48
+ */
49
+ export function SubBar({ tabs, favoriteKey, hasHelp, favoriteOff, onRefresh }: { tabs?: { label: string; href: string; active: boolean; icon?: RegistryIcon }[]; favoriteKey?: string; hasHelp: boolean; /** The view turned Favorite off. */ favoriteOff?: boolean; /** Undefined = Refresh is unavailable here (not a view, or the view turned it off). */ onRefresh?: () => void }) {
50
+ useStore(logStore);
51
+ const panel = useStore(sidePanel);
52
+ const favs = useStore(favorites);
53
+ const level = log.indicator();
54
+ const isFav = !!favoriteKey && favs.includes(favoriteKey);
55
+ return (
56
+ <div className="subbar">
57
+ {(tabs ?? []).length > 1 ? <TabBar tabs={tabs!} /> : <div className="subbar-tabs" />}
58
+ <div className="subbar-actions">
59
+ <button className="bar-btn icon-only" onClick={onRefresh} disabled={!onRefresh} title={onRefresh ? 'Refresh' : 'Nothing to refresh here'} aria-label="Refresh"><i className="fa-solid fa-rotate" /></button>
60
+ <ToolsMenu />
61
+ {/* Favorite is shown on every page, and is active only on pages that can be starred (views that haven't turned it off). */}
62
+ <button className={`bar-btn icon-only${isFav ? ' on fav-on' : ''}`} onClick={() => favoriteKey && toggleFavorite(favoriteKey)} disabled={!favoriteKey} aria-label="Favorite" aria-pressed={isFav} title={favoriteKey ? 'Favorite' : favoriteOff ? 'Favorite is turned off for this page' : 'Only views can be favorites'}>
63
+ <i className={`${isFav ? 'fa-solid' : 'fa-regular'} fa-star`} />
64
+ </button>
65
+ <button className={`bar-btn icon-only${panel === 'log' ? ' on' : ''}${level ? ` sev-${level}` : ''}`} onClick={() => togglePanel('log')} title="Activity Log (⌘.)" aria-label="Activity Log"><i className="fa-regular fa-file-lines" /></button>
66
+ <button className={`bar-btn icon-only${panel === 'help' ? ' on' : ''}`} onClick={() => togglePanel('help')} disabled={!hasHelp} title="Help (⌘?)" aria-label="Help"><i className="fa-solid fa-life-ring" /></button>
67
+ </div>
68
+ </div>
69
+ );
70
+ }
71
+
72
+ function LevelFilter() {
73
+ const { visibleLevels } = useStore(settings);
74
+ const [open, setOpen] = useState(false);
75
+ const set = (levels: string[]) => void updateSettings({ visibleLevels: levels });
76
+ const onlyNotes = useStore(onlyNotifications);
77
+ const allOn = log.LEVELS.every((l) => visibleLevels.includes(l));
78
+ return (
79
+ <div className="filter">
80
+ <button className="bar-btn" onClick={() => setOpen(!open)}>Levels ▾</button>
81
+ {open && (
82
+ <div className="filter-menu" onMouseLeave={() => setOpen(false)}>
83
+ <div className="filter-row"><button onClick={() => set(allOn ? [] : [...log.LEVELS])}>{allOn ? 'Deselect all' : 'Select all'}</button></div>
84
+ {log.LEVELS.map((l) => (
85
+ <label key={l}><input type="checkbox" checked={visibleLevels.includes(l)} onChange={(e) => set(e.target.checked ? [...visibleLevels, l] : visibleLevels.filter((x) => x !== l))} /> <span className={`lvl lvl-${l}`}>{l}</span></label>
86
+ ))}
87
+ <label className="sep"><input type="checkbox" checked={onlyNotes} onChange={(e) => setOnlyNotifications(e.target.checked)} /> Notifications only</label>
88
+ </div>
89
+ )}
90
+ </div>
91
+ );
92
+ }
93
+
94
+ /** HH:MM:SS (24 h) for the left column; the full date and time are in the tooltip. */
95
+ const clock = (at: number) => new Date(at).toLocaleTimeString([], { hour12: false });
96
+
97
+ function LogPanel() {
98
+ useStore(logStore);
99
+ const { visibleLevels } = useStore(settings);
100
+ const onlyNotes = useStore(onlyNotifications);
101
+ useEffect(() => { log.setPanelOpen(true); return () => log.setPanelOpen(false); }, []);
102
+ const text = useStore(logFilter);
103
+ const q = text.trim().toLowerCase();
104
+ const rows = log.all();
105
+ return (
106
+ <>
107
+ <div className="panel-head"><ClearableInput wrapperClass="log-filter" placeholder="Filter" aria-label="Filter the Activity Log" value={text} onValue={(v) => logFilter.set(v)} /><LevelFilter /><button className="bar-btn" onClick={log.clear}>Clear</button></div>
108
+ <ol className="log-list">
109
+ {[...rows].reverse().map((e) => (
110
+ // Hidden rather than dropped, so turning a level on later shows earlier lines too (ADR-040).
111
+ <li key={e.id} hidden={!visibleLevels.includes(e.level as LogLevel) || (onlyNotes && e.tag !== 'notification') || !rowMatches(e, q)}>
112
+ <div className="log-head">
113
+ <time dateTime={new Date(e.at).toISOString()} title={new Date(e.at).toLocaleString()}>{clock(e.at)}</time>
114
+ <span className={`lvl lvl-${e.level}`}>{e.level}</span>
115
+ {e.tag === 'notification' && <span className="tag">notification</span>}
116
+ {e.source && <span className="src">{e.source}</span>}
117
+ </div>
118
+ <div className="msg">{e.message}</div>
119
+ {e.data !== undefined && <pre className="data">{JSON.stringify(e.data, null, 1)}</pre>}
120
+ </li>
121
+ ))}
122
+ </ol>
123
+ </>
124
+ );
125
+ }
126
+
127
+ /** Log and Help share one right-hand slot; each remembers its own width, 240–800 px (ADR-039). */
128
+ export function SidePanel({ helpText, helpTitle }: { helpText?: string; helpTitle: string }) {
129
+ const panel = useStore(sidePanel);
130
+ const [width, setWidth] = useState(() => pref(`side.width.${panel}`, 420));
131
+ const dragging = useRef(false);
132
+ useEffect(() => setWidth(pref(`side.width.${panel}`, 420)), [panel]);
133
+ if (!panel) return null;
134
+ const startDrag = (e: React.PointerEvent) => {
135
+ dragging.current = true;
136
+ const startX = e.clientX, startW = width;
137
+ const move = (ev: PointerEvent) => setWidth(Math.min(800, Math.max(240, startW + (startX - ev.clientX))));
138
+ const up = (ev: PointerEvent) => { dragging.current = false; setPref(`side.width.${panel}`, Math.min(800, Math.max(240, startW + (startX - ev.clientX)))); removeEventListener('pointermove', move); removeEventListener('pointerup', up); };
139
+ addEventListener('pointermove', move);
140
+ addEventListener('pointerup', up);
141
+ };
142
+ return (
143
+ <aside className="side" style={{ width }}>
144
+ <div className="side-grip" onPointerDown={startDrag} onDoubleClick={() => { setWidth(420); setPref(`side.width.${panel}`, 420); }} />
145
+ {panel === 'log' ? <LogPanel /> : (<><div className="panel-head"><strong>Help · {helpTitle}</strong></div><div className="help-body"><Markdown text={helpText} /></div></>)}
146
+ </aside>
147
+ );
148
+ }
@@ -0,0 +1,56 @@
1
+ import { useLayoutEffect, useRef, useState } from 'react';
2
+ import type { RegistryIcon } from '../types.ts';
3
+ import { fit, TAB_GUTTER } from '../core/tabfit.ts';
4
+ import { Icon } from './Icon.tsx';
5
+
6
+ export interface Tab { label: string; href: string; active: boolean; icon?: RegistryIcon }
7
+
8
+ /** The 3rd-level tabs, anchored left. They keep a 64 px gutter before the buttons on the right; whatever would overlap it goes in a "More" menu. */
9
+ export function TabBar({ tabs }: { tabs: Tab[] }) {
10
+ const box = useRef<HTMLDivElement>(null);
11
+ const measure = useRef<HTMLDivElement>(null);
12
+ const [layout, setLayout] = useState<{ shown: number[]; hidden: number[] }>({ shown: tabs.map((_, i) => i), hidden: [] });
13
+ const [open, setOpen] = useState(false);
14
+ const activeAt = tabs.findIndex((t) => t.active);
15
+ // The layout is measured after render, so for one render it can describe the PREVIOUS tab list (13 tabs → 4): ignore indices that no longer exist.
16
+ const shown = layout.shown.filter((i) => i < tabs.length);
17
+ const hidden = layout.hidden.filter((i) => i < tabs.length);
18
+ const sig = tabs.map((t) => `${t.label}|${t.active}`).join('/');
19
+
20
+ useLayoutEffect(() => {
21
+ const run = () => {
22
+ const m = measure.current, b = box.current;
23
+ if (!m || !b) return;
24
+ const kids = [...m.children] as HTMLElement[];
25
+ const widths = kids.slice(0, tabs.length).map((k) => k.offsetWidth);
26
+ const next = fit(widths, kids[tabs.length]?.offsetWidth ?? 70, b.clientWidth, activeAt);
27
+ setLayout((cur) => (cur.shown.join() === next.shown.join() && cur.hidden.join() === next.hidden.join() ? cur : next));
28
+ };
29
+ run();
30
+ const ro = new ResizeObserver(run);
31
+ if (box.current) ro.observe(box.current);
32
+ // The icon font may arrive after the first measure and change every tab's width: watch the measuring strip too, and re-measure when fonts are ready.
33
+ if (measure.current) ro.observe(measure.current);
34
+ void document.fonts?.ready.then(run);
35
+ return () => ro.disconnect();
36
+ }, [sig, activeAt, tabs.length]);
37
+
38
+ useLayoutEffect(() => { setOpen(false); }, [sig]);
39
+ const link = (t: Tab, cls: string) => <a key={t.href} href={t.href} className={`${cls}${t.active ? ' active' : ''}`} onClick={() => setOpen(false)}><Icon icon={t.icon} />{t.label}</a>;
40
+ return (
41
+ <div className="subbar-tabs" ref={box} style={{ marginRight: TAB_GUTTER }}>
42
+ {shown.map((i) => link(tabs[i], 'tab'))}
43
+ {hidden.length > 0 && (
44
+ <div className="tab-more">
45
+ <button className={`tab${hidden.includes(activeAt) ? ' active' : ''}`} onClick={() => setOpen(!open)} aria-expanded={open} aria-haspopup="menu" title={shown.length ? 'More' : tabs[activeAt]?.label}>{shown.length === 0 && activeAt >= 0 ? tabs[activeAt].label : 'More'} <i className="fa-solid fa-chevron-down" /></button>
46
+ {open && <div className="tab-more-menu" role="menu" onMouseLeave={() => setOpen(false)}>{hidden.map((i) => link(tabs[i], 'menu-link'))}</div>}
47
+ </div>
48
+ )}
49
+ {/* Off-screen copy used only to measure every tab (and More) at its natural width. */}
50
+ <div className="tabs-measure" ref={measure} aria-hidden="true">
51
+ {tabs.map((t) => <span key={t.href} className="tab"><Icon icon={t.icon} />{t.label}</span>)}
52
+ <span className="tab">More <i className="fa-solid fa-chevron-down" /></span>
53
+ </div>
54
+ </div>
55
+ );
56
+ }
@@ -0,0 +1,122 @@
1
+ import { Component, useEffect, useMemo, useState, type ReactNode } from 'react';
2
+ import { createFramework, setSlotRenderer } from '../core/bus.ts';
3
+ import * as log from '../core/log.ts';
4
+ import { unmet } from '../core/nav.ts';
5
+ import { createPage, currentPage, deliver, type Page } from '../core/page.ts';
6
+ import { systemToolsFor } from '../core/systemtools.ts';
7
+ import * as router from '../core/router.ts';
8
+ import * as services from '../core/services.ts';
9
+ import * as vault from '../core/vault.ts';
10
+ import * as cards from '../core/cards.ts';
11
+ import { pref, setPref } from '../core/prefs.ts';
12
+ import { viewKey, type RegistryCard, type RegistryPanel, type RegistryView } from '../types.ts';
13
+ import { Icon } from './Icon.tsx';
14
+ import { useShell, useStore, type ShellInput } from './hooks.ts';
15
+
16
+ class Boundary extends Component<{ name: string; quiet?: boolean; children: ReactNode }, { error?: Error }> {
17
+ state: { error?: Error } = {};
18
+ static getDerivedStateFromError(error: Error) { return { error }; }
19
+ componentDidCatch(error: Error) { log.add('error', `${this.props.name} crashed: ${error.message}`); }
20
+ render() {
21
+ if (!this.state.error) return this.props.children;
22
+ if (this.props.quiet) return <div className="card danger small">{this.props.name} crashed (details in the Activity Log).</div>;
23
+ return <div className="card danger"><strong>This view crashed.</strong><p className="muted">{this.state.error.message}</p><p className="muted">Details are in the Activity Log.</p></div>;
24
+ }
25
+ }
26
+
27
+ /** Panels other modules contributed to a slot of the page's view (ADR-053). Each gets its own module-scoped framework on the shared page. */
28
+ function SlotHost({ page, name }: { page: Page; name: string }) {
29
+ const input = useShell();
30
+ useStore(services.states);
31
+ const [module, view] = [page.key.slice(0, page.key.lastIndexOf('/')), page.key.slice(page.key.lastIndexOf('/') + 1)];
32
+ const panels = (input.registry.panels ?? []).filter((p) => p.into.module === module && p.into.view === view && p.into.slot === name);
33
+ return <div className="slot" data-slot={name}>{panels.map((p) => <PanelHost key={`${p.module}/${p.name}`} panel={p} page={page} input={input} slot={name} />)}</div>;
34
+ }
35
+
36
+ function PanelHost({ panel, page, input, slot }: { panel: RegistryPanel; page: Page; input: ShellInput; slot: string }) {
37
+ const framework = useMemo(() => createFramework(panel.module, page), [panel.module, page]);
38
+ const Panel = input.panels?.[`${panel.module}/${panel.name}`];
39
+ // A panel whose services aren't usable stays out of the page rather than showing a broken box.
40
+ if (!Panel || unmet({ ...panel, requires: panel.requires } as unknown as RegistryView, services.isUsable).length) return null;
41
+ return <Boundary name={`Panel ${panel.label} (${panel.module})`} quiet><Panel framework={framework} slot={slot} /></Boundary>;
42
+ }
43
+
44
+ /** One card: header (icon, label, collapse) and the module's component, given only the page-context entries it is wired to. */
45
+ function CardHost({ card, context, page, input }: { card: RegistryCard; context: Record<string, unknown>; page: Page; input: ShellInput }) {
46
+ const id = `${card.module}/${card.name}`;
47
+ const framework = useMemo(() => createFramework(card.module, page), [card.module, page]);
48
+ const [closed, setClosed] = useState(() => { const saved = pref<Record<string, boolean>>('cards.collapsed', {}); return id in saved ? saved[id] : card.collapsed; });
49
+ const Card = input.cards?.[id];
50
+ if (!Card) return null;
51
+ const toggle = () => { setClosed(!closed); setPref('cards.collapsed', { ...pref<Record<string, boolean>>('cards.collapsed', {}), [id]: !closed }); };
52
+ return (
53
+ <section className={`card-host${closed ? ' closed' : ''}`} data-card={id}>
54
+ <button className="card-head" onClick={toggle} aria-expanded={!closed}>
55
+ <i className={`fa-solid fa-chevron-${closed ? 'right' : 'down'} card-chev`} /><Icon icon={card.icon} /><strong>{card.label}</strong><span className="muted small">{card.module}</span>
56
+ </button>
57
+ {!closed && <div className="card-body"><Boundary name={`Card ${card.label} (${card.module})`} quiet><Card framework={framework} context={context} /></Boundary></div>}
58
+ </section>
59
+ );
60
+ }
61
+
62
+ /**
63
+ * Cards for the current page (ADR-062): every module's card whose wired context entries the page context has, shown under the view.
64
+ * It follows the page context live, so a card appears (or goes) when a component sets the entry with page.set. A view opts out with "cards": false.
65
+ */
66
+ function CardsRegion({ page, view }: { page: Page; view: RegistryView }) {
67
+ const input = useShell();
68
+ useStore(services.states);
69
+ const ctx = useStore(page.page);
70
+ if (view.cards === false) return null;
71
+ const list = cards.applicable(input.registry.cards ?? [], ctx).filter(({ card }) => !unmet({ ...card } as unknown as RegistryView, services.isUsable).length && input.cards?.[`${card.module}/${card.name}`]);
72
+ if (!list.length) return null;
73
+ return (
74
+ <aside className="cards-region" aria-label="Cards">
75
+ <h2 className="cards-title"><i className="fa-solid fa-layer-group" /> Cards <span className="muted small">{list.length}</span></h2>
76
+ <div className="cards-grid">{list.map(({ card, context }) => <CardHost key={`${card.module}/${card.name}`} card={card} context={context} page={page} input={input} />)}</div>
77
+ </aside>
78
+ );
79
+ }
80
+
81
+ // Registered once, before any view renders: registering it in an effect left a view's first paint without its panels.
82
+ setSlotRenderer((p, name) => <SlotHost page={p} name={name} />);
83
+
84
+ /** Mounts a module view with its page and framework instance, or the screen that explains why it can't run yet. */
85
+ export function ViewHost({ view }: { view: RegistryView }) {
86
+ const input = useShell();
87
+ useStore(services.states);
88
+ const key = viewKey(view);
89
+ const vaultState = useStore({ get: vault.status, subscribe: (fn) => vault.subscribe(fn) });
90
+ // The page lives as long as this view is mounted; it starts with the context showView left in the mailbox.
91
+ const page = useMemo(() => createPage(key, router.takeContext(key)), [key]);
92
+ const framework = useMemo(() => createFramework(view.module, page), [view.module, page]);
93
+
94
+ useEffect(() => {
95
+ // The system tools this view lists in its manifest (ADR-054), for as long as it is open.
96
+ const removeSystem = systemToolsFor(view.tools).map((t) => page.tools.add(t));
97
+ currentPage.set(page);
98
+ const initial = page.viewContext.get();
99
+ if (initial) log.add('debug', `Opened ${key} with context: ${Object.keys(initial).join(', ')}`, initial, 'navigation');
100
+ // Later hand-offs while this view is open arrive live, without a re-mount (ADR-036).
101
+ router.setLiveHandler(key, (ctx) => { log.add('debug', `${key} received context: ${Object.keys(ctx).join(', ')}`, ctx, 'navigation'); deliver(page, ctx); });
102
+ return () => { removeSystem.forEach((r) => r()); router.setLiveHandler(key, null); if (currentPage.get() === page) currentPage.set(null); };
103
+ }, [page, key, input, view.tools]);
104
+
105
+ const missing = unmet(view, services.isUsable);
106
+ if (missing.length) {
107
+ return (
108
+ <div className="card">
109
+ <h2>Set up {missing.length === 1 ? 'a service' : 'services'} first</h2>
110
+ <p className="muted">This view needs:</p>
111
+ <ul>{missing.map((k) => { const [type, name] = k.split('/'); const s = services.find(type, name); return <li key={k}><a href={router.href.settings('services', type, name)}>{s?.label ?? type} ({k})</a>: {s && !services.stateOf(s).enabled ? 'turned off' : 'not set up'}</li>; })}</ul>
112
+ <p className="muted">Set it up, then come back here.</p>
113
+ </div>
114
+ );
115
+ }
116
+ const needsVault = view.requires.some((r) => { const s = services.find(r.type, r.name); return !!s && services.stateOf(s).mode !== 'session'; });
117
+ if (needsVault && vaultState === 'locked') return <div className="card"><h2>The vault is locked</h2><p className="muted">This view uses saved credentials.</p><button className="primary" onClick={() => void vault.whenUnlocked()}>Unlock</button></div>;
118
+
119
+ const View = input.views[key];
120
+ if (!View) return <div className="card"><h2>{view.label}</h2><p className="muted">This view has no component (taco.module.json › entry).</p></div>;
121
+ return <><Boundary name={`View ${key}`}><View framework={framework} context={page.viewContext.get()} /></Boundary><CardsRegion page={page} view={view} /></>;
122
+ }
@@ -0,0 +1,21 @@
1
+ import { createContext, useContext, useSyncExternalStore, type ComponentType } from 'react';
2
+ import type { CardProps, PanelProps, Routine, ServiceImpl, ViewProps } from '@tacoshell/sdk';
3
+ import type { Registry } from '../types.ts';
4
+
5
+ export const useStore = <T,>(s: { get: () => T; subscribe: (fn: () => void) => () => void }) => useSyncExternalStore(s.subscribe, s.get);
6
+
7
+ export interface ShellInput {
8
+ registry: Registry;
9
+ /** View components by `<module>/<view>` (generated entry). */
10
+ views: Record<string, ComponentType<ViewProps>>;
11
+ /** Service implementations by `<type>/<name>`. */
12
+ services: Record<string, ServiceImpl>;
13
+ /** Panel components by `<module>/<panel>` (ADR-053). */
14
+ panels?: Record<string, ComponentType<PanelProps>>;
15
+ /** Card components by `<module>/<card>` (ADR-062). */
16
+ cards?: Record<string, ComponentType<CardProps<any>>>;
17
+ /** Refreshable datasets' routines by `<module>/<dataset>` (ADR-043). */
18
+ routines?: Record<string, Routine>;
19
+ }
20
+ export const ShellContext = createContext<ShellInput | null>(null);
21
+ export const useShell = () => useContext(ShellContext)!;
@@ -0,0 +1,162 @@
1
+ import { useRef, useState } from 'react';
2
+ import { createFramework } from '../../core/bus.ts';
3
+ import * as datasets from '../../core/datasets.ts';
4
+ import { download } from '../../core/localdata.ts';
5
+ import { href } from '../../core/router.ts';
6
+ import { toast } from '../../core/toasts.ts';
7
+ import * as vault from '../../core/vault.ts';
8
+ import type { RegistryDataset } from '../../types.ts';
9
+ import { useShell, useStore } from '../hooks.ts';
10
+ import { Markdown } from '../Markdown.tsx';
11
+ import { ScheduleEditor } from './ScheduleEditor.tsx';
12
+
13
+ const size = (n: number) => (n < 1024 ? `${n} B` : n < 1048576 ? `${(n / 1024).toFixed(1)} KB` : `${(n / 1048576).toFixed(1)} MB`);
14
+ const when = (iso?: string) => (iso ? `${new Date(iso).toLocaleString()} (${ago(iso)})` : 'never');
15
+ const signed = (n: number) => (n > 0 ? `+${n.toLocaleString()}` : n.toLocaleString());
16
+
17
+ interface Pending { name: string; bytes: number; modified: number; text: string; a: datasets.CsvAnalysis }
18
+
19
+ const vaultStore = { get: vault.status, subscribe: (fn: () => void) => vault.subscribe(fn) };
20
+ const ago = (iso?: string) => { if (!iso) return 'never'; const s = (Date.now() - new Date(iso).getTime()) / 1000; return s < 60 ? 'just now' : s < 3600 ? `${Math.round(s / 60)} min ago` : s < 86400 ? `${Math.round(s / 3600)} h ago` : new Date(iso).toLocaleDateString(); };
21
+ const cell = (v: unknown) => (v === null || v === undefined ? '—' : typeof v === 'object' ? JSON.stringify(v) : String(v));
22
+
23
+ /** Shown before any CSV replaces a dataset: what is in the file, what it will replace, and what looks off. Nothing is stored until Import is pressed. */
24
+ function ImportConfirm({ d, p, busy, onCancel, onConfirm }: { d: RegistryDataset; p: Pending; busy: boolean; onCancel: () => void; onConfirm: () => void }) {
25
+ const st = datasets.stateOf(d);
26
+ const { a } = p;
27
+ const delta = a.rows.length - st.rows;
28
+ const shrinks = st.rows > 0 && a.rows.length < st.rows * 0.5;
29
+ const cols = a.columns.slice(0, 8);
30
+ const row = (k: string, v: React.ReactNode) => <tr><td className="muted">{k}</td><td>{v}</td></tr>;
31
+ return (
32
+ <div className="backdrop" onKeyDown={(e) => e.key === 'Escape' && onCancel()}>
33
+ <div className="modal import-confirm" role="alertdialog" aria-labelledby="imp-title">
34
+ <button className="close" onClick={onCancel} aria-label="Close">×</button>
35
+ <h2 id="imp-title">Import into {d.label}?</h2>
36
+ <p className="muted small">A CSV import <strong>replaces every row</strong> in this dataset. Nothing changes until you press Import.</p>
37
+ <div className="import-cols">
38
+ <div><h3>The file</h3><table className="keys"><tbody>
39
+ {row('Name', <code>{p.name}</code>)}
40
+ {row('Size', size(p.bytes))}
41
+ {row('File modified', new Date(p.modified).toLocaleString())}
42
+ {row('Rows in file', a.fileRows.toLocaleString())}
43
+ {row('Rows to import', <strong>{a.rows.length.toLocaleString()}</strong>)}
44
+ {row('Columns', `${a.columns.length}${a.missing.length ? ` (${a.missing.length} missing)` : ''}${a.extra.length ? ` (${a.extra.length} not in the schema)` : ''}`)}
45
+ </tbody></table></div>
46
+ <div><h3>What it replaces</h3><table className="keys"><tbody>
47
+ {row('Current rows', st.rows.toLocaleString())}
48
+ {row('Last updated', when(st.updatedAt))}
49
+ {row('Last source', st.source ?? '—')}
50
+ {row('Change', <strong className={delta < 0 ? 'sched-warn' : ''}>{signed(delta)} rows</strong>)}
51
+ </tbody></table></div>
52
+ </div>
53
+ {shrinks && <p className="sched-warn small">⚠ The file has less than half as many rows as the dataset has now ({a.rows.length.toLocaleString()} vs {st.rows.toLocaleString()}). Is it the right file?</p>}
54
+ {d.kind === 'refreshable' && st.source === 'routine' && <p className="sched-warn small">⚠ These rows came from a refresh; the CSV replaces them until the next refresh.</p>}
55
+ {a.warnings.map((w) => <p key={w} className="sched-warn small">⚠ {w}</p>)}
56
+ {a.emptyKeys > 0 && <p className="sched-warn small">⚠ {a.emptyKeys} row(s) have an empty "{d.key}".</p>}
57
+ <h3>First rows</h3>
58
+ <div className="grid-wrap"><table className="grid"><thead><tr>{cols.map((c) => <th key={c}>{c}</th>)}</tr></thead>
59
+ <tbody>{a.rows.slice(0, 5).map((r, i) => <tr key={i}>{cols.map((c) => <td key={c}>{cell(r[c])}</td>)}</tr>)}</tbody></table>
60
+ {a.columns.length > cols.length && <p className="muted small">+{a.columns.length - cols.length} more column(s).</p>}</div>
61
+ <div className="actions"><button onClick={onCancel}>Cancel</button><button className="primary" autoFocus disabled={busy || !a.rows.length} onClick={onConfirm}>Import {a.rows.length.toLocaleString()} rows</button></div>
62
+ </div>
63
+ </div>
64
+ );
65
+ }
66
+
67
+ /** When it refreshes, when it is next due, and a warning when a scheduled time has passed without an update. */
68
+ function Schedule({ d, onEdit }: { d: RegistryDataset; onEdit: () => void }) {
69
+ useStore(datasets.states);
70
+ const next = datasets.nextDue(d), c = datasets.compliance(d);
71
+ const custom = !!datasets.stateOf(d).schedule;
72
+ return (
73
+ <p className="schedule-line small">
74
+ <i className="fa-regular fa-clock" /> <strong>{datasets.describeSchedule(d)}</strong>{custom ? <span className="muted"> (your choice)</span> : d.schedule ? <span className="muted"> (default)</span> : null}
75
+ {next && <span className="muted"> · next {new Date(next).toLocaleString(undefined, { weekday: 'short', day: 'numeric', month: 'short', hour: 'numeric', minute: '2-digit' })}</span>}
76
+ {c.scheduled && (c.ok ? <span className="sched-ok"> ✓ up to date</span> : <span className="sched-warn"> ⚠ a scheduled refresh is overdue</span>)}
77
+ {' '}<button className="link" onClick={onEdit}>Schedule…</button>
78
+ </p>
79
+ );
80
+ }
81
+
82
+ function DatasetCard({ d }: { d: RegistryDataset }) {
83
+ useStore(datasets.states);
84
+ const st = datasets.stateOf(d);
85
+ const [open, setOpen] = useState<'preview' | 'schema' | 'instructions' | null>(null);
86
+ const [preview, setPreview] = useState<datasets.Row[]>([]);
87
+ const [busy, setBusy] = useState(false);
88
+ const [confirmClear, setConfirmClear] = useState(false);
89
+ const [scheduling, setScheduling] = useState(false);
90
+ const file = useRef<HTMLInputElement>(null);
91
+ const run = async (what: () => Promise<void>) => { setBusy(true); try { await what(); } catch (e) { toast((e as Error).message, 'error'); } finally { setBusy(false); } };
92
+ const [pending, setPending] = useState<Pending | null>(null);
93
+ // Picking a file only reads and analyses it; the import itself waits for the confirmation.
94
+ const stageFile = (f?: File) => f && run(async () => {
95
+ try { setPending({ name: f.name, bytes: f.size, modified: f.lastModified, text: await f.text(), a: datasets.analyzeCsv(d, await f.text()) }); }
96
+ finally { if (file.current) file.current.value = ''; }
97
+ });
98
+ const confirmImport = () => pending && run(async () => {
99
+ const r = await datasets.importCsv(d, pending.text);
100
+ setPending(null);
101
+ toast(`${d.label}: ${r.rows} row(s) imported.${r.warnings.length ? ` ${r.warnings.join(' ')}` : ''}`, r.warnings.length ? 'error' : 'info');
102
+ if (open === 'preview') setPreview((await datasets.rows(d)).slice(0, 20));
103
+ });
104
+ const toggle = (what: 'preview' | 'schema' | 'instructions') => run(async () => {
105
+ if (open === what) return setOpen(null);
106
+ if (what === 'preview') setPreview((await datasets.rows(d)).slice(0, 20));
107
+ setOpen(what);
108
+ });
109
+ const columns = st.columns.length ? st.columns : Object.keys(d.schema ?? {});
110
+ const est = datasets.estimateMs(d);
111
+ return (
112
+ <div className="card dataset">
113
+ <div className="dataset-head">
114
+ <div><strong>{d.label}</strong> <span className={`pill ${d.kind === 'refreshable' ? 'ok' : ''}`}>{d.kind === 'importOnly' ? 'Import only' : 'Refreshable'}</span>
115
+ <div className="muted small">{d.module}/{d.name}{d.key ? ` · key ${d.key}` : ''}</div></div>
116
+ <div className="dataset-stats"><strong>{st.rows.toLocaleString()}</strong> rows<div className="muted small">updated {ago(st.updatedAt)}{st.source ? ` (${st.source})` : ''}</div></div>
117
+ </div>
118
+ {d.kind === 'refreshable' && <Schedule d={d} onEdit={() => setScheduling(true)} />}
119
+ {scheduling && <ScheduleEditor title={d.label} description="When this dataset refreshes by itself. The developer ships a default; this is your choice for this install." current={datasets.cronOf(d)} defaultCron={d.schedule?.cron ?? null}
120
+ onSave={(cron) => datasets.setSchedule(d, cron)} onClose={() => setScheduling(false)} />}
121
+ {st.lastError && <p className="error small">Last refresh failed: {st.lastError}</p>}
122
+ <div className="actions">
123
+ <button className="primary" disabled={busy} onClick={() => file.current?.click()}><i className="fa-solid fa-file-csv" /> Import CSV</button>
124
+ <input ref={file} type="file" accept=".csv,text/csv" hidden onChange={(e) => void stageFile(e.target.files?.[0])} />
125
+ {pending && <ImportConfirm d={d} p={pending} busy={busy} onCancel={() => setPending(null)} onConfirm={() => void confirmImport()} />}
126
+ <button disabled={busy || !st.rows} onClick={() => void run(async () => download(`${d.name}.csv`, await datasets.exportCsv(d), 'text/csv'))}><i className="fa-solid fa-file-export" /> Export CSV</button>
127
+ {d.kind === 'refreshable' && <button disabled={busy || st.refreshing || !datasets.hasRoutine(d)} onClick={() => void run(async () => { const n = await datasets.refresh(d, createFramework(d.module)); toast(`${d.label} refreshed: ${n} row(s).`); })}>
128
+ <i className={`fa-solid fa-rotate${st.refreshing ? ' fa-spin' : ''}`} /> {st.refreshing ? 'Refreshing…' : 'Refresh now'}{est ? ` (~${Math.max(1, Math.round(est / 1000))} s)` : ''}</button>}
129
+ <button disabled={busy || !st.rows} onClick={() => void toggle('preview')}>{open === 'preview' ? 'Hide preview' : 'Preview'}</button>
130
+ <button onClick={() => void toggle('schema')}>{open === 'schema' ? 'Hide schema' : 'Schema'}</button>
131
+ {d.instructionsText && <button onClick={() => void toggle('instructions')}>{open === 'instructions' ? 'Hide instructions' : 'Instructions'}</button>}
132
+ <button className="danger" disabled={busy || !st.rows} onClick={() => { if (!confirmClear) return setConfirmClear(true); setConfirmClear(false); void run(() => datasets.clear(d)); }}>{confirmClear ? 'Click again to clear' : 'Clear'}</button>
133
+ </div>
134
+ {open === 'instructions' && <div className="help-body"><Markdown text={d.instructionsText} /></div>}
135
+ {open === 'schema' && (
136
+ <table className="grid"><thead><tr><th>Column</th><th>Type</th></tr></thead>
137
+ <tbody>{Object.entries(d.schema ?? {}).map(([c, t]) => <tr key={c}><td><code>{c}</code>{c === d.key ? ' (key)' : ''}</td><td>{t}</td></tr>)}</tbody></table>
138
+ )}
139
+ {open === 'preview' && (
140
+ <div className="grid-wrap"><table className="grid"><thead><tr>{columns.map((c) => <th key={c}>{c}</th>)}</tr></thead>
141
+ <tbody>{preview.map((r, i) => <tr key={i}>{columns.map((c) => <td key={c}>{cell(r[c])}</td>)}</tr>)}</tbody></table>
142
+ <p className="muted small">First {preview.length} of {st.rows} row(s).</p></div>
143
+ )}
144
+ </div>
145
+ );
146
+ }
147
+
148
+ /** Settings → Datasets (ADR-043): every dataset the app's modules declare. Rows are only readable while the vault is unlocked. */
149
+ export function DatasetsPage() {
150
+ const { registry } = useShell();
151
+ const status = useStore(vaultStore);
152
+ return (
153
+ <div className="page">
154
+ <h1>Datasets</h1>
155
+ <p className="muted">Datasets are stored encrypted in the vault. <strong>Import only</strong> datasets are filled from a CSV; <strong>refreshable</strong> ones also refresh themselves from their services (a CSV import still works).</p>
156
+ {!registry.datasets.length && <p className="muted">No module in this app declares a dataset. Add one with <code>taco-cli add component --type=dataset</code>.</p>}
157
+ {status === 'uninitialized' && registry.datasets.length > 0 && <div className="card">Create the vault first: <a href={href.settings('getting-started')}>Getting Started</a>.</div>}
158
+ {status === 'locked' && registry.datasets.length > 0 && <div className="card">The vault is locked. <button className="primary" onClick={() => void vault.whenUnlocked()}><i className="fa-solid fa-lock-open" /> Unlock</button></div>}
159
+ {status === 'unlocked' && registry.datasets.map((d) => <DatasetCard key={`${d.module}/${d.name}`} d={d} />)}
160
+ </div>
161
+ );
162
+ }
@@ -0,0 +1,19 @@
1
+ import { useShell } from '../hooks.ts';
2
+ import { Markdown } from '../Markdown.tsx';
3
+
4
+ /**
5
+ * Settings → Release Notes: the app's `self/docs/release-notes.md`, newest first. Written by hand for now (`taco-cli deploy --release` adds the heading);
6
+ * the shape `## vX.Y.Z — date` + `- change ([#12](https://github.com/org/repo/pull/12))` is what a generator can fill from commit messages and PRs later.
7
+ */
8
+ export function ReleaseNotesPage() {
9
+ const { registry } = useShell();
10
+ return (
11
+ <div className="page">
12
+ <h1>Release Notes</h1>
13
+ <p className="muted">What changed in each version of {registry.app.displayName}, newest first. You are on <strong>v{registry.app.version}</strong>.</p>
14
+ {registry.releaseNotesText?.trim()
15
+ ? <div className="card release-notes"><Markdown text={registry.releaseNotesText} /></div>
16
+ : <div className="card"><p className="muted">No release notes yet. Write them in <code>self/docs/release-notes.md</code>.</p></div>}
17
+ </div>
18
+ );
19
+ }