@zenera/cli 1.3.22 → 1.3.24
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/package.json +6 -6
- package/templates/editor/.github/skills/zen-review/scripts/check-paths.sh +1 -1
- package/templates/project/agents/skills/html-page/SKILL.md +164 -57
- package/templates/project/agents/skills/html-page/assets/app/api/items.api.py +3 -2
- package/templates/project/agents/skills/html-page/assets/app/app.tsx +140 -0
- package/templates/project/agents/skills/html-page/assets/dashboard.tsx +162 -0
- package/templates/project/agents/skills/html-page/kit/Chart.tsx +79 -0
- package/templates/project/agents/skills/html-page/kit/Table.tsx +89 -0
- package/templates/project/agents/skills/html-page/kit/api.ts +93 -0
- package/templates/project/agents/skills/html-page/kit/components.tsx +302 -0
- package/templates/project/agents/skills/html-page/kit/format.ts +60 -0
- package/templates/project/agents/skills/html-page/kit/hooks.ts +159 -0
- package/templates/project/agents/skills/html-page/kit/index.ts +36 -0
- package/templates/project/agents/skills/html-page/kit/modules.d.ts +37 -0
- package/templates/project/agents/skills/html-page/kit/mount.tsx +62 -0
- package/templates/project/agents/skills/html-page/kit/shell.html +19 -0
- package/templates/project/agents/skills/html-page/kit/theme.css +356 -0
- package/templates/project/agents/skills/html-page/references/charts-and-tables.md +105 -53
- package/templates/project/agents/skills/html-page/references/python-functions.md +37 -29
- package/templates/project/agents/skills/html-page/scripts/build.ts +990 -0
- package/templates/project/agents/skills/html-page/assets/api.js +0 -87
- package/templates/project/agents/skills/html-page/assets/app/index.html +0 -278
- package/templates/project/agents/skills/html-page/assets/dashboard.html +0 -423
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { useEffect, useRef } from 'react';
|
|
2
|
+
import { useDarkMode } from './hooks.ts';
|
|
3
|
+
|
|
4
|
+
/** An ECharts option object: https://echarts.apache.org/en/option.html */
|
|
5
|
+
export type ChartOption = Record<string, any>;
|
|
6
|
+
|
|
7
|
+
/** What a click on a bar, point or slice gives: `name` is its category. */
|
|
8
|
+
export interface ChartEvent {
|
|
9
|
+
name: string;
|
|
10
|
+
value: unknown;
|
|
11
|
+
seriesName?: string;
|
|
12
|
+
dataIndex: number;
|
|
13
|
+
data: unknown;
|
|
14
|
+
[key: string]: unknown;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
interface EChart {
|
|
18
|
+
setOption(option: ChartOption, notMerge?: boolean): void;
|
|
19
|
+
resize(): void;
|
|
20
|
+
dispose(): void;
|
|
21
|
+
on(event: string, handler: (event: ChartEvent) => void): void;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// Loaded from the CDN by the page's html; the build adds it when a page uses Chart.
|
|
25
|
+
declare const echarts: { init(el: HTMLElement, theme?: string | null): EChart };
|
|
26
|
+
|
|
27
|
+
const BASE: ChartOption = {
|
|
28
|
+
backgroundColor: 'transparent',
|
|
29
|
+
tooltip: { trigger: 'axis', confine: true },
|
|
30
|
+
grid: { left: 8, right: 16, top: 32, bottom: 8, containLabel: true },
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* An ECharts chart that fills its card's width, follows the panel's size and the light/dark
|
|
35
|
+
* scheme, and redraws when `option` changes. Top-level keys of `option` replace the defaults
|
|
36
|
+
* (an axis tooltip, a tight grid); a pie wants `tooltip: { trigger: 'item' }`.
|
|
37
|
+
*
|
|
38
|
+
* <Chart option={{ xAxis: {…}, yAxis: {…}, series: [{ type: 'bar', data }] }} />
|
|
39
|
+
*/
|
|
40
|
+
export function Chart({
|
|
41
|
+
option,
|
|
42
|
+
height = 320,
|
|
43
|
+
onClick,
|
|
44
|
+
className,
|
|
45
|
+
}: {
|
|
46
|
+
option: ChartOption;
|
|
47
|
+
height?: number | string;
|
|
48
|
+
onClick?: (event: ChartEvent) => void;
|
|
49
|
+
className?: string;
|
|
50
|
+
}) {
|
|
51
|
+
const el = useRef<HTMLDivElement>(null);
|
|
52
|
+
const chart = useRef<EChart | null>(null);
|
|
53
|
+
const optionRef = useRef(option);
|
|
54
|
+
optionRef.current = option;
|
|
55
|
+
const clickRef = useRef(onClick);
|
|
56
|
+
clickRef.current = onClick;
|
|
57
|
+
const dark = useDarkMode();
|
|
58
|
+
|
|
59
|
+
useEffect(() => {
|
|
60
|
+
const node = el.current!;
|
|
61
|
+
const c = echarts.init(node, dark ? 'dark' : null);
|
|
62
|
+
chart.current = c;
|
|
63
|
+
c.setOption({ ...BASE, ...optionRef.current }, true);
|
|
64
|
+
c.on('click', (event) => clickRef.current?.(event));
|
|
65
|
+
const resize = new ResizeObserver(() => c.resize());
|
|
66
|
+
resize.observe(node);
|
|
67
|
+
return () => {
|
|
68
|
+
resize.disconnect();
|
|
69
|
+
c.dispose();
|
|
70
|
+
chart.current = null;
|
|
71
|
+
};
|
|
72
|
+
}, [dark]);
|
|
73
|
+
|
|
74
|
+
useEffect(() => {
|
|
75
|
+
chart.current?.setOption({ ...BASE, ...option }, true);
|
|
76
|
+
}, [option]);
|
|
77
|
+
|
|
78
|
+
return <div ref={el} className={`chart ${className ?? ''}`} style={{ height }} />;
|
|
79
|
+
}
|
|
@@ -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,302 @@
|
|
|
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
|
+
/** Cards and blocks one under another, with the page's gap. */
|
|
156
|
+
export function Stack({ children }: { children?: ReactNode }) {
|
|
157
|
+
return <div className="stack">{children}</div>;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* A list and what is open from it: a message, a record, a form to write a new one.
|
|
162
|
+
*
|
|
163
|
+
* Wide: side by side, `placeholder` on the right while nothing is open.
|
|
164
|
+
* Narrow (the chat's side panel): the list, or - while `detail` is given - only the detail,
|
|
165
|
+
* with a Back button (calling `onBack`) above it.
|
|
166
|
+
*
|
|
167
|
+
* `detail` is null when nothing is open, and whatever is open otherwise: anything the user
|
|
168
|
+
* can open, including a compose or edit form, goes in it, so it is reachable at every width.
|
|
169
|
+
*
|
|
170
|
+
* <Split
|
|
171
|
+
* list={<Inbox onOpen={setOpenId} onNew={() => setComposing(true)} />}
|
|
172
|
+
* detail={composing ? <Compose … /> : openId != null ? <Message id={openId} /> : null}
|
|
173
|
+
* onBack={() => { setComposing(false); setOpenId(null); }}
|
|
174
|
+
* />
|
|
175
|
+
*/
|
|
176
|
+
export function Split({
|
|
177
|
+
list,
|
|
178
|
+
detail,
|
|
179
|
+
onBack,
|
|
180
|
+
placeholder = 'Pick an item to open it.',
|
|
181
|
+
backLabel = 'Back',
|
|
182
|
+
}: {
|
|
183
|
+
list: ReactNode;
|
|
184
|
+
/** what is open, or null (or false) when nothing is */
|
|
185
|
+
detail: ReactNode;
|
|
186
|
+
/** closes what is open: the narrow layout's Back button */
|
|
187
|
+
onBack: () => void;
|
|
188
|
+
placeholder?: ReactNode;
|
|
189
|
+
backLabel?: ReactNode;
|
|
190
|
+
}) {
|
|
191
|
+
const open = detail != null && detail !== false;
|
|
192
|
+
return (
|
|
193
|
+
<div className={`split${open ? ' split-open' : ''}`}>
|
|
194
|
+
<div className="split-list">{list}</div>
|
|
195
|
+
<div className="split-detail">
|
|
196
|
+
{open ? (
|
|
197
|
+
<>
|
|
198
|
+
<button className="split-back" onClick={onBack}>
|
|
199
|
+
← {backLabel}
|
|
200
|
+
</button>
|
|
201
|
+
{detail}
|
|
202
|
+
</>
|
|
203
|
+
) : (
|
|
204
|
+
<Card>
|
|
205
|
+
<Empty>{placeholder}</Empty>
|
|
206
|
+
</Card>
|
|
207
|
+
)}
|
|
208
|
+
</div>
|
|
209
|
+
</div>
|
|
210
|
+
);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export function Loading({ children = 'Loading…' }: { children?: ReactNode }) {
|
|
214
|
+
return (
|
|
215
|
+
<p className="muted" role="status">
|
|
216
|
+
{children}
|
|
217
|
+
</p>
|
|
218
|
+
);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** What there is to say when there is nothing to show: "No orders yet". */
|
|
222
|
+
export function Empty({ children = 'Nothing here yet.' }: { children?: ReactNode }) {
|
|
223
|
+
return <p className="muted empty">{children}</p>;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** An error, shown on the page; nothing when there is none. */
|
|
227
|
+
export function ErrorBox({ error, onRetry }: { error: unknown; onRetry?: () => void }) {
|
|
228
|
+
if (!error) return null;
|
|
229
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
230
|
+
return (
|
|
231
|
+
<div className="card error" role="alert">
|
|
232
|
+
<span>{message}</span>
|
|
233
|
+
{onRetry && <button onClick={onRetry}>Try again</button>}
|
|
234
|
+
</div>
|
|
235
|
+
);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* A button that asks for a second click before it acts: the page has no confirm() dialog.
|
|
240
|
+
*
|
|
241
|
+
* <ConfirmButton onConfirm={() => remove.run(item.id)}>Delete</ConfirmButton>
|
|
242
|
+
*/
|
|
243
|
+
export function ConfirmButton({
|
|
244
|
+
onConfirm,
|
|
245
|
+
children,
|
|
246
|
+
confirm = 'Sure?',
|
|
247
|
+
className = 'danger',
|
|
248
|
+
disabled,
|
|
249
|
+
timeoutMs = 3000,
|
|
250
|
+
}: {
|
|
251
|
+
onConfirm: () => unknown;
|
|
252
|
+
children?: ReactNode;
|
|
253
|
+
/** the label while it waits for the second click */
|
|
254
|
+
confirm?: ReactNode;
|
|
255
|
+
className?: string;
|
|
256
|
+
disabled?: boolean;
|
|
257
|
+
timeoutMs?: number;
|
|
258
|
+
}) {
|
|
259
|
+
const [armed, setArmed] = useState(false);
|
|
260
|
+
useEffect(() => {
|
|
261
|
+
if (!armed) return;
|
|
262
|
+
const timer = setTimeout(() => setArmed(false), timeoutMs);
|
|
263
|
+
return () => clearTimeout(timer);
|
|
264
|
+
}, [armed, timeoutMs]);
|
|
265
|
+
return (
|
|
266
|
+
<button
|
|
267
|
+
className={className}
|
|
268
|
+
disabled={disabled}
|
|
269
|
+
onClick={() => {
|
|
270
|
+
if (!armed) return setArmed(true);
|
|
271
|
+
setArmed(false);
|
|
272
|
+
void onConfirm();
|
|
273
|
+
}}
|
|
274
|
+
>
|
|
275
|
+
{armed ? confirm : children}
|
|
276
|
+
</button>
|
|
277
|
+
);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* HTML from outside - an email body, a fetched article - shown in a sandboxed frame where its
|
|
282
|
+
* scripts cannot run and its links open in a new tab. Never put such HTML in the page itself.
|
|
283
|
+
*/
|
|
284
|
+
export function SafeHtml({
|
|
285
|
+
html,
|
|
286
|
+
title = 'Content',
|
|
287
|
+
height = 400,
|
|
288
|
+
}: {
|
|
289
|
+
html: string;
|
|
290
|
+
title?: string;
|
|
291
|
+
height?: number | string;
|
|
292
|
+
}) {
|
|
293
|
+
return (
|
|
294
|
+
<iframe
|
|
295
|
+
className="safe-html"
|
|
296
|
+
sandbox="allow-popups allow-popups-to-escape-sandbox"
|
|
297
|
+
srcDoc={`<base target="_blank">${html}`}
|
|
298
|
+
title={title}
|
|
299
|
+
style={{ height }}
|
|
300
|
+
/>
|
|
301
|
+
);
|
|
302
|
+
}
|
|
@@ -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
|
+
}
|