@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/src/grid.tsx
ADDED
|
@@ -0,0 +1,906 @@
|
|
|
1
|
+
/* DataGrid: an interactive table for large or server-driven datasets, built on
|
|
2
|
+
TanStack Table and TanStack Virtual (optional peer dependencies). Mortar owns
|
|
3
|
+
the markup, styles, keyboard handling and public types; no TanStack type
|
|
4
|
+
appears in the props, so the engine can change without a breaking release. */
|
|
5
|
+
import {
|
|
6
|
+
useCallback,
|
|
7
|
+
useLayoutEffect,
|
|
8
|
+
useMemo,
|
|
9
|
+
useRef,
|
|
10
|
+
useState,
|
|
11
|
+
type ReactNode,
|
|
12
|
+
} from "react";
|
|
13
|
+
import {
|
|
14
|
+
columnFilteringFeature,
|
|
15
|
+
columnPinningFeature,
|
|
16
|
+
columnVisibilityFeature,
|
|
17
|
+
createFilteredRowModel,
|
|
18
|
+
createPaginatedRowModel,
|
|
19
|
+
createSortedRowModel,
|
|
20
|
+
globalFilteringFeature,
|
|
21
|
+
rowPaginationFeature,
|
|
22
|
+
rowSelectionFeature,
|
|
23
|
+
rowSortingFeature,
|
|
24
|
+
tableFeatures,
|
|
25
|
+
useTable,
|
|
26
|
+
type ColumnDef,
|
|
27
|
+
type ColumnFiltersState,
|
|
28
|
+
type PaginationState,
|
|
29
|
+
type RowSelectionState,
|
|
30
|
+
type SortingState,
|
|
31
|
+
type Updater,
|
|
32
|
+
} from "@tanstack/react-table";
|
|
33
|
+
import { useVirtualizer } from "@tanstack/react-virtual";
|
|
34
|
+
import { Popover, PopoverButton, PopoverPanel } from "@headlessui/react";
|
|
35
|
+
import { KitLink } from "./navigation.js";
|
|
36
|
+
import {
|
|
37
|
+
Button,
|
|
38
|
+
Checkbox,
|
|
39
|
+
EmptyState,
|
|
40
|
+
Input,
|
|
41
|
+
Notice,
|
|
42
|
+
Select,
|
|
43
|
+
} from "./primitives.js";
|
|
44
|
+
import { Pagination } from "./application.js";
|
|
45
|
+
import { SortArrows } from "./icons.js";
|
|
46
|
+
import type { HeadingLevel } from "./heading.js";
|
|
47
|
+
import { componentRoot, cx } from "./internal.js";
|
|
48
|
+
import {
|
|
49
|
+
columnAlign,
|
|
50
|
+
compareValues,
|
|
51
|
+
isEmpty,
|
|
52
|
+
SelectAll,
|
|
53
|
+
type DataTableColumn,
|
|
54
|
+
type SortDirection,
|
|
55
|
+
type TableSort,
|
|
56
|
+
} from "./table-core.js";
|
|
57
|
+
|
|
58
|
+
type SortValue = string | number | Date | null | undefined;
|
|
59
|
+
|
|
60
|
+
export interface DataGridColumn<T> extends Omit<DataTableColumn<T>, "pin"> {
|
|
61
|
+
/** Keep the column in view while the grid scrolls sideways. */
|
|
62
|
+
pin?: "start" | "end";
|
|
63
|
+
/**
|
|
64
|
+
* Adds a filter control to the toolbar. `text` matches part of the value,
|
|
65
|
+
* ignoring case; `options` offers an exact-match choice.
|
|
66
|
+
*/
|
|
67
|
+
filter?: "text" | { options: { value: string; label: string }[] };
|
|
68
|
+
/** The value filters and search compare. Defaults to sortValue, then row[key]. */
|
|
69
|
+
filterValue?: (row: T) => string | number | null | undefined;
|
|
70
|
+
/** Whether people can hide the column from the Columns menu. Default true; the first column always shows. */
|
|
71
|
+
hideable?: boolean;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** Column key to filter value. A missing or empty value means no filter. */
|
|
75
|
+
export type DataGridFilters = Record<string, string>;
|
|
76
|
+
|
|
77
|
+
export interface DataGridPagination {
|
|
78
|
+
/** One-based page number. */
|
|
79
|
+
page: number;
|
|
80
|
+
pageSize: number;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface DataGridProps<T extends { id: string }> {
|
|
84
|
+
caption: string;
|
|
85
|
+
columns: DataGridColumn<T>[];
|
|
86
|
+
/** Every row in client mode; the current page in server mode. */
|
|
87
|
+
rows: T[];
|
|
88
|
+
rowLabel: (row: T) => string;
|
|
89
|
+
/**
|
|
90
|
+
* `client` sorts, filters, searches and pages rows in the browser. `server`
|
|
91
|
+
* only reports state changes: pass the matching page of rows and rowCount.
|
|
92
|
+
*/
|
|
93
|
+
mode?: "client" | "server";
|
|
94
|
+
/** Total matching rows. Required in server mode. */
|
|
95
|
+
rowCount?: number;
|
|
96
|
+
/** Controlled sort levels, the first sorting first. Shift-click a header to add a level. */
|
|
97
|
+
sort?: TableSort[];
|
|
98
|
+
defaultSort?: TableSort[];
|
|
99
|
+
onSortChange?: (sort: TableSort[]) => void;
|
|
100
|
+
filters?: DataGridFilters;
|
|
101
|
+
defaultFilters?: DataGridFilters;
|
|
102
|
+
onFiltersChange?: (filters: DataGridFilters) => void;
|
|
103
|
+
/** Show a search field that matches any column's filter value. */
|
|
104
|
+
searchable?: boolean;
|
|
105
|
+
/** Controlled search text. */
|
|
106
|
+
search?: string;
|
|
107
|
+
defaultSearch?: string;
|
|
108
|
+
onSearchChange?: (search: string) => void;
|
|
109
|
+
/** Selected row ids, which may include rows that are not loaded. */
|
|
110
|
+
selectedIds?: string[];
|
|
111
|
+
onSelectionChange?: (ids: string[]) => void;
|
|
112
|
+
/** Keys of hidden columns. */
|
|
113
|
+
hiddenColumns?: string[];
|
|
114
|
+
defaultHiddenColumns?: string[];
|
|
115
|
+
onHiddenColumnsChange?: (keys: string[]) => void;
|
|
116
|
+
/** Pages rows when set; without it every row renders (pair large sets with virtualize). */
|
|
117
|
+
pagination?: DataGridPagination;
|
|
118
|
+
defaultPagination?: DataGridPagination;
|
|
119
|
+
onPaginationChange?: (pagination: DataGridPagination) => void;
|
|
120
|
+
/** Render only the rows in view. Needs maxHeight (default 32rem when virtualizing). */
|
|
121
|
+
virtualize?: boolean;
|
|
122
|
+
/** Row height in pixels used for virtualization until a row is measured. Default 44. */
|
|
123
|
+
estimateRowHeight?: number;
|
|
124
|
+
/** Link each row's first cell to a detail page. */
|
|
125
|
+
rowHref?: (row: T) => string | undefined;
|
|
126
|
+
maxHeight?: string;
|
|
127
|
+
density?: "default" | "compact";
|
|
128
|
+
striped?: boolean;
|
|
129
|
+
/** Extra toolbar content, after the built-in search and filters. */
|
|
130
|
+
toolbar?: ReactNode;
|
|
131
|
+
bulkActions?: ReactNode;
|
|
132
|
+
footer?: ReactNode;
|
|
133
|
+
empty?: { title: string; description?: string; action?: ReactNode };
|
|
134
|
+
/** Shown when rows exist but search or filters match none. */
|
|
135
|
+
noResults?: { title: string; description?: string };
|
|
136
|
+
headingLevel?: HeadingLevel;
|
|
137
|
+
loading?: boolean;
|
|
138
|
+
error?: string;
|
|
139
|
+
/** Plural noun for counts, e.g. "invoices". Default "rows". */
|
|
140
|
+
noun?: string;
|
|
141
|
+
id?: string;
|
|
142
|
+
className?: string;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const features = tableFeatures({
|
|
146
|
+
columnFilteringFeature,
|
|
147
|
+
globalFilteringFeature,
|
|
148
|
+
filteredRowModel: createFilteredRowModel(),
|
|
149
|
+
rowSortingFeature,
|
|
150
|
+
sortedRowModel: createSortedRowModel(),
|
|
151
|
+
rowPaginationFeature,
|
|
152
|
+
paginatedRowModel: createPaginatedRowModel(),
|
|
153
|
+
rowSelectionFeature,
|
|
154
|
+
columnVisibilityFeature,
|
|
155
|
+
columnPinningFeature,
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
/** Controlled when value is defined, otherwise local state seeded from initial. */
|
|
159
|
+
function useControllable<V>(
|
|
160
|
+
value: V | undefined,
|
|
161
|
+
initial: V,
|
|
162
|
+
onChange?: (next: V) => void,
|
|
163
|
+
) {
|
|
164
|
+
const [local, setLocal] = useState(initial);
|
|
165
|
+
const current = value !== undefined ? value : local;
|
|
166
|
+
const set = (next: V) => {
|
|
167
|
+
if (value === undefined) setLocal(next);
|
|
168
|
+
onChange?.(next);
|
|
169
|
+
};
|
|
170
|
+
return [current, set] as const;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const resolve = <V,>(updater: Updater<V>, old: V) =>
|
|
174
|
+
typeof updater === "function" ? (updater as (old: V) => V)(old) : updater;
|
|
175
|
+
|
|
176
|
+
function sortValueOf<T>(col: DataGridColumn<T>, row: T): SortValue {
|
|
177
|
+
return col.sortValue
|
|
178
|
+
? col.sortValue(row)
|
|
179
|
+
: ((row as Record<string, unknown>)[col.key] as SortValue);
|
|
180
|
+
}
|
|
181
|
+
function filterValueOf<T>(col: DataGridColumn<T>, row: T) {
|
|
182
|
+
const value = col.filterValue ? col.filterValue(row) : sortValueOf(col, row);
|
|
183
|
+
if (isEmpty(value)) return "";
|
|
184
|
+
return value instanceof Date ? value.toISOString() : String(value);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const matches = (value: string, query: string) =>
|
|
188
|
+
value.toLocaleLowerCase().includes(query.trim().toLocaleLowerCase());
|
|
189
|
+
|
|
190
|
+
// A stable default: a new [] each render would rebuild the selection set and
|
|
191
|
+
// recount select-all over every row on every render.
|
|
192
|
+
const NO_IDS: string[] = [];
|
|
193
|
+
|
|
194
|
+
// Stable table options: functions recreated each render would invalidate
|
|
195
|
+
// TanStack's row-model caches.
|
|
196
|
+
const getRowId = (row: { id: string }) => row.id;
|
|
197
|
+
const isMultiSortEvent = (e: unknown) =>
|
|
198
|
+
!!(e as { shiftKey?: boolean })?.shiftKey;
|
|
199
|
+
const globalFilterFn = (
|
|
200
|
+
row: { getValue: (columnId: string) => unknown },
|
|
201
|
+
columnId: string,
|
|
202
|
+
value: string,
|
|
203
|
+
) => matches(String(row.getValue(columnId) ?? ""), value);
|
|
204
|
+
|
|
205
|
+
export function DataGrid<T extends { id: string }>({
|
|
206
|
+
caption,
|
|
207
|
+
columns,
|
|
208
|
+
rows,
|
|
209
|
+
rowLabel,
|
|
210
|
+
mode = "client",
|
|
211
|
+
rowCount,
|
|
212
|
+
sort: sortProp,
|
|
213
|
+
defaultSort = [],
|
|
214
|
+
onSortChange,
|
|
215
|
+
filters: filtersProp,
|
|
216
|
+
defaultFilters = {},
|
|
217
|
+
onFiltersChange,
|
|
218
|
+
searchable = false,
|
|
219
|
+
search: searchProp,
|
|
220
|
+
defaultSearch = "",
|
|
221
|
+
onSearchChange,
|
|
222
|
+
selectedIds: selectedIdsProp,
|
|
223
|
+
onSelectionChange,
|
|
224
|
+
hiddenColumns: hiddenProp,
|
|
225
|
+
defaultHiddenColumns = [],
|
|
226
|
+
onHiddenColumnsChange,
|
|
227
|
+
pagination: paginationProp,
|
|
228
|
+
defaultPagination,
|
|
229
|
+
onPaginationChange,
|
|
230
|
+
virtualize = false,
|
|
231
|
+
estimateRowHeight = 44,
|
|
232
|
+
rowHref,
|
|
233
|
+
maxHeight = virtualize ? "32rem" : undefined,
|
|
234
|
+
density = "default",
|
|
235
|
+
striped = false,
|
|
236
|
+
toolbar,
|
|
237
|
+
bulkActions,
|
|
238
|
+
footer,
|
|
239
|
+
empty = {
|
|
240
|
+
title: "No records",
|
|
241
|
+
description: "Records will appear here when they are available.",
|
|
242
|
+
},
|
|
243
|
+
noResults = {
|
|
244
|
+
title: "No matching records",
|
|
245
|
+
description: "Try a different search or clear the filters.",
|
|
246
|
+
},
|
|
247
|
+
headingLevel = 3,
|
|
248
|
+
loading,
|
|
249
|
+
error,
|
|
250
|
+
noun = "rows",
|
|
251
|
+
id,
|
|
252
|
+
className,
|
|
253
|
+
}: DataGridProps<T>) {
|
|
254
|
+
const server = mode === "server";
|
|
255
|
+
const selectedIds = selectedIdsProp ?? NO_IDS;
|
|
256
|
+
const [sort, setSort] = useControllable(sortProp, defaultSort, onSortChange);
|
|
257
|
+
const [filters, setFilters] = useControllable(
|
|
258
|
+
filtersProp,
|
|
259
|
+
defaultFilters,
|
|
260
|
+
onFiltersChange,
|
|
261
|
+
);
|
|
262
|
+
const [search, setSearch] = useControllable(
|
|
263
|
+
searchProp,
|
|
264
|
+
defaultSearch,
|
|
265
|
+
onSearchChange,
|
|
266
|
+
);
|
|
267
|
+
const [hidden, setHidden] = useControllable(
|
|
268
|
+
hiddenProp,
|
|
269
|
+
defaultHiddenColumns,
|
|
270
|
+
onHiddenColumnsChange,
|
|
271
|
+
);
|
|
272
|
+
const [paging, setPaging] = useControllable(
|
|
273
|
+
paginationProp,
|
|
274
|
+
defaultPagination,
|
|
275
|
+
onPaginationChange as (p: DataGridPagination | undefined) => void,
|
|
276
|
+
);
|
|
277
|
+
|
|
278
|
+
// TanStack state derived from Mortar's public state. Each slice is memoised on
|
|
279
|
+
// its value: a new object every render would make TanStack re-sort and
|
|
280
|
+
// re-filter every row on every render, including each scroll frame.
|
|
281
|
+
const sortKey = JSON.stringify(sort);
|
|
282
|
+
const sorting = useMemo<SortingState>(
|
|
283
|
+
() => sort.map((s) => ({ id: s.key, desc: s.direction === "descending" })),
|
|
284
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
285
|
+
[sortKey],
|
|
286
|
+
);
|
|
287
|
+
const filtersKey = JSON.stringify(filters);
|
|
288
|
+
const columnFilters = useMemo<ColumnFiltersState>(
|
|
289
|
+
() =>
|
|
290
|
+
Object.entries(filters)
|
|
291
|
+
.filter(([, value]) => !isEmpty(value))
|
|
292
|
+
.map(([key, value]) => ({ id: key, value })),
|
|
293
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
294
|
+
[filtersKey],
|
|
295
|
+
);
|
|
296
|
+
const selected = useMemo(() => new Set(selectedIds), [selectedIds]);
|
|
297
|
+
const rowSelection = useMemo<RowSelectionState>(
|
|
298
|
+
() => Object.fromEntries(selectedIds.map((rowId) => [rowId, true])),
|
|
299
|
+
[selectedIds],
|
|
300
|
+
);
|
|
301
|
+
const hiddenKey = hidden.join(",");
|
|
302
|
+
const columnVisibility = useMemo(
|
|
303
|
+
() =>
|
|
304
|
+
Object.fromEntries(
|
|
305
|
+
columns.map((col, index) => [
|
|
306
|
+
col.key,
|
|
307
|
+
index === 0 || !hidden.includes(col.key),
|
|
308
|
+
]),
|
|
309
|
+
),
|
|
310
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
311
|
+
[columns, hiddenKey],
|
|
312
|
+
);
|
|
313
|
+
const columnPinning = useMemo(
|
|
314
|
+
() => ({
|
|
315
|
+
start: columns.filter((c) => c.pin === "start").map((c) => c.key),
|
|
316
|
+
end: columns.filter((c) => c.pin === "end").map((c) => c.key),
|
|
317
|
+
}),
|
|
318
|
+
[columns],
|
|
319
|
+
);
|
|
320
|
+
const pageIndex = paging ? Math.max(0, paging.page - 1) : 0;
|
|
321
|
+
const pageSize = paging ? paging.pageSize : Number.MAX_SAFE_INTEGER;
|
|
322
|
+
const pagination = useMemo<PaginationState>(
|
|
323
|
+
() => ({ pageIndex, pageSize }),
|
|
324
|
+
[pageIndex, pageSize],
|
|
325
|
+
);
|
|
326
|
+
|
|
327
|
+
const defs = useMemo<ColumnDef<typeof features, T>[]>(
|
|
328
|
+
() =>
|
|
329
|
+
columns.map((col) => ({
|
|
330
|
+
id: col.key,
|
|
331
|
+
// Empty values read as undefined, so sortUndefined puts them last in
|
|
332
|
+
// both directions, as DataTable does. Filters treat them as "".
|
|
333
|
+
accessorFn: (row: T) => filterValueOf(col, row) || undefined,
|
|
334
|
+
enableSorting: !!col.sortable,
|
|
335
|
+
enableColumnFilter: !!col.filter,
|
|
336
|
+
enableHiding: col.hideable !== false,
|
|
337
|
+
// Ascending only; TanStack reverses for descending. Rows whose value
|
|
338
|
+
// is empty never reach here: sortUndefined handles them.
|
|
339
|
+
sortFn: (a, b) =>
|
|
340
|
+
compareValues(
|
|
341
|
+
sortValueOf(col, a.original),
|
|
342
|
+
sortValueOf(col, b.original),
|
|
343
|
+
),
|
|
344
|
+
sortUndefined: "last",
|
|
345
|
+
filterFn: (row, columnId, value: string) => {
|
|
346
|
+
const cell = String(row.getValue(columnId) ?? "");
|
|
347
|
+
return typeof col.filter === "object"
|
|
348
|
+
? cell === value
|
|
349
|
+
: matches(cell, value);
|
|
350
|
+
},
|
|
351
|
+
})),
|
|
352
|
+
[columns],
|
|
353
|
+
);
|
|
354
|
+
|
|
355
|
+
const table = useTable({
|
|
356
|
+
features,
|
|
357
|
+
columns: defs,
|
|
358
|
+
data: rows,
|
|
359
|
+
getRowId,
|
|
360
|
+
state: {
|
|
361
|
+
sorting,
|
|
362
|
+
columnFilters,
|
|
363
|
+
globalFilter: search,
|
|
364
|
+
rowSelection,
|
|
365
|
+
columnVisibility,
|
|
366
|
+
columnPinning,
|
|
367
|
+
pagination,
|
|
368
|
+
},
|
|
369
|
+
manualSorting: server,
|
|
370
|
+
manualFiltering: server,
|
|
371
|
+
manualPagination: server || !paging,
|
|
372
|
+
rowCount: server ? rowCount : undefined,
|
|
373
|
+
enableMultiSort: true,
|
|
374
|
+
isMultiSortEvent,
|
|
375
|
+
enableSortingRemoval: true,
|
|
376
|
+
autoResetPageIndex: false,
|
|
377
|
+
globalFilterFn,
|
|
378
|
+
onSortingChange: (u) =>
|
|
379
|
+
setSort(
|
|
380
|
+
resolve(u, sorting).map((s) => ({
|
|
381
|
+
key: s.id,
|
|
382
|
+
direction: (s.desc ? "descending" : "ascending") as SortDirection,
|
|
383
|
+
})),
|
|
384
|
+
),
|
|
385
|
+
onColumnFiltersChange: (u) =>
|
|
386
|
+
setFilters(
|
|
387
|
+
Object.fromEntries(
|
|
388
|
+
resolve(u, columnFilters).map((f) => [f.id, String(f.value)]),
|
|
389
|
+
),
|
|
390
|
+
),
|
|
391
|
+
onGlobalFilterChange: (u) => setSearch(String(resolve(u, search) ?? "")),
|
|
392
|
+
onRowSelectionChange: (u) => {
|
|
393
|
+
const next = resolve(u, rowSelection);
|
|
394
|
+
onSelectionChange?.(Object.keys(next).filter((key) => next[key]));
|
|
395
|
+
},
|
|
396
|
+
onColumnVisibilityChange: (u) => {
|
|
397
|
+
const next = resolve(u, columnVisibility);
|
|
398
|
+
setHidden(columns.filter((c) => !next[c.key]).map((c) => c.key));
|
|
399
|
+
},
|
|
400
|
+
onPaginationChange: (u) => {
|
|
401
|
+
if (!paging) return;
|
|
402
|
+
const next = resolve(u, pagination);
|
|
403
|
+
setPaging({ page: next.pageIndex + 1, pageSize: next.pageSize });
|
|
404
|
+
},
|
|
405
|
+
});
|
|
406
|
+
|
|
407
|
+
// Filtering or searching moves back to the first page.
|
|
408
|
+
const resetPage = () => paging && setPaging({ ...paging, page: 1 });
|
|
409
|
+
|
|
410
|
+
const visibleColumns = columns.filter((c) => columnVisibility[c.key]);
|
|
411
|
+
const ordered = [
|
|
412
|
+
...visibleColumns.filter((c) => c.pin === "start"),
|
|
413
|
+
...visibleColumns.filter((c) => !c.pin),
|
|
414
|
+
...visibleColumns.filter((c) => c.pin === "end"),
|
|
415
|
+
];
|
|
416
|
+
const matchingCount = server
|
|
417
|
+
? (rowCount ?? rows.length)
|
|
418
|
+
: table.getFilteredRowModel().rows.length;
|
|
419
|
+
// A page past the end (rows removed, or a stale controlled page) shows the
|
|
420
|
+
// last page; the effect below reports the corrected page.
|
|
421
|
+
const pageCount = paging
|
|
422
|
+
? Math.max(1, Math.ceil(matchingCount / paging.pageSize))
|
|
423
|
+
: 1;
|
|
424
|
+
const page = paging ? Math.min(Math.max(1, paging.page), pageCount) : 1;
|
|
425
|
+
const sortedRows = table.getSortedRowModel().rows;
|
|
426
|
+
const displayRows =
|
|
427
|
+
paging && !server
|
|
428
|
+
? sortedRows.slice((page - 1) * paging.pageSize, page * paging.pageSize)
|
|
429
|
+
: table.getRowModel().rows;
|
|
430
|
+
useLayoutEffect(() => {
|
|
431
|
+
if (paging && paging.page !== page && matchingCount > 0)
|
|
432
|
+
setPaging({ ...paging, page });
|
|
433
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
434
|
+
}, [page, paging?.page, matchingCount]);
|
|
435
|
+
const filtering = columnFilters.length > 0 || !isEmpty(search.trim());
|
|
436
|
+
|
|
437
|
+
// Select all covers every matching row in client mode, and the loaded page in
|
|
438
|
+
// server mode; selections elsewhere are kept.
|
|
439
|
+
const scopeRows = server ? displayRows : table.getFilteredRowModel().rows;
|
|
440
|
+
const scopeIds = useMemo(() => scopeRows.map((row) => row.id), [scopeRows]);
|
|
441
|
+
// Counted once per selection or result change, not on every scroll frame.
|
|
442
|
+
const selectedInScope = useMemo(
|
|
443
|
+
() => scopeIds.reduce((n, rowId) => n + (selected.has(rowId) ? 1 : 0), 0),
|
|
444
|
+
[scopeIds, selected],
|
|
445
|
+
);
|
|
446
|
+
const allInScope = scopeIds.length > 0 && selectedInScope === scopeIds.length;
|
|
447
|
+
const scopeSet = useMemo(() => new Set(scopeIds), [scopeIds]);
|
|
448
|
+
const toggleAll = () =>
|
|
449
|
+
onSelectionChange?.(
|
|
450
|
+
allInScope
|
|
451
|
+
? selectedIds.filter((rowId) => !scopeSet.has(rowId))
|
|
452
|
+
: [...selectedIds, ...scopeIds.filter((rowId) => !selected.has(rowId))],
|
|
453
|
+
);
|
|
454
|
+
|
|
455
|
+
// Sticky offsets for pinned columns come from the rendered header widths.
|
|
456
|
+
// A callback ref, so the effect re-runs when the table remounts after an
|
|
457
|
+
// empty or loading state.
|
|
458
|
+
const [headerRow, setHeaderRow] = useState<HTMLTableRowElement | null>(null);
|
|
459
|
+
const [offsets, setOffsets] = useState<Record<string, number>>({});
|
|
460
|
+
const pinKey = ordered
|
|
461
|
+
.filter((c) => c.pin)
|
|
462
|
+
.map((c) => `${c.key}:${c.pin}`)
|
|
463
|
+
.join(",");
|
|
464
|
+
useLayoutEffect(() => {
|
|
465
|
+
const tr = headerRow;
|
|
466
|
+
if (!tr || !pinKey) return;
|
|
467
|
+
const measure = () => {
|
|
468
|
+
if (!tr.isConnected) return;
|
|
469
|
+
const cells = [...tr.children] as HTMLElement[];
|
|
470
|
+
const next: Record<string, number> = {};
|
|
471
|
+
let start = 0;
|
|
472
|
+
for (const cell of cells) {
|
|
473
|
+
const key = cell.dataset.key;
|
|
474
|
+
const pin = cell.dataset.pin;
|
|
475
|
+
if (pin === "start" || cell.dataset.select !== undefined) {
|
|
476
|
+
if (key) next[key] = start;
|
|
477
|
+
start += cell.offsetWidth;
|
|
478
|
+
} else break;
|
|
479
|
+
}
|
|
480
|
+
let end = 0;
|
|
481
|
+
for (const cell of cells.reverse()) {
|
|
482
|
+
if (cell.dataset.pin !== "end") break;
|
|
483
|
+
next[cell.dataset.key!] = end;
|
|
484
|
+
end += cell.offsetWidth;
|
|
485
|
+
}
|
|
486
|
+
setOffsets((old) =>
|
|
487
|
+
JSON.stringify(old) === JSON.stringify(next) ? old : next,
|
|
488
|
+
);
|
|
489
|
+
};
|
|
490
|
+
measure();
|
|
491
|
+
// Column widths can change while the row's width stays the same (new
|
|
492
|
+
// data, a new virtual window), so watch the pinned cells themselves.
|
|
493
|
+
const observer = new ResizeObserver(measure);
|
|
494
|
+
observer.observe(tr);
|
|
495
|
+
for (const cell of tr.querySelectorAll("[data-pin], [data-select]"))
|
|
496
|
+
observer.observe(cell);
|
|
497
|
+
return () => observer.disconnect();
|
|
498
|
+
}, [headerRow, pinKey, hidden.join(",")]);
|
|
499
|
+
|
|
500
|
+
// Row virtualization: only the rows in view render, with spacer rows keeping
|
|
501
|
+
// the scroll height. Rows keep aria-rowindex so assistive tech knows the size.
|
|
502
|
+
// Rows share one height, so one rendered row is measured and its height used
|
|
503
|
+
// for all of them. Measuring each row as it scrolls in would make the
|
|
504
|
+
// virtualizer recompute every later row's position on each frame.
|
|
505
|
+
const scrollRef = useRef<HTMLDivElement>(null);
|
|
506
|
+
const [rowHeight, setRowHeight] = useState(estimateRowHeight);
|
|
507
|
+
const getScrollElement = useCallback(() => scrollRef.current, []);
|
|
508
|
+
const estimateSize = useCallback(() => rowHeight, [rowHeight]);
|
|
509
|
+
const virtualizer = useVirtualizer({
|
|
510
|
+
count: virtualize ? displayRows.length : 0,
|
|
511
|
+
getScrollElement,
|
|
512
|
+
estimateSize,
|
|
513
|
+
overscan: 8,
|
|
514
|
+
});
|
|
515
|
+
const items = virtualize ? virtualizer.getVirtualItems() : [];
|
|
516
|
+
useLayoutEffect(() => {
|
|
517
|
+
if (!virtualize) return;
|
|
518
|
+
const row = scrollRef.current?.querySelector<HTMLElement>(
|
|
519
|
+
"tbody tr:not(.m-data-grid-spacer)",
|
|
520
|
+
);
|
|
521
|
+
const height = row?.getBoundingClientRect().height;
|
|
522
|
+
if (height && Math.abs(height - rowHeight) > 0.5) setRowHeight(height);
|
|
523
|
+
// A new estimateSize alone does not rebuild the cached row positions.
|
|
524
|
+
virtualizer.measure();
|
|
525
|
+
// Only when row height can change: not on every scroll frame, where a
|
|
526
|
+
// measurement would force a synchronous layout.
|
|
527
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
528
|
+
}, [
|
|
529
|
+
virtualize,
|
|
530
|
+
density,
|
|
531
|
+
hiddenKey,
|
|
532
|
+
// The first virtual rows appear a render after mount, once the virtualizer
|
|
533
|
+
// has its scroll element: measure then.
|
|
534
|
+
items.length > 0,
|
|
535
|
+
loading,
|
|
536
|
+
rowHeight,
|
|
537
|
+
]);
|
|
538
|
+
const windowRows = virtualize
|
|
539
|
+
? items.map((item) => ({ row: displayRows[item.index], index: item.index }))
|
|
540
|
+
: displayRows.map((row, index) => ({ row, index }));
|
|
541
|
+
const padTop = virtualize && items.length ? items[0].start : 0;
|
|
542
|
+
const padBottom =
|
|
543
|
+
virtualize && items.length
|
|
544
|
+
? virtualizer.getTotalSize() - items[items.length - 1].end
|
|
545
|
+
: 0;
|
|
546
|
+
const rowOffset = paging ? (page - 1) * paging.pageSize : 0;
|
|
547
|
+
const span = ordered.length + (onSelectionChange ? 1 : 0);
|
|
548
|
+
|
|
549
|
+
const pinStyle = (col: DataGridColumn<T>) =>
|
|
550
|
+
col.pin && offsets[col.key] !== undefined
|
|
551
|
+
? col.pin === "start"
|
|
552
|
+
? { insetInlineStart: offsets[col.key] }
|
|
553
|
+
: { insetInlineEnd: offsets[col.key] }
|
|
554
|
+
: undefined;
|
|
555
|
+
const cellProps = (col: DataGridColumn<T>, index: number) => ({
|
|
556
|
+
"data-key": col.key,
|
|
557
|
+
"data-pin": col.pin,
|
|
558
|
+
"data-priority":
|
|
559
|
+
index > 0 && col.priority && col.priority !== "high"
|
|
560
|
+
? col.priority
|
|
561
|
+
: undefined,
|
|
562
|
+
"data-align": columnAlign(col.align),
|
|
563
|
+
"data-truncate": col.truncate || undefined,
|
|
564
|
+
style: pinStyle(col),
|
|
565
|
+
});
|
|
566
|
+
|
|
567
|
+
const filterColumns = columns.filter((col) => col.filter);
|
|
568
|
+
const hideable = columns.filter(
|
|
569
|
+
(col, index) => index > 0 && col.hideable !== false,
|
|
570
|
+
);
|
|
571
|
+
const hasToolbarControls =
|
|
572
|
+
searchable || filterColumns.length > 0 || hideable.length > 0;
|
|
573
|
+
const sortIndex = (key: string) => sort.findIndex((s) => s.key === key);
|
|
574
|
+
|
|
575
|
+
return (
|
|
576
|
+
<section
|
|
577
|
+
id={id}
|
|
578
|
+
{...componentRoot("DataGrid")}
|
|
579
|
+
className={cx("m-data-table", "m-data-grid", className)}
|
|
580
|
+
aria-label={caption}
|
|
581
|
+
data-density={density === "default" ? undefined : density}
|
|
582
|
+
data-striped={striped || undefined}
|
|
583
|
+
>
|
|
584
|
+
{(hasToolbarControls || toolbar || selectedIds.length > 0) && (
|
|
585
|
+
<div className="m-table-toolbar">
|
|
586
|
+
{selectedIds.length > 0 ? (
|
|
587
|
+
<>
|
|
588
|
+
<strong>{selectedIds.length} selected</strong>
|
|
589
|
+
<div className="m-actions">
|
|
590
|
+
{bulkActions}
|
|
591
|
+
<Button variant="ghost" onClick={() => onSelectionChange?.([])}>
|
|
592
|
+
Clear selection
|
|
593
|
+
</Button>
|
|
594
|
+
</div>
|
|
595
|
+
</>
|
|
596
|
+
) : (
|
|
597
|
+
<>
|
|
598
|
+
<div className="m-data-grid-controls">
|
|
599
|
+
{searchable && (
|
|
600
|
+
<Input
|
|
601
|
+
label="Search"
|
|
602
|
+
type="search"
|
|
603
|
+
value={search}
|
|
604
|
+
onChange={(event) => {
|
|
605
|
+
table.setGlobalFilter(event.target.value);
|
|
606
|
+
resetPage();
|
|
607
|
+
}}
|
|
608
|
+
/>
|
|
609
|
+
)}
|
|
610
|
+
{filterColumns.map((col) => {
|
|
611
|
+
const value = filters[col.key] ?? "";
|
|
612
|
+
const setValue = (next: string) => {
|
|
613
|
+
table.getColumn(col.key)?.setFilterValue(next || undefined);
|
|
614
|
+
resetPage();
|
|
615
|
+
};
|
|
616
|
+
return typeof col.filter === "object" ? (
|
|
617
|
+
<Select
|
|
618
|
+
key={col.key}
|
|
619
|
+
label={col.label}
|
|
620
|
+
value={value}
|
|
621
|
+
options={[
|
|
622
|
+
{ value: "", label: "All" },
|
|
623
|
+
...col.filter.options,
|
|
624
|
+
]}
|
|
625
|
+
onChange={(event) => setValue(event.target.value)}
|
|
626
|
+
/>
|
|
627
|
+
) : (
|
|
628
|
+
<Input
|
|
629
|
+
key={col.key}
|
|
630
|
+
label={col.label}
|
|
631
|
+
value={value}
|
|
632
|
+
onChange={(event) => setValue(event.target.value)}
|
|
633
|
+
/>
|
|
634
|
+
);
|
|
635
|
+
})}
|
|
636
|
+
{toolbar}
|
|
637
|
+
</div>
|
|
638
|
+
{hideable.length > 0 && (
|
|
639
|
+
<Popover className="m-data-grid-columns">
|
|
640
|
+
<PopoverButton as={Button} variant="secondary">
|
|
641
|
+
Columns
|
|
642
|
+
</PopoverButton>
|
|
643
|
+
<PopoverPanel
|
|
644
|
+
anchor="bottom end"
|
|
645
|
+
className="m-data-grid-columns-panel"
|
|
646
|
+
>
|
|
647
|
+
<fieldset>
|
|
648
|
+
<legend>Show columns</legend>
|
|
649
|
+
{hideable.map((col) => (
|
|
650
|
+
<Checkbox
|
|
651
|
+
key={col.key}
|
|
652
|
+
label={col.label}
|
|
653
|
+
checked={!hidden.includes(col.key)}
|
|
654
|
+
onChange={() =>
|
|
655
|
+
setHidden(
|
|
656
|
+
hidden.includes(col.key)
|
|
657
|
+
? hidden.filter((key) => key !== col.key)
|
|
658
|
+
: [...hidden, col.key],
|
|
659
|
+
)
|
|
660
|
+
}
|
|
661
|
+
/>
|
|
662
|
+
))}
|
|
663
|
+
</fieldset>
|
|
664
|
+
</PopoverPanel>
|
|
665
|
+
</Popover>
|
|
666
|
+
)}
|
|
667
|
+
</>
|
|
668
|
+
)}
|
|
669
|
+
</div>
|
|
670
|
+
)}
|
|
671
|
+
{/* Mounted before loading starts so screen readers announce the change. */}
|
|
672
|
+
<p
|
|
673
|
+
className={loading ? "m-table-state" : "m-sr-only"}
|
|
674
|
+
role="status"
|
|
675
|
+
data-loading={loading || undefined}
|
|
676
|
+
>
|
|
677
|
+
{loading
|
|
678
|
+
? "Loading records…"
|
|
679
|
+
: filtering
|
|
680
|
+
? `${matchingCount} matching ${noun}`
|
|
681
|
+
: ""}
|
|
682
|
+
</p>
|
|
683
|
+
{loading ? null : error ? (
|
|
684
|
+
<Notice title="Unable to load records" tone="danger" announce>
|
|
685
|
+
{error}
|
|
686
|
+
</Notice>
|
|
687
|
+
) : !rows.length && !filtering ? (
|
|
688
|
+
<EmptyState
|
|
689
|
+
title={empty.title}
|
|
690
|
+
description={empty.description}
|
|
691
|
+
action={empty.action}
|
|
692
|
+
headingLevel={headingLevel}
|
|
693
|
+
/>
|
|
694
|
+
) : !displayRows.length ? (
|
|
695
|
+
<EmptyState
|
|
696
|
+
title={noResults.title}
|
|
697
|
+
description={noResults.description}
|
|
698
|
+
headingLevel={headingLevel}
|
|
699
|
+
action={
|
|
700
|
+
<Button
|
|
701
|
+
variant="secondary"
|
|
702
|
+
onClick={() => {
|
|
703
|
+
table.resetColumnFilters(true);
|
|
704
|
+
table.resetGlobalFilter(true);
|
|
705
|
+
setFilters({});
|
|
706
|
+
setSearch("");
|
|
707
|
+
resetPage();
|
|
708
|
+
}}
|
|
709
|
+
>
|
|
710
|
+
Clear filters
|
|
711
|
+
</Button>
|
|
712
|
+
}
|
|
713
|
+
/>
|
|
714
|
+
) : (
|
|
715
|
+
<div
|
|
716
|
+
ref={scrollRef}
|
|
717
|
+
className="m-table-scroll"
|
|
718
|
+
role="region"
|
|
719
|
+
aria-label={`${caption} scroll area`}
|
|
720
|
+
tabIndex={0}
|
|
721
|
+
style={maxHeight ? { maxHeight } : undefined}
|
|
722
|
+
data-sticky={maxHeight ? true : undefined}
|
|
723
|
+
>
|
|
724
|
+
<table aria-rowcount={virtualize ? matchingCount + 1 : undefined}>
|
|
725
|
+
<caption className="m-sr-only">{caption}</caption>
|
|
726
|
+
{ordered.some((col) => col.width) && (
|
|
727
|
+
<colgroup>
|
|
728
|
+
{onSelectionChange && <col className="m-table-select-col" />}
|
|
729
|
+
{ordered.map((col) => (
|
|
730
|
+
<col
|
|
731
|
+
key={col.key}
|
|
732
|
+
style={col.width ? { width: col.width } : undefined}
|
|
733
|
+
/>
|
|
734
|
+
))}
|
|
735
|
+
</colgroup>
|
|
736
|
+
)}
|
|
737
|
+
<thead>
|
|
738
|
+
<tr ref={setHeaderRow} aria-rowindex={virtualize ? 1 : undefined}>
|
|
739
|
+
{onSelectionChange && (
|
|
740
|
+
<th
|
|
741
|
+
scope="col"
|
|
742
|
+
data-select=""
|
|
743
|
+
data-pin={columnPinning.start.length ? "start" : undefined}
|
|
744
|
+
style={
|
|
745
|
+
columnPinning.start.length
|
|
746
|
+
? { insetInlineStart: 0 }
|
|
747
|
+
: undefined
|
|
748
|
+
}
|
|
749
|
+
>
|
|
750
|
+
<SelectAll
|
|
751
|
+
checked={allInScope}
|
|
752
|
+
partial={selectedInScope > 0 && !allInScope}
|
|
753
|
+
onChange={toggleAll}
|
|
754
|
+
/>
|
|
755
|
+
</th>
|
|
756
|
+
)}
|
|
757
|
+
{ordered.map((col, index) => {
|
|
758
|
+
const position = sortIndex(col.key);
|
|
759
|
+
const direction =
|
|
760
|
+
position >= 0 ? sort[position].direction : undefined;
|
|
761
|
+
return (
|
|
762
|
+
<th
|
|
763
|
+
key={col.key}
|
|
764
|
+
scope="col"
|
|
765
|
+
{...cellProps(col, index)}
|
|
766
|
+
aria-sort={
|
|
767
|
+
col.sortable
|
|
768
|
+
? position === 0
|
|
769
|
+
? direction
|
|
770
|
+
: "none"
|
|
771
|
+
: undefined
|
|
772
|
+
}
|
|
773
|
+
>
|
|
774
|
+
{col.sortable ? (
|
|
775
|
+
<button
|
|
776
|
+
type="button"
|
|
777
|
+
className="m-sort-button"
|
|
778
|
+
onClick={(event) =>
|
|
779
|
+
table
|
|
780
|
+
.getColumn(col.key)
|
|
781
|
+
?.toggleSorting(
|
|
782
|
+
undefined,
|
|
783
|
+
event.shiftKey && sort.length > 0,
|
|
784
|
+
)
|
|
785
|
+
}
|
|
786
|
+
>
|
|
787
|
+
{col.label}
|
|
788
|
+
<SortArrows direction={direction} />
|
|
789
|
+
{sort.length > 1 && position >= 0 && (
|
|
790
|
+
<span className="m-sort-order">
|
|
791
|
+
<span className="m-sr-only">, sort level </span>
|
|
792
|
+
{position + 1}
|
|
793
|
+
</span>
|
|
794
|
+
)}
|
|
795
|
+
</button>
|
|
796
|
+
) : (
|
|
797
|
+
col.label
|
|
798
|
+
)}
|
|
799
|
+
</th>
|
|
800
|
+
);
|
|
801
|
+
})}
|
|
802
|
+
</tr>
|
|
803
|
+
</thead>
|
|
804
|
+
<tbody>
|
|
805
|
+
{padTop > 0 && (
|
|
806
|
+
<tr aria-hidden="true" className="m-data-grid-spacer">
|
|
807
|
+
<td colSpan={span} style={{ height: padTop }} />
|
|
808
|
+
</tr>
|
|
809
|
+
)}
|
|
810
|
+
{windowRows.map(({ row, index }) => {
|
|
811
|
+
const original = row.original;
|
|
812
|
+
const href = rowHref?.(original);
|
|
813
|
+
const isSelected = selected.has(row.id);
|
|
814
|
+
return (
|
|
815
|
+
<tr
|
|
816
|
+
key={row.id}
|
|
817
|
+
data-selected={isSelected || undefined}
|
|
818
|
+
data-linked={href ? true : undefined}
|
|
819
|
+
aria-rowindex={
|
|
820
|
+
virtualize ? rowOffset + index + 2 : undefined
|
|
821
|
+
}
|
|
822
|
+
>
|
|
823
|
+
{onSelectionChange && (
|
|
824
|
+
<td
|
|
825
|
+
data-select=""
|
|
826
|
+
data-pin={
|
|
827
|
+
columnPinning.start.length ? "start" : undefined
|
|
828
|
+
}
|
|
829
|
+
style={
|
|
830
|
+
columnPinning.start.length
|
|
831
|
+
? { insetInlineStart: 0 }
|
|
832
|
+
: undefined
|
|
833
|
+
}
|
|
834
|
+
>
|
|
835
|
+
<input
|
|
836
|
+
type="checkbox"
|
|
837
|
+
aria-label={`Select ${rowLabel(original)}`}
|
|
838
|
+
checked={isSelected}
|
|
839
|
+
onChange={row.getToggleSelectedHandler()}
|
|
840
|
+
/>
|
|
841
|
+
</td>
|
|
842
|
+
)}
|
|
843
|
+
{ordered.map((col, colIndex) => {
|
|
844
|
+
const content = col.truncate ? (
|
|
845
|
+
<span className="m-truncate">
|
|
846
|
+
{col.render(original)}
|
|
847
|
+
</span>
|
|
848
|
+
) : (
|
|
849
|
+
col.render(original)
|
|
850
|
+
);
|
|
851
|
+
return colIndex === 0 ? (
|
|
852
|
+
<th
|
|
853
|
+
scope="row"
|
|
854
|
+
key={col.key}
|
|
855
|
+
{...cellProps(col, colIndex)}
|
|
856
|
+
>
|
|
857
|
+
{href ? (
|
|
858
|
+
<KitLink className="m-row-link" href={href}>
|
|
859
|
+
{content}
|
|
860
|
+
</KitLink>
|
|
861
|
+
) : (
|
|
862
|
+
content
|
|
863
|
+
)}
|
|
864
|
+
</th>
|
|
865
|
+
) : (
|
|
866
|
+
<td key={col.key} {...cellProps(col, colIndex)}>
|
|
867
|
+
{content}
|
|
868
|
+
</td>
|
|
869
|
+
);
|
|
870
|
+
})}
|
|
871
|
+
</tr>
|
|
872
|
+
);
|
|
873
|
+
})}
|
|
874
|
+
{padBottom > 0 && (
|
|
875
|
+
<tr aria-hidden="true" className="m-data-grid-spacer">
|
|
876
|
+
<td colSpan={span} style={{ height: padBottom }} />
|
|
877
|
+
</tr>
|
|
878
|
+
)}
|
|
879
|
+
</tbody>
|
|
880
|
+
</table>
|
|
881
|
+
</div>
|
|
882
|
+
)}
|
|
883
|
+
{(paging || footer) && !loading && !error && (
|
|
884
|
+
<div className="m-table-footer">
|
|
885
|
+
{paging && matchingCount > 0 && (
|
|
886
|
+
<Pagination
|
|
887
|
+
page={page}
|
|
888
|
+
pageCount={pageCount}
|
|
889
|
+
numbered
|
|
890
|
+
summary={{
|
|
891
|
+
from: Math.min(matchingCount, rowOffset + 1),
|
|
892
|
+
to: Math.min(matchingCount, rowOffset + paging.pageSize),
|
|
893
|
+
total: matchingCount,
|
|
894
|
+
noun,
|
|
895
|
+
}}
|
|
896
|
+
onChange={(page) => setPaging({ ...paging, page })}
|
|
897
|
+
/>
|
|
898
|
+
)}
|
|
899
|
+
{footer}
|
|
900
|
+
</div>
|
|
901
|
+
)}
|
|
902
|
+
</section>
|
|
903
|
+
);
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
export type { TableSort, SortDirection };
|