@zenera/cli 1.3.22 → 1.3.23

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 (23) hide show
  1. package/package.json +6 -6
  2. package/templates/editor/.github/skills/zen-review/scripts/check-paths.sh +1 -1
  3. package/templates/project/agents/skills/html-page/SKILL.md +96 -51
  4. package/templates/project/agents/skills/html-page/assets/app/api/items.api.py +3 -2
  5. package/templates/project/agents/skills/html-page/assets/app/app.tsx +140 -0
  6. package/templates/project/agents/skills/html-page/assets/dashboard.tsx +162 -0
  7. package/templates/project/agents/skills/html-page/kit/Chart.tsx +79 -0
  8. package/templates/project/agents/skills/html-page/kit/Table.tsx +89 -0
  9. package/templates/project/agents/skills/html-page/kit/api.ts +93 -0
  10. package/templates/project/agents/skills/html-page/kit/components.tsx +266 -0
  11. package/templates/project/agents/skills/html-page/kit/format.ts +60 -0
  12. package/templates/project/agents/skills/html-page/kit/hooks.ts +159 -0
  13. package/templates/project/agents/skills/html-page/kit/index.ts +35 -0
  14. package/templates/project/agents/skills/html-page/kit/modules.d.ts +37 -0
  15. package/templates/project/agents/skills/html-page/kit/mount.tsx +62 -0
  16. package/templates/project/agents/skills/html-page/kit/shell.html +19 -0
  17. package/templates/project/agents/skills/html-page/kit/theme.css +326 -0
  18. package/templates/project/agents/skills/html-page/references/charts-and-tables.md +105 -53
  19. package/templates/project/agents/skills/html-page/references/python-functions.md +37 -29
  20. package/templates/project/agents/skills/html-page/scripts/build.ts +825 -0
  21. package/templates/project/agents/skills/html-page/assets/api.js +0 -87
  22. package/templates/project/agents/skills/html-page/assets/app/index.html +0 -278
  23. package/templates/project/agents/skills/html-page/assets/dashboard.html +0 -423
@@ -0,0 +1,89 @@
1
+ import { useEffect, useRef } from 'react';
2
+
3
+ /**
4
+ * A Tabulator column: `title`, `field`, and any of its options - `sorter: 'number'`,
5
+ * `hozAlign: 'right'`, `headerFilter: 'input'`, `formatter: (cell) => …`, `minWidth`.
6
+ * https://tabulator.info/docs/6.3/columns
7
+ */
8
+ export type Column = { title: string; field?: string; [option: string]: any };
9
+
10
+ interface Tabulator {
11
+ on(event: string, handler: (...args: any[]) => void): void;
12
+ replaceData(data: unknown[]): Promise<void>;
13
+ setColumns(columns: Column[]): void;
14
+ destroy(): void;
15
+ }
16
+
17
+ // Loaded from the CDN by the page's html; the build adds it when a page uses Table.
18
+ declare const Tabulator: new (el: HTMLElement, options: Record<string, any>) => Tabulator;
19
+
20
+ const columnsKey = (columns: readonly Column[]) =>
21
+ JSON.stringify(columns.map(({ title, field }) => [title, field]));
22
+
23
+ /**
24
+ * A Tabulator table: sorts, filters per column with `headerFilter`, pages through many rows,
25
+ * and collapses the columns that do not fit a narrow panel - put the important ones first.
26
+ * New `data` replaces the rows; columns are set again when their titles or fields change.
27
+ *
28
+ * <Table data={rows} columns={[{ title: 'Amount', field: 'amount', sorter: 'number' }]} />
29
+ */
30
+ export function Table<T extends object>({
31
+ data,
32
+ columns,
33
+ options,
34
+ onRowClick,
35
+ placeholder = 'No rows match the filters',
36
+ }: {
37
+ data: readonly T[];
38
+ columns: Column[];
39
+ /** more Tabulator options, e.g. `{ paginationSize: 50 }` or `{ pagination: false }` */
40
+ options?: Record<string, any>;
41
+ onRowClick?: (row: T) => void;
42
+ placeholder?: string;
43
+ }) {
44
+ const el = useRef<HTMLDivElement>(null);
45
+ const table = useRef<{ tabulator: Tabulator; built: Promise<void> } | null>(null);
46
+ const first = useRef({ data, columns, options, placeholder });
47
+ const shown = useRef({ data, columns: columnsKey(columns) });
48
+ const clickRef = useRef(onRowClick);
49
+ clickRef.current = onRowClick;
50
+
51
+ useEffect(() => {
52
+ const { data, columns, options, placeholder } = first.current;
53
+ const tabulator = new Tabulator(el.current!, {
54
+ data: [...data],
55
+ columns,
56
+ layout: 'fitDataStretch',
57
+ responsiveLayout: 'collapse',
58
+ pagination: true,
59
+ paginationSize: 25,
60
+ paginationCounter: 'rows',
61
+ placeholder,
62
+ ...options,
63
+ });
64
+ const built = new Promise<void>((done) => tabulator.on('tableBuilt', () => done()));
65
+ tabulator.on('rowClick', (_event, row) => clickRef.current?.(row.getData() as T));
66
+ table.current = { tabulator, built };
67
+ return () => {
68
+ table.current = null;
69
+ tabulator.destroy();
70
+ };
71
+ }, []);
72
+
73
+ const key = columnsKey(columns);
74
+ useEffect(() => {
75
+ const current = table.current;
76
+ if (!current || shown.current.columns === key) return;
77
+ shown.current.columns = key;
78
+ void current.built.then(() => current.tabulator.setColumns(columns));
79
+ }, [key]);
80
+
81
+ useEffect(() => {
82
+ const current = table.current;
83
+ if (!current || shown.current.data === data) return;
84
+ shown.current.data = data;
85
+ void current.built.then(() => current.tabulator.replaceData([...data])).catch(() => {});
86
+ }, [data]);
87
+
88
+ return <div ref={el} className="table" />;
89
+ }
@@ -0,0 +1,93 @@
1
+ /*
2
+ * Calls the functions of the page's *.api.py files.
3
+ *
4
+ * interface ItemsApi {
5
+ * list_items(args?: { show?: string }): Promise<Item[]>;
6
+ * add_item(args: { title: string }): Promise<Item>;
7
+ * }
8
+ * const items = api<ItemsApi>('api/items'); // api/items.api.py, relative to the page
9
+ * const list = await items.list_items(); // list_items()
10
+ * await items.add_item({ title: 'Milk' }); // add_item(title="Milk")
11
+ *
12
+ * Each call is a POST of the arguments as JSON to `<file>/<function>`. It resolves with what the
13
+ * function returned, or rejects with an ApiError: `.status` (0 when the server could not be
14
+ * reached) and `.message` (the function's HttpError message, or what went wrong).
15
+ * A server still starting (503) or busy (429) is waited for and asked again, up to 3 times.
16
+ */
17
+
18
+ export class ApiError extends Error {
19
+ readonly status: number;
20
+ readonly body: unknown;
21
+
22
+ constructor(message: string, status: number, body?: unknown) {
23
+ super(message);
24
+ this.name = 'ApiError';
25
+ this.status = status;
26
+ this.body = body;
27
+ }
28
+ }
29
+
30
+ /** What `api()` gives without an interface: any function name, any result. */
31
+ export type AnyApi = Record<string, (args?: Record<string, unknown>) => Promise<any>>;
32
+
33
+ const sleep = (ms: number) => new Promise((done) => setTimeout(done, ms));
34
+
35
+ /** One call of `name` in `file` (relative to the page, without `.api.py`). */
36
+ export async function call<T = unknown>(file: string, name: string, args?: object): Promise<T> {
37
+ const url = `${String(file).replace(/\/+$/, '')}/${encodeURIComponent(name)}`;
38
+ for (let attempt = 0; ; attempt++) {
39
+ let res: Response;
40
+ try {
41
+ // text/plain keeps this a "simple" request: the sandboxed page has no origin, and a
42
+ // JSON content type would need a CORS preflight the app's host does not answer.
43
+ res = await fetch(url, {
44
+ method: 'POST',
45
+ headers: { 'content-type': 'text/plain;charset=UTF-8', accept: 'application/json' },
46
+ body: JSON.stringify(args ?? {}),
47
+ });
48
+ } catch (err) {
49
+ throw new ApiError(`${name}: the app's server could not be reached`, 0, err);
50
+ }
51
+ if ((res.status === 503 || res.status === 429) && attempt < 3) {
52
+ const seconds = Number(res.headers.get('retry-after')) || 2 * (attempt + 1);
53
+ await sleep(Math.min(seconds, 10) * 1000);
54
+ continue;
55
+ }
56
+ const text = await res.text();
57
+ let body: unknown = null;
58
+ if (text) {
59
+ try {
60
+ body = JSON.parse(text);
61
+ } catch {
62
+ body = text;
63
+ }
64
+ }
65
+ if (!res.ok) {
66
+ const error =
67
+ body && typeof body === 'object' && 'error' in body ? String(body.error) : '';
68
+ const message =
69
+ error ||
70
+ (typeof body === 'string' && body ? body.slice(0, 300) : '') ||
71
+ `${name} failed (${res.status})`;
72
+ throw new ApiError(message, res.status, body);
73
+ }
74
+ return body as T;
75
+ }
76
+ }
77
+
78
+ /**
79
+ * The functions of one .api.py file, by its path relative to the page without `.api.py`.
80
+ * Give it an interface of the functions to have their arguments and results checked.
81
+ */
82
+ export function api<T extends object = AnyApi>(file: string): T {
83
+ return new Proxy(
84
+ {},
85
+ {
86
+ get(_, name) {
87
+ // `then` too: an object returned from an async function must not look like a promise.
88
+ if (typeof name !== 'string' || name === 'then') return undefined;
89
+ return (args?: object) => call(file, name, args);
90
+ },
91
+ },
92
+ ) as T;
93
+ }
@@ -0,0 +1,266 @@
1
+ import { useEffect, useState, type CSSProperties, type ReactNode } from 'react';
2
+ import { fmt } from './format.ts';
3
+
4
+ /**
5
+ * The page: a heading, the content, and a footer naming the source. `narrow` (900 px) suits
6
+ * an app or a list, `wide` (1400 px) a dashboard.
7
+ */
8
+ export function Page({
9
+ title,
10
+ subtitle,
11
+ actions,
12
+ footer,
13
+ width = 'wide',
14
+ children,
15
+ }: {
16
+ title?: ReactNode;
17
+ subtitle?: ReactNode;
18
+ /** buttons or a "signed in as" beside the heading */
19
+ actions?: ReactNode;
20
+ footer?: ReactNode;
21
+ width?: 'narrow' | 'wide';
22
+ children?: ReactNode;
23
+ }) {
24
+ return (
25
+ <main className={`page page-${width}`}>
26
+ {(title || subtitle || actions) && (
27
+ <header className="page-header">
28
+ <div className="page-heading">
29
+ {title && <h1>{title}</h1>}
30
+ {subtitle && <p>{subtitle}</p>}
31
+ </div>
32
+ {actions && <div className="row">{actions}</div>}
33
+ </header>
34
+ )}
35
+ {children}
36
+ {footer && <footer className="page-footer">{footer}</footer>}
37
+ </main>
38
+ );
39
+ }
40
+
41
+ /** The controls of the page, in one row that wraps on a narrow panel. */
42
+ export function Toolbar({ children }: { children?: ReactNode }) {
43
+ return <section className="card toolbar">{children}</section>;
44
+ }
45
+
46
+ /** A labelled control: `<Field label="From"><input type="date" … /></Field>`. */
47
+ export function Field({ label, children }: { label: ReactNode; children?: ReactNode }) {
48
+ return (
49
+ <label className="field">
50
+ <span>{label}</span>
51
+ {children}
52
+ </label>
53
+ );
54
+ }
55
+
56
+ export type Option = string | { value: string; label: string };
57
+
58
+ /** A select over `options`; `all` adds a first option with value `''` ("All"). */
59
+ export function Select({
60
+ label,
61
+ value,
62
+ options,
63
+ onChange,
64
+ all,
65
+ }: {
66
+ label?: string;
67
+ value: string;
68
+ options: readonly Option[];
69
+ onChange: (value: string) => void;
70
+ all?: string;
71
+ }) {
72
+ const select = (
73
+ <select value={value} onChange={(e) => onChange(e.target.value)} aria-label={label}>
74
+ {all !== undefined && <option value="">{all}</option>}
75
+ {options.map((o) => {
76
+ const { value: v, label: l } = typeof o === 'string' ? { value: o, label: o } : o;
77
+ return (
78
+ <option key={v} value={v}>
79
+ {l}
80
+ </option>
81
+ );
82
+ })}
83
+ </select>
84
+ );
85
+ return label ? <Field label={label}>{select}</Field> : select;
86
+ }
87
+
88
+ /** A row of headline numbers. */
89
+ export function Kpis({ children }: { children?: ReactNode }) {
90
+ return <section className="kpis">{children}</section>;
91
+ }
92
+
93
+ /** One headline number: `value` already formatted, `delta` a fraction (0.12 is +12%). */
94
+ export function Kpi({
95
+ label,
96
+ value,
97
+ delta,
98
+ hint,
99
+ }: {
100
+ label: ReactNode;
101
+ value: ReactNode;
102
+ delta?: number | null;
103
+ hint?: ReactNode;
104
+ }) {
105
+ return (
106
+ <div className="card kpi">
107
+ <div className="kpi-label">{label}</div>
108
+ <div className="kpi-value">{value}</div>
109
+ {delta != null && (
110
+ <div className={`kpi-delta ${delta >= 0 ? 'up' : 'down'}`}>
111
+ {delta >= 0 ? '▲' : '▼'} {fmt.pct(Math.abs(delta))}
112
+ </div>
113
+ )}
114
+ {hint && <div className="kpi-hint">{hint}</div>}
115
+ </div>
116
+ );
117
+ }
118
+
119
+ /** Cards side by side when there is room, one per row when there is not. */
120
+ export function Grid({ children, min = 420 }: { children?: ReactNode; min?: number }) {
121
+ return (
122
+ <section className="grid" style={{ '--min': `${min}px` } as CSSProperties}>
123
+ {children}
124
+ </section>
125
+ );
126
+ }
127
+
128
+ /** A box with a heading; `wide` spans the whole row of a Grid. */
129
+ export function Card({
130
+ title,
131
+ actions,
132
+ wide,
133
+ className,
134
+ children,
135
+ }: {
136
+ title?: ReactNode;
137
+ actions?: ReactNode;
138
+ wide?: boolean;
139
+ className?: string;
140
+ children?: ReactNode;
141
+ }) {
142
+ return (
143
+ <section className={['card', wide && 'wide', className].filter(Boolean).join(' ')}>
144
+ {(title || actions) && (
145
+ <div className="card-header">
146
+ {title && <h2>{title}</h2>}
147
+ {actions && <div className="row">{actions}</div>}
148
+ </div>
149
+ )}
150
+ {children}
151
+ </section>
152
+ );
153
+ }
154
+
155
+ /**
156
+ * A list and the item opened from it. Wide: side by side. Narrow (the chat's side panel):
157
+ * the list, or the item when one is open - give the item a Back button that closes it.
158
+ */
159
+ export function Split({
160
+ list,
161
+ detail,
162
+ open,
163
+ }: {
164
+ list: ReactNode;
165
+ detail: ReactNode;
166
+ /** whether an item is open (detail shown instead of the list when narrow) */
167
+ open: boolean;
168
+ }) {
169
+ return (
170
+ <div className={`split${open ? ' split-open' : ''}`}>
171
+ <div className="split-list">{list}</div>
172
+ <div className="split-detail">{detail}</div>
173
+ </div>
174
+ );
175
+ }
176
+
177
+ export function Loading({ children = 'Loading…' }: { children?: ReactNode }) {
178
+ return (
179
+ <p className="muted" role="status">
180
+ {children}
181
+ </p>
182
+ );
183
+ }
184
+
185
+ /** What there is to say when there is nothing to show: "No orders yet". */
186
+ export function Empty({ children = 'Nothing here yet.' }: { children?: ReactNode }) {
187
+ return <p className="muted empty">{children}</p>;
188
+ }
189
+
190
+ /** An error, shown on the page; nothing when there is none. */
191
+ export function ErrorBox({ error, onRetry }: { error: unknown; onRetry?: () => void }) {
192
+ if (!error) return null;
193
+ const message = error instanceof Error ? error.message : String(error);
194
+ return (
195
+ <div className="card error" role="alert">
196
+ <span>{message}</span>
197
+ {onRetry && <button onClick={onRetry}>Try again</button>}
198
+ </div>
199
+ );
200
+ }
201
+
202
+ /**
203
+ * A button that asks for a second click before it acts: the page has no confirm() dialog.
204
+ *
205
+ * <ConfirmButton onConfirm={() => remove.run(item.id)}>Delete</ConfirmButton>
206
+ */
207
+ export function ConfirmButton({
208
+ onConfirm,
209
+ children,
210
+ confirm = 'Sure?',
211
+ className = 'danger',
212
+ disabled,
213
+ timeoutMs = 3000,
214
+ }: {
215
+ onConfirm: () => unknown;
216
+ children?: ReactNode;
217
+ /** the label while it waits for the second click */
218
+ confirm?: ReactNode;
219
+ className?: string;
220
+ disabled?: boolean;
221
+ timeoutMs?: number;
222
+ }) {
223
+ const [armed, setArmed] = useState(false);
224
+ useEffect(() => {
225
+ if (!armed) return;
226
+ const timer = setTimeout(() => setArmed(false), timeoutMs);
227
+ return () => clearTimeout(timer);
228
+ }, [armed, timeoutMs]);
229
+ return (
230
+ <button
231
+ className={className}
232
+ disabled={disabled}
233
+ onClick={() => {
234
+ if (!armed) return setArmed(true);
235
+ setArmed(false);
236
+ void onConfirm();
237
+ }}
238
+ >
239
+ {armed ? confirm : children}
240
+ </button>
241
+ );
242
+ }
243
+
244
+ /**
245
+ * HTML from outside - an email body, a fetched article - shown in a sandboxed frame where its
246
+ * scripts cannot run and its links open in a new tab. Never put such HTML in the page itself.
247
+ */
248
+ export function SafeHtml({
249
+ html,
250
+ title = 'Content',
251
+ height = 400,
252
+ }: {
253
+ html: string;
254
+ title?: string;
255
+ height?: number | string;
256
+ }) {
257
+ return (
258
+ <iframe
259
+ className="safe-html"
260
+ sandbox="allow-popups allow-popups-to-escape-sandbox"
261
+ srcDoc={`<base target="_blank">${html}`}
262
+ title={title}
263
+ style={{ height }}
264
+ />
265
+ );
266
+ }
@@ -0,0 +1,60 @@
1
+ /** Numbers, money, percents and dates as the reader's locale writes them; `–` for none. */
2
+ export const fmt = {
3
+ num(value: number | null | undefined, digits = 0): string {
4
+ return value == null || Number.isNaN(value)
5
+ ? '–'
6
+ : new Intl.NumberFormat(undefined, { maximumFractionDigits: digits }).format(value);
7
+ },
8
+ money(value: number | null | undefined, currency = 'USD', digits = 0): string {
9
+ return value == null || Number.isNaN(value)
10
+ ? '–'
11
+ : new Intl.NumberFormat(undefined, {
12
+ style: 'currency',
13
+ currency,
14
+ maximumFractionDigits: digits,
15
+ }).format(value);
16
+ },
17
+ /** a fraction: 0.12 is 12% */
18
+ pct(value: number | null | undefined, digits = 1): string {
19
+ return value == null || Number.isNaN(value)
20
+ ? '–'
21
+ : new Intl.NumberFormat(undefined, {
22
+ style: 'percent',
23
+ maximumFractionDigits: digits,
24
+ }).format(value);
25
+ },
26
+ date(
27
+ value: string | number | Date | null | undefined,
28
+ style: 'short' | 'medium' | 'long' = 'medium',
29
+ ): string {
30
+ if (value == null || value === '') return '–';
31
+ const date = value instanceof Date ? value : new Date(value);
32
+ return Number.isNaN(date.getTime())
33
+ ? String(value)
34
+ : new Intl.DateTimeFormat(undefined, { dateStyle: style }).format(date);
35
+ },
36
+ };
37
+
38
+ /** The total of a numeric field; values that are not numbers count as 0. */
39
+ export function sum<T extends object>(rows: readonly T[], field: keyof T): number {
40
+ return rows.reduce((total, row) => total + (Number(row[field]) || 0), 0);
41
+ }
42
+
43
+ /** `[key, total]` per distinct value of `key`, in first-seen order. */
44
+ export function groupSum<T extends object>(
45
+ rows: readonly T[],
46
+ key: keyof T,
47
+ field: keyof T,
48
+ ): [string, number][] {
49
+ const totals = new Map<string, number>();
50
+ for (const row of rows) {
51
+ const k = String(row[key]);
52
+ totals.set(k, (totals.get(k) ?? 0) + (Number(row[field]) || 0));
53
+ }
54
+ return [...totals.entries()];
55
+ }
56
+
57
+ /** The distinct values of a field, sorted. */
58
+ export function uniq<T extends object>(rows: readonly T[], field: keyof T): string[] {
59
+ return [...new Set(rows.map((row) => String(row[field])))].sort();
60
+ }
@@ -0,0 +1,159 @@
1
+ import { useCallback, useEffect, useRef, useState, type DependencyList } from 'react';
2
+
3
+ /** Anything thrown, as an Error with a message to show. */
4
+ export function toError(err: unknown): Error {
5
+ return err instanceof Error ? err : new Error(String(err));
6
+ }
7
+
8
+ export interface Call<T> {
9
+ /** the last result; undefined until the first one arrives */
10
+ data: T | undefined;
11
+ /** what the last call threw, until the next one succeeds */
12
+ error: Error | undefined;
13
+ loading: boolean;
14
+ /** call again, e.g. after a change was saved */
15
+ reload: () => Promise<void>;
16
+ /** replace the data in place, e.g. with what a save returned */
17
+ setData: (data: T) => void;
18
+ }
19
+
20
+ /**
21
+ * Calls `fn` when the component mounts and whenever `deps` change, and keeps its result,
22
+ * error and loading state. A slower earlier call never overwrites a later one.
23
+ *
24
+ * const list = useCall(() => items.list_items({ show }), [show]);
25
+ */
26
+ export function useCall<T>(fn: () => Promise<T>, deps: DependencyList = []): Call<T> {
27
+ const [data, setData] = useState<T>();
28
+ const [error, setError] = useState<Error>();
29
+ const [loading, setLoading] = useState(true);
30
+ const latest = useRef(0);
31
+ const fnRef = useRef(fn);
32
+ fnRef.current = fn;
33
+
34
+ const reload = useCallback(async () => {
35
+ const id = ++latest.current;
36
+ setLoading(true);
37
+ try {
38
+ const value = await fnRef.current();
39
+ if (id === latest.current) {
40
+ setData(() => value);
41
+ setError(undefined);
42
+ }
43
+ } catch (err) {
44
+ if (id === latest.current) setError(toError(err));
45
+ } finally {
46
+ if (id === latest.current) setLoading(false);
47
+ }
48
+ }, []);
49
+
50
+ useEffect(() => {
51
+ void reload();
52
+ return () => {
53
+ latest.current++;
54
+ };
55
+ }, deps);
56
+
57
+ const set = useCallback((value: T) => setData(() => value), []);
58
+ return { data, error, loading, reload, setData: set };
59
+ }
60
+
61
+ /** A JSON file by its path relative to the page. */
62
+ export async function fetchJson<T = any>(file: string): Promise<T> {
63
+ const res = await fetch(file);
64
+ if (!res.ok) throw new Error(`${file}: ${res.status} ${res.statusText}`.trim());
65
+ return (await res.json()) as T;
66
+ }
67
+
68
+ /** A JSON file beside the page, `data.json` by default, as a useCall. */
69
+ export function useData<T = any>(file = 'data.json'): Call<T> {
70
+ return useCall(() => fetchJson<T>(file), [file]);
71
+ }
72
+
73
+ export interface Action<A extends unknown[]> {
74
+ /** runs the action; resolves true when it (and `after`) succeeded */
75
+ run: (...args: A) => Promise<boolean>;
76
+ busy: boolean;
77
+ error: Error | undefined;
78
+ clear: () => void;
79
+ }
80
+
81
+ /**
82
+ * A change the user makes: runs `fn`, then `after` (usually a list's reload), keeping busy and
83
+ * error state for the button and the error box.
84
+ *
85
+ * const add = useAction((title: string) => items.add_item({ title }), list.reload);
86
+ * <button disabled={add.busy} onClick={() => add.run(text)}>Add</button>
87
+ */
88
+ export function useAction<A extends unknown[]>(
89
+ fn: (...args: A) => Promise<unknown>,
90
+ after?: () => unknown,
91
+ ): Action<A> {
92
+ const [busy, setBusy] = useState(false);
93
+ const [error, setError] = useState<Error>();
94
+ const fnRef = useRef(fn);
95
+ fnRef.current = fn;
96
+ const afterRef = useRef(after);
97
+ afterRef.current = after;
98
+
99
+ const run = useCallback(async (...args: A) => {
100
+ setBusy(true);
101
+ setError(undefined);
102
+ try {
103
+ await fnRef.current(...args);
104
+ await afterRef.current?.();
105
+ return true;
106
+ } catch (err) {
107
+ setError(toError(err));
108
+ return false;
109
+ } finally {
110
+ setBusy(false);
111
+ }
112
+ }, []);
113
+ const clear = useCallback(() => setError(undefined), []);
114
+ return { run, busy, error, clear };
115
+ }
116
+
117
+ function hashParams(): URLSearchParams {
118
+ return new URLSearchParams(location.hash.replace(/^#/, ''));
119
+ }
120
+
121
+ /**
122
+ * A piece of view state kept in the page's `#hash` (`#tab=orders&id=7`), so a reload or a
123
+ * shared link opens the same view. Storage is not available to pages; this is.
124
+ */
125
+ export function useHashState(key: string, initial = ''): [string, (value: string) => void] {
126
+ const [value, setValue] = useState(() => hashParams().get(key) ?? initial);
127
+ useEffect(() => {
128
+ const sync = () => setValue(hashParams().get(key) ?? initial);
129
+ window.addEventListener('hashchange', sync);
130
+ return () => window.removeEventListener('hashchange', sync);
131
+ }, [key, initial]);
132
+ const set = useCallback(
133
+ (next: string) => {
134
+ const params = hashParams();
135
+ if (next === initial) params.delete(key);
136
+ else params.set(key, next);
137
+ location.hash = params.toString();
138
+ setValue(next);
139
+ },
140
+ [key, initial],
141
+ );
142
+ return [value, set];
143
+ }
144
+
145
+ const DARK = '(prefers-color-scheme: dark)';
146
+
147
+ /** Whether the page is shown in dark mode; follows the system as it changes. */
148
+ export function useDarkMode(): boolean {
149
+ const [dark, setDark] = useState(
150
+ () => typeof matchMedia === 'function' && matchMedia(DARK).matches,
151
+ );
152
+ useEffect(() => {
153
+ const media = matchMedia(DARK);
154
+ const sync = () => setDark(media.matches);
155
+ media.addEventListener('change', sync);
156
+ return () => media.removeEventListener('change', sync);
157
+ }, []);
158
+ return dark;
159
+ }