@tacoshell/shell 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/LICENSE +28 -0
  2. package/README.md +6 -2
  3. package/package.json +40 -4
  4. package/src/background.ts +41 -0
  5. package/src/core/bus.ts +210 -0
  6. package/src/core/cards.ts +33 -0
  7. package/src/core/contrib.ts +70 -0
  8. package/src/core/cron.ts +63 -0
  9. package/src/core/cronfriendly.ts +70 -0
  10. package/src/core/csv.ts +36 -0
  11. package/src/core/csvfeature.ts +57 -0
  12. package/src/core/datasets.ts +367 -0
  13. package/src/core/domshot.ts +81 -0
  14. package/src/core/guards.ts +36 -0
  15. package/src/core/hosts.ts +15 -0
  16. package/src/core/hotkeys.ts +44 -0
  17. package/src/core/indicators.ts +62 -0
  18. package/src/core/jobs.ts +37 -0
  19. package/src/core/localdata.ts +88 -0
  20. package/src/core/log.ts +91 -0
  21. package/src/core/markdown.ts +57 -0
  22. package/src/core/nav.ts +105 -0
  23. package/src/core/notifyrules.ts +31 -0
  24. package/src/core/page.ts +91 -0
  25. package/src/core/prefs.ts +119 -0
  26. package/src/core/router.ts +78 -0
  27. package/src/core/search.ts +65 -0
  28. package/src/core/services.ts +178 -0
  29. package/src/core/sessions.ts +93 -0
  30. package/src/core/startpage.ts +28 -0
  31. package/src/core/storage.ts +54 -0
  32. package/src/core/systemtools.ts +85 -0
  33. package/src/core/tabfit.ts +30 -0
  34. package/src/core/templates.ts +48 -0
  35. package/src/core/text.ts +6 -0
  36. package/src/core/toasts.ts +13 -0
  37. package/src/core/vault.ts +208 -0
  38. package/src/env.d.ts +2 -0
  39. package/src/index.ts +58 -0
  40. package/src/styles.css +391 -0
  41. package/src/types.ts +133 -0
  42. package/src/ui/ActionModal.tsx +22 -0
  43. package/src/ui/App.tsx +241 -0
  44. package/src/ui/ClearableInput.tsx +23 -0
  45. package/src/ui/CsvFeature.tsx +151 -0
  46. package/src/ui/Icon.tsx +8 -0
  47. package/src/ui/ItemFeature.tsx +39 -0
  48. package/src/ui/Markdown.tsx +24 -0
  49. package/src/ui/Rail.tsx +135 -0
  50. package/src/ui/RelatedMenu.tsx +57 -0
  51. package/src/ui/Search.tsx +111 -0
  52. package/src/ui/Sessions.tsx +76 -0
  53. package/src/ui/SidePanel.tsx +150 -0
  54. package/src/ui/TabBar.tsx +56 -0
  55. package/src/ui/ViewHost.tsx +142 -0
  56. package/src/ui/hooks.ts +28 -0
  57. package/src/ui/settings/Datasets.tsx +172 -0
  58. package/src/ui/settings/ReleaseNotes.tsx +96 -0
  59. package/src/ui/settings/ScheduleEditor.tsx +57 -0
  60. package/src/ui/settings/Settings.tsx +339 -0
  61. package/src/ui/settings/SettingsTabs.tsx +63 -0
  62. package/src/ui/settings/Templates.tsx +52 -0
  63. package/src/ui/useContrib.ts +36 -0
@@ -0,0 +1,62 @@
1
+ // Indicator bubbles (left navigation): any feature may have any number, set from its view or its background job.
2
+ // State is per feature (`<module>::<feature>`, the nav feature key), in memory only: a background job repopulates it.
3
+
4
+ import type { Indicator, Indicators } from '@tacoshell/sdk';
5
+ import { createStore } from './prefs.ts';
6
+ import { clipText } from './text.ts';
7
+
8
+ export const PALETTE_SIZE = 16;
9
+ export const MAX_BUBBLES = 4;
10
+ export const MAX_CHARS = 4;
11
+
12
+ export const all = createStore<Record<string, Indicator[]>>({});
13
+
14
+ /** At most 4 characters; emoji and other multi-code-unit characters count once. */
15
+ export const clip = (text: string): string => clipText(text, MAX_CHARS);
16
+
17
+ const put = (feature: string, list: Indicator[]) => { const next = { ...all.get() }; if (list.length) next[feature] = list; else delete next[feature]; all.set(next); };
18
+ const same = (a: Indicator, b: Indicator) => a.id === b.id && a.text === b.text && a.color === b.color && a.background === b.background && a.title === b.title && a.view === b.view;
19
+
20
+ /** The API a feature gets as `framework.indicators`. */
21
+ export function forFeature(feature: string | undefined): Indicators {
22
+ const get = () => (feature ? all.get()[feature] ?? [] : []);
23
+ return {
24
+ add(i) {
25
+ if (!feature) return;
26
+ const next = { ...i, text: clip(i.text) };
27
+ const cur = get();
28
+ const old = cur.find((x) => x.id === i.id);
29
+ if (old && same(old, next)) return;
30
+ put(feature, [...cur.filter((x) => x.id !== i.id), next]);
31
+ },
32
+ update(id, patch) {
33
+ if (!feature) return;
34
+ const cur = get();
35
+ if (!cur.some((x) => x.id === id)) return;
36
+ put(feature, cur.map((x) => (x.id === id ? { ...x, ...patch, ...(patch.text !== undefined ? { text: clip(patch.text) } : {}), id } : x)));
37
+ },
38
+ remove(id) { if (feature && get().some((x) => x.id === id)) put(feature, get().filter((x) => x.id !== id)); },
39
+ clear() { if (feature && get().length) put(feature, []); },
40
+ list: () => [...get()],
41
+ };
42
+ }
43
+
44
+ /** Stable palette slot (0–15) for an indicator, so its color doesn't change between renders. */
45
+ export function slotOf(feature: string, id: string): number {
46
+ let h = 0;
47
+ for (const ch of `${feature}|${id}`) h = (h * 31 + ch.charCodeAt(0)) >>> 0;
48
+ return h % PALETTE_SIZE;
49
+ }
50
+
51
+ /** CSS colors: the indicator's own, else the theme's `--taco-ind-N-bg` / `-fg` pair. */
52
+ export const styleOf = (feature: string, i: Indicator) => {
53
+ const n = slotOf(feature, i.id) + 1;
54
+ return { background: i.background ?? `var(--taco-ind-${n}-bg)`, color: i.color ?? `var(--taco-ind-${n}-fg)` };
55
+ };
56
+
57
+ export interface Bubble { feature: string; indicator: Indicator }
58
+ /** Bubbles of the given features (a row's own, or a collapsed parent's children) in order: the first `max`, and how many more there are. */
59
+ export function bubblesOf(map: Record<string, Indicator[]>, features: string[], max = MAX_BUBBLES, pick: (i: Indicator) => boolean = () => true): { shown: Bubble[]; more: number } {
60
+ const every = features.flatMap((feature) => (map[feature] ?? []).filter(pick).map((indicator) => ({ feature, indicator })));
61
+ return { shown: every.slice(0, max), more: Math.max(0, every.length - max) };
62
+ }
@@ -0,0 +1,37 @@
1
+ // Feature background jobs (manifest `background: { entry, everySeconds }`): run inside the app, like dataset refreshes, one at a time and only
2
+ // while the vault is unlocked. They typically update `framework.indicators`. Anything they log goes to the Activity Log.
3
+
4
+ import type { BackgroundJob, Framework } from '@tacoshell/sdk';
5
+ import * as log from './log.ts';
6
+ import * as services from './services.ts';
7
+ import * as vault from './vault.ts';
8
+ import { viewKey, type Registry } from '../types.ts';
9
+
10
+ export function startJobs(reg: Registry, jobs: Record<string, BackgroundJob>, framework: (module: string, featureView: string) => Framework, tickMs = 5_000): () => void {
11
+ const due = new Map<string, number>();
12
+ let running = false;
13
+ const tick = async () => {
14
+ if (running || vault.status() !== 'unlocked') return;
15
+ running = true;
16
+ try {
17
+ for (const v of reg.views) {
18
+ const job = jobs[viewKey(v)];
19
+ if (!job || !v.background) continue;
20
+ const key = viewKey(v);
21
+ if ((due.get(key) ?? 0) > Date.now()) continue;
22
+ due.set(key, Date.now() + Math.max(10, v.background.everySeconds) * 1000);
23
+ try { await job.run({ framework: framework(v.module, v.name), log: log.logger(`Background › ${v.label}`) }); }
24
+ catch (e) { log.add('error', `Background job for ${v.label} failed: ${(e as Error).message}`, undefined, `Background › ${v.label}`); }
25
+ if (vault.status() !== 'unlocked') break;
26
+ }
27
+ } finally { running = false; }
28
+ };
29
+ const timer = setInterval(() => void tick(), tickMs);
30
+ const off = vault.subscribe((s) => { if (s === 'unlocked') void tick(); });
31
+ // What a job shows (counts, indicators) depends on its services' settings: when one is saved, turned on / off or tested, every job runs again soon
32
+ // (debounced, so Save followed by Test is one re-run).
33
+ let rerun: ReturnType<typeof setTimeout> | undefined;
34
+ const offServices = services.states.subscribe(() => { clearTimeout(rerun); rerun = setTimeout(() => { due.clear(); void tick(); }, 500); });
35
+ void tick();
36
+ return () => { clearInterval(timer); clearTimeout(rerun); off(); offServices(); };
37
+ }
@@ -0,0 +1,88 @@
1
+ // Local data management (from v2 config/localdata.js + Settings › Manage Local Data / Clear All Local Data / Share setup).
2
+ // Everything the app keeps in this browser, what each collection is, and how to clear it, plus export / import of NON-secret configuration.
3
+
4
+ import * as log from './log.ts';
5
+ import { favorites, settings, SETTINGS_KEY, updateSettings, type UserSettings } from './prefs.ts';
6
+ import * as services from './services.ts';
7
+ import * as store from './storage.ts';
8
+ import * as vault from './vault.ts';
9
+ import type { Registry } from '../types.ts';
10
+
11
+ export interface Collection { id: string; label: string; description: string; caution?: boolean; clear(): Promise<void> }
12
+
13
+ const uiPrefKeys = () => (typeof localStorage === 'undefined' ? [] : Object.keys(localStorage).filter((k) => k.startsWith('taco.') && k !== 'taco.favorites'));
14
+
15
+ export const collections: Collection[] = [
16
+ { id: 'favorites', label: 'Favorites', description: 'Your starred pages and their order. Clearing removes every favorite.',
17
+ async clear() { favorites.set([]); localStorage.removeItem('taco.favorites'); } },
18
+ { id: 'ui', label: 'Layout preferences', description: 'Panel widths, which panel is open, collapsed groups and filters. Clearing restores the defaults.',
19
+ async clear() { for (const k of uiPrefKeys()) localStorage.removeItem(k); } },
20
+ { id: 'settings', label: 'Configuration', description: 'Theme, notification and HotKey choices, the idle lock and the Activity Log levels. Clearing restores the defaults.',
21
+ async clear() { await store.remove('local', SETTINGS_KEY); } },
22
+ { id: 'log', label: 'Activity Log', description: 'The saved Activity Log entries (the last 500).',
23
+ async clear() { log.clear(); await store.remove('local', 'taco.log'); } },
24
+ { id: 'services', label: 'Service settings (advanced)', description: 'Non-secret service details: on/off, sign-in mode, fields such as site names, last test results. Secrets in the vault are kept, but you will re-enter the details.', caution: true,
25
+ async clear() { await store.remove('local', 'taco.services'); } },
26
+ ];
27
+
28
+ /** Clear All Local Data: every collection AND the vault (secrets, module data). The page reloads afterwards. */
29
+ export async function clearAll() {
30
+ for (const c of collections) await c.clear();
31
+ await vault.destroy();
32
+ for (const k of ['taco.lastActivity', 'taco.lockReason', 'taco.notifyOpen']) await store.remove('session', k);
33
+ }
34
+
35
+ // ── Share setup: export / import (never secrets) ──────────────────────────────────────────────────────────────────
36
+
37
+ export interface SetupFile { format: 'taco-setup'; version: 1; app: string; settings: Omit<UserSettings, 'notifications'> & { notifications: Omit<UserSettings['notifications'], 'items'> & { items: Record<string, boolean> } }; services: Record<string, { enabled: boolean; mode: string; config: Record<string, string> }> }
38
+
39
+ export function exportSetup(reg: Registry): SetupFile {
40
+ const svc: SetupFile['services'] = {};
41
+ for (const s of reg.services) {
42
+ const st = services.stateOf(s);
43
+ // Only fields the service declares as non-secret: a secret can't leak even if someone typed it into the wrong box.
44
+ const allowed = new Set(services.fieldsFor(s, st.mode).filter((f) => !f.secret).map((f) => f.key));
45
+ svc[`${s.type}/${s.name}`] = { enabled: st.enabled, mode: st.mode, config: Object.fromEntries(Object.entries(st.config).filter(([k]) => allowed.has(k))) };
46
+ }
47
+ return { format: 'taco-setup', version: 1, app: reg.app.name, settings: settings.get(), services: svc };
48
+ }
49
+
50
+ /** Applies an exported setup. Unknown services and fields are ignored; nothing in it can reach the vault. Returns what was applied. */
51
+ export async function importSetup(reg: Registry, raw: unknown): Promise<string[]> {
52
+ const f = raw as Partial<SetupFile>;
53
+ if (!f || f.format !== 'taco-setup' || f.version !== 1) throw new Error('This is not a Taco setup file.');
54
+ const applied: string[] = [];
55
+ for (const [key, v] of Object.entries(f.services ?? {})) {
56
+ const [type, name] = key.split('/');
57
+ const s = services.find(type, name);
58
+ if (!s || typeof v !== 'object' || !v) continue;
59
+ const mode = s.auth.includes(v.mode as never) ? (v.mode as typeof s.auth[number]) : services.stateOf(s).mode;
60
+ const allowed = new Set(services.fieldsFor(s, mode).filter((x) => !x.secret).map((x) => x.key));
61
+ const config = Object.fromEntries(Object.entries(v.config ?? {}).filter(([k, val]) => allowed.has(k) && typeof val === 'string'));
62
+ await services.update(s, { enabled: v.enabled !== false, mode, config: { ...services.stateOf(s).config, ...config } });
63
+ applied.push(`${s.label} (${key})`);
64
+ }
65
+ if (f.settings) {
66
+ const cur = settings.get();
67
+ const next: UserSettings = {
68
+ theme: ['dark', 'light', 'system'].includes(f.settings.theme) ? f.settings.theme : cur.theme,
69
+ idleLockMinutes: Number.isFinite(f.settings.idleLockMinutes) ? f.settings.idleLockMinutes : cur.idleLockMinutes,
70
+ visibleLevels: Array.isArray(f.settings.visibleLevels) ? f.settings.visibleLevels.filter((l) => typeof l === 'string') : cur.visibleLevels,
71
+ notifications: { ...cur.notifications, ...(f.settings.notifications ?? {}) },
72
+ confirmLock: typeof f.settings.confirmLock === 'boolean' ? f.settings.confirmLock : cur.confirmLock,
73
+ startPage: f.settings.startPage === null || typeof f.settings.startPage === 'string' ? f.settings.startPage : cur.startPage,
74
+ hotkeys: { enabled: f.settings.hotkeys?.enabled ?? cur.hotkeys.enabled, map: { ...(f.settings.hotkeys?.map ?? cur.hotkeys.map) } },
75
+ };
76
+ await updateSettings(next);
77
+ applied.push('Configuration');
78
+ }
79
+ log.add('info', `Imported setup from ${f.app ?? 'another install'}: ${applied.join(', ') || 'nothing matched this app'}`, undefined, 'Settings');
80
+ return applied;
81
+ }
82
+
83
+ /** Saves a file to Downloads (an <a download> click; no extra permission). Objects are written as JSON. */
84
+ export function download(name: string, data: unknown, type = 'application/json') {
85
+ const url = URL.createObjectURL(new Blob([typeof data === 'string' ? data : JSON.stringify(data, null, 2)], { type }));
86
+ Object.assign(document.createElement('a'), { href: url, download: name }).click();
87
+ setTimeout(() => URL.revokeObjectURL(url), 5000);
88
+ }
@@ -0,0 +1,91 @@
1
+ // Activity Log store (ADR-027, ADR-040). Adding an entry is synchronous and never waits for rendering or storage;
2
+ // subscribers are told in a microtask and entries are persisted in the background.
3
+
4
+ import type { LogLevel, Logger } from '@tacoshell/sdk';
5
+ import * as store from './storage.ts';
6
+
7
+ export const LEVELS: LogLevel[] = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'];
8
+ const SEVERITY = (l: LogLevel) => LEVELS.indexOf(l);
9
+ /** The indicator reacts to info and above; trace and debug never color the Log button. */
10
+ const INDICATOR_MIN = SEVERITY('info');
11
+ const STORE_KEY = 'taco.log';
12
+ const KEEP = 500;
13
+
14
+ export interface Entry { id: number; at: number; level: LogLevel; message: string; data?: unknown; source?: string; tag?: 'notification' | 'api' }
15
+
16
+ let entries: Entry[] = [];
17
+ let nextId = 1;
18
+ let unseen = -1;
19
+ let panelOpen = false;
20
+ let version = 0;
21
+ const listeners = new Set<() => void>();
22
+ let notifyQueued = false;
23
+ let persistTimer: ReturnType<typeof setTimeout> | undefined;
24
+
25
+ function changed() {
26
+ version++;
27
+ if (notifyQueued) return;
28
+ notifyQueued = true;
29
+ queueMicrotask(() => { notifyQueued = false; for (const fn of listeners) fn(); });
30
+ }
31
+
32
+ const SECRET_KEY = /pass(word)?|secret|token|authorization|cookie|api[-_]?key|session|credential/i;
33
+ const SECRET_VALUE = /^(bearer|basic)\s+\S+/i;
34
+ /** Masks values under secret-looking keys and auth-looking strings; never throws (ADR-040). */
35
+ export function redact(data: unknown, depth = 0): unknown {
36
+ if (depth > 6) return '…';
37
+ if (typeof data === 'string') return SECRET_VALUE.test(data) ? '••••' : data.length > 2000 ? data.slice(0, 2000) + '…' : data;
38
+ if (Array.isArray(data)) return data.slice(0, 50).map((v) => redact(v, depth + 1));
39
+ if (data && typeof data === 'object') {
40
+ const out: Record<string, unknown> = {};
41
+ for (const [k, v] of Object.entries(data)) out[k] = SECRET_KEY.test(k) ? '••••' : redact(v, depth + 1);
42
+ return out;
43
+ }
44
+ return data;
45
+ }
46
+
47
+ export function add(level: LogLevel, message: string, data?: unknown, source?: string, tag?: Entry['tag']) {
48
+ const entry: Entry = { id: nextId++, at: Date.now(), level, message, source, tag };
49
+ if (data !== undefined) entry.data = redact(data);
50
+ entries.push(entry);
51
+ if (entries.length > 2000) entries = entries.slice(-2000);
52
+ if (!panelOpen && SEVERITY(level) >= INDICATOR_MIN) unseen = Math.max(unseen, SEVERITY(level));
53
+ changed();
54
+ clearTimeout(persistTimer);
55
+ persistTimer = setTimeout(persist, 250);
56
+ }
57
+
58
+ export const logger = (source?: string): Logger =>
59
+ Object.fromEntries(LEVELS.map((l) => [l, (message: string, data?: unknown) => add(l, message, data, source)])) as Logger;
60
+
61
+ /** Highest severity received since the log was last viewed, or null (ADR-027: the color "sticks" until viewed). */
62
+ export const indicator = (): LogLevel | null => (unseen >= INDICATOR_MIN ? LEVELS[unseen] : null);
63
+
64
+ export function setPanelOpen(open: boolean) {
65
+ panelOpen = open;
66
+ if (open) unseen = -1;
67
+ changed();
68
+ }
69
+
70
+ export const all = () => entries;
71
+ export const getVersion = () => version;
72
+ export function clear() { entries = []; unseen = -1; changed(); void persist(); }
73
+ export const subscribe = (fn: () => void) => { listeners.add(fn); return () => { listeners.delete(fn); }; };
74
+
75
+ async function persist() {
76
+ try { await store.set('local', STORE_KEY, entries.slice(-KEEP)); } catch { /* storage full or closing: the in-memory log is still complete */ }
77
+ }
78
+
79
+ /** Loads entries saved by earlier sessions and saves on the way out. */
80
+ export async function init() {
81
+ const saved = await store.get<Entry[]>('local', STORE_KEY);
82
+ if (saved?.length) {
83
+ entries = [...saved, ...entries];
84
+ nextId = Math.max(nextId, ...entries.map((e) => e.id + 1));
85
+ changed();
86
+ }
87
+ if (typeof addEventListener === 'function') addEventListener('pagehide', () => { void persist(); });
88
+ }
89
+
90
+ /** Test helper. */
91
+ export function resetForTests() { entries = []; nextId = 1; unseen = -1; panelOpen = false; listeners.clear(); }
@@ -0,0 +1,57 @@
1
+ // A small Markdown subset for Help and how-to pages, parsed into tokens and rendered as React elements (never innerHTML).
2
+ // Supports: # headings (1–3), paragraphs, - / 1. lists, ``` code blocks, `code`, **bold**, [text](https://…) links.
3
+
4
+ export type Inline = { t: 'text'; v: string } | { t: 'code'; v: string } | { t: 'bold'; v: string } | { t: 'link'; v: string; href: string };
5
+ export type Block =
6
+ | { t: 'h'; level: 1 | 2 | 3; inl: Inline[] }
7
+ | { t: 'p'; inl: Inline[] }
8
+ | { t: 'ul' | 'ol'; items: Inline[][] }
9
+ | { t: 'code'; v: string };
10
+
11
+ export function inline(s: string): Inline[] {
12
+ const out: Inline[] = [];
13
+ const re = /`([^`]+)`|\*\*([^*]+)\*\*|\[([^\]]+)\]\(([^)\s]+)\)/g;
14
+ let last = 0;
15
+ for (let m; (m = re.exec(s));) {
16
+ if (m.index > last) out.push({ t: 'text', v: s.slice(last, m.index) });
17
+ if (m[1] !== undefined) out.push({ t: 'code', v: m[1] });
18
+ else if (m[2] !== undefined) out.push({ t: 'bold', v: m[2] });
19
+ else if (/^https:\/\//i.test(m[4])) out.push({ t: 'link', v: m[3], href: m[4] });
20
+ else out.push({ t: 'text', v: m[3] }); // only https links are clickable (SECURITY.md rule 5)
21
+ last = re.lastIndex;
22
+ }
23
+ if (last < s.length) out.push({ t: 'text', v: s.slice(last) });
24
+ return out;
25
+ }
26
+
27
+ export function parse(md: string): Block[] {
28
+ const blocks: Block[] = [];
29
+ const lines = md.replace(/\r\n/g, '\n').split('\n');
30
+ let para: string[] = [];
31
+ const flush = () => { if (para.length) { blocks.push({ t: 'p', inl: inline(para.join(' ')) }); para = []; } };
32
+ for (let i = 0; i < lines.length; i++) {
33
+ const line = lines[i];
34
+ if (line.startsWith('```')) {
35
+ flush();
36
+ const body: string[] = [];
37
+ while (++i < lines.length && !lines[i].startsWith('```')) body.push(lines[i]);
38
+ blocks.push({ t: 'code', v: body.join('\n') });
39
+ continue;
40
+ }
41
+ const h = /^(#{1,3})\s+(.*)$/.exec(line);
42
+ if (h) { flush(); blocks.push({ t: 'h', level: h[1].length as 1 | 2 | 3, inl: inline(h[2]) }); continue; }
43
+ const li = /^\s*(?:([-*])|(\d+)\.)\s+(.*)$/.exec(line);
44
+ if (li) {
45
+ flush();
46
+ const kind = li[1] ? 'ul' : 'ol';
47
+ const prev = blocks[blocks.length - 1];
48
+ if (prev && prev.t === kind) prev.items.push(inline(li[3]));
49
+ else blocks.push({ t: kind, items: [inline(li[3])] });
50
+ continue;
51
+ }
52
+ if (!line.trim()) { flush(); continue; }
53
+ para.push(line.trim());
54
+ }
55
+ flush();
56
+ return blocks;
57
+ }
@@ -0,0 +1,105 @@
1
+ // Navigation model (ADR-038): sections → buckets → groups → features → views (the 3rd-level bar).
2
+ // Pure function of the registry, so it is unit-tested and recomputed whenever services change.
3
+
4
+ import { serviceKey, viewKey, type Registry, type RegistryIcon, type RegistryView } from '../types.ts';
5
+
6
+ export interface NavFeature { key: string; label: string; views: RegistryView[]; /** The first icon any of its views declares. */ icon?: RegistryIcon }
7
+ export interface NavGroup { key: string; label: string; features: NavFeature[]; /** One feature → shown as a plain link. */ flat: boolean; serviceType?: string }
8
+ export interface NavSection { featured: NavFeature[]; tools: NavGroup[]; services: NavGroup[] }
9
+ export interface NavModel { home: NavSection; reports: NavSection; byView: Map<string, NavFeature> }
10
+
11
+ /** The Level-2 group a view sits in (the rail's group heading): its `nav.group`, else the service type's label (Services) or "Tools". Featured views have none. */
12
+ export function groupLabelOf(reg: Registry, v: RegistryView): string | undefined {
13
+ if (v.nav.bucket === 'featured') return undefined;
14
+ const serviceType = v.nav.bucket === 'services' ? v.requires[0]?.type : undefined;
15
+ return v.nav.group ?? (v.nav.bucket === 'services' ? (serviceType ? reg.services.find((s) => s.type === serviceType)?.label ?? serviceType : 'Services') : 'Tools');
16
+ }
17
+
18
+ /** "Display in NavBars": a heuristic of every feature, true unless the view says otherwise (ACTION views default to false). */
19
+ export const inNav = (v: RegistryView) => v.showInNavBars ?? v.viewType !== 'ACTION';
20
+
21
+ export interface BarItem { view: RegistryView; label: string }
22
+
23
+ /**
24
+ * Level 3 (the 3rd-level bar) mirrors Level 2: the items of the group the current view is in. One item per feature (labelled by the feature), or one per view
25
+ * when a feature has several. A featured view has no group, so its bar shows just its own feature's views. The bar is shown when there is more than one.
26
+ */
27
+ export function barItems(reg: Registry, current: RegistryView): BarItem[] {
28
+ const group = groupLabelOf(reg, current);
29
+ const section = current.nav.section ?? 'home';
30
+ const peers = group === undefined ? [current] : reg.views.filter((v) => inNav(v) && (v.nav.section ?? 'home') === section && v.nav.bucket === current.nav.bucket && groupLabelOf(reg, v) === group);
31
+ const features = new Map<string, RegistryView[]>();
32
+ for (const v of peers) features.set(`${v.module}::${v.nav.feature ?? v.name}`, [...(features.get(`${v.module}::${v.nav.feature ?? v.name}`) ?? []), v]);
33
+ if (group === undefined) {
34
+ // Featured: the feature's own views, wherever they are.
35
+ const key = `${current.module}::${current.nav.feature ?? current.name}`;
36
+ const own = reg.views.filter((v) => inNav(v) && `${v.module}::${v.nav.feature ?? v.name}` === key && v.nav.bucket === 'featured');
37
+ features.clear(); features.set(key, own);
38
+ }
39
+ return [...features.values()].flatMap((views) => (views.length === 1 ? [{ view: views[0], label: views[0].nav.feature ?? views[0].label }] : views.map((view) => ({ view, label: view.label }))));
40
+ }
41
+
42
+ /** The page title: "Level 2 · Item" (the group, or the Featured action a related action belongs to), or just the item when they read the same. */
43
+ export function pageTitle(reg: Registry, current: RegistryView): string {
44
+ const item = barItems(reg, current).find((b) => b.view === current)?.label ?? current.label;
45
+ // Level 2 is the group, or for a Featured action the action itself: its related actions read "Hello World · History".
46
+ const level2 = groupLabelOf(reg, current) ?? current.nav.feature ?? current.label;
47
+ return level2 !== item ? `${level2} · ${item}` : item;
48
+ }
49
+
50
+ /** `isUsable(type, name)`: the service is enabled and configured. Used to hide service groups that can't work (v2 ADR-050). */
51
+ export function buildNav(reg: Registry, isUsable: (type: string, name: string) => boolean, filter = ''): NavModel {
52
+ const label = (type: string) => reg.services.find((s) => s.type === type)?.label ?? type;
53
+ const q = filter.trim().toLowerCase();
54
+ const byView = new Map<string, NavFeature>();
55
+
56
+ const section = (id: 'home' | 'reports'): NavSection => {
57
+ const views = reg.views.filter((v) => inNav(v) && (v.nav.section ?? 'home') === id);
58
+ const features = new Map<string, NavFeature & { bucket: string; group: string; serviceType?: string }>();
59
+ for (const v of views) {
60
+ const fkey = `${v.module}::${v.nav.feature ?? v.name}`;
61
+ let f = features.get(fkey);
62
+ if (!f) {
63
+ const serviceType = v.nav.bucket === 'services' ? v.requires[0]?.type : undefined;
64
+ const group = groupLabelOf(reg, v) ?? 'Tools';
65
+ f = { key: fkey, label: v.nav.feature ?? v.label, views: [], bucket: v.nav.bucket, group, serviceType };
66
+ features.set(fkey, f);
67
+ }
68
+ f.views.push(v);
69
+ if (!f.icon && v.icon) f.icon = v.icon;
70
+ byView.set(viewKey(v), f);
71
+ }
72
+ const matches = (f: NavFeature) => !q || f.label.toLowerCase().includes(q) || f.views.some((v) => v.label.toLowerCase().includes(q));
73
+ const list = [...features.values()].filter(matches);
74
+
75
+ const groups = (bucket: string) => {
76
+ const out = new Map<string, NavGroup>();
77
+ for (const f of list.filter((x) => x.bucket === bucket)) {
78
+ const g = out.get(f.group) ?? { key: `${bucket}:${f.group}`, label: f.group, features: [], flat: false, serviceType: f.serviceType };
79
+ g.features.push(f);
80
+ out.set(f.group, g);
81
+ }
82
+ return [...out.values()].map((g) => ({ ...g, flat: g.features.length === 1 }));
83
+ };
84
+
85
+ const usable = (g: NavGroup) => {
86
+ const needs = g.features.flatMap((f) => f.views.flatMap((v) => v.requires));
87
+ return !needs.length || needs.some((r) => isUsable(r.type, r.name));
88
+ };
89
+ return {
90
+ featured: list.filter((f) => f.bucket === 'featured'),
91
+ tools: groups('tools'),
92
+ services: groups('services').filter(usable).sort((a, b) => a.label.localeCompare(b.label)),
93
+ };
94
+ };
95
+
96
+ return { home: section('home'), reports: section('reports'), byView };
97
+ }
98
+
99
+ /** The first Featured Action, used as the start page once a vault exists (ADR-047). */
100
+ export const firstFeatured = (nav: NavModel) => nav.home.featured[0]?.views[0];
101
+
102
+ export const hasReports = (nav: NavModel) => nav.reports.featured.length + nav.reports.tools.length + nav.reports.services.length > 0;
103
+
104
+ /** Every service a view needs that isn't usable (for the "configure it" screen). */
105
+ export const unmet = (v: RegistryView, isUsable: (type: string, name: string) => boolean) => v.requires.filter((r) => !isUsable(r.type, r.name)).map(serviceKey);
@@ -0,0 +1,31 @@
1
+ // When a Chrome (system) notification may pop up (ADR-041, v2 lib/notify.js). Pure functions, so they are unit-tested.
2
+ // The in-app toast and the Activity Log entry are not affected: these rules only decide about the desktop notification.
3
+
4
+ import type { NotifySettings } from './prefs.ts';
5
+
6
+ const minutes = (hhmm: string) => { const m = /^(\d{1,2}):(\d{2})$/.exec(hhmm); return m ? Number(m[1]) * 60 + Number(m[2]) : null; };
7
+
8
+ /** True inside quiet hours. Handles ranges across midnight (22:00–07:00). Empty or invalid → never quiet. */
9
+ export function inQuietHours(s: Pick<NotifySettings, 'quietFrom' | 'quietTo'>, now = new Date()): boolean {
10
+ const from = minutes(s.quietFrom), to = minutes(s.quietTo);
11
+ if (from === null || to === null || from === to) return false;
12
+ const t = now.getHours() * 60 + now.getMinutes();
13
+ return from < to ? t >= from && t < to : t >= from || t < to;
14
+ }
15
+
16
+ const DEDUPE_MS = 24 * 60 * 60 * 1000;
17
+ /** The same notification key is shown at most once per 24 h (v2 DEDUPE_HOURS). `seen` maps key → last shown (ms); it is updated. */
18
+ export function dedupe(key: string | undefined, seen: Record<string, number>, now = Date.now()): boolean {
19
+ if (!key) return true;
20
+ for (const [k, at] of Object.entries(seen)) if (now - at > DEDUPE_MS) delete seen[k];
21
+ if (seen[key]) return false;
22
+ seen[key] = now;
23
+ return true;
24
+ }
25
+
26
+ /** Should the desktop notification show? (`appInFront`: the app tab is visible and its window focused.) */
27
+ export function showSystem(s: NotifySettings, appInFront: boolean, now = new Date()): { show: boolean; why?: string } {
28
+ if (inQuietHours(s, now)) return { show: false, why: `quiet hours (${s.quietFrom}–${s.quietTo})` };
29
+ if (s.onlyWhenAway && appInFront) return { show: false, why: 'the app is in front (only when away)' };
30
+ return { show: true };
31
+ }
@@ -0,0 +1,91 @@
1
+ // One Page per mounted view (ADR-052, ADR-053): its view context, the page context shared with the panels in its slots,
2
+ // refresh listeners, and the tools it put in the Tools menu. Everything is dropped when the user navigates away.
3
+
4
+ import type { Context, PageContext, Store, Tool } from '@tacoshell/sdk';
5
+ import * as log from './log.ts';
6
+ import { createStore } from './prefs.ts';
7
+
8
+ export interface Page {
9
+ key: string;
10
+ viewContext: Store<Context | undefined> & { set(ctx: Context | undefined): void };
11
+ page: PageContext;
12
+ /** How many components on the page listen for refresh (usePageRefresh). */
13
+ refreshListeners(): number;
14
+ tools: Store<Tool[]> & { add(tool: Tool): () => void };
15
+ /** What the feature says it is showing (`framework.expose`): the context Related and Actions contributors receive. */
16
+ exposed: Store<Context> & { set(ctx: Context): void };
17
+ /** Set when the page is an ACTION modal: closes it. */
18
+ close?: () => void;
19
+ /** A view's own setContextHandler, called with every live hand-off. */
20
+ handler?: (ctx: Context) => void;
21
+ }
22
+
23
+ /** One shared empty context, so an unset `exposed` is a stable snapshot. */
24
+ export const NO_CONTEXT: Context = Object.freeze({});
25
+
26
+ export function createPage(key: string, initial?: Context): Page {
27
+ const viewContext = createStore<Context | undefined>(initial);
28
+ const state = createStore<Context>({ ...(initial ?? {}) });
29
+ const refreshers = new Set<(reason?: string) => void>();
30
+ const tools = createStore<Tool[]>([]);
31
+ const exposed = createStore<Context>(NO_CONTEXT);
32
+ return {
33
+ key,
34
+ exposed,
35
+ viewContext,
36
+ refreshListeners: () => refreshers.size,
37
+ page: {
38
+ get: state.get,
39
+ subscribe: state.subscribe,
40
+ set(patch) {
41
+ const next = { ...state.get(), ...patch };
42
+ if (JSON.stringify(next) === JSON.stringify(state.get())) return; // no-op sets don't re-render the page
43
+ state.set(next);
44
+ log.add('trace', `page ${key}: ${Object.keys(patch).join(', ')} changed`, patch, 'page');
45
+ },
46
+ refresh(reason) {
47
+ log.add('debug', `page ${key}: refresh${reason ? ` (${reason})` : ''}`, undefined, 'page');
48
+ for (const fn of refreshers) queueMicrotask(() => fn(reason));
49
+ },
50
+ onRefresh(fn) { refreshers.add(fn); return () => { refreshers.delete(fn); }; },
51
+ },
52
+ tools: {
53
+ get: tools.get,
54
+ subscribe: tools.subscribe,
55
+ add(tool) {
56
+ tools.set([...tools.get().filter((t) => t.id !== tool.id), tool]);
57
+ return () => tools.set(tools.get().filter((t) => t !== tool));
58
+ },
59
+ },
60
+ };
61
+ }
62
+
63
+ /** A live hand-off from showView while the page is open: update the view context, merge into the page context, tell the view. */
64
+ export function deliver(p: Page, ctx: Context) {
65
+ p.viewContext.set(ctx);
66
+ p.page.set(ctx);
67
+ p.handler?.(ctx);
68
+ }
69
+
70
+ /** The page the user is looking at (the SubBar reads its tools). */
71
+ export const currentPage = createStore<Page | null>(null);
72
+
73
+ /**
74
+ * Checks a context against a view's declared shape (`"context": { "slug": "string", "ticket": "number?" }`).
75
+ * Returns a problem, or null. Undeclared views accept any plain-JSON context.
76
+ */
77
+ export function checkContext(decl: Record<string, string> | undefined, ctx: Context | undefined): string | null {
78
+ if (!decl || ctx === undefined) return null;
79
+ const problems: string[] = [];
80
+ for (const [k, t] of Object.entries(decl)) {
81
+ const optional = t.endsWith('?');
82
+ const base = t.replace(/\?$/, '');
83
+ const v = ctx[k];
84
+ if (v === undefined || v === null) { if (!optional) problems.push(`"${k}" is required`); continue; }
85
+ const ok = base.endsWith('[]') ? Array.isArray(v) : base === 'object' ? typeof v === 'object' && !Array.isArray(v) : base === 'unknown' || typeof v === base;
86
+ if (!ok) problems.push(`"${k}" should be ${base}`);
87
+ }
88
+ // `referrer` is reserved: the framework adds it when a Related link or an Action opens the view.
89
+ for (const k of Object.keys(ctx)) if (k !== 'referrer' && !(k in decl)) problems.push(`"${k}" isn't declared`);
90
+ return problems.length ? problems.join('; ') : null;
91
+ }