@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
package/src/ui/App.tsx ADDED
@@ -0,0 +1,241 @@
1
+ import { useEffect, useMemo, useRef, useState } from 'react';
2
+ import { barItems, buildNav, firstFeatured, hasReports, pageTitle, type NavSection } from '../core/nav.ts';
3
+ import { favorites, moveFavorite, settings, togglePanel, toggleFavorite, updateSettings } from '../core/prefs.ts';
4
+ import * as router from '../core/router.ts';
5
+ import { currentPage } from '../core/page.ts';
6
+ import * as services from '../core/services.ts';
7
+ import * as datasets from '../core/datasets.ts';
8
+ import { dismiss, toast, toasts } from '../core/toasts.ts';
9
+ import * as vault from '../core/vault.ts';
10
+ import { viewKey, type RegistryView } from '../types.ts';
11
+ import { useShell, useStore } from './hooks.ts';
12
+ import { Icon } from './Icon.tsx';
13
+ import { Rail, SettingsRail } from './Rail.tsx';
14
+ import { Configuration, GettingStarted, ServicePage, ServicesList, VaultAndData } from './settings/Settings.tsx';
15
+ import { DatasetsPage } from './settings/Datasets.tsx';
16
+ import { ReleaseNotesPage } from './settings/ReleaseNotes.tsx';
17
+ import { SettingsTabbed } from './settings/SettingsTabs.tsx';
18
+ import { TemplatesPage } from './settings/Templates.tsx';
19
+ import { comboOf, match } from '../core/hotkeys.ts';
20
+ import { appDefaultOf, startHash } from '../core/startpage.ts';
21
+ import { SearchBar } from './Search.tsx';
22
+ import { SessionsMenu } from './Sessions.tsx';
23
+ import { SidePanel, SubBar } from './SidePanel.tsx';
24
+ import { ViewHost } from './ViewHost.tsx';
25
+
26
+ const vaultStore = { get: vault.status, subscribe: (fn: () => void) => vault.subscribe(fn) };
27
+
28
+ function UnlockPrompt({ onClose }: { onClose: () => void }) {
29
+ const [pass, setPass] = useState('');
30
+ const [wrong, setWrong] = useState(false);
31
+ const submit = async () => { if (await vault.unlock(pass)) onClose(); else { setWrong(true); setPass(''); } };
32
+ return (
33
+ <div className="backdrop">
34
+ <div className="modal">
35
+ <button className="close" onClick={onClose} aria-label="Close">×</button>
36
+ <h2>Unlock the vault</h2>
37
+ <p className="muted">Anything waiting for a saved credential continues after you unlock.</p>
38
+ <input autoFocus type="password" value={pass} placeholder="Passphrase" onChange={(e) => { setPass(e.target.value); setWrong(false); }} onKeyDown={(e) => e.key === 'Enter' && void submit()} />
39
+ {wrong && <p className="error">That passphrase isn't right.</p>}
40
+ <div className="actions"><button className="primary" onClick={() => void submit()}>Unlock</button></div>
41
+ </div>
42
+ </div>
43
+ );
44
+ }
45
+
46
+ function Toasts() {
47
+ const list = useStore(toasts);
48
+ return <div className="toasts">{list.map((t) => <div key={t.id} className={`toast ${t.kind}`} onClick={() => dismiss(t.id)}>{t.title && <strong>{t.title}</strong>}<div>{t.text}</div></div>)}</div>;
49
+ }
50
+
51
+ function FavoritesMenu({ views }: { views: RegistryView[] }) {
52
+ const favs = useStore(favorites);
53
+ const [open, setOpen] = useState(false);
54
+ const items = favs.map((k) => views.find((v) => viewKey(v) === k)).filter((v): v is RegistryView => !!v);
55
+ return (
56
+ <div className="favmenu">
57
+ <button className="bar-btn icon-only" onClick={() => setOpen(!open)} title="Favorites" aria-label="Favorites"><i className="fa-solid fa-bars" /></button>
58
+ {open && (
59
+ <div className="favmenu-list" onMouseLeave={() => setOpen(false)}>
60
+ {!items.length && <p className="muted small">Star a page with Favorite in its bar.</p>}
61
+ {items.map((v) => (
62
+ <div key={viewKey(v)} className="favmenu-row" tabIndex={0} onKeyDown={(e) => { if (e.altKey && e.key === 'ArrowUp') moveFavorite(viewKey(v), -1); if (e.altKey && e.key === 'ArrowDown') moveFavorite(viewKey(v), 1); }}>
63
+ <a href={router.href.view(v.module, v.name)} onClick={() => setOpen(false)}><Icon icon={v.icon} />{v.label}</a>
64
+ <button onClick={() => moveFavorite(viewKey(v), -1)} title="Move up (Alt+↑)">↑</button><button onClick={() => moveFavorite(viewKey(v), 1)} title="Move down (Alt+↓)">↓</button>
65
+ </div>
66
+ ))}
67
+ </div>
68
+ )}
69
+ </div>
70
+ );
71
+ }
72
+
73
+ /** "Lock the vault?" before the Vault button locks it (Settings → Configuration → Vault: Confirm before locking; default on). Enter locks, Esc cancels. */
74
+ function LockConfirm({ onClose }: { onClose: () => void }) {
75
+ const lock = () => { onClose(); void vault.lock(); };
76
+ return (
77
+ <div className="backdrop" onMouseDown={(e) => e.target === e.currentTarget && onClose()} onKeyDown={(e) => e.key === 'Escape' && onClose()}>
78
+ <div className="modal" role="alertdialog" aria-labelledby="lock-title">
79
+ <h2 id="lock-title">Lock the vault?</h2>
80
+ <p className="muted">Saved credentials, datasets and templates become unavailable until you enter your passphrase again. Anything waiting for the vault pauses.</p>
81
+ <div className="actions"><button onClick={onClose}>Cancel</button><button className="primary" autoFocus onClick={lock}>Lock</button></div>
82
+ </div>
83
+ </div>
84
+ );
85
+ }
86
+
87
+ /** Vault state at a glance, icon only: green open lock while unlocked (click to lock, after a confirmation), red closed lock while locked (click to unlock). */
88
+ function VaultButton({ state, onUnlock }: { state: ReturnType<typeof vault.status>; onUnlock: () => void }) {
89
+ const confirm = useStore(settings).confirmLock;
90
+ const [asking, setAsking] = useState(false);
91
+ if (state === 'uninitialized') return null;
92
+ const unlocked = state === 'unlocked';
93
+ return (
94
+ <>
95
+ <button className={`bar-btn icon-only ${unlocked ? 'st-ok' : 'st-bad'}`} title="Vault" aria-label="Vault" onClick={() => (unlocked ? (confirm ? setAsking(true) : void vault.lock()) : onUnlock())}>
96
+ <i className={`fa-solid ${unlocked ? 'fa-lock-open' : 'fa-lock'}`} />
97
+ </button>
98
+ {asking && unlocked && <LockConfirm onClose={() => setAsking(false)} />}
99
+ </>
100
+ );
101
+ }
102
+
103
+ /** One click turns notifications on / off (the same switch as Settings → Configuration → Notifications): green bell when on, red crossed-out bell when off or paused by a locked vault. */
104
+ function NotifyBell({ locked }: { locked: boolean }) {
105
+ const prefs = useStore(settings).notifications;
106
+ const on = prefs.enabled && !locked;
107
+ const toggle = () => { void updateSettings({ notifications: { ...prefs, enabled: !prefs.enabled } }); toast(prefs.enabled ? 'Notifications off' : 'Notifications on'); };
108
+ return <button className={`bar-btn icon-only ${on ? 'st-ok' : 'st-bad'}`} onClick={toggle} disabled={locked} title="Notifications" aria-label="Notifications" aria-pressed={on}><i className={`fa-solid ${on ? 'fa-bell' : 'fa-bell-slash'}`} /></button>;
109
+ }
110
+
111
+ /** A database icon that pulses (selected color ↔ disabled gray) while any dataset refreshes in the background, and is gone otherwise. */
112
+ function DatasetRefreshIcon() {
113
+ const ids = useStore(datasets.refreshingNow);
114
+ const progress = useStore(datasets.progressNow);
115
+ if (!ids.length) return null;
116
+ const names = ids.map((id) => { const [m, n] = [id.slice(0, id.lastIndexOf('/')), id.slice(id.lastIndexOf('/') + 1)]; return `${datasets.find(m, n)?.label ?? id}${progress[id]?.text ? `: ${progress[id].text}` : ''}`; });
117
+ return <span className="refresh-indicator" role="status" aria-label="Refreshing datasets" title={`Refreshing: ${names.join(', ')}`}><i className="fa-solid fa-database" /></span>;
118
+ }
119
+
120
+ function FullscreenButton() {
121
+ const [full, setFull] = useState(() => !!document.fullscreenElement);
122
+ useEffect(() => { const f = () => setFull(!!document.fullscreenElement); document.addEventListener('fullscreenchange', f); return () => document.removeEventListener('fullscreenchange', f); }, []);
123
+ const toggle = () => { if (document.fullscreenElement) void document.exitFullscreen(); else document.documentElement.requestFullscreen().catch(() => toast('Full screen not allowed here', 'error')); };
124
+ return <button className={`bar-btn icon-only${full ? ' st-ok' : ''}`} onClick={toggle} title="Full Screen" aria-label="Full Screen" aria-pressed={full}><i className={`fa-solid ${full ? 'fa-compress' : 'fa-expand'}`} /></button>;
125
+ }
126
+
127
+ function Landing({ title, section, views }: { title: string; section: NavSection; views: RegistryView[] }) {
128
+ const favs = useStore(favorites);
129
+ const tiles = title === 'Home' ? favs.map((k) => views.find((v) => viewKey(v) === k)).filter((v): v is RegistryView => !!v) : [];
130
+ const all = [...section.featured, ...section.tools.flatMap((g) => g.features), ...section.services.flatMap((g) => g.features)];
131
+ return (
132
+ <div className="page">
133
+ <h1>{title}</h1>
134
+ {title === 'Home' && <><h2>Favorites</h2>{tiles.length ? <div className="tiles">{tiles.map((v) => <a key={viewKey(v)} className="tile" href={router.href.view(v.module, v.name)}><strong><Icon icon={v.icon} />{v.label}</strong><span className="muted small">{v.module}</span><button className="unstar" onClick={(e) => { e.preventDefault(); toggleFavorite(viewKey(v)); }}>★</button></a>)}</div> : <p className="muted">Star a page with Favorite in its bar to pin it here.</p>}</>}
135
+ <h2>{title === 'Home' ? 'Everything' : 'Reports'}</h2>
136
+ <div className="tiles">{all.map((f) => <a key={f.key} className="tile" href={router.href.view(f.views[0].module, f.views[0].name)}><strong><Icon icon={f.icon} />{f.label}</strong><span className="muted small">{f.views.length} view{f.views.length === 1 ? '' : 's'}</span></a>)}</div>
137
+ </div>
138
+ );
139
+ }
140
+
141
+ export function App() {
142
+ const { registry } = useShell();
143
+ const hash = useStore(router.current);
144
+ const vaultState = useStore(vaultStore);
145
+ useStore(services.states);
146
+ const [filter, setFilter] = useState('');
147
+ const [prompt, setPrompt] = useState(false);
148
+ // Refresh: pages that listen (usePageRefresh) are asked to reload their data; a page with no listeners is re-mounted, which reloads it from scratch.
149
+ const [remount, setRemount] = useState(0);
150
+ const filterRef = useRef<HTMLInputElement>(null);
151
+ const searchRef = useRef<HTMLInputElement>(null);
152
+ const nav = useMemo(() => buildNav(registry, services.isUsable, filter), [registry, filter, services.states.get(), vaultState]);
153
+
154
+ useEffect(() => vault.setUnlockPrompt(() => setPrompt(true)), []);
155
+ // Always ask for the passphrase when the app starts with a locked vault (an idle lock, a browser restart). Closing the prompt keeps it locked; the Vault button asks again.
156
+ useEffect(() => { if (vault.status() === 'locked') setPrompt(true); }, []);
157
+ // Start page (ADR-047, ADR-064): Getting Started until a vault exists, then the user's choice (Settings → Configuration), else the app's default
158
+ // (taco.json settings.startPage), else the first Featured Action, else Home.
159
+ const userStart = useStore(settings).startPage;
160
+ useEffect(() => {
161
+ if (router.parse(hash)) return;
162
+ router.replace(vaultState === 'uninitialized' ? router.href.settings('getting-started') : startHash(registry, firstFeatured(nav), userStart, appDefaultOf(registry)));
163
+ }, [hash]);
164
+ // HotKeys (ADR-046): the user's mapping from Settings → Configuration, defaults from core/hotkeys.ts.
165
+ useEffect(() => {
166
+ const onKey = (e: KeyboardEvent) => {
167
+ const hk = settings.get().hotkeys;
168
+ if (!hk.enabled || (e.target as HTMLElement)?.classList?.contains('hotkey-rec')) return;
169
+ const def = match(comboOf(e), hk.map);
170
+ if (!def) return;
171
+ e.preventDefault();
172
+ if (def.id === 'navFilter') { filterRef.current?.focus(); filterRef.current?.select(); }
173
+ else if (def.id === 'search') { searchRef.current?.focus(); }
174
+ else if (def.id === 'log') togglePanel('log');
175
+ else if (def.id === 'help') togglePanel('help');
176
+ else if (def.id === 'lock') void vault.lock();
177
+ else if (def.id === 'favorite') { const r = router.parse(location.hash); if (r?.page === 'view' && registry.views.find((v) => v.module === r.module && v.name === r.view)?.favorite !== false) toggleFavorite(`${r.module}/${r.view}`); }
178
+ };
179
+ addEventListener('keydown', onKey);
180
+ return () => removeEventListener('keydown', onKey);
181
+ }, [registry]);
182
+
183
+ const route = router.parse(hash) ?? { page: 'home' as const };
184
+ const section = route.page === 'settings' ? 'settings' : route.page === 'reports' ? 'reports' : route.page === 'view' ? (registry.views.find((v) => v.module === route.module && v.name === route.view)?.nav.section ?? 'home') : 'home';
185
+ const view = route.page === 'view' ? registry.views.find((v) => v.module === route.module && v.name === route.view) : undefined;
186
+ const feature = view ? nav.byView.get(viewKey(view)) : undefined;
187
+
188
+ const refresh = () => {
189
+ const p = currentPage.get();
190
+ if (p && p.refreshListeners() > 0) p.page.refresh('Refresh button');
191
+ else setRemount((n) => n + 1);
192
+ };
193
+
194
+ let body;
195
+ let help: { text?: string; title: string } = { title: 'This page' };
196
+ if (route.page === 'view') {
197
+ body = view ? <ViewHost key={`${viewKey(view)}:${remount}`} view={view} /> : <div className="page"><h1>Not found</h1><p className="muted">No view {route.module}/{route.view} in this app.</p></div>;
198
+ if (view) help = { text: view.helpText, title: view.label };
199
+ } else if (route.page === 'settings') {
200
+ body = route.sub === 'getting-started' ? <GettingStarted /> : route.sub === 'configuration' ? <SettingsTabbed page="configuration" coreLabel="Configuration" tab={route.type}><Configuration /></SettingsTabbed> : route.sub === 'vault' ? <SettingsTabbed page="vault" coreLabel="Vault & Data" tab={route.type}><VaultAndData /></SettingsTabbed>
201
+ : route.sub === 'datasets' ? <SettingsTabbed page="datasets" coreLabel="Datasets" tab={route.type}><DatasetsPage /></SettingsTabbed> : route.sub === 'templates' ? <SettingsTabbed page="templates" coreLabel="Templates" tab={route.type}><TemplatesPage /></SettingsTabbed> : route.sub === 'release-notes' ? <ReleaseNotesPage tab={route.type ?? 'notes'} /> : route.type && route.name ? <ServicePage type={route.type} name={route.name} /> : <ServicesList />;
202
+ if (route.sub === 'services' && route.type && route.name) { const s = services.find(route.type, route.name); help = { text: s?.howToText, title: s?.label ?? 'Service' }; }
203
+ } else {
204
+ body = <Landing title={route.page === 'reports' ? 'Reports' : 'Home'} section={route.page === 'reports' ? nav.reports : nav.home} views={registry.views} />;
205
+ }
206
+
207
+ return (
208
+ <div className="app">
209
+ <header className="top">
210
+ <FavoritesMenu views={registry.views} />
211
+ <strong className="app-name">{registry.app.displayName}</strong>
212
+ <nav className="sections">
213
+ <a className={section === 'home' ? 'on' : ''} href="#/home"><Icon icon={registry.sectionIcons?.home} />Home</a>
214
+ {hasReports(nav) && <a className={section === 'reports' ? 'on' : ''} href="#/reports"><Icon icon={registry.sectionIcons?.reports} />Reports</a>}
215
+ <a className={section === 'settings' ? 'on' : ''} href={router.href.settings('getting-started')}><Icon icon={registry.sectionIcons?.settings} />Settings</a>
216
+ </nav>
217
+ <a className="pill version" href={router.href.settings('release-notes')} title={`${registry.app.displayName} v${registry.app.version}: click for the release notes`}>v{registry.app.version}</a>
218
+ <SearchBar registry={registry} inputRef={searchRef} />
219
+ <div className="top-right">
220
+ <DatasetRefreshIcon />
221
+ <SessionsMenu registry={registry} />
222
+ <NotifyBell locked={vaultState === 'locked'} />
223
+ <VaultButton state={vaultState} onUnlock={() => setPrompt(true)} />
224
+ <FullscreenButton />
225
+ </div>
226
+ </header>
227
+ <div className="layout">
228
+ {section === 'settings' ? <SettingsRail active={route.page === 'settings' ? route.sub : ''} />
229
+ : <Rail section={section === 'reports' ? nav.reports : nav.home} active={view ? viewKey(view) : undefined} filter={filter} setFilter={setFilter} filterRef={filterRef} />}
230
+ <main className="content">
231
+ <SubBar tabs={view ? barItems(registry, view).map((b) => ({ label: b.label, href: router.href.view(b.view.module, b.view.name), active: b.view === view, icon: b.view.icon })) : undefined} favoriteKey={view && view.favorite !== false ? viewKey(view) : undefined} favoriteOff={view?.favorite === false} hasHelp={!!help.text} onRefresh={view && view.refresh !== false ? refresh : undefined} />
232
+ {view && <h1 className="page-title"><Icon icon={view.icon} />{pageTitle(registry, view)}</h1>}
233
+ <div className={view ? 'view-body' : undefined}>{body}</div>
234
+ </main>
235
+ <SidePanel helpText={help.text} helpTitle={help.title} />
236
+ </div>
237
+ {prompt && vaultState === 'locked' && <UnlockPrompt onClose={() => setPrompt(false)} />}
238
+ <Toasts />
239
+ </div>
240
+ );
241
+ }
@@ -0,0 +1,23 @@
1
+ import type { InputHTMLAttributes, RefObject } from 'react';
2
+
3
+ /** The "×" inside a filter box: shown only while there is text; clears it and keeps focus in the box. */
4
+ export function ClearButton({ onClear }: { onClear: () => void }) {
5
+ return <button type="button" className="clear-x" onClick={onClear} onMouseDown={(e) => e.preventDefault()} title="Clear" aria-label="Clear"><i className="fa-solid fa-xmark" /></button>;
6
+ }
7
+
8
+ type Props = Omit<InputHTMLAttributes<HTMLInputElement>, 'value' | 'onChange'> & {
9
+ value: string;
10
+ onValue: (v: string) => void;
11
+ inputRef?: RefObject<HTMLInputElement | null>;
12
+ wrapperClass?: string;
13
+ };
14
+
15
+ /** A text box with a "×" on its right that clears it: used by the Activity Log filter, the left-rail filter and header search. */
16
+ export function ClearableInput({ value, onValue, inputRef, wrapperClass = '', ...rest }: Props) {
17
+ return (
18
+ <div className={`clearable ${wrapperClass}`}>
19
+ <input {...rest} ref={inputRef} value={value} onChange={(e) => onValue(e.target.value)} />
20
+ {value && <ClearButton onClear={() => { onValue(''); inputRef?.current?.focus(); }} />}
21
+ </div>
22
+ );
23
+ }
@@ -0,0 +1,151 @@
1
+ import { useMemo, useRef, useState } from 'react';
2
+ import type { CsvFeatureDef, Framework, RowResult } from '@tacoshell/sdk';
3
+ import { BLANK, distinct, ICON, labelOf, normalizeResult, parseUpload, shownColumns, sleep, templateCsv, templateName, visibleIndexes, type CsvRow } from '../core/csvfeature.ts';
4
+ import { toast } from '../core/toasts.ts';
5
+ import type { RegistryView } from '../types.ts';
6
+
7
+ type Run = { queue: number[]; pos: number; state: 'idle' | 'running' | 'stopped' | 'done' };
8
+
9
+ /** Header cell with a checkbox dropdown of the column's values. Everything is ticked by default. */
10
+ function ColumnFilter({ label, values, excluded, onChange, disabled }: { label: string; values: string[]; excluded: ReadonlySet<string>; onChange: (next: Set<string>) => void; disabled: boolean }) {
11
+ const [open, setOpen] = useState(false);
12
+ const active = excluded.size > 0;
13
+ const toggle = (v: string) => { const n = new Set(excluded); if (n.has(v)) n.delete(v); else n.add(v); onChange(n); };
14
+ return (
15
+ <th>
16
+ <div className="csv-th"><span>{label}</span>
17
+ <button className={`bar-btn icon-only csv-filter${active ? ' on' : ''}`} disabled={disabled} aria-label={`Filter ${label}`} aria-expanded={open} onClick={() => setOpen(!open)}><i className="fa-solid fa-filter" /></button>
18
+ </div>
19
+ {open && (
20
+ <div className="filter-menu csv-menu" onMouseLeave={() => setOpen(false)}>
21
+ <div className="filter-row"><button onClick={() => onChange(new Set())}>Select all</button><button onClick={() => onChange(new Set(values))}>Select none</button></div>
22
+ {values.map((v) => <label key={v}><input type="checkbox" checked={!excluded.has(v)} onChange={() => toggle(v)} /> {v}</label>)}
23
+ </div>
24
+ )}
25
+ </th>
26
+ );
27
+ }
28
+
29
+ /**
30
+ * CSV: upload (with a template download) → Preview table with a value filter per shown column → Process, after a confirmation that lists
31
+ * the feature's steps and warning. Every displayed row goes, one at a time, to the feature's `processRow` with progress, Stop and Resume (v2 FR-BULK-1).
32
+ */
33
+ export function CsvFeature({ def, framework, view }: { def: CsvFeatureDef; framework: Framework; view: RegistryView }) {
34
+ const [file, setFile] = useState('');
35
+ const [rows, setRows] = useState<CsvRow[]>([]);
36
+ const [excluded, setExcluded] = useState<Record<string, Set<string>>>({});
37
+ const [results, setResults] = useState<Record<number, RowResult>>({});
38
+ const [run, setRun] = useState<Run>({ queue: [], pos: 0, state: 'idle' });
39
+ const [asking, setAsking] = useState(false);
40
+ const stopRef = useRef(false);
41
+ const runRef = useRef(run);
42
+ const releaseRef = useRef<(() => void)[]>([]);
43
+ const cols = shownColumns(def);
44
+ const options = useMemo(() => Object.fromEntries(cols.map((c) => [c.key, distinct(rows, c.key)])), [rows]);
45
+ const visible = useMemo(() => visibleIndexes(rows, excluded), [rows, excluded]);
46
+ const running = run.state === 'running';
47
+ const update = (next: Run) => { runRef.current = next; setRun(next); };
48
+
49
+ const releaseGuards = () => { releaseRef.current.forEach((r) => r()); releaseRef.current = []; };
50
+ const onFile = async (f: File | undefined) => {
51
+ if (!f) return;
52
+ const parsed = parseUpload(await f.text(), def);
53
+ framework.log.info(`CSV ${f.name}: ${parsed.rows.length} row(s)`);
54
+ for (const s of parsed.skipped) framework.log.warn(`Removed ${s}`);
55
+ if (parsed.problems.length) {
56
+ framework.log.error(`CSV rejected: ${f.name}`, parsed.problems.slice(0, 50));
57
+ toast(`CSV rejected: ${parsed.problems[0]}${parsed.problems.length > 1 ? ` (+${parsed.problems.length - 1} more, see the Activity Log)` : ''}`, 'error');
58
+ return;
59
+ }
60
+ setFile(f.name); setRows(parsed.rows); setExcluded({}); setResults({}); update({ queue: [], pos: 0, state: 'idle' });
61
+ };
62
+ const download = () => {
63
+ const url = URL.createObjectURL(new Blob([templateCsv(def)], { type: 'text/csv' }));
64
+ const a = Object.assign(document.createElement('a'), { href: url, download: templateName(def, view.name) });
65
+ a.click(); URL.revokeObjectURL(url);
66
+ };
67
+
68
+ const go = async (from: Run) => {
69
+ stopRef.current = false;
70
+ update({ ...from, state: 'running' });
71
+ releaseGuards();
72
+ releaseRef.current.push(framework.guard.block(`A CSV run is going (${from.queue.length - from.pos} remaining)`));
73
+ let pos = from.pos, failed = 0;
74
+ while (pos < from.queue.length) {
75
+ if (stopRef.current) break; // Stop is checked before each row, so Resume continues with the next unprocessed one
76
+ const index = from.queue[pos];
77
+ let result: RowResult;
78
+ try { result = normalizeResult(await def.processRow(rows[index], { framework, index: pos, total: from.queue.length, log: framework.log })); }
79
+ catch (e) { result = { status: 'error', message: (e as Error).message }; }
80
+ if (result.status === 'error') failed++;
81
+ setResults((r) => ({ ...r, [index]: result }));
82
+ pos++;
83
+ update({ queue: from.queue, pos, state: 'running' });
84
+ if (def.delayMs && pos < from.queue.length) await sleep(def.delayMs);
85
+ }
86
+ releaseGuards();
87
+ const state = pos >= from.queue.length ? 'done' : 'stopped';
88
+ update({ queue: from.queue, pos, state });
89
+ framework.log[failed ? 'warn' : 'info'](state === 'done' ? `${def.processLabel ?? 'Process'} finished: ${from.queue.length - failed} of ${from.queue.length} without error` : `Stopped after ${pos} of ${from.queue.length} rows.`);
90
+ // After a Stop that left rows unprocessed, leaving is allowed but warned about: this page's tracking (and Resume) would be lost.
91
+ if (state === 'stopped') releaseRef.current.push(framework.guard.unsaved(() => runRef.current.state === 'stopped'));
92
+ };
93
+
94
+ const start = () => { setAsking(false); setResults({}); void go({ queue: visible, pos: 0, state: 'running' }); };
95
+ const left = run.queue.length - run.pos;
96
+ const label = run.state === 'stopped' ? `Stopped — ${left} remaining` : left > 0 ? `${left} remaining` : 'Complete';
97
+
98
+ return (
99
+ <div className="csv-feature" data-feature-type="CSV">
100
+ {def.intro && <p className="muted">{def.intro}</p>}
101
+ <div className="csv-upload card">
102
+ <input type="file" accept=".csv,text/csv" aria-label="CSV file" disabled={running} onChange={(e) => { void onFile(e.target.files?.[0]); e.target.value = ''; }} />
103
+ <button onClick={download}><i className="fa-solid fa-download" /> Download template</button>
104
+ {file && <span className="muted small">{file}: {rows.length} row(s)</span>}
105
+ </div>
106
+ {rows.length > 0 && (
107
+ <>
108
+ <h2>Preview <span className="muted small">{visible.length} of {rows.length} rows shown</span></h2>
109
+ <div className="table-wrap csv-table">
110
+ <table>
111
+ <thead><tr>{cols.map((c) => <ColumnFilter key={c.key} label={labelOf(c)} values={options[c.key]} excluded={excluded[c.key] ?? new Set()} disabled={running} onChange={(n) => setExcluded({ ...excluded, [c.key]: n })} />)}<th className="csv-status-col">Result</th></tr></thead>
112
+ <tbody>
113
+ {visible.map((i) => {
114
+ const r = results[i];
115
+ return (
116
+ <tr key={i} className={r ? `row-${r.status}` : undefined} data-row={i}>
117
+ {cols.map((c) => <td key={c.key}>{rows[i][c.key] || <span className="muted">{BLANK}</span>}</td>)}
118
+ <td className="csv-status" title={r?.message ?? ''}>{r ? ICON[r.status] : ''}</td>
119
+ </tr>
120
+ );
121
+ })}
122
+ </tbody>
123
+ </table>
124
+ </div>
125
+ <div className="csv-run">
126
+ <span className="spacer" />
127
+ {run.state !== 'idle' && (
128
+ <span className="csv-progress">
129
+ <progress max={run.queue.length || 1} value={run.pos} /><span className="muted small">{label}</span>
130
+ {running && <button onClick={() => { stopRef.current = true; }}>Stop</button>}
131
+ {run.state === 'stopped' && left > 0 && <button className="primary" onClick={() => void go(run)}>Resume</button>}
132
+ </span>
133
+ )}
134
+ <button className="primary" disabled={running || !visible.length} onClick={() => setAsking(true)}>{def.processLabel ?? 'Process'} ({visible.length})</button>
135
+ </div>
136
+ </>
137
+ )}
138
+ {asking && (
139
+ <div className="backdrop" onMouseDown={(e) => e.target === e.currentTarget && setAsking(false)} onKeyDown={(e) => e.key === 'Escape' && setAsking(false)}>
140
+ <div className="modal csv-confirm" role="alertdialog" aria-labelledby="csv-confirm-title">
141
+ <h2 id="csv-confirm-title">{def.confirm.title ?? `${def.processLabel ?? 'Process'} ${visible.length} row(s)?`}</h2>
142
+ <p className="muted">{visible.length} row(s) will be processed, one at a time. These steps happen for each row:</p>
143
+ <ol>{def.confirm.steps.map((s, i) => <li key={i}>{s}</li>)}</ol>
144
+ {def.confirm.warning && <div className="callout warn" role="note"><i className="fa-solid fa-triangle-exclamation" /> {def.confirm.warning}</div>}
145
+ <div className="actions"><button onClick={() => setAsking(false)}>Cancel</button><button className="primary" autoFocus onClick={start}>Confirm</button></div>
146
+ </div>
147
+ </div>
148
+ )}
149
+ </div>
150
+ );
151
+ }
@@ -0,0 +1,8 @@
1
+ import type { RegistryIcon } from '../types.ts';
2
+
3
+ /** A module-declared icon: Font Awesome classes, or a bundled image. Draws nothing when the feature has none. */
4
+ export function Icon({ icon, className = '' }: { icon?: RegistryIcon; className?: string }) {
5
+ if (!icon) return null;
6
+ if ('fa' in icon) return <i className={`${icon.fa} fa-fw nav-icon ${className}`} aria-hidden="true" />;
7
+ return <img className={`nav-icon nav-img ${className}`} src={icon.img} alt="" aria-hidden="true" />;
8
+ }
@@ -0,0 +1,39 @@
1
+ import { useState } from 'react';
2
+ import type { Framework, ItemFeatureDef } from '@tacoshell/sdk';
3
+ import { actionProblem, targetContext } from '../core/contrib.ts';
4
+ import * as log from '../core/log.ts';
5
+ import type { Page } from '../core/page.ts';
6
+ import type { RegistryView } from '../types.ts';
7
+ import { ActionModal } from './ActionModal.tsx';
8
+ import { useContributions } from './useContrib.ts';
9
+
10
+ /**
11
+ * ITEM: a main pane (yours) and a fixed 300 px right rail: your Header, the framework's Actions, your Footer. Header and Footer are left out when
12
+ * not defined; Actions is left out when no feature contributes. Each Action is an ACTION feature that opens in a modal with this item's context as `referrer`.
13
+ */
14
+ export function ItemFeature({ def, framework, page, context }: { def: ItemFeatureDef; framework: Framework; page: Page; context?: Record<string, unknown> }) {
15
+ const { items, exposed } = useContributions('actions', page);
16
+ // The modal's context is fixed when it opens, so what the page exposes later doesn't rebuild the action's page.
17
+ const [open, setOpen] = useState<{ view: RegistryView; context: Record<string, unknown> } | null>(null);
18
+ const { leftPane: Left, rightRailHeader: Header, rightRailFooter: Footer } = def;
19
+ const props = { framework, context };
20
+ const hasRail = !!Header || !!Footer || items.length > 0;
21
+ return (
22
+ <div className={`item-layout${hasRail ? '' : ' no-rail'}`}>
23
+ <div className="item-main"><Left {...props} /></div>
24
+ {hasRail && (
25
+ <aside className="item-rail" aria-label="Item rail">
26
+ {Header && <section className="rail-header" data-rail="header"><Header {...props} /></section>}
27
+ {items.length > 0 && (
28
+ <section className="rail-actions" data-rail="actions">
29
+ <h3 className="rail-title">Actions</h3>
30
+ {items.map((i) => <button key={i.id} className="action-btn" onClick={() => { const context = targetContext(i, exposed); const problem = actionProblem(i.view, context); if (problem) log.add('error', `Action "${i.label}": context for ${i.view.module}/${i.view.name} doesn't match its declaration (${problem})`, context, i.view.module); else setOpen({ view: i.view, context }); }}>{i.icon?.startsWith('fa-') ? <i className={i.icon} /> : null}<span>{i.label}</span></button>)}
31
+ </section>
32
+ )}
33
+ {Footer && <section className="rail-footer" data-rail="footer"><Footer {...props} /></section>}
34
+ </aside>
35
+ )}
36
+ {open && <ActionModal view={open.view} context={open.context} onClose={() => setOpen(null)} />}
37
+ </div>
38
+ );
39
+ }
@@ -0,0 +1,24 @@
1
+ import { parse, type Inline } from '../core/markdown.ts';
2
+
3
+ const inl = (items: Inline[]) =>
4
+ items.map((x, i) =>
5
+ x.t === 'code' ? <code key={i}>{x.v}</code>
6
+ : x.t === 'bold' ? <strong key={i}>{x.v}</strong>
7
+ : x.t === 'link' ? <a key={i} href={x.href} target="_blank" rel="noopener noreferrer">{x.v}</a>
8
+ : <span key={i}>{x.v}</span>);
9
+
10
+ /** Renders the Markdown subset as React elements: text is never interpreted as HTML (SECURITY.md rule 5). */
11
+ export function Markdown({ text }: { text?: string }) {
12
+ if (!text?.trim()) return <p className="muted">No help has been written for this page yet.</p>;
13
+ return (
14
+ <div className="md">
15
+ {parse(text).map((b, i) => {
16
+ if (b.t === 'h') { const H = (`h${b.level + 1}`) as 'h2' | 'h3' | 'h4'; return <H key={i}>{inl(b.inl)}</H>; }
17
+ if (b.t === 'p') return <p key={i}>{inl(b.inl)}</p>;
18
+ if (b.t === 'code') return <pre key={i}><code>{b.v}</code></pre>;
19
+ const L = b.t;
20
+ return <L key={i}>{b.items.map((it, j) => <li key={j}>{inl(it)}</li>)}</L>;
21
+ })}
22
+ </div>
23
+ );
24
+ }
@@ -0,0 +1,135 @@
1
+ import { useEffect, useState, type KeyboardEvent, type RefObject } from 'react';
2
+ import type { NavFeature, NavGroup, NavSection } from '../core/nav.ts';
3
+ import { prefList, setPref } from '../core/prefs.ts';
4
+ import { go, href } from '../core/router.ts';
5
+ import * as indicators from '../core/indicators.ts';
6
+ import { viewKey } from '../types.ts';
7
+ import { useStore } from './hooks.ts';
8
+ import { ClearableInput } from './ClearableInput.tsx';
9
+ import { Icon } from './Icon.tsx';
10
+
11
+ const featureHref = (f: NavFeature) => href.view(f.views[0].module, f.views[0].name);
12
+
13
+ /** Indicator bubbles for a row: its own feature's, or (a collapsed parent) its children's. The first four, then "+N". */
14
+ function Bubbles({ features, pick }: { features: string[]; pick?: (i: import('@tacoshell/sdk').Indicator) => boolean }) {
15
+ const map = useStore(indicators.all);
16
+ const { shown, more } = indicators.bubblesOf(map, features, indicators.MAX_BUBBLES, pick);
17
+ if (!shown.length) return null;
18
+ return (
19
+ <span className="bubbles">
20
+ {shown.map(({ feature, indicator: i }) => <span key={`${feature}|${i.id}`} className="bubble" data-indicator={i.id} style={indicators.styleOf(feature, i)} title={i.title}>{i.text}</span>)}
21
+ {more > 0 && <span className="bubble more">+{more}</span>}
22
+ </span>
23
+ );
24
+ }
25
+
26
+ function Link({ f, active, picked }: { f: NavFeature; active?: string; picked?: string | null }) {
27
+ const on = f.views.some((v) => viewKey(v) === active);
28
+ return <a data-feature={f.key} className={`rail-link${on ? ' active' : ''}${picked === f.key ? ' kbd-sel' : ''}`} href={featureHref(f)}><Icon icon={f.icon} /><span className="rail-text">{f.label}</span><Bubbles features={[f.key]} /></a>;
29
+ }
30
+
31
+ /**
32
+ * A Featured feature (a 2nd-level item). With several views it gets the collapse toggle, collapsed by default (remembered per feature), and its views are the
33
+ * 3rd-level rows beneath it, like a group's features. Indicators with a `view` sit on that view's row while expanded and roll up onto this row while collapsed.
34
+ */
35
+ function FeatureRow({ f, active, picked, forceOpen }: { f: NavFeature; active?: string; picked?: string | null; forceOpen: boolean }) {
36
+ const holdsActive = f.views.some((v) => viewKey(v) === active);
37
+ const [open, setOpen] = useState(() => prefList('nav.featuredOpen').includes(f.key) || holdsActive);
38
+ if (f.views.length < 2) return <Link f={f} active={active} picked={picked} />;
39
+ const toggle = () => {
40
+ const list = prefList('nav.featuredOpen');
41
+ setPref('nav.featuredOpen', open ? list.filter((k) => k !== f.key) : [...list, f.key]);
42
+ setOpen(!open);
43
+ };
44
+ const shown = open || forceOpen;
45
+ return (
46
+ <div className="rail-feature" data-feature-group={f.key}>
47
+ <div className={`rail-link rail-parent${!shown && holdsActive ? ' active' : ''}${picked === f.key ? ' kbd-sel' : ''}`} data-feature={f.key}>
48
+ <button className="rail-toggle" onClick={toggle} aria-expanded={shown} aria-label={`${shown ? 'Collapse' : 'Expand'} ${f.label}`}>{shown ? '▾' : '▸'}</button>
49
+ <a className="rail-parent-link" href={featureHref(f)}><Icon icon={f.icon} /><span className="rail-text">{f.label}</span></a>
50
+ {/* Collapsed: every bubble of the feature (its views' too). Expanded: only the ones that belong to the feature itself. */}
51
+ <Bubbles features={[f.key]} pick={shown ? (i) => !i.view : undefined} />
52
+ </div>
53
+ {shown && f.views.map((v) => (
54
+ <a key={viewKey(v)} className={`rail-link rail-child${viewKey(v) === active ? ' active' : ''}`} data-view={viewKey(v)} href={href.view(v.module, v.name)}>
55
+ <Icon icon={v.icon} /><span className="rail-text">{v.label}</span><Bubbles features={[f.key]} pick={(i) => i.view === v.name} />
56
+ </a>
57
+ ))}
58
+ </div>
59
+ );
60
+ }
61
+
62
+ function Group({ g, active, forceOpen, picked }: { g: NavGroup; active?: string; forceOpen: boolean; picked?: string | null }) {
63
+ const [open, setOpen] = useState(() => !prefList('nav.collapsed').includes(g.key));
64
+ if (g.flat) return <Link f={g.features[0]} active={active} picked={picked} />;
65
+ const toggle = () => {
66
+ const collapsed = prefList('nav.collapsed');
67
+ setPref('nav.collapsed', open ? [...collapsed, g.key] : collapsed.filter((k) => k !== g.key));
68
+ setOpen(!open);
69
+ };
70
+ const shown = open || forceOpen;
71
+ return (
72
+ <div className="rail-group">
73
+ <button className="rail-group-head" onClick={toggle} aria-expanded={shown}><span>{shown ? '▾' : '▸'} {g.label}</span>{!shown && <Bubbles features={g.features.map((f) => f.key)} />}</button>
74
+ {shown && g.features.map((f) => <Link key={f.key} f={f} active={active} picked={picked} />)}
75
+ </div>
76
+ );
77
+ }
78
+
79
+ /** Left rail (ADR-038): Featured (always open; a feature with several views is collapsible) → filter → Tools groups → Services groups A–Z. */
80
+ export function Rail({ section, active, filter, setFilter, filterRef }: { section: NavSection; active?: string; filter: string; setFilter: (s: string) => void; filterRef: RefObject<HTMLInputElement | null> }) {
81
+ const [picked, setPicked] = useState<string | null>(null);
82
+ useEffect(() => setPicked(null), [filter]);
83
+ // What is on display, top to bottom: Featured, then each group's features unless the group is collapsed (a filter opens them all).
84
+ const shownFeatures = (): NavFeature[] => {
85
+ const collapsed = prefList('nav.collapsed');
86
+ const open = (g: NavGroup) => g.flat || !!filter || !collapsed.includes(g.key);
87
+ return [...section.featured, ...[...section.tools, ...section.services].filter(open).flatMap((g) => g.features)];
88
+ };
89
+ // ↑ ↓ move the selection through what is shown; Enter opens it (with a filter typed and nothing picked, the first match).
90
+ const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
91
+ const list = shownFeatures();
92
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
93
+ e.preventDefault();
94
+ if (!list.length) return;
95
+ const i = list.findIndex((f) => f.key === picked);
96
+ const next = list[i < 0 ? (e.key === 'ArrowDown' ? 0 : list.length - 1) : (i + (e.key === 'ArrowDown' ? 1 : list.length - 1)) % list.length];
97
+ setPicked(next.key);
98
+ requestAnimationFrame(() => document.querySelector(`[data-feature="${CSS.escape(next.key)}"]`)?.scrollIntoView({ block: 'nearest' }));
99
+ } else if (e.key === 'Enter') {
100
+ const f = list.find((x) => x.key === picked) ?? (filter.trim() ? list[0] : undefined);
101
+ if (f) { e.preventDefault(); if (go(featureHref(f))) { setPicked(null); e.currentTarget.blur(); } }
102
+ } else if (e.key === 'Escape') { setPicked(null); e.currentTarget.blur(); }
103
+ };
104
+ const empty = !section.featured.length && !section.tools.length && !section.services.length;
105
+ return (
106
+ <nav className="rail">
107
+ {section.featured.length > 0 && <div className="rail-label">Featured</div>}
108
+ {section.featured.map((f) => <FeatureRow key={f.key} f={f} active={active} picked={picked} forceOpen={!!filter} />)}
109
+ <ClearableInput inputRef={filterRef} wrapperClass="rail-filter" placeholder="Filter (⌘/)" aria-label="Filter navigation" value={filter} onValue={setFilter} onKeyDown={onKeyDown} />
110
+ {section.tools.length > 0 && <div className="rail-label">Tools</div>}
111
+ {section.tools.map((g) => <Group key={g.key} g={g} active={active} forceOpen={!!filter} picked={picked} />)}
112
+ {section.services.length > 0 && <div className="rail-label">Services</div>}
113
+ {section.services.map((g) => <Group key={g.key} g={g} active={active} forceOpen={!!filter} picked={picked} />)}
114
+ {empty && <p className="muted small">{filter ? 'Nothing matches the filter.' : 'No views yet. Add one with `taco-cli add component --type=view`.'}</p>}
115
+ </nav>
116
+ );
117
+ }
118
+
119
+ export function SettingsRail({ active }: { active: string }) {
120
+ const items: [string, string, string][] = [
121
+ ['getting-started', 'Getting Started', 'fa-solid fa-flag-checkered'],
122
+ ['services', 'Services', 'fa-solid fa-plug'],
123
+ ['datasets', 'Datasets', 'fa-solid fa-database'],
124
+ ['templates', 'Templates', 'fa-solid fa-file-lines'],
125
+ ['configuration', 'Configuration', 'fa-solid fa-sliders'],
126
+ ['vault', 'Vault & Data', 'fa-solid fa-shield-halved'],
127
+ ['release-notes', 'Release Notes', 'fa-solid fa-clipboard-list'],
128
+ ];
129
+ return (
130
+ <nav className="rail">
131
+ <div className="rail-label">Settings</div>
132
+ {items.map(([id, label, icon]) => <a key={id} className={`rail-link${active === id ? ' active' : ''}`} href={href.settings(id)}><i className={`${icon} rail-icon`} />{label}</a>)}
133
+ </nav>
134
+ );
135
+ }