@tonycodes-ui/mortar 0.28.1 → 0.30.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/dist/grid.js ADDED
@@ -0,0 +1,371 @@
1
+ import { jsxs as _jsxs, jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
2
+ /* DataGrid: an interactive table for large or server-driven datasets, built on
3
+ TanStack Table and TanStack Virtual (optional peer dependencies). Mortar owns
4
+ the markup, styles, keyboard handling and public types; no TanStack type
5
+ appears in the props, so the engine can change without a breaking release. */
6
+ import { useCallback, useLayoutEffect, useMemo, useRef, useState, } from "react";
7
+ import { columnFilteringFeature, columnPinningFeature, columnVisibilityFeature, createFilteredRowModel, createPaginatedRowModel, createSortedRowModel, globalFilteringFeature, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, tableFeatures, useTable, } from "@tanstack/react-table";
8
+ import { useVirtualizer } from "@tanstack/react-virtual";
9
+ import { Popover, PopoverButton, PopoverPanel } from "@headlessui/react";
10
+ import { KitLink } from "./navigation.js";
11
+ import { Button, Checkbox, EmptyState, Input, Notice, Select, } from "./primitives.js";
12
+ import { Pagination } from "./application.js";
13
+ import { SortArrows } from "./icons.js";
14
+ import { componentRoot, cx } from "./internal.js";
15
+ import { columnAlign, compareValues, isEmpty, SelectAll, } from "./table-core.js";
16
+ const features = tableFeatures({
17
+ columnFilteringFeature,
18
+ globalFilteringFeature,
19
+ filteredRowModel: createFilteredRowModel(),
20
+ rowSortingFeature,
21
+ sortedRowModel: createSortedRowModel(),
22
+ rowPaginationFeature,
23
+ paginatedRowModel: createPaginatedRowModel(),
24
+ rowSelectionFeature,
25
+ columnVisibilityFeature,
26
+ columnPinningFeature,
27
+ });
28
+ /** Controlled when value is defined, otherwise local state seeded from initial. */
29
+ function useControllable(value, initial, onChange) {
30
+ const [local, setLocal] = useState(initial);
31
+ const current = value !== undefined ? value : local;
32
+ const set = (next) => {
33
+ if (value === undefined)
34
+ setLocal(next);
35
+ onChange?.(next);
36
+ };
37
+ return [current, set];
38
+ }
39
+ const resolve = (updater, old) => typeof updater === "function" ? updater(old) : updater;
40
+ function sortValueOf(col, row) {
41
+ return col.sortValue
42
+ ? col.sortValue(row)
43
+ : row[col.key];
44
+ }
45
+ function filterValueOf(col, row) {
46
+ const value = col.filterValue ? col.filterValue(row) : sortValueOf(col, row);
47
+ if (isEmpty(value))
48
+ return "";
49
+ return value instanceof Date ? value.toISOString() : String(value);
50
+ }
51
+ const matches = (value, query) => value.toLocaleLowerCase().includes(query.trim().toLocaleLowerCase());
52
+ // A stable default: a new [] each render would rebuild the selection set and
53
+ // recount select-all over every row on every render.
54
+ const NO_IDS = [];
55
+ // Stable table options: functions recreated each render would invalidate
56
+ // TanStack's row-model caches.
57
+ const getRowId = (row) => row.id;
58
+ const isMultiSortEvent = (e) => !!e?.shiftKey;
59
+ const globalFilterFn = (row, columnId, value) => matches(String(row.getValue(columnId) ?? ""), value);
60
+ export function DataGrid({ caption, columns, rows, rowLabel, mode = "client", rowCount, sort: sortProp, defaultSort = [], onSortChange, filters: filtersProp, defaultFilters = {}, onFiltersChange, searchable = false, search: searchProp, defaultSearch = "", onSearchChange, selectedIds: selectedIdsProp, onSelectionChange, hiddenColumns: hiddenProp, defaultHiddenColumns = [], onHiddenColumnsChange, pagination: paginationProp, defaultPagination, onPaginationChange, virtualize = false, estimateRowHeight = 44, rowHref, maxHeight = virtualize ? "32rem" : undefined, density = "default", striped = false, toolbar, bulkActions, footer, empty = {
61
+ title: "No records",
62
+ description: "Records will appear here when they are available.",
63
+ }, noResults = {
64
+ title: "No matching records",
65
+ description: "Try a different search or clear the filters.",
66
+ }, headingLevel = 3, loading, error, noun = "rows", id, className, }) {
67
+ const server = mode === "server";
68
+ const selectedIds = selectedIdsProp ?? NO_IDS;
69
+ const [sort, setSort] = useControllable(sortProp, defaultSort, onSortChange);
70
+ const [filters, setFilters] = useControllable(filtersProp, defaultFilters, onFiltersChange);
71
+ const [search, setSearch] = useControllable(searchProp, defaultSearch, onSearchChange);
72
+ const [hidden, setHidden] = useControllable(hiddenProp, defaultHiddenColumns, onHiddenColumnsChange);
73
+ const [paging, setPaging] = useControllable(paginationProp, defaultPagination, onPaginationChange);
74
+ // TanStack state derived from Mortar's public state. Each slice is memoised on
75
+ // its value: a new object every render would make TanStack re-sort and
76
+ // re-filter every row on every render, including each scroll frame.
77
+ const sortKey = JSON.stringify(sort);
78
+ const sorting = useMemo(() => sort.map((s) => ({ id: s.key, desc: s.direction === "descending" })),
79
+ // eslint-disable-next-line react-hooks/exhaustive-deps
80
+ [sortKey]);
81
+ const filtersKey = JSON.stringify(filters);
82
+ const columnFilters = useMemo(() => Object.entries(filters)
83
+ .filter(([, value]) => !isEmpty(value))
84
+ .map(([key, value]) => ({ id: key, value })),
85
+ // eslint-disable-next-line react-hooks/exhaustive-deps
86
+ [filtersKey]);
87
+ const selected = useMemo(() => new Set(selectedIds), [selectedIds]);
88
+ const rowSelection = useMemo(() => Object.fromEntries(selectedIds.map((rowId) => [rowId, true])), [selectedIds]);
89
+ const hiddenKey = hidden.join(",");
90
+ const columnVisibility = useMemo(() => Object.fromEntries(columns.map((col, index) => [
91
+ col.key,
92
+ index === 0 || !hidden.includes(col.key),
93
+ ])),
94
+ // eslint-disable-next-line react-hooks/exhaustive-deps
95
+ [columns, hiddenKey]);
96
+ const columnPinning = useMemo(() => ({
97
+ start: columns.filter((c) => c.pin === "start").map((c) => c.key),
98
+ end: columns.filter((c) => c.pin === "end").map((c) => c.key),
99
+ }), [columns]);
100
+ const pageIndex = paging ? Math.max(0, paging.page - 1) : 0;
101
+ const pageSize = paging ? paging.pageSize : Number.MAX_SAFE_INTEGER;
102
+ const pagination = useMemo(() => ({ pageIndex, pageSize }), [pageIndex, pageSize]);
103
+ const defs = useMemo(() => columns.map((col) => ({
104
+ id: col.key,
105
+ // Empty values read as undefined, so sortUndefined puts them last in
106
+ // both directions, as DataTable does. Filters treat them as "".
107
+ accessorFn: (row) => filterValueOf(col, row) || undefined,
108
+ enableSorting: !!col.sortable,
109
+ enableColumnFilter: !!col.filter,
110
+ enableHiding: col.hideable !== false,
111
+ // Ascending only; TanStack reverses for descending. Rows whose value
112
+ // is empty never reach here: sortUndefined handles them.
113
+ sortFn: (a, b) => compareValues(sortValueOf(col, a.original), sortValueOf(col, b.original)),
114
+ sortUndefined: "last",
115
+ filterFn: (row, columnId, value) => {
116
+ const cell = String(row.getValue(columnId) ?? "");
117
+ return typeof col.filter === "object"
118
+ ? cell === value
119
+ : matches(cell, value);
120
+ },
121
+ })), [columns]);
122
+ const table = useTable({
123
+ features,
124
+ columns: defs,
125
+ data: rows,
126
+ getRowId,
127
+ state: {
128
+ sorting,
129
+ columnFilters,
130
+ globalFilter: search,
131
+ rowSelection,
132
+ columnVisibility,
133
+ columnPinning,
134
+ pagination,
135
+ },
136
+ manualSorting: server,
137
+ manualFiltering: server,
138
+ manualPagination: server || !paging,
139
+ rowCount: server ? rowCount : undefined,
140
+ enableMultiSort: true,
141
+ isMultiSortEvent,
142
+ enableSortingRemoval: true,
143
+ autoResetPageIndex: false,
144
+ globalFilterFn,
145
+ onSortingChange: (u) => setSort(resolve(u, sorting).map((s) => ({
146
+ key: s.id,
147
+ direction: (s.desc ? "descending" : "ascending"),
148
+ }))),
149
+ onColumnFiltersChange: (u) => setFilters(Object.fromEntries(resolve(u, columnFilters).map((f) => [f.id, String(f.value)]))),
150
+ onGlobalFilterChange: (u) => setSearch(String(resolve(u, search) ?? "")),
151
+ onRowSelectionChange: (u) => {
152
+ const next = resolve(u, rowSelection);
153
+ onSelectionChange?.(Object.keys(next).filter((key) => next[key]));
154
+ },
155
+ onColumnVisibilityChange: (u) => {
156
+ const next = resolve(u, columnVisibility);
157
+ setHidden(columns.filter((c) => !next[c.key]).map((c) => c.key));
158
+ },
159
+ onPaginationChange: (u) => {
160
+ if (!paging)
161
+ return;
162
+ const next = resolve(u, pagination);
163
+ setPaging({ page: next.pageIndex + 1, pageSize: next.pageSize });
164
+ },
165
+ });
166
+ // Filtering or searching moves back to the first page.
167
+ const resetPage = () => paging && setPaging({ ...paging, page: 1 });
168
+ const visibleColumns = columns.filter((c) => columnVisibility[c.key]);
169
+ const ordered = [
170
+ ...visibleColumns.filter((c) => c.pin === "start"),
171
+ ...visibleColumns.filter((c) => !c.pin),
172
+ ...visibleColumns.filter((c) => c.pin === "end"),
173
+ ];
174
+ const matchingCount = server
175
+ ? (rowCount ?? rows.length)
176
+ : table.getFilteredRowModel().rows.length;
177
+ // A page past the end (rows removed, or a stale controlled page) shows the
178
+ // last page; the effect below reports the corrected page.
179
+ const pageCount = paging
180
+ ? Math.max(1, Math.ceil(matchingCount / paging.pageSize))
181
+ : 1;
182
+ const page = paging ? Math.min(Math.max(1, paging.page), pageCount) : 1;
183
+ const sortedRows = table.getSortedRowModel().rows;
184
+ const displayRows = paging && !server
185
+ ? sortedRows.slice((page - 1) * paging.pageSize, page * paging.pageSize)
186
+ : table.getRowModel().rows;
187
+ useLayoutEffect(() => {
188
+ if (paging && paging.page !== page && matchingCount > 0)
189
+ setPaging({ ...paging, page });
190
+ // eslint-disable-next-line react-hooks/exhaustive-deps
191
+ }, [page, paging?.page, matchingCount]);
192
+ const filtering = columnFilters.length > 0 || !isEmpty(search.trim());
193
+ // Select all covers every matching row in client mode, and the loaded page in
194
+ // server mode; selections elsewhere are kept.
195
+ const scopeRows = server ? displayRows : table.getFilteredRowModel().rows;
196
+ const scopeIds = useMemo(() => scopeRows.map((row) => row.id), [scopeRows]);
197
+ // Counted once per selection or result change, not on every scroll frame.
198
+ const selectedInScope = useMemo(() => scopeIds.reduce((n, rowId) => n + (selected.has(rowId) ? 1 : 0), 0), [scopeIds, selected]);
199
+ const allInScope = scopeIds.length > 0 && selectedInScope === scopeIds.length;
200
+ const scopeSet = useMemo(() => new Set(scopeIds), [scopeIds]);
201
+ const toggleAll = () => onSelectionChange?.(allInScope
202
+ ? selectedIds.filter((rowId) => !scopeSet.has(rowId))
203
+ : [...selectedIds, ...scopeIds.filter((rowId) => !selected.has(rowId))]);
204
+ // Sticky offsets for pinned columns come from the rendered header widths.
205
+ // A callback ref, so the effect re-runs when the table remounts after an
206
+ // empty or loading state.
207
+ const [headerRow, setHeaderRow] = useState(null);
208
+ const [offsets, setOffsets] = useState({});
209
+ const pinKey = ordered
210
+ .filter((c) => c.pin)
211
+ .map((c) => `${c.key}:${c.pin}`)
212
+ .join(",");
213
+ useLayoutEffect(() => {
214
+ const tr = headerRow;
215
+ if (!tr || !pinKey)
216
+ return;
217
+ const measure = () => {
218
+ if (!tr.isConnected)
219
+ return;
220
+ const cells = [...tr.children];
221
+ const next = {};
222
+ let start = 0;
223
+ for (const cell of cells) {
224
+ const key = cell.dataset.key;
225
+ const pin = cell.dataset.pin;
226
+ if (pin === "start" || cell.dataset.select !== undefined) {
227
+ if (key)
228
+ next[key] = start;
229
+ start += cell.offsetWidth;
230
+ }
231
+ else
232
+ break;
233
+ }
234
+ let end = 0;
235
+ for (const cell of cells.reverse()) {
236
+ if (cell.dataset.pin !== "end")
237
+ break;
238
+ next[cell.dataset.key] = end;
239
+ end += cell.offsetWidth;
240
+ }
241
+ setOffsets((old) => JSON.stringify(old) === JSON.stringify(next) ? old : next);
242
+ };
243
+ measure();
244
+ // Column widths can change while the row's width stays the same (new
245
+ // data, a new virtual window), so watch the pinned cells themselves.
246
+ const observer = new ResizeObserver(measure);
247
+ observer.observe(tr);
248
+ for (const cell of tr.querySelectorAll("[data-pin], [data-select]"))
249
+ observer.observe(cell);
250
+ return () => observer.disconnect();
251
+ }, [headerRow, pinKey, hidden.join(",")]);
252
+ // Row virtualization: only the rows in view render, with spacer rows keeping
253
+ // the scroll height. Rows keep aria-rowindex so assistive tech knows the size.
254
+ // Rows share one height, so one rendered row is measured and its height used
255
+ // for all of them. Measuring each row as it scrolls in would make the
256
+ // virtualizer recompute every later row's position on each frame.
257
+ const scrollRef = useRef(null);
258
+ const [rowHeight, setRowHeight] = useState(estimateRowHeight);
259
+ const getScrollElement = useCallback(() => scrollRef.current, []);
260
+ const estimateSize = useCallback(() => rowHeight, [rowHeight]);
261
+ const virtualizer = useVirtualizer({
262
+ count: virtualize ? displayRows.length : 0,
263
+ getScrollElement,
264
+ estimateSize,
265
+ overscan: 8,
266
+ });
267
+ const items = virtualize ? virtualizer.getVirtualItems() : [];
268
+ useLayoutEffect(() => {
269
+ if (!virtualize)
270
+ return;
271
+ const row = scrollRef.current?.querySelector("tbody tr:not(.m-data-grid-spacer)");
272
+ const height = row?.getBoundingClientRect().height;
273
+ if (height && Math.abs(height - rowHeight) > 0.5)
274
+ setRowHeight(height);
275
+ // A new estimateSize alone does not rebuild the cached row positions.
276
+ virtualizer.measure();
277
+ // Only when row height can change: not on every scroll frame, where a
278
+ // measurement would force a synchronous layout.
279
+ // eslint-disable-next-line react-hooks/exhaustive-deps
280
+ }, [
281
+ virtualize,
282
+ density,
283
+ hiddenKey,
284
+ // The first virtual rows appear a render after mount, once the virtualizer
285
+ // has its scroll element: measure then.
286
+ items.length > 0,
287
+ loading,
288
+ rowHeight,
289
+ ]);
290
+ const windowRows = virtualize
291
+ ? items.map((item) => ({ row: displayRows[item.index], index: item.index }))
292
+ : displayRows.map((row, index) => ({ row, index }));
293
+ const padTop = virtualize && items.length ? items[0].start : 0;
294
+ const padBottom = virtualize && items.length
295
+ ? virtualizer.getTotalSize() - items[items.length - 1].end
296
+ : 0;
297
+ const rowOffset = paging ? (page - 1) * paging.pageSize : 0;
298
+ const span = ordered.length + (onSelectionChange ? 1 : 0);
299
+ const pinStyle = (col) => col.pin && offsets[col.key] !== undefined
300
+ ? col.pin === "start"
301
+ ? { insetInlineStart: offsets[col.key] }
302
+ : { insetInlineEnd: offsets[col.key] }
303
+ : undefined;
304
+ const cellProps = (col, index) => ({
305
+ "data-key": col.key,
306
+ "data-pin": col.pin,
307
+ "data-priority": index > 0 && col.priority && col.priority !== "high"
308
+ ? col.priority
309
+ : undefined,
310
+ "data-align": columnAlign(col.align),
311
+ "data-truncate": col.truncate || undefined,
312
+ style: pinStyle(col),
313
+ });
314
+ const filterColumns = columns.filter((col) => col.filter);
315
+ const hideable = columns.filter((col, index) => index > 0 && col.hideable !== false);
316
+ const hasToolbarControls = searchable || filterColumns.length > 0 || hideable.length > 0;
317
+ const sortIndex = (key) => sort.findIndex((s) => s.key === key);
318
+ return (_jsxs("section", { id: id, ...componentRoot("DataGrid"), className: cx("m-data-table", "m-data-grid", className), "aria-label": caption, "data-density": density === "default" ? undefined : density, "data-striped": striped || undefined, children: [(hasToolbarControls || toolbar || selectedIds.length > 0) && (_jsx("div", { className: "m-table-toolbar", children: selectedIds.length > 0 ? (_jsxs(_Fragment, { children: [_jsxs("strong", { children: [selectedIds.length, " selected"] }), _jsxs("div", { className: "m-actions", children: [bulkActions, _jsx(Button, { variant: "ghost", onClick: () => onSelectionChange?.([]), children: "Clear selection" })] })] })) : (_jsxs(_Fragment, { children: [_jsxs("div", { className: "m-data-grid-controls", children: [searchable && (_jsx(Input, { label: "Search", type: "search", value: search, onChange: (event) => {
319
+ table.setGlobalFilter(event.target.value);
320
+ resetPage();
321
+ } })), filterColumns.map((col) => {
322
+ const value = filters[col.key] ?? "";
323
+ const setValue = (next) => {
324
+ table.getColumn(col.key)?.setFilterValue(next || undefined);
325
+ resetPage();
326
+ };
327
+ return typeof col.filter === "object" ? (_jsx(Select, { label: col.label, value: value, options: [
328
+ { value: "", label: "All" },
329
+ ...col.filter.options,
330
+ ], onChange: (event) => setValue(event.target.value) }, col.key)) : (_jsx(Input, { label: col.label, value: value, onChange: (event) => setValue(event.target.value) }, col.key));
331
+ }), toolbar] }), hideable.length > 0 && (_jsxs(Popover, { className: "m-data-grid-columns", children: [_jsx(PopoverButton, { as: Button, variant: "secondary", children: "Columns" }), _jsx(PopoverPanel, { anchor: "bottom end", className: "m-data-grid-columns-panel", children: _jsxs("fieldset", { children: [_jsx("legend", { children: "Show columns" }), hideable.map((col) => (_jsx(Checkbox, { label: col.label, checked: !hidden.includes(col.key), onChange: () => setHidden(hidden.includes(col.key)
332
+ ? hidden.filter((key) => key !== col.key)
333
+ : [...hidden, col.key]) }, col.key)))] }) })] }))] })) })), _jsx("p", { className: loading ? "m-table-state" : "m-sr-only", role: "status", "data-loading": loading || undefined, children: loading
334
+ ? "Loading records…"
335
+ : filtering
336
+ ? `${matchingCount} matching ${noun}`
337
+ : "" }), loading ? null : error ? (_jsx(Notice, { title: "Unable to load records", tone: "danger", announce: true, children: error })) : !rows.length && !filtering ? (_jsx(EmptyState, { title: empty.title, description: empty.description, action: empty.action, headingLevel: headingLevel })) : !displayRows.length ? (_jsx(EmptyState, { title: noResults.title, description: noResults.description, headingLevel: headingLevel, action: _jsx(Button, { variant: "secondary", onClick: () => {
338
+ table.resetColumnFilters(true);
339
+ table.resetGlobalFilter(true);
340
+ setFilters({});
341
+ setSearch("");
342
+ resetPage();
343
+ }, children: "Clear filters" }) })) : (_jsx("div", { ref: scrollRef, className: "m-table-scroll", role: "region", "aria-label": `${caption} scroll area`, tabIndex: 0, style: maxHeight ? { maxHeight } : undefined, "data-sticky": maxHeight ? true : undefined, children: _jsxs("table", { "aria-rowcount": virtualize ? matchingCount + 1 : undefined, children: [_jsx("caption", { className: "m-sr-only", children: caption }), ordered.some((col) => col.width) && (_jsxs("colgroup", { children: [onSelectionChange && _jsx("col", { className: "m-table-select-col" }), ordered.map((col) => (_jsx("col", { style: col.width ? { width: col.width } : undefined }, col.key)))] })), _jsx("thead", { children: _jsxs("tr", { ref: setHeaderRow, "aria-rowindex": virtualize ? 1 : undefined, children: [onSelectionChange && (_jsx("th", { scope: "col", "data-select": "", "data-pin": columnPinning.start.length ? "start" : undefined, style: columnPinning.start.length
344
+ ? { insetInlineStart: 0 }
345
+ : undefined, children: _jsx(SelectAll, { checked: allInScope, partial: selectedInScope > 0 && !allInScope, onChange: toggleAll }) })), ordered.map((col, index) => {
346
+ const position = sortIndex(col.key);
347
+ const direction = position >= 0 ? sort[position].direction : undefined;
348
+ return (_jsx("th", { scope: "col", ...cellProps(col, index), "aria-sort": col.sortable
349
+ ? position === 0
350
+ ? direction
351
+ : "none"
352
+ : undefined, children: col.sortable ? (_jsxs("button", { type: "button", className: "m-sort-button", onClick: (event) => table
353
+ .getColumn(col.key)
354
+ ?.toggleSorting(undefined, event.shiftKey && sort.length > 0), children: [col.label, _jsx(SortArrows, { direction: direction }), sort.length > 1 && position >= 0 && (_jsxs("span", { className: "m-sort-order", children: [_jsx("span", { className: "m-sr-only", children: ", sort level " }), position + 1] }))] })) : (col.label) }, col.key));
355
+ })] }) }), _jsxs("tbody", { children: [padTop > 0 && (_jsx("tr", { "aria-hidden": "true", className: "m-data-grid-spacer", children: _jsx("td", { colSpan: span, style: { height: padTop } }) })), windowRows.map(({ row, index }) => {
356
+ const original = row.original;
357
+ const href = rowHref?.(original);
358
+ const isSelected = selected.has(row.id);
359
+ return (_jsxs("tr", { "data-selected": isSelected || undefined, "data-linked": href ? true : undefined, "aria-rowindex": virtualize ? rowOffset + index + 2 : undefined, children: [onSelectionChange && (_jsx("td", { "data-select": "", "data-pin": columnPinning.start.length ? "start" : undefined, style: columnPinning.start.length
360
+ ? { insetInlineStart: 0 }
361
+ : undefined, children: _jsx("input", { type: "checkbox", "aria-label": `Select ${rowLabel(original)}`, checked: isSelected, onChange: row.getToggleSelectedHandler() }) })), ordered.map((col, colIndex) => {
362
+ const content = col.truncate ? (_jsx("span", { className: "m-truncate", children: col.render(original) })) : (col.render(original));
363
+ return colIndex === 0 ? (_jsx("th", { scope: "row", ...cellProps(col, colIndex), children: href ? (_jsx(KitLink, { className: "m-row-link", href: href, children: content })) : (content) }, col.key)) : (_jsx("td", { ...cellProps(col, colIndex), children: content }, col.key));
364
+ })] }, row.id));
365
+ }), padBottom > 0 && (_jsx("tr", { "aria-hidden": "true", className: "m-data-grid-spacer", children: _jsx("td", { colSpan: span, style: { height: padBottom } }) }))] })] }) })), (paging || footer) && !loading && !error && (_jsxs("div", { className: "m-table-footer", children: [paging && matchingCount > 0 && (_jsx(Pagination, { page: page, pageCount: pageCount, numbered: true, summary: {
366
+ from: Math.min(matchingCount, rowOffset + 1),
367
+ to: Math.min(matchingCount, rowOffset + paging.pageSize),
368
+ total: matchingCount,
369
+ noun,
370
+ }, onChange: (page) => setPaging({ ...paging, page }) })), footer] }))] }));
371
+ }
@@ -0,0 +1,28 @@
1
+ import { type ChartSlot } from "./chart-core.js";
2
+ export interface SparklineProps {
3
+ /** The values in order, oldest first. Missing values (NaN) break the line. */
4
+ values: readonly number[];
5
+ /** What the values measure, e.g. "Revenue, last 12 months". Read as the start of its summary. */
6
+ label: string;
7
+ /** Formats values in the spoken summary. Defaults to the locale's number format. */
8
+ format?: (value: number) => string;
9
+ /** Series colour slot, 1–8. Default 1. */
10
+ slot?: ChartSlot;
11
+ /** Height in pixels; the width follows the container. Default 32. */
12
+ height?: number;
13
+ /** Mark the latest value with a dot. Default true. */
14
+ showLast?: boolean;
15
+ /** Fill under the line. */
16
+ area?: boolean;
17
+ /** Shade a reference range, such as a target or normal band. */
18
+ band?: {
19
+ min: number;
20
+ max: number;
21
+ };
22
+ id?: string;
23
+ className?: string;
24
+ }
25
+ /** The spoken summary: label, count, range and latest value. */
26
+ export declare function sparklineSummary(values: readonly number[], label: string, format?: (value: number) => string): string;
27
+ /** A small, axis-free trend line for a stat tile, table cell or list row. */
28
+ export declare function Sparkline({ values, label, format, slot, height, showLast, area, band, id, className, }: SparklineProps): import("react").JSX.Element;
@@ -0,0 +1,31 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { componentRoot, cx } from "./internal.js";
3
+ import { areaPath, extent, linearScale, linePath, seriesColour, } from "./chart-core.js";
4
+ const number = new Intl.NumberFormat();
5
+ /** The spoken summary: label, count, range and latest value. */
6
+ export function sparklineSummary(values, label, format = (v) => number.format(v)) {
7
+ const finite = values.filter(Number.isFinite);
8
+ if (!finite.length)
9
+ return `${label}: no data`;
10
+ const [min, max] = extent(finite);
11
+ const last = finite[finite.length - 1];
12
+ return finite.length === 1
13
+ ? `${label}: ${format(last)}`
14
+ : `${label}: ${finite.length} values from ${format(min)} to ${format(max)}, latest ${format(last)}`;
15
+ }
16
+ /** A small, axis-free trend line for a stat tile, table cell or list row. */
17
+ export function Sparkline({ values, label, format, slot = 1, height = 32, showLast = true, area = false, band, id, className, }) {
18
+ const [min, max] = extent(band ? [...values, band.min, band.max] : [...values]);
19
+ // A single value maps through a flat domain to the middle.
20
+ const x = linearScale([0, values.length - 1], [0, 100]);
21
+ const y = linearScale([min, max], [100, 0]);
22
+ const points = values.map((v, i) => ({ x: x(i), y: y(v) }));
23
+ let lastIndex = values.length - 1;
24
+ while (lastIndex >= 0 && !Number.isFinite(values[lastIndex]))
25
+ lastIndex--;
26
+ const last = lastIndex >= 0 ? points[lastIndex] : undefined;
27
+ return (_jsx("span", { id: id, ...componentRoot("Sparkline"), className: cx("m-sparkline", className), role: "img", "aria-label": sparklineSummary(values, label, format), style: {
28
+ height,
29
+ "--m-sparkline-colour": seriesColour(slot),
30
+ }, children: _jsxs("span", { className: "m-sparkline-plot", children: [_jsxs("svg", { viewBox: "0 0 100 100", preserveAspectRatio: "none", "aria-hidden": "true", focusable: "false", children: [band && (_jsx("rect", { className: "m-sparkline-band", x: "0", width: "100", y: Math.min(y(band.min), y(band.max)), height: Math.abs(y(band.min) - y(band.max)) })), area && (_jsx("path", { className: "m-sparkline-area", d: areaPath(points, 100) })), _jsx("path", { className: "m-sparkline-line", d: linePath(points), vectorEffect: "non-scaling-stroke" })] }), showLast && last && (_jsx("span", { className: "m-sparkline-last", style: { left: `${last.x}%`, top: `${last.y}%` }, "aria-hidden": "true" }))] }) }));
31
+ }
@@ -0,0 +1,54 @@
1
+ import { type ReactNode } from "react";
2
+ export type SortDirection = "ascending" | "descending";
3
+ export interface TableSort {
4
+ key: string;
5
+ direction: SortDirection;
6
+ }
7
+ export interface DataTableColumn<T> {
8
+ key: string;
9
+ label: string;
10
+ render: (row: T) => ReactNode;
11
+ /** `end` aligns numbers and amounts to the trailing edge. */
12
+ align?: "start" | "end";
13
+ /** Enable header sorting. Supply sortValue unless row[key] is a string, number or Date. */
14
+ sortable?: boolean;
15
+ sortValue?: (row: T) => string | number | Date | null | undefined;
16
+ /** CSS width, e.g. "12rem" or "30%". */
17
+ width?: string;
18
+ /** Clip long values to one line with an ellipsis. */
19
+ truncate?: boolean;
20
+ /**
21
+ * How long the column stays as the table narrows (its own width, not the
22
+ * screen's): `medium` hides below 480px, `low` below 768px. The first
23
+ * column always shows. Hidden columns leave the accessibility tree too, so
24
+ * keep what people need in visible columns or on the detail page.
25
+ */
26
+ priority?: "high" | "medium" | "low";
27
+ /**
28
+ * `end` pins the column to the trailing edge while the table scrolls
29
+ * sideways, so a row-actions or status column stays reachable.
30
+ */
31
+ pin?: "end";
32
+ }
33
+ /** Responsive attributes shared by a column's `col`, header and cells. */
34
+ export declare function columnLayout<T>(col: DataTableColumn<T>, index: number): {
35
+ "data-priority": "low" | "medium" | undefined;
36
+ "data-pin": "end" | undefined;
37
+ };
38
+ export declare const isEmpty: (v: unknown) => v is "" | null | undefined;
39
+ export declare function compareValues(a: unknown, b: unknown): number;
40
+ /** Stable sort; empty values always sort last regardless of direction. */
41
+ export declare function sortRows<T>(rows: T[], column: Pick<DataTableColumn<T>, "key" | "sortValue">, direction: SortDirection): T[];
42
+ export declare function SelectAll({ checked, partial, onChange, }: {
43
+ checked: boolean;
44
+ partial: boolean;
45
+ onChange: () => void;
46
+ }): import("react").JSX.Element;
47
+ /** Buckets ordered rows by group; groups keep their first-appearance order in the unsorted rows. */
48
+ export declare function groupRows<T>(rows: T[], ordered: T[], groupBy: (row: T) => string): [string, T[]][];
49
+ /** Full-width header row that labels the rows of its tbody. */
50
+ export declare function TableGroupRow({ label, span, }: {
51
+ label: string;
52
+ span: number;
53
+ }): import("react").JSX.Element;
54
+ export declare const columnAlign: (align?: "start" | "end") => "end" | undefined;
@@ -0,0 +1,59 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ // Table building blocks shared by DataTable and DataGrid. Internal: the public
3
+ // types are re-exported from application.tsx and the package entry.
4
+ import { useEffect, useRef } from "react";
5
+ /** Responsive attributes shared by a column's `col`, header and cells. */
6
+ export function columnLayout(col, index) {
7
+ return {
8
+ "data-priority": index > 0 && col.priority && col.priority !== "high"
9
+ ? col.priority
10
+ : undefined,
11
+ "data-pin": col.pin,
12
+ };
13
+ }
14
+ const collator = new Intl.Collator(undefined, {
15
+ numeric: true,
16
+ sensitivity: "base",
17
+ });
18
+ export const isEmpty = (v) => v === null || v === undefined || v === "";
19
+ export function compareValues(a, b) {
20
+ if (isEmpty(a) || isEmpty(b))
21
+ return isEmpty(a) === isEmpty(b) ? 0 : isEmpty(a) ? 1 : -1;
22
+ if (a instanceof Date && b instanceof Date)
23
+ return a.getTime() - b.getTime();
24
+ if (typeof a === "number" && typeof b === "number")
25
+ return a - b;
26
+ return collator.compare(String(a), String(b));
27
+ }
28
+ /** Stable sort; empty values always sort last regardless of direction. */
29
+ export function sortRows(rows, column, direction) {
30
+ const value = column.sortValue ||
31
+ ((row) => row[column.key]);
32
+ const sign = direction === "ascending" ? 1 : -1;
33
+ return rows
34
+ .map((row, index) => ({ row, index, v: value(row) }))
35
+ .sort((a, b) =>
36
+ // Empty values sort last in both directions, so only real values flip.
37
+ (isEmpty(a.v) || isEmpty(b.v) ? 1 : sign) * compareValues(a.v, b.v) ||
38
+ a.index - b.index)
39
+ .map((entry) => entry.row);
40
+ }
41
+ export function SelectAll({ checked, partial, onChange, }) {
42
+ const ref = useRef(null);
43
+ useEffect(() => {
44
+ if (ref.current)
45
+ ref.current.indeterminate = partial;
46
+ }, [partial]);
47
+ return (_jsx("input", { ref: ref, type: "checkbox", "aria-label": "Select all rows", checked: checked, onChange: onChange }));
48
+ }
49
+ /** Buckets ordered rows by group; groups keep their first-appearance order in the unsorted rows. */
50
+ export function groupRows(rows, ordered, groupBy) {
51
+ const groups = new Map(rows.map((row) => [groupBy(row), []]));
52
+ ordered.forEach((row) => groups.get(groupBy(row)).push(row));
53
+ return [...groups];
54
+ }
55
+ /** Full-width header row that labels the rows of its tbody. */
56
+ export function TableGroupRow({ label, span, }) {
57
+ return (_jsx("tr", { className: "m-table-group", children: _jsx("th", { colSpan: span, scope: "rowgroup", children: label }) }));
58
+ }
59
+ export const columnAlign = (align) => align === "end" ? "end" : undefined;
package/docs/agents.md CHANGED
@@ -77,6 +77,7 @@ npx mortar component DataTable
77
77
  npx mortar packet AppShell DataTable
78
78
  npx mortar packet --brief "an admin screen listing invoices with filters"
79
79
  npx mortar audit .
80
+ npx mortar audit . --render http://localhost:5173/,http://localhost:5173/settings
80
81
  npx mortar guide theming
81
82
  ```
82
83
 
@@ -88,7 +89,7 @@ Add `--json` for machine-readable output. `mortar audit` exits with status 1 whe
88
89
  2. **Packet.** Call `get_build_packet` with the components you picked, or with the brief. Compose from it: the contracts list every prop, and the page templates show complete page patterns to follow.
89
90
  3. **Compose.** Use named imports from `@tonycodes-ui/mortar` and the exact props and values in each contract. Keep product names, data, routes, permissions and actions in props and slots. Theme with `ThemeProvider` and tokens (`get_guide theming`). Never copy a component's source, wrap it repeatedly, or override `.m-*` classes or `[data-m-component]` in your CSS. When replacing an unlabeled native `<input>`, move search icons onto `leadingIcon`/`trailingIcon` and units onto `prefix`/`suffix`; do not keep `relative`/`absolute` chrome around a labeled `Input`, and do not put static text in `action` (that slot is for an attached Button or menu).
90
91
  For an iOS, iPadOS or Android app, use the SwiftUI package and the Compose library (`get_guide native`). A component's contract names its native equivalent under `native`, and a packet for a native brief lists every component the native libraries have.
91
- 4. **Audit.** Run `audit_app` (or `npx mortar audit`) and fix what it finds, then run the app's own typecheck and build. Verify in a browser: mobile and desktop, light and dark, keyboard and focus, and loading, empty and error states.
92
+ 4. **Audit.** Run `audit_app` (or `npx mortar audit`) and fix what it finds, then run the app's own typecheck and build. With the app running, add the page URLs (`render`, or `--render`) to check what rendered. Verify in a browser: mobile and desktop, light and dark, keyboard and focus, and loading, empty and error states.
92
93
  5. **Contribute.** If a shared pattern is missing or a component is wrong, fix it in the kit, not in the app. Open a pull request at [github.com/tonycodes/mortar](https://github.com/tonycodes/mortar) following [CONTRIBUTING.md](../CONTRIBUTING.md) and [AGENTS.md](../AGENTS.md) (`get_guide contributing`). Maintainer review and CI decide what merges; agents never approve, merge or publish their own changes.
93
94
 
94
95
  ## The audit
@@ -124,6 +125,21 @@ Add `--json` for machine-readable output. `mortar audit` exits with status 1 whe
124
125
 
125
126
  The audit is a fast scanner, not a type checker. It checks JSX body children when a component's contract has no `children` slot (for example `<Switch>…</Switch>`). It does not see props passed through a spread (`{...props}`), components re-exported or wrapped under another name, class names built at runtime, or markup in `.vue`, `.svelte`, `.astro` or `.html` files. Run the app's typecheck and build as well.
126
127
 
128
+ ### Rendered checks
129
+
130
+ `--render` (or `audit_app`'s `render` argument) takes comma-separated URLs of the running app. After the source scan, each page opens in a headless browser at 390px and 1280px, in light and dark, and the audit checks what actually rendered. It only reads the pages: it never clicks, types or submits. It needs Playwright in the app (`npm install -D playwright` and `npx playwright install chromium`); set `MORTAR_CHROME` to use another Chromium.
131
+
132
+ | Rule | Severity | Finds |
133
+ | ----------------------- | -------- | -------------------------------------------------------------------------------------------------------- |
134
+ | `render-error` | error | A console error or uncaught exception, or a page that does not load |
135
+ | `render-missing-styles` | error | Mortar components on a page without Mortar's tokens, so `styles.css` is not loaded |
136
+ | `render-box-sizing` | error | Mortar controls with content-box sizing, usually because Tailwind is not imported before Mortar's styles |
137
+ | `render-row-height` | warning | Mortar controls side by side in one row at different heights |
138
+ | `render-label-align` | warning | A Mortar field label that is not start-aligned, usually inherited from a parent's `text-align` |
139
+ | `render-overflow` | warning | A page that scrolls sideways at 390px |
140
+
141
+ Each problem is reported once, with the widths and appearances it showed in when it was not all of them. Rendered checks cover the states a page shows when it loads; open dialogs, menus and error states are not reached. Keep checking those in a browser.
142
+
127
143
  A clean audit means the audit found none of the problems above. It is not proof that a page is built only from Mortar components: hand-written layout, typography or animation in the app's own markup is invisible to it unless it touches Mortar's classes, colours, or an obvious ancestor/native-element visual override. Do not report a passing audit as that proof. To show a page is composed from the kit, point to the components it renders (each root carries `data-m-component`) and to [what you can extend](theming.md#what-you-can-extend).
128
144
 
129
145
  ## Agent skill