@tanstack/react-table 8.6.0 → 8.7.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.
@@ -1,3446 +0,0 @@
1
- /**
2
- * react-table
3
- *
4
- * Copyright (c) TanStack
5
- *
6
- * This source code is licensed under the MIT license found in the
7
- * LICENSE.md file in the root directory of this source tree.
8
- *
9
- * @license MIT
10
- */
11
- 'use strict';
12
-
13
- Object.defineProperty(exports, '__esModule', { value: true });
14
-
15
- /**
16
- * table-core
17
- *
18
- * Copyright (c) TanStack
19
- *
20
- * This source code is licensed under the MIT license found in the
21
- * LICENSE.md file in the root directory of this source tree.
22
- *
23
- * @license MIT
24
- */
25
- // Is this type a tuple?
26
-
27
- // If this type is a tuple, what indices are allowed?
28
-
29
- ///
30
-
31
- function functionalUpdate(updater, input) {
32
- return typeof updater === 'function' ? updater(input) : updater;
33
- }
34
- function noop() {
35
- //
36
- }
37
- function makeStateUpdater(key, instance) {
38
- return updater => {
39
- instance.setState(old => {
40
- return {
41
- ...old,
42
- [key]: functionalUpdate(updater, old[key])
43
- };
44
- });
45
- };
46
- }
47
- function isFunction(d) {
48
- return d instanceof Function;
49
- }
50
- function flattenBy(arr, getChildren) {
51
- const flat = [];
52
- const recurse = subArr => {
53
- subArr.forEach(item => {
54
- flat.push(item);
55
- const children = getChildren(item);
56
- if (children != null && children.length) {
57
- recurse(children);
58
- }
59
- });
60
- };
61
- recurse(arr);
62
- return flat;
63
- }
64
- function memo(getDeps, fn, opts) {
65
- let deps = [];
66
- let result;
67
- return () => {
68
- let depTime;
69
- if (opts.key && opts.debug) depTime = Date.now();
70
- const newDeps = getDeps();
71
- const depsChanged = newDeps.length !== deps.length || newDeps.some((dep, index) => deps[index] !== dep);
72
- if (!depsChanged) {
73
- return result;
74
- }
75
- deps = newDeps;
76
- let resultTime;
77
- if (opts.key && opts.debug) resultTime = Date.now();
78
- result = fn(...newDeps);
79
- opts == null ? void 0 : opts.onChange == null ? void 0 : opts.onChange(result);
80
- if (opts.key && opts.debug) {
81
- if (opts != null && opts.debug()) {
82
- const depEndTime = Math.round((Date.now() - depTime) * 100) / 100;
83
- const resultEndTime = Math.round((Date.now() - resultTime) * 100) / 100;
84
- const resultFpsPercentage = resultEndTime / 16;
85
- const pad = (str, num) => {
86
- str = String(str);
87
- while (str.length < num) {
88
- str = ' ' + str;
89
- }
90
- return str;
91
- };
92
- console.info(`%c⏱ ${pad(resultEndTime, 5)} /${pad(depEndTime, 5)} ms`, `
93
- font-size: .6rem;
94
- font-weight: bold;
95
- color: hsl(${Math.max(0, Math.min(120 - 120 * resultFpsPercentage, 120))}deg 100% 31%);`, opts == null ? void 0 : opts.key);
96
- }
97
- }
98
- return result;
99
- };
100
- }
101
-
102
- function createColumn(table, columnDef, depth, parent) {
103
- const defaultColumn = table._getDefaultColumnDef();
104
- const resolvedColumnDef = {
105
- ...defaultColumn,
106
- ...columnDef
107
- };
108
- const accessorKey = resolvedColumnDef.accessorKey;
109
- let id = resolvedColumnDef.id ?? (accessorKey ? accessorKey.replace('.', '_') : undefined) ?? (typeof resolvedColumnDef.header === 'string' ? resolvedColumnDef.header : undefined);
110
- let accessorFn;
111
- if (resolvedColumnDef.accessorFn) {
112
- accessorFn = resolvedColumnDef.accessorFn;
113
- } else if (accessorKey) {
114
- // Support deep accessor keys
115
- if (accessorKey.includes('.')) {
116
- accessorFn = originalRow => {
117
- let result = originalRow;
118
- for (const key of accessorKey.split('.')) {
119
- result = result[key];
120
- if (process.env.NODE_ENV !== 'production' && result === undefined) {
121
- throw new Error(`"${key}" in deeply nested key "${accessorKey}" returned undefined.`);
122
- }
123
- }
124
- return result;
125
- };
126
- } else {
127
- accessorFn = originalRow => originalRow[resolvedColumnDef.accessorKey];
128
- }
129
- }
130
- if (!id) {
131
- if (process.env.NODE_ENV !== 'production') {
132
- throw new Error(resolvedColumnDef.accessorFn ? `Columns require an id when using an accessorFn` : `Columns require an id when using a non-string header`);
133
- }
134
- throw new Error();
135
- }
136
- let column = {
137
- id: `${String(id)}`,
138
- accessorFn,
139
- parent: parent,
140
- depth,
141
- columnDef: resolvedColumnDef,
142
- columns: [],
143
- getFlatColumns: memo(() => [true], () => {
144
- var _column$columns;
145
- return [column, ...((_column$columns = column.columns) == null ? void 0 : _column$columns.flatMap(d => d.getFlatColumns()))];
146
- }, {
147
- key: process.env.NODE_ENV === 'production' && 'column.getFlatColumns',
148
- debug: () => table.options.debugAll ?? table.options.debugColumns
149
- }),
150
- getLeafColumns: memo(() => [table._getOrderColumnsFn()], orderColumns => {
151
- var _column$columns2;
152
- if ((_column$columns2 = column.columns) != null && _column$columns2.length) {
153
- let leafColumns = column.columns.flatMap(column => column.getLeafColumns());
154
- return orderColumns(leafColumns);
155
- }
156
- return [column];
157
- }, {
158
- key: process.env.NODE_ENV === 'production' && 'column.getLeafColumns',
159
- debug: () => table.options.debugAll ?? table.options.debugColumns
160
- })
161
- };
162
- column = table._features.reduce((obj, feature) => {
163
- return Object.assign(obj, feature.createColumn == null ? void 0 : feature.createColumn(column, table));
164
- }, column);
165
-
166
- // Yes, we have to convert table to uknown, because we know more than the compiler here.
167
- return column;
168
- }
169
-
170
- //
171
-
172
- function createHeader(table, column, options) {
173
- const id = options.id ?? column.id;
174
- let header = {
175
- id,
176
- column,
177
- index: options.index,
178
- isPlaceholder: !!options.isPlaceholder,
179
- placeholderId: options.placeholderId,
180
- depth: options.depth,
181
- subHeaders: [],
182
- colSpan: 0,
183
- rowSpan: 0,
184
- headerGroup: null,
185
- getLeafHeaders: () => {
186
- const leafHeaders = [];
187
- const recurseHeader = h => {
188
- if (h.subHeaders && h.subHeaders.length) {
189
- h.subHeaders.map(recurseHeader);
190
- }
191
- leafHeaders.push(h);
192
- };
193
- recurseHeader(header);
194
- return leafHeaders;
195
- },
196
- getContext: () => ({
197
- table,
198
- header: header,
199
- column
200
- })
201
- };
202
- table._features.forEach(feature => {
203
- Object.assign(header, feature.createHeader == null ? void 0 : feature.createHeader(header, table));
204
- });
205
- return header;
206
- }
207
- const Headers = {
208
- createTable: table => {
209
- return {
210
- // Header Groups
211
-
212
- getHeaderGroups: memo(() => [table.getAllColumns(), table.getVisibleLeafColumns(), table.getState().columnPinning.left, table.getState().columnPinning.right], (allColumns, leafColumns, left, right) => {
213
- const leftColumns = (left == null ? void 0 : left.map(columnId => leafColumns.find(d => d.id === columnId)).filter(Boolean)) ?? [];
214
- const rightColumns = (right == null ? void 0 : right.map(columnId => leafColumns.find(d => d.id === columnId)).filter(Boolean)) ?? [];
215
- const centerColumns = leafColumns.filter(column => !(left != null && left.includes(column.id)) && !(right != null && right.includes(column.id)));
216
- const headerGroups = buildHeaderGroups(allColumns, [...leftColumns, ...centerColumns, ...rightColumns], table);
217
- return headerGroups;
218
- }, {
219
- key: process.env.NODE_ENV === 'development' && 'getHeaderGroups',
220
- debug: () => table.options.debugAll ?? table.options.debugHeaders
221
- }),
222
- getCenterHeaderGroups: memo(() => [table.getAllColumns(), table.getVisibleLeafColumns(), table.getState().columnPinning.left, table.getState().columnPinning.right], (allColumns, leafColumns, left, right) => {
223
- leafColumns = leafColumns.filter(column => !(left != null && left.includes(column.id)) && !(right != null && right.includes(column.id)));
224
- return buildHeaderGroups(allColumns, leafColumns, table, 'center');
225
- }, {
226
- key: process.env.NODE_ENV === 'development' && 'getCenterHeaderGroups',
227
- debug: () => table.options.debugAll ?? table.options.debugHeaders
228
- }),
229
- getLeftHeaderGroups: memo(() => [table.getAllColumns(), table.getVisibleLeafColumns(), table.getState().columnPinning.left], (allColumns, leafColumns, left) => {
230
- const orderedLeafColumns = (left == null ? void 0 : left.map(columnId => leafColumns.find(d => d.id === columnId)).filter(Boolean)) ?? [];
231
- return buildHeaderGroups(allColumns, orderedLeafColumns, table, 'left');
232
- }, {
233
- key: process.env.NODE_ENV === 'development' && 'getLeftHeaderGroups',
234
- debug: () => table.options.debugAll ?? table.options.debugHeaders
235
- }),
236
- getRightHeaderGroups: memo(() => [table.getAllColumns(), table.getVisibleLeafColumns(), table.getState().columnPinning.right], (allColumns, leafColumns, right) => {
237
- const orderedLeafColumns = (right == null ? void 0 : right.map(columnId => leafColumns.find(d => d.id === columnId)).filter(Boolean)) ?? [];
238
- return buildHeaderGroups(allColumns, orderedLeafColumns, table, 'right');
239
- }, {
240
- key: process.env.NODE_ENV === 'development' && 'getRightHeaderGroups',
241
- debug: () => table.options.debugAll ?? table.options.debugHeaders
242
- }),
243
- // Footer Groups
244
-
245
- getFooterGroups: memo(() => [table.getHeaderGroups()], headerGroups => {
246
- return [...headerGroups].reverse();
247
- }, {
248
- key: process.env.NODE_ENV === 'development' && 'getFooterGroups',
249
- debug: () => table.options.debugAll ?? table.options.debugHeaders
250
- }),
251
- getLeftFooterGroups: memo(() => [table.getLeftHeaderGroups()], headerGroups => {
252
- return [...headerGroups].reverse();
253
- }, {
254
- key: process.env.NODE_ENV === 'development' && 'getLeftFooterGroups',
255
- debug: () => table.options.debugAll ?? table.options.debugHeaders
256
- }),
257
- getCenterFooterGroups: memo(() => [table.getCenterHeaderGroups()], headerGroups => {
258
- return [...headerGroups].reverse();
259
- }, {
260
- key: process.env.NODE_ENV === 'development' && 'getCenterFooterGroups',
261
- debug: () => table.options.debugAll ?? table.options.debugHeaders
262
- }),
263
- getRightFooterGroups: memo(() => [table.getRightHeaderGroups()], headerGroups => {
264
- return [...headerGroups].reverse();
265
- }, {
266
- key: process.env.NODE_ENV === 'development' && 'getRightFooterGroups',
267
- debug: () => table.options.debugAll ?? table.options.debugHeaders
268
- }),
269
- // Flat Headers
270
-
271
- getFlatHeaders: memo(() => [table.getHeaderGroups()], headerGroups => {
272
- return headerGroups.map(headerGroup => {
273
- return headerGroup.headers;
274
- }).flat();
275
- }, {
276
- key: process.env.NODE_ENV === 'development' && 'getFlatHeaders',
277
- debug: () => table.options.debugAll ?? table.options.debugHeaders
278
- }),
279
- getLeftFlatHeaders: memo(() => [table.getLeftHeaderGroups()], left => {
280
- return left.map(headerGroup => {
281
- return headerGroup.headers;
282
- }).flat();
283
- }, {
284
- key: process.env.NODE_ENV === 'development' && 'getLeftFlatHeaders',
285
- debug: () => table.options.debugAll ?? table.options.debugHeaders
286
- }),
287
- getCenterFlatHeaders: memo(() => [table.getCenterHeaderGroups()], left => {
288
- return left.map(headerGroup => {
289
- return headerGroup.headers;
290
- }).flat();
291
- }, {
292
- key: process.env.NODE_ENV === 'development' && 'getCenterFlatHeaders',
293
- debug: () => table.options.debugAll ?? table.options.debugHeaders
294
- }),
295
- getRightFlatHeaders: memo(() => [table.getRightHeaderGroups()], left => {
296
- return left.map(headerGroup => {
297
- return headerGroup.headers;
298
- }).flat();
299
- }, {
300
- key: process.env.NODE_ENV === 'development' && 'getRightFlatHeaders',
301
- debug: () => table.options.debugAll ?? table.options.debugHeaders
302
- }),
303
- // Leaf Headers
304
-
305
- getCenterLeafHeaders: memo(() => [table.getCenterFlatHeaders()], flatHeaders => {
306
- return flatHeaders.filter(header => {
307
- var _header$subHeaders;
308
- return !((_header$subHeaders = header.subHeaders) != null && _header$subHeaders.length);
309
- });
310
- }, {
311
- key: process.env.NODE_ENV === 'development' && 'getCenterLeafHeaders',
312
- debug: () => table.options.debugAll ?? table.options.debugHeaders
313
- }),
314
- getLeftLeafHeaders: memo(() => [table.getLeftFlatHeaders()], flatHeaders => {
315
- return flatHeaders.filter(header => {
316
- var _header$subHeaders2;
317
- return !((_header$subHeaders2 = header.subHeaders) != null && _header$subHeaders2.length);
318
- });
319
- }, {
320
- key: process.env.NODE_ENV === 'development' && 'getLeftLeafHeaders',
321
- debug: () => table.options.debugAll ?? table.options.debugHeaders
322
- }),
323
- getRightLeafHeaders: memo(() => [table.getRightFlatHeaders()], flatHeaders => {
324
- return flatHeaders.filter(header => {
325
- var _header$subHeaders3;
326
- return !((_header$subHeaders3 = header.subHeaders) != null && _header$subHeaders3.length);
327
- });
328
- }, {
329
- key: process.env.NODE_ENV === 'development' && 'getRightLeafHeaders',
330
- debug: () => table.options.debugAll ?? table.options.debugHeaders
331
- }),
332
- getLeafHeaders: memo(() => [table.getLeftHeaderGroups(), table.getCenterHeaderGroups(), table.getRightHeaderGroups()], (left, center, right) => {
333
- var _left$, _center$, _right$;
334
- return [...(((_left$ = left[0]) == null ? void 0 : _left$.headers) ?? []), ...(((_center$ = center[0]) == null ? void 0 : _center$.headers) ?? []), ...(((_right$ = right[0]) == null ? void 0 : _right$.headers) ?? [])].map(header => {
335
- return header.getLeafHeaders();
336
- }).flat();
337
- }, {
338
- key: process.env.NODE_ENV === 'development' && 'getLeafHeaders',
339
- debug: () => table.options.debugAll ?? table.options.debugHeaders
340
- })
341
- };
342
- }
343
- };
344
- function buildHeaderGroups(allColumns, columnsToGroup, table, headerFamily) {
345
- var _headerGroups$;
346
- // Find the max depth of the columns:
347
- // build the leaf column row
348
- // build each buffer row going up
349
- // placeholder for non-existent level
350
- // real column for existing level
351
-
352
- let maxDepth = 0;
353
- const findMaxDepth = function (columns, depth) {
354
- if (depth === void 0) {
355
- depth = 1;
356
- }
357
- maxDepth = Math.max(maxDepth, depth);
358
- columns.filter(column => column.getIsVisible()).forEach(column => {
359
- var _column$columns;
360
- if ((_column$columns = column.columns) != null && _column$columns.length) {
361
- findMaxDepth(column.columns, depth + 1);
362
- }
363
- }, 0);
364
- };
365
- findMaxDepth(allColumns);
366
- let headerGroups = [];
367
- const createHeaderGroup = (headersToGroup, depth) => {
368
- // The header group we are creating
369
- const headerGroup = {
370
- depth,
371
- id: [headerFamily, `${depth}`].filter(Boolean).join('_'),
372
- headers: []
373
- };
374
-
375
- // The parent columns we're going to scan next
376
- const pendingParentHeaders = [];
377
-
378
- // Scan each column for parents
379
- headersToGroup.forEach(headerToGroup => {
380
- // What is the latest (last) parent column?
381
-
382
- const latestPendingParentHeader = [...pendingParentHeaders].reverse()[0];
383
- const isLeafHeader = headerToGroup.column.depth === headerGroup.depth;
384
- let column;
385
- let isPlaceholder = false;
386
- if (isLeafHeader && headerToGroup.column.parent) {
387
- // The parent header is new
388
- column = headerToGroup.column.parent;
389
- } else {
390
- // The parent header is repeated
391
- column = headerToGroup.column;
392
- isPlaceholder = true;
393
- }
394
- if (latestPendingParentHeader && (latestPendingParentHeader == null ? void 0 : latestPendingParentHeader.column) === column) {
395
- // This column is repeated. Add it as a sub header to the next batch
396
- latestPendingParentHeader.subHeaders.push(headerToGroup);
397
- } else {
398
- // This is a new header. Let's create it
399
- const header = createHeader(table, column, {
400
- id: [headerFamily, depth, column.id, headerToGroup == null ? void 0 : headerToGroup.id].filter(Boolean).join('_'),
401
- isPlaceholder,
402
- placeholderId: isPlaceholder ? `${pendingParentHeaders.filter(d => d.column === column).length}` : undefined,
403
- depth,
404
- index: pendingParentHeaders.length
405
- });
406
-
407
- // Add the headerToGroup as a subHeader of the new header
408
- header.subHeaders.push(headerToGroup);
409
- // Add the new header to the pendingParentHeaders to get grouped
410
- // in the next batch
411
- pendingParentHeaders.push(header);
412
- }
413
- headerGroup.headers.push(headerToGroup);
414
- headerToGroup.headerGroup = headerGroup;
415
- });
416
- headerGroups.push(headerGroup);
417
- if (depth > 0) {
418
- createHeaderGroup(pendingParentHeaders, depth - 1);
419
- }
420
- };
421
- const bottomHeaders = columnsToGroup.map((column, index) => createHeader(table, column, {
422
- depth: maxDepth,
423
- index
424
- }));
425
- createHeaderGroup(bottomHeaders, maxDepth - 1);
426
- headerGroups.reverse();
427
-
428
- // headerGroups = headerGroups.filter(headerGroup => {
429
- // return !headerGroup.headers.every(header => header.isPlaceholder)
430
- // })
431
-
432
- const recurseHeadersForSpans = headers => {
433
- const filteredHeaders = headers.filter(header => header.column.getIsVisible());
434
- return filteredHeaders.map(header => {
435
- let colSpan = 0;
436
- let rowSpan = 0;
437
- let childRowSpans = [0];
438
- if (header.subHeaders && header.subHeaders.length) {
439
- childRowSpans = [];
440
- recurseHeadersForSpans(header.subHeaders).forEach(_ref => {
441
- let {
442
- colSpan: childColSpan,
443
- rowSpan: childRowSpan
444
- } = _ref;
445
- colSpan += childColSpan;
446
- childRowSpans.push(childRowSpan);
447
- });
448
- } else {
449
- colSpan = 1;
450
- }
451
- const minChildRowSpan = Math.min(...childRowSpans);
452
- rowSpan = rowSpan + minChildRowSpan;
453
- header.colSpan = colSpan;
454
- header.rowSpan = rowSpan;
455
- return {
456
- colSpan,
457
- rowSpan
458
- };
459
- });
460
- };
461
- recurseHeadersForSpans(((_headerGroups$ = headerGroups[0]) == null ? void 0 : _headerGroups$.headers) ?? []);
462
- return headerGroups;
463
- }
464
-
465
- //
466
-
467
- const defaultColumnSizing = {
468
- size: 150,
469
- minSize: 20,
470
- maxSize: Number.MAX_SAFE_INTEGER
471
- };
472
- const getDefaultColumnSizingInfoState = () => ({
473
- startOffset: null,
474
- startSize: null,
475
- deltaOffset: null,
476
- deltaPercentage: null,
477
- isResizingColumn: false,
478
- columnSizingStart: []
479
- });
480
- const ColumnSizing = {
481
- getDefaultColumnDef: () => {
482
- return defaultColumnSizing;
483
- },
484
- getInitialState: state => {
485
- return {
486
- columnSizing: {},
487
- columnSizingInfo: getDefaultColumnSizingInfoState(),
488
- ...state
489
- };
490
- },
491
- getDefaultOptions: table => {
492
- return {
493
- columnResizeMode: 'onEnd',
494
- onColumnSizingChange: makeStateUpdater('columnSizing', table),
495
- onColumnSizingInfoChange: makeStateUpdater('columnSizingInfo', table)
496
- };
497
- },
498
- createColumn: (column, table) => {
499
- return {
500
- getSize: () => {
501
- const columnSize = table.getState().columnSizing[column.id];
502
- return Math.min(Math.max(column.columnDef.minSize ?? defaultColumnSizing.minSize, columnSize ?? column.columnDef.size ?? defaultColumnSizing.size), column.columnDef.maxSize ?? defaultColumnSizing.maxSize);
503
- },
504
- getStart: position => {
505
- const columns = !position ? table.getVisibleLeafColumns() : position === 'left' ? table.getLeftVisibleLeafColumns() : table.getRightVisibleLeafColumns();
506
- const index = columns.findIndex(d => d.id === column.id);
507
- if (index > 0) {
508
- const prevSiblingColumn = columns[index - 1];
509
- return prevSiblingColumn.getStart(position) + prevSiblingColumn.getSize();
510
- }
511
- return 0;
512
- },
513
- resetSize: () => {
514
- table.setColumnSizing(_ref => {
515
- let {
516
- [column.id]: _,
517
- ...rest
518
- } = _ref;
519
- return rest;
520
- });
521
- },
522
- getCanResize: () => {
523
- return (column.columnDef.enableResizing ?? true) && (table.options.enableColumnResizing ?? true);
524
- },
525
- getIsResizing: () => {
526
- return table.getState().columnSizingInfo.isResizingColumn === column.id;
527
- }
528
- };
529
- },
530
- createHeader: (header, table) => {
531
- return {
532
- getSize: () => {
533
- let sum = 0;
534
- const recurse = header => {
535
- if (header.subHeaders.length) {
536
- header.subHeaders.forEach(recurse);
537
- } else {
538
- sum += header.column.getSize() ?? 0;
539
- }
540
- };
541
- recurse(header);
542
- return sum;
543
- },
544
- getStart: () => {
545
- if (header.index > 0) {
546
- const prevSiblingHeader = header.headerGroup.headers[header.index - 1];
547
- return prevSiblingHeader.getStart() + prevSiblingHeader.getSize();
548
- }
549
- return 0;
550
- },
551
- getResizeHandler: () => {
552
- const column = table.getColumn(header.column.id);
553
- const canResize = column.getCanResize();
554
- return e => {
555
- if (!canResize) {
556
- return;
557
- }
558
- e.persist == null ? void 0 : e.persist();
559
- if (isTouchStartEvent(e)) {
560
- // lets not respond to multiple touches (e.g. 2 or 3 fingers)
561
- if (e.touches && e.touches.length > 1) {
562
- return;
563
- }
564
- }
565
- const startSize = header.getSize();
566
- const columnSizingStart = header ? header.getLeafHeaders().map(d => [d.column.id, d.column.getSize()]) : [[column.id, column.getSize()]];
567
- const clientX = isTouchStartEvent(e) ? Math.round(e.touches[0].clientX) : e.clientX;
568
- const updateOffset = (eventType, clientXPos) => {
569
- if (typeof clientXPos !== 'number') {
570
- return;
571
- }
572
- let newColumnSizing = {};
573
- table.setColumnSizingInfo(old => {
574
- const deltaOffset = clientXPos - ((old == null ? void 0 : old.startOffset) ?? 0);
575
- const deltaPercentage = Math.max(deltaOffset / ((old == null ? void 0 : old.startSize) ?? 0), -0.999999);
576
- old.columnSizingStart.forEach(_ref2 => {
577
- let [columnId, headerSize] = _ref2;
578
- newColumnSizing[columnId] = Math.round(Math.max(headerSize + headerSize * deltaPercentage, 0) * 100) / 100;
579
- });
580
- return {
581
- ...old,
582
- deltaOffset,
583
- deltaPercentage
584
- };
585
- });
586
- if (table.options.columnResizeMode === 'onChange' || eventType === 'end') {
587
- table.setColumnSizing(old => ({
588
- ...old,
589
- ...newColumnSizing
590
- }));
591
- }
592
- };
593
- const onMove = clientXPos => updateOffset('move', clientXPos);
594
- const onEnd = clientXPos => {
595
- updateOffset('end', clientXPos);
596
- table.setColumnSizingInfo(old => ({
597
- ...old,
598
- isResizingColumn: false,
599
- startOffset: null,
600
- startSize: null,
601
- deltaOffset: null,
602
- deltaPercentage: null,
603
- columnSizingStart: []
604
- }));
605
- };
606
- const mouseEvents = {
607
- moveHandler: e => onMove(e.clientX),
608
- upHandler: e => {
609
- document.removeEventListener('mousemove', mouseEvents.moveHandler);
610
- document.removeEventListener('mouseup', mouseEvents.upHandler);
611
- onEnd(e.clientX);
612
- }
613
- };
614
- const touchEvents = {
615
- moveHandler: e => {
616
- if (e.cancelable) {
617
- e.preventDefault();
618
- e.stopPropagation();
619
- }
620
- onMove(e.touches[0].clientX);
621
- return false;
622
- },
623
- upHandler: e => {
624
- var _e$touches$;
625
- document.removeEventListener('touchmove', touchEvents.moveHandler);
626
- document.removeEventListener('touchend', touchEvents.upHandler);
627
- if (e.cancelable) {
628
- e.preventDefault();
629
- e.stopPropagation();
630
- }
631
- onEnd((_e$touches$ = e.touches[0]) == null ? void 0 : _e$touches$.clientX);
632
- }
633
- };
634
- const passiveIfSupported = passiveEventSupported() ? {
635
- passive: false
636
- } : false;
637
- if (isTouchStartEvent(e)) {
638
- document.addEventListener('touchmove', touchEvents.moveHandler, passiveIfSupported);
639
- document.addEventListener('touchend', touchEvents.upHandler, passiveIfSupported);
640
- } else {
641
- document.addEventListener('mousemove', mouseEvents.moveHandler, passiveIfSupported);
642
- document.addEventListener('mouseup', mouseEvents.upHandler, passiveIfSupported);
643
- }
644
- table.setColumnSizingInfo(old => ({
645
- ...old,
646
- startOffset: clientX,
647
- startSize,
648
- deltaOffset: 0,
649
- deltaPercentage: 0,
650
- columnSizingStart,
651
- isResizingColumn: column.id
652
- }));
653
- };
654
- }
655
- };
656
- },
657
- createTable: table => {
658
- return {
659
- setColumnSizing: updater => table.options.onColumnSizingChange == null ? void 0 : table.options.onColumnSizingChange(updater),
660
- setColumnSizingInfo: updater => table.options.onColumnSizingInfoChange == null ? void 0 : table.options.onColumnSizingInfoChange(updater),
661
- resetColumnSizing: defaultState => {
662
- table.setColumnSizing(defaultState ? {} : table.initialState.columnSizing ?? {});
663
- },
664
- resetHeaderSizeInfo: defaultState => {
665
- table.setColumnSizingInfo(defaultState ? getDefaultColumnSizingInfoState() : table.initialState.columnSizingInfo ?? getDefaultColumnSizingInfoState());
666
- },
667
- getTotalSize: () => {
668
- var _table$getHeaderGroup;
669
- return ((_table$getHeaderGroup = table.getHeaderGroups()[0]) == null ? void 0 : _table$getHeaderGroup.headers.reduce((sum, header) => {
670
- return sum + header.getSize();
671
- }, 0)) ?? 0;
672
- },
673
- getLeftTotalSize: () => {
674
- var _table$getLeftHeaderG;
675
- return ((_table$getLeftHeaderG = table.getLeftHeaderGroups()[0]) == null ? void 0 : _table$getLeftHeaderG.headers.reduce((sum, header) => {
676
- return sum + header.getSize();
677
- }, 0)) ?? 0;
678
- },
679
- getCenterTotalSize: () => {
680
- var _table$getCenterHeade;
681
- return ((_table$getCenterHeade = table.getCenterHeaderGroups()[0]) == null ? void 0 : _table$getCenterHeade.headers.reduce((sum, header) => {
682
- return sum + header.getSize();
683
- }, 0)) ?? 0;
684
- },
685
- getRightTotalSize: () => {
686
- var _table$getRightHeader;
687
- return ((_table$getRightHeader = table.getRightHeaderGroups()[0]) == null ? void 0 : _table$getRightHeader.headers.reduce((sum, header) => {
688
- return sum + header.getSize();
689
- }, 0)) ?? 0;
690
- }
691
- };
692
- }
693
- };
694
- let passiveSupported = null;
695
- function passiveEventSupported() {
696
- if (typeof passiveSupported === 'boolean') return passiveSupported;
697
- let supported = false;
698
- try {
699
- const options = {
700
- get passive() {
701
- supported = true;
702
- return false;
703
- }
704
- };
705
- const noop = () => {};
706
- window.addEventListener('test', noop, options);
707
- window.removeEventListener('test', noop);
708
- } catch (err) {
709
- supported = false;
710
- }
711
- passiveSupported = supported;
712
- return passiveSupported;
713
- }
714
- function isTouchStartEvent(e) {
715
- return e.type === 'touchstart';
716
- }
717
-
718
- //
719
-
720
- const Expanding = {
721
- getInitialState: state => {
722
- return {
723
- expanded: {},
724
- ...state
725
- };
726
- },
727
- getDefaultOptions: table => {
728
- return {
729
- onExpandedChange: makeStateUpdater('expanded', table),
730
- paginateExpandedRows: true
731
- };
732
- },
733
- createTable: table => {
734
- let registered = false;
735
- let queued = false;
736
- return {
737
- _autoResetExpanded: () => {
738
- if (!registered) {
739
- table._queue(() => {
740
- registered = true;
741
- });
742
- return;
743
- }
744
- if (table.options.autoResetAll ?? table.options.autoResetExpanded ?? !table.options.manualExpanding) {
745
- if (queued) return;
746
- queued = true;
747
- table._queue(() => {
748
- table.resetExpanded();
749
- queued = false;
750
- });
751
- }
752
- },
753
- setExpanded: updater => table.options.onExpandedChange == null ? void 0 : table.options.onExpandedChange(updater),
754
- toggleAllRowsExpanded: expanded => {
755
- if (expanded ?? !table.getIsAllRowsExpanded()) {
756
- table.setExpanded(true);
757
- } else {
758
- table.setExpanded({});
759
- }
760
- },
761
- resetExpanded: defaultState => {
762
- var _table$initialState;
763
- table.setExpanded(defaultState ? {} : ((_table$initialState = table.initialState) == null ? void 0 : _table$initialState.expanded) ?? {});
764
- },
765
- getCanSomeRowsExpand: () => {
766
- return table.getRowModel().flatRows.some(row => row.getCanExpand());
767
- },
768
- getToggleAllRowsExpandedHandler: () => {
769
- return e => {
770
- e.persist == null ? void 0 : e.persist();
771
- table.toggleAllRowsExpanded();
772
- };
773
- },
774
- getIsSomeRowsExpanded: () => {
775
- const expanded = table.getState().expanded;
776
- return expanded === true || Object.values(expanded).some(Boolean);
777
- },
778
- getIsAllRowsExpanded: () => {
779
- const expanded = table.getState().expanded;
780
-
781
- // If expanded is true, save some cycles and return true
782
- if (typeof expanded === 'boolean') {
783
- return expanded === true;
784
- }
785
- if (!Object.keys(expanded).length) {
786
- return false;
787
- }
788
-
789
- // If any row is not expanded, return false
790
- if (table.getRowModel().flatRows.some(row => !row.getIsExpanded())) {
791
- return false;
792
- }
793
-
794
- // They must all be expanded :shrug:
795
- return true;
796
- },
797
- getExpandedDepth: () => {
798
- let maxDepth = 0;
799
- const rowIds = table.getState().expanded === true ? Object.keys(table.getRowModel().rowsById) : Object.keys(table.getState().expanded);
800
- rowIds.forEach(id => {
801
- const splitId = id.split('.');
802
- maxDepth = Math.max(maxDepth, splitId.length);
803
- });
804
- return maxDepth;
805
- },
806
- getPreExpandedRowModel: () => table.getSortedRowModel(),
807
- getExpandedRowModel: () => {
808
- if (!table._getExpandedRowModel && table.options.getExpandedRowModel) {
809
- table._getExpandedRowModel = table.options.getExpandedRowModel(table);
810
- }
811
- if (table.options.manualExpanding || !table._getExpandedRowModel) {
812
- return table.getPreExpandedRowModel();
813
- }
814
- return table._getExpandedRowModel();
815
- }
816
- };
817
- },
818
- createRow: (row, table) => {
819
- return {
820
- toggleExpanded: expanded => {
821
- table.setExpanded(old => {
822
- const exists = old === true ? true : !!(old != null && old[row.id]);
823
- let oldExpanded = {};
824
- if (old === true) {
825
- Object.keys(table.getRowModel().rowsById).forEach(rowId => {
826
- oldExpanded[rowId] = true;
827
- });
828
- } else {
829
- oldExpanded = old;
830
- }
831
- expanded = expanded ?? !exists;
832
- if (!exists && expanded) {
833
- return {
834
- ...oldExpanded,
835
- [row.id]: true
836
- };
837
- }
838
- if (exists && !expanded) {
839
- const {
840
- [row.id]: _,
841
- ...rest
842
- } = oldExpanded;
843
- return rest;
844
- }
845
- return old;
846
- });
847
- },
848
- getIsExpanded: () => {
849
- const expanded = table.getState().expanded;
850
- return !!((table.options.getIsRowExpanded == null ? void 0 : table.options.getIsRowExpanded(row)) ?? (expanded === true || expanded != null && expanded[row.id]));
851
- },
852
- getCanExpand: () => {
853
- var _row$subRows;
854
- return (table.options.getRowCanExpand == null ? void 0 : table.options.getRowCanExpand(row)) ?? ((table.options.enableExpanding ?? true) && !!((_row$subRows = row.subRows) != null && _row$subRows.length));
855
- },
856
- getToggleExpandedHandler: () => {
857
- const canExpand = row.getCanExpand();
858
- return () => {
859
- if (!canExpand) return;
860
- row.toggleExpanded();
861
- };
862
- }
863
- };
864
- }
865
- };
866
-
867
- const includesString = (row, columnId, filterValue) => {
868
- var _row$getValue;
869
- const search = filterValue.toLowerCase();
870
- return Boolean((_row$getValue = row.getValue(columnId)) == null ? void 0 : _row$getValue.toLowerCase().includes(search));
871
- };
872
- includesString.autoRemove = val => testFalsey(val);
873
- const includesStringSensitive = (row, columnId, filterValue) => {
874
- var _row$getValue2;
875
- return Boolean((_row$getValue2 = row.getValue(columnId)) == null ? void 0 : _row$getValue2.includes(filterValue));
876
- };
877
- includesStringSensitive.autoRemove = val => testFalsey(val);
878
- const equalsString = (row, columnId, filterValue) => {
879
- var _row$getValue3;
880
- return ((_row$getValue3 = row.getValue(columnId)) == null ? void 0 : _row$getValue3.toLowerCase()) === filterValue.toLowerCase();
881
- };
882
- equalsString.autoRemove = val => testFalsey(val);
883
- const arrIncludes = (row, columnId, filterValue) => {
884
- var _row$getValue4;
885
- return (_row$getValue4 = row.getValue(columnId)) == null ? void 0 : _row$getValue4.includes(filterValue);
886
- };
887
- arrIncludes.autoRemove = val => testFalsey(val) || !(val != null && val.length);
888
- const arrIncludesAll = (row, columnId, filterValue) => {
889
- return !filterValue.some(val => {
890
- var _row$getValue5;
891
- return !((_row$getValue5 = row.getValue(columnId)) != null && _row$getValue5.includes(val));
892
- });
893
- };
894
- arrIncludesAll.autoRemove = val => testFalsey(val) || !(val != null && val.length);
895
- const arrIncludesSome = (row, columnId, filterValue) => {
896
- return filterValue.some(val => {
897
- var _row$getValue6;
898
- return (_row$getValue6 = row.getValue(columnId)) == null ? void 0 : _row$getValue6.includes(val);
899
- });
900
- };
901
- arrIncludesSome.autoRemove = val => testFalsey(val) || !(val != null && val.length);
902
- const equals = (row, columnId, filterValue) => {
903
- return row.getValue(columnId) === filterValue;
904
- };
905
- equals.autoRemove = val => testFalsey(val);
906
- const weakEquals = (row, columnId, filterValue) => {
907
- return row.getValue(columnId) == filterValue;
908
- };
909
- weakEquals.autoRemove = val => testFalsey(val);
910
- const inNumberRange = (row, columnId, filterValue) => {
911
- let [min, max] = filterValue;
912
- const rowValue = row.getValue(columnId);
913
- return rowValue >= min && rowValue <= max;
914
- };
915
- inNumberRange.resolveFilterValue = val => {
916
- let [unsafeMin, unsafeMax] = val;
917
- let parsedMin = typeof unsafeMin !== 'number' ? parseFloat(unsafeMin) : unsafeMin;
918
- let parsedMax = typeof unsafeMax !== 'number' ? parseFloat(unsafeMax) : unsafeMax;
919
- let min = unsafeMin === null || Number.isNaN(parsedMin) ? -Infinity : parsedMin;
920
- let max = unsafeMax === null || Number.isNaN(parsedMax) ? Infinity : parsedMax;
921
- if (min > max) {
922
- const temp = min;
923
- min = max;
924
- max = temp;
925
- }
926
- return [min, max];
927
- };
928
- inNumberRange.autoRemove = val => testFalsey(val) || testFalsey(val[0]) && testFalsey(val[1]);
929
-
930
- // Export
931
-
932
- const filterFns = {
933
- includesString,
934
- includesStringSensitive,
935
- equalsString,
936
- arrIncludes,
937
- arrIncludesAll,
938
- arrIncludesSome,
939
- equals,
940
- weakEquals,
941
- inNumberRange
942
- };
943
- // Utils
944
-
945
- function testFalsey(val) {
946
- return val === undefined || val === null || val === '';
947
- }
948
-
949
- //
950
-
951
- const Filters = {
952
- getDefaultColumnDef: () => {
953
- return {
954
- filterFn: 'auto'
955
- };
956
- },
957
- getInitialState: state => {
958
- return {
959
- columnFilters: [],
960
- globalFilter: undefined,
961
- // filtersProgress: 1,
962
- // facetProgress: {},
963
- ...state
964
- };
965
- },
966
- getDefaultOptions: table => {
967
- return {
968
- onColumnFiltersChange: makeStateUpdater('columnFilters', table),
969
- onGlobalFilterChange: makeStateUpdater('globalFilter', table),
970
- filterFromLeafRows: false,
971
- maxLeafRowFilterDepth: 100,
972
- globalFilterFn: 'auto',
973
- getColumnCanGlobalFilter: column => {
974
- var _table$getCoreRowMode, _table$getCoreRowMode2;
975
- const value = (_table$getCoreRowMode = table.getCoreRowModel().flatRows[0]) == null ? void 0 : (_table$getCoreRowMode2 = _table$getCoreRowMode._getAllCellsByColumnId()[column.id]) == null ? void 0 : _table$getCoreRowMode2.getValue();
976
- return typeof value === 'string' || typeof value === 'number';
977
- }
978
- };
979
- },
980
- createColumn: (column, table) => {
981
- return {
982
- getAutoFilterFn: () => {
983
- const firstRow = table.getCoreRowModel().flatRows[0];
984
- const value = firstRow == null ? void 0 : firstRow.getValue(column.id);
985
- if (typeof value === 'string') {
986
- return filterFns.includesString;
987
- }
988
- if (typeof value === 'number') {
989
- return filterFns.inNumberRange;
990
- }
991
- if (typeof value === 'boolean') {
992
- return filterFns.equals;
993
- }
994
- if (value !== null && typeof value === 'object') {
995
- return filterFns.equals;
996
- }
997
- if (Array.isArray(value)) {
998
- return filterFns.arrIncludes;
999
- }
1000
- return filterFns.weakEquals;
1001
- },
1002
- getFilterFn: () => {
1003
- var _table$options$filter;
1004
- return isFunction(column.columnDef.filterFn) ? column.columnDef.filterFn : column.columnDef.filterFn === 'auto' ? column.getAutoFilterFn() : ((_table$options$filter = table.options.filterFns) == null ? void 0 : _table$options$filter[column.columnDef.filterFn]) ?? filterFns[column.columnDef.filterFn];
1005
- },
1006
- getCanFilter: () => {
1007
- return (column.columnDef.enableColumnFilter ?? true) && (table.options.enableColumnFilters ?? true) && (table.options.enableFilters ?? true) && !!column.accessorFn;
1008
- },
1009
- getCanGlobalFilter: () => {
1010
- return (column.columnDef.enableGlobalFilter ?? true) && (table.options.enableGlobalFilter ?? true) && (table.options.enableFilters ?? true) && ((table.options.getColumnCanGlobalFilter == null ? void 0 : table.options.getColumnCanGlobalFilter(column)) ?? true) && !!column.accessorFn;
1011
- },
1012
- getIsFiltered: () => column.getFilterIndex() > -1,
1013
- getFilterValue: () => {
1014
- var _table$getState$colum, _table$getState$colum2;
1015
- return (_table$getState$colum = table.getState().columnFilters) == null ? void 0 : (_table$getState$colum2 = _table$getState$colum.find(d => d.id === column.id)) == null ? void 0 : _table$getState$colum2.value;
1016
- },
1017
- getFilterIndex: () => {
1018
- var _table$getState$colum3;
1019
- return ((_table$getState$colum3 = table.getState().columnFilters) == null ? void 0 : _table$getState$colum3.findIndex(d => d.id === column.id)) ?? -1;
1020
- },
1021
- setFilterValue: value => {
1022
- table.setColumnFilters(old => {
1023
- const filterFn = column.getFilterFn();
1024
- const previousfilter = old == null ? void 0 : old.find(d => d.id === column.id);
1025
- const newFilter = functionalUpdate(value, previousfilter ? previousfilter.value : undefined);
1026
-
1027
- //
1028
- if (shouldAutoRemoveFilter(filterFn, newFilter, column)) {
1029
- return (old == null ? void 0 : old.filter(d => d.id !== column.id)) ?? [];
1030
- }
1031
- const newFilterObj = {
1032
- id: column.id,
1033
- value: newFilter
1034
- };
1035
- if (previousfilter) {
1036
- return (old == null ? void 0 : old.map(d => {
1037
- if (d.id === column.id) {
1038
- return newFilterObj;
1039
- }
1040
- return d;
1041
- })) ?? [];
1042
- }
1043
- if (old != null && old.length) {
1044
- return [...old, newFilterObj];
1045
- }
1046
- return [newFilterObj];
1047
- });
1048
- },
1049
- _getFacetedRowModel: table.options.getFacetedRowModel && table.options.getFacetedRowModel(table, column.id),
1050
- getFacetedRowModel: () => {
1051
- if (!column._getFacetedRowModel) {
1052
- return table.getPreFilteredRowModel();
1053
- }
1054
- return column._getFacetedRowModel();
1055
- },
1056
- _getFacetedUniqueValues: table.options.getFacetedUniqueValues && table.options.getFacetedUniqueValues(table, column.id),
1057
- getFacetedUniqueValues: () => {
1058
- if (!column._getFacetedUniqueValues) {
1059
- return new Map();
1060
- }
1061
- return column._getFacetedUniqueValues();
1062
- },
1063
- _getFacetedMinMaxValues: table.options.getFacetedMinMaxValues && table.options.getFacetedMinMaxValues(table, column.id),
1064
- getFacetedMinMaxValues: () => {
1065
- if (!column._getFacetedMinMaxValues) {
1066
- return undefined;
1067
- }
1068
- return column._getFacetedMinMaxValues();
1069
- }
1070
- // () => [column.getFacetedRowModel()],
1071
- // facetedRowModel => getRowModelMinMaxValues(facetedRowModel, column.id),
1072
- };
1073
- },
1074
-
1075
- createRow: (row, table) => {
1076
- return {
1077
- columnFilters: {},
1078
- columnFiltersMeta: {}
1079
- };
1080
- },
1081
- createTable: table => {
1082
- return {
1083
- getGlobalAutoFilterFn: () => {
1084
- return filterFns.includesString;
1085
- },
1086
- getGlobalFilterFn: () => {
1087
- var _table$options$filter2;
1088
- const {
1089
- globalFilterFn: globalFilterFn
1090
- } = table.options;
1091
- return isFunction(globalFilterFn) ? globalFilterFn : globalFilterFn === 'auto' ? table.getGlobalAutoFilterFn() : ((_table$options$filter2 = table.options.filterFns) == null ? void 0 : _table$options$filter2[globalFilterFn]) ?? filterFns[globalFilterFn];
1092
- },
1093
- setColumnFilters: updater => {
1094
- const leafColumns = table.getAllLeafColumns();
1095
- const updateFn = old => {
1096
- var _functionalUpdate;
1097
- return (_functionalUpdate = functionalUpdate(updater, old)) == null ? void 0 : _functionalUpdate.filter(filter => {
1098
- const column = leafColumns.find(d => d.id === filter.id);
1099
- if (column) {
1100
- const filterFn = column.getFilterFn();
1101
- if (shouldAutoRemoveFilter(filterFn, filter.value, column)) {
1102
- return false;
1103
- }
1104
- }
1105
- return true;
1106
- });
1107
- };
1108
- table.options.onColumnFiltersChange == null ? void 0 : table.options.onColumnFiltersChange(updateFn);
1109
- },
1110
- setGlobalFilter: updater => {
1111
- table.options.onGlobalFilterChange == null ? void 0 : table.options.onGlobalFilterChange(updater);
1112
- },
1113
- resetGlobalFilter: defaultState => {
1114
- table.setGlobalFilter(defaultState ? undefined : table.initialState.globalFilter);
1115
- },
1116
- resetColumnFilters: defaultState => {
1117
- var _table$initialState;
1118
- table.setColumnFilters(defaultState ? [] : ((_table$initialState = table.initialState) == null ? void 0 : _table$initialState.columnFilters) ?? []);
1119
- },
1120
- getPreFilteredRowModel: () => table.getCoreRowModel(),
1121
- getFilteredRowModel: () => {
1122
- if (!table._getFilteredRowModel && table.options.getFilteredRowModel) {
1123
- table._getFilteredRowModel = table.options.getFilteredRowModel(table);
1124
- }
1125
- if (table.options.manualFiltering || !table._getFilteredRowModel) {
1126
- return table.getPreFilteredRowModel();
1127
- }
1128
- return table._getFilteredRowModel();
1129
- },
1130
- _getGlobalFacetedRowModel: table.options.getFacetedRowModel && table.options.getFacetedRowModel(table, '__global__'),
1131
- getGlobalFacetedRowModel: () => {
1132
- if (table.options.manualFiltering || !table._getGlobalFacetedRowModel) {
1133
- return table.getPreFilteredRowModel();
1134
- }
1135
- return table._getGlobalFacetedRowModel();
1136
- },
1137
- _getGlobalFacetedUniqueValues: table.options.getFacetedUniqueValues && table.options.getFacetedUniqueValues(table, '__global__'),
1138
- getGlobalFacetedUniqueValues: () => {
1139
- if (!table._getGlobalFacetedUniqueValues) {
1140
- return new Map();
1141
- }
1142
- return table._getGlobalFacetedUniqueValues();
1143
- },
1144
- _getGlobalFacetedMinMaxValues: table.options.getFacetedMinMaxValues && table.options.getFacetedMinMaxValues(table, '__global__'),
1145
- getGlobalFacetedMinMaxValues: () => {
1146
- if (!table._getGlobalFacetedMinMaxValues) {
1147
- return;
1148
- }
1149
- return table._getGlobalFacetedMinMaxValues();
1150
- }
1151
- };
1152
- }
1153
- };
1154
- function shouldAutoRemoveFilter(filterFn, value, column) {
1155
- return (filterFn && filterFn.autoRemove ? filterFn.autoRemove(value, column) : false) || typeof value === 'undefined' || typeof value === 'string' && !value;
1156
- }
1157
-
1158
- const sum = (columnId, _leafRows, childRows) => {
1159
- // It's faster to just add the aggregations together instead of
1160
- // process leaf nodes individually
1161
- return childRows.reduce((sum, next) => {
1162
- const nextValue = next.getValue(columnId);
1163
- return sum + (typeof nextValue === 'number' ? nextValue : 0);
1164
- }, 0);
1165
- };
1166
- const min = (columnId, _leafRows, childRows) => {
1167
- let min;
1168
- childRows.forEach(row => {
1169
- const value = row.getValue(columnId);
1170
- if (value != null && (min > value || min === undefined && value >= value)) {
1171
- min = value;
1172
- }
1173
- });
1174
- return min;
1175
- };
1176
- const max = (columnId, _leafRows, childRows) => {
1177
- let max;
1178
- childRows.forEach(row => {
1179
- const value = row.getValue(columnId);
1180
- if (value != null && (max < value || max === undefined && value >= value)) {
1181
- max = value;
1182
- }
1183
- });
1184
- return max;
1185
- };
1186
- const extent = (columnId, _leafRows, childRows) => {
1187
- let min;
1188
- let max;
1189
- childRows.forEach(row => {
1190
- const value = row.getValue(columnId);
1191
- if (value != null) {
1192
- if (min === undefined) {
1193
- if (value >= value) min = max = value;
1194
- } else {
1195
- if (min > value) min = value;
1196
- if (max < value) max = value;
1197
- }
1198
- }
1199
- });
1200
- return [min, max];
1201
- };
1202
- const mean = (columnId, leafRows) => {
1203
- let count = 0;
1204
- let sum = 0;
1205
- leafRows.forEach(row => {
1206
- let value = row.getValue(columnId);
1207
- if (value != null && (value = +value) >= value) {
1208
- ++count, sum += value;
1209
- }
1210
- });
1211
- if (count) return sum / count;
1212
- return;
1213
- };
1214
- const median = (columnId, leafRows) => {
1215
- if (!leafRows.length) {
1216
- return;
1217
- }
1218
- let min = 0;
1219
- let max = 0;
1220
- leafRows.forEach(row => {
1221
- let value = row.getValue(columnId);
1222
- if (typeof value === 'number') {
1223
- min = Math.min(min, value);
1224
- max = Math.max(max, value);
1225
- }
1226
- });
1227
- return (min + max) / 2;
1228
- };
1229
- const unique = (columnId, leafRows) => {
1230
- return Array.from(new Set(leafRows.map(d => d.getValue(columnId))).values());
1231
- };
1232
- const uniqueCount = (columnId, leafRows) => {
1233
- return new Set(leafRows.map(d => d.getValue(columnId))).size;
1234
- };
1235
- const count = (_columnId, leafRows) => {
1236
- return leafRows.length;
1237
- };
1238
- const aggregationFns = {
1239
- sum,
1240
- min,
1241
- max,
1242
- extent,
1243
- mean,
1244
- median,
1245
- unique,
1246
- uniqueCount,
1247
- count
1248
- };
1249
-
1250
- //
1251
-
1252
- const Grouping = {
1253
- getDefaultColumnDef: () => {
1254
- return {
1255
- aggregatedCell: props => {
1256
- var _props$getValue;
1257
- return ((_props$getValue = props.getValue()) == null ? void 0 : _props$getValue.toString == null ? void 0 : _props$getValue.toString()) ?? null;
1258
- },
1259
- aggregationFn: 'auto'
1260
- };
1261
- },
1262
- getInitialState: state => {
1263
- return {
1264
- grouping: [],
1265
- ...state
1266
- };
1267
- },
1268
- getDefaultOptions: table => {
1269
- return {
1270
- onGroupingChange: makeStateUpdater('grouping', table),
1271
- groupedColumnMode: 'reorder'
1272
- };
1273
- },
1274
- createColumn: (column, table) => {
1275
- return {
1276
- toggleGrouping: () => {
1277
- table.setGrouping(old => {
1278
- // Find any existing grouping for this column
1279
- if (old != null && old.includes(column.id)) {
1280
- return old.filter(d => d !== column.id);
1281
- }
1282
- return [...(old ?? []), column.id];
1283
- });
1284
- },
1285
- getCanGroup: () => {
1286
- return column.columnDef.enableGrouping ?? true ?? table.options.enableGrouping ?? true ?? !!column.accessorFn;
1287
- },
1288
- getIsGrouped: () => {
1289
- var _table$getState$group;
1290
- return (_table$getState$group = table.getState().grouping) == null ? void 0 : _table$getState$group.includes(column.id);
1291
- },
1292
- getGroupedIndex: () => {
1293
- var _table$getState$group2;
1294
- return (_table$getState$group2 = table.getState().grouping) == null ? void 0 : _table$getState$group2.indexOf(column.id);
1295
- },
1296
- getToggleGroupingHandler: () => {
1297
- const canGroup = column.getCanGroup();
1298
- return () => {
1299
- if (!canGroup) return;
1300
- column.toggleGrouping();
1301
- };
1302
- },
1303
- getAutoAggregationFn: () => {
1304
- const firstRow = table.getCoreRowModel().flatRows[0];
1305
- const value = firstRow == null ? void 0 : firstRow.getValue(column.id);
1306
- if (typeof value === 'number') {
1307
- return aggregationFns.sum;
1308
- }
1309
- if (Object.prototype.toString.call(value) === '[object Date]') {
1310
- return aggregationFns.extent;
1311
- }
1312
- },
1313
- getAggregationFn: () => {
1314
- var _table$options$aggreg;
1315
- if (!column) {
1316
- throw new Error();
1317
- }
1318
- return isFunction(column.columnDef.aggregationFn) ? column.columnDef.aggregationFn : column.columnDef.aggregationFn === 'auto' ? column.getAutoAggregationFn() : ((_table$options$aggreg = table.options.aggregationFns) == null ? void 0 : _table$options$aggreg[column.columnDef.aggregationFn]) ?? aggregationFns[column.columnDef.aggregationFn];
1319
- }
1320
- };
1321
- },
1322
- createTable: table => {
1323
- return {
1324
- setGrouping: updater => table.options.onGroupingChange == null ? void 0 : table.options.onGroupingChange(updater),
1325
- resetGrouping: defaultState => {
1326
- var _table$initialState;
1327
- table.setGrouping(defaultState ? [] : ((_table$initialState = table.initialState) == null ? void 0 : _table$initialState.grouping) ?? []);
1328
- },
1329
- getPreGroupedRowModel: () => table.getFilteredRowModel(),
1330
- getGroupedRowModel: () => {
1331
- if (!table._getGroupedRowModel && table.options.getGroupedRowModel) {
1332
- table._getGroupedRowModel = table.options.getGroupedRowModel(table);
1333
- }
1334
- if (table.options.manualGrouping || !table._getGroupedRowModel) {
1335
- return table.getPreGroupedRowModel();
1336
- }
1337
- return table._getGroupedRowModel();
1338
- }
1339
- };
1340
- },
1341
- createRow: row => {
1342
- return {
1343
- getIsGrouped: () => !!row.groupingColumnId,
1344
- _groupingValuesCache: {}
1345
- };
1346
- },
1347
- createCell: (cell, column, row, table) => {
1348
- return {
1349
- getIsGrouped: () => column.getIsGrouped() && column.id === row.groupingColumnId,
1350
- getIsPlaceholder: () => !cell.getIsGrouped() && column.getIsGrouped(),
1351
- getIsAggregated: () => {
1352
- var _row$subRows;
1353
- return !cell.getIsGrouped() && !cell.getIsPlaceholder() && !!((_row$subRows = row.subRows) != null && _row$subRows.length);
1354
- }
1355
- };
1356
- }
1357
- };
1358
- function orderColumns(leafColumns, grouping, groupedColumnMode) {
1359
- if (!(grouping != null && grouping.length) || !groupedColumnMode) {
1360
- return leafColumns;
1361
- }
1362
- const nonGroupingColumns = leafColumns.filter(col => !grouping.includes(col.id));
1363
- if (groupedColumnMode === 'remove') {
1364
- return nonGroupingColumns;
1365
- }
1366
- const groupingColumns = grouping.map(g => leafColumns.find(col => col.id === g)).filter(Boolean);
1367
- return [...groupingColumns, ...nonGroupingColumns];
1368
- }
1369
-
1370
- //
1371
-
1372
- const Ordering = {
1373
- getInitialState: state => {
1374
- return {
1375
- columnOrder: [],
1376
- ...state
1377
- };
1378
- },
1379
- getDefaultOptions: table => {
1380
- return {
1381
- onColumnOrderChange: makeStateUpdater('columnOrder', table)
1382
- };
1383
- },
1384
- createTable: table => {
1385
- return {
1386
- setColumnOrder: updater => table.options.onColumnOrderChange == null ? void 0 : table.options.onColumnOrderChange(updater),
1387
- resetColumnOrder: defaultState => {
1388
- table.setColumnOrder(defaultState ? [] : table.initialState.columnOrder ?? []);
1389
- },
1390
- _getOrderColumnsFn: memo(() => [table.getState().columnOrder, table.getState().grouping, table.options.groupedColumnMode], (columnOrder, grouping, groupedColumnMode) => columns => {
1391
- // Sort grouped columns to the start of the column list
1392
- // before the headers are built
1393
- let orderedColumns = [];
1394
-
1395
- // If there is no order, return the normal columns
1396
- if (!(columnOrder != null && columnOrder.length)) {
1397
- orderedColumns = columns;
1398
- } else {
1399
- const columnOrderCopy = [...columnOrder];
1400
-
1401
- // If there is an order, make a copy of the columns
1402
- const columnsCopy = [...columns];
1403
-
1404
- // And make a new ordered array of the columns
1405
-
1406
- // Loop over the columns and place them in order into the new array
1407
- while (columnsCopy.length && columnOrderCopy.length) {
1408
- const targetColumnId = columnOrderCopy.shift();
1409
- const foundIndex = columnsCopy.findIndex(d => d.id === targetColumnId);
1410
- if (foundIndex > -1) {
1411
- orderedColumns.push(columnsCopy.splice(foundIndex, 1)[0]);
1412
- }
1413
- }
1414
-
1415
- // If there are any columns left, add them to the end
1416
- orderedColumns = [...orderedColumns, ...columnsCopy];
1417
- }
1418
- return orderColumns(orderedColumns, grouping, groupedColumnMode);
1419
- }, {
1420
- key: process.env.NODE_ENV === 'development' && 'getOrderColumnsFn'
1421
- // debug: () => table.options.debugAll ?? table.options.debugTable,
1422
- })
1423
- };
1424
- }
1425
- };
1426
-
1427
- //
1428
-
1429
- const defaultPageIndex = 0;
1430
- const defaultPageSize = 10;
1431
- const getDefaultPaginationState = () => ({
1432
- pageIndex: defaultPageIndex,
1433
- pageSize: defaultPageSize
1434
- });
1435
- const Pagination = {
1436
- getInitialState: state => {
1437
- return {
1438
- ...state,
1439
- pagination: {
1440
- ...getDefaultPaginationState(),
1441
- ...(state == null ? void 0 : state.pagination)
1442
- }
1443
- };
1444
- },
1445
- getDefaultOptions: table => {
1446
- return {
1447
- onPaginationChange: makeStateUpdater('pagination', table)
1448
- };
1449
- },
1450
- createTable: table => {
1451
- let registered = false;
1452
- let queued = false;
1453
- return {
1454
- _autoResetPageIndex: () => {
1455
- if (!registered) {
1456
- table._queue(() => {
1457
- registered = true;
1458
- });
1459
- return;
1460
- }
1461
- if (table.options.autoResetAll ?? table.options.autoResetPageIndex ?? !table.options.manualPagination) {
1462
- if (queued) return;
1463
- queued = true;
1464
- table._queue(() => {
1465
- table.resetPageIndex();
1466
- queued = false;
1467
- });
1468
- }
1469
- },
1470
- setPagination: updater => {
1471
- const safeUpdater = old => {
1472
- let newState = functionalUpdate(updater, old);
1473
- return newState;
1474
- };
1475
- return table.options.onPaginationChange == null ? void 0 : table.options.onPaginationChange(safeUpdater);
1476
- },
1477
- resetPagination: defaultState => {
1478
- table.setPagination(defaultState ? getDefaultPaginationState() : table.initialState.pagination ?? getDefaultPaginationState());
1479
- },
1480
- setPageIndex: updater => {
1481
- table.setPagination(old => {
1482
- let pageIndex = functionalUpdate(updater, old.pageIndex);
1483
- const maxPageIndex = typeof table.options.pageCount === 'undefined' || table.options.pageCount === -1 ? Number.MAX_SAFE_INTEGER : table.options.pageCount - 1;
1484
- pageIndex = Math.max(0, Math.min(pageIndex, maxPageIndex));
1485
- return {
1486
- ...old,
1487
- pageIndex
1488
- };
1489
- });
1490
- },
1491
- resetPageIndex: defaultState => {
1492
- var _table$initialState, _table$initialState$p;
1493
- table.setPageIndex(defaultState ? defaultPageIndex : ((_table$initialState = table.initialState) == null ? void 0 : (_table$initialState$p = _table$initialState.pagination) == null ? void 0 : _table$initialState$p.pageIndex) ?? defaultPageIndex);
1494
- },
1495
- resetPageSize: defaultState => {
1496
- var _table$initialState2, _table$initialState2$;
1497
- table.setPageSize(defaultState ? defaultPageSize : ((_table$initialState2 = table.initialState) == null ? void 0 : (_table$initialState2$ = _table$initialState2.pagination) == null ? void 0 : _table$initialState2$.pageSize) ?? defaultPageSize);
1498
- },
1499
- setPageSize: updater => {
1500
- table.setPagination(old => {
1501
- const pageSize = Math.max(1, functionalUpdate(updater, old.pageSize));
1502
- const topRowIndex = old.pageSize * old.pageIndex;
1503
- const pageIndex = Math.floor(topRowIndex / pageSize);
1504
- return {
1505
- ...old,
1506
- pageIndex,
1507
- pageSize
1508
- };
1509
- });
1510
- },
1511
- setPageCount: updater => table.setPagination(old => {
1512
- let newPageCount = functionalUpdate(updater, table.options.pageCount ?? -1);
1513
- if (typeof newPageCount === 'number') {
1514
- newPageCount = Math.max(-1, newPageCount);
1515
- }
1516
- return {
1517
- ...old,
1518
- pageCount: newPageCount
1519
- };
1520
- }),
1521
- getPageOptions: memo(() => [table.getPageCount()], pageCount => {
1522
- let pageOptions = [];
1523
- if (pageCount && pageCount > 0) {
1524
- pageOptions = [...new Array(pageCount)].fill(null).map((_, i) => i);
1525
- }
1526
- return pageOptions;
1527
- }, {
1528
- key: process.env.NODE_ENV === 'development' && 'getPageOptions',
1529
- debug: () => table.options.debugAll ?? table.options.debugTable
1530
- }),
1531
- getCanPreviousPage: () => table.getState().pagination.pageIndex > 0,
1532
- getCanNextPage: () => {
1533
- const {
1534
- pageIndex
1535
- } = table.getState().pagination;
1536
- const pageCount = table.getPageCount();
1537
- if (pageCount === -1) {
1538
- return true;
1539
- }
1540
- if (pageCount === 0) {
1541
- return false;
1542
- }
1543
- return pageIndex < pageCount - 1;
1544
- },
1545
- previousPage: () => {
1546
- return table.setPageIndex(old => old - 1);
1547
- },
1548
- nextPage: () => {
1549
- return table.setPageIndex(old => {
1550
- return old + 1;
1551
- });
1552
- },
1553
- getPrePaginationRowModel: () => table.getExpandedRowModel(),
1554
- getPaginationRowModel: () => {
1555
- if (!table._getPaginationRowModel && table.options.getPaginationRowModel) {
1556
- table._getPaginationRowModel = table.options.getPaginationRowModel(table);
1557
- }
1558
- if (table.options.manualPagination || !table._getPaginationRowModel) {
1559
- return table.getPrePaginationRowModel();
1560
- }
1561
- return table._getPaginationRowModel();
1562
- },
1563
- getPageCount: () => {
1564
- return table.options.pageCount ?? Math.ceil(table.getPrePaginationRowModel().rows.length / table.getState().pagination.pageSize);
1565
- }
1566
- };
1567
- }
1568
- };
1569
-
1570
- //
1571
-
1572
- const getDefaultPinningState = () => ({
1573
- left: [],
1574
- right: []
1575
- });
1576
- const Pinning = {
1577
- getInitialState: state => {
1578
- return {
1579
- columnPinning: getDefaultPinningState(),
1580
- ...state
1581
- };
1582
- },
1583
- getDefaultOptions: table => {
1584
- return {
1585
- onColumnPinningChange: makeStateUpdater('columnPinning', table)
1586
- };
1587
- },
1588
- createColumn: (column, table) => {
1589
- return {
1590
- pin: position => {
1591
- const columnIds = column.getLeafColumns().map(d => d.id).filter(Boolean);
1592
- table.setColumnPinning(old => {
1593
- if (position === 'right') {
1594
- return {
1595
- left: ((old == null ? void 0 : old.left) ?? []).filter(d => !(columnIds != null && columnIds.includes(d))),
1596
- right: [...((old == null ? void 0 : old.right) ?? []).filter(d => !(columnIds != null && columnIds.includes(d))), ...columnIds]
1597
- };
1598
- }
1599
- if (position === 'left') {
1600
- return {
1601
- left: [...((old == null ? void 0 : old.left) ?? []).filter(d => !(columnIds != null && columnIds.includes(d))), ...columnIds],
1602
- right: ((old == null ? void 0 : old.right) ?? []).filter(d => !(columnIds != null && columnIds.includes(d)))
1603
- };
1604
- }
1605
- return {
1606
- left: ((old == null ? void 0 : old.left) ?? []).filter(d => !(columnIds != null && columnIds.includes(d))),
1607
- right: ((old == null ? void 0 : old.right) ?? []).filter(d => !(columnIds != null && columnIds.includes(d)))
1608
- };
1609
- });
1610
- },
1611
- getCanPin: () => {
1612
- const leafColumns = column.getLeafColumns();
1613
- return leafColumns.some(d => (d.columnDef.enablePinning ?? true) && (table.options.enablePinning ?? true));
1614
- },
1615
- getIsPinned: () => {
1616
- const leafColumnIds = column.getLeafColumns().map(d => d.id);
1617
- const {
1618
- left,
1619
- right
1620
- } = table.getState().columnPinning;
1621
- const isLeft = leafColumnIds.some(d => left == null ? void 0 : left.includes(d));
1622
- const isRight = leafColumnIds.some(d => right == null ? void 0 : right.includes(d));
1623
- return isLeft ? 'left' : isRight ? 'right' : false;
1624
- },
1625
- getPinnedIndex: () => {
1626
- var _table$getState$colum, _table$getState$colum2;
1627
- const position = column.getIsPinned();
1628
- return position ? ((_table$getState$colum = table.getState().columnPinning) == null ? void 0 : (_table$getState$colum2 = _table$getState$colum[position]) == null ? void 0 : _table$getState$colum2.indexOf(column.id)) ?? -1 : 0;
1629
- }
1630
- };
1631
- },
1632
- createRow: (row, table) => {
1633
- return {
1634
- getCenterVisibleCells: memo(() => [row._getAllVisibleCells(), table.getState().columnPinning.left, table.getState().columnPinning.right], (allCells, left, right) => {
1635
- const leftAndRight = [...(left ?? []), ...(right ?? [])];
1636
- return allCells.filter(d => !leftAndRight.includes(d.column.id));
1637
- }, {
1638
- key: process.env.NODE_ENV === 'production' && 'row.getCenterVisibleCells',
1639
- debug: () => table.options.debugAll ?? table.options.debugRows
1640
- }),
1641
- getLeftVisibleCells: memo(() => [row._getAllVisibleCells(), table.getState().columnPinning.left,,], (allCells, left) => {
1642
- const cells = (left ?? []).map(columnId => allCells.find(cell => cell.column.id === columnId)).filter(Boolean).map(d => ({
1643
- ...d,
1644
- position: 'left'
1645
- }));
1646
- return cells;
1647
- }, {
1648
- key: process.env.NODE_ENV === 'production' && 'row.getLeftVisibleCells',
1649
- debug: () => table.options.debugAll ?? table.options.debugRows
1650
- }),
1651
- getRightVisibleCells: memo(() => [row._getAllVisibleCells(), table.getState().columnPinning.right], (allCells, right) => {
1652
- const cells = (right ?? []).map(columnId => allCells.find(cell => cell.column.id === columnId)).filter(Boolean).map(d => ({
1653
- ...d,
1654
- position: 'right'
1655
- }));
1656
- return cells;
1657
- }, {
1658
- key: process.env.NODE_ENV === 'production' && 'row.getRightVisibleCells',
1659
- debug: () => table.options.debugAll ?? table.options.debugRows
1660
- })
1661
- };
1662
- },
1663
- createTable: table => {
1664
- return {
1665
- setColumnPinning: updater => table.options.onColumnPinningChange == null ? void 0 : table.options.onColumnPinningChange(updater),
1666
- resetColumnPinning: defaultState => {
1667
- var _table$initialState;
1668
- return table.setColumnPinning(defaultState ? getDefaultPinningState() : ((_table$initialState = table.initialState) == null ? void 0 : _table$initialState.columnPinning) ?? getDefaultPinningState());
1669
- },
1670
- getIsSomeColumnsPinned: position => {
1671
- var _pinningState$positio;
1672
- const pinningState = table.getState().columnPinning;
1673
- if (!position) {
1674
- var _pinningState$left, _pinningState$right;
1675
- return Boolean(((_pinningState$left = pinningState.left) == null ? void 0 : _pinningState$left.length) || ((_pinningState$right = pinningState.right) == null ? void 0 : _pinningState$right.length));
1676
- }
1677
- return Boolean((_pinningState$positio = pinningState[position]) == null ? void 0 : _pinningState$positio.length);
1678
- },
1679
- getLeftLeafColumns: memo(() => [table.getAllLeafColumns(), table.getState().columnPinning.left], (allColumns, left) => {
1680
- return (left ?? []).map(columnId => allColumns.find(column => column.id === columnId)).filter(Boolean);
1681
- }, {
1682
- key: process.env.NODE_ENV === 'development' && 'getLeftLeafColumns',
1683
- debug: () => table.options.debugAll ?? table.options.debugColumns
1684
- }),
1685
- getRightLeafColumns: memo(() => [table.getAllLeafColumns(), table.getState().columnPinning.right], (allColumns, right) => {
1686
- return (right ?? []).map(columnId => allColumns.find(column => column.id === columnId)).filter(Boolean);
1687
- }, {
1688
- key: process.env.NODE_ENV === 'development' && 'getRightLeafColumns',
1689
- debug: () => table.options.debugAll ?? table.options.debugColumns
1690
- }),
1691
- getCenterLeafColumns: memo(() => [table.getAllLeafColumns(), table.getState().columnPinning.left, table.getState().columnPinning.right], (allColumns, left, right) => {
1692
- const leftAndRight = [...(left ?? []), ...(right ?? [])];
1693
- return allColumns.filter(d => !leftAndRight.includes(d.id));
1694
- }, {
1695
- key: process.env.NODE_ENV === 'development' && 'getCenterLeafColumns',
1696
- debug: () => table.options.debugAll ?? table.options.debugColumns
1697
- })
1698
- };
1699
- }
1700
- };
1701
-
1702
- //
1703
-
1704
- const RowSelection = {
1705
- getInitialState: state => {
1706
- return {
1707
- rowSelection: {},
1708
- ...state
1709
- };
1710
- },
1711
- getDefaultOptions: table => {
1712
- return {
1713
- onRowSelectionChange: makeStateUpdater('rowSelection', table),
1714
- enableRowSelection: true,
1715
- enableMultiRowSelection: true,
1716
- enableSubRowSelection: true
1717
- // enableGroupingRowSelection: false,
1718
- // isAdditiveSelectEvent: (e: unknown) => !!e.metaKey,
1719
- // isInclusiveSelectEvent: (e: unknown) => !!e.shiftKey,
1720
- };
1721
- },
1722
-
1723
- createTable: table => {
1724
- return {
1725
- setRowSelection: updater => table.options.onRowSelectionChange == null ? void 0 : table.options.onRowSelectionChange(updater),
1726
- resetRowSelection: defaultState => table.setRowSelection(defaultState ? {} : table.initialState.rowSelection ?? {}),
1727
- toggleAllRowsSelected: value => {
1728
- table.setRowSelection(old => {
1729
- value = typeof value !== 'undefined' ? value : !table.getIsAllRowsSelected();
1730
- const rowSelection = {
1731
- ...old
1732
- };
1733
- const preGroupedFlatRows = table.getPreGroupedRowModel().flatRows;
1734
-
1735
- // We don't use `mutateRowIsSelected` here for performance reasons.
1736
- // All of the rows are flat already, so it wouldn't be worth it
1737
- if (value) {
1738
- preGroupedFlatRows.forEach(row => {
1739
- if (!row.getCanSelect()) {
1740
- return;
1741
- }
1742
- rowSelection[row.id] = true;
1743
- });
1744
- } else {
1745
- preGroupedFlatRows.forEach(row => {
1746
- delete rowSelection[row.id];
1747
- });
1748
- }
1749
- return rowSelection;
1750
- });
1751
- },
1752
- toggleAllPageRowsSelected: value => table.setRowSelection(old => {
1753
- const resolvedValue = typeof value !== 'undefined' ? value : !table.getIsAllPageRowsSelected();
1754
- const rowSelection = {
1755
- ...old
1756
- };
1757
- table.getRowModel().rows.forEach(row => {
1758
- mutateRowIsSelected(rowSelection, row.id, resolvedValue, table);
1759
- });
1760
- return rowSelection;
1761
- }),
1762
- // addRowSelectionRange: rowId => {
1763
- // const {
1764
- // rows,
1765
- // rowsById,
1766
- // options: { selectGroupingRows, selectSubRows },
1767
- // } = table
1768
-
1769
- // const findSelectedRow = (rows: Row[]) => {
1770
- // let found
1771
- // rows.find(d => {
1772
- // if (d.getIsSelected()) {
1773
- // found = d
1774
- // return true
1775
- // }
1776
- // const subFound = findSelectedRow(d.subRows || [])
1777
- // if (subFound) {
1778
- // found = subFound
1779
- // return true
1780
- // }
1781
- // return false
1782
- // })
1783
- // return found
1784
- // }
1785
-
1786
- // const firstRow = findSelectedRow(rows) || rows[0]
1787
- // const lastRow = rowsById[rowId]
1788
-
1789
- // let include = false
1790
- // const selectedRowIds = {}
1791
-
1792
- // const addRow = (row: Row) => {
1793
- // mutateRowIsSelected(selectedRowIds, row.id, true, {
1794
- // rowsById,
1795
- // selectGroupingRows: selectGroupingRows!,
1796
- // selectSubRows: selectSubRows!,
1797
- // })
1798
- // }
1799
-
1800
- // table.rows.forEach(row => {
1801
- // const isFirstRow = row.id === firstRow.id
1802
- // const isLastRow = row.id === lastRow.id
1803
-
1804
- // if (isFirstRow || isLastRow) {
1805
- // if (!include) {
1806
- // include = true
1807
- // } else if (include) {
1808
- // addRow(row)
1809
- // include = false
1810
- // }
1811
- // }
1812
-
1813
- // if (include) {
1814
- // addRow(row)
1815
- // }
1816
- // })
1817
-
1818
- // table.setRowSelection(selectedRowIds)
1819
- // },
1820
- getPreSelectedRowModel: () => table.getCoreRowModel(),
1821
- getSelectedRowModel: memo(() => [table.getState().rowSelection, table.getCoreRowModel()], (rowSelection, rowModel) => {
1822
- if (!Object.keys(rowSelection).length) {
1823
- return {
1824
- rows: [],
1825
- flatRows: [],
1826
- rowsById: {}
1827
- };
1828
- }
1829
- return selectRowsFn(table, rowModel);
1830
- }, {
1831
- key: process.env.NODE_ENV === 'development' && 'getSelectedRowModel',
1832
- debug: () => table.options.debugAll ?? table.options.debugTable
1833
- }),
1834
- getFilteredSelectedRowModel: memo(() => [table.getState().rowSelection, table.getFilteredRowModel()], (rowSelection, rowModel) => {
1835
- if (!Object.keys(rowSelection).length) {
1836
- return {
1837
- rows: [],
1838
- flatRows: [],
1839
- rowsById: {}
1840
- };
1841
- }
1842
- return selectRowsFn(table, rowModel);
1843
- }, {
1844
- key: process.env.NODE_ENV === 'production' && 'getFilteredSelectedRowModel',
1845
- debug: () => table.options.debugAll ?? table.options.debugTable
1846
- }),
1847
- getGroupedSelectedRowModel: memo(() => [table.getState().rowSelection, table.getSortedRowModel()], (rowSelection, rowModel) => {
1848
- if (!Object.keys(rowSelection).length) {
1849
- return {
1850
- rows: [],
1851
- flatRows: [],
1852
- rowsById: {}
1853
- };
1854
- }
1855
- return selectRowsFn(table, rowModel);
1856
- }, {
1857
- key: process.env.NODE_ENV === 'production' && 'getGroupedSelectedRowModel',
1858
- debug: () => table.options.debugAll ?? table.options.debugTable
1859
- }),
1860
- ///
1861
-
1862
- // getGroupingRowCanSelect: rowId => {
1863
- // const row = table.getRow(rowId)
1864
-
1865
- // if (!row) {
1866
- // throw new Error()
1867
- // }
1868
-
1869
- // if (typeof table.options.enableGroupingRowSelection === 'function') {
1870
- // return table.options.enableGroupingRowSelection(row)
1871
- // }
1872
-
1873
- // return table.options.enableGroupingRowSelection ?? false
1874
- // },
1875
-
1876
- getIsAllRowsSelected: () => {
1877
- const preGroupedFlatRows = table.getFilteredRowModel().flatRows;
1878
- const {
1879
- rowSelection
1880
- } = table.getState();
1881
- let isAllRowsSelected = Boolean(preGroupedFlatRows.length && Object.keys(rowSelection).length);
1882
- if (isAllRowsSelected) {
1883
- if (preGroupedFlatRows.some(row => row.getCanSelect() && !rowSelection[row.id])) {
1884
- isAllRowsSelected = false;
1885
- }
1886
- }
1887
- return isAllRowsSelected;
1888
- },
1889
- getIsAllPageRowsSelected: () => {
1890
- const paginationFlatRows = table.getPaginationRowModel().flatRows;
1891
- const {
1892
- rowSelection
1893
- } = table.getState();
1894
- let isAllPageRowsSelected = !!paginationFlatRows.length;
1895
- if (isAllPageRowsSelected && paginationFlatRows.some(row => !rowSelection[row.id])) {
1896
- isAllPageRowsSelected = false;
1897
- }
1898
- return isAllPageRowsSelected;
1899
- },
1900
- getIsSomeRowsSelected: () => {
1901
- const totalSelected = Object.keys(table.getState().rowSelection ?? {}).length;
1902
- return totalSelected > 0 && totalSelected < table.getFilteredRowModel().flatRows.length;
1903
- },
1904
- getIsSomePageRowsSelected: () => {
1905
- const paginationFlatRows = table.getPaginationRowModel().flatRows;
1906
- return table.getIsAllPageRowsSelected() ? false : paginationFlatRows.some(d => d.getIsSelected() || d.getIsSomeSelected());
1907
- },
1908
- getToggleAllRowsSelectedHandler: () => {
1909
- return e => {
1910
- table.toggleAllRowsSelected(e.target.checked);
1911
- };
1912
- },
1913
- getToggleAllPageRowsSelectedHandler: () => {
1914
- return e => {
1915
- table.toggleAllPageRowsSelected(e.target.checked);
1916
- };
1917
- }
1918
- };
1919
- },
1920
- createRow: (row, table) => {
1921
- return {
1922
- toggleSelected: value => {
1923
- const isSelected = row.getIsSelected();
1924
- table.setRowSelection(old => {
1925
- value = typeof value !== 'undefined' ? value : !isSelected;
1926
- if (isSelected === value) {
1927
- return old;
1928
- }
1929
- const selectedRowIds = {
1930
- ...old
1931
- };
1932
- mutateRowIsSelected(selectedRowIds, row.id, value, table);
1933
- return selectedRowIds;
1934
- });
1935
- },
1936
- getIsSelected: () => {
1937
- const {
1938
- rowSelection
1939
- } = table.getState();
1940
- return isRowSelected(row, rowSelection);
1941
- },
1942
- getIsSomeSelected: () => {
1943
- const {
1944
- rowSelection
1945
- } = table.getState();
1946
- return isSubRowSelected(row, rowSelection) === 'some';
1947
- },
1948
- getIsAllSubRowsSelected: () => {
1949
- const {
1950
- rowSelection
1951
- } = table.getState();
1952
- return isSubRowSelected(row, rowSelection) === 'all';
1953
- },
1954
- getCanSelect: () => {
1955
- if (typeof table.options.enableRowSelection === 'function') {
1956
- return table.options.enableRowSelection(row);
1957
- }
1958
- return table.options.enableRowSelection ?? true;
1959
- },
1960
- getCanSelectSubRows: () => {
1961
- if (typeof table.options.enableSubRowSelection === 'function') {
1962
- return table.options.enableSubRowSelection(row);
1963
- }
1964
- return table.options.enableSubRowSelection ?? true;
1965
- },
1966
- getCanMultiSelect: () => {
1967
- if (typeof table.options.enableMultiRowSelection === 'function') {
1968
- return table.options.enableMultiRowSelection(row);
1969
- }
1970
- return table.options.enableMultiRowSelection ?? true;
1971
- },
1972
- getToggleSelectedHandler: () => {
1973
- const canSelect = row.getCanSelect();
1974
- return e => {
1975
- var _target;
1976
- if (!canSelect) return;
1977
- row.toggleSelected((_target = e.target) == null ? void 0 : _target.checked);
1978
- };
1979
- }
1980
- };
1981
- }
1982
- };
1983
- const mutateRowIsSelected = (selectedRowIds, id, value, table) => {
1984
- var _row$subRows;
1985
- const row = table.getRow(id);
1986
-
1987
- // const isGrouped = row.getIsGrouped()
1988
-
1989
- // if ( // TODO: enforce grouping row selection rules
1990
- // !isGrouped ||
1991
- // (isGrouped && table.options.enableGroupingRowSelection)
1992
- // ) {
1993
- if (value) {
1994
- if (!row.getCanMultiSelect()) {
1995
- Object.keys(selectedRowIds).forEach(key => delete selectedRowIds[key]);
1996
- }
1997
- if (row.getCanSelect()) {
1998
- selectedRowIds[id] = true;
1999
- }
2000
- } else {
2001
- delete selectedRowIds[id];
2002
- }
2003
- // }
2004
-
2005
- if ((_row$subRows = row.subRows) != null && _row$subRows.length && row.getCanSelectSubRows()) {
2006
- row.subRows.forEach(row => mutateRowIsSelected(selectedRowIds, row.id, value, table));
2007
- }
2008
- };
2009
- function selectRowsFn(table, rowModel) {
2010
- const rowSelection = table.getState().rowSelection;
2011
- const newSelectedFlatRows = [];
2012
- const newSelectedRowsById = {};
2013
-
2014
- // Filters top level and nested rows
2015
- const recurseRows = function (rows, depth) {
2016
- return rows.map(row => {
2017
- var _row$subRows2;
2018
- const isSelected = isRowSelected(row, rowSelection);
2019
- if (isSelected) {
2020
- newSelectedFlatRows.push(row);
2021
- newSelectedRowsById[row.id] = row;
2022
- }
2023
- if ((_row$subRows2 = row.subRows) != null && _row$subRows2.length) {
2024
- row = {
2025
- ...row,
2026
- subRows: recurseRows(row.subRows)
2027
- };
2028
- }
2029
- if (isSelected) {
2030
- return row;
2031
- }
2032
- }).filter(Boolean);
2033
- };
2034
- return {
2035
- rows: recurseRows(rowModel.rows),
2036
- flatRows: newSelectedFlatRows,
2037
- rowsById: newSelectedRowsById
2038
- };
2039
- }
2040
- function isRowSelected(row, selection) {
2041
- return selection[row.id] ?? false;
2042
- }
2043
- function isSubRowSelected(row, selection, table) {
2044
- if (row.subRows && row.subRows.length) {
2045
- let allChildrenSelected = true;
2046
- let someSelected = false;
2047
- row.subRows.forEach(subRow => {
2048
- // Bail out early if we know both of these
2049
- if (someSelected && !allChildrenSelected) {
2050
- return;
2051
- }
2052
- if (isRowSelected(subRow, selection)) {
2053
- someSelected = true;
2054
- } else {
2055
- allChildrenSelected = false;
2056
- }
2057
- });
2058
- return allChildrenSelected ? 'all' : someSelected ? 'some' : false;
2059
- }
2060
- return false;
2061
- }
2062
-
2063
- const reSplitAlphaNumeric = /([0-9]+)/gm;
2064
- const alphanumeric = (rowA, rowB, columnId) => {
2065
- return compareAlphanumeric(toString(rowA.getValue(columnId)).toLowerCase(), toString(rowB.getValue(columnId)).toLowerCase());
2066
- };
2067
- const alphanumericCaseSensitive = (rowA, rowB, columnId) => {
2068
- return compareAlphanumeric(toString(rowA.getValue(columnId)), toString(rowB.getValue(columnId)));
2069
- };
2070
-
2071
- // The text filter is more basic (less numeric support)
2072
- // but is much faster
2073
- const text = (rowA, rowB, columnId) => {
2074
- return compareBasic(toString(rowA.getValue(columnId)).toLowerCase(), toString(rowB.getValue(columnId)).toLowerCase());
2075
- };
2076
-
2077
- // The text filter is more basic (less numeric support)
2078
- // but is much faster
2079
- const textCaseSensitive = (rowA, rowB, columnId) => {
2080
- return compareBasic(toString(rowA.getValue(columnId)), toString(rowB.getValue(columnId)));
2081
- };
2082
- const datetime = (rowA, rowB, columnId) => {
2083
- const a = rowA.getValue(columnId);
2084
- const b = rowB.getValue(columnId);
2085
-
2086
- // Can handle nullish values
2087
- // Use > and < because == (and ===) doesn't work with
2088
- // Date objects (would require calling getTime()).
2089
- return a > b ? 1 : a < b ? -1 : 0;
2090
- };
2091
- const basic = (rowA, rowB, columnId) => {
2092
- return compareBasic(rowA.getValue(columnId), rowB.getValue(columnId));
2093
- };
2094
-
2095
- // Utils
2096
-
2097
- function compareBasic(a, b) {
2098
- return a === b ? 0 : a > b ? 1 : -1;
2099
- }
2100
- function toString(a) {
2101
- if (typeof a === 'number') {
2102
- if (isNaN(a) || a === Infinity || a === -Infinity) {
2103
- return '';
2104
- }
2105
- return String(a);
2106
- }
2107
- if (typeof a === 'string') {
2108
- return a;
2109
- }
2110
- return '';
2111
- }
2112
-
2113
- // Mixed sorting is slow, but very inclusive of many edge cases.
2114
- // It handles numbers, mixed alphanumeric combinations, and even
2115
- // null, undefined, and Infinity
2116
- function compareAlphanumeric(aStr, bStr) {
2117
- // Split on number groups, but keep the delimiter
2118
- // Then remove falsey split values
2119
- const a = aStr.split(reSplitAlphaNumeric).filter(Boolean);
2120
- const b = bStr.split(reSplitAlphaNumeric).filter(Boolean);
2121
-
2122
- // While
2123
- while (a.length && b.length) {
2124
- const aa = a.shift();
2125
- const bb = b.shift();
2126
- const an = parseInt(aa, 10);
2127
- const bn = parseInt(bb, 10);
2128
- const combo = [an, bn].sort();
2129
-
2130
- // Both are string
2131
- if (isNaN(combo[0])) {
2132
- if (aa > bb) {
2133
- return 1;
2134
- }
2135
- if (bb > aa) {
2136
- return -1;
2137
- }
2138
- continue;
2139
- }
2140
-
2141
- // One is a string, one is a number
2142
- if (isNaN(combo[1])) {
2143
- return isNaN(an) ? -1 : 1;
2144
- }
2145
-
2146
- // Both are numbers
2147
- if (an > bn) {
2148
- return 1;
2149
- }
2150
- if (bn > an) {
2151
- return -1;
2152
- }
2153
- }
2154
- return a.length - b.length;
2155
- }
2156
-
2157
- // Exports
2158
-
2159
- const sortingFns = {
2160
- alphanumeric,
2161
- alphanumericCaseSensitive,
2162
- text,
2163
- textCaseSensitive,
2164
- datetime,
2165
- basic
2166
- };
2167
-
2168
- //
2169
-
2170
- const Sorting = {
2171
- getInitialState: state => {
2172
- return {
2173
- sorting: [],
2174
- ...state
2175
- };
2176
- },
2177
- getDefaultColumnDef: () => {
2178
- return {
2179
- sortingFn: 'auto'
2180
- };
2181
- },
2182
- getDefaultOptions: table => {
2183
- return {
2184
- onSortingChange: makeStateUpdater('sorting', table),
2185
- isMultiSortEvent: e => {
2186
- return e.shiftKey;
2187
- }
2188
- };
2189
- },
2190
- createColumn: (column, table) => {
2191
- return {
2192
- getAutoSortingFn: () => {
2193
- const firstRows = table.getFilteredRowModel().flatRows.slice(10);
2194
- let isString = false;
2195
- for (const row of firstRows) {
2196
- const value = row == null ? void 0 : row.getValue(column.id);
2197
- if (Object.prototype.toString.call(value) === '[object Date]') {
2198
- return sortingFns.datetime;
2199
- }
2200
- if (typeof value === 'string') {
2201
- isString = true;
2202
- if (value.split(reSplitAlphaNumeric).length > 1) {
2203
- return sortingFns.alphanumeric;
2204
- }
2205
- }
2206
- }
2207
- if (isString) {
2208
- return sortingFns.text;
2209
- }
2210
- return sortingFns.basic;
2211
- },
2212
- getAutoSortDir: () => {
2213
- const firstRow = table.getFilteredRowModel().flatRows[0];
2214
- const value = firstRow == null ? void 0 : firstRow.getValue(column.id);
2215
- if (typeof value === 'string') {
2216
- return 'asc';
2217
- }
2218
- return 'desc';
2219
- },
2220
- getSortingFn: () => {
2221
- var _table$options$sortin;
2222
- if (!column) {
2223
- throw new Error();
2224
- }
2225
- return isFunction(column.columnDef.sortingFn) ? column.columnDef.sortingFn : column.columnDef.sortingFn === 'auto' ? column.getAutoSortingFn() : ((_table$options$sortin = table.options.sortingFns) == null ? void 0 : _table$options$sortin[column.columnDef.sortingFn]) ?? sortingFns[column.columnDef.sortingFn];
2226
- },
2227
- toggleSorting: (desc, multi) => {
2228
- // if (column.columns.length) {
2229
- // column.columns.forEach((c, i) => {
2230
- // if (c.id) {
2231
- // table.toggleColumnSorting(c.id, undefined, multi || !!i)
2232
- // }
2233
- // })
2234
- // return
2235
- // }
2236
-
2237
- // this needs to be outside of table.setSorting to be in sync with rerender
2238
- const nextSortingOrder = column.getNextSortingOrder();
2239
- const hasManualValue = typeof desc !== 'undefined' && desc !== null;
2240
- table.setSorting(old => {
2241
- // Find any existing sorting for this column
2242
- const existingSorting = old == null ? void 0 : old.find(d => d.id === column.id);
2243
- const existingIndex = old == null ? void 0 : old.findIndex(d => d.id === column.id);
2244
- let newSorting = [];
2245
-
2246
- // What should we do with this sort action?
2247
- let sortAction;
2248
- let nextDesc = hasManualValue ? desc : nextSortingOrder === 'desc';
2249
-
2250
- // Multi-mode
2251
- if (old != null && old.length && column.getCanMultiSort() && multi) {
2252
- if (existingSorting) {
2253
- sortAction = 'toggle';
2254
- } else {
2255
- sortAction = 'add';
2256
- }
2257
- } else {
2258
- // Normal mode
2259
- if (old != null && old.length && existingIndex !== old.length - 1) {
2260
- sortAction = 'replace';
2261
- } else if (existingSorting) {
2262
- sortAction = 'toggle';
2263
- } else {
2264
- sortAction = 'replace';
2265
- }
2266
- }
2267
-
2268
- // Handle toggle states that will remove the sorting
2269
- if (sortAction === 'toggle') {
2270
- // If we are "actually" toggling (not a manual set value), should we remove the sorting?
2271
- if (!hasManualValue) {
2272
- // Is our intention to remove?
2273
- if (!nextSortingOrder) {
2274
- sortAction = 'remove';
2275
- }
2276
- }
2277
- }
2278
- if (sortAction === 'add') {
2279
- newSorting = [...old, {
2280
- id: column.id,
2281
- desc: nextDesc
2282
- }];
2283
- // Take latest n columns
2284
- newSorting.splice(0, newSorting.length - (table.options.maxMultiSortColCount ?? Number.MAX_SAFE_INTEGER));
2285
- } else if (sortAction === 'toggle') {
2286
- // This flips (or sets) the
2287
- newSorting = old.map(d => {
2288
- if (d.id === column.id) {
2289
- return {
2290
- ...d,
2291
- desc: nextDesc
2292
- };
2293
- }
2294
- return d;
2295
- });
2296
- } else if (sortAction === 'remove') {
2297
- newSorting = old.filter(d => d.id !== column.id);
2298
- } else {
2299
- newSorting = [{
2300
- id: column.id,
2301
- desc: nextDesc
2302
- }];
2303
- }
2304
- return newSorting;
2305
- });
2306
- },
2307
- getFirstSortDir: () => {
2308
- const sortDescFirst = column.columnDef.sortDescFirst ?? table.options.sortDescFirst ?? column.getAutoSortDir() === 'desc';
2309
- return sortDescFirst ? 'desc' : 'asc';
2310
- },
2311
- getNextSortingOrder: multi => {
2312
- const firstSortDirection = column.getFirstSortDir();
2313
- const isSorted = column.getIsSorted();
2314
- if (!isSorted) {
2315
- return firstSortDirection;
2316
- }
2317
- if (isSorted !== firstSortDirection && (table.options.enableSortingRemoval ?? true) && (
2318
- // If enableSortRemove, enable in general
2319
- multi ? table.options.enableMultiRemove ?? true : true) // If multi, don't allow if enableMultiRemove))
2320
- ) {
2321
- return false;
2322
- }
2323
- return isSorted === 'desc' ? 'asc' : 'desc';
2324
- },
2325
- getCanSort: () => {
2326
- return (column.columnDef.enableSorting ?? true) && (table.options.enableSorting ?? true) && !!column.accessorFn;
2327
- },
2328
- getCanMultiSort: () => {
2329
- return column.columnDef.enableMultiSort ?? table.options.enableMultiSort ?? !!column.accessorFn;
2330
- },
2331
- getIsSorted: () => {
2332
- var _table$getState$sorti;
2333
- const columnSort = (_table$getState$sorti = table.getState().sorting) == null ? void 0 : _table$getState$sorti.find(d => d.id === column.id);
2334
- return !columnSort ? false : columnSort.desc ? 'desc' : 'asc';
2335
- },
2336
- getSortIndex: () => {
2337
- var _table$getState$sorti2;
2338
- return ((_table$getState$sorti2 = table.getState().sorting) == null ? void 0 : _table$getState$sorti2.findIndex(d => d.id === column.id)) ?? -1;
2339
- },
2340
- clearSorting: () => {
2341
- //clear sorting for just 1 column
2342
- table.setSorting(old => old != null && old.length ? old.filter(d => d.id !== column.id) : []);
2343
- },
2344
- getToggleSortingHandler: () => {
2345
- const canSort = column.getCanSort();
2346
- return e => {
2347
- if (!canSort) return;
2348
- e.persist == null ? void 0 : e.persist();
2349
- column.toggleSorting == null ? void 0 : column.toggleSorting(undefined, column.getCanMultiSort() ? table.options.isMultiSortEvent == null ? void 0 : table.options.isMultiSortEvent(e) : false);
2350
- };
2351
- }
2352
- };
2353
- },
2354
- createTable: table => {
2355
- return {
2356
- setSorting: updater => table.options.onSortingChange == null ? void 0 : table.options.onSortingChange(updater),
2357
- resetSorting: defaultState => {
2358
- var _table$initialState;
2359
- table.setSorting(defaultState ? [] : ((_table$initialState = table.initialState) == null ? void 0 : _table$initialState.sorting) ?? []);
2360
- },
2361
- getPreSortedRowModel: () => table.getGroupedRowModel(),
2362
- getSortedRowModel: () => {
2363
- if (!table._getSortedRowModel && table.options.getSortedRowModel) {
2364
- table._getSortedRowModel = table.options.getSortedRowModel(table);
2365
- }
2366
- if (table.options.manualSorting || !table._getSortedRowModel) {
2367
- return table.getPreSortedRowModel();
2368
- }
2369
- return table._getSortedRowModel();
2370
- }
2371
- };
2372
- }
2373
- };
2374
-
2375
- //
2376
-
2377
- const Visibility = {
2378
- getInitialState: state => {
2379
- return {
2380
- columnVisibility: {},
2381
- ...state
2382
- };
2383
- },
2384
- getDefaultOptions: table => {
2385
- return {
2386
- onColumnVisibilityChange: makeStateUpdater('columnVisibility', table)
2387
- };
2388
- },
2389
- createColumn: (column, table) => {
2390
- return {
2391
- toggleVisibility: value => {
2392
- if (column.getCanHide()) {
2393
- table.setColumnVisibility(old => ({
2394
- ...old,
2395
- [column.id]: value ?? !column.getIsVisible()
2396
- }));
2397
- }
2398
- },
2399
- getIsVisible: () => {
2400
- var _table$getState$colum;
2401
- return ((_table$getState$colum = table.getState().columnVisibility) == null ? void 0 : _table$getState$colum[column.id]) ?? true;
2402
- },
2403
- getCanHide: () => {
2404
- return (column.columnDef.enableHiding ?? true) && (table.options.enableHiding ?? true);
2405
- },
2406
- getToggleVisibilityHandler: () => {
2407
- return e => {
2408
- column.toggleVisibility == null ? void 0 : column.toggleVisibility(e.target.checked);
2409
- };
2410
- }
2411
- };
2412
- },
2413
- createRow: (row, table) => {
2414
- return {
2415
- _getAllVisibleCells: memo(() => [row.getAllCells(), table.getState().columnVisibility], cells => {
2416
- return cells.filter(cell => cell.column.getIsVisible());
2417
- }, {
2418
- key: process.env.NODE_ENV === 'production' && 'row._getAllVisibleCells',
2419
- debug: () => table.options.debugAll ?? table.options.debugRows
2420
- }),
2421
- getVisibleCells: memo(() => [row.getLeftVisibleCells(), row.getCenterVisibleCells(), row.getRightVisibleCells()], (left, center, right) => [...left, ...center, ...right], {
2422
- key: process.env.NODE_ENV === 'development' && 'row.getVisibleCells',
2423
- debug: () => table.options.debugAll ?? table.options.debugRows
2424
- })
2425
- };
2426
- },
2427
- createTable: table => {
2428
- const makeVisibleColumnsMethod = (key, getColumns) => {
2429
- return memo(() => [getColumns(), getColumns().filter(d => d.getIsVisible()).map(d => d.id).join('_')], columns => {
2430
- return columns.filter(d => d.getIsVisible == null ? void 0 : d.getIsVisible());
2431
- }, {
2432
- key,
2433
- debug: () => table.options.debugAll ?? table.options.debugColumns
2434
- });
2435
- };
2436
- return {
2437
- getVisibleFlatColumns: makeVisibleColumnsMethod('getVisibleFlatColumns', () => table.getAllFlatColumns()),
2438
- getVisibleLeafColumns: makeVisibleColumnsMethod('getVisibleLeafColumns', () => table.getAllLeafColumns()),
2439
- getLeftVisibleLeafColumns: makeVisibleColumnsMethod('getLeftVisibleLeafColumns', () => table.getLeftLeafColumns()),
2440
- getRightVisibleLeafColumns: makeVisibleColumnsMethod('getRightVisibleLeafColumns', () => table.getRightLeafColumns()),
2441
- getCenterVisibleLeafColumns: makeVisibleColumnsMethod('getCenterVisibleLeafColumns', () => table.getCenterLeafColumns()),
2442
- setColumnVisibility: updater => table.options.onColumnVisibilityChange == null ? void 0 : table.options.onColumnVisibilityChange(updater),
2443
- resetColumnVisibility: defaultState => {
2444
- table.setColumnVisibility(defaultState ? {} : table.initialState.columnVisibility ?? {});
2445
- },
2446
- toggleAllColumnsVisible: value => {
2447
- value = value ?? !table.getIsAllColumnsVisible();
2448
- table.setColumnVisibility(table.getAllLeafColumns().reduce((obj, column) => ({
2449
- ...obj,
2450
- [column.id]: !value ? !(column.getCanHide != null && column.getCanHide()) : value
2451
- }), {}));
2452
- },
2453
- getIsAllColumnsVisible: () => !table.getAllLeafColumns().some(column => !(column.getIsVisible != null && column.getIsVisible())),
2454
- getIsSomeColumnsVisible: () => table.getAllLeafColumns().some(column => column.getIsVisible == null ? void 0 : column.getIsVisible()),
2455
- getToggleAllColumnsVisibilityHandler: () => {
2456
- return e => {
2457
- var _target;
2458
- table.toggleAllColumnsVisible((_target = e.target) == null ? void 0 : _target.checked);
2459
- };
2460
- }
2461
- };
2462
- }
2463
- };
2464
-
2465
- const features = [Headers, Visibility, Ordering, Pinning, Filters, Sorting, Grouping, Expanding, Pagination, RowSelection, ColumnSizing];
2466
-
2467
- //
2468
-
2469
- function createTable(options) {
2470
- if (options.debugAll || options.debugTable) {
2471
- console.info('Creating Table Instance...');
2472
- }
2473
- let table = {
2474
- _features: features
2475
- };
2476
- const defaultOptions = table._features.reduce((obj, feature) => {
2477
- return Object.assign(obj, feature.getDefaultOptions == null ? void 0 : feature.getDefaultOptions(table));
2478
- }, {});
2479
- const mergeOptions = options => {
2480
- if (table.options.mergeOptions) {
2481
- return table.options.mergeOptions(defaultOptions, options);
2482
- }
2483
- return {
2484
- ...defaultOptions,
2485
- ...options
2486
- };
2487
- };
2488
- const coreInitialState = {};
2489
- let initialState = {
2490
- ...coreInitialState,
2491
- ...(options.initialState ?? {})
2492
- };
2493
- table._features.forEach(feature => {
2494
- initialState = (feature.getInitialState == null ? void 0 : feature.getInitialState(initialState)) ?? initialState;
2495
- });
2496
- const queued = [];
2497
- let queuedTimeout = false;
2498
- const coreInstance = {
2499
- _features: features,
2500
- options: {
2501
- ...defaultOptions,
2502
- ...options
2503
- },
2504
- initialState,
2505
- _queue: cb => {
2506
- queued.push(cb);
2507
- if (!queuedTimeout) {
2508
- queuedTimeout = true;
2509
-
2510
- // Schedule a microtask to run the queued callbacks after
2511
- // the current call stack (render, etc) has finished.
2512
- Promise.resolve().then(() => {
2513
- while (queued.length) {
2514
- queued.shift()();
2515
- }
2516
- queuedTimeout = false;
2517
- }).catch(error => setTimeout(() => {
2518
- throw error;
2519
- }));
2520
- }
2521
- },
2522
- reset: () => {
2523
- table.setState(table.initialState);
2524
- },
2525
- setOptions: updater => {
2526
- const newOptions = functionalUpdate(updater, table.options);
2527
- table.options = mergeOptions(newOptions);
2528
- },
2529
- getState: () => {
2530
- return table.options.state;
2531
- },
2532
- setState: updater => {
2533
- table.options.onStateChange == null ? void 0 : table.options.onStateChange(updater);
2534
- },
2535
- _getRowId: (row, index, parent) => (table.options.getRowId == null ? void 0 : table.options.getRowId(row, index, parent)) ?? `${parent ? [parent.id, index].join('.') : index}`,
2536
- getCoreRowModel: () => {
2537
- if (!table._getCoreRowModel) {
2538
- table._getCoreRowModel = table.options.getCoreRowModel(table);
2539
- }
2540
- return table._getCoreRowModel();
2541
- },
2542
- // The final calls start at the bottom of the model,
2543
- // expanded rows, which then work their way up
2544
-
2545
- getRowModel: () => {
2546
- return table.getPaginationRowModel();
2547
- },
2548
- getRow: id => {
2549
- const row = table.getRowModel().rowsById[id];
2550
- if (!row) {
2551
- if (process.env.NODE_ENV !== 'production') {
2552
- throw new Error(`getRow expected an ID, but got ${id}`);
2553
- }
2554
- throw new Error();
2555
- }
2556
- return row;
2557
- },
2558
- _getDefaultColumnDef: memo(() => [table.options.defaultColumn], defaultColumn => {
2559
- defaultColumn = defaultColumn ?? {};
2560
- return {
2561
- header: props => {
2562
- const resolvedColumnDef = props.header.column.columnDef;
2563
- if (resolvedColumnDef.accessorKey) {
2564
- return resolvedColumnDef.accessorKey;
2565
- }
2566
- if (resolvedColumnDef.accessorFn) {
2567
- return resolvedColumnDef.id;
2568
- }
2569
- return null;
2570
- },
2571
- // footer: props => props.header.column.id,
2572
- cell: props => {
2573
- var _props$renderValue;
2574
- return ((_props$renderValue = props.renderValue()) == null ? void 0 : _props$renderValue.toString == null ? void 0 : _props$renderValue.toString()) ?? null;
2575
- },
2576
- ...table._features.reduce((obj, feature) => {
2577
- return Object.assign(obj, feature.getDefaultColumnDef == null ? void 0 : feature.getDefaultColumnDef());
2578
- }, {}),
2579
- ...defaultColumn
2580
- };
2581
- }, {
2582
- debug: () => table.options.debugAll ?? table.options.debugColumns,
2583
- key: process.env.NODE_ENV === 'development' && 'getDefaultColumnDef'
2584
- }),
2585
- _getColumnDefs: () => table.options.columns,
2586
- getAllColumns: memo(() => [table._getColumnDefs()], columnDefs => {
2587
- const recurseColumns = function (columnDefs, parent, depth) {
2588
- if (depth === void 0) {
2589
- depth = 0;
2590
- }
2591
- return columnDefs.map(columnDef => {
2592
- const column = createColumn(table, columnDef, depth, parent);
2593
- const groupingColumnDef = columnDef;
2594
- column.columns = groupingColumnDef.columns ? recurseColumns(groupingColumnDef.columns, column, depth + 1) : [];
2595
- return column;
2596
- });
2597
- };
2598
- return recurseColumns(columnDefs);
2599
- }, {
2600
- key: process.env.NODE_ENV === 'development' && 'getAllColumns',
2601
- debug: () => table.options.debugAll ?? table.options.debugColumns
2602
- }),
2603
- getAllFlatColumns: memo(() => [table.getAllColumns()], allColumns => {
2604
- return allColumns.flatMap(column => {
2605
- return column.getFlatColumns();
2606
- });
2607
- }, {
2608
- key: process.env.NODE_ENV === 'development' && 'getAllFlatColumns',
2609
- debug: () => table.options.debugAll ?? table.options.debugColumns
2610
- }),
2611
- _getAllFlatColumnsById: memo(() => [table.getAllFlatColumns()], flatColumns => {
2612
- return flatColumns.reduce((acc, column) => {
2613
- acc[column.id] = column;
2614
- return acc;
2615
- }, {});
2616
- }, {
2617
- key: process.env.NODE_ENV === 'development' && 'getAllFlatColumnsById',
2618
- debug: () => table.options.debugAll ?? table.options.debugColumns
2619
- }),
2620
- getAllLeafColumns: memo(() => [table.getAllColumns(), table._getOrderColumnsFn()], (allColumns, orderColumns) => {
2621
- let leafColumns = allColumns.flatMap(column => column.getLeafColumns());
2622
- return orderColumns(leafColumns);
2623
- }, {
2624
- key: process.env.NODE_ENV === 'development' && 'getAllLeafColumns',
2625
- debug: () => table.options.debugAll ?? table.options.debugColumns
2626
- }),
2627
- getColumn: columnId => {
2628
- const column = table._getAllFlatColumnsById()[columnId];
2629
- if (!column) {
2630
- if (process.env.NODE_ENV !== 'production') {
2631
- console.warn(`[Table] Column with id ${columnId} does not exist.`);
2632
- }
2633
- throw new Error();
2634
- }
2635
- return column;
2636
- }
2637
- };
2638
- Object.assign(table, coreInstance);
2639
- table._features.forEach(feature => {
2640
- return Object.assign(table, feature.createTable == null ? void 0 : feature.createTable(table));
2641
- });
2642
- return table;
2643
- }
2644
-
2645
- function createCell(table, row, column, columnId) {
2646
- const getRenderValue = () => cell.getValue() ?? table.options.renderFallbackValue;
2647
- const cell = {
2648
- id: `${row.id}_${column.id}`,
2649
- row,
2650
- column,
2651
- getValue: () => row.getValue(columnId),
2652
- renderValue: getRenderValue,
2653
- getContext: memo(() => [table, column, row, cell], (table, column, row, cell) => ({
2654
- table,
2655
- column,
2656
- row,
2657
- cell: cell,
2658
- getValue: cell.getValue,
2659
- renderValue: cell.renderValue
2660
- }), {
2661
- key: process.env.NODE_ENV === 'development' && 'cell.getContext',
2662
- debug: () => table.options.debugAll
2663
- })
2664
- };
2665
- table._features.forEach(feature => {
2666
- Object.assign(cell, feature.createCell == null ? void 0 : feature.createCell(cell, column, row, table));
2667
- }, {});
2668
- return cell;
2669
- }
2670
-
2671
- const createRow = (table, id, original, rowIndex, depth, subRows) => {
2672
- let row = {
2673
- id,
2674
- index: rowIndex,
2675
- original,
2676
- depth,
2677
- _valuesCache: {},
2678
- _uniqueValuesCache: {},
2679
- getValue: columnId => {
2680
- if (row._valuesCache.hasOwnProperty(columnId)) {
2681
- return row._valuesCache[columnId];
2682
- }
2683
- const column = table.getColumn(columnId);
2684
- if (!column.accessorFn) {
2685
- return undefined;
2686
- }
2687
- row._valuesCache[columnId] = column.accessorFn(row.original, rowIndex);
2688
- return row._valuesCache[columnId];
2689
- },
2690
- getUniqueValues: columnId => {
2691
- if (row._uniqueValuesCache.hasOwnProperty(columnId)) {
2692
- return row._uniqueValuesCache[columnId];
2693
- }
2694
- const column = table.getColumn(columnId);
2695
- if (!column.accessorFn) {
2696
- return undefined;
2697
- }
2698
- if (!column.columnDef.getUniqueValues) {
2699
- row._uniqueValuesCache[columnId] = [row.getValue(columnId)];
2700
- return row._uniqueValuesCache[columnId];
2701
- }
2702
- row._uniqueValuesCache[columnId] = column.columnDef.getUniqueValues(row.original, rowIndex);
2703
- return row._uniqueValuesCache[columnId];
2704
- },
2705
- renderValue: columnId => row.getValue(columnId) ?? table.options.renderFallbackValue,
2706
- subRows: subRows ?? [],
2707
- getLeafRows: () => flattenBy(row.subRows, d => d.subRows),
2708
- getAllCells: memo(() => [table.getAllLeafColumns()], leafColumns => {
2709
- return leafColumns.map(column => {
2710
- return createCell(table, row, column, column.id);
2711
- });
2712
- }, {
2713
- key: process.env.NODE_ENV === 'development' && 'row.getAllCells',
2714
- debug: () => table.options.debugAll ?? table.options.debugRows
2715
- }),
2716
- _getAllCellsByColumnId: memo(() => [row.getAllCells()], allCells => {
2717
- return allCells.reduce((acc, cell) => {
2718
- acc[cell.column.id] = cell;
2719
- return acc;
2720
- }, {});
2721
- }, {
2722
- key: process.env.NODE_ENV === 'production' && 'row.getAllCellsByColumnId',
2723
- debug: () => table.options.debugAll ?? table.options.debugRows
2724
- })
2725
- };
2726
- for (let i = 0; i < table._features.length; i++) {
2727
- const feature = table._features[i];
2728
- Object.assign(row, feature == null ? void 0 : feature.createRow == null ? void 0 : feature.createRow(row, table));
2729
- }
2730
- return row;
2731
- };
2732
-
2733
- // type Person = {
2734
- // firstName: string
2735
- // lastName: string
2736
- // age: number
2737
- // visits: number
2738
- // status: string
2739
- // progress: number
2740
- // createdAt: Date
2741
- // nested: {
2742
- // foo: [
2743
- // {
2744
- // bar: 'bar'
2745
- // }
2746
- // ]
2747
- // bar: { subBar: boolean }[]
2748
- // baz: {
2749
- // foo: 'foo'
2750
- // bar: {
2751
- // baz: 'baz'
2752
- // }
2753
- // }
2754
- // }
2755
- // }
2756
-
2757
- // const test: DeepKeys<Person> = 'nested.foo.0.bar'
2758
- // const test2: DeepKeys<Person> = 'nested.bar'
2759
-
2760
- // const helper = createColumnHelper<Person>()
2761
-
2762
- // helper.accessor('nested.foo', {
2763
- // cell: info => info.getValue(),
2764
- // })
2765
-
2766
- // helper.accessor('nested.foo.0.bar', {
2767
- // cell: info => info.getValue(),
2768
- // })
2769
-
2770
- // helper.accessor('nested.bar', {
2771
- // cell: info => info.getValue(),
2772
- // })
2773
-
2774
- function createColumnHelper() {
2775
- return {
2776
- accessor: (accessor, column) => {
2777
- return typeof accessor === 'function' ? {
2778
- ...column,
2779
- accessorFn: accessor
2780
- } : {
2781
- ...column,
2782
- accessorKey: accessor
2783
- };
2784
- },
2785
- display: column => column,
2786
- group: column => column
2787
- };
2788
- }
2789
-
2790
- function getCoreRowModel() {
2791
- return table => memo(() => [table.options.data], data => {
2792
- const rowModel = {
2793
- rows: [],
2794
- flatRows: [],
2795
- rowsById: {}
2796
- };
2797
- const accessRows = function (originalRows, depth, parent) {
2798
- if (depth === void 0) {
2799
- depth = 0;
2800
- }
2801
- const rows = [];
2802
- for (let i = 0; i < originalRows.length; i++) {
2803
- // This could be an expensive check at scale, so we should move it somewhere else, but where?
2804
- // if (!id) {
2805
- // if (process.env.NODE_ENV !== 'production') {
2806
- // throw new Error(`getRowId expected an ID, but got ${id}`)
2807
- // }
2808
- // }
2809
-
2810
- // Make the row
2811
- const row = createRow(table, table._getRowId(originalRows[i], i, parent), originalRows[i], i, depth);
2812
-
2813
- // Keep track of every row in a flat array
2814
- rowModel.flatRows.push(row);
2815
- // Also keep track of every row by its ID
2816
- rowModel.rowsById[row.id] = row;
2817
- // Push table row into parent
2818
- rows.push(row);
2819
-
2820
- // Get the original subrows
2821
- if (table.options.getSubRows) {
2822
- var _row$originalSubRows;
2823
- row.originalSubRows = table.options.getSubRows(originalRows[i], i);
2824
-
2825
- // Then recursively access them
2826
- if ((_row$originalSubRows = row.originalSubRows) != null && _row$originalSubRows.length) {
2827
- row.subRows = accessRows(row.originalSubRows, depth + 1, row);
2828
- }
2829
- }
2830
- }
2831
- return rows;
2832
- };
2833
- rowModel.rows = accessRows(data);
2834
- return rowModel;
2835
- }, {
2836
- key: process.env.NODE_ENV === 'development' && 'getRowModel',
2837
- debug: () => table.options.debugAll ?? table.options.debugTable,
2838
- onChange: () => {
2839
- table._autoResetPageIndex();
2840
- }
2841
- });
2842
- }
2843
-
2844
- function filterRows(rows, filterRowImpl, table) {
2845
- if (table.options.filterFromLeafRows) {
2846
- return filterRowModelFromLeafs(rows, filterRowImpl, table);
2847
- }
2848
- return filterRowModelFromRoot(rows, filterRowImpl, table);
2849
- }
2850
- function filterRowModelFromLeafs(rowsToFilter, filterRow, table) {
2851
- const newFilteredFlatRows = [];
2852
- const newFilteredRowsById = {};
2853
- const maxDepth = table.options.maxLeafRowFilterDepth ?? 100;
2854
- const recurseFilterRows = function (rowsToFilter, depth) {
2855
- if (depth === void 0) {
2856
- depth = 0;
2857
- }
2858
- const rows = [];
2859
-
2860
- // Filter from children up first
2861
- for (let i = 0; i < rowsToFilter.length; i++) {
2862
- var _row$subRows;
2863
- let row = rowsToFilter[i];
2864
- const newRow = createRow(table, row.id, row.original, row.index, row.depth);
2865
- newRow.columnFilters = row.columnFilters;
2866
- if ((_row$subRows = row.subRows) != null && _row$subRows.length && depth < maxDepth) {
2867
- newRow.subRows = recurseFilterRows(row.subRows, depth + 1);
2868
- row = newRow;
2869
- if (filterRow(row) && !newRow.subRows.length) {
2870
- rows.push(row);
2871
- newFilteredRowsById[row.id] = row;
2872
- newFilteredRowsById[i] = row;
2873
- continue;
2874
- }
2875
- if (filterRow(row) || newRow.subRows.length) {
2876
- rows.push(row);
2877
- newFilteredRowsById[row.id] = row;
2878
- newFilteredRowsById[i] = row;
2879
- continue;
2880
- }
2881
- } else {
2882
- row = newRow;
2883
- if (filterRow(row)) {
2884
- rows.push(row);
2885
- newFilteredRowsById[row.id] = row;
2886
- newFilteredRowsById[i] = row;
2887
- }
2888
- }
2889
- }
2890
- return rows;
2891
- };
2892
- return {
2893
- rows: recurseFilterRows(rowsToFilter),
2894
- flatRows: newFilteredFlatRows,
2895
- rowsById: newFilteredRowsById
2896
- };
2897
- }
2898
- function filterRowModelFromRoot(rowsToFilter, filterRow, table) {
2899
- const newFilteredFlatRows = [];
2900
- const newFilteredRowsById = {};
2901
- const maxDepth = table.options.maxLeafRowFilterDepth ?? 100;
2902
-
2903
- // Filters top level and nested rows
2904
- const recurseFilterRows = function (rowsToFilter, depth) {
2905
- if (depth === void 0) {
2906
- depth = 0;
2907
- }
2908
- // Filter from parents downward first
2909
-
2910
- const rows = [];
2911
-
2912
- // Apply the filter to any subRows
2913
- for (let i = 0; i < rowsToFilter.length; i++) {
2914
- let row = rowsToFilter[i];
2915
- const pass = filterRow(row);
2916
- if (pass) {
2917
- var _row$subRows2;
2918
- if ((_row$subRows2 = row.subRows) != null && _row$subRows2.length && depth < maxDepth) {
2919
- const newRow = createRow(table, row.id, row.original, row.index, row.depth);
2920
- newRow.subRows = recurseFilterRows(row.subRows, depth + 1);
2921
- row = newRow;
2922
- }
2923
- rows.push(row);
2924
- newFilteredFlatRows.push(row);
2925
- newFilteredRowsById[row.id] = row;
2926
- }
2927
- }
2928
- return rows;
2929
- };
2930
- return {
2931
- rows: recurseFilterRows(rowsToFilter),
2932
- flatRows: newFilteredFlatRows,
2933
- rowsById: newFilteredRowsById
2934
- };
2935
- }
2936
-
2937
- function getFilteredRowModel() {
2938
- return table => memo(() => [table.getPreFilteredRowModel(), table.getState().columnFilters, table.getState().globalFilter], (rowModel, columnFilters, globalFilter) => {
2939
- if (!rowModel.rows.length || !(columnFilters != null && columnFilters.length) && !globalFilter) {
2940
- for (let i = 0; i < rowModel.flatRows.length; i++) {
2941
- rowModel.flatRows[i].columnFilters = {};
2942
- rowModel.flatRows[i].columnFiltersMeta = {};
2943
- }
2944
- return rowModel;
2945
- }
2946
- const resolvedColumnFilters = [];
2947
- const resolvedGlobalFilters = [];
2948
- (columnFilters ?? []).forEach(d => {
2949
- const column = table.getColumn(d.id);
2950
- if (!column) {
2951
- if (process.env.NODE_ENV !== 'production') {
2952
- console.warn(`Table: Could not find a column to filter with columnId: ${d.id}`);
2953
- }
2954
- }
2955
- const filterFn = column.getFilterFn();
2956
- if (!filterFn) {
2957
- if (process.env.NODE_ENV !== 'production') {
2958
- console.warn(`Could not find a valid 'column.filterFn' for column with the ID: ${column.id}.`);
2959
- }
2960
- return;
2961
- }
2962
- resolvedColumnFilters.push({
2963
- id: d.id,
2964
- filterFn,
2965
- resolvedValue: (filterFn.resolveFilterValue == null ? void 0 : filterFn.resolveFilterValue(d.value)) ?? d.value
2966
- });
2967
- });
2968
- const filterableIds = columnFilters.map(d => d.id);
2969
- const globalFilterFn = table.getGlobalFilterFn();
2970
- const globallyFilterableColumns = table.getAllLeafColumns().filter(column => column.getCanGlobalFilter());
2971
- if (globalFilter && globalFilterFn && globallyFilterableColumns.length) {
2972
- filterableIds.push('__global__');
2973
- globallyFilterableColumns.forEach(column => {
2974
- resolvedGlobalFilters.push({
2975
- id: column.id,
2976
- filterFn: globalFilterFn,
2977
- resolvedValue: (globalFilterFn.resolveFilterValue == null ? void 0 : globalFilterFn.resolveFilterValue(globalFilter)) ?? globalFilter
2978
- });
2979
- });
2980
- }
2981
- let currentColumnFilter;
2982
- let currentGlobalFilter;
2983
-
2984
- // Flag the prefiltered row model with each filter state
2985
- for (let j = 0; j < rowModel.flatRows.length; j++) {
2986
- const row = rowModel.flatRows[j];
2987
- row.columnFilters = {};
2988
- if (resolvedColumnFilters.length) {
2989
- for (let i = 0; i < resolvedColumnFilters.length; i++) {
2990
- currentColumnFilter = resolvedColumnFilters[i];
2991
- const id = currentColumnFilter.id;
2992
-
2993
- // Tag the row with the column filter state
2994
- row.columnFilters[id] = currentColumnFilter.filterFn(row, id, currentColumnFilter.resolvedValue, filterMeta => {
2995
- row.columnFiltersMeta[id] = filterMeta;
2996
- });
2997
- }
2998
- }
2999
- if (resolvedGlobalFilters.length) {
3000
- for (let i = 0; i < resolvedGlobalFilters.length; i++) {
3001
- currentGlobalFilter = resolvedGlobalFilters[i];
3002
- const id = currentGlobalFilter.id;
3003
- // Tag the row with the first truthy global filter state
3004
- if (currentGlobalFilter.filterFn(row, id, currentGlobalFilter.resolvedValue, filterMeta => {
3005
- row.columnFiltersMeta[id] = filterMeta;
3006
- })) {
3007
- row.columnFilters.__global__ = true;
3008
- break;
3009
- }
3010
- }
3011
- if (row.columnFilters.__global__ !== true) {
3012
- row.columnFilters.__global__ = false;
3013
- }
3014
- }
3015
- }
3016
- const filterRowsImpl = row => {
3017
- // Horizontally filter rows through each column
3018
- for (let i = 0; i < filterableIds.length; i++) {
3019
- if (row.columnFilters[filterableIds[i]] === false) {
3020
- return false;
3021
- }
3022
- }
3023
- return true;
3024
- };
3025
-
3026
- // Filter final rows using all of the active filters
3027
- return filterRows(rowModel.rows, filterRowsImpl, table);
3028
- }, {
3029
- key: process.env.NODE_ENV === 'development' && 'getFilteredRowModel',
3030
- debug: () => table.options.debugAll ?? table.options.debugTable,
3031
- onChange: () => {
3032
- table._autoResetPageIndex();
3033
- }
3034
- });
3035
- }
3036
-
3037
- function getFacetedRowModel() {
3038
- return (table, columnId) => memo(() => [table.getPreFilteredRowModel(), table.getState().columnFilters, table.getState().globalFilter, table.getFilteredRowModel()], (preRowModel, columnFilters, globalFilter) => {
3039
- if (!preRowModel.rows.length || !(columnFilters != null && columnFilters.length) && !globalFilter) {
3040
- return preRowModel;
3041
- }
3042
- const filterableIds = [...columnFilters.map(d => d.id).filter(d => d !== columnId), globalFilter ? '__global__' : undefined].filter(Boolean);
3043
- const filterRowsImpl = row => {
3044
- // Horizontally filter rows through each column
3045
- for (let i = 0; i < filterableIds.length; i++) {
3046
- if (row.columnFilters[filterableIds[i]] === false) {
3047
- return false;
3048
- }
3049
- }
3050
- return true;
3051
- };
3052
- return filterRows(preRowModel.rows, filterRowsImpl, table);
3053
- }, {
3054
- key: process.env.NODE_ENV === 'development' && 'getFacetedRowModel_' + columnId,
3055
- debug: () => table.options.debugAll ?? table.options.debugTable,
3056
- onChange: () => {}
3057
- });
3058
- }
3059
-
3060
- function getFacetedUniqueValues() {
3061
- return (table, columnId) => memo(() => [table.getColumn(columnId).getFacetedRowModel()], facetedRowModel => {
3062
- let facetedUniqueValues = new Map();
3063
- for (let i = 0; i < facetedRowModel.flatRows.length; i++) {
3064
- const values = facetedRowModel.flatRows[i].getUniqueValues(columnId);
3065
- for (let j = 0; j < values.length; j++) {
3066
- const value = values[j];
3067
- if (facetedUniqueValues.has(value)) {
3068
- facetedUniqueValues.set(value, (facetedUniqueValues.get(value) ?? 0) + 1);
3069
- } else {
3070
- facetedUniqueValues.set(value, 1);
3071
- }
3072
- }
3073
- }
3074
- return facetedUniqueValues;
3075
- }, {
3076
- key: process.env.NODE_ENV === 'development' && 'getFacetedUniqueValues_' + columnId,
3077
- debug: () => table.options.debugAll ?? table.options.debugTable,
3078
- onChange: () => {}
3079
- });
3080
- }
3081
-
3082
- function getFacetedMinMaxValues() {
3083
- return (table, columnId) => memo(() => [table.getColumn(columnId).getFacetedRowModel()], facetedRowModel => {
3084
- var _facetedRowModel$flat;
3085
- const firstValue = (_facetedRowModel$flat = facetedRowModel.flatRows[0]) == null ? void 0 : _facetedRowModel$flat.getUniqueValues(columnId);
3086
- if (typeof firstValue === 'undefined') {
3087
- return undefined;
3088
- }
3089
- let facetedMinMaxValues = [firstValue, firstValue];
3090
- for (let i = 0; i < facetedRowModel.flatRows.length; i++) {
3091
- const values = facetedRowModel.flatRows[i].getUniqueValues(columnId);
3092
- for (let j = 0; j < values.length; j++) {
3093
- const value = values[j];
3094
- if (value < facetedMinMaxValues[0]) {
3095
- facetedMinMaxValues[0] = value;
3096
- } else if (value > facetedMinMaxValues[1]) {
3097
- facetedMinMaxValues[1] = value;
3098
- }
3099
- }
3100
- }
3101
- return facetedMinMaxValues;
3102
- }, {
3103
- key: process.env.NODE_ENV === 'development' && 'getFacetedMinMaxValues_' + columnId,
3104
- debug: () => table.options.debugAll ?? table.options.debugTable,
3105
- onChange: () => {}
3106
- });
3107
- }
3108
-
3109
- function getSortedRowModel() {
3110
- return table => memo(() => [table.getState().sorting, table.getPreSortedRowModel()], (sorting, rowModel) => {
3111
- if (!rowModel.rows.length || !(sorting != null && sorting.length)) {
3112
- return rowModel;
3113
- }
3114
- const sortingState = table.getState().sorting;
3115
- const sortedFlatRows = [];
3116
-
3117
- // Filter out sortings that correspond to non existing columns
3118
- const availableSorting = sortingState.filter(sort => table.getColumn(sort.id).getCanSort());
3119
- const columnInfoById = {};
3120
- availableSorting.forEach(sortEntry => {
3121
- const column = table.getColumn(sortEntry.id);
3122
- columnInfoById[sortEntry.id] = {
3123
- sortUndefined: column.columnDef.sortUndefined,
3124
- invertSorting: column.columnDef.invertSorting,
3125
- sortingFn: column.getSortingFn()
3126
- };
3127
- });
3128
- const sortData = rows => {
3129
- // This will also perform a stable sorting using the row index
3130
- // if needed.
3131
- const sortedData = [...rows];
3132
- sortedData.sort((rowA, rowB) => {
3133
- for (let i = 0; i < availableSorting.length; i += 1) {
3134
- const sortEntry = availableSorting[i];
3135
- const columnInfo = columnInfoById[sortEntry.id];
3136
- const isDesc = (sortEntry == null ? void 0 : sortEntry.desc) ?? false;
3137
- if (columnInfo.sortUndefined) {
3138
- const aValue = rowA.getValue(sortEntry.id);
3139
- const bValue = rowB.getValue(sortEntry.id);
3140
- const aUndefined = typeof aValue === 'undefined';
3141
- const bUndefined = typeof bValue === 'undefined';
3142
- if (aUndefined || bUndefined) {
3143
- return aUndefined && bUndefined ? 0 : aUndefined ? columnInfo.sortUndefined : -columnInfo.sortUndefined;
3144
- }
3145
- }
3146
-
3147
- // This function should always return in ascending order
3148
- let sortInt = columnInfo.sortingFn(rowA, rowB, sortEntry.id);
3149
- if (sortInt !== 0) {
3150
- if (isDesc) {
3151
- sortInt *= -1;
3152
- }
3153
- if (columnInfo.invertSorting) {
3154
- sortInt *= -1;
3155
- }
3156
- return sortInt;
3157
- }
3158
- }
3159
- return rowA.index - rowB.index;
3160
- });
3161
-
3162
- // If there are sub-rows, sort them
3163
- sortedData.forEach(row => {
3164
- var _row$subRows;
3165
- sortedFlatRows.push(row);
3166
- if ((_row$subRows = row.subRows) != null && _row$subRows.length) {
3167
- row.subRows = sortData(row.subRows);
3168
- }
3169
- });
3170
- return sortedData;
3171
- };
3172
- return {
3173
- rows: sortData(rowModel.rows),
3174
- flatRows: sortedFlatRows,
3175
- rowsById: rowModel.rowsById
3176
- };
3177
- }, {
3178
- key: process.env.NODE_ENV === 'development' && 'getSortedRowModel',
3179
- debug: () => table.options.debugAll ?? table.options.debugTable,
3180
- onChange: () => {
3181
- table._autoResetPageIndex();
3182
- }
3183
- });
3184
- }
3185
-
3186
- function getGroupedRowModel() {
3187
- return table => memo(() => [table.getState().grouping, table.getPreGroupedRowModel()], (grouping, rowModel) => {
3188
- if (!rowModel.rows.length || !grouping.length) {
3189
- return rowModel;
3190
- }
3191
-
3192
- // Filter the grouping list down to columns that exist
3193
- const existingGrouping = grouping.filter(columnId => table.getColumn(columnId));
3194
- const groupedFlatRows = [];
3195
- const groupedRowsById = {};
3196
- // const onlyGroupedFlatRows: Row[] = [];
3197
- // const onlyGroupedRowsById: Record<RowId, Row> = {};
3198
- // const nonGroupedFlatRows: Row[] = [];
3199
- // const nonGroupedRowsById: Record<RowId, Row> = {};
3200
-
3201
- // Recursively group the data
3202
- const groupUpRecursively = function (rows, depth, parentId) {
3203
- if (depth === void 0) {
3204
- depth = 0;
3205
- }
3206
- // Grouping depth has been been met
3207
- // Stop grouping and simply rewrite thd depth and row relationships
3208
- if (depth >= existingGrouping.length) {
3209
- return rows.map(row => {
3210
- row.depth = depth;
3211
- groupedFlatRows.push(row);
3212
- groupedRowsById[row.id] = row;
3213
- if (row.subRows) {
3214
- row.subRows = groupUpRecursively(row.subRows, depth + 1);
3215
- }
3216
- return row;
3217
- });
3218
- }
3219
- const columnId = existingGrouping[depth];
3220
-
3221
- // Group the rows together for this level
3222
- const rowGroupsMap = groupBy(rows, columnId);
3223
-
3224
- // Peform aggregations for each group
3225
- const aggregatedGroupedRows = Array.from(rowGroupsMap.entries()).map((_ref, index) => {
3226
- let [groupingValue, groupedRows] = _ref;
3227
- let id = `${columnId}:${groupingValue}`;
3228
- id = parentId ? `${parentId}>${id}` : id;
3229
-
3230
- // First, Recurse to group sub rows before aggregation
3231
- const subRows = groupUpRecursively(groupedRows, depth + 1, id);
3232
-
3233
- // Flatten the leaf rows of the rows in this group
3234
- const leafRows = depth ? flattenBy(groupedRows, row => row.subRows) : groupedRows;
3235
- const row = createRow(table, id, leafRows[0].original, index, depth);
3236
- Object.assign(row, {
3237
- groupingColumnId: columnId,
3238
- groupingValue,
3239
- subRows,
3240
- leafRows,
3241
- getValue: columnId => {
3242
- // Don't aggregate columns that are in the grouping
3243
- if (existingGrouping.includes(columnId)) {
3244
- if (row._valuesCache.hasOwnProperty(columnId)) {
3245
- return row._valuesCache[columnId];
3246
- }
3247
- if (groupedRows[0]) {
3248
- row._valuesCache[columnId] = groupedRows[0].getValue(columnId) ?? undefined;
3249
- }
3250
- return row._valuesCache[columnId];
3251
- }
3252
- if (row._groupingValuesCache.hasOwnProperty(columnId)) {
3253
- return row._groupingValuesCache[columnId];
3254
- }
3255
-
3256
- // Aggregate the values
3257
- const column = table.getColumn(columnId);
3258
- const aggregateFn = column.getAggregationFn();
3259
- if (aggregateFn) {
3260
- row._groupingValuesCache[columnId] = aggregateFn(columnId, leafRows, groupedRows);
3261
- return row._groupingValuesCache[columnId];
3262
- }
3263
- }
3264
- });
3265
- subRows.forEach(subRow => {
3266
- groupedFlatRows.push(subRow);
3267
- groupedRowsById[subRow.id] = subRow;
3268
- // if (subRow.getIsGrouped?.()) {
3269
- // onlyGroupedFlatRows.push(subRow);
3270
- // onlyGroupedRowsById[subRow.id] = subRow;
3271
- // } else {
3272
- // nonGroupedFlatRows.push(subRow);
3273
- // nonGroupedRowsById[subRow.id] = subRow;
3274
- // }
3275
- });
3276
-
3277
- return row;
3278
- });
3279
- return aggregatedGroupedRows;
3280
- };
3281
- const groupedRows = groupUpRecursively(rowModel.rows, 0, '');
3282
- groupedRows.forEach(subRow => {
3283
- groupedFlatRows.push(subRow);
3284
- groupedRowsById[subRow.id] = subRow;
3285
- // if (subRow.getIsGrouped?.()) {
3286
- // onlyGroupedFlatRows.push(subRow);
3287
- // onlyGroupedRowsById[subRow.id] = subRow;
3288
- // } else {
3289
- // nonGroupedFlatRows.push(subRow);
3290
- // nonGroupedRowsById[subRow.id] = subRow;
3291
- // }
3292
- });
3293
-
3294
- return {
3295
- rows: groupedRows,
3296
- flatRows: groupedFlatRows,
3297
- rowsById: groupedRowsById
3298
- };
3299
- }, {
3300
- key: process.env.NODE_ENV === 'development' && 'getGroupedRowModel',
3301
- debug: () => table.options.debugAll ?? table.options.debugTable,
3302
- onChange: () => {
3303
- table._queue(() => {
3304
- table._autoResetExpanded();
3305
- table._autoResetPageIndex();
3306
- });
3307
- }
3308
- });
3309
- }
3310
- function groupBy(rows, columnId) {
3311
- const groupMap = new Map();
3312
- return rows.reduce((map, row) => {
3313
- const resKey = `${row.getValue(columnId)}`;
3314
- const previous = map.get(resKey);
3315
- if (!previous) {
3316
- map.set(resKey, [row]);
3317
- } else {
3318
- previous.push(row);
3319
- }
3320
- return map;
3321
- }, groupMap);
3322
- }
3323
-
3324
- function getExpandedRowModel() {
3325
- return table => memo(() => [table.getState().expanded, table.getPreExpandedRowModel(), table.options.paginateExpandedRows], (expanded, rowModel, paginateExpandedRows) => {
3326
- if (!rowModel.rows.length || expanded !== true && !Object.keys(expanded ?? {}).length) {
3327
- return rowModel;
3328
- }
3329
- if (!paginateExpandedRows) {
3330
- // Only expand rows at this point if they are being paginated
3331
- return rowModel;
3332
- }
3333
- return expandRows(rowModel);
3334
- }, {
3335
- key: process.env.NODE_ENV === 'development' && 'getExpandedRowModel',
3336
- debug: () => table.options.debugAll ?? table.options.debugTable
3337
- });
3338
- }
3339
- function expandRows(rowModel) {
3340
- const expandedRows = [];
3341
- const handleRow = row => {
3342
- var _row$subRows;
3343
- expandedRows.push(row);
3344
- if ((_row$subRows = row.subRows) != null && _row$subRows.length && row.getIsExpanded()) {
3345
- row.subRows.forEach(handleRow);
3346
- }
3347
- };
3348
- rowModel.rows.forEach(handleRow);
3349
- return {
3350
- rows: expandedRows,
3351
- flatRows: rowModel.flatRows,
3352
- rowsById: rowModel.rowsById
3353
- };
3354
- }
3355
-
3356
- function getPaginationRowModel(opts) {
3357
- return table => memo(() => [table.getState().pagination, table.getPrePaginationRowModel(), table.options.paginateExpandedRows ? undefined : table.getState().expanded], (pagination, rowModel) => {
3358
- if (!rowModel.rows.length) {
3359
- return rowModel;
3360
- }
3361
- const {
3362
- pageSize,
3363
- pageIndex
3364
- } = pagination;
3365
- let {
3366
- rows,
3367
- flatRows,
3368
- rowsById
3369
- } = rowModel;
3370
- const pageStart = pageSize * pageIndex;
3371
- const pageEnd = pageStart + pageSize;
3372
- rows = rows.slice(pageStart, pageEnd);
3373
- let paginatedRowModel;
3374
- if (!table.options.paginateExpandedRows) {
3375
- paginatedRowModel = expandRows({
3376
- rows,
3377
- flatRows,
3378
- rowsById
3379
- });
3380
- } else {
3381
- paginatedRowModel = {
3382
- rows,
3383
- flatRows,
3384
- rowsById
3385
- };
3386
- }
3387
- paginatedRowModel.flatRows = [];
3388
- const handleRow = row => {
3389
- paginatedRowModel.flatRows.push(row);
3390
- if (row.subRows.length) {
3391
- row.subRows.forEach(handleRow);
3392
- }
3393
- };
3394
- paginatedRowModel.rows.forEach(handleRow);
3395
- return paginatedRowModel;
3396
- }, {
3397
- key: process.env.NODE_ENV === 'development' && 'getPaginationRowModel',
3398
- debug: () => table.options.debugAll ?? table.options.debugTable
3399
- });
3400
- }
3401
-
3402
- exports.ColumnSizing = ColumnSizing;
3403
- exports.Expanding = Expanding;
3404
- exports.Filters = Filters;
3405
- exports.Grouping = Grouping;
3406
- exports.Headers = Headers;
3407
- exports.Ordering = Ordering;
3408
- exports.Pagination = Pagination;
3409
- exports.Pinning = Pinning;
3410
- exports.RowSelection = RowSelection;
3411
- exports.Sorting = Sorting;
3412
- exports.Visibility = Visibility;
3413
- exports.aggregationFns = aggregationFns;
3414
- exports.buildHeaderGroups = buildHeaderGroups;
3415
- exports.createCell = createCell;
3416
- exports.createColumn = createColumn;
3417
- exports.createColumnHelper = createColumnHelper;
3418
- exports.createRow = createRow;
3419
- exports.createTable = createTable;
3420
- exports.defaultColumnSizing = defaultColumnSizing;
3421
- exports.expandRows = expandRows;
3422
- exports.filterFns = filterFns;
3423
- exports.flattenBy = flattenBy;
3424
- exports.functionalUpdate = functionalUpdate;
3425
- exports.getCoreRowModel = getCoreRowModel;
3426
- exports.getExpandedRowModel = getExpandedRowModel;
3427
- exports.getFacetedMinMaxValues = getFacetedMinMaxValues;
3428
- exports.getFacetedRowModel = getFacetedRowModel;
3429
- exports.getFacetedUniqueValues = getFacetedUniqueValues;
3430
- exports.getFilteredRowModel = getFilteredRowModel;
3431
- exports.getGroupedRowModel = getGroupedRowModel;
3432
- exports.getPaginationRowModel = getPaginationRowModel;
3433
- exports.getSortedRowModel = getSortedRowModel;
3434
- exports.isFunction = isFunction;
3435
- exports.isRowSelected = isRowSelected;
3436
- exports.isSubRowSelected = isSubRowSelected;
3437
- exports.makeStateUpdater = makeStateUpdater;
3438
- exports.memo = memo;
3439
- exports.noop = noop;
3440
- exports.orderColumns = orderColumns;
3441
- exports.passiveEventSupported = passiveEventSupported;
3442
- exports.reSplitAlphaNumeric = reSplitAlphaNumeric;
3443
- exports.selectRowsFn = selectRowsFn;
3444
- exports.shouldAutoRemoveFilter = shouldAutoRemoveFilter;
3445
- exports.sortingFns = sortingFns;
3446
- //# sourceMappingURL=index.js.map