@makoai/app-sdk 2.10.0 → 2.11.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/README.md CHANGED
@@ -209,7 +209,7 @@ The kit is the dashboard furniture every app was re-forking:
209
209
  import "@makoai/app-sdk/ui.css"; // before ./styles.css, so the app wins
210
210
  import {
211
211
  PageHeader, Card, KpiRow, KpiTile, Button, StatusDot,
212
- MultiSelect, FreshnessBadge, RefreshAllButton,
212
+ MultiSelect, FreshnessBadge, RefreshAllButton, DataTable,
213
213
  } from "@makoai/app-sdk/ui";
214
214
 
215
215
  <PageHeader
@@ -299,6 +299,89 @@ const SEGMENTS = [ // bottom-up, as stacked; drives the bars AND the tooltip
299
299
  - On a chart with an HTML overlay (a donut's centre label), lift the tooltip:
300
300
  `<Tooltip wrapperStyle={{ zIndex: 20 }} … />`.
301
301
 
302
+ ### Data tables: `DataTable` (2.11+)
303
+
304
+ `DataTable` is the table the best workspace dashboards converged on: a card
305
+ with click-to-sort headers, a sticky header, an optional pinned first column,
306
+ right-aligned tabular numbers, fixed column widths, a pager footer ("1–50 of
307
+ 312 customers", 25 / 50 / 100 per page, « ‹ Page 2 of 7 › »), an empty state
308
+ and CSV export.
309
+
310
+ ```tsx
311
+ import { DataTable, type DataTableColumn } from "@makoai/app-sdk/ui";
312
+
313
+ const COLUMNS: DataTableColumn<Customer>[] = [
314
+ { id: "name", label: "Customer", value: c => c.name, sticky: true, width: 260,
315
+ render: c => <><div>{c.name}</div><SystemLinks c={c} /></> },
316
+ { id: "paid", label: "Paid on", value: c => c.paidDay, date: true, render: c => fmtDay(c.paidDay) },
317
+ { id: "mrr", label: "MRR", num: true, value: c => c.mrr, render: c => fmtEur(c.mrr) },
318
+ { id: "links", label: "Links", value: () => null, sortable: false, csv: false, width: 120, render: c => <Links c={c} /> },
319
+ ];
320
+
321
+ <DataTable
322
+ title={`${fmtInt(list.length)} customers not onboarded`}
323
+ actions={<input className="search" value={q} onChange={e => setQ(e.target.value)} />}
324
+ rows={list}
325
+ resetKey={q}
326
+ columns={COLUMNS}
327
+ noun="customers"
328
+ empty="No customers match these filters."
329
+ defaultSort={{ id: "mrr", dir: "desc" }}
330
+ exportFilename="onboarding-customers"
331
+ fill
332
+ />
333
+ ```
334
+
335
+ - **Columns.** `value(row)` is what the column sorts by and exports;
336
+ `render(row)` is what the cell shows. `num` right-aligns with tabular
337
+ figures and sorts largest first on the first click (text sorts A→Z). Empty
338
+ values (null, "", NaN) sort last both ways. `sticky` (pin the first column),
339
+ `sortable: false`, `hint` (header hover text), `csv` (`false` to leave a
340
+ column out, a function for a readable cell such as a level name). Numeric
341
+ strings ("1.25", "-10") sort as numbers.
342
+ - **Widths: no layout shift.** The table uses `table-layout: fixed` and a
343
+ `<colgroup>`, so a column's width never depends on the rows on screen.
344
+ Sorting, filtering, paging, the empty state and loading all keep the same
345
+ widths. Each column is exactly its `width` (px as a number, or any CSS
346
+ length such as `"12rem"`). Defaults by kind: `num` or right-aligned 96px,
347
+ `date: true` 110px, the first or sticky column 240px, other text 140px.
348
+ When the card is wider than the sum, the `grow: true` columns take the extra
349
+ space. Without one, the first column grows. `minWidth` sets a growing
350
+ column's floor. When the card is narrower than the sum, the table scrolls
351
+ sideways inside the card. `columnLayout(columns)` returns the widths the
352
+ table renders.
353
+ - **Cells stay on one line.** A cell ellipsizes at its column's width with the
354
+ raw value (text or number) as the hover title. Headers ellipsize too, and
355
+ the sort icon stays visible. `truncate: false` wraps a cell's text inside
356
+ its column instead: the width holds and the row grows.
357
+ - **Sort, page, page size** are each uncontrolled by default or controlled with
358
+ `sort` + `onSortChange`, `page` (1-based) + `onPageChange`, `pageSize` +
359
+ `onPageSizeChange`, so an app can keep them in the URL. Pass your filter
360
+ state as `resetKey` (e.g. `resetKey={{ q, owners }}`): when it changes the
361
+ table goes back to page 1. A sort or page-size click resets the page too.
362
+ New row objects never do, so a load or a background refresh keeps the page.
363
+ A page past the end shows the last page and reports it through
364
+ `onPageChange`. The table scrolls to the top on a page change. `rows`
365
+ defaults to `[]`, so a table can render while its data loads.
366
+ - **Height.** `fill` makes the card fill its parent's height and the body
367
+ scroll inside it, with the pager always in view: give the parent a height
368
+ (e.g. `<main style={{ height: "100dvh", display: "flex", flexDirection: "column" }}>`).
369
+ On phones it falls back to a 70vh scroll box. Without `fill` the body scrolls
370
+ past `maxHeight` (default 70vh).
371
+ - **Rows.** `onRowClick(row)` makes rows clickable (and Enter or Space on a
372
+ focused row); clicks on links and buttons inside a cell stay theirs.
373
+ `rowLabel(row)` names a clickable row for screen readers. `rowKey` defaults
374
+ to `row.id`.
375
+ - **CSV.** `exportFilename` adds an "Export CSV" button that downloads every
376
+ row on every page, as sorted. Mako's app frames allow downloads. Numbers
377
+ export as is. Text starting with `=`, `+`, `-`, `@`, tab or CR gets a
378
+ leading apostrophe so a spreadsheet never runs it. A Date at local or UTC
379
+ midnight exports as `YYYY-MM-DD`, any other Date as a UTC ISO timestamp. For
380
+ your own button: `saveCsv(filename, toCsv(rows, columns))` returns
381
+ `"downloaded"` or `"failed"`.
382
+ - Pure helpers for custom tables: `sortRows`, `compareValues`, `nextSort`,
383
+ `pageSlice`, `pageToSync`, `toCsv`, `csvCell`, `csvDate`, `csvToTsv`.
384
+
302
385
  `ui.css` is plain CSS (no Tailwind needed; it coexists with Tailwind) and
303
386
  every kit class is prefixed `mk-`. It also sets the house base: Inter 14px on
304
387
  the warm `--canvas`.
package/index.js CHANGED
@@ -32,7 +32,7 @@ import {
32
32
  * in a page (or this export) says which SDK a deployed app actually runs.
33
33
  * Kept in step with package.json by snapshot.test.mjs.
34
34
  */
35
- export const SDK_VERSION = "2.10.0";
35
+ export const SDK_VERSION = "2.11.0";
36
36
  if (typeof window !== "undefined") {
37
37
  try {
38
38
  window.__MAKO_APP_SDK__ = SDK_VERSION;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@makoai/app-sdk",
3
- "version": "2.10.0",
3
+ "version": "2.11.0",
4
4
  "description": "Mako app SDK: data bindings (useQuery/useDuckDB), URL state, theme, and the house dashboard kit (/ui).",
5
5
  "license": "MIT",
6
6
  "repository": {
package/ui-core.js CHANGED
@@ -59,3 +59,225 @@ export function tooltipSeriesRows(datum, series, { stacked = false } = {}) {
59
59
  .filter(r => r.value != null && r.value !== 0 && !Number.isNaN(Number(r.value)));
60
60
  return stacked ? rows.reverse() : rows.sort((a, b) => Number(b.value) - Number(a.value));
61
61
  }
62
+
63
+ // ---------------------------------------------------------------------------
64
+ // Data tables: sort, page and CSV, without React
65
+ // ---------------------------------------------------------------------------
66
+
67
+ /** null, undefined, "" and NaN sort last both ways and export as an empty cell. */
68
+ const isEmpty = v => v == null || v === "" || (typeof v === "number" && Number.isNaN(v));
69
+ const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
70
+
71
+ const isNumeric = v => typeof v === "number" || typeof v === "bigint";
72
+ const isNumericString = v => typeof v === "string" && v.trim() !== "" && Number.isFinite(Number(v));
73
+
74
+ /**
75
+ * Compare two cell values ascending: numbers, bigints and dates by value (a
76
+ * bigint against a number too), two numeric strings ("1.5", "-10") as
77
+ * numbers, booleans false first, everything else as text A→Z with digit runs
78
+ * in numeric order.
79
+ */
80
+ export function compareValues(a, b) {
81
+ let x = a instanceof Date ? a.getTime() : a;
82
+ let y = b instanceof Date ? b.getTime() : b;
83
+ if (isNumericString(x) && isNumericString(y)) (x = Number(x)), (y = Number(y));
84
+ if (isNumeric(x) && isNumeric(y)) return x < y ? -1 : x > y ? 1 : 0;
85
+ if (typeof x === "boolean" && typeof y === "boolean") return Number(x) - Number(y);
86
+ return collator.compare(String(x), String(y));
87
+ }
88
+
89
+ /**
90
+ * The direction a column sorts in on its first click: numbers largest first
91
+ * (`num: true`), text A→Z.
92
+ */
93
+ export function firstSortDir(column) {
94
+ return column?.num ? "desc" : "asc";
95
+ }
96
+
97
+ /** The sort after a header click: the same column flips, a new one starts at its first direction. */
98
+ export function nextSort(sort, column) {
99
+ if (sort && sort.id === column.id) return { id: column.id, dir: sort.dir === "asc" ? "desc" : "asc" };
100
+ return { id: column.id, dir: firstSortDir(column) };
101
+ }
102
+
103
+ /**
104
+ * A sorted copy of `rows` by the column `sort.id` (its `value(row)`), stable,
105
+ * empty values last in both directions. No sort or an unknown column returns
106
+ * the rows in their given order.
107
+ */
108
+ export function sortRows(rows, columns, sort) {
109
+ const col = sort && columns.find(c => c.id === sort.id);
110
+ if (!col) return rows.slice();
111
+ const sign = sort.dir === "desc" ? -1 : 1;
112
+ return rows
113
+ .map((row, i) => ({ row, i, v: col.value(row) }))
114
+ .sort((a, b) => {
115
+ const ea = isEmpty(a.v);
116
+ const eb = isEmpty(b.v);
117
+ if (ea || eb) return ea && eb ? a.i - b.i : ea ? 1 : -1;
118
+ return compareValues(a.v, b.v) * sign || a.i - b.i;
119
+ })
120
+ .map(x => x.row);
121
+ }
122
+
123
+ /** Default column widths in px, by kind: see `defaultColumnWidth`. */
124
+ export const COLUMN_WIDTHS = { num: 96, date: 110, first: 240, text: 140 };
125
+
126
+ /** A width as CSS: a number is px, a string passes through ("12rem", "20%"). */
127
+ export function cssLength(v) {
128
+ return typeof v === "number" ? `${v}px` : v;
129
+ }
130
+
131
+ /**
132
+ * A column's width when it sets none: numbers (`num` or right-aligned) 96px,
133
+ * dates (`date`) 110px, the first or sticky column 240px, other text 140px.
134
+ */
135
+ export function defaultColumnWidth(column, index = 1) {
136
+ if (column?.num || column?.align === "right") return COLUMN_WIDTHS.num;
137
+ if (column?.date) return COLUMN_WIDTHS.date;
138
+ if (column?.sticky || index === 0) return COLUMN_WIDTHS.first;
139
+ return COLUMN_WIDTHS.text;
140
+ }
141
+
142
+ /**
143
+ * The fixed layout of a DataTable: one `<col>` width per column and the
144
+ * table's minimum width (their sum). Every column is exactly its `width`
145
+ * (default `defaultColumnWidth`). The flexible columns (`grow: true`, else the
146
+ * first column) take the space left when the card is wider than the sum; their
147
+ * floor is `minWidth`, else their width. Widths never depend on the rows, so
148
+ * sorting, filtering and paging never move a column.
149
+ * Returns `{ cols: [{ id, width: CSS length | null (flexible) }], minWidth }`.
150
+ */
151
+ export function columnLayout(columns) {
152
+ const anyGrow = columns.some(c => c.grow);
153
+ let px = 0;
154
+ const other = [];
155
+ const cols = columns.map((c, i) => {
156
+ const grow = anyGrow ? !!c.grow : i === 0;
157
+ const base = c.width ?? defaultColumnWidth(c, i);
158
+ const floor = grow ? (c.minWidth ?? base) : base;
159
+ if (typeof floor === "number") px += floor;
160
+ else other.push(floor);
161
+ return { id: c.id, width: grow ? null : cssLength(base) };
162
+ });
163
+ const minWidth = other.length ? `calc(${[`${px}px`, ...other].join(" + ")})` : `${px}px`;
164
+ return { cols, minWidth };
165
+ }
166
+
167
+ /**
168
+ * Paging math for `total` rows. `page` is 1-based and clamped into range.
169
+ * Returns `{ page, pageCount, start, end }`: rows `start` (inclusive) to
170
+ * `end` (exclusive) are on the page.
171
+ */
172
+ export function pageSlice(total, page, pageSize) {
173
+ const size = Math.max(1, Math.floor(pageSize) || 1);
174
+ const pageCount = Math.max(1, Math.ceil(total / size));
175
+ const p = Math.min(Math.max(1, Math.floor(page) || 1), pageCount);
176
+ const start = (p - 1) * size;
177
+ return { page: p, pageCount, start, end: Math.min(start + size, total) };
178
+ }
179
+
180
+ /**
181
+ * The page to report back when the requested page is out of range, so a
182
+ * controlled page (in the URL) matches what the table shows. null when the
183
+ * requested page is fine, or while there are no rows yet (still loading), so
184
+ * `?page=3` survives the first render.
185
+ */
186
+ export function pageToSync(requested, total, pageSize) {
187
+ if (!(total > 0)) return null;
188
+ const { page } = pageSlice(total, requested, pageSize);
189
+ return page === requested ? null : page;
190
+ }
191
+
192
+ /**
193
+ * A `resetKey` as a comparable string: JSON, with Sets and Maps as arrays and
194
+ * bigints as text. Two keys that serialise the same are the same filters.
195
+ */
196
+ export function serializeResetKey(key) {
197
+ if (key === undefined) return "";
198
+ try {
199
+ return JSON.stringify(key, (_, v) =>
200
+ v instanceof Set ? [...v] : v instanceof Map ? [...v.entries()] : typeof v === "bigint" ? `${v}n` : v,
201
+ );
202
+ } catch {
203
+ return String(key);
204
+ }
205
+ }
206
+
207
+ const pad2 = n => String(n).padStart(2, "0");
208
+
209
+ /**
210
+ * A Date as CSV text: a date at local midnight is that local day
211
+ * (YYYY-MM-DD), a date at UTC midnight (how DuckDB hands over a DATE) is that
212
+ * UTC day, anything else is the full ISO timestamp in UTC.
213
+ */
214
+ export function csvDate(d) {
215
+ if (Number.isNaN(d.getTime())) return "";
216
+ if (d.getHours() === 0 && d.getMinutes() === 0 && d.getSeconds() === 0 && d.getMilliseconds() === 0) {
217
+ return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
218
+ }
219
+ const iso = d.toISOString();
220
+ return iso.endsWith("T00:00:00.000Z") ? iso.slice(0, 10) : iso;
221
+ }
222
+
223
+ const PLAIN_NUMBER = /^-?\d+(\.\d+)?(e[+-]?\d+)?$/i;
224
+
225
+ /**
226
+ * One cell as CSV text. Numbers, bigints and plain numeric text ("-5",
227
+ * "-1.25e3") pass through as they are. Other text starting with = + - @ tab
228
+ * or CR would run as a formula in a spreadsheet, so it gets a leading
229
+ * apostrophe.
230
+ */
231
+ export function csvCell(v) {
232
+ if (isEmpty(v)) return "";
233
+ if (isNumeric(v)) return String(v);
234
+ if (v instanceof Date) return csvDate(v);
235
+ const t = String(v);
236
+ if (PLAIN_NUMBER.test(t)) return t;
237
+ return /^[=+\-@\t\r]/.test(t) ? "'" + t : t;
238
+ }
239
+ const csvHeader = c => (typeof c.label === "string" || typeof c.label === "number" ? String(c.label) : c.id);
240
+
241
+ /**
242
+ * The rows as CSV text: a header row of column labels, then one line per row
243
+ * from each column's `csv(row)` (or `value(row)`); columns with `csv: false`
244
+ * are left out. Every cell is quoted, a byte-order mark keeps Excel on UTF-8,
245
+ * and cells go through `csvCell` (numbers as is, text formulas guarded, dates
246
+ * as `csvDate`).
247
+ */
248
+ export function toCsv(rows, columns) {
249
+ const cols = columns.filter(c => c.csv !== false);
250
+ const table = [cols.map(csvHeader), ...rows.map(r => cols.map(c => (typeof c.csv === "function" ? c.csv(r) : c.value(r))))];
251
+ return "" + table.map(line => line.map(v => '"' + csvCell(v).replace(/"/g, '""') + '"').join(",")).join("\r\n") + "\r\n";
252
+ }
253
+
254
+ /** Parse CSV text (quoted or not, CRLF or LF) into rows of cells. */
255
+ export function parseCsv(text) {
256
+ const src = text.replace(/^/, "");
257
+ const rows = [];
258
+ let row = [];
259
+ let cell = "";
260
+ let quoted = false;
261
+ for (let i = 0; i < src.length; i++) {
262
+ const ch = src[i];
263
+ if (quoted) {
264
+ if (ch === '"' && src[i + 1] === '"') (cell += '"'), i++;
265
+ else if (ch === '"') quoted = false;
266
+ else cell += ch;
267
+ } else if (ch === '"') quoted = true;
268
+ else if (ch === ",") row.push(cell), (cell = "");
269
+ else if (ch === "\n" || ch === "\r") {
270
+ if (ch === "\r" && src[i + 1] === "\n") i++;
271
+ row.push(cell), rows.push(row), (row = []), (cell = "");
272
+ } else cell += ch;
273
+ }
274
+ if (cell !== "" || row.length) row.push(cell), rows.push(row);
275
+ return rows;
276
+ }
277
+
278
+ /** CSV text as tab-separated lines, which paste into spreadsheet columns. */
279
+ export function csvToTsv(text) {
280
+ return parseCsv(text)
281
+ .map(r => r.map(v => v.replace(/[\t\r\n]+/g, " ")).join("\t"))
282
+ .join("\n");
283
+ }
package/ui.css CHANGED
@@ -137,6 +137,85 @@ button:not(:disabled), [role="button"]:not(:disabled) { cursor: pointer; }
137
137
  .mk-tip-total th, .mk-tip-total td { font-weight: 600; }
138
138
  .mk-tip-rule th, .mk-tip-rule td { border-top: 1px solid var(--border); padding-top: 3px; }
139
139
 
140
+ /* ---- DataTable ----------------------------------------------------------- */
141
+ /* A card whose table scrolls inside it: a sticky header, an optional pinned
142
+ * first column, hover on the cells (so a pinned cell follows its row), and a
143
+ * pager footer. `.mk-dt--fill` fills the parent's height (give the parent one,
144
+ * e.g. a 100dvh flex column); otherwise the body scrolls past 70vh. */
145
+ .mk-dt { display: flex; flex-direction: column; padding: 0; overflow: hidden; min-width: 0; }
146
+ .mk-dt > .mk-card-head { flex: none; flex-wrap: wrap; margin: 0; padding: 16px 16px 12px; }
147
+ .mk-dt .mk-card-actions { flex-wrap: wrap; }
148
+ .mk-dt--fill { flex: 1 1 auto; height: 100%; min-height: 320px; }
149
+ .mk-dt-note { flex: none; margin: 0; padding: 0 16px 10px; font-size: 12px; color: var(--muted-foreground); }
150
+ .mk-dt-scroll { overflow: auto; max-height: 70vh; border-top: 1px solid var(--border); scrollbar-width: thin; scrollbar-color: var(--border) transparent; }
151
+ .mk-dt > .mk-dt-scroll:first-child { border-top: 0; }
152
+ .mk-dt--fill .mk-dt-scroll { flex: 1 1 auto; min-height: 0; max-height: none; }
153
+ /* Fixed layout: the <colgroup> sets every width, so the rows on screen never
154
+ * resize a column. The table fills the card; its inline min-width (the sum of
155
+ * the columns) makes it scroll sideways in a narrower card. */
156
+ .mk-dt-table { width: 100%; table-layout: fixed; border-collapse: separate; border-spacing: 0; font-size: 13px; }
157
+ .mk-dt-table th, .mk-dt-table td {
158
+ padding: 7px 10px; text-align: left; white-space: nowrap; vertical-align: middle; overflow: hidden;
159
+ border-bottom: 1px solid var(--mk-row-line); background: var(--card);
160
+ }
161
+ .mk-dt-table thead th {
162
+ position: sticky; top: 0; z-index: 2; padding: 0; border-bottom: 0;
163
+ font-size: 12px; font-weight: 500; color: var(--muted-foreground);
164
+ box-shadow: inset 0 -1px 0 var(--border);
165
+ }
166
+ .mk-dt-table thead th.mk-dt-sorted { color: var(--foreground); }
167
+ .mk-dt-label { display: flex; padding: 8px 10px; }
168
+ .mk-dt-sort {
169
+ appearance: none; display: flex; align-items: center; gap: 4px; width: 100%; min-width: 0; padding: 8px 10px;
170
+ font: inherit; color: inherit; background: none; border: 0; text-align: inherit; white-space: nowrap;
171
+ }
172
+ /* A long header label ellipsizes; the sort icon beside it never shrinks. */
173
+ .mk-dt-th-text { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
174
+ .mk-dt-sort:hover { color: var(--foreground); }
175
+ .mk-dt-sort:focus-visible { outline: 2px solid var(--ring); outline-offset: -2px; border-radius: var(--mk-radius-sm); }
176
+ .mk-dt-sort svg { flex: none; }
177
+ .mk-dt-faint { opacity: .35; }
178
+ .mk-dt-table .mk-dt-num { text-align: right; font-variant-numeric: tabular-nums; }
179
+ .mk-dt-table th.mk-dt-num :is(.mk-dt-sort, .mk-dt-label) { justify-content: flex-end; }
180
+ .mk-dt-table .mk-dt-center { text-align: center; }
181
+ .mk-dt-table th.mk-dt-center :is(.mk-dt-sort, .mk-dt-label) { justify-content: center; }
182
+ /* The pinned column: solid background and a hairline on its right edge. */
183
+ .mk-dt-table .mk-dt-pin { position: sticky; left: 0; z-index: 1; box-shadow: inset -1px 0 0 var(--border); }
184
+ /* The corner cell is pinned both ways and keeps BOTH borders: one box-shadow
185
+ * would otherwise override the other and drop the header's bottom rule. */
186
+ .mk-dt-table thead th.mk-dt-pin { z-index: 3; box-shadow: inset -1px 0 0 var(--border), inset 0 -1px 0 var(--border); }
187
+ .mk-dt-table tbody tr:hover > td { background: color-mix(in srgb, var(--muted) 50%, var(--card)); }
188
+ .mk-dt-table tbody tr:last-child > td { border-bottom: 0; }
189
+ .mk-dt-click { cursor: pointer; }
190
+ .mk-dt-click:focus-visible { outline: none; }
191
+ .mk-dt-click:focus-visible > td { background: color-mix(in srgb, var(--muted) 70%, var(--card)); }
192
+ .mk-dt-cell { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
193
+ /* A render() that returns blocks (a name over its links) ellipsizes each line. */
194
+ .mk-dt-cell :where(div, p) { overflow: hidden; text-overflow: ellipsis; }
195
+ /* `truncate: false`: the text wraps inside the column; the width still holds. */
196
+ .mk-dt-wrap { white-space: normal; overflow-wrap: anywhere; }
197
+ .mk-dt-table td.mk-dt-empty { text-align: center; color: var(--muted-foreground); padding: 48px 10px; white-space: normal; }
198
+ .mk-dt-foot {
199
+ flex: none; display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 8px;
200
+ padding: 8px 12px; border-top: 1px solid var(--border); font-size: 12px; color: var(--muted-foreground);
201
+ }
202
+ .mk-dt-foot b { font-weight: 500; color: var(--foreground); font-variant-numeric: tabular-nums; }
203
+ .mk-dt-nav { display: flex; align-items: center; gap: 4px; }
204
+ .mk-dt-nav .mk-btn { width: 28px; padding: 0; }
205
+ .mk-dt-size {
206
+ cursor: pointer; height: 28px; margin-right: 8px; padding: 0 8px; font-size: 12px; color: var(--foreground);
207
+ background: var(--background); border: 1px solid var(--border); border-radius: var(--mk-radius-md); box-shadow: var(--mk-shadow-xs);
208
+ }
209
+ .mk-dt-size:focus-visible { outline: none; border-color: var(--ring); box-shadow: var(--mk-ring-focus); }
210
+ .mk-dt-page { padding: 0 6px; font-variant-numeric: tabular-nums; }
211
+ @media (max-width: 640px) {
212
+ /* Phones: the page scrolls as usual and the table keeps a scroll box of its own. */
213
+ .mk-dt--fill { height: auto; }
214
+ .mk-dt--fill .mk-dt-scroll { max-height: 70vh; }
215
+ .mk-dt-nav .mk-btn { width: 38px; }
216
+ .mk-dt-size { height: 38px; }
217
+ }
218
+
140
219
  /* ---- MultiSelect --------------------------------------------------------- */
141
220
  .mk-ms { position: relative; display: inline-block; }
142
221
  .mk-ms-trigger {
package/ui.d.ts CHANGED
@@ -175,3 +175,147 @@ export function tooltipSeriesRows<K extends string>(
175
175
  series: readonly { key: K; label?: string; color?: string }[],
176
176
  opts?: { stacked?: boolean },
177
177
  ): { key: K; label: string; color?: string; value: number }[];
178
+
179
+ /** A table sort: the column id and its direction. */
180
+ export interface DataTableSort {
181
+ id: string;
182
+ dir: "asc" | "desc";
183
+ }
184
+ export interface DataTableColumn<R = any> {
185
+ id: string;
186
+ /** Header text; also the CSV header when it is a string (else `id`). */
187
+ label: React.ReactNode;
188
+ /** The cell's raw value: what it sorts by and what CSV exports. */
189
+ value: (row: R) => unknown;
190
+ /** What the cell shows; defaults to `value(row)`. */
191
+ render?: (row: R) => React.ReactNode;
192
+ /** A number: right-aligned, tabular figures, sorts largest first on the first click. */
193
+ num?: boolean;
194
+ align?: "left" | "right" | "center";
195
+ /** A date column: takes the 110px default width. */
196
+ date?: boolean;
197
+ /**
198
+ * The column's fixed width: px as a number (120) or any CSS length ("12rem").
199
+ * Defaults by kind: numbers (`num` or right-aligned) 96px, `date` 110px, the
200
+ * first or sticky column 240px, other text 140px. The rows on screen never
201
+ * change it, so sorting, filtering and paging never shift the layout.
202
+ */
203
+ width?: number | string;
204
+ /**
205
+ * This column takes the space left when the card is wider than the sum of
206
+ * the widths. Without any `grow` column, the first column grows.
207
+ */
208
+ grow?: boolean;
209
+ /** A growing column's floor; defaults to its `width`. Other columns are exactly `width`. */
210
+ minWidth?: number | string;
211
+ /**
212
+ * Default true: the cell stays on one line and ellipsizes at the column's
213
+ * width, the raw value (text or number) as its hover title. false wraps the
214
+ * text inside the column instead (the width still holds; the row grows).
215
+ */
216
+ truncate?: boolean;
217
+ /** Pin to the left edge with a solid background. Use on the first column. */
218
+ sticky?: boolean;
219
+ /** Default true. */
220
+ sortable?: boolean;
221
+ /** Header hover text, e.g. the column's definition. */
222
+ hint?: string;
223
+ /**
224
+ * false leaves the column out of CSV; a function exports a readable cell (a
225
+ * level name). Numbers export as is; a Date at local or UTC midnight exports
226
+ * as YYYY-MM-DD, any other Date as a full UTC ISO timestamp.
227
+ */
228
+ csv?: false | ((row: R) => unknown);
229
+ }
230
+ export interface DataTableProps<R = any> {
231
+ /** Default [] (renders the empty state while loading). */
232
+ rows?: readonly R[];
233
+ columns: readonly DataTableColumn<R>[];
234
+ /** A stable key per row; defaults to `row.id`, else the position. */
235
+ rowKey?: (row: R) => React.Key;
236
+ title?: React.ReactNode;
237
+ description?: React.ReactNode;
238
+ /** Controls in the card's title row (search, filters). */
239
+ actions?: React.ReactNode;
240
+ /** Controlled sort (put it in the URL); pair with `onSortChange`. */
241
+ sort?: DataTableSort | null;
242
+ defaultSort?: DataTableSort | null;
243
+ onSortChange?: (sort: DataTableSort) => void;
244
+ /**
245
+ * Controlled page, 1-based; pair with `onPageChange`. A page past the end
246
+ * shows the last page and reports it through `onPageChange` (once there are
247
+ * rows), so a URL stays in sync.
248
+ */
249
+ page?: number;
250
+ onPageChange?: (page: number) => void;
251
+ /**
252
+ * The filter state (search text, selected values; any JSON-serialisable
253
+ * value). When it changes the table goes back to page 1. A sort or page-size
254
+ * click also resets the page. New row objects with the same key (a load, a
255
+ * background refresh, rows rebuilt inline) keep the page.
256
+ */
257
+ resetKey?: unknown;
258
+ pageSize?: number;
259
+ /** Default 50. */
260
+ defaultPageSize?: number;
261
+ onPageSizeChange?: (size: number) => void;
262
+ /** Default [25, 50, 100]; one entry hides the select. */
263
+ pageSizes?: readonly number[];
264
+ /** Plural noun for the footer: "1–50 of 312 customers". Default "rows". */
265
+ noun?: string;
266
+ /** Shown when there are no rows. Default "No rows match these filters." */
267
+ empty?: React.ReactNode;
268
+ /** Fill the parent's height; the body scrolls inside the card. */
269
+ fill?: boolean;
270
+ /** Body scroll height when not `fill`. Default 70vh. */
271
+ maxHeight?: number | string;
272
+ /** Row click (and Enter or Space on a focused row). Clicks on links, buttons and fields inside the row are theirs. */
273
+ onRowClick?: (row: R, event: React.SyntheticEvent) => void;
274
+ /** The accessible name of a clickable row, e.g. `c => \`Open ${c.name}\``. */
275
+ rowLabel?: (row: R) => string;
276
+ /** Adds an "Export CSV" button: downloads every row, as sorted. */
277
+ exportFilename?: string;
278
+ className?: string;
279
+ style?: React.CSSProperties;
280
+ }
281
+ /**
282
+ * The house data table: sortable, paged, sticky header, optional pinned first
283
+ * column, CSV export. Fixed column widths (`table-layout: fixed` + a
284
+ * `<colgroup>`): no layout shift on sort, filter, page, empty or loading.
285
+ */
286
+ export function DataTable<R = any>(props: DataTableProps<R>): React.ReactElement;
287
+
288
+ /** Default widths in px by kind. */
289
+ export const COLUMN_WIDTHS: { num: number; date: number; first: number; text: number };
290
+ /** A column's width when it sets none: num/right 96, date 110, first or sticky 240, text 140. */
291
+ export function defaultColumnWidth(column: Pick<DataTableColumn, "num" | "align" | "date" | "sticky">, index?: number): number;
292
+ /**
293
+ * The fixed layout a DataTable renders: each `<col>` width (null for a
294
+ * growing column) and the table's min-width, the sum of the columns.
295
+ */
296
+ export function columnLayout(columns: readonly Pick<DataTableColumn, "id" | "num" | "align" | "date" | "sticky" | "width" | "minWidth" | "grow">[]): {
297
+ cols: { id: string; width: string | null }[];
298
+ minWidth: string;
299
+ };
300
+ /** A sorted copy: stable, by `value(row)`, empty values (null, "", NaN) last both ways. */
301
+ export function sortRows<R>(rows: readonly R[], columns: readonly DataTableColumn<R>[], sort: DataTableSort | null | undefined): R[];
302
+ /** The sort after a header click: same column flips; a new one starts desc for `num`, else asc. */
303
+ export function nextSort(sort: DataTableSort | null | undefined, column: Pick<DataTableColumn, "id" | "num">): DataTableSort;
304
+ /** Compare two cell values ascending: numbers, bigints, dates and two numeric strings by value; text A→Z. */
305
+ export function compareValues(a: unknown, b: unknown): number;
306
+ /** Paging math, 1-based and clamped: rows `start` (inclusive) to `end` (exclusive). */
307
+ export function pageSlice(total: number, page: number, pageSize: number): { page: number; pageCount: number; start: number; end: number };
308
+ /** The clamped page to report when `requested` is out of range; null when it is fine or there are no rows yet. */
309
+ export function pageToSync(requested: number, total: number, pageSize: number): number | null;
310
+ /** A `resetKey` as a comparable string (JSON; Sets and Maps as arrays, bigints as text). */
311
+ export function serializeResetKey(key: unknown): string;
312
+ /** CSV text with a header row; skips `csv: false` columns; quotes every cell; cells via `csvCell`. */
313
+ export function toCsv<R>(rows: readonly R[], columns: readonly DataTableColumn<R>[]): string;
314
+ /** One CSV cell: numbers as is, text starting with = + - @ tab or CR guarded with an apostrophe, dates via `csvDate`. */
315
+ export function csvCell(value: unknown): string;
316
+ /** A Date at local or UTC midnight as YYYY-MM-DD; any other Date as a full UTC ISO timestamp. */
317
+ export function csvDate(date: Date): string;
318
+ /** CSV text as tab-separated lines (pastes into spreadsheet columns). */
319
+ export function csvToTsv(text: string): string;
320
+ /** Download CSV text as a file. Works inside Mako's app frame. */
321
+ export function saveCsv(filename: string, text: string): "downloaded" | "failed";
package/ui.js CHANGED
@@ -11,9 +11,44 @@
11
11
  import * as React from "react";
12
12
  import { createPortal } from "react-dom";
13
13
  import { bindingPhaseLabel, refreshBinding, useBindingProgress } from "./index.js";
14
- import { formatSeconds as fmtSecs, normalizeTone, refreshOrder, tooltipSeriesRows } from "./ui-core.js";
14
+ import {
15
+ COLUMN_WIDTHS,
16
+ columnLayout,
17
+ compareValues,
18
+ csvCell,
19
+ csvDate,
20
+ csvToTsv,
21
+ defaultColumnWidth,
22
+ formatSeconds as fmtSecs,
23
+ nextSort,
24
+ normalizeTone,
25
+ pageSlice,
26
+ pageToSync,
27
+ refreshOrder,
28
+ serializeResetKey,
29
+ sortRows,
30
+ toCsv,
31
+ tooltipSeriesRows,
32
+ } from "./ui-core.js";
15
33
 
16
- export { normalizeTone, refreshOrder, tooltipSeriesRows };
34
+ export {
35
+ COLUMN_WIDTHS,
36
+ columnLayout,
37
+ compareValues,
38
+ csvCell,
39
+ csvDate,
40
+ csvToTsv,
41
+ defaultColumnWidth,
42
+ nextSort,
43
+ normalizeTone,
44
+ pageSlice,
45
+ pageToSync,
46
+ refreshOrder,
47
+ serializeResetKey,
48
+ sortRows,
49
+ toCsv,
50
+ tooltipSeriesRows,
51
+ };
17
52
 
18
53
  const h = React.createElement;
19
54
 
@@ -259,6 +294,312 @@ export function tableTooltip(build) {
259
294
  };
260
295
  }
261
296
 
297
+ // ---------------------------------------------------------------------------
298
+ // DataTable: sortable, paged, sticky header, CSV export
299
+ // ---------------------------------------------------------------------------
300
+
301
+ const IconSort = ({ dir }) =>
302
+ svg(
303
+ 12,
304
+ 2,
305
+ [
306
+ h("path", {
307
+ key: "p",
308
+ d:
309
+ dir === "asc"
310
+ ? "m5 12 7-7 7 7M12 19V5"
311
+ : dir === "desc"
312
+ ? "M12 5v14M19 12l-7 7-7-7"
313
+ : "m21 16-4 4-4-4M17 20V4M3 8l4-4 4 4M7 4v16",
314
+ }),
315
+ ],
316
+ dir ? undefined : "mk-dt-faint",
317
+ );
318
+
319
+ /** A value that is controlled when `value !== undefined`, local state otherwise. */
320
+ function useControlled(value, initial, onChange) {
321
+ const [local, setLocal] = React.useState(initial);
322
+ const controlled = value !== undefined;
323
+ const set = React.useCallback(
324
+ next => {
325
+ if (!controlled) setLocal(next);
326
+ onChange?.(next);
327
+ },
328
+ [controlled, onChange],
329
+ );
330
+ return [controlled ? value : local, set];
331
+ }
332
+
333
+ /**
334
+ * Download CSV text (from `toCsv`) as `filename` (".csv" added when missing).
335
+ * Mako's app frames allow downloads, so this works inside Mako and out.
336
+ * Returns "downloaded", or "failed" when the browser refused.
337
+ */
338
+ export function saveCsv(filename, text) {
339
+ if (typeof document === "undefined") return "failed";
340
+ try {
341
+ const name = /\.csv$/i.test(filename) ? filename : `${filename}.csv`;
342
+ const url = URL.createObjectURL(new Blob([text], { type: "text/csv;charset=utf-8;" }));
343
+ const a = document.createElement("a");
344
+ a.href = url;
345
+ a.download = name;
346
+ document.body.appendChild(a);
347
+ a.click();
348
+ a.remove();
349
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
350
+ return "downloaded";
351
+ } catch {
352
+ return "failed";
353
+ }
354
+ }
355
+
356
+ const fmtCount = n => n.toLocaleString("en-US");
357
+ // A click on a link, button or field inside a row is that control's, not the row's.
358
+ const INTERACTIVE = "a,button,input,select,textarea,label,[role=button]";
359
+
360
+ /**
361
+ * The house data table: click-to-sort headers, a sticky header (and first
362
+ * column with `sticky`), right-aligned tabular numbers, and a pager footer
363
+ * ("1–50 of 312 customers", rows per page, « ‹ Page x of y › »). Sort, page
364
+ * and page size are each controlled (`sort` + `onSortChange`, …) or left to
365
+ * the table. Pass the filter state as `resetKey`: when it changes the table
366
+ * goes back to page 1. `fill` makes the card fill its parent's height with the
367
+ * body scrolling inside; `exportFilename` adds an "Export CSV" button.
368
+ *
369
+ * Columns have fixed widths (`table-layout: fixed` and a `<colgroup>`), from
370
+ * each column's `width` or a default by kind (see `columnLayout`). The rows
371
+ * on screen never change a width, so sorting, filtering and paging never
372
+ * shift the layout. Cells ellipsize at their width with the full value on hover.
373
+ */
374
+ export function DataTable({
375
+ rows = [],
376
+ columns,
377
+ rowKey,
378
+ title,
379
+ description,
380
+ actions,
381
+ sort: sortProp,
382
+ defaultSort = null,
383
+ onSortChange,
384
+ page: pageProp,
385
+ onPageChange,
386
+ pageSize: pageSizeProp,
387
+ defaultPageSize = 50,
388
+ onPageSizeChange,
389
+ pageSizes = [25, 50, 100],
390
+ noun = "rows",
391
+ empty = "No rows match these filters.",
392
+ fill = false,
393
+ maxHeight,
394
+ onRowClick,
395
+ rowLabel,
396
+ resetKey,
397
+ exportFilename,
398
+ className,
399
+ style,
400
+ }) {
401
+ const [sort, setSort] = useControlled(sortProp, defaultSort, onSortChange);
402
+ const [rawPage, setRawPage] = useControlled(pageProp, 1, onPageChange);
403
+ const [pageSize, setPageSize] = useControlled(pageSizeProp, defaultPageSize, onPageSizeChange);
404
+ const [note, setNote] = React.useState(null);
405
+ const scrollRef = React.useRef(null);
406
+
407
+ const sorted = React.useMemo(() => sortRows(rows, columns, sort), [rows, columns, sort]);
408
+ const layout = React.useMemo(() => columnLayout(columns), [columns]);
409
+ const { page, pageCount, start, end } = pageSlice(sorted.length, rawPage, pageSize);
410
+ const visible = sorted.slice(start, end);
411
+
412
+ const goTo = p => {
413
+ if (p !== rawPage) setRawPage(p);
414
+ scrollRef.current?.scrollTo?.({ top: 0 });
415
+ };
416
+
417
+ // Back to page 1 when the filters change, as the caller states them in
418
+ // `resetKey`. Row identity never resets the page: a load, a background
419
+ // refresh or rows rebuilt inline keep it.
420
+ const key = serializeResetKey(resetKey);
421
+ const prevKey = React.useRef(key);
422
+ React.useEffect(() => {
423
+ if (prevKey.current === key) return;
424
+ prevKey.current = key;
425
+ if (rawPage !== 1) goTo(1);
426
+ }, [key]); // eslint-disable-line react-hooks/exhaustive-deps
427
+
428
+ // A page past the end (rows shrank, a stale URL) shows the last page; report
429
+ // it so a controlled page matches. Skipped while there are no rows yet.
430
+ const syncTo = pageToSync(rawPage, sorted.length, pageSize);
431
+ React.useEffect(() => {
432
+ if (syncTo != null) setRawPage(syncTo);
433
+ }, [syncTo]); // eslint-disable-line react-hooks/exhaustive-deps
434
+
435
+ React.useEffect(() => {
436
+ if (!note) return undefined;
437
+ const t = setTimeout(() => setNote(null), 8000);
438
+ return () => clearTimeout(t);
439
+ }, [note]);
440
+
441
+ const sortBy = col => {
442
+ setSort(nextSort(sort, col));
443
+ goTo(1);
444
+ };
445
+ const exportCsv = () => {
446
+ const res = saveCsv(exportFilename, toCsv(sorted, columns));
447
+ setNote(res === "failed" ? "The browser blocked the download. Open the app in a new tab and export again." : null);
448
+ };
449
+
450
+ const cellClass = (col, extra) =>
451
+ cx(col.num && "mk-dt-num", col.align === "right" && "mk-dt-num", col.align === "center" && "mk-dt-center", col.sticky && "mk-dt-pin", extra);
452
+
453
+ const head = h(
454
+ "thead",
455
+ null,
456
+ h(
457
+ "tr",
458
+ null,
459
+ ...columns.map(col => {
460
+ const active = sort?.id === col.id;
461
+ const text = typeof col.label === "string" ? col.label : col.id;
462
+ const label =
463
+ col.sortable === false
464
+ ? h("span", { className: "mk-dt-label", title: col.hint ?? text }, h("span", { className: "mk-dt-th-text" }, col.label))
465
+ : h(
466
+ "button",
467
+ {
468
+ type: "button",
469
+ className: "mk-dt-sort",
470
+ onClick: () => sortBy(col),
471
+ title: `${col.hint ?? text} · click to sort`,
472
+ },
473
+ h("span", { className: "mk-dt-th-text" }, col.label),
474
+ h(IconSort, { dir: active ? sort.dir : null }),
475
+ );
476
+ return h(
477
+ "th",
478
+ {
479
+ key: col.id,
480
+ scope: "col",
481
+ className: cellClass(col, active && "mk-dt-sorted"),
482
+ "aria-sort": col.sortable === false ? undefined : active ? (sort.dir === "asc" ? "ascending" : "descending") : "none",
483
+ },
484
+ label,
485
+ );
486
+ }),
487
+ ),
488
+ );
489
+
490
+ // Every cell ellipsizes at its column's width, with the raw value (text or
491
+ // a number) as the hover title. `truncate: false` wraps instead.
492
+ const cell = (col, row) => {
493
+ const v = col.value(row);
494
+ const content = col.render ? col.render(row) : v;
495
+ if (col.truncate === false) return h("div", { className: "mk-dt-wrap" }, content);
496
+ const title = typeof v === "string" || typeof v === "number" || typeof v === "bigint" ? String(v) : undefined;
497
+ return h("div", { className: "mk-dt-cell", title: title || undefined }, content);
498
+ };
499
+
500
+ const body = h(
501
+ "tbody",
502
+ null,
503
+ visible.length === 0
504
+ ? h("tr", { key: "__empty" }, h("td", { colSpan: columns.length, className: "mk-dt-empty" }, empty))
505
+ : visible.map((row, i) => {
506
+ const key = rowKey ? rowKey(row) : (row?.id ?? start + i);
507
+ const click = onRowClick
508
+ ? {
509
+ tabIndex: 0,
510
+ className: "mk-dt-click",
511
+ "aria-label": rowLabel ? rowLabel(row) : undefined,
512
+ onClick: e => {
513
+ if (!e.target.closest?.(INTERACTIVE)) onRowClick(row, e);
514
+ },
515
+ onKeyDown: e => {
516
+ if ((e.key === "Enter" || e.key === " ") && e.target === e.currentTarget) {
517
+ e.preventDefault();
518
+ onRowClick(row, e);
519
+ }
520
+ },
521
+ }
522
+ : null;
523
+ return h(
524
+ "tr",
525
+ { key, ...click },
526
+ ...columns.map(col => h("td", { key: col.id, className: cellClass(col) || undefined }, cell(col, row))),
527
+ );
528
+ }),
529
+ );
530
+
531
+ const footer = h(
532
+ "footer",
533
+ { className: "mk-dt-foot" },
534
+ h(
535
+ "span",
536
+ { "aria-live": "polite" },
537
+ sorted.length
538
+ ? [h("b", { key: "r" }, `${fmtCount(start + 1)}–${fmtCount(end)}`), " of ", h("b", { key: "t" }, fmtCount(sorted.length)), ` ${noun}`]
539
+ : `No ${noun}`,
540
+ ),
541
+ h(
542
+ "div",
543
+ { className: "mk-dt-nav" },
544
+ pageSizes.length > 1 &&
545
+ h(
546
+ "select",
547
+ {
548
+ className: "mk-dt-size",
549
+ "aria-label": "Rows per page",
550
+ value: pageSize,
551
+ onChange: e => {
552
+ setPageSize(Number(e.target.value));
553
+ goTo(1);
554
+ },
555
+ },
556
+ ...pageSizes.map(n => h("option", { key: n, value: n }, `${n} per page`)),
557
+ ),
558
+ h(Button, { size: "sm", "aria-label": "First page", disabled: page <= 1, onClick: () => goTo(1) }, "«"),
559
+ h(Button, { size: "sm", "aria-label": "Previous page", disabled: page <= 1, onClick: () => goTo(page - 1) }, "‹"),
560
+ h("span", { className: "mk-dt-page" }, `Page ${page} of ${pageCount}`),
561
+ h(Button, { size: "sm", "aria-label": "Next page", disabled: page >= pageCount, onClick: () => goTo(page + 1) }, "›"),
562
+ h(Button, { size: "sm", "aria-label": "Last page", disabled: page >= pageCount, onClick: () => goTo(pageCount) }, "»"),
563
+ ),
564
+ );
565
+
566
+ const exportButton =
567
+ exportFilename != null &&
568
+ h(
569
+ Button,
570
+ { key: "__export", disabled: !sorted.length, onClick: exportCsv, title: "Export every row on every page, as sorted" },
571
+ "Export CSV",
572
+ );
573
+
574
+ return h(
575
+ Card,
576
+ {
577
+ title,
578
+ description,
579
+ actions: actions != null || exportButton ? h(React.Fragment, null, actions, exportButton) : undefined,
580
+ className: cx("mk-dt", fill && "mk-dt--fill", className),
581
+ style,
582
+ },
583
+ note && h("p", { className: "mk-dt-note", role: "status" }, note),
584
+ h(
585
+ "div",
586
+ { className: "mk-dt-scroll", ref: scrollRef, style: !fill && maxHeight != null ? { maxHeight } : undefined },
587
+ h(
588
+ "table",
589
+ { className: "mk-dt-table", style: { minWidth: layout.minWidth } },
590
+ h(
591
+ "colgroup",
592
+ null,
593
+ ...layout.cols.map(c => h("col", { key: c.id, style: c.width ? { width: c.width } : undefined })),
594
+ ),
595
+ head,
596
+ body,
597
+ ),
598
+ ),
599
+ footer,
600
+ );
601
+ }
602
+
262
603
  // ---------------------------------------------------------------------------
263
604
  // MultiSelect
264
605
  // ---------------------------------------------------------------------------