@tacoshell/shell 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +28 -0
- package/README.md +6 -2
- package/package.json +40 -4
- package/src/background.ts +41 -0
- package/src/core/bus.ts +186 -0
- package/src/core/cards.ts +33 -0
- package/src/core/cron.ts +63 -0
- package/src/core/cronfriendly.ts +70 -0
- package/src/core/csv.ts +36 -0
- package/src/core/datasets.ts +276 -0
- package/src/core/domshot.ts +81 -0
- package/src/core/guards.ts +36 -0
- package/src/core/hosts.ts +15 -0
- package/src/core/hotkeys.ts +44 -0
- package/src/core/localdata.ts +88 -0
- package/src/core/log.ts +91 -0
- package/src/core/markdown.ts +57 -0
- package/src/core/nav.ts +102 -0
- package/src/core/notifyrules.ts +31 -0
- package/src/core/page.ts +81 -0
- package/src/core/prefs.ts +114 -0
- package/src/core/router.ts +78 -0
- package/src/core/search.ts +65 -0
- package/src/core/services.ts +161 -0
- package/src/core/sessions.ts +72 -0
- package/src/core/startpage.ts +28 -0
- package/src/core/storage.ts +54 -0
- package/src/core/systemtools.ts +85 -0
- package/src/core/tabfit.ts +30 -0
- package/src/core/templates.ts +48 -0
- package/src/core/toasts.ts +13 -0
- package/src/core/vault.ts +208 -0
- package/src/env.d.ts +2 -0
- package/src/index.ts +56 -0
- package/src/styles.css +288 -0
- package/src/types.ts +113 -0
- package/src/ui/App.tsx +229 -0
- package/src/ui/ClearableInput.tsx +23 -0
- package/src/ui/Icon.tsx +8 -0
- package/src/ui/Markdown.tsx +24 -0
- package/src/ui/Rail.tsx +89 -0
- package/src/ui/Search.tsx +111 -0
- package/src/ui/Sessions.tsx +72 -0
- package/src/ui/SidePanel.tsx +148 -0
- package/src/ui/TabBar.tsx +56 -0
- package/src/ui/ViewHost.tsx +122 -0
- package/src/ui/hooks.ts +21 -0
- package/src/ui/settings/Datasets.tsx +162 -0
- package/src/ui/settings/ReleaseNotes.tsx +19 -0
- package/src/ui/settings/ScheduleEditor.tsx +57 -0
- package/src/ui/settings/Settings.tsx +328 -0
- package/src/ui/settings/Templates.tsx +52 -0
|
@@ -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
|
+
}
|
package/src/core/nav.ts
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
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
|
+
export interface BarItem { view: RegistryView; label: string }
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* 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
|
|
22
|
+
* 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.
|
|
23
|
+
*/
|
|
24
|
+
export function barItems(reg: Registry, current: RegistryView): BarItem[] {
|
|
25
|
+
const group = groupLabelOf(reg, current);
|
|
26
|
+
const section = current.nav.section ?? 'home';
|
|
27
|
+
const peers = group === undefined ? [current] : reg.views.filter((v) => (v.nav.section ?? 'home') === section && v.nav.bucket === current.nav.bucket && groupLabelOf(reg, v) === group);
|
|
28
|
+
const features = new Map<string, RegistryView[]>();
|
|
29
|
+
for (const v of peers) features.set(`${v.module}::${v.nav.feature ?? v.name}`, [...(features.get(`${v.module}::${v.nav.feature ?? v.name}`) ?? []), v]);
|
|
30
|
+
if (group === undefined) {
|
|
31
|
+
// Featured: the feature's own views, wherever they are.
|
|
32
|
+
const key = `${current.module}::${current.nav.feature ?? current.name}`;
|
|
33
|
+
const own = reg.views.filter((v) => `${v.module}::${v.nav.feature ?? v.name}` === key && v.nav.bucket === 'featured');
|
|
34
|
+
features.clear(); features.set(key, own);
|
|
35
|
+
}
|
|
36
|
+
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 }))));
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 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. */
|
|
40
|
+
export function pageTitle(reg: Registry, current: RegistryView): string {
|
|
41
|
+
const item = barItems(reg, current).find((b) => b.view === current)?.label ?? current.label;
|
|
42
|
+
// Level 2 is the group, or for a Featured action the action itself: its related actions read "Hello World · History".
|
|
43
|
+
const level2 = groupLabelOf(reg, current) ?? current.nav.feature ?? current.label;
|
|
44
|
+
return level2 !== item ? `${level2} · ${item}` : item;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** `isUsable(type, name)`: the service is enabled and configured. Used to hide service groups that can't work (v2 ADR-050). */
|
|
48
|
+
export function buildNav(reg: Registry, isUsable: (type: string, name: string) => boolean, filter = ''): NavModel {
|
|
49
|
+
const label = (type: string) => reg.services.find((s) => s.type === type)?.label ?? type;
|
|
50
|
+
const q = filter.trim().toLowerCase();
|
|
51
|
+
const byView = new Map<string, NavFeature>();
|
|
52
|
+
|
|
53
|
+
const section = (id: 'home' | 'reports'): NavSection => {
|
|
54
|
+
const views = reg.views.filter((v) => (v.nav.section ?? 'home') === id);
|
|
55
|
+
const features = new Map<string, NavFeature & { bucket: string; group: string; serviceType?: string }>();
|
|
56
|
+
for (const v of views) {
|
|
57
|
+
const fkey = `${v.module}::${v.nav.feature ?? v.name}`;
|
|
58
|
+
let f = features.get(fkey);
|
|
59
|
+
if (!f) {
|
|
60
|
+
const serviceType = v.nav.bucket === 'services' ? v.requires[0]?.type : undefined;
|
|
61
|
+
const group = groupLabelOf(reg, v) ?? 'Tools';
|
|
62
|
+
f = { key: fkey, label: v.nav.feature ?? v.label, views: [], bucket: v.nav.bucket, group, serviceType };
|
|
63
|
+
features.set(fkey, f);
|
|
64
|
+
}
|
|
65
|
+
f.views.push(v);
|
|
66
|
+
if (!f.icon && v.icon) f.icon = v.icon;
|
|
67
|
+
byView.set(viewKey(v), f);
|
|
68
|
+
}
|
|
69
|
+
const matches = (f: NavFeature) => !q || f.label.toLowerCase().includes(q) || f.views.some((v) => v.label.toLowerCase().includes(q));
|
|
70
|
+
const list = [...features.values()].filter(matches);
|
|
71
|
+
|
|
72
|
+
const groups = (bucket: string) => {
|
|
73
|
+
const out = new Map<string, NavGroup>();
|
|
74
|
+
for (const f of list.filter((x) => x.bucket === bucket)) {
|
|
75
|
+
const g = out.get(f.group) ?? { key: `${bucket}:${f.group}`, label: f.group, features: [], flat: false, serviceType: f.serviceType };
|
|
76
|
+
g.features.push(f);
|
|
77
|
+
out.set(f.group, g);
|
|
78
|
+
}
|
|
79
|
+
return [...out.values()].map((g) => ({ ...g, flat: g.features.length === 1 }));
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
const usable = (g: NavGroup) => {
|
|
83
|
+
const needs = g.features.flatMap((f) => f.views.flatMap((v) => v.requires));
|
|
84
|
+
return !needs.length || needs.some((r) => isUsable(r.type, r.name));
|
|
85
|
+
};
|
|
86
|
+
return {
|
|
87
|
+
featured: list.filter((f) => f.bucket === 'featured'),
|
|
88
|
+
tools: groups('tools'),
|
|
89
|
+
services: groups('services').filter(usable).sort((a, b) => a.label.localeCompare(b.label)),
|
|
90
|
+
};
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
return { home: section('home'), reports: section('reports'), byView };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** The first Featured Action, used as the start page once a vault exists (ADR-047). */
|
|
97
|
+
export const firstFeatured = (nav: NavModel) => nav.home.featured[0]?.views[0];
|
|
98
|
+
|
|
99
|
+
export const hasReports = (nav: NavModel) => nav.reports.featured.length + nav.reports.tools.length + nav.reports.services.length > 0;
|
|
100
|
+
|
|
101
|
+
/** Every service a view needs that isn't usable (for the "configure it" screen). */
|
|
102
|
+
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
|
+
}
|
package/src/core/page.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
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
|
+
/** A view's own setContextHandler, called with every live hand-off. */
|
|
16
|
+
handler?: (ctx: Context) => void;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function createPage(key: string, initial?: Context): Page {
|
|
20
|
+
const viewContext = createStore<Context | undefined>(initial);
|
|
21
|
+
const state = createStore<Context>({ ...(initial ?? {}) });
|
|
22
|
+
const refreshers = new Set<(reason?: string) => void>();
|
|
23
|
+
const tools = createStore<Tool[]>([]);
|
|
24
|
+
return {
|
|
25
|
+
key,
|
|
26
|
+
viewContext,
|
|
27
|
+
refreshListeners: () => refreshers.size,
|
|
28
|
+
page: {
|
|
29
|
+
get: state.get,
|
|
30
|
+
subscribe: state.subscribe,
|
|
31
|
+
set(patch) {
|
|
32
|
+
const next = { ...state.get(), ...patch };
|
|
33
|
+
if (JSON.stringify(next) === JSON.stringify(state.get())) return; // no-op sets don't re-render the page
|
|
34
|
+
state.set(next);
|
|
35
|
+
log.add('trace', `page ${key}: ${Object.keys(patch).join(', ')} changed`, patch, 'page');
|
|
36
|
+
},
|
|
37
|
+
refresh(reason) {
|
|
38
|
+
log.add('debug', `page ${key}: refresh${reason ? ` (${reason})` : ''}`, undefined, 'page');
|
|
39
|
+
for (const fn of refreshers) queueMicrotask(() => fn(reason));
|
|
40
|
+
},
|
|
41
|
+
onRefresh(fn) { refreshers.add(fn); return () => { refreshers.delete(fn); }; },
|
|
42
|
+
},
|
|
43
|
+
tools: {
|
|
44
|
+
get: tools.get,
|
|
45
|
+
subscribe: tools.subscribe,
|
|
46
|
+
add(tool) {
|
|
47
|
+
tools.set([...tools.get().filter((t) => t.id !== tool.id), tool]);
|
|
48
|
+
return () => tools.set(tools.get().filter((t) => t !== tool));
|
|
49
|
+
},
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** A live hand-off from showView while the page is open: update the view context, merge into the page context, tell the view. */
|
|
55
|
+
export function deliver(p: Page, ctx: Context) {
|
|
56
|
+
p.viewContext.set(ctx);
|
|
57
|
+
p.page.set(ctx);
|
|
58
|
+
p.handler?.(ctx);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The page the user is looking at (the SubBar reads its tools). */
|
|
62
|
+
export const currentPage = createStore<Page | null>(null);
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Checks a context against a view's declared shape (`"context": { "slug": "string", "ticket": "number?" }`).
|
|
66
|
+
* Returns a problem, or null. Undeclared views accept any plain-JSON context.
|
|
67
|
+
*/
|
|
68
|
+
export function checkContext(decl: Record<string, string> | undefined, ctx: Context | undefined): string | null {
|
|
69
|
+
if (!decl || ctx === undefined) return null;
|
|
70
|
+
const problems: string[] = [];
|
|
71
|
+
for (const [k, t] of Object.entries(decl)) {
|
|
72
|
+
const optional = t.endsWith('?');
|
|
73
|
+
const base = t.replace(/\?$/, '');
|
|
74
|
+
const v = ctx[k];
|
|
75
|
+
if (v === undefined || v === null) { if (!optional) problems.push(`"${k}" is required`); continue; }
|
|
76
|
+
const ok = base.endsWith('[]') ? Array.isArray(v) : base === 'object' ? typeof v === 'object' && !Array.isArray(v) : base === 'unknown' || typeof v === base;
|
|
77
|
+
if (!ok) problems.push(`"${k}" should be ${base}`);
|
|
78
|
+
}
|
|
79
|
+
for (const k of Object.keys(ctx)) if (!(k in decl)) problems.push(`"${k}" isn't declared`);
|
|
80
|
+
return problems.length ? problems.join('; ') : null;
|
|
81
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// UI preferences (localStorage, page-only, never secrets: ADR-003) and user settings the service worker must read (chrome.storage.local).
|
|
2
|
+
|
|
3
|
+
import * as store from './storage.ts';
|
|
4
|
+
|
|
5
|
+
/** A tiny observable value for React's useSyncExternalStore. */
|
|
6
|
+
export function createStore<T>(initial: T) {
|
|
7
|
+
let value = initial;
|
|
8
|
+
const listeners = new Set<() => void>();
|
|
9
|
+
return {
|
|
10
|
+
get: () => value,
|
|
11
|
+
set(next: T) { value = next; for (const fn of listeners) fn(); },
|
|
12
|
+
subscribe(fn: () => void) { listeners.add(fn); return () => { listeners.delete(fn); }; },
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const ls = () => (typeof localStorage !== 'undefined' ? localStorage : undefined);
|
|
17
|
+
export function pref<T>(key: string, fallback: T): T {
|
|
18
|
+
try { const raw = ls()?.getItem(`taco.${key}`); return raw == null ? fallback : (JSON.parse(raw) as T); } catch { return fallback; }
|
|
19
|
+
}
|
|
20
|
+
export function setPref(key: string, value: unknown) {
|
|
21
|
+
try { ls()?.setItem(`taco.${key}`, JSON.stringify(value)); } catch { /* private window or storage blocked: the pref just isn't remembered */ }
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// ── Favorites: view keys, in the user's order (FR-FAV-1..3) ─────────────────────────────────────────────────────────
|
|
25
|
+
export const favorites = createStore<string[]>(pref('favorites', []));
|
|
26
|
+
export function toggleFavorite(key: string) {
|
|
27
|
+
const list = favorites.get();
|
|
28
|
+
const next = list.includes(key) ? list.filter((k) => k !== key) : [...list, key];
|
|
29
|
+
favorites.set(next);
|
|
30
|
+
setPref('favorites', next);
|
|
31
|
+
}
|
|
32
|
+
export function moveFavorite(key: string, delta: -1 | 1) {
|
|
33
|
+
const list = [...favorites.get()];
|
|
34
|
+
const i = list.indexOf(key), j = i + delta;
|
|
35
|
+
if (i < 0 || j < 0 || j >= list.length) return;
|
|
36
|
+
[list[i], list[j]] = [list[j], list[i]];
|
|
37
|
+
favorites.set(list);
|
|
38
|
+
setPref('favorites', list);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// ── Side panel: Log or Help share one slot (ADR-039) ─────────────────────────────────────────────────────────────────
|
|
42
|
+
export type Panel = 'log' | 'help' | null;
|
|
43
|
+
export const sidePanel = createStore<Panel>(pref<Panel>('side.panel', null));
|
|
44
|
+
export function togglePanel(p: Exclude<Panel, null>) {
|
|
45
|
+
const next = sidePanel.get() === p ? null : p;
|
|
46
|
+
sidePanel.set(next);
|
|
47
|
+
setPref('side.panel', next);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// ── User settings (chrome.storage.local, so the service worker can read the idle lock) ──────────────────────────────
|
|
51
|
+
export type ThemeMode = 'dark' | 'light' | 'system';
|
|
52
|
+
/** Notification preferences (ADR-041, v2 config/notifications.js). The service worker reads them, so they live in chrome.storage.local. */
|
|
53
|
+
export interface NotifySettings {
|
|
54
|
+
enabled: boolean;
|
|
55
|
+
items: Record<string, boolean>;
|
|
56
|
+
/** Chrome notifications only while the app isn't the focused window (the in-app toast always shows). */
|
|
57
|
+
onlyWhenAway: boolean;
|
|
58
|
+
/** "HH:MM"–"HH:MM", local time; empty = none. Nothing pops up during quiet hours (it's still in the Activity Log). */
|
|
59
|
+
quietFrom: string;
|
|
60
|
+
quietTo: string;
|
|
61
|
+
/** Keep Chrome notifications on screen until dismissed. */
|
|
62
|
+
sticky: boolean;
|
|
63
|
+
/** Count unseen notifications on the toolbar icon. */
|
|
64
|
+
badge: boolean;
|
|
65
|
+
}
|
|
66
|
+
export interface UserSettings {
|
|
67
|
+
theme: ThemeMode;
|
|
68
|
+
idleLockMinutes: number;
|
|
69
|
+
visibleLevels: string[];
|
|
70
|
+
notifications: NotifySettings;
|
|
71
|
+
/** The user's start page, overriding the app's default (null = use the app's default). "auto" | "home" | "reports" | "<module>/<view>". */
|
|
72
|
+
startPage: string | null;
|
|
73
|
+
/** Ask "Lock the vault?" before the header's Vault button locks it. Default on. */
|
|
74
|
+
confirmLock: boolean;
|
|
75
|
+
/** HotKeys (ADR-046): `map` = the user's combos by hotkey id; unset = the default. */
|
|
76
|
+
hotkeys: { enabled: boolean; map: Record<string, string> };
|
|
77
|
+
}
|
|
78
|
+
export const SETTINGS_KEY = 'taco.settings';
|
|
79
|
+
export const DEFAULT_NOTIFY: NotifySettings = { enabled: true, items: {}, onlyWhenAway: true, quietFrom: '', quietTo: '', sticky: false, badge: true };
|
|
80
|
+
export const settings = createStore<UserSettings>({ theme: 'dark', idleLockMinutes: 15, visibleLevels: ['info', 'warn', 'error', 'fatal'], notifications: { ...DEFAULT_NOTIFY }, confirmLock: true, startPage: null, hotkeys: { enabled: true, map: {} } });
|
|
81
|
+
|
|
82
|
+
// ── Theme: dark (default), light, or follow the system (v2 had dark / light) ─────────────────────────────────────────
|
|
83
|
+
let systemQuery: MediaQueryList | undefined;
|
|
84
|
+
export function applyTheme(mode: ThemeMode) {
|
|
85
|
+
if (typeof document === 'undefined') return;
|
|
86
|
+
const dark = mode === 'system' ? !!globalThis.matchMedia?.('(prefers-color-scheme: dark)').matches : mode === 'dark';
|
|
87
|
+
document.documentElement.dataset.theme = dark ? 'dark' : 'light';
|
|
88
|
+
if (mode === 'system' && !systemQuery && typeof matchMedia === 'function') {
|
|
89
|
+
systemQuery = matchMedia('(prefers-color-scheme: dark)');
|
|
90
|
+
systemQuery.addEventListener('change', () => { if (settings.get().theme === 'system') applyTheme('system'); });
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export async function initSettings(defaults: { idleLockMinutes: number; visibleLevels: string[] }) {
|
|
95
|
+
const saved = await store.get<Partial<UserSettings>>('local', SETTINGS_KEY);
|
|
96
|
+
const merged: UserSettings = {
|
|
97
|
+
theme: saved?.theme ?? 'dark',
|
|
98
|
+
idleLockMinutes: saved?.idleLockMinutes ?? defaults.idleLockMinutes,
|
|
99
|
+
visibleLevels: saved?.visibleLevels ?? defaults.visibleLevels,
|
|
100
|
+
notifications: { ...DEFAULT_NOTIFY, ...(saved?.notifications ?? {}) },
|
|
101
|
+
confirmLock: saved?.confirmLock ?? true,
|
|
102
|
+
startPage: typeof saved?.startPage === 'string' ? saved.startPage : null,
|
|
103
|
+
hotkeys: { enabled: saved?.hotkeys?.enabled ?? true, map: saved?.hotkeys?.map ?? {} },
|
|
104
|
+
};
|
|
105
|
+
settings.set(merged);
|
|
106
|
+
applyTheme(merged.theme);
|
|
107
|
+
await store.set('local', SETTINGS_KEY, merged);
|
|
108
|
+
}
|
|
109
|
+
export async function updateSettings(patch: Partial<UserSettings>) {
|
|
110
|
+
const next = { ...settings.get(), ...patch };
|
|
111
|
+
settings.set(next);
|
|
112
|
+
if (patch.theme) applyTheme(patch.theme);
|
|
113
|
+
await store.set('local', SETTINGS_KEY, next);
|
|
114
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// Hash router with guards on every navigation (ADR-036) and an in-memory context mailbox for showView.
|
|
2
|
+
// Routes: #/home · #/reports · #/v/<module>/<view> · #/settings/<page>[/<type>/<name>]
|
|
3
|
+
|
|
4
|
+
import * as guards from './guards.ts';
|
|
5
|
+
import { createStore } from './prefs.ts';
|
|
6
|
+
import { toast } from './toasts.ts';
|
|
7
|
+
|
|
8
|
+
export type Route =
|
|
9
|
+
| { page: 'home' } | { page: 'reports' }
|
|
10
|
+
| { page: 'view'; module: string; view: string }
|
|
11
|
+
| { page: 'settings'; sub: string; type?: string; name?: string };
|
|
12
|
+
|
|
13
|
+
export function parse(hash: string): Route | null {
|
|
14
|
+
const parts = hash.replace(/^#\/?/, '').split('/').map(decodeURIComponent);
|
|
15
|
+
if (!parts[0]) return null;
|
|
16
|
+
if (parts[0] === 'home') return { page: 'home' };
|
|
17
|
+
if (parts[0] === 'reports') return { page: 'reports' };
|
|
18
|
+
if (parts[0] === 'v' && parts[1] && parts[2]) return { page: 'view', module: parts[1], view: parts[2] };
|
|
19
|
+
if (parts[0] === 'settings') return { page: 'settings', sub: parts[1] || 'services', type: parts[2], name: parts[3] };
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const href = {
|
|
24
|
+
view: (module: string, view: string) => `#/v/${encodeURIComponent(module)}/${encodeURIComponent(view)}`,
|
|
25
|
+
settings: (sub: string, type?: string, name?: string) => `#/settings/${[sub, type, name].filter(Boolean).join('/')}`,
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export const current = createStore<string>(typeof location !== 'undefined' ? location.hash : '');
|
|
29
|
+
let approved: string | null = null;
|
|
30
|
+
|
|
31
|
+
/** Contexts waiting for their view to mount (never stored; lost on reload: ADR-036). */
|
|
32
|
+
const mailbox = new Map<string, Record<string, unknown>>();
|
|
33
|
+
const liveHandlers = new Map<string, (ctx: Record<string, unknown>) => void>();
|
|
34
|
+
export const takeContext = (viewKey: string) => { const c = mailbox.get(viewKey); mailbox.delete(viewKey); return c; };
|
|
35
|
+
export function setLiveHandler(viewKey: string, fn: ((ctx: Record<string, unknown>) => void) | null) {
|
|
36
|
+
if (fn) liveHandlers.set(viewKey, fn); else liveHandlers.delete(viewKey);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const ask = () => guards.ask((q) => confirm(q), (reason) => toast(`Can't leave yet: ${reason}. Press Stop first, or wait for it to finish.`, 'error'));
|
|
40
|
+
|
|
41
|
+
/** Navigate (guarded). Returns false if a guard refused. */
|
|
42
|
+
export function go(hash: string, context?: Record<string, unknown>, viewKey?: string): boolean {
|
|
43
|
+
if (hash === location.hash) {
|
|
44
|
+
if (context && viewKey) {
|
|
45
|
+
const live = liveHandlers.get(viewKey);
|
|
46
|
+
if (live) live(context); else mailbox.set(viewKey, context);
|
|
47
|
+
}
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
50
|
+
if (!ask()) return false;
|
|
51
|
+
if (context && viewKey) mailbox.set(viewKey, context);
|
|
52
|
+
guards.clearAll();
|
|
53
|
+
approved = hash;
|
|
54
|
+
location.hash = hash;
|
|
55
|
+
return true;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function start() {
|
|
59
|
+
let previous = location.hash;
|
|
60
|
+
addEventListener('hashchange', () => {
|
|
61
|
+
if (approved === location.hash) {
|
|
62
|
+
approved = null;
|
|
63
|
+
} else if (!ask()) {
|
|
64
|
+
history.replaceState(null, '', previous || '#/home'); // refuse: put the address back (no hashchange fires)
|
|
65
|
+
return;
|
|
66
|
+
} else {
|
|
67
|
+
guards.clearAll();
|
|
68
|
+
}
|
|
69
|
+
previous = location.hash;
|
|
70
|
+
current.set(location.hash);
|
|
71
|
+
});
|
|
72
|
+
addEventListener('beforeunload', (e) => { if (guards.anyActive()) e.preventDefault(); });
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function replace(hash: string) {
|
|
76
|
+
history.replaceState(null, '', hash);
|
|
77
|
+
current.set(hash);
|
|
78
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// Header search: connectors opt in with a resolver, views offer Quick Actions for what it resolves to.
|
|
2
|
+
// term → (resolve per connector) → one context (picked, or inferred when there is only one) → Quick Action tiles → showView with that context.
|
|
3
|
+
|
|
4
|
+
import type { Context, SearchResult } from '@tacoshell/sdk';
|
|
5
|
+
import { serviceKey, type QuickActionDecl, type Registry, type RegistryService, type RegistryView } from '../types.ts';
|
|
6
|
+
import * as log from './log.ts';
|
|
7
|
+
import * as services from './services.ts';
|
|
8
|
+
|
|
9
|
+
export interface Hit { service: RegistryService; result: SearchResult }
|
|
10
|
+
export interface Outcome { hits: Hit[]; failed: string[] }
|
|
11
|
+
export interface Tile { view: RegistryView; action: QuickActionDecl; label: string; icon?: string }
|
|
12
|
+
|
|
13
|
+
/** Connectors that can resolve a term right now: they declare a resolver and are enabled and configured. */
|
|
14
|
+
export const resolvers = (reg: Registry, usable: (type: string, name: string) => boolean = services.isUsable) =>
|
|
15
|
+
reg.services.filter((s) => s.resolver && usable(s.type, s.name));
|
|
16
|
+
|
|
17
|
+
/** The search box hint: just "Find" (the resolvers' labels and hints are not shown). */
|
|
18
|
+
export function placeholder(_list?: RegistryService[]): string { return 'Find'; }
|
|
19
|
+
|
|
20
|
+
/** Asks every resolver at once. One that fails doesn't hide the others' results; its failure is reported and logged. */
|
|
21
|
+
export async function resolve(term: string, list: RegistryService[], run?: (s: RegistryService, term: string) => Promise<SearchResult[]>): Promise<Outcome> {
|
|
22
|
+
const ask = run ?? ((s, t) => {
|
|
23
|
+
const impl = services.implFor(s);
|
|
24
|
+
if (!impl?.resolve) throw new Error(`${s.label} declares a resolver but its implementation has no resolve().`);
|
|
25
|
+
return impl.resolve(t, services.contextFor(s));
|
|
26
|
+
});
|
|
27
|
+
const settled = await Promise.allSettled(list.map(async (s) => ask(s, term)));
|
|
28
|
+
const out: Outcome = { hits: [], failed: [] };
|
|
29
|
+
const seen = new Set<string>();
|
|
30
|
+
settled.forEach((r, i) => {
|
|
31
|
+
const s = list[i];
|
|
32
|
+
if (r.status === 'rejected') {
|
|
33
|
+
const message = (r.reason as Error)?.message ?? String(r.reason);
|
|
34
|
+
log.add('warn', `Search in ${s.label} failed: ${message}`, undefined, 'search');
|
|
35
|
+
out.failed.push(`${s.label}: ${message}`);
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
for (const result of r.value ?? []) {
|
|
39
|
+
const k = `${serviceKey(s)}:${result.id}`;
|
|
40
|
+
if (!seen.has(k)) { seen.add(k); out.hits.push({ service: s, result }); }
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
log.add('debug', `Search "${term}": ${out.hits.length} result(s) from ${list.length} connector(s)`, undefined, 'search');
|
|
44
|
+
return out;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Quick Action tiles for a resolved service: every view that registered one for its type and whose own services are usable. */
|
|
48
|
+
export function tilesFor(reg: Registry, service: RegistryService, usable: (type: string, name: string) => boolean = services.isUsable): Tile[] {
|
|
49
|
+
return reg.views.flatMap((view) => (view.quickActions ?? [])
|
|
50
|
+
.filter((a) => a.service === service.type && view.requires.every((r) => usable(r.type, r.name)))
|
|
51
|
+
.map((action) => ({ view, action, label: action.label ?? view.label, icon: action.icon })));
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The context handed to the view: `map` renames keys (view key → resolved key); without it, the resolved keys the view declares (or all of them if it declares none). */
|
|
55
|
+
export function contextFor(tile: Pick<Tile, 'view' | 'action'>, resolved: Context): Context {
|
|
56
|
+
const { map } = tile.action;
|
|
57
|
+
const out: Context = {};
|
|
58
|
+
if (map) {
|
|
59
|
+
for (const [viewKey, resolvedKey] of Object.entries(map)) if (resolved[resolvedKey] !== undefined) out[viewKey] = resolved[resolvedKey];
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
const declared = tile.view.context;
|
|
63
|
+
for (const [k, v] of Object.entries(resolved)) if (!declared || k in declared) out[k] = v;
|
|
64
|
+
return out;
|
|
65
|
+
}
|