@zenera/cli 1.3.21 → 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 +40 -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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zenera/cli",
3
- "version": "1.3.21",
3
+ "version": "1.3.23",
4
4
  "description": "Command-line front end for @zenera/neo: agentic projects you can run, share and commit.",
5
5
  "keywords": [
6
6
  "agents",
@@ -56,11 +56,11 @@
56
56
  "@google/genai": "^2.30.0",
57
57
  "@inkjs/ui": "^2.0.0",
58
58
  "@openrouter/sdk": "^1.4.25",
59
- "@zenera/engine": "^1.3.21",
60
- "@zenera/neo": "^1.3.21",
61
- "@zenera/sandbox": "^1.3.21",
62
- "@zenera/server": "^1.3.21",
63
- "@zenera/view": "^1.3.21",
59
+ "@zenera/engine": "^1.3.23",
60
+ "@zenera/neo": "^1.3.23",
61
+ "@zenera/sandbox": "^1.3.23",
62
+ "@zenera/server": "^1.3.23",
63
+ "@zenera/view": "^1.3.23",
64
64
  "google-auth-library": "^10.0.0",
65
65
  "ink": "^7.1.1",
66
66
  "openai": "^6.0.0",
@@ -54,7 +54,7 @@ strip_urls() {
54
54
  # any byte that differs as `rules.stale`.
55
55
  #
56
56
  # The html-page skill is left out too. Its paths are the page's own urls,
57
- # relative to the page (`api('api/orders')`, `../api.js`), and to this sweep
57
+ # relative to the page (`api('api/orders')`, `useData('../data.json')`), and to this sweep
58
58
  # they look exactly like files the agent cannot open.
59
59
  files() {
60
60
  {
@@ -1,11 +1,11 @@
1
1
  ---
2
2
  name: html-page
3
- description: Building an interactive HTML page the user opens from the chat - a dashboard or report with charts, tables, filters and headline numbers, or a small app whose page calls Python functions to read and change data (a tracker, a CRUD tool, a form that saves, a page that queries a database each time it opens). Where to write it, how it gets its data, the layout that works in the chat's side panel and full page, and how to check it. Load when an answer has more than one chart or table, data the user will want to filter or explore, or the user wants something to use and change.
4
- tags: [html, dashboard, report, app, charts, api, python, ui]
5
- version: 1.0.0
3
+ description: Building an interactive page the user opens from the chat - a dashboard or report with charts, tables, filters and headline numbers, or a small app whose page calls Python functions to read and change data (a tracker, a CRUD tool, a mail or ticket view, a form that saves, a page that queries a database each time it opens). The page is a React component in TypeScript (app.tsx) that a build checks and turns into one HTML file. Where to write it, how it gets its data, the kit of components, the layout that works in the chat's side panel and full page, and how to build and check it. Load when an answer has more than one chart or table, data the user will want to filter or explore, or the user wants something to use and change.
4
+ tags: [html, react, typescript, dashboard, report, app, charts, api, python, ui]
5
+ version: 2.0.0
6
6
  ---
7
7
 
8
- # Interactive HTML pages
8
+ # Interactive pages
9
9
 
10
10
  A page is the answer when a reply would be too long or too static: several
11
11
  related charts and tables, a breakdown to filter, sort or drill into, or
@@ -13,6 +13,11 @@ something the user will use and change (add items, edit records, run a
13
13
  query). One chart or a short table is better inline in the chat (load `a2ui`
14
14
  and `a2ui-charts`).
15
15
 
16
+ You write the page as **one React component in TypeScript, `app.tsx`**. The
17
+ build checks it (types, what a sandboxed page may do, a first render) and
18
+ writes **`index.html`**, the file the user opens: React, the kit and your code
19
+ inlined, nothing else to copy.
20
+
16
21
  ## First: where its data comes from
17
22
 
18
23
  | The page | Its data | Read next |
@@ -35,11 +40,12 @@ One folder per page, under `/workspace/pages/`:
35
40
 
36
41
  ```
37
42
  /workspace/pages/sales-q1/
38
- ├── index.html the page
43
+ ├── app.tsx the page: export default function App() - you write this
44
+ ├── components/ more components it imports, if it grows (optional)
45
+ ├── index.html written by the build - never edit it
39
46
  ├── data.json data it shows, written by your script (static data)
40
- ├── api.js calls the functions - copied, never edited (functions)
41
47
  └── api/
42
- ├── orders.api.py functions the page calls
48
+ ├── orders.api.py functions the page calls (functions)
43
49
  ├── db.py helpers they import (not callable from the page)
44
50
  └── .data/ the page's own data (SQLite); never downloadable
45
51
  ```
@@ -49,97 +55,136 @@ One folder per page, under `/workspace/pages/`:
49
55
  data.
50
56
  - A script that builds `data.json` goes under `/workspace/.tmp/`, so the page
51
57
  can be refreshed by running it again.
52
- - More pages of one app are more `.html` files in the folder.
58
+ - Every `.tsx` directly in the folder is a page: `app.tsx` builds
59
+ `index.html`, `report.tsx` builds `report.html`. Components it imports go
60
+ in a subfolder (`components/Inbox.tsx`), never beside `app.tsx`.
53
61
 
54
62
  ## Start from a template
55
63
 
56
64
  Copy one and edit it rather than writing a page from scratch:
57
65
 
58
66
  ```sh
59
- # a dashboard or report: charts, KPIs, filters, table
67
+ # a dashboard or report: filters, KPIs, charts, table, from data.json
60
68
  mkdir -p /workspace/pages/sales-q1
61
- cp /skills/html-page/assets/dashboard.html /workspace/pages/sales-q1/index.html
69
+ cp /skills/html-page/assets/dashboard.tsx /workspace/pages/sales-q1/app.tsx
62
70
 
63
71
  # an app: a list kept in SQLite, with add, check off, filter and delete
64
72
  cp -r /skills/html-page/assets/app /workspace/pages/todo
65
- cp /skills/html-page/assets/api.js /workspace/pages/todo/
66
73
  ```
67
74
 
68
- Keep the templates' layout, theme and helpers; replace the part marked
69
- `The page: replace from here`. A dashboard with live data is the dashboard
70
- template plus `api.js` and an `*.api.py`: its `loadData()` says what to
71
- change.
75
+ Keep the template's structure - imports from `@page/kit`, the data's types,
76
+ then `App` - and replace the part marked `The page: replace from here`. A
77
+ dashboard with live data is the dashboard template with `useCall` and an
78
+ `*.api.py`: its comment says what to change.
79
+
80
+ ## The kit: `@page/kit`
81
+
82
+ Import everything from `@page/kit`; React from `react`. Nothing else is
83
+ installed - no npm packages, no CSS frameworks. The kit's source is in
84
+ `/skills/html-page/kit/` if you need to look something up.
85
+
86
+ | Need | Use |
87
+ | -------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
88
+ | Call `*.api.py` functions | `api<ItemsApi>('api/items')` - an interface of the functions you call (python-functions.md) |
89
+ | Load data, with loading and error state | `useCall(() => items.list_items({ show }), [show])`, `useData<Report>('data.json')` |
90
+ | A change the user makes, then reload | `useAction((title: string) => items.add_item({ title }), list.reload)`: `.run`, `.busy`, `.error` |
91
+ | View state that survives a reload (tab, open item) | `useHashState('tab', 'orders')` - kept in `#tab=...` |
92
+ | Layout | `Page` (`width="narrow"` for an app), `Toolbar`, `Grid`, `Card` (`wide`), `Split` |
93
+ | Controls | `Select`, `Field` around any input, plain `<input>`, `<button className="primary">` |
94
+ | Headline numbers | `Kpis` with `Kpi` (`value` formatted, `delta` a fraction) |
95
+ | Charts | `Chart` with an ECharts `option` (charts-and-tables.md) |
96
+ | Tables | `Table` with Tabulator `columns` (charts-and-tables.md) |
97
+ | States | `Loading`, `Empty`, `ErrorBox` |
98
+ | Delete and other destructive actions | `ConfirmButton` - acts on the second click |
99
+ | HTML from outside (an email, an article) | `SafeHtml` - a sandboxed frame; never put such HTML in the page |
100
+ | Numbers, money, percents, dates | `fmt.num`, `fmt.money`, `fmt.pct`, `fmt.date`; `sum`, `groupSum`, `uniq` for rows |
72
101
 
73
102
  ## How it is shown, and what that allows
74
103
 
75
104
  The chat opens the page in a side panel next to the conversation (often 400 -
76
- 600 px wide) or in a full browser tab. Either way it runs sandboxed:
105
+ 600 px wide) or in a full browser tab. Either way it runs sandboxed. The
106
+ build reports most of these; know them so you do not write them:
77
107
 
78
108
  - It reaches files and functions of its folder **by a path relative to the
79
- page**: `fetch('data.json')`, `<img src="logo.png">`, `api('api/orders')`,
109
+ page**: `useData('data.json')`, `<img src="logo.png">`, `api('api/orders')`,
80
110
  and `..` to go up. Never `file:///`, `/workspace/...`, `http://localhost`
81
111
  or an `.api.py` name in the page.
112
+ - Images and other small files can also be imported (`import logo from
113
+ './logo.png'`) and are inlined.
82
114
  - Scripts, styles and fonts load only from `cdn.jsdelivr.net`, `unpkg.com`
83
115
  and `cdnjs.cloudflare.com`. Any other host is blocked - no external APIs,
84
116
  images, map tiles or analytics from the page. A page that needs an outside
85
117
  service calls a Python function that does.
86
- - No `localStorage`, `sessionStorage`, cookies or `IndexedDB` (the page has
87
- no origin of its own; touching them throws). Keep view state in variables
88
- or `location.hash`, and anything to keep in the database.
89
- - No `<form>` submission: use inputs, buttons and `click` / `change`
90
- listeners. No `alert`, `confirm` or `prompt` (blocked): confirm a delete
91
- with a second click, as the app template does.
118
+ - No `localStorage`, `sessionStorage`, cookies or `IndexedDB`. Keep view
119
+ state in hooks or `useHashState`, and anything to keep in the database.
120
+ - No `alert`, `confirm` or `prompt` (blocked): `ConfirmButton` for a delete,
121
+ `ErrorBox` for a message. No form submission: handle `onClick` /
122
+ `onKeyDown`, or a `<form onSubmit>` that calls `e.preventDefault()`.
92
123
  - Links to other sites need `target="_blank" rel="noopener"`.
93
124
  - The page cannot call the agent or any tool.
94
125
 
95
126
  ## Layout - always adaptive
96
127
 
97
128
  Every page must work at 360 px (narrow panel) and 1600 px (wide tab) without
98
- horizontal scrolling. The templates do this; keep to their rules:
99
-
100
- - `<meta name="viewport" content="width=device-width, initial-scale=1">`.
101
- - No fixed widths: CSS grid that reflows
102
- (`repeat(auto-fit, minmax(min(100%, 420px), 1fr))`), flex rows that wrap.
103
- - Every grid or flex child gets `min-width: 0` (the templates' `.card` has
104
- it), or a chart, table or long text pushes the page wider than the panel.
129
+ horizontal scrolling. The kit's components do this; keep to their rules:
130
+
131
+ - No fixed widths. `Grid` reflows cards, `Toolbar` and `.row` wrap, `Split`
132
+ shows a list and its open item side by side when wide and one at a time
133
+ when narrow (give the item a Back button).
134
+ - Anything you add inside a grid or flex row gets `min-width: 0` (the kit's
135
+ `.card` has it), or a chart, table or long text pushes the page wider than
136
+ the panel.
105
137
  - Let the page scroll; do not lock the body to `100vh`.
106
- - Light and dark: colours come from the CSS variables in `:root`, switched by
107
- `prefers-color-scheme`. Use `var(--fg)`, `var(--muted)` and the rest - no
108
- hard-coded colours in new elements.
138
+ - Light and dark: colours come from the kit's CSS variables, switched by
139
+ `prefers-color-scheme`. Use `var(--fg)`, `var(--muted)`, `var(--line)`,
140
+ `var(--accent)`, `var(--danger)` - no hard-coded colours. For styles of
141
+ your own, `import './app.css'`.
109
142
  - Controls in one wrapping row at the top; then headline numbers; then
110
143
  charts or the list; the detailed table last.
111
144
 
112
145
  ## Page code
113
146
 
114
- - One `state` object and one `render()` that draws everything from it; every
115
- control only changes `state` and calls `render()` (or reloads first). The
116
- numbers, charts and lists then always agree.
147
+ - `export default function App()` in `app.tsx`; `export const title = '...'`
148
+ names the browser tab. The build mounts `App` - never call `createRoot`.
149
+ - State lives in hooks; everything on the page is drawn from it, so the
150
+ numbers, charts and lists always agree. Derive filtered rows and chart
151
+ options with `useMemo` from the data and the filters.
117
152
  - Show "Loading…", an empty state ("No orders yet", "No data for these
118
- filters") and errors in a box on the page - never fail silently.
119
- - Put values from data into the page with `textContent` (or the templates'
120
- `esc()`), never raw into `innerHTML`.
121
- - Libraries: ECharts for charts, Tabulator for tables, from the CDN URLs in
122
- `dashboard.html`. No CSS frameworks, React or Vue (no build step here).
123
-
124
- ## Check before you link it
153
+ filters") and errors on the page with `Loading`, `Empty` and `ErrorBox` -
154
+ never fail silently. `useCall` and `useAction` catch errors for you.
155
+ - JSX escapes values: `{row.name}` is always safe. Never
156
+ `dangerouslySetInnerHTML` or `innerHTML`; `SafeHtml` for HTML from outside.
157
+ - Touch `window` and `document` only in `useEffect` and in handlers: the
158
+ build renders `App` once without a browser.
159
+ - Type the data: an interface for each row and for the functions you call
160
+ (`ItemsApi`). The build then catches a misspelt field before the user does.
161
+ - A long page is several components: put them in `components/` and import
162
+ them (`import { Inbox } from './components/Inbox'`).
163
+
164
+ ## Build and check before you link it
125
165
 
126
166
  ```sh
127
- cd /workspace/pages/sales-q1
128
- grep -nE "file://|/workspace|localhost|localStorage|sessionStorage|<form|alert\(|confirm\(|prompt\(" *.html || echo "paths ok"
129
- grep -noE "(src|href)=\"https?://[^\"]+" *.html | grep -vE "cdn.jsdelivr.net|unpkg.com|cdnjs.cloudflare.com" || echo "hosts ok"
130
- [ ! -f data.json ] || python3 -c "import json; json.load(open('data.json'))" && echo "data ok"
167
+ node /skills/html-page/scripts/build.ts /workspace/pages/sales-q1
131
168
  ```
132
169
 
133
- Confirm every relative file the page loads exists in its folder. A page with
134
- functions: call each of them from the shell first (`python-functions.md`,
135
- "Test before you link it").
170
+ It type-checks, checks the rules above, renders `App` once, and writes
171
+ `index.html` - or writes nothing and lists what to fix as `file:line:col
172
+ message`. Fix each one and build again until it prints `✓ wrote index.html`.
173
+
174
+ - Build after **every** change to the page's `.tsx`, `.ts` or `.css`. The user
175
+ sees `index.html`, not your source. `node .../build.ts <folder> --check`
176
+ says whether it is out of date.
177
+ - Never edit `index.html` by hand: the next build replaces it.
178
+ - A page with functions: call each of them from the shell first
179
+ (python-functions.md, "Test before you link it").
180
+ - The build runs in the sandbox, where its tools are installed.
136
181
 
137
182
  ## Hand it over
138
183
 
139
184
  - The main findings with their numbers in two to four sentences, or for an
140
185
  app what it does - the reply must stand on its own for someone who never
141
186
  opens the page.
142
- - Then the page as a link, alone in its own paragraph:
187
+ - Then the page as a link, alone in its own paragraph (the build prints it):
143
188
 
144
189
  [Sales Q1 dashboard](file:///workspace/pages/sales-q1/index.html)
145
190
 
@@ -1,8 +1,9 @@
1
- """The app's API: every public function here can be called from index.html.
1
+ """The app's API: every public function here can be called from app.tsx.
2
2
 
3
- const items = api('api/items');
3
+ const items = api<ItemsApi>('api/items');
4
4
  await items.add_item({ title: 'Milk' }) -> add_item(title="Milk")
5
5
 
6
+ Keep the page's ItemsApi interface in step with these functions.
6
7
  Names starting with `_` and anything imported are not callable from the page.
7
8
  Try them from a shell before linking the app:
8
9
 
@@ -0,0 +1,140 @@
1
+ // An app: a list kept in SQLite by api/items.api.py, with add, check off, filter and delete.
2
+ // Copy the whole folder, rename api/items.api.py to what it holds, and change both together.
3
+ import { useState } from 'react';
4
+ import {
5
+ api,
6
+ Card,
7
+ ConfirmButton,
8
+ Empty,
9
+ ErrorBox,
10
+ Loading,
11
+ Page,
12
+ Select,
13
+ useAction,
14
+ useCall,
15
+ } from '@page/kit';
16
+
17
+ // ---- The page: replace from here ----
18
+ // The functions of api/items.api.py as the page calls them: keep this in step with the Python.
19
+
20
+ type Show = 'all' | 'open' | 'done';
21
+
22
+ interface Item {
23
+ id: number;
24
+ title: string;
25
+ done: boolean;
26
+ created: string;
27
+ }
28
+
29
+ interface Me {
30
+ id: string;
31
+ name: string;
32
+ role: string | null;
33
+ }
34
+
35
+ interface ItemsApi {
36
+ me(): Promise<Me | null>;
37
+ list_items(args: { show: Show }): Promise<Item[]>;
38
+ add_item(args: { title: string }): Promise<Item>;
39
+ set_done(args: { id: number; done: boolean }): Promise<Item>;
40
+ remove_item(args: { id: number }): Promise<{ removed: number }>;
41
+ }
42
+
43
+ const items = api<ItemsApi>('api/items');
44
+
45
+ export const title = 'Items';
46
+
47
+ const SHOW = [
48
+ { value: 'all', label: 'All' },
49
+ { value: 'open', label: 'Open' },
50
+ { value: 'done', label: 'Done' },
51
+ ];
52
+
53
+ export default function App() {
54
+ const [show, setShow] = useState<Show>('all');
55
+ const [text, setText] = useState('');
56
+
57
+ // Who is signed in comes from the server (me() in api/items.api.py), never the page.
58
+ const me = useCall(() => items.me(), []);
59
+ const list = useCall(() => items.list_items({ show }), [show]);
60
+
61
+ // Every change: call, then load the list again, so the page shows what is really saved.
62
+ const add = useAction(async (title: string) => {
63
+ await items.add_item({ title });
64
+ setText('');
65
+ }, list.reload);
66
+ const setDone = useAction(
67
+ (id: number, done: boolean) => items.set_done({ id, done }),
68
+ list.reload,
69
+ );
70
+ const remove = useAction((id: number) => items.remove_item({ id }), list.reload);
71
+
72
+ const submit = () => {
73
+ const title = text.trim();
74
+ if (title) void add.run(title);
75
+ };
76
+ const error = add.error ?? setDone.error ?? remove.error ?? list.error ?? me.error;
77
+
78
+ return (
79
+ <Page
80
+ width="narrow"
81
+ title={title}
82
+ subtitle="Add, check off and remove items. Changes are saved."
83
+ actions={me.data && <span className="muted">Signed in as {me.data.name}</span>}
84
+ >
85
+ <ErrorBox error={error} onRetry={list.error ? list.reload : undefined} />
86
+
87
+ <Card>
88
+ <div className="row">
89
+ <input
90
+ type="text"
91
+ placeholder="New item"
92
+ aria-label="New item"
93
+ maxLength={200}
94
+ value={text}
95
+ onChange={(e) => setText(e.target.value)}
96
+ onKeyDown={(e) => e.key === 'Enter' && submit()}
97
+ />
98
+ <button
99
+ className="primary"
100
+ disabled={add.busy || !text.trim()}
101
+ onClick={submit}
102
+ >
103
+ Add
104
+ </button>
105
+ <Select
106
+ value={show}
107
+ options={SHOW}
108
+ onChange={(value) => setShow(value as Show)}
109
+ />
110
+ </div>
111
+ </Card>
112
+
113
+ <Card>
114
+ {list.loading && !list.data ? (
115
+ <Loading />
116
+ ) : !list.data?.length ? (
117
+ <Empty>{show === 'all' ? 'Nothing here yet.' : `No ${show} items.`}</Empty>
118
+ ) : (
119
+ <ul className="list">
120
+ {list.data.map((item) => (
121
+ <li key={item.id} className={item.done ? 'done' : undefined}>
122
+ <input
123
+ type="checkbox"
124
+ aria-label="Done"
125
+ checked={item.done}
126
+ disabled={setDone.busy}
127
+ onChange={(e) => void setDone.run(item.id, e.target.checked)}
128
+ />
129
+ <span className="grow">{item.title}</span>
130
+ <ConfirmButton onConfirm={() => remove.run(item.id)}>
131
+ Delete
132
+ </ConfirmButton>
133
+ </li>
134
+ ))}
135
+ </ul>
136
+ )}
137
+ </Card>
138
+ </Page>
139
+ );
140
+ }
@@ -0,0 +1,162 @@
1
+ // A dashboard: filters, headline numbers, two charts and a table, from data.json beside the page.
2
+ // Copy this to <page>/app.tsx and keep the shape: data, then derived rows, then the page.
3
+ import { useEffect, useMemo, useState } from 'react';
4
+ import {
5
+ Card,
6
+ Chart,
7
+ Empty,
8
+ ErrorBox,
9
+ Grid,
10
+ Kpi,
11
+ Kpis,
12
+ Loading,
13
+ Page,
14
+ Select,
15
+ Table,
16
+ Toolbar,
17
+ fmt,
18
+ groupSum,
19
+ sum,
20
+ uniq,
21
+ useData,
22
+ type Column,
23
+ } from '@page/kit';
24
+
25
+ // ---- The page: replace from here with the real data's fields. ----
26
+ // data.json, written by your script: { "title", "subtitle", "source", "rows": [Row, ...] }.
27
+ // Live data instead: `const report = useCall(() => api<ReportApi>('api/report').get_data(), []);`
28
+ // with get_data() in api/report.api.py returning the same shape (references/python-functions.md).
29
+
30
+ interface Row {
31
+ date: string;
32
+ category: string;
33
+ region: string;
34
+ amount: number;
35
+ }
36
+
37
+ interface Report {
38
+ title: string;
39
+ subtitle?: string;
40
+ source?: string;
41
+ rows: Row[];
42
+ }
43
+
44
+ export const title = 'Dashboard';
45
+
46
+ const columns: Column[] = [
47
+ { title: 'Date', field: 'date', headerFilter: 'input', minWidth: 100 },
48
+ { title: 'Category', field: 'category', headerFilter: 'input' },
49
+ { title: 'Region', field: 'region', headerFilter: 'input' },
50
+ {
51
+ title: 'Amount',
52
+ field: 'amount',
53
+ hozAlign: 'right',
54
+ sorter: 'number',
55
+ formatter: (cell: { getValue(): number }) => fmt.num(cell.getValue(), 2),
56
+ },
57
+ ];
58
+
59
+ export default function App() {
60
+ const report = useData<Report>('data.json');
61
+ const [category, setCategory] = useState('');
62
+ const [region, setRegion] = useState('');
63
+
64
+ const all = report.data?.rows;
65
+ useEffect(() => {
66
+ if (report.data) document.title = report.data.title;
67
+ }, [report.data]);
68
+ const rows = useMemo(
69
+ () =>
70
+ (all ?? []).filter(
71
+ (r) => (!category || r.category === category) && (!region || r.region === region),
72
+ ),
73
+ [all, category, region],
74
+ );
75
+ const byCategory = useMemo(() => {
76
+ const totals = groupSum(rows, 'category', 'amount').sort((a, b) => b[1] - a[1]);
77
+ return {
78
+ xAxis: {
79
+ type: 'category',
80
+ data: totals.map((d) => d[0]),
81
+ axisLabel: { interval: 0, rotate: totals.length > 5 ? 30 : 0 },
82
+ },
83
+ yAxis: { type: 'value' },
84
+ series: [{ type: 'bar', data: totals.map((d) => d[1]) }],
85
+ };
86
+ }, [rows]);
87
+ const overTime = useMemo(() => {
88
+ const totals = groupSum(rows, 'date', 'amount').sort((a, b) => a[0].localeCompare(b[0]));
89
+ return {
90
+ xAxis: { type: 'category', data: totals.map((d) => d[0]) },
91
+ yAxis: { type: 'value' },
92
+ dataZoom: totals.length > 30 ? [{ type: 'inside' }] : [],
93
+ series: [
94
+ {
95
+ type: 'line',
96
+ showSymbol: false,
97
+ areaStyle: { opacity: 0.15 },
98
+ data: totals.map((d) => d[1]),
99
+ },
100
+ ],
101
+ };
102
+ }, [rows]);
103
+
104
+ if (report.error) {
105
+ return (
106
+ <Page title={title}>
107
+ <ErrorBox error={report.error} onRetry={report.reload} />
108
+ </Page>
109
+ );
110
+ }
111
+ if (!report.data || !all) {
112
+ return (
113
+ <Page title={title}>
114
+ <Loading />
115
+ </Page>
116
+ );
117
+ }
118
+ return (
119
+ <Page title={report.data.title} subtitle={report.data.subtitle} footer={report.data.source}>
120
+ <Toolbar>
121
+ <Select
122
+ label="Category"
123
+ all="All"
124
+ value={category}
125
+ options={uniq(all, 'category')}
126
+ onChange={setCategory}
127
+ />
128
+ <Select
129
+ label="Region"
130
+ all="All"
131
+ value={region}
132
+ options={uniq(all, 'region')}
133
+ onChange={setRegion}
134
+ />
135
+ </Toolbar>
136
+
137
+ <Kpis>
138
+ <Kpi label="Total amount" value={fmt.num(sum(rows, 'amount'))} />
139
+ <Kpi label="Rows" value={fmt.num(rows.length)} />
140
+ <Kpi label="Categories" value={fmt.num(uniq(rows, 'category').length)} />
141
+ </Kpis>
142
+
143
+ {rows.length === 0 ? (
144
+ <Card>
145
+ <Empty>No data for these filters.</Empty>
146
+ </Card>
147
+ ) : (
148
+ <Grid>
149
+ <Card title="Amount by category">
150
+ <Chart option={byCategory} onClick={(e) => setCategory(e.name)} />
151
+ </Card>
152
+ <Card title="Amount over time">
153
+ <Chart option={overTime} />
154
+ </Card>
155
+ <Card title="Rows" wide>
156
+ <Table data={rows} columns={columns} />
157
+ </Card>
158
+ </Grid>
159
+ )}
160
+ </Page>
161
+ );
162
+ }
@@ -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
+ }