@reactloom/data-grid 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/README.md +65 -2
  2. package/dist/LICENSE +21 -0
  3. package/dist/_internal/hooks/use-controllable-state.js +24 -0
  4. package/dist/_internal/hooks/use-controllable-state.js.map +1 -0
  5. package/dist/_internal/primitives/visually-hidden.js +29 -0
  6. package/dist/_internal/primitives/visually-hidden.js.map +1 -0
  7. package/dist/_internal/utils/cx.js +10 -0
  8. package/dist/_internal/utils/cx.js.map +1 -0
  9. package/dist/_internal/utils/data-attr.js +8 -0
  10. package/dist/_internal/utils/data-attr.js.map +1 -0
  11. package/dist/_internal/utils/warn.js +13 -0
  12. package/dist/_internal/utils/warn.js.map +1 -0
  13. package/dist/cell-editor.d.ts +26 -0
  14. package/dist/cell-editor.d.ts.map +1 -0
  15. package/dist/cell-editor.js +109 -0
  16. package/dist/cell-editor.js.map +1 -0
  17. package/dist/clipboard.d.ts +10 -0
  18. package/dist/clipboard.d.ts.map +1 -0
  19. package/dist/clipboard.js +54 -0
  20. package/dist/clipboard.js.map +1 -0
  21. package/dist/column-filters.d.ts +4 -0
  22. package/dist/column-filters.d.ts.map +1 -0
  23. package/dist/column-filters.js +30 -0
  24. package/dist/column-filters.js.map +1 -0
  25. package/dist/column-layout.d.ts +18 -0
  26. package/dist/column-layout.d.ts.map +1 -0
  27. package/dist/column-layout.js +59 -0
  28. package/dist/column-layout.js.map +1 -0
  29. package/dist/csv.d.ts +26 -0
  30. package/dist/csv.d.ts.map +1 -0
  31. package/dist/csv.js +60 -0
  32. package/dist/csv.js.map +1 -0
  33. package/dist/data-grid.d.ts +11 -0
  34. package/dist/data-grid.d.ts.map +1 -0
  35. package/dist/data-grid.js +1610 -0
  36. package/dist/data-grid.js.map +1 -0
  37. package/dist/data-grid.module.js +70 -0
  38. package/dist/data-grid.module.js.map +1 -0
  39. package/dist/index.d.ts +6 -0
  40. package/dist/index.d.ts.map +1 -0
  41. package/dist/index.js +6 -0
  42. package/dist/pivot-table.d.ts +26 -0
  43. package/dist/pivot-table.d.ts.map +1 -0
  44. package/dist/pivot-table.js +174 -0
  45. package/dist/pivot-table.js.map +1 -0
  46. package/dist/pivot-table.module.js +30 -0
  47. package/dist/pivot-table.module.js.map +1 -0
  48. package/dist/server.d.ts +34 -0
  49. package/dist/server.d.ts.map +1 -0
  50. package/dist/server.js +97 -0
  51. package/dist/server.js.map +1 -0
  52. package/dist/spreadsheet.d.ts +18 -0
  53. package/dist/spreadsheet.d.ts.map +1 -0
  54. package/dist/spreadsheet.js +329 -0
  55. package/dist/spreadsheet.js.map +1 -0
  56. package/dist/spreadsheet.module.js +30 -0
  57. package/dist/spreadsheet.module.js.map +1 -0
  58. package/dist/styles.css +3 -0
  59. package/dist/tree.d.ts +24 -0
  60. package/dist/tree.d.ts.map +1 -0
  61. package/dist/tree.js +75 -0
  62. package/dist/tree.js.map +1 -0
  63. package/dist/types.d.ts +365 -0
  64. package/dist/types.d.ts.map +1 -0
  65. package/dist/types.js +43 -0
  66. package/dist/types.js.map +1 -0
  67. package/dist/use-grid-navigation.d.ts +36 -0
  68. package/dist/use-grid-navigation.d.ts.map +1 -0
  69. package/dist/use-grid-navigation.js +188 -0
  70. package/dist/use-grid-navigation.js.map +1 -0
  71. package/dist/xlsx.d.ts +12 -0
  72. package/dist/xlsx.d.ts.map +1 -0
  73. package/dist/xlsx.js +57 -0
  74. package/dist/xlsx.js.map +1 -0
  75. package/dist/zip.d.ts +6 -0
  76. package/dist/zip.d.ts.map +1 -0
  77. package/dist/zip.js +54 -0
  78. package/dist/zip.js.map +1 -0
  79. package/package.json +108 -3
@@ -0,0 +1,1610 @@
1
+ "use client";
2
+ import { VisuallyHidden } from "./_internal/primitives/visually-hidden.js";
3
+ import { cx } from "./_internal/utils/cx.js";
4
+ import { dataAttr } from "./_internal/utils/data-attr.js";
5
+ import { warnOnce } from "./_internal/utils/warn.js";
6
+ import { CellEditor } from "./cell-editor.js";
7
+ import { parseTsv, toHtmlTable, toTsv } from "./clipboard.js";
8
+ import { downloadText, toCsv } from "./csv.js";
9
+ import { ancestorsOf, buildTree, visibleTree } from "./tree.js";
10
+ import { defaultLabels } from "./types.js";
11
+ import { useGridNavigation } from "./use-grid-navigation.js";
12
+ import { arrangeColumns, getPinnedOffsets, snapshotColumnLayout } from "./column-layout.js";
13
+ import { isEmpty, matchesColumnFilter } from "./column-filters.js";
14
+ import data_grid_module_default from "./data-grid.module.js";
15
+ import { forwardRef, useCallback, useEffect, useId, useImperativeHandle, useMemo, useRef, useState } from "react";
16
+ import { columnFilteringFeature, columnOrderingFeature, columnResizingFeature, columnSizingFeature, columnVisibilityFeature, createFilteredRowModel, createPaginatedRowModel, createSortedRowModel, filterFn_includesString, globalFilteringFeature, rowPaginationFeature, rowSelectionFeature, rowSortingFeature, tableFeatures, useTable } from "@tanstack/react-table";
17
+ import { useVirtualizer } from "@tanstack/react-virtual";
18
+ import { Checkbox, Pagination, Spinner, useLocale } from "@reactloom/ui";
19
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
20
+ // src/data-grid.tsx
21
+ var features = /*#__PURE__*/ tableFeatures({
22
+ rowSortingFeature,
23
+ sortedRowModel: createSortedRowModel(),
24
+ columnFilteringFeature,
25
+ globalFilteringFeature,
26
+ filteredRowModel: createFilteredRowModel(),
27
+ filterFns: { includesString: filterFn_includesString },
28
+ rowPaginationFeature,
29
+ paginatedRowModel: createPaginatedRowModel(),
30
+ rowSelectionFeature,
31
+ columnOrderingFeature,
32
+ columnVisibilityFeature,
33
+ columnSizingFeature,
34
+ columnResizingFeature
35
+ });
36
+ var SELECT_COL = "__select";
37
+ var DETAIL_COL = "__detail";
38
+ var EMPTY_KEYS = [];
39
+ var isPromise = (value) => Boolean(value && typeof value.then === "function");
40
+ var ROW_HEIGHT = {
41
+ compact: 36,
42
+ comfortable: 44
43
+ };
44
+ var EMPTY_SORTS = [];
45
+ var EMPTY_FILTERS = [];
46
+ var read = (row, key) => row && typeof row === "object" ? row[key] : void 0;
47
+ var apply = (updater, current) => typeof updater === "function" ? updater(current) : updater;
48
+ /** Controlled-or-uncontrolled state without effects. */
49
+ function useMaybeControlled(value, initial, onChange) {
50
+ const [inner, setInner] = useState(initial);
51
+ const controlled = value !== void 0;
52
+ const current = controlled ? value : inner;
53
+ return [current, useCallback((updater) => {
54
+ const next = apply(updater, current);
55
+ if (!controlled) setInner(next);
56
+ onChange?.(next);
57
+ }, [
58
+ controlled,
59
+ current,
60
+ onChange
61
+ ])];
62
+ }
63
+ var SortIcon = ({ direction }) => /* @__PURE__ */ jsxs("svg", {
64
+ className: data_grid_module_default.sortIcon,
65
+ viewBox: "0 0 16 16",
66
+ width: "1em",
67
+ height: "1em",
68
+ "aria-hidden": "true",
69
+ focusable: "false",
70
+ "data-direction": direction || void 0,
71
+ children: [/* @__PURE__ */ jsx("path", {
72
+ d: "M5 6.5 8 3.5l3 3",
73
+ fill: "none",
74
+ stroke: "currentColor",
75
+ strokeWidth: "1.5",
76
+ strokeLinecap: "round",
77
+ strokeLinejoin: "round",
78
+ "data-part": "up"
79
+ }), /* @__PURE__ */ jsx("path", {
80
+ d: "M5 9.5 8 12.5l3-3",
81
+ fill: "none",
82
+ stroke: "currentColor",
83
+ strokeWidth: "1.5",
84
+ strokeLinecap: "round",
85
+ strokeLinejoin: "round",
86
+ "data-part": "down"
87
+ })]
88
+ });
89
+ var ChevronIcon = () => /* @__PURE__ */ jsx("svg", {
90
+ className: data_grid_module_default.groupChevron,
91
+ viewBox: "0 0 16 16",
92
+ width: "1em",
93
+ height: "1em",
94
+ "aria-hidden": "true",
95
+ focusable: "false",
96
+ children: /* @__PURE__ */ jsx("path", {
97
+ d: "M6 4l4 4-4 4",
98
+ fill: "none",
99
+ stroke: "currentColor",
100
+ strokeWidth: "1.5",
101
+ strokeLinecap: "round",
102
+ strokeLinejoin: "round"
103
+ })
104
+ });
105
+ /** Compares two non-empty values: dates and numbers by value, text with the locale's collation. */
106
+ function compareValues(x, y, collator) {
107
+ if (x instanceof Date && y instanceof Date) return x.getTime() - y.getTime();
108
+ if (typeof x === "number" && typeof y === "number") return x - y;
109
+ return collator.compare(String(x), String(y));
110
+ }
111
+ /** Parses a number typed in the user's locale ("1.234,5" in German). Empty → null. */
112
+ function parseLocaleNumber(text, locale) {
113
+ const trimmed = text.trim();
114
+ if (trimmed === "") return null;
115
+ const parts = new Intl.NumberFormat(locale).formatToParts(12345.6);
116
+ const group = parts.find((p) => p.type === "group")?.value ?? ",";
117
+ const decimal = parts.find((p) => p.type === "decimal")?.value ?? ".";
118
+ const normalized = trimmed.split(group).join("").replace(/\s/g, "").replace(decimal, ".").replace(/^\u2212/, "-");
119
+ return /^[-+]?(\d+\.?\d*|\.\d+)(e[-+]?\d+)?$/i.test(normalized) ? Number(normalized) : NaN;
120
+ }
121
+ var textOf = (column) => column.textValue ?? (typeof column.header === "string" ? column.header : column.key);
122
+ var isEditable = (column, row) => Boolean(column && (typeof column.editable === "function" ? column.editable(row) : column.editable));
123
+ function DataGridInner(props, ref) {
124
+ const { columns, rows, getRowId, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledBy, manualSorting = false, manualFiltering = false, pageSize, rowCount, manualPagination = false, selectionMode = "none", isRowSelectable, height, density = "comfortable", striped = false, loading = false, emptyState = "No results", className } = props;
125
+ if (!ariaLabel && !ariaLabelledBy) warnOnce("DataGrid: provide `aria-label` or `aria-labelledby`.");
126
+ const labels = useMemo(() => ({
127
+ ...defaultLabels,
128
+ ...props.labels
129
+ }), [props.labels]);
130
+ const id = useId();
131
+ const { locale } = useLocale();
132
+ const collator = useMemo(() => new Intl.Collator(locale, {
133
+ numeric: true,
134
+ sensitivity: "base"
135
+ }), [locale]);
136
+ const selectable = selectionMode === "multiple";
137
+ const multiSort = Boolean(props.multiSort || props.sorts !== void 0 || props.defaultSorts !== void 0 || props.onSortsChange);
138
+ const [sort, setSort] = useMaybeControlled(props.sort, props.defaultSort ?? null, props.onSortChange);
139
+ const [sorts, setSorts] = useMaybeControlled(props.sorts, props.defaultSorts ?? EMPTY_SORTS, (next) => props.onSortsChange?.([...next]));
140
+ const [filters, setFilters] = useMaybeControlled(props.filters, props.defaultFilters ?? EMPTY_FILTERS, props.onFiltersChange);
141
+ const [search, setSearch] = useMaybeControlled(props.search, props.defaultSearch ?? "", props.onSearchChange);
142
+ const [page, setPage] = useMaybeControlled(props.page, props.defaultPage ?? 1, props.onPageChange);
143
+ const [selected, setSelected] = useMaybeControlled(props.selectedIds, props.defaultSelectedIds ?? [], props.onSelectionChange);
144
+ const [visibility, setVisibility] = useMaybeControlled(props.columnVisibility, props.defaultColumnVisibility ?? {}, props.onColumnVisibilityChange);
145
+ const [columnLayout, setColumnLayout] = useMaybeControlled(props.columnLayout, props.defaultColumnLayout ?? {}, props.onColumnLayoutChange);
146
+ const [widths, setWidths] = useMaybeControlled(props.columnWidths, {}, props.onColumnWidthsChange);
147
+ const [announcement, setAnnouncement] = useState("");
148
+ const toKeys = (value) => value ? [value] : EMPTY_KEYS;
149
+ const [groupKeys, setGroupKeys] = useMaybeControlled(props.grouping ?? (props.groupBy !== void 0 ? toKeys(props.groupBy) : void 0), props.defaultGrouping ?? toKeys(props.defaultGroupBy), (next) => {
150
+ props.onGroupingChange?.([...next]);
151
+ props.onGroupByChange?.(next[0] ?? null);
152
+ });
153
+ const groupColumns = useMemo(() => groupKeys.flatMap((key) => columns.find((c) => c.key === key) ?? []), [groupKeys, columns]);
154
+ const groupColumn = groupColumns[0];
155
+ const treeData = Boolean(props.getSubRows);
156
+ if (treeData && groupColumns.length) warnOnce("DataGrid: tree data (`getSubRows`) and grouping cannot be combined; grouping is ignored.");
157
+ const grouping = !treeData && groupColumns.length > 0;
158
+ const tree = useMemo(() => props.getSubRows ? buildTree(rows, getRowId, props.getSubRows) : null, [
159
+ rows,
160
+ getRowId,
161
+ props.getSubRows
162
+ ]);
163
+ const parentIds = useMemo(() => tree ? [...tree.childrenOf.keys()].filter((key) => key !== null && (tree.childrenOf.get(key)?.length ?? 0) > 0) : [], [tree]);
164
+ const [expandedIds, setExpandedIds] = useMaybeControlled(props.expandedRowIds, props.defaultExpandedRowIds === "all" ? parentIds : props.defaultExpandedRowIds ?? EMPTY_KEYS, (next) => props.onExpandedRowIdsChange?.([...next]));
165
+ const [filterToggled, setFilterToggled] = useState({
166
+ query: "",
167
+ ids: /* @__PURE__ */ new Set()
168
+ });
169
+ const [detailIds, setDetailIds] = useMaybeControlled(props.detailRowIds, props.defaultDetailRowIds ?? EMPTY_KEYS, (next) => props.onDetailRowIdsChange?.([...next]));
170
+ const hasDetail = Boolean(props.renderDetail);
171
+ const [range, setRange] = useState(null);
172
+ const dragAnchor = useRef(null);
173
+ const history = useRef({
174
+ undo: [],
175
+ redo: []
176
+ });
177
+ const [toggledGroups, setToggledGroups] = useState(/* @__PURE__ */ new Set());
178
+ const [editing, setEditing] = useState(null);
179
+ const savingRef = useRef(false);
180
+ const sortOrder = useMemo(() => {
181
+ if (!multiSort) return sort ? [sort] : EMPTY_SORTS;
182
+ const available = new Set(columns.filter((column) => column.sortable).map((column) => column.key));
183
+ return sorts.filter(({ column }) => available.delete(column));
184
+ }, [
185
+ columns,
186
+ multiSort,
187
+ sort,
188
+ sorts
189
+ ]);
190
+ const sorting = useMemo(() => sortOrder.map(({ column, direction }) => ({
191
+ id: column,
192
+ desc: direction === "descending"
193
+ })), [sortOrder]);
194
+ const sortPriorities = useMemo(() => new Map(sortOrder.map((entry, index) => [entry.column, index + 1])), [sortOrder]);
195
+ const columnFilters = useMemo(() => {
196
+ const available = new Set(columns.map((column) => column.key));
197
+ const byColumn = /* @__PURE__ */ new Map();
198
+ for (const filter of filters) {
199
+ if (!available.has(filter.column)) continue;
200
+ const rules = byColumn.get(filter.column);
201
+ if (rules) rules.push(filter);
202
+ else byColumn.set(filter.column, [filter]);
203
+ }
204
+ return [...byColumn].map(([key, rules]) => ({
205
+ id: key,
206
+ value: {
207
+ rules,
208
+ locale
209
+ }
210
+ }));
211
+ }, [
212
+ columns,
213
+ filters,
214
+ locale
215
+ ]);
216
+ const filterKey = useMemo(() => JSON.stringify(columnFilters.map(({ id: key, value }) => [key, value.rules.map((rule) => [
217
+ rule.type,
218
+ rule.operator,
219
+ "value" in rule ? rule.value : null
220
+ ])])), [columnFilters]);
221
+ const rowSelection = useMemo(() => Object.fromEntries(selected.map((s) => [s, true])), [selected]);
222
+ const pagination = useMemo(() => ({
223
+ pageIndex: Math.max(0, page - 1),
224
+ pageSize: pageSize ?? Number.MAX_SAFE_INTEGER
225
+ }), [page, pageSize]);
226
+ const columnDefs = useMemo(() => {
227
+ const defs = columns.map((c) => ({
228
+ id: c.key,
229
+ accessorFn: (row) => {
230
+ const v = c.value ? c.value(row) : read(row, c.key);
231
+ return isEmpty(v) ? void 0 : v;
232
+ },
233
+ header: () => c.header,
234
+ cell: (ctx) => c.cell ? c.cell(ctx.row.original) : String(ctx.getValue() ?? ""),
235
+ enableSorting: Boolean(c.sortable),
236
+ enableGlobalFilter: c.searchable !== false,
237
+ filterFn: (row, columnId, { rules, locale }) => {
238
+ const value = row.getValue(columnId);
239
+ return rules.every((rule) => matchesColumnFilter(value, rule, locale));
240
+ },
241
+ enableHiding: c.hideable !== false,
242
+ enableResizing: c.resizable !== false,
243
+ size: c.width ?? 160,
244
+ minSize: c.minWidth ?? 60,
245
+ maxSize: c.maxWidth ?? 2e3,
246
+ sortFn: (a, b, columnId) => {
247
+ const x = a.getValue(columnId);
248
+ const y = b.getValue(columnId);
249
+ if (x instanceof Date && y instanceof Date) return x.getTime() - y.getTime();
250
+ if (typeof x === "number" && typeof y === "number") return x - y;
251
+ return collator.compare(String(x), String(y));
252
+ },
253
+ sortUndefined: "last"
254
+ }));
255
+ const fixed = (key) => ({
256
+ id: key,
257
+ header: () => null,
258
+ cell: () => null,
259
+ enableSorting: false,
260
+ enableHiding: false,
261
+ enableResizing: false,
262
+ enableGlobalFilter: false,
263
+ size: 44,
264
+ minSize: 44,
265
+ maxSize: 44
266
+ });
267
+ if (hasDetail) defs.unshift(fixed(DETAIL_COL));
268
+ if (selectable) defs.unshift(fixed(SELECT_COL));
269
+ return defs;
270
+ }, [
271
+ columns,
272
+ selectable,
273
+ hasDetail,
274
+ collator
275
+ ]);
276
+ const leadingColumns = useMemo(() => [...selectable ? [SELECT_COL] : [], ...hasDetail ? [DETAIL_COL] : []], [selectable, hasDetail]);
277
+ const layout = useMemo(() => arrangeColumns(columns.map((column) => column.key), columnLayout, leadingColumns), [
278
+ columns,
279
+ columnLayout,
280
+ leadingColumns
281
+ ]);
282
+ const table = useTable({
283
+ features,
284
+ columns: columnDefs,
285
+ data: tree ? tree.all : rows,
286
+ getRowId: (row) => getRowId(row),
287
+ state: {
288
+ sorting,
289
+ columnFilters,
290
+ globalFilter: search,
291
+ pagination: (grouping || treeData) && !manualPagination ? {
292
+ pageIndex: 0,
293
+ pageSize: Number.MAX_SAFE_INTEGER
294
+ } : pagination,
295
+ rowSelection,
296
+ columnVisibility: visibility,
297
+ columnOrder: layout.order,
298
+ columnSizing: widths
299
+ },
300
+ onSortingChange: (u) => {
301
+ const next = apply(u, sorting).map(({ id: column, desc }) => ({
302
+ column,
303
+ direction: desc ? "descending" : "ascending"
304
+ }));
305
+ if (multiSort) setSorts(next);
306
+ else setSort(next[0] ?? null);
307
+ },
308
+ onPaginationChange: (u) => setPage(apply(u, pagination).pageIndex + 1),
309
+ onRowSelectionChange: (u) => setSelected(Object.keys(apply(u, rowSelection)).filter((k) => apply(u, rowSelection)[k])),
310
+ onColumnVisibilityChange: (u) => setVisibility(apply(u, visibility)),
311
+ onColumnSizingChange: (u) => setWidths(apply(u, widths)),
312
+ globalFilterFn: "includesString",
313
+ enableRowSelection: (row) => isRowSelectable ? isRowSelectable(row.original) : true,
314
+ enableSortingRemoval: true,
315
+ enableMultiSort: multiSort,
316
+ columnResizeMode: "onChange",
317
+ manualSorting,
318
+ manualFiltering,
319
+ manualPagination,
320
+ autoResetPageIndex: false,
321
+ ...manualPagination && rowCount !== void 0 ? { rowCount } : {}
322
+ });
323
+ const lastFilter = useRef({
324
+ search,
325
+ filterKey
326
+ });
327
+ useEffect(() => {
328
+ const columnFiltersChanged = lastFilter.current.filterKey !== filterKey;
329
+ if (lastFilter.current.search !== search || columnFiltersChanged) {
330
+ lastFilter.current = {
331
+ search,
332
+ filterKey
333
+ };
334
+ if (page !== 1) setPage(1);
335
+ if (columnFiltersChanged && !manualFiltering) setAnnouncement(labels.results(table.getPrePaginatedRowModel().rows.length));
336
+ }
337
+ }, [
338
+ filterKey,
339
+ search,
340
+ page,
341
+ setPage,
342
+ manualFiltering,
343
+ labels,
344
+ table
345
+ ]);
346
+ const visibleColumns = table.getVisibleLeafColumns();
347
+ const pinned = getPinnedOffsets(visibleColumns, layout.sides);
348
+ const leafRows = table.getRowModel().rows;
349
+ const groupKeyOf = useCallback((value) => isEmpty(value) ? "\0empty" : value instanceof Date ? `d:${value.getTime()}` : `${typeof value}:${String(value)}`, []);
350
+ const filtering = !manualFiltering && (search.trim() !== "" || filters.length > 0);
351
+ const queryKey = `${search}\u0000${filterKey}`;
352
+ const allItems = useMemo(() => {
353
+ const detailOpen = new Set(detailIds);
354
+ const withDetail = (item) => hasDetail && detailOpen.has(item.row.id) ? [item, {
355
+ kind: "detail",
356
+ row: item.row
357
+ }] : [item];
358
+ if (tree) {
359
+ const rank = new Map(leafRows.map((row, index) => [row.id, index]));
360
+ const forced = /* @__PURE__ */ new Set();
361
+ if (filtering) for (const row of leafRows) for (const id of ancestorsOf(tree, row.id)) forced.add(id);
362
+ const toggled = filterToggled.query === queryKey ? filterToggled.ids : /* @__PURE__ */ new Set();
363
+ const open = new Set(expandedIds);
364
+ const isExpanded = (rowId) => filtering ? forced.has(rowId) !== toggled.has(rowId) : open.has(rowId);
365
+ return visibleTree(tree, rank, isExpanded).flatMap((node) => {
366
+ const row = table.getRow(node.id, true);
367
+ return row ? withDetail({
368
+ kind: "row",
369
+ row,
370
+ depth: node.depth,
371
+ hasChildren: node.hasChildren,
372
+ expanded: node.hasChildren ? isExpanded(node.id) : void 0,
373
+ setSize: node.setSize,
374
+ posInSet: node.posInSet
375
+ }) : [];
376
+ });
377
+ }
378
+ if (!grouping) return leafRows.flatMap((row) => withDetail({
379
+ kind: "row",
380
+ row
381
+ }));
382
+ const collapsedByDefault = Boolean(props.defaultGroupsCollapsed);
383
+ const build = (list, level, parentKey) => {
384
+ const column = groupColumns[level];
385
+ if (!column) return list.flatMap((row) => withDetail({
386
+ kind: "row",
387
+ row
388
+ }));
389
+ const groups = /* @__PURE__ */ new Map();
390
+ for (const row of list) {
391
+ const value = column.value ? column.value(row.original) : read(row.original, column.key);
392
+ const key = `${parentKey}/${groupKeyOf(value)}`;
393
+ const group = groups.get(key) ?? {
394
+ kind: "group",
395
+ key,
396
+ value,
397
+ rows: [],
398
+ expanded: true,
399
+ depth: level,
400
+ column
401
+ };
402
+ group.rows.push(row);
403
+ groups.set(key, group);
404
+ }
405
+ const ordered = [...groups.values()];
406
+ const groupSort = sortOrder.find((entry) => entry.column === column.key);
407
+ if (!groupSort || multiSort && !manualSorting) {
408
+ const direction = groupSort?.direction === "descending" ? -1 : 1;
409
+ ordered.sort((a, b) => isEmpty(a.value) ? 1 : isEmpty(b.value) ? -1 : direction * compareValues(a.value, b.value, collator));
410
+ }
411
+ return ordered.flatMap((g) => {
412
+ const expanded = toggledGroups.has(g.key) ? collapsedByDefault : !collapsedByDefault;
413
+ const header = {
414
+ ...g,
415
+ expanded
416
+ };
417
+ return expanded ? [header, ...build(g.rows, level + 1, g.key)] : [header];
418
+ });
419
+ };
420
+ return build(leafRows, 0, "");
421
+ }, [
422
+ leafRows,
423
+ tree,
424
+ filtering,
425
+ filterToggled,
426
+ queryKey,
427
+ expandedIds,
428
+ grouping,
429
+ groupColumns,
430
+ groupKeyOf,
431
+ sortOrder,
432
+ multiSort,
433
+ manualSorting,
434
+ collator,
435
+ toggledGroups,
436
+ props.defaultGroupsCollapsed,
437
+ detailIds,
438
+ hasDetail
439
+ ]);
440
+ const clientPagedGroups = (grouping || treeData || hasDetail) && !manualPagination && pageSize !== void 0;
441
+ const total = manualPagination ? rowCount ?? leafRows.length : grouping || treeData ? allItems.length : table.getPrePaginatedRowModel().rows.length;
442
+ const pageCount = pageSize ? Math.max(1, Math.ceil(total / pageSize)) : 1;
443
+ const firstRowIndex = pageSize ? (page - 1) * pageSize : 0;
444
+ const bodyRows = clientPagedGroups ? pageItems(allItems, firstRowIndex, pageSize ?? 0, grouping || treeData) : allItems;
445
+ const rowHeaderKey = (columns.find((c) => c.rowHeader) ?? columns[0])?.key;
446
+ const rowHeight = ROW_HEIGHT[density];
447
+ const scrollRef = useRef(null);
448
+ const virtual = Boolean(height) && (props.virtualize ?? bodyRows.length > 100);
449
+ const detailHeight = props.detailHeight ?? 160;
450
+ const virtualizer = useVirtualizer({
451
+ count: bodyRows.length,
452
+ getScrollElement: () => scrollRef.current,
453
+ estimateSize: (index) => bodyRows[index]?.kind === "detail" ? detailHeight : rowHeight,
454
+ overscan: 8,
455
+ enabled: virtual
456
+ });
457
+ const rendered = virtual ? virtualizer.getVirtualItems().map((v) => ({
458
+ index: v.index,
459
+ start: v.start
460
+ })) : bodyRows.map((_, index) => ({
461
+ index,
462
+ start: 0
463
+ }));
464
+ const visibleColumnsEarly = table.getVisibleLeafColumns();
465
+ const virtualColumns = props.virtualizeColumns ?? visibleColumnsEarly.length > 30;
466
+ const columnVirtualizer = useVirtualizer({
467
+ horizontal: true,
468
+ count: visibleColumnsEarly.length,
469
+ getScrollElement: () => scrollRef.current,
470
+ estimateSize: (index) => visibleColumnsEarly[index]?.getSize() ?? 160,
471
+ overscan: 3,
472
+ enabled: virtualColumns
473
+ });
474
+ const widthKey = visibleColumnsEarly.map((c) => `${c.id}:${c.getSize()}`).join("|");
475
+ useEffect(() => {
476
+ if (virtualColumns) columnVirtualizer.measure();
477
+ }, [
478
+ virtualColumns,
479
+ widthKey,
480
+ columnVirtualizer
481
+ ]);
482
+ const gridRef = useRef(null);
483
+ const pendingColumn = useRef(null);
484
+ const toggleSortFor = useCallback((col, append = false) => {
485
+ const column = visibleColumns[col];
486
+ if (!column || !column.getCanSort()) return;
487
+ const name = columns.find((c) => c.key === column.id);
488
+ const text = name?.textValue ?? (typeof name?.header === "string" ? name.header : column.id);
489
+ const now = column.getIsSorted();
490
+ const next = now === "asc" ? {
491
+ column: column.id,
492
+ direction: "descending"
493
+ } : now === "desc" ? null : {
494
+ column: column.id,
495
+ direction: "ascending"
496
+ };
497
+ if (!multiSort) {
498
+ setSort(next);
499
+ setAnnouncement(next ? next.direction === "ascending" ? labels.sortedAscending(text) : labels.sortedDescending(text) : labels.sortCleared);
500
+ return;
501
+ }
502
+ const order = append ? [...sortOrder] : [];
503
+ const previous = order.findIndex((entry) => entry.column === column.id);
504
+ if (previous >= 0) order.splice(previous, 1, ...next ? [next] : []);
505
+ else if (next) order.push(next);
506
+ setSorts(order);
507
+ setAnnouncement(order.map((entry, index) => {
508
+ const definition = columns.find((candidate) => candidate.key === entry.column);
509
+ const title = definition ? textOf(definition) : entry.column;
510
+ const message = entry.direction === "ascending" ? labels.sortedAscending(title) : labels.sortedDescending(title);
511
+ return `${labels.sortPriority(index + 1)}. ${message}`;
512
+ }).join(". ") || labels.sortCleared);
513
+ }, [
514
+ visibleColumns,
515
+ columns,
516
+ labels,
517
+ multiSort,
518
+ sortOrder,
519
+ setSort,
520
+ setSorts
521
+ ]);
522
+ const onHeaderKey = (col, event) => {
523
+ const column = visibleColumns[col];
524
+ if (!column) return false;
525
+ if (multiSort && column.getCanSort() && event.shiftKey && (event.key === "Enter" || event.key === " ")) {
526
+ event.preventDefault();
527
+ toggleSortFor(col, true);
528
+ return true;
529
+ }
530
+ if (!event.altKey || event.key !== "ArrowLeft" && event.key !== "ArrowRight") return false;
531
+ const rtl = getComputedStyle(event.currentTarget).direction === "rtl";
532
+ const forward = event.key === "ArrowRight" !== rtl;
533
+ if (event.shiftKey && props.reorderableColumns) {
534
+ event.preventDefault();
535
+ const index = col + (forward ? 1 : -1);
536
+ const adjacent = visibleColumns[index];
537
+ const fixed = (key) => key === SELECT_COL || key === DETAIL_COL;
538
+ if (!adjacent || fixed(column.id) || fixed(adjacent.id) || layout.sides.get(column.id) !== layout.sides.get(adjacent.id)) return true;
539
+ const order = [...layout.order];
540
+ const from = order.indexOf(column.id);
541
+ const to = order.indexOf(adjacent.id);
542
+ order[from] = adjacent.id;
543
+ order[to] = column.id;
544
+ const pinnedStart = order.filter((key) => !fixed(key) && layout.sides.get(key) === "start");
545
+ const pinnedEnd = order.filter((key) => layout.sides.get(key) === "end");
546
+ pendingColumn.current = {
547
+ key: column.id,
548
+ index,
549
+ focused: event.currentTarget.ownerDocument.activeElement
550
+ };
551
+ setColumnLayout({
552
+ order: order.filter((key) => !fixed(key)),
553
+ pinnedStart,
554
+ pinnedEnd
555
+ });
556
+ return true;
557
+ }
558
+ if (event.shiftKey || !column.getCanResize()) return false;
559
+ event.preventDefault();
560
+ const size = Math.min(column.columnDef.maxSize ?? 2e3, Math.max(column.columnDef.minSize ?? 60, column.getSize() + (forward ? 16 : -16)));
561
+ setWidths({
562
+ ...widths,
563
+ [column.id]: size
564
+ });
565
+ return true;
566
+ };
567
+ const ensureRendered = useCallback((row, col) => {
568
+ if (virtual && row > 0) virtualizer.scrollToIndex(row - 1, { align: "auto" });
569
+ if (virtualColumns && col !== void 0) columnVirtualizer.scrollToIndex(col, { align: "auto" });
570
+ }, [
571
+ virtual,
572
+ virtualizer,
573
+ virtualColumns,
574
+ columnVirtualizer
575
+ ]);
576
+ const columnByKey = useCallback((key) => columns.find((c) => c.key === key), [columns]);
577
+ const rowName = useCallback((row) => {
578
+ const header = rowHeaderKey ? columns.find((c) => c.key === rowHeaderKey) : void 0;
579
+ const v = header ? header.value ? header.value(row) : read(row, header.key) : void 0;
580
+ return v instanceof Date ? v.toLocaleDateString(locale) : String(v ?? "");
581
+ }, [
582
+ columns,
583
+ locale,
584
+ rowHeaderKey
585
+ ]);
586
+ const valueOf = (column, row) => column.value ? column.value(row) : read(row, column.key);
587
+ const draftOf = (column, row) => {
588
+ const v = valueOf(column, row);
589
+ if (v === null || v === void 0) return "";
590
+ if (typeof v === "number" && column.editor === "number") return new Intl.NumberFormat(locale, {
591
+ useGrouping: false,
592
+ maximumFractionDigits: 20
593
+ }).format(v);
594
+ return v instanceof Date ? v.toISOString().slice(0, 10) : String(v);
595
+ };
596
+ const leafById = useCallback((rowId) => leafRows.find((r) => r.id === rowId), [leafRows]);
597
+ const startEdit = (rowId, key, draft) => {
598
+ const row = leafById(rowId);
599
+ const column = columnByKey(key);
600
+ if (!row || !column || !isEditable(column, row.original)) return false;
601
+ setEditing({
602
+ rowId,
603
+ column: key,
604
+ draft: draft ?? draftOf(column, row.original),
605
+ typed: draft !== void 0 && draft !== ""
606
+ });
607
+ return true;
608
+ };
609
+ const refocusCell = () => nav.moveTo(nav.active);
610
+ const cancelEdit = () => {
611
+ if (savingRef.current) return;
612
+ setEditing(null);
613
+ refocusCell();
614
+ };
615
+ const commitEdit = (override, restoreFocus = true) => {
616
+ if (!editing || savingRef.current) return;
617
+ const row = leafById(editing.rowId);
618
+ const column = columnByKey(editing.column);
619
+ if (!row || !column) return setEditing(null);
620
+ const previousValue = valueOf(column, row.original);
621
+ const doc = gridRef.current?.ownerDocument;
622
+ const focused = doc?.activeElement;
623
+ const restoreCellFocus = () => {
624
+ if (restoreFocus && doc && (doc.activeElement === focused || doc.activeElement === doc.body)) refocusCell();
625
+ };
626
+ const fail = (message) => {
627
+ savingRef.current = false;
628
+ setEditing((current) => current && {
629
+ ...current,
630
+ error: message,
631
+ saving: false
632
+ });
633
+ setAnnouncement(message);
634
+ };
635
+ const reject = (reason) => fail(reason instanceof Error ? reason.message : String(reason));
636
+ try {
637
+ let value = override;
638
+ if (value === void 0) value = column.parse ? column.parse(editing.draft, row.original) : column.editor === "number" ? parseLocaleNumber(editing.draft, locale) : editing.draft;
639
+ if (typeof value === "number" && Number.isNaN(value)) return fail(labels.invalidNumber);
640
+ const error = column.validate?.(value, row.original);
641
+ if (error) return fail(error);
642
+ const done = () => {
643
+ savingRef.current = false;
644
+ setEditing(null);
645
+ setAnnouncement(labels.edited(textOf(column), rowName(row.original)));
646
+ record([{
647
+ row: row.original,
648
+ rowId: row.id,
649
+ column: column.key,
650
+ value,
651
+ previousValue
652
+ }]);
653
+ restoreCellFocus();
654
+ };
655
+ if (value === previousValue || value === "" && isEmpty(previousValue)) {
656
+ setEditing(null);
657
+ restoreCellFocus();
658
+ return;
659
+ }
660
+ savingRef.current = true;
661
+ const edit = {
662
+ row: row.original,
663
+ rowId: row.id,
664
+ column: column.key,
665
+ value,
666
+ previousValue
667
+ };
668
+ const result = props.onCellEdit ? props.onCellEdit(edit) : props.onCellsEdit?.([edit]);
669
+ if (result && typeof result.then === "function") {
670
+ setEditing((current) => current && {
671
+ ...current,
672
+ error: void 0,
673
+ saving: true
674
+ });
675
+ Promise.resolve(result).then(done, reject);
676
+ } else done();
677
+ } catch (reason) {
678
+ reject(reason);
679
+ }
680
+ };
681
+ const record = (batch) => {
682
+ const limit = props.undoLimit ?? 50;
683
+ if (!batch.length || limit <= 0) return;
684
+ history.current.undo = [...history.current.undo, batch].slice(-limit);
685
+ history.current.redo = [];
686
+ };
687
+ /** Sends edits to `onCellsEdit` (or `onCellEdit` each); resolves true when they were accepted. */
688
+ const sendEdits = (edits) => {
689
+ if (!edits.length) return false;
690
+ const fail = (reason) => {
691
+ setAnnouncement(reason instanceof Error ? reason.message : String(reason));
692
+ return false;
693
+ };
694
+ try {
695
+ const result = props.onCellsEdit ? props.onCellsEdit(edits) : edits.map((edit) => props.onCellEdit?.(edit)).find(isPromise);
696
+ return isPromise(result) ? result.then(() => true, fail) : true;
697
+ } catch (reason) {
698
+ return fail(reason);
699
+ }
700
+ };
701
+ const applyEdits = (edits, message) => {
702
+ const outcome = sendEdits(edits);
703
+ const finish = (ok) => {
704
+ if (!ok) return;
705
+ record(edits);
706
+ setAnnouncement(message);
707
+ };
708
+ if (isPromise(outcome)) outcome.then(finish);
709
+ else finish(outcome);
710
+ };
711
+ const replay = (direction) => {
712
+ const stack = history.current[direction];
713
+ const batch = stack.at(-1);
714
+ if (!batch) {
715
+ if (direction === "undo") setAnnouncement(labels.nothingToUndo);
716
+ return false;
717
+ }
718
+ const edits = batch.flatMap((edit) => {
719
+ const original = (leafById(edit.rowId) ?? (tree ? table.getRow(edit.rowId, true) : void 0))?.original ?? edit.row;
720
+ return direction === "undo" ? [{
721
+ row: original,
722
+ rowId: edit.rowId,
723
+ column: edit.column,
724
+ value: edit.previousValue,
725
+ previousValue: edit.value
726
+ }] : [{
727
+ row: original,
728
+ rowId: edit.rowId,
729
+ column: edit.column,
730
+ value: edit.value,
731
+ previousValue: edit.previousValue
732
+ }];
733
+ });
734
+ const outcome = sendEdits(edits);
735
+ const finish = (ok) => {
736
+ if (!ok) return;
737
+ history.current[direction] = stack.slice(0, -1);
738
+ const other = direction === "undo" ? "redo" : "undo";
739
+ history.current[other] = [...history.current[other], batch];
740
+ setAnnouncement(direction === "undo" ? labels.undone(batch.length) : labels.redone(batch.length));
741
+ };
742
+ if (isPromise(outcome)) outcome.then(finish);
743
+ else finish(outcome);
744
+ return true;
745
+ };
746
+ const dataColumnAt = (col) => {
747
+ const id = visibleColumns[col]?.id;
748
+ return id && id !== SELECT_COL && id !== DETAIL_COL ? columnByKey(id) : void 0;
749
+ };
750
+ const dataRowAt = (row) => {
751
+ const item = bodyRows[row - 1];
752
+ return item?.kind === "row" ? item.row : void 0;
753
+ };
754
+ const rect = (r) => ({
755
+ top: Math.max(1, Math.min(r.anchor.row, r.focus.row)),
756
+ bottom: Math.max(r.anchor.row, r.focus.row),
757
+ left: Math.min(r.anchor.col, r.focus.col),
758
+ right: Math.max(r.anchor.col, r.focus.col)
759
+ });
760
+ const inRange = (row, col) => {
761
+ if (!range) return false;
762
+ const r = rect(range);
763
+ return row >= r.top && row <= r.bottom && col >= r.left && col <= r.right;
764
+ };
765
+ /** Cells of the range (or the active cell): data rows × data columns, in reading order. */
766
+ const targetCells = () => {
767
+ const r = range ? rect(range) : {
768
+ top: nav.active.row,
769
+ bottom: nav.active.row,
770
+ left: nav.active.col,
771
+ right: nav.active.col
772
+ };
773
+ const out = [];
774
+ for (let row = r.top; row <= r.bottom; row++) {
775
+ const gridRow = dataRowAt(row);
776
+ if (!gridRow) continue;
777
+ const cells = [];
778
+ for (let col = r.left; col <= r.right; col++) {
779
+ const column = dataColumnAt(col);
780
+ if (column) cells.push({
781
+ row: gridRow,
782
+ column
783
+ });
784
+ }
785
+ if (cells.length) out.push(cells);
786
+ }
787
+ return out;
788
+ };
789
+ const clipboardText = (column, row) => {
790
+ const v = valueOf(column, row);
791
+ if (isEmpty(v)) return "";
792
+ return v instanceof Date ? v.toISOString() : String(v);
793
+ };
794
+ const announceRange = (next) => {
795
+ if (!next) return;
796
+ const r = rect(next);
797
+ setAnnouncement(labels.cellsSelected(r.bottom - r.top + 1, r.right - r.left + 1));
798
+ };
799
+ /** Parses text for a cell like the editor would; returns undefined when it is rejected. */
800
+ const parseFor = (column, row, text) => {
801
+ let value = text;
802
+ if (column.parse) value = column.parse(text, row);
803
+ else if (column.editor === "number") value = parseLocaleNumber(text, locale);
804
+ else if (column.editor === "select" && column.options) {
805
+ const match = column.options.find((o) => o.value === text || o.label.toLocaleLowerCase() === text.trim().toLocaleLowerCase());
806
+ if (!match) return void 0;
807
+ value = match.value;
808
+ }
809
+ if (typeof value === "number" && Number.isNaN(value)) return void 0;
810
+ if (column.validate?.(value, row)) return void 0;
811
+ return { value };
812
+ };
813
+ const editOf = (gridRow, column, value) => {
814
+ const previousValue = valueOf(column, gridRow.original);
815
+ if (value === previousValue || isEmpty(value) && isEmpty(previousValue)) return void 0;
816
+ return {
817
+ row: gridRow.original,
818
+ rowId: gridRow.id,
819
+ column: column.key,
820
+ value,
821
+ previousValue
822
+ };
823
+ };
824
+ const canEdit = Boolean(props.onCellEdit || props.onCellsEdit);
825
+ const pasteText = (text) => {
826
+ const matrix = parseTsv(text);
827
+ const cells = targetCells();
828
+ if (!cells[0]?.[0] || !canEdit) return;
829
+ const edits = [];
830
+ let skipped = 0;
831
+ const single = matrix.length === 1 && matrix[0]?.length === 1;
832
+ const visit = (gridRow, column, raw) => {
833
+ if (!isEditable(column, gridRow.original)) return void skipped++;
834
+ const parsed = parseFor(column, gridRow.original, raw);
835
+ if (!parsed) return void skipped++;
836
+ const edit = editOf(gridRow, column, parsed.value);
837
+ if (edit) edits.push(edit);
838
+ };
839
+ if (single && range) for (const line of cells) for (const { row, column } of line) visit(row, column, matrix[0]?.[0] ?? "");
840
+ else {
841
+ const r = range ? rect(range) : {
842
+ top: nav.active.row,
843
+ left: nav.active.col
844
+ };
845
+ const cols = [];
846
+ for (let col = r.left; col < visibleColumns.length && cols.length < (matrix[0]?.length ?? 0); col++) {
847
+ const column = dataColumnAt(col);
848
+ if (column) cols.push(column);
849
+ }
850
+ let line = 0;
851
+ for (let row = r.top; row <= bodyRows.length && line < matrix.length; row++) {
852
+ const gridRow = dataRowAt(row);
853
+ if (!gridRow) continue;
854
+ (matrix[line++] ?? []).forEach((raw, i) => {
855
+ const column = cols[i];
856
+ if (column) visit(gridRow, column, raw);
857
+ });
858
+ }
859
+ }
860
+ if (edits.length) applyEdits(edits, labels.pasted(edits.length, skipped));
861
+ else setAnnouncement(labels.pasted(0, skipped));
862
+ };
863
+ const fillDown = () => {
864
+ const cells = targetCells();
865
+ if (cells.length < 2 || !canEdit) return false;
866
+ const [first, ...rest] = cells;
867
+ const edits = [];
868
+ for (const line of rest) line.forEach(({ row, column }, i) => {
869
+ const source = first?.[i];
870
+ if (!source || source.column !== column || !isEditable(column, row.original)) return;
871
+ const value = valueOf(column, source.row.original);
872
+ if (column.validate?.(value, row.original)) return;
873
+ const edit = editOf(row, column, value);
874
+ if (edit) edits.push(edit);
875
+ });
876
+ if (edits.length) applyEdits(edits, labels.filled(edits.length));
877
+ return true;
878
+ };
879
+ const clearRange = () => {
880
+ if (!canEdit) return;
881
+ const edits = [];
882
+ for (const line of targetCells()) for (const { row, column } of line) {
883
+ if (!isEditable(column, row.original)) continue;
884
+ const parsed = parseFor(column, row.original, "");
885
+ const edit = parsed && editOf(row, column, parsed.value);
886
+ if (edit) edits.push(edit);
887
+ }
888
+ if (edits.length) applyEdits(edits, labels.cleared(edits.length));
889
+ };
890
+ const onCopy = (event) => {
891
+ const target = event.target;
892
+ if (target.closest("input, textarea, [contenteditable=\"true\"]")) return;
893
+ if (!target.closest("[data-grid-cell]") || nav.active.row === 0) return;
894
+ const matrix = targetCells().map((line) => line.map(({ row, column }) => clipboardText(column, row.original)));
895
+ if (!matrix.length) return;
896
+ event.preventDefault();
897
+ event.clipboardData.setData("text/plain", toTsv(matrix));
898
+ event.clipboardData.setData("text/html", toHtmlTable(matrix));
899
+ setAnnouncement(labels.copied(matrix.reduce((n, line) => n + line.length, 0)));
900
+ };
901
+ const onPaste = (event) => {
902
+ const target = event.target;
903
+ if (editing || target.closest("input, textarea, [contenteditable=\"true\"]") || !target.closest("[data-grid-cell]")) return;
904
+ const text = event.clipboardData.getData("text/plain");
905
+ if (!text || !canEdit) return;
906
+ event.preventDefault();
907
+ pasteText(text);
908
+ };
909
+ const toggleExpanded = (rowId) => {
910
+ if (filtering) {
911
+ setFilterToggled((prev) => {
912
+ const ids = new Set(prev.query === queryKey ? prev.ids : []);
913
+ if (ids.has(rowId)) ids.delete(rowId);
914
+ else ids.add(rowId);
915
+ return {
916
+ query: queryKey,
917
+ ids
918
+ };
919
+ });
920
+ return;
921
+ }
922
+ setExpandedIds(expandedIds.includes(rowId) ? expandedIds.filter((id) => id !== rowId) : [...expandedIds, rowId]);
923
+ };
924
+ const toggleDetail = (rowId) => setDetailIds(detailIds.includes(rowId) ? detailIds.filter((id) => id !== rowId) : [...detailIds, rowId]);
925
+ /** Keys on an editable cell start editing (APG grid: Enter / F2, or typing replaces the value). */
926
+ const onGridKeyDown = (event) => {
927
+ if (onRangeKeys(event)) return;
928
+ const cell = event.target.closest("[data-grid-cell][data-editable]");
929
+ if (cell && event.target === cell && !editing) {
930
+ const rowId = cell.dataset.rowId ?? "";
931
+ const key = cell.dataset.columnKey ?? "";
932
+ const printable = event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey && event.key !== " ";
933
+ if (event.key === "Enter" || event.key === "F2" ? startEdit(rowId, key) : printable && columnByKey(key)?.editor !== "select" ? startEdit(rowId, key, event.key) : event.key === "Backspace" || event.key === "Delete" ? startEdit(rowId, key, "") : false) {
934
+ event.preventDefault();
935
+ return;
936
+ }
937
+ }
938
+ nav.onKeyDown(event);
939
+ };
940
+ /** Undo/redo, range selection, fill, clear and tree keys. Returns true when it handled the key. */
941
+ const onRangeKeys = (event) => {
942
+ const target = event.target;
943
+ const cell = target.closest("[data-grid-cell]");
944
+ if (!cell || editing || target.closest("input, textarea, select, [contenteditable=\"true\"]")) return false;
945
+ const [row = 0, col = 0] = (cell.dataset.gridCell ?? "0:0").split(":").map(Number);
946
+ const mod = event.ctrlKey || event.metaKey;
947
+ const key = event.key.toLowerCase();
948
+ if (mod && !event.altKey && canEdit) {
949
+ if (key === "z" && !event.shiftKey) {
950
+ event.preventDefault();
951
+ replay("undo");
952
+ return true;
953
+ }
954
+ if (key === "z" && event.shiftKey || key === "y") {
955
+ event.preventDefault();
956
+ replay("redo");
957
+ return true;
958
+ }
959
+ }
960
+ if (row === 0) return false;
961
+ const item = bodyRows[row - 1];
962
+ if (tree && item?.kind === "row" && cell.getAttribute("role") === "rowheader" && !mod && !event.shiftKey && !event.altKey) {
963
+ const rtl = getComputedStyle(cell).direction === "rtl";
964
+ const forward = event.key === (rtl ? "ArrowLeft" : "ArrowRight");
965
+ const back = event.key === (rtl ? "ArrowRight" : "ArrowLeft");
966
+ if (forward && item.hasChildren && !item.expanded) {
967
+ event.preventDefault();
968
+ toggleExpanded(item.row.id);
969
+ return true;
970
+ }
971
+ if (back && item.hasChildren && item.expanded) {
972
+ event.preventDefault();
973
+ toggleExpanded(item.row.id);
974
+ return true;
975
+ }
976
+ const parent = back ? tree.parentOf.get(item.row.id) : null;
977
+ if (parent) {
978
+ const index = bodyRows.findIndex((candidate) => candidate.kind === "row" && candidate.row.id === parent);
979
+ if (index >= 0) {
980
+ event.preventDefault();
981
+ nav.moveTo({
982
+ row: index + 1,
983
+ col
984
+ });
985
+ return true;
986
+ }
987
+ }
988
+ }
989
+ if (!props.cellSelection) {
990
+ if (mod && key === "c") return false;
991
+ return false;
992
+ }
993
+ const arrows = {
994
+ ArrowUp: [-1, 0],
995
+ ArrowDown: [1, 0],
996
+ ArrowLeft: [0, -1],
997
+ ArrowRight: [0, 1]
998
+ };
999
+ if (event.shiftKey && !mod && !event.altKey && (arrows[event.key] || event.key === "Home" || event.key === "End")) {
1000
+ event.preventDefault();
1001
+ const rtl = getComputedStyle(cell).direction === "rtl";
1002
+ const from = range?.focus ?? {
1003
+ row,
1004
+ col
1005
+ };
1006
+ const anchor = range?.anchor ?? {
1007
+ row,
1008
+ col
1009
+ };
1010
+ const [dr, dc] = arrows[event.key] ?? [0, 0];
1011
+ const next = event.key === "Home" ? {
1012
+ row: from.row,
1013
+ col: 0
1014
+ } : event.key === "End" ? {
1015
+ row: from.row,
1016
+ col: visibleColumns.length - 1
1017
+ } : {
1018
+ row: Math.max(1, Math.min(bodyRows.length, from.row + dr)),
1019
+ col: Math.max(0, Math.min(visibleColumns.length - 1, from.col + (rtl ? -dc : dc)))
1020
+ };
1021
+ const nextRange = {
1022
+ anchor,
1023
+ focus: next
1024
+ };
1025
+ setRange(nextRange);
1026
+ announceRange(nextRange);
1027
+ nav.moveTo(next);
1028
+ return true;
1029
+ }
1030
+ if (mod && key === "a" && !event.shiftKey) {
1031
+ event.preventDefault();
1032
+ const all = {
1033
+ anchor: {
1034
+ row: 1,
1035
+ col: 0
1036
+ },
1037
+ focus: {
1038
+ row: bodyRows.length,
1039
+ col: visibleColumns.length - 1
1040
+ }
1041
+ };
1042
+ setRange(all);
1043
+ announceRange(all);
1044
+ return true;
1045
+ }
1046
+ if (mod && key === "d" && !event.shiftKey) {
1047
+ if (fillDown()) {
1048
+ event.preventDefault();
1049
+ return true;
1050
+ }
1051
+ return false;
1052
+ }
1053
+ if ((event.key === "Delete" || event.key === "Backspace") && range && (range.anchor.row !== range.focus.row || range.anchor.col !== range.focus.col)) {
1054
+ event.preventDefault();
1055
+ clearRange();
1056
+ return true;
1057
+ }
1058
+ if (event.key === "Escape" && range) {
1059
+ event.preventDefault();
1060
+ setRange(null);
1061
+ return true;
1062
+ }
1063
+ if (range && !event.shiftKey && (arrows[event.key] || event.key === "Home" || event.key === "End" || event.key === "PageUp" || event.key === "PageDown")) setRange(null);
1064
+ return false;
1065
+ };
1066
+ const cellPosition = (el) => {
1067
+ const cell = el?.closest?.("[data-grid-cell]");
1068
+ if (!cell || !gridRef.current?.contains(cell)) return null;
1069
+ const [row = 0, col = 0] = (cell.dataset.gridCell ?? "0:0").split(":").map(Number);
1070
+ return row > 0 && !cell.hasAttribute("aria-colspan") ? {
1071
+ row,
1072
+ col
1073
+ } : null;
1074
+ };
1075
+ const onPointerDown = (event) => {
1076
+ if (!props.cellSelection || event.button !== 0 || editing) return;
1077
+ if (event.target.closest("button, a, input, select, textarea, [role=\"checkbox\"]")) return;
1078
+ const pos = cellPosition(event.target);
1079
+ if (!pos) return;
1080
+ if (event.shiftKey) {
1081
+ event.preventDefault();
1082
+ const next = {
1083
+ anchor: range?.anchor ?? nav.active,
1084
+ focus: pos
1085
+ };
1086
+ setRange(next);
1087
+ announceRange(next);
1088
+ return;
1089
+ }
1090
+ dragAnchor.current = pos;
1091
+ setRange(null);
1092
+ };
1093
+ const onPointerMove = (event) => {
1094
+ const anchor = dragAnchor.current;
1095
+ if (!anchor || !(event.buttons & 1)) return;
1096
+ const pos = cellPosition(document.elementFromPoint(event.clientX, event.clientY));
1097
+ if (!pos || range && range.focus.row === pos.row && range.focus.col === pos.col) return;
1098
+ if (pos.row === anchor.row && pos.col === anchor.col && !range) return;
1099
+ setRange({
1100
+ anchor,
1101
+ focus: pos
1102
+ });
1103
+ };
1104
+ const onPointerUp = () => {
1105
+ if (dragAnchor.current && range) announceRange(range);
1106
+ dragAnchor.current = null;
1107
+ };
1108
+ const onCellDoubleClick = (event) => {
1109
+ const cell = event.target.closest("[data-grid-cell][data-editable]");
1110
+ if (cell && !editing) startEdit(cell.dataset.rowId ?? "", cell.dataset.columnKey ?? "");
1111
+ };
1112
+ const toggleGroup = (key) => setToggledGroups((prev) => {
1113
+ const next = new Set(prev);
1114
+ if (next.has(key)) next.delete(key);
1115
+ else next.add(key);
1116
+ return next;
1117
+ });
1118
+ const numberFormat = useMemo(() => new Intl.NumberFormat(locale, { maximumFractionDigits: 2 }), [locale]);
1119
+ const aggregatesFor = (group) => columns.flatMap((column) => {
1120
+ const kind = column.aggregate;
1121
+ if (!kind || visibility[column.key] === false) return [];
1122
+ const originals = group.rows.map((r) => r.original);
1123
+ if (typeof kind === "function") return [{
1124
+ key: column.key,
1125
+ label: labels.aggregate("custom", textOf(column)),
1126
+ text: kind(originals)
1127
+ }];
1128
+ if (kind === "count") return [{
1129
+ key: column.key,
1130
+ label: labels.aggregate("count", textOf(column)),
1131
+ text: numberFormat.format(originals.filter((r) => !isEmpty(valueOf(column, r))).length)
1132
+ }];
1133
+ const nums = originals.map((r) => valueOf(column, r)).filter((v) => typeof v === "number" && Number.isFinite(v));
1134
+ if (nums.length === 0) return [];
1135
+ const n = kind === "sum" ? nums.reduce((a, b) => a + b, 0) : kind === "avg" ? nums.reduce((a, b) => a + b, 0) / nums.length : kind === "min" ? Math.min(...nums) : Math.max(...nums);
1136
+ return [{
1137
+ key: column.key,
1138
+ label: labels.aggregate(kind, textOf(column)),
1139
+ text: column.formatAggregate ? column.formatAggregate(n) : numberFormat.format(n)
1140
+ }];
1141
+ });
1142
+ const groupLabel = (group) => {
1143
+ if (!groupColumn) return null;
1144
+ if (isEmpty(group.value)) return labels.emptyGroup;
1145
+ const first = group.rows[0];
1146
+ return groupColumn.cell && first ? groupColumn.cell(first.original) : group.value instanceof Date ? group.value.toLocaleDateString(locale) : String(group.value);
1147
+ };
1148
+ const exportColumns = () => visibleColumns.flatMap((c) => {
1149
+ const def = c.id === SELECT_COL || c.id === DETAIL_COL ? void 0 : columns.find((d) => d.key === c.id);
1150
+ return def ? [def] : [];
1151
+ });
1152
+ const rowsFor = (scope = "view") => {
1153
+ if (scope === "all") return [...rows];
1154
+ const view = table.getPrePaginatedRowModel().rows;
1155
+ const ordered = grouping ? allItemsLeafOrder(allItems, leafRows) : tree ? allItems.flatMap((item) => item.kind === "row" ? [item.row] : []) : view;
1156
+ return scope === "selected" ? ordered.filter((r) => selected.includes(r.id)).map((r) => r.original) : ordered.map((r) => r.original);
1157
+ };
1158
+ const getColumnLayout = () => snapshotColumnLayout(layout, leadingColumns);
1159
+ const restoreView = (view) => {
1160
+ if (view.version !== 1) return false;
1161
+ const validSorts = view.sorts.filter(({ column }) => columnByKey(column)?.sortable);
1162
+ const validFilters = view.filters.filter(({ column }) => columnByKey(column));
1163
+ const nextVisibility = Object.fromEntries(Object.entries(view.columnVisibility).filter(([key]) => {
1164
+ const column = columnByKey(key);
1165
+ return column && column.hideable !== false;
1166
+ }));
1167
+ const nextWidths = Object.fromEntries(Object.entries(view.columnWidths).filter(([key, width]) => columnByKey(key) && Number.isFinite(width) && width > 0));
1168
+ const nextGrouping = (view.grouping ?? (view.groupBy ? [view.groupBy] : [])).filter((key) => columnByKey(key));
1169
+ const nextLayout = snapshotColumnLayout(arrangeColumns(columns.map((column) => column.key), view.columnLayout), leadingColumns);
1170
+ setColumnLayout(nextLayout);
1171
+ setVisibility(nextVisibility);
1172
+ setWidths(nextWidths);
1173
+ if (multiSort) setSorts(validSorts);
1174
+ else setSort(validSorts[0] ?? null);
1175
+ setFilters(validFilters);
1176
+ setSearch(view.search);
1177
+ setGroupKeys(nextGrouping);
1178
+ return true;
1179
+ };
1180
+ useImperativeHandle(props.apiRef, () => ({
1181
+ getRows: rowsFor,
1182
+ getFilters: () => filters,
1183
+ setFilters,
1184
+ getExportColumns: exportColumns,
1185
+ getColumnLayout,
1186
+ setColumnLayout,
1187
+ getView: () => ({
1188
+ version: 1,
1189
+ columnLayout: getColumnLayout(),
1190
+ columnVisibility: { ...visibility },
1191
+ columnWidths: { ...widths },
1192
+ sorts: sortOrder.map((entry) => ({ ...entry })),
1193
+ filters: filters.map((entry) => ({ ...entry })),
1194
+ search,
1195
+ groupBy: groupColumn?.key ?? null,
1196
+ grouping: groupColumns.map((column) => column.key)
1197
+ }),
1198
+ restoreView,
1199
+ undo: () => replay("undo"),
1200
+ redo: () => replay("redo"),
1201
+ canUndo: () => history.current.undo.length > 0,
1202
+ canRedo: () => history.current.redo.length > 0,
1203
+ expandAll: () => setExpandedIds(parentIds),
1204
+ collapseAll: () => setExpandedIds([]),
1205
+ toCsv: ({ scope, ...options } = {}) => toCsv(exportColumns(), rowsFor(scope), options),
1206
+ downloadCsv: (filename = "export.csv", { scope, ...options } = {}) => {
1207
+ const list = rowsFor(scope);
1208
+ downloadText(toCsv(exportColumns(), list, options), filename);
1209
+ setAnnouncement(labels.exported(list.length));
1210
+ }
1211
+ }));
1212
+ const nav = useGridNavigation({
1213
+ gridRef,
1214
+ rowCount: bodyRows.length + 1,
1215
+ colCount: visibleColumns.length,
1216
+ pageRows: Math.max(1, Math.floor((typeof height === "number" ? height : 400) / rowHeight) - 1),
1217
+ ensureRendered,
1218
+ onHeaderKey
1219
+ });
1220
+ const { moveTo } = nav;
1221
+ useEffect(() => {
1222
+ const move = pendingColumn.current;
1223
+ if (!move || visibleColumns[move.index]?.id !== move.key) return;
1224
+ pendingColumn.current = null;
1225
+ const def = columnByKey(move.key);
1226
+ setAnnouncement(labels.columnMoved(def ? textOf(def) : move.key, move.index + 1));
1227
+ const doc = gridRef.current?.ownerDocument;
1228
+ if (doc && (doc.activeElement === move.focused || doc.activeElement === doc.body)) moveTo({
1229
+ row: 0,
1230
+ col: move.index
1231
+ });
1232
+ }, [
1233
+ visibleColumns,
1234
+ columnByKey,
1235
+ labels,
1236
+ moveTo
1237
+ ]);
1238
+ const flexColumn = visibleColumns.reduce((last, column, index) => pinned.has(column.id) ? last : index, -1);
1239
+ const template = visibleColumns.map((c, i) => i === flexColumn ? `minmax(${c.getSize()}px, 1fr)` : `${c.getSize()}px`).join(" ");
1240
+ const renderedColumns = virtualColumns ? /* @__PURE__ */ new Set([
1241
+ ...columnVirtualizer.getVirtualItems().map((v) => v.index),
1242
+ ...visibleColumns.flatMap((c, i) => pinned.has(c.id) ? [i] : []),
1243
+ nav.active.col
1244
+ ]) : null;
1245
+ const shows = (col) => !renderedColumns || renderedColumns.has(col);
1246
+ const place = (col) => renderedColumns ? { gridColumn: col + 1 } : void 0;
1247
+ const allSelected = table.getIsAllPageRowsSelected();
1248
+ const someSelected = table.getIsSomePageRowsSelected();
1249
+ return /* @__PURE__ */ jsxs("div", {
1250
+ ref,
1251
+ className: cx(data_grid_module_default.root, className),
1252
+ "data-density": density,
1253
+ "data-striped": dataAttr(striped),
1254
+ children: [
1255
+ /* @__PURE__ */ jsx("div", {
1256
+ ref: scrollRef,
1257
+ className: data_grid_module_default.scroller,
1258
+ style: height !== void 0 ? { height } : void 0,
1259
+ "data-scroll-y": dataAttr(height !== void 0),
1260
+ children: /* @__PURE__ */ jsxs("div", {
1261
+ ref: gridRef,
1262
+ role: tree ? "treegrid" : "grid",
1263
+ "aria-label": ariaLabel,
1264
+ "aria-labelledby": ariaLabelledBy,
1265
+ "aria-rowcount": total + 1,
1266
+ "aria-colcount": visibleColumns.length,
1267
+ "aria-multiselectable": selectable || props.cellSelection || void 0,
1268
+ "aria-busy": loading || void 0,
1269
+ className: data_grid_module_default.grid,
1270
+ style: {
1271
+ "--_cols": template,
1272
+ "--_row-h": `${rowHeight}px`
1273
+ },
1274
+ onKeyDown: onGridKeyDown,
1275
+ onFocus: (event) => {
1276
+ nav.onFocus(event);
1277
+ const pos = cellPosition(event.target);
1278
+ if (range && pos && (pos.row !== range.focus.row || pos.col !== range.focus.col)) setRange(null);
1279
+ },
1280
+ onDoubleClick: onCellDoubleClick,
1281
+ onCopy,
1282
+ onPaste,
1283
+ onPointerDown,
1284
+ onPointerMove,
1285
+ onPointerUp,
1286
+ "data-cell-selection": dataAttr(props.cellSelection),
1287
+ children: [/* @__PURE__ */ jsx("div", {
1288
+ role: "rowgroup",
1289
+ className: data_grid_module_default.head,
1290
+ children: /* @__PURE__ */ jsx("div", {
1291
+ role: "row",
1292
+ "aria-rowindex": 1,
1293
+ className: data_grid_module_default.row,
1294
+ children: visibleColumns.map((column, col) => {
1295
+ if (!shows(col)) return null;
1296
+ const def = columns.find((c) => c.key === column.id);
1297
+ const pin = pinned.get(column.id);
1298
+ const sorted = column.getIsSorted();
1299
+ const priority = sortPriorities.get(column.id);
1300
+ const priorityId = multiSort && priority !== void 0 ? `${id}-priority-${col}` : void 0;
1301
+ const sortDirection = sorted === "asc" ? "ascending" : sorted === "desc" ? "descending" : "none";
1302
+ const header = table.getHeaderGroups()[0]?.headers.find((h) => h.column.id === column.id);
1303
+ return /* @__PURE__ */ jsxs("div", {
1304
+ role: "columnheader",
1305
+ "aria-colindex": col + 1,
1306
+ "aria-sort": column.getCanSort() && (!multiSort || priority === 1) ? sortDirection : void 0,
1307
+ "data-grid-cell": `0:${col}`,
1308
+ className: data_grid_module_default.headerCell,
1309
+ "data-pinned": pin?.side,
1310
+ style: {
1311
+ ...place(col),
1312
+ ...pin && { "--_pin-offset": `${pin.offset}px` }
1313
+ },
1314
+ "data-align": def?.align ?? "start",
1315
+ children: [column.id === DETAIL_COL ? /* @__PURE__ */ jsx(VisuallyHidden, { children: labels.detailsColumn }) : column.id === SELECT_COL ? /* @__PURE__ */ jsx(Checkbox, {
1316
+ size: "sm",
1317
+ "aria-label": labels.selectAll,
1318
+ checked: allSelected,
1319
+ indeterminate: someSelected && !allSelected,
1320
+ onCheckedChange: (v) => table.toggleAllPageRowsSelected(v)
1321
+ }) : column.getCanSort() ? /* @__PURE__ */ jsxs("button", {
1322
+ type: "button",
1323
+ className: data_grid_module_default.sortButton,
1324
+ "data-active": dataAttr(Boolean(sorted)),
1325
+ "aria-describedby": multiSort ? [priorityId, `${id}-multi-sort`].filter(Boolean).join(" ") : void 0,
1326
+ onClick: (event) => toggleSortFor(col, event.shiftKey),
1327
+ children: [
1328
+ /* @__PURE__ */ jsx("span", { children: def?.header }),
1329
+ /* @__PURE__ */ jsx(SortIcon, { direction: sorted }),
1330
+ priorityId && priority !== void 0 ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("span", {
1331
+ className: data_grid_module_default.sortPriority,
1332
+ "aria-hidden": "true",
1333
+ children: priority
1334
+ }), /* @__PURE__ */ jsxs("span", {
1335
+ id: priorityId,
1336
+ hidden: true,
1337
+ children: [
1338
+ labels.sortPriority(priority),
1339
+ ". ",
1340
+ sorted === "asc" ? labels.sortedAscending(def ? textOf(def) : column.id) : labels.sortedDescending(def ? textOf(def) : column.id)
1341
+ ]
1342
+ })] }) : null
1343
+ ]
1344
+ }) : /* @__PURE__ */ jsx("span", {
1345
+ className: data_grid_module_default.headerText,
1346
+ children: def?.header
1347
+ }), column.getCanResize() && header ? /* @__PURE__ */ jsx("div", {
1348
+ "aria-hidden": "true",
1349
+ className: data_grid_module_default.resizer,
1350
+ "data-resizing": dataAttr(column.getIsResizing()),
1351
+ onMouseDown: header.getResizeHandler(),
1352
+ onTouchStart: header.getResizeHandler(),
1353
+ onDoubleClick: () => column.resetSize()
1354
+ }) : null]
1355
+ }, column.id);
1356
+ })
1357
+ })
1358
+ }), /* @__PURE__ */ jsx("div", {
1359
+ role: "rowgroup",
1360
+ className: data_grid_module_default.body,
1361
+ style: virtual ? { height: virtualizer.getTotalSize() } : void 0,
1362
+ "data-virtual": dataAttr(virtual),
1363
+ children: bodyRows.length === 0 ? /* @__PURE__ */ jsx("div", {
1364
+ role: "row",
1365
+ "aria-rowindex": 2,
1366
+ className: data_grid_module_default.row,
1367
+ children: /* @__PURE__ */ jsx("div", {
1368
+ role: "gridcell",
1369
+ "aria-colindex": 1,
1370
+ className: data_grid_module_default.empty,
1371
+ "data-grid-cell": "1:0",
1372
+ style: { gridColumn: "1 / -1" },
1373
+ children: loading ? /* @__PURE__ */ jsx(Spinner, {
1374
+ size: "sm",
1375
+ label: labels.loading
1376
+ }) : emptyState
1377
+ })
1378
+ }) : rendered.map(({ index, start }) => {
1379
+ const item = bodyRows[index];
1380
+ if (!item) return null;
1381
+ const position = virtual ? {
1382
+ position: "absolute",
1383
+ insetInline: 0,
1384
+ top: 0,
1385
+ transform: `translateY(${start}px)`
1386
+ } : void 0;
1387
+ const measure = virtual && hasDetail ? {
1388
+ "data-index": index,
1389
+ ref: virtualizer.measureElement
1390
+ } : {};
1391
+ if (item.kind === "detail") {
1392
+ const detailId = `${id}-detail-${item.row.id}`;
1393
+ return /* @__PURE__ */ jsx("div", {
1394
+ ...measure,
1395
+ role: "row",
1396
+ id: detailId,
1397
+ "aria-rowindex": firstRowIndex + index + 2,
1398
+ className: cx(data_grid_module_default.row, data_grid_module_default.detailRow),
1399
+ style: position,
1400
+ children: /* @__PURE__ */ jsx("div", {
1401
+ role: "gridcell",
1402
+ "aria-colindex": 1,
1403
+ "aria-colspan": visibleColumns.length,
1404
+ "data-grid-cell": `${index + 1}:0`,
1405
+ "data-grid-content": "",
1406
+ className: data_grid_module_default.detailCell,
1407
+ style: { gridColumn: "1 / -1" },
1408
+ children: props.renderDetail?.(item.row.original)
1409
+ })
1410
+ }, `detail-${item.row.id}`);
1411
+ }
1412
+ if (item.kind === "group") {
1413
+ const aggregates = aggregatesFor(item);
1414
+ return /* @__PURE__ */ jsx("div", {
1415
+ ...measure,
1416
+ role: "row",
1417
+ "aria-rowindex": firstRowIndex + index + 2,
1418
+ className: cx(data_grid_module_default.row, data_grid_module_default.groupRow),
1419
+ style: position,
1420
+ "data-depth": item.depth,
1421
+ children: /* @__PURE__ */ jsxs("div", {
1422
+ role: "gridcell",
1423
+ "aria-colindex": 1,
1424
+ "aria-colspan": visibleColumns.length,
1425
+ "data-grid-cell": `${index + 1}:0`,
1426
+ className: data_grid_module_default.groupCell,
1427
+ style: {
1428
+ gridColumn: "1 / -1",
1429
+ "--_depth": item.depth
1430
+ },
1431
+ children: [/* @__PURE__ */ jsxs("button", {
1432
+ type: "button",
1433
+ className: data_grid_module_default.groupToggle,
1434
+ "aria-expanded": item.expanded,
1435
+ onClick: () => toggleGroup(item.key),
1436
+ children: [
1437
+ /* @__PURE__ */ jsx(ChevronIcon, {}),
1438
+ /* @__PURE__ */ jsxs("span", {
1439
+ className: data_grid_module_default.groupLabel,
1440
+ children: [groupColumns.length > 1 ? `${textOf(item.column)}: ` : null, groupLabel(item)]
1441
+ }),
1442
+ /* @__PURE__ */ jsx("span", {
1443
+ className: data_grid_module_default.groupCount,
1444
+ children: labels.groupCount(item.rows.length)
1445
+ })
1446
+ ]
1447
+ }), aggregates.length > 0 && /* @__PURE__ */ jsx("span", {
1448
+ className: data_grid_module_default.aggregates,
1449
+ children: aggregates.map((a) => /* @__PURE__ */ jsxs("span", {
1450
+ className: data_grid_module_default.aggregate,
1451
+ children: [
1452
+ /* @__PURE__ */ jsx("span", {
1453
+ className: data_grid_module_default.aggregateLabel,
1454
+ children: a.label
1455
+ }),
1456
+ " ",
1457
+ a.text
1458
+ ]
1459
+ }, a.key))
1460
+ })]
1461
+ })
1462
+ }, `group-${item.key}`);
1463
+ }
1464
+ const row = item.row;
1465
+ const isSelected = row.getIsSelected();
1466
+ const headerCellId = `${id}-rh-${row.id}`;
1467
+ return /* @__PURE__ */ jsx("div", {
1468
+ ...measure,
1469
+ role: "row",
1470
+ "aria-rowindex": firstRowIndex + index + 2,
1471
+ "aria-level": tree ? (item.depth ?? 0) + 1 : void 0,
1472
+ "aria-expanded": tree && item.hasChildren ? Boolean(item.expanded) : void 0,
1473
+ "aria-setsize": tree ? item.setSize : void 0,
1474
+ "aria-posinset": tree ? item.posInSet : void 0,
1475
+ "aria-selected": selectable ? isSelected : void 0,
1476
+ className: data_grid_module_default.row,
1477
+ "data-selected": dataAttr(selectable && isSelected),
1478
+ "data-odd": dataAttr(index % 2 === 1),
1479
+ style: position,
1480
+ children: row.getVisibleCells().map((cell, col) => {
1481
+ if (!shows(col)) return null;
1482
+ const def = columns.find((c) => c.key === cell.column.id);
1483
+ const pin = pinned.get(cell.column.id);
1484
+ const isHeader = cell.column.id === rowHeaderKey;
1485
+ const editable = isEditable(def, row.original);
1486
+ const isEditing = Boolean(def && editing && editing.rowId === row.id && editing.column === def.key);
1487
+ const selectedCell = props.cellSelection ? inRange(index + 1, col) : false;
1488
+ const detailOpen = hasDetail && detailIds.includes(row.id);
1489
+ return /* @__PURE__ */ jsxs("div", {
1490
+ role: isHeader ? "rowheader" : "gridcell",
1491
+ id: isHeader ? headerCellId : void 0,
1492
+ "aria-colindex": col + 1,
1493
+ "aria-readonly": def && def.editable && !editable ? true : void 0,
1494
+ "data-grid-cell": `${index + 1}:${col}`,
1495
+ "data-editable": dataAttr(editable),
1496
+ "data-editing": dataAttr(isEditing),
1497
+ "data-row-id": editable ? row.id : void 0,
1498
+ "data-column-key": editable ? def?.key : void 0,
1499
+ "aria-selected": props.cellSelection && def ? selectedCell : void 0,
1500
+ "data-in-range": dataAttr(selectedCell),
1501
+ className: cx(data_grid_module_default.cell, isHeader && data_grid_module_default.rowHeader),
1502
+ "data-pinned": pin?.side,
1503
+ "data-depth": tree && isHeader ? item.depth ?? 0 : void 0,
1504
+ style: {
1505
+ ...place(col),
1506
+ ...pin && { "--_pin-offset": `${pin.offset}px` },
1507
+ ...tree && isHeader ? { "--_depth": item.depth ?? 0 } : null
1508
+ },
1509
+ "data-align": def?.align ?? "start",
1510
+ children: [tree && isHeader ? /* @__PURE__ */ jsx("span", {
1511
+ className: data_grid_module_default.treeToggle,
1512
+ "aria-hidden": "true",
1513
+ "data-leaf": dataAttr(!item.hasChildren),
1514
+ "data-expanded": dataAttr(item.expanded),
1515
+ onClick: item.hasChildren ? () => toggleExpanded(row.id) : void 0,
1516
+ children: item.hasChildren ? /* @__PURE__ */ jsx(ChevronIcon, {}) : null
1517
+ }) : null, cell.column.id === DETAIL_COL ? /* @__PURE__ */ jsx("button", {
1518
+ type: "button",
1519
+ className: data_grid_module_default.detailToggle,
1520
+ "aria-expanded": detailOpen,
1521
+ "aria-controls": detailOpen ? `${id}-detail-${row.id}` : void 0,
1522
+ "aria-label": labels.showDetails(rowName(row.original)),
1523
+ onClick: () => toggleDetail(row.id),
1524
+ children: /* @__PURE__ */ jsx(ChevronIcon, {})
1525
+ }) : cell.column.id === SELECT_COL ? /* @__PURE__ */ jsx(Checkbox, {
1526
+ size: "sm",
1527
+ id: `${id}-sel-${row.id}`,
1528
+ "aria-label": labels.selectRow,
1529
+ "aria-labelledby": `${id}-sel-${row.id} ${headerCellId}`,
1530
+ checked: isSelected,
1531
+ disabled: !row.getCanSelect(),
1532
+ onCheckedChange: (v) => row.toggleSelected(v)
1533
+ }) : isEditing && def && editing ? /* @__PURE__ */ jsx(CellEditor, {
1534
+ column: def,
1535
+ row: row.original,
1536
+ value: valueOf(def, row.original),
1537
+ state: editing,
1538
+ label: labels.editCell(textOf(def), rowName(row.original)),
1539
+ errorId: `${id}-edit-error`,
1540
+ savingLabel: labels.saving,
1541
+ onDraftChange: (draft) => setEditing({
1542
+ ...editing,
1543
+ draft,
1544
+ error: void 0
1545
+ }),
1546
+ onCommit: commitEdit,
1547
+ onCancel: cancelEdit
1548
+ }) : /* @__PURE__ */ jsx(table.FlexRender, { cell })]
1549
+ }, cell.id);
1550
+ })
1551
+ }, row.id);
1552
+ })
1553
+ })]
1554
+ })
1555
+ }),
1556
+ pageSize && pageCount > 1 ? /* @__PURE__ */ jsxs("div", {
1557
+ className: data_grid_module_default.footer,
1558
+ children: [/* @__PURE__ */ jsx("span", {
1559
+ className: data_grid_module_default.footerText,
1560
+ children: labels.results(total)
1561
+ }), /* @__PURE__ */ jsx(Pagination, {
1562
+ size: "sm",
1563
+ "aria-label": labels.pagination(ariaLabel),
1564
+ pageCount,
1565
+ page: Math.min(page, pageCount),
1566
+ onPageChange: setPage
1567
+ })]
1568
+ }) : null,
1569
+ multiSort && /* @__PURE__ */ jsx(VisuallyHidden, {
1570
+ id: `${id}-multi-sort`,
1571
+ children: labels.multiSortHint
1572
+ }),
1573
+ /* @__PURE__ */ jsx(VisuallyHidden, {
1574
+ role: "status",
1575
+ "aria-live": "polite",
1576
+ children: announcement
1577
+ })
1578
+ ]
1579
+ });
1580
+ }
1581
+ /** A page of items: `size` rows (or groups) per page; detail rows stay with their row. */
1582
+ function pageItems(items, first, size, countAll) {
1583
+ if (countAll && !items.some((item) => item.kind === "detail")) return items.slice(first, first + size);
1584
+ const out = [];
1585
+ let index = 0;
1586
+ for (const item of items) {
1587
+ if (item.kind === "detail") {
1588
+ if (index > first && index <= first + size) out.push(item);
1589
+ continue;
1590
+ }
1591
+ if (index >= first && index < first + size) out.push(item);
1592
+ index++;
1593
+ }
1594
+ return out;
1595
+ }
1596
+ /** Leaf rows in the order the grouped view shows them (collapsed groups included). */
1597
+ function allItemsLeafOrder(items, leafRows) {
1598
+ const out = [];
1599
+ for (const item of items) if (item.kind === "group" && item.depth === 0) out.push(...item.rows);
1600
+ return out.length ? out : leafRows;
1601
+ }
1602
+ /**
1603
+ * An interactive data grid (`role="grid"`): one tab stop and arrow-key navigation between cells,
1604
+ * sorting, search, pagination, row selection, resizable and hideable columns, and row
1605
+ * virtualization for large data sets. Built on TanStack Table; the API is ReactLoom's own.
1606
+ */
1607
+ var DataGrid = /*#__PURE__*/ forwardRef(DataGridInner);
1608
+ export { DataGrid };
1609
+
1610
+ //# sourceMappingURL=data-grid.js.map