@tonycodes-ui/mortar 0.28.1 → 0.29.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/CHANGELOG.md +19 -2
- package/bin/mortar.mjs +16 -4
- package/catalog.json +630 -355
- package/cli/audit.mjs +24 -9
- package/cli/data.mjs +5 -0
- package/cli/packet.mjs +39 -3
- package/cli/render.mjs +315 -0
- package/cli/tools.mjs +24 -2
- package/dist/agent-data.json +1 -1
- package/dist/application.d.ts +2 -33
- package/dist/application.js +2 -56
- package/dist/data-grid.d.ts +2 -0
- package/dist/data-grid.js +4 -0
- package/dist/grid.d.ts +102 -0
- package/dist/grid.js +371 -0
- package/dist/table-core.d.ts +54 -0
- package/dist/table-core.js +59 -0
- package/docs/agents.md +17 -1
- package/docs/data-grid.md +155 -0
- package/package.json +17 -3
- package/skills/mortar/SKILL.md +1 -1
- package/src/application.tsx +15 -114
- package/src/data-grid.ts +13 -0
- package/src/data.css +64 -1
- package/src/foundation.css +3 -1
- package/src/grid.tsx +906 -0
- package/src/table-core.tsx +128 -0
package/dist/application.d.ts
CHANGED
|
@@ -193,37 +193,8 @@ export interface MetricGroupProps {
|
|
|
193
193
|
className?: string;
|
|
194
194
|
}
|
|
195
195
|
export declare function MetricGroup({ label, items, variant, className, }: MetricGroupProps): import("react").JSX.Element;
|
|
196
|
-
export type SortDirection
|
|
197
|
-
|
|
198
|
-
key: string;
|
|
199
|
-
direction: SortDirection;
|
|
200
|
-
}
|
|
201
|
-
export interface DataTableColumn<T> {
|
|
202
|
-
key: string;
|
|
203
|
-
label: string;
|
|
204
|
-
render: (row: T) => ReactNode;
|
|
205
|
-
/** `end` aligns numbers and amounts to the trailing edge. */
|
|
206
|
-
align?: "start" | "end";
|
|
207
|
-
/** Enable header sorting. Supply sortValue unless row[key] is a string, number or Date. */
|
|
208
|
-
sortable?: boolean;
|
|
209
|
-
sortValue?: (row: T) => string | number | Date | null | undefined;
|
|
210
|
-
/** CSS width, e.g. "12rem" or "30%". */
|
|
211
|
-
width?: string;
|
|
212
|
-
/** Clip long values to one line with an ellipsis. */
|
|
213
|
-
truncate?: boolean;
|
|
214
|
-
/**
|
|
215
|
-
* How long the column stays as the table narrows (its own width, not the
|
|
216
|
-
* screen's): `medium` hides below 480px, `low` below 768px. The first
|
|
217
|
-
* column always shows. Hidden columns leave the accessibility tree too, so
|
|
218
|
-
* keep what people need in visible columns or on the detail page.
|
|
219
|
-
*/
|
|
220
|
-
priority?: "high" | "medium" | "low";
|
|
221
|
-
/**
|
|
222
|
-
* `end` pins the column to the trailing edge while the table scrolls
|
|
223
|
-
* sideways, so a row-actions or status column stays reachable.
|
|
224
|
-
*/
|
|
225
|
-
pin?: "end";
|
|
226
|
-
}
|
|
196
|
+
export type { SortDirection, TableSort, DataTableColumn, } from "./table-core.js";
|
|
197
|
+
import { type DataTableColumn, type TableSort } from "./table-core.js";
|
|
227
198
|
export interface DataTableProps<T extends {
|
|
228
199
|
id: string;
|
|
229
200
|
}> {
|
|
@@ -264,8 +235,6 @@ export interface DataTableProps<T extends {
|
|
|
264
235
|
id?: string;
|
|
265
236
|
className?: string;
|
|
266
237
|
}
|
|
267
|
-
/** Stable sort; empty values always sort last regardless of direction. */
|
|
268
|
-
export declare function sortRows<T>(rows: T[], column: Pick<DataTableColumn<T>, "key" | "sortValue">, direction: SortDirection): T[];
|
|
269
238
|
export declare function DataTable<T extends {
|
|
270
239
|
id: string;
|
|
271
240
|
}>({ caption, columns, rows, selectedIds, onSelectionChange, rowLabel, rowHref, defaultSort, sort: controlledSort, onSortChange, groupBy, maxHeight, density, striped, toolbar, bulkActions, footer, empty, headingLevel, loading, error, id, className, }: DataTableProps<T>): import("react").JSX.Element;
|
package/dist/application.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
2
2
|
import { KitLink } from "./navigation.js";
|
|
3
|
-
import { useId,
|
|
3
|
+
import { useId, useState, } from "react";
|
|
4
4
|
import { Button, EmptyState, Input, Notice } from "./primitives.js";
|
|
5
5
|
import { BrandMark, Divider } from "./layout.js";
|
|
6
6
|
import { AuthHeader, ProviderButtons } from "./auth.js";
|
|
@@ -87,61 +87,7 @@ export function MetricGroup({ label, items, variant = "shared", className, }) {
|
|
|
87
87
|
details: (_jsxs(_Fragment, { children: [_jsx("strong", { children: item.value }), item.previous && (_jsxs("span", { className: "m-metric-previous", children: ["from ", item.previous] })), item.change && (_jsxs("span", { className: "m-metric-change", "data-tone": item.tone && item.tone !== "neutral" ? item.tone : undefined, "data-trend": item.trend, children: [item.trend && (_jsxs(_Fragment, { children: [item.trend === "up" ? _jsx(ArrowUp, {}) : _jsx(ArrowDown, {}), _jsx("span", { className: "m-sr-only", children: item.trend === "up" ? "Increased by " : "Decreased by " })] })), item.change] }))] })),
|
|
88
88
|
})) }));
|
|
89
89
|
}
|
|
90
|
-
|
|
91
|
-
function columnLayout(col, index) {
|
|
92
|
-
return {
|
|
93
|
-
"data-priority": index > 0 && col.priority && col.priority !== "high"
|
|
94
|
-
? col.priority
|
|
95
|
-
: undefined,
|
|
96
|
-
"data-pin": col.pin,
|
|
97
|
-
};
|
|
98
|
-
}
|
|
99
|
-
const collator = new Intl.Collator(undefined, {
|
|
100
|
-
numeric: true,
|
|
101
|
-
sensitivity: "base",
|
|
102
|
-
});
|
|
103
|
-
const isEmpty = (v) => v === null || v === undefined || v === "";
|
|
104
|
-
function compareValues(a, b) {
|
|
105
|
-
if (isEmpty(a) || isEmpty(b))
|
|
106
|
-
return isEmpty(a) === isEmpty(b) ? 0 : isEmpty(a) ? 1 : -1;
|
|
107
|
-
if (a instanceof Date && b instanceof Date)
|
|
108
|
-
return a.getTime() - b.getTime();
|
|
109
|
-
if (typeof a === "number" && typeof b === "number")
|
|
110
|
-
return a - b;
|
|
111
|
-
return collator.compare(String(a), String(b));
|
|
112
|
-
}
|
|
113
|
-
/** Stable sort; empty values always sort last regardless of direction. */
|
|
114
|
-
export function sortRows(rows, column, direction) {
|
|
115
|
-
const value = column.sortValue ||
|
|
116
|
-
((row) => row[column.key]);
|
|
117
|
-
const sign = direction === "ascending" ? 1 : -1;
|
|
118
|
-
return rows
|
|
119
|
-
.map((row, index) => ({ row, index, v: value(row) }))
|
|
120
|
-
.sort((a, b) =>
|
|
121
|
-
// Empty values sort last in both directions, so only real values flip.
|
|
122
|
-
(isEmpty(a.v) || isEmpty(b.v) ? 1 : sign) * compareValues(a.v, b.v) ||
|
|
123
|
-
a.index - b.index)
|
|
124
|
-
.map((entry) => entry.row);
|
|
125
|
-
}
|
|
126
|
-
function SelectAll({ checked, partial, onChange, }) {
|
|
127
|
-
const ref = useRef(null);
|
|
128
|
-
useEffect(() => {
|
|
129
|
-
if (ref.current)
|
|
130
|
-
ref.current.indeterminate = partial;
|
|
131
|
-
}, [partial]);
|
|
132
|
-
return (_jsx("input", { ref: ref, type: "checkbox", "aria-label": "Select all rows", checked: checked, onChange: onChange }));
|
|
133
|
-
}
|
|
134
|
-
/** Buckets ordered rows by group; groups keep their first-appearance order in the unsorted rows. */
|
|
135
|
-
function groupRows(rows, ordered, groupBy) {
|
|
136
|
-
const groups = new Map(rows.map((row) => [groupBy(row), []]));
|
|
137
|
-
ordered.forEach((row) => groups.get(groupBy(row)).push(row));
|
|
138
|
-
return [...groups];
|
|
139
|
-
}
|
|
140
|
-
/** Full-width header row that labels the rows of its tbody. */
|
|
141
|
-
function TableGroupRow({ label, span }) {
|
|
142
|
-
return (_jsx("tr", { className: "m-table-group", children: _jsx("th", { colSpan: span, scope: "rowgroup", children: label }) }));
|
|
143
|
-
}
|
|
144
|
-
const columnAlign = (align) => align === "end" ? "end" : undefined;
|
|
90
|
+
import { columnAlign, columnLayout, groupRows, SelectAll, sortRows, TableGroupRow, } from "./table-core.js";
|
|
145
91
|
export function DataTable({ caption, columns, rows, selectedIds = [], onSelectionChange, rowLabel, rowHref, defaultSort, sort: controlledSort, onSortChange, groupBy, maxHeight, density = "default", striped = false, toolbar, bulkActions, footer, empty = {
|
|
146
92
|
title: "No records",
|
|
147
93
|
description: "Records will appear here when they are available.",
|
package/dist/grid.d.ts
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { type ReactNode } from "react";
|
|
2
|
+
import type { HeadingLevel } from "./heading.js";
|
|
3
|
+
import { type DataTableColumn, type SortDirection, type TableSort } from "./table-core.js";
|
|
4
|
+
export interface DataGridColumn<T> extends Omit<DataTableColumn<T>, "pin"> {
|
|
5
|
+
/** Keep the column in view while the grid scrolls sideways. */
|
|
6
|
+
pin?: "start" | "end";
|
|
7
|
+
/**
|
|
8
|
+
* Adds a filter control to the toolbar. `text` matches part of the value,
|
|
9
|
+
* ignoring case; `options` offers an exact-match choice.
|
|
10
|
+
*/
|
|
11
|
+
filter?: "text" | {
|
|
12
|
+
options: {
|
|
13
|
+
value: string;
|
|
14
|
+
label: string;
|
|
15
|
+
}[];
|
|
16
|
+
};
|
|
17
|
+
/** The value filters and search compare. Defaults to sortValue, then row[key]. */
|
|
18
|
+
filterValue?: (row: T) => string | number | null | undefined;
|
|
19
|
+
/** Whether people can hide the column from the Columns menu. Default true; the first column always shows. */
|
|
20
|
+
hideable?: boolean;
|
|
21
|
+
}
|
|
22
|
+
/** Column key to filter value. A missing or empty value means no filter. */
|
|
23
|
+
export type DataGridFilters = Record<string, string>;
|
|
24
|
+
export interface DataGridPagination {
|
|
25
|
+
/** One-based page number. */
|
|
26
|
+
page: number;
|
|
27
|
+
pageSize: number;
|
|
28
|
+
}
|
|
29
|
+
export interface DataGridProps<T extends {
|
|
30
|
+
id: string;
|
|
31
|
+
}> {
|
|
32
|
+
caption: string;
|
|
33
|
+
columns: DataGridColumn<T>[];
|
|
34
|
+
/** Every row in client mode; the current page in server mode. */
|
|
35
|
+
rows: T[];
|
|
36
|
+
rowLabel: (row: T) => string;
|
|
37
|
+
/**
|
|
38
|
+
* `client` sorts, filters, searches and pages rows in the browser. `server`
|
|
39
|
+
* only reports state changes: pass the matching page of rows and rowCount.
|
|
40
|
+
*/
|
|
41
|
+
mode?: "client" | "server";
|
|
42
|
+
/** Total matching rows. Required in server mode. */
|
|
43
|
+
rowCount?: number;
|
|
44
|
+
/** Controlled sort levels, the first sorting first. Shift-click a header to add a level. */
|
|
45
|
+
sort?: TableSort[];
|
|
46
|
+
defaultSort?: TableSort[];
|
|
47
|
+
onSortChange?: (sort: TableSort[]) => void;
|
|
48
|
+
filters?: DataGridFilters;
|
|
49
|
+
defaultFilters?: DataGridFilters;
|
|
50
|
+
onFiltersChange?: (filters: DataGridFilters) => void;
|
|
51
|
+
/** Show a search field that matches any column's filter value. */
|
|
52
|
+
searchable?: boolean;
|
|
53
|
+
/** Controlled search text. */
|
|
54
|
+
search?: string;
|
|
55
|
+
defaultSearch?: string;
|
|
56
|
+
onSearchChange?: (search: string) => void;
|
|
57
|
+
/** Selected row ids, which may include rows that are not loaded. */
|
|
58
|
+
selectedIds?: string[];
|
|
59
|
+
onSelectionChange?: (ids: string[]) => void;
|
|
60
|
+
/** Keys of hidden columns. */
|
|
61
|
+
hiddenColumns?: string[];
|
|
62
|
+
defaultHiddenColumns?: string[];
|
|
63
|
+
onHiddenColumnsChange?: (keys: string[]) => void;
|
|
64
|
+
/** Pages rows when set; without it every row renders (pair large sets with virtualize). */
|
|
65
|
+
pagination?: DataGridPagination;
|
|
66
|
+
defaultPagination?: DataGridPagination;
|
|
67
|
+
onPaginationChange?: (pagination: DataGridPagination) => void;
|
|
68
|
+
/** Render only the rows in view. Needs maxHeight (default 32rem when virtualizing). */
|
|
69
|
+
virtualize?: boolean;
|
|
70
|
+
/** Row height in pixels used for virtualization until a row is measured. Default 44. */
|
|
71
|
+
estimateRowHeight?: number;
|
|
72
|
+
/** Link each row's first cell to a detail page. */
|
|
73
|
+
rowHref?: (row: T) => string | undefined;
|
|
74
|
+
maxHeight?: string;
|
|
75
|
+
density?: "default" | "compact";
|
|
76
|
+
striped?: boolean;
|
|
77
|
+
/** Extra toolbar content, after the built-in search and filters. */
|
|
78
|
+
toolbar?: ReactNode;
|
|
79
|
+
bulkActions?: ReactNode;
|
|
80
|
+
footer?: ReactNode;
|
|
81
|
+
empty?: {
|
|
82
|
+
title: string;
|
|
83
|
+
description?: string;
|
|
84
|
+
action?: ReactNode;
|
|
85
|
+
};
|
|
86
|
+
/** Shown when rows exist but search or filters match none. */
|
|
87
|
+
noResults?: {
|
|
88
|
+
title: string;
|
|
89
|
+
description?: string;
|
|
90
|
+
};
|
|
91
|
+
headingLevel?: HeadingLevel;
|
|
92
|
+
loading?: boolean;
|
|
93
|
+
error?: string;
|
|
94
|
+
/** Plural noun for counts, e.g. "invoices". Default "rows". */
|
|
95
|
+
noun?: string;
|
|
96
|
+
id?: string;
|
|
97
|
+
className?: string;
|
|
98
|
+
}
|
|
99
|
+
export declare function DataGrid<T extends {
|
|
100
|
+
id: string;
|
|
101
|
+
}>({ caption, columns, rows, rowLabel, mode, rowCount, sort: sortProp, defaultSort, onSortChange, filters: filtersProp, defaultFilters, onFiltersChange, searchable, search: searchProp, defaultSearch, onSearchChange, selectedIds: selectedIdsProp, onSelectionChange, hiddenColumns: hiddenProp, defaultHiddenColumns, onHiddenColumnsChange, pagination: paginationProp, defaultPagination, onPaginationChange, virtualize, estimateRowHeight, rowHref, maxHeight, density, striped, toolbar, bulkActions, footer, empty, noResults, headingLevel, loading, error, noun, id, className, }: DataGridProps<T>): import("react").JSX.Element;
|
|
102
|
+
export type { TableSort, SortDirection };
|
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
|
+
}
|