@tacoshell/shell 0.1.0 → 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.
package/src/ui/Rail.tsx CHANGED
@@ -1,42 +1,88 @@
1
1
  import { useEffect, useState, type KeyboardEvent, type RefObject } from 'react';
2
2
  import type { NavFeature, NavGroup, NavSection } from '../core/nav.ts';
3
- import { pref, setPref } from '../core/prefs.ts';
3
+ import { prefList, setPref } from '../core/prefs.ts';
4
4
  import { go, href } from '../core/router.ts';
5
+ import * as indicators from '../core/indicators.ts';
5
6
  import { viewKey } from '../types.ts';
7
+ import { useStore } from './hooks.ts';
6
8
  import { ClearableInput } from './ClearableInput.tsx';
7
9
  import { Icon } from './Icon.tsx';
8
10
 
9
11
  const featureHref = (f: NavFeature) => href.view(f.views[0].module, f.views[0].name);
10
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
+
11
26
  function Link({ f, active, picked }: { f: NavFeature; active?: string; picked?: string | null }) {
12
27
  const on = f.views.some((v) => viewKey(v) === active);
13
- return <a data-feature={f.key} className={`rail-link${on ? ' active' : ''}${picked === f.key ? ' kbd-sel' : ''}`} href={featureHref(f)}><Icon icon={f.icon} />{f.label}</a>;
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
+ );
14
60
  }
15
61
 
16
62
  function Group({ g, active, forceOpen, picked }: { g: NavGroup; active?: string; forceOpen: boolean; picked?: string | null }) {
17
- const [open, setOpen] = useState(() => !pref<string[]>('nav.collapsed', []).includes(g.key));
63
+ const [open, setOpen] = useState(() => !prefList('nav.collapsed').includes(g.key));
18
64
  if (g.flat) return <Link f={g.features[0]} active={active} picked={picked} />;
19
65
  const toggle = () => {
20
- const collapsed = pref<string[]>('nav.collapsed', []);
66
+ const collapsed = prefList('nav.collapsed');
21
67
  setPref('nav.collapsed', open ? [...collapsed, g.key] : collapsed.filter((k) => k !== g.key));
22
68
  setOpen(!open);
23
69
  };
24
70
  const shown = open || forceOpen;
25
71
  return (
26
72
  <div className="rail-group">
27
- <button className="rail-group-head" onClick={toggle} aria-expanded={shown}>{shown ? '▾' : '▸'} {g.label}</button>
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>
28
74
  {shown && g.features.map((f) => <Link key={f.key} f={f} active={active} picked={picked} />)}
29
75
  </div>
30
76
  );
31
77
  }
32
78
 
33
- /** Left rail (ADR-038): Featured (never collapses) → filter → Tools groups → Services groups A–Z. */
79
+ /** Left rail (ADR-038): Featured (always open; a feature with several views is collapsible) → filter → Tools groups → Services groups A–Z. */
34
80
  export function Rail({ section, active, filter, setFilter, filterRef }: { section: NavSection; active?: string; filter: string; setFilter: (s: string) => void; filterRef: RefObject<HTMLInputElement | null> }) {
35
81
  const [picked, setPicked] = useState<string | null>(null);
36
82
  useEffect(() => setPicked(null), [filter]);
37
83
  // What is on display, top to bottom: Featured, then each group's features unless the group is collapsed (a filter opens them all).
38
84
  const shownFeatures = (): NavFeature[] => {
39
- const collapsed = pref<string[]>('nav.collapsed', []);
85
+ const collapsed = prefList('nav.collapsed');
40
86
  const open = (g: NavGroup) => g.flat || !!filter || !collapsed.includes(g.key);
41
87
  return [...section.featured, ...[...section.tools, ...section.services].filter(open).flatMap((g) => g.features)];
42
88
  };
@@ -59,7 +105,7 @@ export function Rail({ section, active, filter, setFilter, filterRef }: { sectio
59
105
  return (
60
106
  <nav className="rail">
61
107
  {section.featured.length > 0 && <div className="rail-label">Featured</div>}
62
- {section.featured.map((f) => <Link key={f.key} f={f} active={active} picked={picked} />)}
108
+ {section.featured.map((f) => <FeatureRow key={f.key} f={f} active={active} picked={picked} forceOpen={!!filter} />)}
63
109
  <ClearableInput inputRef={filterRef} wrapperClass="rail-filter" placeholder="Filter (⌘/)" aria-label="Filter navigation" value={filter} onValue={setFilter} onKeyDown={onKeyDown} />
64
110
  {section.tools.length > 0 && <div className="rail-label">Tools</div>}
65
111
  {section.tools.map((g) => <Group key={g.key} g={g} active={active} forceOpen={!!filter} picked={picked} />)}
@@ -0,0 +1,57 @@
1
+ import { useState } from 'react';
2
+ import type { Context } from '@tacoshell/sdk';
3
+ import { navigate } from '../core/bus.ts';
4
+ import { actionProblem, buttonContext, targetContext, type CollectedButton } from '../core/contrib.ts';
5
+ import * as log from '../core/log.ts';
6
+ import { currentPage } from '../core/page.ts';
7
+ import { toast } from '../core/toasts.ts';
8
+ import type { RegistryView } from '../types.ts';
9
+ import { ActionModal } from './ActionModal.tsx';
10
+ import { useStore } from './hooks.ts';
11
+ import { useContributions } from './useContrib.ts';
12
+
13
+ /** A Related button: the framework's look for `styleType`, overridden by `styleClass`, overridden by `styleInline`. */
14
+ function ContribButton({ b, onClick }: { b: CollectedButton; onClick: () => void }) {
15
+ const cls = ['rel-btn', b.styleType ? `rel-btn-${b.styleType}` : '', b.styleClass ?? ''].filter(Boolean).join(' ');
16
+ return <button type="button" className={cls} style={b.styleInline} data-style-type={b.styleType} onClick={(e) => { e.stopPropagation(); onClick(); }}>{b.label}</button>;
17
+ }
18
+
19
+ /**
20
+ * Related ▾: appears (left of Tools) once at least one feature contributes, and keeps filling in. Links carry this page's context as `context.referrer`.
21
+ * An entry may also have one button that launches an ACTION in a modal (its own context first, this page's as `referrer`).
22
+ */
23
+ export function RelatedMenu() {
24
+ const page = useStore(currentPage);
25
+ const { items, exposed } = useContributions('related', page);
26
+ const [open, setOpen] = useState(false);
27
+ // Fixed when the button is pressed, so what the page exposes later doesn't rebuild the action's page.
28
+ const [action, setAction] = useState<{ view: RegistryView; context: Context } | null>(null);
29
+ const go = (i: (typeof items)[number]) => { setOpen(false); void navigate({ kind: 'view', module: i.view.module, component: `view:${i.view.name}` }, targetContext(i, exposed)); };
30
+ const launch = (b: CollectedButton) => {
31
+ setOpen(false);
32
+ const context = buttonContext(b, exposed);
33
+ const problem = actionProblem(b.action, context);
34
+ if (problem) { log.add('error', `Related button "${b.label}": context for ${b.action.module}/${b.action.name} doesn't match its declaration (${problem})`, context, b.action.module); toast(`Can't open ${b.action.label}: ${problem}`, 'error'); return; }
35
+ setAction({ view: b.action, context });
36
+ };
37
+ return (
38
+ <>
39
+ {items.length > 0 && (
40
+ <div className="filter" data-menu="related">
41
+ <button className={`bar-btn${open ? ' on' : ''}`} onClick={() => setOpen(!open)} aria-expanded={open}><i className="fa-solid fa-link" /> Related ▾</button>
42
+ {open && (
43
+ <div className="filter-menu" onMouseLeave={() => setOpen(false)}>
44
+ {items.map((i) => (
45
+ <div key={i.id} className="related-row">
46
+ <a className="menu-item" href={i.href} onClick={(e) => { e.preventDefault(); go(i); }}>{i.icon?.startsWith('fa-') ? <i className={i.icon} /> : null} {i.label}</a>
47
+ {i.button && <ContribButton b={i.button} onClick={() => launch(i.button!)} />}
48
+ </div>
49
+ ))}
50
+ </div>
51
+ )}
52
+ </div>
53
+ )}
54
+ {action && <ActionModal view={action.view} context={action.context} onClose={() => setAction(null)} />}
55
+ </>
56
+ );
57
+ }
@@ -3,6 +3,7 @@ import * as services from '../core/services.ts';
3
3
  import * as sessions from '../core/sessions.ts';
4
4
  import { href } from '../core/router.ts';
5
5
  import { serviceKey, type Registry, type RegistryService } from '../types.ts';
6
+ import { toast } from '../core/toasts.ts';
6
7
  import { Icon } from './Icon.tsx';
7
8
  import { useStore } from './hooks.ts';
8
9
 
@@ -67,6 +68,9 @@ function SessionRow({ s, st, onClose }: { s: RegistryService; st?: sessions.Sess
67
68
  <Icon icon={s.icon} />
68
69
  <span className="session-name">{s.label} <span className="muted small">{req}</span></span>
69
70
  <span className={`${level ? `sess-${level}` : 'muted'} small`}>{word}</span>
71
+ {state === 'missing' && sessions.canReauth(s) && (
72
+ <button type="button" className="session-reauth" onClick={(e) => { e.preventDefault(); e.stopPropagation(); void sessions.reauth(s).then((err) => { if (err) toast(`${s.label}: ${err}`, 'error'); }); }}>Sign in again</button>
73
+ )}
70
74
  </a>
71
75
  );
72
76
  }
@@ -9,6 +9,7 @@ import { ClearableInput } from './ClearableInput.tsx';
9
9
  import { Icon } from './Icon.tsx';
10
10
  import { TabBar } from './TabBar.tsx';
11
11
  import { Markdown } from './Markdown.tsx';
12
+ import { RelatedMenu } from './RelatedMenu.tsx';
12
13
  import type { RegistryIcon } from '../types.ts';
13
14
 
14
15
  const logStore = { get: log.getVersion, subscribe: log.subscribe };
@@ -44,7 +45,7 @@ function ToolsMenu() {
44
45
 
45
46
  /**
46
47
  * 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
+ * Refresh · Related ▾ (when features contribute) · Tools ▾ (when the page has any) · Favorite · Log · Help. Tooltips carry the names.
48
49
  */
49
50
  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
51
  useStore(logStore);
@@ -57,6 +58,7 @@ export function SubBar({ tabs, favoriteKey, hasHelp, favoriteOff, onRefresh }: {
57
58
  {(tabs ?? []).length > 1 ? <TabBar tabs={tabs!} /> : <div className="subbar-tabs" />}
58
59
  <div className="subbar-actions">
59
60
  <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>
61
+ <RelatedMenu />
60
62
  <ToolsMenu />
61
63
  {/* Favorite is shown on every page, and is active only on pages that can be starred (views that haven't turned it off). */}
62
64
  <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'}>
@@ -1,4 +1,4 @@
1
- import { Component, useEffect, useMemo, useState, type ReactNode } from 'react';
1
+ import { Component, type ComponentType, useEffect, useMemo, useState, type ReactNode } from 'react';
2
2
  import { createFramework, setSlotRenderer } from '../core/bus.ts';
3
3
  import * as log from '../core/log.ts';
4
4
  import { unmet } from '../core/nav.ts';
@@ -10,10 +10,13 @@ import * as vault from '../core/vault.ts';
10
10
  import * as cards from '../core/cards.ts';
11
11
  import { pref, setPref } from '../core/prefs.ts';
12
12
  import { viewKey, type RegistryCard, type RegistryPanel, type RegistryView } from '../types.ts';
13
+ import type { Framework, ViewProps } from '@tacoshell/sdk';
14
+ import { CsvFeature } from './CsvFeature.tsx';
13
15
  import { Icon } from './Icon.tsx';
16
+ import { ItemFeature } from './ItemFeature.tsx';
14
17
  import { useShell, useStore, type ShellInput } from './hooks.ts';
15
18
 
16
- class Boundary extends Component<{ name: string; quiet?: boolean; children: ReactNode }, { error?: Error }> {
19
+ export class Boundary extends Component<{ name: string; quiet?: boolean; children: ReactNode }, { error?: Error }> {
17
20
  state: { error?: Error } = {};
18
21
  static getDerivedStateFromError(error: Error) { return { error }; }
19
22
  componentDidCatch(error: Error) { log.add('error', `${this.props.name} crashed: ${error.message}`); }
@@ -81,6 +84,39 @@ function CardsRegion({ page, view }: { page: Page; view: RegistryView }) {
81
84
  // Registered once, before any view renders: registering it in an effect left a view's first paint without its panels.
82
85
  setSlotRenderer((p, name) => <SlotHost page={p} name={name} />);
83
86
 
87
+
88
+ /** The view itself, or the screen that explains why it can't run yet. Shared by pages and ACTION modals. Standard feature types (CSV, ITEM) are rendered by the framework from the entry's definition. */
89
+ export function ViewBody({ view, page, framework }: { view: RegistryView; page: Page; framework: Framework }) {
90
+ const input = useShell();
91
+ useStore(services.states);
92
+ const key = viewKey(view);
93
+ const vaultState = useStore({ get: vault.status, subscribe: (fn) => vault.subscribe(fn) });
94
+ const missing = unmet(view, services.isUsable);
95
+ if (missing.length) {
96
+ return (
97
+ <div className="card">
98
+ <h2>Set up {missing.length === 1 ? 'a service' : 'services'} first</h2>
99
+ <p className="muted">This view needs:</p>
100
+ <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>
101
+ <p className="muted">Set it up, then come back here.</p>
102
+ </div>
103
+ );
104
+ }
105
+ const needsVault = view.requires.some((r) => { const s = services.find(r.type, r.name); return !!s && services.stateOf(s).mode !== 'session'; });
106
+ 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>;
107
+
108
+ const entry = input.views[key];
109
+ if (view.viewType === 'ITEMS') return <div className="card"><h2>{view.label}</h2><p className="muted">The ITEMS feature type is reserved and not implemented yet.</p></div>;
110
+ if (!entry) return <div className="card"><h2>{view.label}</h2><p className="muted">This view has no component (taco.module.json › entry).</p></div>;
111
+ const context = page.viewContext.get();
112
+ const def = typeof entry === 'function' ? undefined : entry;
113
+ if (def && view.viewType === 'CSV' && def.kind === 'csv') return <Boundary name={`View ${key}`}><CsvFeature def={def} framework={framework} view={view} /></Boundary>;
114
+ if (def && view.viewType === 'ITEM' && def.kind === 'item') return <Boundary name={`View ${key}`}><ItemFeature def={def} framework={framework} page={page} context={context} /></Boundary>;
115
+ if (def || view.viewType === 'CSV' || view.viewType === 'ITEM') return <div className="card danger"><strong>{view.label} is a {view.viewType} view</strong><p className="muted">Its entry must export default {view.viewType === 'CSV' ? 'defineCsvFeature({ … })' : 'defineItemFeature({ … })'}.</p></div>;
116
+ const View = entry as ComponentType<ViewProps>;
117
+ return <Boundary name={`View ${key}`}><View framework={framework} context={context} /></Boundary>;
118
+ }
119
+
84
120
  /** Mounts a module view with its page and framework instance, or the screen that explains why it can't run yet. */
85
121
  export function ViewHost({ view }: { view: RegistryView }) {
86
122
  const input = useShell();
@@ -102,21 +138,5 @@ export function ViewHost({ view }: { view: RegistryView }) {
102
138
  return () => { removeSystem.forEach((r) => r()); router.setLiveHandler(key, null); if (currentPage.get() === page) currentPage.set(null); };
103
139
  }, [page, key, input, view.tools]);
104
140
 
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} /></>;
141
+ return <><ViewBody view={view} page={page} framework={framework} /><CardsRegion page={page} view={view} /></>;
122
142
  }
package/src/ui/hooks.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { createContext, useContext, useSyncExternalStore, type ComponentType } from 'react';
2
- import type { CardProps, PanelProps, Routine, ServiceImpl, ViewProps } from '@tacoshell/sdk';
2
+ import type { BackgroundJob, CardProps, FeatureDef, PanelProps, Routine, ServiceImpl, SettingsTabProps, ViewProps } from '@tacoshell/sdk';
3
+ import type { Handlers } from '../core/contrib.ts';
3
4
  import type { Registry } from '../types.ts';
4
5
 
5
6
  export const useStore = <T,>(s: { get: () => T; subscribe: (fn: () => void) => () => void }) => useSyncExternalStore(s.subscribe, s.get);
@@ -7,13 +8,19 @@ export const useStore = <T,>(s: { get: () => T; subscribe: (fn: () => void) => (
7
8
  export interface ShellInput {
8
9
  registry: Registry;
9
10
  /** View components by `<module>/<view>` (generated entry). */
10
- views: Record<string, ComponentType<ViewProps>>;
11
+ views: Record<string, ComponentType<ViewProps> | FeatureDef>;
12
+ /** Each view entry's named exports (`contributeRelated`, `contributeActions`) by `<module>/<view>`. */
13
+ handlers?: Handlers;
14
+ /** Background jobs by `<module>/<view>`. */
15
+ background?: Record<string, BackgroundJob>;
11
16
  /** Service implementations by `<type>/<name>`. */
12
17
  services: Record<string, ServiceImpl>;
13
18
  /** Panel components by `<module>/<panel>` (ADR-053). */
14
19
  panels?: Record<string, ComponentType<PanelProps>>;
15
20
  /** Card components by `<module>/<card>` (ADR-062). */
16
21
  cards?: Record<string, ComponentType<CardProps<any>>>;
22
+ /** Settings tab components by `<module>/<tab>` (ADR-072). */
23
+ settingsTabs?: Record<string, ComponentType<SettingsTabProps>>;
17
24
  /** Refreshable datasets' routines by `<module>/<dataset>` (ADR-043). */
18
25
  routines?: Record<string, Routine>;
19
26
  }
@@ -108,6 +108,13 @@ function DatasetCard({ d }: { d: RegistryDataset }) {
108
108
  });
109
109
  const columns = st.columns.length ? st.columns : Object.keys(d.schema ?? {});
110
110
  const est = datasets.estimateMs(d);
111
+ const prog = useStore(datasets.progressNow)[datasets.idOf(d)];
112
+ const cancelling = !!prog?.cancelling;
113
+ const load = datasets.loadOf(d);
114
+ const go = (ask?: 'full') => run(async () => {
115
+ try { const n = await datasets.refresh(d, createFramework(d.module), { load: ask }); toast(`${d.label} ${load === 'incremental' && !ask ? 'updated' : 'refreshed'}: ${n} row(s) loaded.`); }
116
+ catch (e) { if ((e as Error).message === 'Cancelled') toast(`${d.label}: refresh cancelled.`); else throw e; }
117
+ });
111
118
  return (
112
119
  <div className="card dataset">
113
120
  <div className="dataset-head">
@@ -118,14 +125,17 @@ function DatasetCard({ d }: { d: RegistryDataset }) {
118
125
  {d.kind === 'refreshable' && <Schedule d={d} onEdit={() => setScheduling(true)} />}
119
126
  {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
127
  onSave={(cron) => datasets.setSchedule(d, cron)} onClose={() => setScheduling(false)} />}
128
+ {st.refreshing && <p className="muted small dataset-progress" role="status"><i className="fa-solid fa-circle-notch fa-spin" /> {prog?.text ?? 'Working…'}</p>}
121
129
  {st.lastError && <p className="error small">Last refresh failed: {st.lastError}</p>}
122
130
  <div className="actions">
123
131
  <button className="primary" disabled={busy} onClick={() => file.current?.click()}><i className="fa-solid fa-file-csv" /> Import CSV</button>
124
132
  <input ref={file} type="file" accept=".csv,text/csv" hidden onChange={(e) => void stageFile(e.target.files?.[0])} />
125
133
  {pending && <ImportConfirm d={d} p={pending} busy={busy} onCancel={() => setPending(null)} onConfirm={() => void confirmImport()} />}
126
134
  <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>}
135
+ {d.kind === 'refreshable' && <button disabled={busy || st.refreshing || !datasets.hasRoutine(d)} onClick={() => void go()}>
136
+ <i className={`fa-solid fa-rotate${st.refreshing ? ' fa-spin' : ''}`} /> {st.refreshing ? 'Refreshing…' : d.incremental && load === 'incremental' ? 'Refresh now (incremental)' : 'Refresh now'}{est && !st.refreshing ? ` (~${Math.max(1, Math.round(est / 1000))} s)` : ''}</button>}
137
+ {d.kind === 'refreshable' && d.incremental && !st.refreshing && st.rows > 0 && <button disabled={busy || !datasets.hasRoutine(d)} title="Replace every row instead of loading only what changed" onClick={() => void go('full')}><i className="fa-solid fa-arrows-rotate" /> Full Load</button>}
138
+ {st.refreshing && <button className="danger" disabled={cancelling} onClick={() => datasets.cancel(d)}>{cancelling ? 'Cancelling…' : 'Cancel'}</button>}
129
139
  <button disabled={busy || !st.rows} onClick={() => void toggle('preview')}>{open === 'preview' ? 'Hide preview' : 'Preview'}</button>
130
140
  <button onClick={() => void toggle('schema')}>{open === 'schema' ? 'Hide schema' : 'Schema'}</button>
131
141
  {d.instructionsText && <button onClick={() => void toggle('instructions')}>{open === 'instructions' ? 'Hide instructions' : 'Instructions'}</button>}
@@ -1,19 +1,96 @@
1
+ import { useEffect, useState } from 'react';
2
+ import { href } from '../../core/router.ts';
1
3
  import { useShell } from '../hooks.ts';
4
+ import { ContributedTab, TabStrip, tabKey, useContributedTabs } from './SettingsTabs.tsx';
2
5
  import { Markdown } from '../Markdown.tsx';
3
6
 
7
+ /** What the build writes to `sbom.json` (CycloneDX 1.5): only the fields this page shows. */
8
+ interface Bom {
9
+ serialNumber?: string; specVersion?: string;
10
+ metadata?: { timestamp?: string; component?: { name?: string; version?: string } };
11
+ components?: { name: string; version: string; type: string; purl?: string; licenses?: ({ license: { id?: string; name?: string } } | { expression: string })[]; properties?: { name: string; value: string }[] }[];
12
+ services?: { name: string; description?: string; endpoints?: string[]; properties?: { name: string; value: string }[] }[];
13
+ }
14
+ const ORIGIN: Record<string, string> = { framework: 'Framework', module: 'Taco module', dependency: 'Dependency', external: 'External tool' };
15
+ const originOf = (c: NonNullable<Bom['components']>[number]) => ORIGIN[c.properties?.find((p) => p.name === 'taco:origin')?.value ?? ''] ?? 'Dependency';
16
+ const licenseOf = (c: NonNullable<Bom['components']>[number]) => (c.licenses ?? []).map((l) => ('expression' in l ? l.expression : l.license.id ?? l.license.name ?? '')).filter(Boolean).join(', ') || 'unknown';
17
+
18
+ /** Settings → Release Notes → SBOM: the external dependencies the build shipped, as a table, with the CycloneDX JSON to download. */
19
+ function SbomTab() {
20
+ const { registry } = useShell();
21
+ const [bom, setBom] = useState<Bom | null>(null);
22
+ const [error, setError] = useState<string | null>(null);
23
+ useEffect(() => {
24
+ let stop = false;
25
+ fetch('sbom.json').then((r) => (r.ok ? r.json() : Promise.reject(new Error(`sbom.json is missing from this build (${r.status}). Build with taco-cli deploy.`)))).then((b) => { if (!stop) setBom(b); }).catch((e: Error) => { if (!stop) setError(e.message); });
26
+ return () => { stop = true; };
27
+ }, []);
28
+ if (error) return <div className="card"><p className="muted">{error}</p></div>;
29
+ if (!bom) return <p className="muted">Loading…</p>;
30
+ const components = bom.components ?? [], services = bom.services ?? [];
31
+ const counts = (o: string) => components.filter((c) => originOf(c) === o).length;
32
+ return (
33
+ <div data-testid="sbom">
34
+ <p className="muted">
35
+ Everything that ships inside {registry.app.displayName} v{registry.app.version}: {components.length} component(s) ({counts('Dependency')} external dependencies, {counts('External tool')} external tools, {counts('Framework')} framework, {counts('Taco module')} Taco modules)
36
+ and {services.length} external service(s). Generated by the build{bom.metadata?.timestamp ? ` on ${new Date(bom.metadata.timestamp).toLocaleString()}` : ''}.
37
+ </p>
38
+ <p><a className="button-link" href="sbom.json" download={`${registry.app.name}-${registry.app.version}.cdx.json`} data-sbom-download><i className="fa-solid fa-download" /> Download SBOM (CycloneDX {bom.specVersion ?? '1.5'} JSON)</a></p>
39
+ <div className="table-wrap">
40
+ <table className="sbom-table">
41
+ <thead><tr><th>Component</th><th>Version</th><th>Origin</th><th>License</th><th>Package URL</th></tr></thead>
42
+ <tbody>
43
+ {components.map((c) => (
44
+ <tr key={`${c.name}@${c.version}`} data-component={c.name}>
45
+ <td><strong>{c.name}</strong></td><td>{c.version}</td><td>{originOf(c)}</td><td>{licenseOf(c)}</td><td><code className="small">{c.purl}</code></td>
46
+ </tr>
47
+ ))}
48
+ </tbody>
49
+ </table>
50
+ </div>
51
+ {services.length > 0 && (
52
+ <>
53
+ <h2>External services</h2>
54
+ <div className="table-wrap">
55
+ <table className="sbom-table">
56
+ <thead><tr><th>Service</th><th>Endpoints</th><th>Provided by</th></tr></thead>
57
+ <tbody>
58
+ {services.map((s) => (
59
+ <tr key={s.name} data-service={s.name}><td><strong>{s.name}</strong></td><td>{(s.endpoints ?? []).join(', ')}</td><td>{s.properties?.find((p) => p.name === 'taco:module')?.value}</td></tr>
60
+ ))}
61
+ </tbody>
62
+ </table>
63
+ </div>
64
+ </>
65
+ )}
66
+ </div>
67
+ );
68
+ }
69
+
4
70
  /**
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.
71
+ * Settings → Release Notes: the app's `self/docs/release-notes.md`, newest first (tab "Release Notes"), and the SBOM of what the build shipped (tab "SBOM").
72
+ * Written by hand for now (`taco-cli deploy --release` adds the heading); the shape `## vX.Y.Z — date` + `- change ([#12](…))` is what a generator can fill later.
7
73
  */
8
- export function ReleaseNotesPage() {
74
+ export function ReleaseNotesPage({ tab = 'notes' }: { tab?: string }) {
9
75
  const { registry } = useShell();
76
+ const contributed = useContributedTabs('release-notes');
77
+ const extra = contributed.find((t) => tabKey(t) === tab);
78
+ const strip = <TabStrip page="release-notes" core={[{ id: 'notes', label: 'Release Notes', href: href.settings('release-notes') }, { id: 'sbom', label: 'SBOM', href: href.settings('release-notes', 'sbom') }]} contributed={contributed} active={extra ? tabKey(extra) : tab === 'sbom' ? 'sbom' : 'notes'} />;
79
+ if (extra) return <>{strip}<ContributedTab tab={extra} /></>;
10
80
  return (
81
+ <>
82
+ {strip}
11
83
  <div className="page">
12
84
  <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>}
85
+ {tab === 'sbom' ? <SbomTab /> : (
86
+ <>
87
+ <p className="muted">What changed in each version of {registry.app.displayName}, newest first. You are on <strong>v{registry.app.version}</strong>.</p>
88
+ {registry.releaseNotesText?.trim()
89
+ ? <div className="card release-notes"><Markdown text={registry.releaseNotesText} /></div>
90
+ : <div className="card"><p className="muted">No release notes yet. Write them in <code>self/docs/release-notes.md</code>.</p></div>}
91
+ </>
92
+ )}
17
93
  </div>
94
+ </>
18
95
  );
19
96
  }
@@ -13,7 +13,7 @@ import { serviceKey, viewKey, type AuthMode, type RegistryService, type Registry
13
13
  import { useShell, useStore } from '../hooks.ts';
14
14
  import { Markdown } from '../Markdown.tsx';
15
15
 
16
- const MODE_LABEL: Record<AuthMode, string> = { session: 'Browser session', apikey: 'API key', basic: 'HTTP Basic', oauth: 'OAuth (PKCE)' };
16
+ const MODE_LABEL: Record<AuthMode, string> = { session: 'Browser session', apikey: 'API key', basic: 'HTTP Basic', none: 'No sign-in', oauth: 'OAuth (PKCE)' };
17
17
  const vaultStore = { get: vault.status, subscribe: (fn: () => void) => vault.subscribe(fn) };
18
18
 
19
19
  export function GettingStarted() {
@@ -58,6 +58,7 @@ function statusOf(s: RegistryService) {
58
58
  if (!st.enabled) return { cls: 'off', text: 'Off' };
59
59
  if (!services.isConfigured(s)) return { cls: 'warn', text: 'Not set up' };
60
60
  if (st.lastTest && !st.lastTest.ok) return { cls: 'bad', text: 'Test failed' };
61
+ if (st.lastTest?.status === 'warn') return { cls: 'warn', text: 'Warning' };
61
62
  return { cls: 'ok', text: st.lastTest?.ok ? 'Connected' : 'Set up' };
62
63
  }
63
64
 
@@ -81,20 +82,6 @@ export function ServicesList() {
81
82
  );
82
83
  }
83
84
 
84
- function SecretInput({ s, field, label }: { s: RegistryService; field: string; label: string }) {
85
- const [value, setValue] = useState('');
86
- const set = services.isConfigured(s) || vault.has(services.secretId(s, field));
87
- const save = async () => { await vault.put(services.secretId(s, field), value); setValue(''); toast(`${label} saved in the vault.`); await services.update(s, {}); };
88
- return (
89
- <div className="form-row">
90
- <label>{label}</label>
91
- <input type="password" placeholder={vault.has(services.secretId(s, field)) ? '•••• saved (type to replace)' : 'Not set'} value={value} onChange={(e) => setValue(e.target.value)} />
92
- <button disabled={!value} onClick={() => void save()}>Save</button>
93
- {set && <span className="muted small">stored encrypted</span>}
94
- </div>
95
- );
96
- }
97
-
98
85
  /** Level 3: Settings → Services → <service>, generated from the declaration (ADR-032). */
99
86
  export function ServicePage({ type, name }: { type: string; name: string }) {
100
87
  const { registry } = useShell();
@@ -102,9 +89,25 @@ export function ServicePage({ type, name }: { type: string; name: string }) {
102
89
  useStore(vaultStore);
103
90
  const s = services.find(type, name);
104
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>>({});
105
94
  if (!s) return <div className="page"><h1>Not found</h1><p className="muted">No service {type}/{name} in this app.</p></div>;
106
95
  const st = services.stateOf(s);
107
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
+ };
108
111
  const run = async (what: () => Promise<unknown>) => { setBusy(true); try { await what(); } catch (e) { toast((e as Error).message, 'error'); } finally { setBusy(false); } };
109
112
  return (
110
113
  <div className="page">
@@ -118,14 +121,17 @@ export function ServicePage({ type, name }: { type: string; name: string }) {
118
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>
119
122
  </div>
120
123
  )}
121
- {services.fieldsFor(s, st.mode).map((f) => f.secret
122
- ? <SecretInput key={f.key} s={s} field={f.key} label={f.label ?? f.key} />
123
- : (
124
- <div className="form-row" key={f.key}>
125
- <label>{f.label ?? f.key}</label>
126
- <input defaultValue={st.config[f.key] ?? ''} placeholder={f.placeholder} onBlur={(e) => void services.update(s, { config: { ...services.stateOf(s).config, [f.key]: e.target.value.trim() } })} />
127
- </div>
128
- ))}
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
+ ))}
129
135
  {st.mode === 'session' && (
130
136
  <>
131
137
  <p className="muted small">Uses your signed-in browser session for {s.hosts.join(', ')}. Sign in there first.</p>
@@ -140,8 +146,13 @@ export function ServicePage({ type, name }: { type: string; name: string }) {
140
146
  <button disabled={busy} onClick={() => void run(() => services.connectOAuth(s))}>{vault.has(services.secretId(s, 'accessToken')) ? 'Reconnect' : 'Connect'}</button>
141
147
  </div>
142
148
  )}
143
- <div className="actions"><button className="primary" disabled={busy || !st.enabled} onClick={() => void run(async () => { const r = await services.test(s); toast(r.detail, r.ok ? 'info' : 'error'); })}>Test</button>
144
- {st.lastTest && <span className="muted small">Last test {new Date(st.lastTest.at).toLocaleString()}: {st.lastTest.detail}</span>}</div>
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>
145
156
  </div>
146
157
  <div className="card"><h2>How to set it up</h2><Markdown text={s.howToText} /></div>
147
158
  </div>