Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 

3583 строки
144 KiB

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