@popmenu/common-ui 0.18.3 → 0.18.4-alpha.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/build/components/index.d.ts +0 -1
  2. package/build/index.es.js +1 -2311
  3. package/build/index.es.js.map +1 -1
  4. package/build/index.js +0 -2309
  5. package/build/index.js.map +1 -1
  6. package/package.json +4 -11
  7. package/build/components/Table/Table.d.ts +0 -3
  8. package/build/components/Table/TableProps.d.ts +0 -28
  9. package/build/components/Table/TableStyles.d.ts +0 -2
  10. package/build/components/Table/index.d.ts +0 -2
  11. package/build/components/Table/util/makeColumns.d.ts +0 -7
  12. package/build/components/TableActionsCell/TableActionsCell.d.ts +0 -3
  13. package/build/components/TableActionsCell/TableActionsCellProps.d.ts +0 -10
  14. package/build/components/TableActionsCell/index.d.ts +0 -2
  15. package/build/components/TableBody/TableBody.d.ts +0 -2
  16. package/build/components/TableBody/index.d.ts +0 -1
  17. package/build/components/TableCell/TableCell.d.ts +0 -2
  18. package/build/components/TableCell/TableCellStyles.d.ts +0 -1
  19. package/build/components/TableCell/index.d.ts +0 -1
  20. package/build/components/TableFooter/TableFooter.d.ts +0 -2
  21. package/build/components/TableFooter/index.d.ts +0 -1
  22. package/build/components/TableHeader/TableHeader.d.ts +0 -2
  23. package/build/components/TableHeader/index.d.ts +0 -1
  24. package/build/components/TableHeaderCell/TableHeaderCell.d.ts +0 -3
  25. package/build/components/TableHeaderCell/TableHeaderCellProps.d.ts +0 -8
  26. package/build/components/TableHeaderCell/TableHeaderCellStyles.d.ts +0 -2
  27. package/build/components/TableHeaderCell/index.d.ts +0 -1
  28. package/build/components/TableHeaderRow/TableHeaderRow.d.ts +0 -2
  29. package/build/components/TableHeaderRow/index.d.ts +0 -1
  30. package/build/components/TableRow/TableRow.d.ts +0 -2
  31. package/build/components/TableRow/TableRowStyles.d.ts +0 -1
  32. package/build/components/TableRow/index.d.ts +0 -1
package/build/index.es.js CHANGED
@@ -40,16 +40,13 @@ export { default as ListItem } from '@material-ui/core/ListItem';
40
40
  export { default as ListItemIcon } from '@material-ui/core/ListItemIcon';
41
41
  export { default as ListItemSecondaryAction } from '@material-ui/core/ListItemSecondaryAction';
42
42
  export { default as ListItemText } from '@material-ui/core/ListItemText';
43
- import Menu from '@material-ui/core/Menu';
44
43
  export { default as Menu } from '@material-ui/core/Menu';
45
- import MenuItem from '@material-ui/core/MenuItem';
46
44
  export { default as MenuItem } from '@material-ui/core/MenuItem';
47
45
  export { default as MenuList } from '@material-ui/core/MenuList';
48
46
  import MuiRadio from '@material-ui/core/Radio';
49
47
  import TextField from '@material-ui/core/TextField';
50
48
  export { default as TextField } from '@material-ui/core/TextField';
51
49
  import MuiSwitch from '@material-ui/core/Switch';
52
- import { Pagination } from '@material-ui/lab';
53
50
  export { default as Tab } from '@material-ui/core/Tab';
54
51
  export { default as Tabs } from '@material-ui/core/Tabs';
55
52
  import MuiToggleButton from '@material-ui/lab/ToggleButton';
@@ -92,70 +89,6 @@ function __rest(s, e) {
92
89
  t[p[i]] = s[p[i]];
93
90
  }
94
91
  return t;
95
- }
96
-
97
- function __spreadArray(to, from, pack) {
98
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
99
- if (ar || !(i in from)) {
100
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
101
- ar[i] = from[i];
102
- }
103
- }
104
- return to.concat(ar || from);
105
- }
106
-
107
- var _path$3K;
108
-
109
- function _extends$3$() { _extends$3$ = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$3$.apply(this, arguments); }
110
-
111
- function SvgMore(props) {
112
- return /*#__PURE__*/React.createElement("svg", _extends$3$({
113
- viewBox: "0 0 16 16",
114
- strokeLinecap: "round",
115
- strokeLinejoin: "round",
116
- stroke: "currentColor",
117
- width: "1em",
118
- height: "1em",
119
- fill: "none"
120
- }, props), _path$3K || (_path$3K = /*#__PURE__*/React.createElement("path", {
121
- d: "M8 8.667a.667.667 0 100-1.334.667.667 0 000 1.334zM8 4a.667.667 0 100-1.333A.667.667 0 008 4zm0 9.333A.667.667 0 108 12a.667.667 0 000 1.333z"
122
- })));
123
- }
124
-
125
- var _path$2X;
126
-
127
- function _extends$3b() { _extends$3b = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$3b.apply(this, arguments); }
128
-
129
- function SvgChevronDown(props) {
130
- return /*#__PURE__*/React.createElement("svg", _extends$3b({
131
- viewBox: "0 0 16 16",
132
- strokeLinecap: "round",
133
- strokeLinejoin: "round",
134
- stroke: "currentColor",
135
- width: "1em",
136
- height: "1em",
137
- fill: "none"
138
- }, props), _path$2X || (_path$2X = /*#__PURE__*/React.createElement("path", {
139
- d: "M4 6l4 4 4-4"
140
- })));
141
- }
142
-
143
- var _path$2W;
144
-
145
- function _extends$3a() { _extends$3a = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends$3a.apply(this, arguments); }
146
-
147
- function SvgChevronUp(props) {
148
- return /*#__PURE__*/React.createElement("svg", _extends$3a({
149
- viewBox: "0 0 16 16",
150
- strokeLinecap: "round",
151
- strokeLinejoin: "round",
152
- stroke: "currentColor",
153
- width: "1em",
154
- height: "1em",
155
- fill: "none"
156
- }, props), _path$2W || (_path$2W = /*#__PURE__*/React.createElement("path", {
157
- d: "M12 10L8 6l-4 4"
158
- })));
159
92
  }
160
93
 
161
94
  var _path$1f;
@@ -1057,2249 +990,6 @@ var Switch = forwardRef(function (props, ref) {
1057
990
  });
1058
991
  Switch.displayName = 'Switch';
1059
992
 
1060
- let renderErr = 'Renderer Error ☝️';
1061
-
1062
- const actions = {
1063
- init: 'init',
1064
- };
1065
-
1066
- const defaultRenderer = ({ value = '' }) => value;
1067
- const emptyRenderer = () => <>&nbsp;</>;
1068
-
1069
- const defaultColumn = {
1070
- Cell: defaultRenderer,
1071
- width: 150,
1072
- minWidth: 0,
1073
- maxWidth: Number.MAX_SAFE_INTEGER,
1074
- };
1075
-
1076
- function mergeProps(...propList) {
1077
- return propList.reduce((props, next) => {
1078
- const { style, className, ...rest } = next;
1079
-
1080
- props = {
1081
- ...props,
1082
- ...rest,
1083
- };
1084
-
1085
- if (style) {
1086
- props.style = props.style
1087
- ? { ...(props.style || {}), ...(style || {}) }
1088
- : style;
1089
- }
1090
-
1091
- if (className) {
1092
- props.className = props.className
1093
- ? props.className + ' ' + className
1094
- : className;
1095
- }
1096
-
1097
- if (props.className === '') {
1098
- delete props.className;
1099
- }
1100
-
1101
- return props
1102
- }, {})
1103
- }
1104
-
1105
- function handlePropGetter(prevProps, userProps, meta) {
1106
- // Handle a lambda, pass it the previous props
1107
- if (typeof userProps === 'function') {
1108
- return handlePropGetter({}, userProps(prevProps, meta))
1109
- }
1110
-
1111
- // Handle an array, merge each item as separate props
1112
- if (Array.isArray(userProps)) {
1113
- return mergeProps(prevProps, ...userProps)
1114
- }
1115
-
1116
- // Handle an object by default, merge the two objects
1117
- return mergeProps(prevProps, userProps)
1118
- }
1119
-
1120
- const makePropGetter = (hooks, meta = {}) => {
1121
- return (userProps = {}) =>
1122
- [...hooks, userProps].reduce(
1123
- (prev, next) =>
1124
- handlePropGetter(prev, next, {
1125
- ...meta,
1126
- userProps,
1127
- }),
1128
- {}
1129
- )
1130
- };
1131
-
1132
- const reduceHooks = (hooks, initial, meta = {}, allowUndefined) =>
1133
- hooks.reduce((prev, next) => {
1134
- const nextValue = next(prev, meta);
1135
- if (process.env.NODE_ENV !== 'production') {
1136
- if (!allowUndefined && typeof nextValue === 'undefined') {
1137
- console.info(next);
1138
- throw new Error(
1139
- 'React Table: A reducer hook ☝️ just returned undefined! This is not allowed.'
1140
- )
1141
- }
1142
- }
1143
- return nextValue
1144
- }, initial);
1145
-
1146
- const loopHooks = (hooks, context, meta = {}) =>
1147
- hooks.forEach(hook => {
1148
- const nextValue = hook(context, meta);
1149
- if (process.env.NODE_ENV !== 'production') {
1150
- if (typeof nextValue !== 'undefined') {
1151
- console.info(hook, nextValue);
1152
- throw new Error(
1153
- 'React Table: A loop-type hook ☝️ just returned a value! This is not allowed.'
1154
- )
1155
- }
1156
- }
1157
- });
1158
-
1159
- function ensurePluginOrder(plugins, befores, pluginName, afters) {
1160
- if (process.env.NODE_ENV !== 'production' && afters) {
1161
- throw new Error(
1162
- `Defining plugins in the "after" section of ensurePluginOrder is no longer supported (see plugin ${pluginName})`
1163
- )
1164
- }
1165
- const pluginIndex = plugins.findIndex(
1166
- plugin => plugin.pluginName === pluginName
1167
- );
1168
-
1169
- if (pluginIndex === -1) {
1170
- if (process.env.NODE_ENV !== 'production') {
1171
- throw new Error(`The plugin "${pluginName}" was not found in the plugin list!
1172
- This usually means you need to need to name your plugin hook by setting the 'pluginName' property of the hook function, eg:
1173
-
1174
- ${pluginName}.pluginName = '${pluginName}'
1175
- `)
1176
- }
1177
- }
1178
-
1179
- befores.forEach(before => {
1180
- const beforeIndex = plugins.findIndex(
1181
- plugin => plugin.pluginName === before
1182
- );
1183
- if (beforeIndex > -1 && beforeIndex > pluginIndex) {
1184
- if (process.env.NODE_ENV !== 'production') {
1185
- throw new Error(
1186
- `React Table: The ${pluginName} plugin hook must be placed after the ${before} plugin hook!`
1187
- )
1188
- }
1189
- }
1190
- });
1191
- }
1192
-
1193
- function functionalUpdate(updater, old) {
1194
- return typeof updater === 'function' ? updater(old) : updater
1195
- }
1196
-
1197
- function useGetLatest(obj) {
1198
- const ref = React__default.useRef();
1199
- ref.current = obj;
1200
-
1201
- return React__default.useCallback(() => ref.current, [])
1202
- }
1203
-
1204
- // SSR has issues with useLayoutEffect still, so use useEffect during SSR
1205
- const safeUseLayoutEffect =
1206
- typeof document !== 'undefined' ? React__default.useLayoutEffect : React__default.useEffect;
1207
-
1208
- function useMountedLayoutEffect(fn, deps) {
1209
- const mountedRef = React__default.useRef(false);
1210
-
1211
- safeUseLayoutEffect(() => {
1212
- if (mountedRef.current) {
1213
- fn();
1214
- }
1215
- mountedRef.current = true;
1216
- // eslint-disable-next-line
1217
- }, deps);
1218
- }
1219
-
1220
- function makeRenderer(instance, column, meta = {}) {
1221
- return (type, userProps = {}) => {
1222
- const Comp = typeof type === 'string' ? column[type] : type;
1223
-
1224
- if (typeof Comp === 'undefined') {
1225
- console.info(column);
1226
- throw new Error(renderErr)
1227
- }
1228
-
1229
- return flexRender(Comp, { ...instance, column, ...meta, ...userProps })
1230
- }
1231
- }
1232
-
1233
- function flexRender(Comp, props) {
1234
- return isReactComponent(Comp) ? <Comp {...props} /> : Comp
1235
- }
1236
-
1237
- function isReactComponent(component) {
1238
- return (
1239
- isClassComponent(component) ||
1240
- typeof component === 'function' ||
1241
- isExoticComponent(component)
1242
- )
1243
- }
1244
-
1245
- function isClassComponent(component) {
1246
- return (
1247
- typeof component === 'function' &&
1248
- (() => {
1249
- const proto = Object.getPrototypeOf(component);
1250
- return proto.prototype && proto.prototype.isReactComponent
1251
- })()
1252
- )
1253
- }
1254
-
1255
- function isExoticComponent(component) {
1256
- return (
1257
- typeof component === 'object' &&
1258
- typeof component.$$typeof === 'symbol' &&
1259
- ['react.memo', 'react.forward_ref'].includes(component.$$typeof.description)
1260
- )
1261
- }
1262
-
1263
- // Build the visible columns, headers and flat column list
1264
- function linkColumnStructure(columns, parent, depth = 0) {
1265
- return columns.map(column => {
1266
- column = {
1267
- ...column,
1268
- parent,
1269
- depth,
1270
- };
1271
-
1272
- assignColumnAccessor(column);
1273
-
1274
- if (column.columns) {
1275
- column.columns = linkColumnStructure(column.columns, column, depth + 1);
1276
- }
1277
- return column
1278
- })
1279
- }
1280
-
1281
- function flattenColumns(columns) {
1282
- return flattenBy(columns, 'columns')
1283
- }
1284
-
1285
- function assignColumnAccessor(column) {
1286
- // First check for string accessor
1287
- let { id, accessor, Header } = column;
1288
-
1289
- if (typeof accessor === 'string') {
1290
- id = id || accessor;
1291
- const accessorPath = accessor.split('.');
1292
- accessor = row => getBy(row, accessorPath);
1293
- }
1294
-
1295
- if (!id && typeof Header === 'string' && Header) {
1296
- id = Header;
1297
- }
1298
-
1299
- if (!id && column.columns) {
1300
- console.error(column);
1301
- throw new Error('A column ID (or unique "Header" value) is required!')
1302
- }
1303
-
1304
- if (!id) {
1305
- console.error(column);
1306
- throw new Error('A column ID (or string accessor) is required!')
1307
- }
1308
-
1309
- Object.assign(column, {
1310
- id,
1311
- accessor,
1312
- });
1313
-
1314
- return column
1315
- }
1316
-
1317
- function decorateColumn(column, userDefaultColumn) {
1318
- if (!userDefaultColumn) {
1319
- throw new Error()
1320
- }
1321
- Object.assign(column, {
1322
- // Make sure there is a fallback header, just in case
1323
- Header: emptyRenderer,
1324
- Footer: emptyRenderer,
1325
- ...defaultColumn,
1326
- ...userDefaultColumn,
1327
- ...column,
1328
- });
1329
-
1330
- Object.assign(column, {
1331
- originalWidth: column.width,
1332
- });
1333
-
1334
- return column
1335
- }
1336
-
1337
- // Build the header groups from the bottom up
1338
- function makeHeaderGroups(
1339
- allColumns,
1340
- defaultColumn,
1341
- additionalHeaderProperties = () => ({})
1342
- ) {
1343
- const headerGroups = [];
1344
-
1345
- let scanColumns = allColumns;
1346
-
1347
- let uid = 0;
1348
- const getUID = () => uid++;
1349
-
1350
- while (scanColumns.length) {
1351
- // The header group we are creating
1352
- const headerGroup = {
1353
- headers: [],
1354
- };
1355
-
1356
- // The parent columns we're going to scan next
1357
- const parentColumns = [];
1358
-
1359
- const hasParents = scanColumns.some(d => d.parent);
1360
-
1361
- // Scan each column for parents
1362
- scanColumns.forEach(column => {
1363
- // What is the latest (last) parent column?
1364
- let latestParentColumn = [...parentColumns].reverse()[0];
1365
-
1366
- let newParent;
1367
-
1368
- if (hasParents) {
1369
- // If the column has a parent, add it if necessary
1370
- if (column.parent) {
1371
- newParent = {
1372
- ...column.parent,
1373
- originalId: column.parent.id,
1374
- id: `${column.parent.id}_${getUID()}`,
1375
- headers: [column],
1376
- ...additionalHeaderProperties(column),
1377
- };
1378
- } else {
1379
- // If other columns have parents, we'll need to add a place holder if necessary
1380
- const originalId = `${column.id}_placeholder`;
1381
- newParent = decorateColumn(
1382
- {
1383
- originalId,
1384
- id: `${column.id}_placeholder_${getUID()}`,
1385
- placeholderOf: column,
1386
- headers: [column],
1387
- ...additionalHeaderProperties(column),
1388
- },
1389
- defaultColumn
1390
- );
1391
- }
1392
-
1393
- // If the resulting parent columns are the same, just add
1394
- // the column and increment the header span
1395
- if (
1396
- latestParentColumn &&
1397
- latestParentColumn.originalId === newParent.originalId
1398
- ) {
1399
- latestParentColumn.headers.push(column);
1400
- } else {
1401
- parentColumns.push(newParent);
1402
- }
1403
- }
1404
-
1405
- headerGroup.headers.push(column);
1406
- });
1407
-
1408
- headerGroups.push(headerGroup);
1409
-
1410
- // Start scanning the parent columns
1411
- scanColumns = parentColumns;
1412
- }
1413
-
1414
- return headerGroups.reverse()
1415
- }
1416
-
1417
- const pathObjCache = new Map();
1418
-
1419
- function getBy(obj, path, def) {
1420
- if (!path) {
1421
- return obj
1422
- }
1423
- const cacheKey = typeof path === 'function' ? path : JSON.stringify(path);
1424
-
1425
- const pathObj =
1426
- pathObjCache.get(cacheKey) ||
1427
- (() => {
1428
- const pathObj = makePathArray(path);
1429
- pathObjCache.set(cacheKey, pathObj);
1430
- return pathObj
1431
- })();
1432
-
1433
- let val;
1434
-
1435
- try {
1436
- val = pathObj.reduce((cursor, pathPart) => cursor[pathPart], obj);
1437
- } catch (e) {
1438
- // continue regardless of error
1439
- }
1440
- return typeof val !== 'undefined' ? val : def
1441
- }
1442
-
1443
- function getFirstDefined(...args) {
1444
- for (let i = 0; i < args.length; i += 1) {
1445
- if (typeof args[i] !== 'undefined') {
1446
- return args[i]
1447
- }
1448
- }
1449
- }
1450
-
1451
- function isFunction(a) {
1452
- if (typeof a === 'function') {
1453
- return a
1454
- }
1455
- }
1456
-
1457
- function flattenBy(arr, key) {
1458
- const flat = [];
1459
-
1460
- const recurse = arr => {
1461
- arr.forEach(d => {
1462
- if (!d[key]) {
1463
- flat.push(d);
1464
- } else {
1465
- recurse(d[key]);
1466
- }
1467
- });
1468
- };
1469
-
1470
- recurse(arr);
1471
-
1472
- return flat
1473
- }
1474
-
1475
- function expandRows(
1476
- rows,
1477
- { manualExpandedKey, expanded, expandSubRows = true }
1478
- ) {
1479
- const expandedRows = [];
1480
-
1481
- const handleRow = (row, addToExpandedRows = true) => {
1482
- row.isExpanded =
1483
- (row.original && row.original[manualExpandedKey]) || expanded[row.id];
1484
-
1485
- row.canExpand = row.subRows && !!row.subRows.length;
1486
-
1487
- if (addToExpandedRows) {
1488
- expandedRows.push(row);
1489
- }
1490
-
1491
- if (row.subRows && row.subRows.length && row.isExpanded) {
1492
- row.subRows.forEach(row => handleRow(row, expandSubRows));
1493
- }
1494
- };
1495
-
1496
- rows.forEach(row => handleRow(row));
1497
-
1498
- return expandedRows
1499
- }
1500
-
1501
- function unpreparedAccessWarning() {
1502
- throw new Error(
1503
- 'React-Table: You have not called prepareRow(row) one or more rows you are attempting to render.'
1504
- )
1505
- }
1506
-
1507
- //
1508
-
1509
- const reOpenBracket = /\[/g;
1510
- const reCloseBracket = /\]/g;
1511
-
1512
- function makePathArray(obj) {
1513
- return (
1514
- flattenDeep(obj)
1515
- // remove all periods in parts
1516
- .map(d => String(d).replace('.', '_'))
1517
- // join parts using period
1518
- .join('.')
1519
- // replace brackets with periods
1520
- .replace(reOpenBracket, '.')
1521
- .replace(reCloseBracket, '')
1522
- // split it back out on periods
1523
- .split('.')
1524
- )
1525
- }
1526
-
1527
- function flattenDeep(arr, newArr = []) {
1528
- if (!Array.isArray(arr)) {
1529
- newArr.push(arr);
1530
- } else {
1531
- for (let i = 0; i < arr.length; i += 1) {
1532
- flattenDeep(arr[i], newArr);
1533
- }
1534
- }
1535
- return newArr
1536
- }
1537
-
1538
- const defaultGetTableProps = props => ({
1539
- role: 'table',
1540
- ...props,
1541
- });
1542
-
1543
- const defaultGetTableBodyProps = props => ({
1544
- role: 'rowgroup',
1545
- ...props,
1546
- });
1547
-
1548
- const defaultGetHeaderProps = (props, { column }) => ({
1549
- key: `header_${column.id}`,
1550
- colSpan: column.totalVisibleHeaderCount,
1551
- role: 'columnheader',
1552
- ...props,
1553
- });
1554
-
1555
- const defaultGetFooterProps = (props, { column }) => ({
1556
- key: `footer_${column.id}`,
1557
- colSpan: column.totalVisibleHeaderCount,
1558
- ...props,
1559
- });
1560
-
1561
- const defaultGetHeaderGroupProps = (props, { index }) => ({
1562
- key: `headerGroup_${index}`,
1563
- role: 'row',
1564
- ...props,
1565
- });
1566
-
1567
- const defaultGetFooterGroupProps = (props, { index }) => ({
1568
- key: `footerGroup_${index}`,
1569
- ...props,
1570
- });
1571
-
1572
- const defaultGetRowProps = (props, { row }) => ({
1573
- key: `row_${row.id}`,
1574
- role: 'row',
1575
- ...props,
1576
- });
1577
-
1578
- const defaultGetCellProps = (props, { cell }) => ({
1579
- key: `cell_${cell.row.id}_${cell.column.id}`,
1580
- role: 'cell',
1581
- ...props,
1582
- });
1583
-
1584
- function makeDefaultPluginHooks() {
1585
- return {
1586
- useOptions: [],
1587
- stateReducers: [],
1588
- useControlledState: [],
1589
- columns: [],
1590
- columnsDeps: [],
1591
- allColumns: [],
1592
- allColumnsDeps: [],
1593
- accessValue: [],
1594
- materializedColumns: [],
1595
- materializedColumnsDeps: [],
1596
- useInstanceAfterData: [],
1597
- visibleColumns: [],
1598
- visibleColumnsDeps: [],
1599
- headerGroups: [],
1600
- headerGroupsDeps: [],
1601
- useInstanceBeforeDimensions: [],
1602
- useInstance: [],
1603
- prepareRow: [],
1604
- getTableProps: [defaultGetTableProps],
1605
- getTableBodyProps: [defaultGetTableBodyProps],
1606
- getHeaderGroupProps: [defaultGetHeaderGroupProps],
1607
- getFooterGroupProps: [defaultGetFooterGroupProps],
1608
- getHeaderProps: [defaultGetHeaderProps],
1609
- getFooterProps: [defaultGetFooterProps],
1610
- getRowProps: [defaultGetRowProps],
1611
- getCellProps: [defaultGetCellProps],
1612
- useFinalInstance: [],
1613
- }
1614
- }
1615
-
1616
- actions.resetHiddenColumns = 'resetHiddenColumns';
1617
- actions.toggleHideColumn = 'toggleHideColumn';
1618
- actions.setHiddenColumns = 'setHiddenColumns';
1619
- actions.toggleHideAllColumns = 'toggleHideAllColumns';
1620
-
1621
- const useColumnVisibility = hooks => {
1622
- hooks.getToggleHiddenProps = [defaultGetToggleHiddenProps];
1623
- hooks.getToggleHideAllColumnsProps = [defaultGetToggleHideAllColumnsProps];
1624
-
1625
- hooks.stateReducers.push(reducer$2);
1626
- hooks.useInstanceBeforeDimensions.push(useInstanceBeforeDimensions);
1627
- hooks.headerGroupsDeps.push((deps, { instance }) => [
1628
- ...deps,
1629
- instance.state.hiddenColumns,
1630
- ]);
1631
- hooks.useInstance.push(useInstance$2);
1632
- };
1633
-
1634
- useColumnVisibility.pluginName = 'useColumnVisibility';
1635
-
1636
- const defaultGetToggleHiddenProps = (props, { column }) => [
1637
- props,
1638
- {
1639
- onChange: e => {
1640
- column.toggleHidden(!e.target.checked);
1641
- },
1642
- style: {
1643
- cursor: 'pointer',
1644
- },
1645
- checked: column.isVisible,
1646
- title: 'Toggle Column Visible',
1647
- },
1648
- ];
1649
-
1650
- const defaultGetToggleHideAllColumnsProps = (props, { instance }) => [
1651
- props,
1652
- {
1653
- onChange: e => {
1654
- instance.toggleHideAllColumns(!e.target.checked);
1655
- },
1656
- style: {
1657
- cursor: 'pointer',
1658
- },
1659
- checked: !instance.allColumnsHidden && !instance.state.hiddenColumns.length,
1660
- title: 'Toggle All Columns Hidden',
1661
- indeterminate:
1662
- !instance.allColumnsHidden && instance.state.hiddenColumns.length,
1663
- },
1664
- ];
1665
-
1666
- function reducer$2(state, action, previousState, instance) {
1667
- if (action.type === actions.init) {
1668
- return {
1669
- hiddenColumns: [],
1670
- ...state,
1671
- }
1672
- }
1673
-
1674
- if (action.type === actions.resetHiddenColumns) {
1675
- return {
1676
- ...state,
1677
- hiddenColumns: instance.initialState.hiddenColumns || [],
1678
- }
1679
- }
1680
-
1681
- if (action.type === actions.toggleHideColumn) {
1682
- const should =
1683
- typeof action.value !== 'undefined'
1684
- ? action.value
1685
- : !state.hiddenColumns.includes(action.columnId);
1686
-
1687
- const hiddenColumns = should
1688
- ? [...state.hiddenColumns, action.columnId]
1689
- : state.hiddenColumns.filter(d => d !== action.columnId);
1690
-
1691
- return {
1692
- ...state,
1693
- hiddenColumns,
1694
- }
1695
- }
1696
-
1697
- if (action.type === actions.setHiddenColumns) {
1698
- return {
1699
- ...state,
1700
- hiddenColumns: functionalUpdate(action.value, state.hiddenColumns),
1701
- }
1702
- }
1703
-
1704
- if (action.type === actions.toggleHideAllColumns) {
1705
- const shouldAll =
1706
- typeof action.value !== 'undefined'
1707
- ? action.value
1708
- : !state.hiddenColumns.length;
1709
-
1710
- return {
1711
- ...state,
1712
- hiddenColumns: shouldAll ? instance.allColumns.map(d => d.id) : [],
1713
- }
1714
- }
1715
- }
1716
-
1717
- function useInstanceBeforeDimensions(instance) {
1718
- const {
1719
- headers,
1720
- state: { hiddenColumns },
1721
- } = instance;
1722
-
1723
- const isMountedRef = React__default.useRef(false);
1724
-
1725
- if (!isMountedRef.current) ;
1726
-
1727
- const handleColumn = (column, parentVisible) => {
1728
- column.isVisible = parentVisible && !hiddenColumns.includes(column.id);
1729
-
1730
- let totalVisibleHeaderCount = 0;
1731
-
1732
- if (column.headers && column.headers.length) {
1733
- column.headers.forEach(
1734
- subColumn =>
1735
- (totalVisibleHeaderCount += handleColumn(subColumn, column.isVisible))
1736
- );
1737
- } else {
1738
- totalVisibleHeaderCount = column.isVisible ? 1 : 0;
1739
- }
1740
-
1741
- column.totalVisibleHeaderCount = totalVisibleHeaderCount;
1742
-
1743
- return totalVisibleHeaderCount
1744
- };
1745
-
1746
- let totalVisibleHeaderCount = 0;
1747
-
1748
- headers.forEach(
1749
- subHeader => (totalVisibleHeaderCount += handleColumn(subHeader, true))
1750
- );
1751
- }
1752
-
1753
- function useInstance$2(instance) {
1754
- const {
1755
- columns,
1756
- flatHeaders,
1757
- dispatch,
1758
- allColumns,
1759
- getHooks,
1760
- state: { hiddenColumns },
1761
- autoResetHiddenColumns = true,
1762
- } = instance;
1763
-
1764
- const getInstance = useGetLatest(instance);
1765
-
1766
- const allColumnsHidden = allColumns.length === hiddenColumns.length;
1767
-
1768
- const toggleHideColumn = React__default.useCallback(
1769
- (columnId, value) =>
1770
- dispatch({ type: actions.toggleHideColumn, columnId, value }),
1771
- [dispatch]
1772
- );
1773
-
1774
- const setHiddenColumns = React__default.useCallback(
1775
- value => dispatch({ type: actions.setHiddenColumns, value }),
1776
- [dispatch]
1777
- );
1778
-
1779
- const toggleHideAllColumns = React__default.useCallback(
1780
- value => dispatch({ type: actions.toggleHideAllColumns, value }),
1781
- [dispatch]
1782
- );
1783
-
1784
- const getToggleHideAllColumnsProps = makePropGetter(
1785
- getHooks().getToggleHideAllColumnsProps,
1786
- { instance: getInstance() }
1787
- );
1788
-
1789
- flatHeaders.forEach(column => {
1790
- column.toggleHidden = value => {
1791
- dispatch({
1792
- type: actions.toggleHideColumn,
1793
- columnId: column.id,
1794
- value,
1795
- });
1796
- };
1797
-
1798
- column.getToggleHiddenProps = makePropGetter(
1799
- getHooks().getToggleHiddenProps,
1800
- {
1801
- instance: getInstance(),
1802
- column,
1803
- }
1804
- );
1805
- });
1806
-
1807
- const getAutoResetHiddenColumns = useGetLatest(autoResetHiddenColumns);
1808
-
1809
- useMountedLayoutEffect(() => {
1810
- if (getAutoResetHiddenColumns()) {
1811
- dispatch({ type: actions.resetHiddenColumns });
1812
- }
1813
- }, [dispatch, columns]);
1814
-
1815
- Object.assign(instance, {
1816
- allColumnsHidden,
1817
- toggleHideColumn,
1818
- setHiddenColumns,
1819
- toggleHideAllColumns,
1820
- getToggleHideAllColumnsProps,
1821
- });
1822
- }
1823
-
1824
- const defaultInitialState = {};
1825
- const defaultColumnInstance = {};
1826
- const defaultReducer = (state, action, prevState) => state;
1827
- const defaultGetSubRows = (row, index) => row.subRows || [];
1828
- const defaultGetRowId = (row, index, parent) =>
1829
- `${parent ? [parent.id, index].join('.') : index}`;
1830
- const defaultUseControlledState = d => d;
1831
-
1832
- function applyDefaults(props) {
1833
- const {
1834
- initialState = defaultInitialState,
1835
- defaultColumn = defaultColumnInstance,
1836
- getSubRows = defaultGetSubRows,
1837
- getRowId = defaultGetRowId,
1838
- stateReducer = defaultReducer,
1839
- useControlledState = defaultUseControlledState,
1840
- ...rest
1841
- } = props;
1842
-
1843
- return {
1844
- ...rest,
1845
- initialState,
1846
- defaultColumn,
1847
- getSubRows,
1848
- getRowId,
1849
- stateReducer,
1850
- useControlledState,
1851
- }
1852
- }
1853
-
1854
- const useTable = (props, ...plugins) => {
1855
- // Apply default props
1856
- props = applyDefaults(props);
1857
-
1858
- // Add core plugins
1859
- plugins = [useColumnVisibility, ...plugins];
1860
-
1861
- // Create the table instance
1862
- let instanceRef = React__default.useRef({});
1863
-
1864
- // Create a getter for the instance (helps avoid a lot of potential memory leaks)
1865
- const getInstance = useGetLatest(instanceRef.current);
1866
-
1867
- // Assign the props, plugins and hooks to the instance
1868
- Object.assign(getInstance(), {
1869
- ...props,
1870
- plugins,
1871
- hooks: makeDefaultPluginHooks(),
1872
- });
1873
-
1874
- // Allow plugins to register hooks as early as possible
1875
- plugins.filter(Boolean).forEach(plugin => {
1876
- plugin(getInstance().hooks);
1877
- });
1878
-
1879
- // Consume all hooks and make a getter for them
1880
- const getHooks = useGetLatest(getInstance().hooks);
1881
- getInstance().getHooks = getHooks;
1882
- delete getInstance().hooks;
1883
-
1884
- // Allow useOptions hooks to modify the options coming into the table
1885
- Object.assign(
1886
- getInstance(),
1887
- reduceHooks(getHooks().useOptions, applyDefaults(props))
1888
- );
1889
-
1890
- const {
1891
- data,
1892
- columns: userColumns,
1893
- initialState,
1894
- defaultColumn,
1895
- getSubRows,
1896
- getRowId,
1897
- stateReducer,
1898
- useControlledState,
1899
- } = getInstance();
1900
-
1901
- // Setup user reducer ref
1902
- const getStateReducer = useGetLatest(stateReducer);
1903
-
1904
- // Build the reducer
1905
- const reducer = React__default.useCallback(
1906
- (state, action) => {
1907
- // Detect invalid actions
1908
- if (!action.type) {
1909
- console.info({ action });
1910
- throw new Error('Unknown Action 👆')
1911
- }
1912
-
1913
- // Reduce the state from all plugin reducers
1914
- return [
1915
- ...getHooks().stateReducers,
1916
- // Allow the user to add their own state reducer(s)
1917
- ...(Array.isArray(getStateReducer())
1918
- ? getStateReducer()
1919
- : [getStateReducer()]),
1920
- ].reduce(
1921
- (s, handler) => handler(s, action, state, getInstance()) || s,
1922
- state
1923
- )
1924
- },
1925
- [getHooks, getStateReducer, getInstance]
1926
- );
1927
-
1928
- // Start the reducer
1929
- const [reducerState, dispatch] = React__default.useReducer(reducer, undefined, () =>
1930
- reducer(initialState, { type: actions.init })
1931
- );
1932
-
1933
- // Allow the user to control the final state with hooks
1934
- const state = reduceHooks(
1935
- [...getHooks().useControlledState, useControlledState],
1936
- reducerState,
1937
- { instance: getInstance() }
1938
- );
1939
-
1940
- Object.assign(getInstance(), {
1941
- state,
1942
- dispatch,
1943
- });
1944
-
1945
- // Decorate All the columns
1946
- const columns = React__default.useMemo(
1947
- () =>
1948
- linkColumnStructure(
1949
- reduceHooks(getHooks().columns, userColumns, {
1950
- instance: getInstance(),
1951
- })
1952
- ),
1953
- [
1954
- getHooks,
1955
- getInstance,
1956
- userColumns,
1957
- // eslint-disable-next-line react-hooks/exhaustive-deps
1958
- ...reduceHooks(getHooks().columnsDeps, [], { instance: getInstance() }),
1959
- ]
1960
- );
1961
- getInstance().columns = columns;
1962
-
1963
- // Get the flat list of all columns and allow hooks to decorate
1964
- // those columns (and trigger this memoization via deps)
1965
- let allColumns = React__default.useMemo(
1966
- () =>
1967
- reduceHooks(getHooks().allColumns, flattenColumns(columns), {
1968
- instance: getInstance(),
1969
- }).map(assignColumnAccessor),
1970
- [
1971
- columns,
1972
- getHooks,
1973
- getInstance,
1974
- // eslint-disable-next-line react-hooks/exhaustive-deps
1975
- ...reduceHooks(getHooks().allColumnsDeps, [], {
1976
- instance: getInstance(),
1977
- }),
1978
- ]
1979
- );
1980
- getInstance().allColumns = allColumns;
1981
-
1982
- // Access the row model using initial columns
1983
- const [rows, flatRows, rowsById] = React__default.useMemo(() => {
1984
- let rows = [];
1985
- let flatRows = [];
1986
- const rowsById = {};
1987
-
1988
- const allColumnsQueue = [...allColumns];
1989
-
1990
- while (allColumnsQueue.length) {
1991
- const column = allColumnsQueue.shift();
1992
- accessRowsForColumn({
1993
- data,
1994
- rows,
1995
- flatRows,
1996
- rowsById,
1997
- column,
1998
- getRowId,
1999
- getSubRows,
2000
- accessValueHooks: getHooks().accessValue,
2001
- getInstance,
2002
- });
2003
- }
2004
-
2005
- return [rows, flatRows, rowsById]
2006
- }, [allColumns, data, getRowId, getSubRows, getHooks, getInstance]);
2007
-
2008
- Object.assign(getInstance(), {
2009
- rows,
2010
- initialRows: [...rows],
2011
- flatRows,
2012
- rowsById,
2013
- // materializedColumns,
2014
- });
2015
-
2016
- loopHooks(getHooks().useInstanceAfterData, getInstance());
2017
-
2018
- // Get the flat list of all columns AFTER the rows
2019
- // have been access, and allow hooks to decorate
2020
- // those columns (and trigger this memoization via deps)
2021
- let visibleColumns = React__default.useMemo(
2022
- () =>
2023
- reduceHooks(getHooks().visibleColumns, allColumns, {
2024
- instance: getInstance(),
2025
- }).map(d => decorateColumn(d, defaultColumn)),
2026
- [
2027
- getHooks,
2028
- allColumns,
2029
- getInstance,
2030
- defaultColumn,
2031
- // eslint-disable-next-line react-hooks/exhaustive-deps
2032
- ...reduceHooks(getHooks().visibleColumnsDeps, [], {
2033
- instance: getInstance(),
2034
- }),
2035
- ]
2036
- );
2037
-
2038
- // Combine new visible columns with all columns
2039
- allColumns = React__default.useMemo(() => {
2040
- const columns = [...visibleColumns];
2041
-
2042
- allColumns.forEach(column => {
2043
- if (!columns.find(d => d.id === column.id)) {
2044
- columns.push(column);
2045
- }
2046
- });
2047
-
2048
- return columns
2049
- }, [allColumns, visibleColumns]);
2050
- getInstance().allColumns = allColumns;
2051
-
2052
- if (process.env.NODE_ENV !== 'production') {
2053
- const duplicateColumns = allColumns.filter((column, i) => {
2054
- return allColumns.findIndex(d => d.id === column.id) !== i
2055
- });
2056
-
2057
- if (duplicateColumns.length) {
2058
- console.info(allColumns);
2059
- throw new Error(
2060
- `Duplicate columns were found with ids: "${duplicateColumns
2061
- .map(d => d.id)
2062
- .join(', ')}" in the columns array above`
2063
- )
2064
- }
2065
- }
2066
-
2067
- // Make the headerGroups
2068
- const headerGroups = React__default.useMemo(
2069
- () =>
2070
- reduceHooks(
2071
- getHooks().headerGroups,
2072
- makeHeaderGroups(visibleColumns, defaultColumn),
2073
- getInstance()
2074
- ),
2075
- [
2076
- getHooks,
2077
- visibleColumns,
2078
- defaultColumn,
2079
- getInstance,
2080
- // eslint-disable-next-line react-hooks/exhaustive-deps
2081
- ...reduceHooks(getHooks().headerGroupsDeps, [], {
2082
- instance: getInstance(),
2083
- }),
2084
- ]
2085
- );
2086
- getInstance().headerGroups = headerGroups;
2087
-
2088
- // Get the first level of headers
2089
- const headers = React__default.useMemo(
2090
- () => (headerGroups.length ? headerGroups[0].headers : []),
2091
- [headerGroups]
2092
- );
2093
- getInstance().headers = headers;
2094
-
2095
- // Provide a flat header list for utilities
2096
- getInstance().flatHeaders = headerGroups.reduce(
2097
- (all, headerGroup) => [...all, ...headerGroup.headers],
2098
- []
2099
- );
2100
-
2101
- loopHooks(getHooks().useInstanceBeforeDimensions, getInstance());
2102
-
2103
- // Filter columns down to visible ones
2104
- const visibleColumnsDep = visibleColumns
2105
- .filter(d => d.isVisible)
2106
- .map(d => d.id)
2107
- .sort()
2108
- .join('_');
2109
-
2110
- visibleColumns = React__default.useMemo(
2111
- () => visibleColumns.filter(d => d.isVisible),
2112
- // eslint-disable-next-line react-hooks/exhaustive-deps
2113
- [visibleColumns, visibleColumnsDep]
2114
- );
2115
- getInstance().visibleColumns = visibleColumns;
2116
-
2117
- // Header Visibility is needed by this point
2118
- const [
2119
- totalColumnsMinWidth,
2120
- totalColumnsWidth,
2121
- totalColumnsMaxWidth,
2122
- ] = calculateHeaderWidths(headers);
2123
-
2124
- getInstance().totalColumnsMinWidth = totalColumnsMinWidth;
2125
- getInstance().totalColumnsWidth = totalColumnsWidth;
2126
- getInstance().totalColumnsMaxWidth = totalColumnsMaxWidth;
2127
-
2128
- loopHooks(getHooks().useInstance, getInstance())
2129
-
2130
- // Each materialized header needs to be assigned a render function and other
2131
- // prop getter properties here.
2132
- ;[...getInstance().flatHeaders, ...getInstance().allColumns].forEach(
2133
- column => {
2134
- // Give columns/headers rendering power
2135
- column.render = makeRenderer(getInstance(), column);
2136
-
2137
- // Give columns/headers a default getHeaderProps
2138
- column.getHeaderProps = makePropGetter(getHooks().getHeaderProps, {
2139
- instance: getInstance(),
2140
- column,
2141
- });
2142
-
2143
- // Give columns/headers a default getFooterProps
2144
- column.getFooterProps = makePropGetter(getHooks().getFooterProps, {
2145
- instance: getInstance(),
2146
- column,
2147
- });
2148
- }
2149
- );
2150
-
2151
- getInstance().headerGroups = React__default.useMemo(
2152
- () =>
2153
- headerGroups.filter((headerGroup, i) => {
2154
- // Filter out any headers and headerGroups that don't have visible columns
2155
- headerGroup.headers = headerGroup.headers.filter(column => {
2156
- const recurse = headers =>
2157
- headers.filter(column => {
2158
- if (column.headers) {
2159
- return recurse(column.headers)
2160
- }
2161
- return column.isVisible
2162
- }).length;
2163
- if (column.headers) {
2164
- return recurse(column.headers)
2165
- }
2166
- return column.isVisible
2167
- });
2168
-
2169
- // Give headerGroups getRowProps
2170
- if (headerGroup.headers.length) {
2171
- headerGroup.getHeaderGroupProps = makePropGetter(
2172
- getHooks().getHeaderGroupProps,
2173
- { instance: getInstance(), headerGroup, index: i }
2174
- );
2175
-
2176
- headerGroup.getFooterGroupProps = makePropGetter(
2177
- getHooks().getFooterGroupProps,
2178
- { instance: getInstance(), headerGroup, index: i }
2179
- );
2180
-
2181
- return true
2182
- }
2183
-
2184
- return false
2185
- }),
2186
- [headerGroups, getInstance, getHooks]
2187
- );
2188
-
2189
- getInstance().footerGroups = [...getInstance().headerGroups].reverse();
2190
-
2191
- // The prepareRow function is absolutely necessary and MUST be called on
2192
- // any rows the user wishes to be displayed.
2193
-
2194
- getInstance().prepareRow = React__default.useCallback(
2195
- row => {
2196
- row.getRowProps = makePropGetter(getHooks().getRowProps, {
2197
- instance: getInstance(),
2198
- row,
2199
- });
2200
-
2201
- // Build the visible cells for each row
2202
- row.allCells = allColumns.map(column => {
2203
- const value = row.values[column.id];
2204
-
2205
- const cell = {
2206
- column,
2207
- row,
2208
- value,
2209
- };
2210
-
2211
- // Give each cell a getCellProps base
2212
- cell.getCellProps = makePropGetter(getHooks().getCellProps, {
2213
- instance: getInstance(),
2214
- cell,
2215
- });
2216
-
2217
- // Give each cell a renderer function (supports multiple renderers)
2218
- cell.render = makeRenderer(getInstance(), column, {
2219
- row,
2220
- cell,
2221
- value,
2222
- });
2223
-
2224
- return cell
2225
- });
2226
-
2227
- row.cells = visibleColumns.map(column =>
2228
- row.allCells.find(cell => cell.column.id === column.id)
2229
- );
2230
-
2231
- // need to apply any row specific hooks (useExpanded requires this)
2232
- loopHooks(getHooks().prepareRow, row, { instance: getInstance() });
2233
- },
2234
- [getHooks, getInstance, allColumns, visibleColumns]
2235
- );
2236
-
2237
- getInstance().getTableProps = makePropGetter(getHooks().getTableProps, {
2238
- instance: getInstance(),
2239
- });
2240
-
2241
- getInstance().getTableBodyProps = makePropGetter(
2242
- getHooks().getTableBodyProps,
2243
- {
2244
- instance: getInstance(),
2245
- }
2246
- );
2247
-
2248
- loopHooks(getHooks().useFinalInstance, getInstance());
2249
-
2250
- return getInstance()
2251
- };
2252
-
2253
- function calculateHeaderWidths(headers, left = 0) {
2254
- let sumTotalMinWidth = 0;
2255
- let sumTotalWidth = 0;
2256
- let sumTotalMaxWidth = 0;
2257
- let sumTotalFlexWidth = 0;
2258
-
2259
- headers.forEach(header => {
2260
- let { headers: subHeaders } = header;
2261
-
2262
- header.totalLeft = left;
2263
-
2264
- if (subHeaders && subHeaders.length) {
2265
- const [
2266
- totalMinWidth,
2267
- totalWidth,
2268
- totalMaxWidth,
2269
- totalFlexWidth,
2270
- ] = calculateHeaderWidths(subHeaders, left);
2271
- header.totalMinWidth = totalMinWidth;
2272
- header.totalWidth = totalWidth;
2273
- header.totalMaxWidth = totalMaxWidth;
2274
- header.totalFlexWidth = totalFlexWidth;
2275
- } else {
2276
- header.totalMinWidth = header.minWidth;
2277
- header.totalWidth = Math.min(
2278
- Math.max(header.minWidth, header.width),
2279
- header.maxWidth
2280
- );
2281
- header.totalMaxWidth = header.maxWidth;
2282
- header.totalFlexWidth = header.canResize ? header.totalWidth : 0;
2283
- }
2284
- if (header.isVisible) {
2285
- left += header.totalWidth;
2286
- sumTotalMinWidth += header.totalMinWidth;
2287
- sumTotalWidth += header.totalWidth;
2288
- sumTotalMaxWidth += header.totalMaxWidth;
2289
- sumTotalFlexWidth += header.totalFlexWidth;
2290
- }
2291
- });
2292
-
2293
- return [sumTotalMinWidth, sumTotalWidth, sumTotalMaxWidth, sumTotalFlexWidth]
2294
- }
2295
-
2296
- function accessRowsForColumn({
2297
- data,
2298
- rows,
2299
- flatRows,
2300
- rowsById,
2301
- column,
2302
- getRowId,
2303
- getSubRows,
2304
- accessValueHooks,
2305
- getInstance,
2306
- }) {
2307
- // Access the row's data column-by-column
2308
- // We do it this way so we can incrementally add materialized
2309
- // columns after the first pass and avoid excessive looping
2310
- const accessRow = (originalRow, rowIndex, depth = 0, parent, parentRows) => {
2311
- // Keep the original reference around
2312
- const original = originalRow;
2313
-
2314
- const id = getRowId(originalRow, rowIndex, parent);
2315
-
2316
- let row = rowsById[id];
2317
-
2318
- // If the row hasn't been created, let's make it
2319
- if (!row) {
2320
- row = {
2321
- id,
2322
- original,
2323
- index: rowIndex,
2324
- depth,
2325
- cells: [{}], // This is a dummy cell
2326
- };
2327
-
2328
- // Override common array functions (and the dummy cell's getCellProps function)
2329
- // to show an error if it is accessed without calling prepareRow
2330
- row.cells.map = unpreparedAccessWarning;
2331
- row.cells.filter = unpreparedAccessWarning;
2332
- row.cells.forEach = unpreparedAccessWarning;
2333
- row.cells[0].getCellProps = unpreparedAccessWarning;
2334
-
2335
- // Create the cells and values
2336
- row.values = {};
2337
-
2338
- // Push this row into the parentRows array
2339
- parentRows.push(row);
2340
- // Keep track of every row in a flat array
2341
- flatRows.push(row);
2342
- // Also keep track of every row by its ID
2343
- rowsById[id] = row;
2344
-
2345
- // Get the original subrows
2346
- row.originalSubRows = getSubRows(originalRow, rowIndex);
2347
-
2348
- // Then recursively access them
2349
- if (row.originalSubRows) {
2350
- const subRows = [];
2351
- row.originalSubRows.forEach((d, i) =>
2352
- accessRow(d, i, depth + 1, row, subRows)
2353
- );
2354
- // Keep the new subRows array on the row
2355
- row.subRows = subRows;
2356
- }
2357
- } else if (row.subRows) {
2358
- // If the row exists, then it's already been accessed
2359
- // Keep recursing, but don't worry about passing the
2360
- // accumlator array (those rows already exist)
2361
- row.originalSubRows.forEach((d, i) => accessRow(d, i, depth + 1, row));
2362
- }
2363
-
2364
- // If the column has an accessor, use it to get a value
2365
- if (column.accessor) {
2366
- row.values[column.id] = column.accessor(
2367
- originalRow,
2368
- rowIndex,
2369
- row,
2370
- parentRows,
2371
- data
2372
- );
2373
- }
2374
-
2375
- // Allow plugins to manipulate the column value
2376
- row.values[column.id] = reduceHooks(
2377
- accessValueHooks,
2378
- row.values[column.id],
2379
- {
2380
- row,
2381
- column,
2382
- instance: getInstance(),
2383
- },
2384
- true
2385
- );
2386
- };
2387
-
2388
- data.forEach((originalRow, rowIndex) =>
2389
- accessRow(originalRow, rowIndex, 0, undefined, rows)
2390
- );
2391
- }
2392
-
2393
- const pluginName = 'usePagination';
2394
-
2395
- // Actions
2396
- actions.resetPage = 'resetPage';
2397
- actions.gotoPage = 'gotoPage';
2398
- actions.setPageSize = 'setPageSize';
2399
-
2400
- const usePagination = hooks => {
2401
- hooks.stateReducers.push(reducer$1);
2402
- hooks.useInstance.push(useInstance$1);
2403
- };
2404
-
2405
- usePagination.pluginName = pluginName;
2406
-
2407
- function reducer$1(state, action, previousState, instance) {
2408
- if (action.type === actions.init) {
2409
- return {
2410
- pageSize: 10,
2411
- pageIndex: 0,
2412
- ...state,
2413
- }
2414
- }
2415
-
2416
- if (action.type === actions.resetPage) {
2417
- return {
2418
- ...state,
2419
- pageIndex: instance.initialState.pageIndex || 0,
2420
- }
2421
- }
2422
-
2423
- if (action.type === actions.gotoPage) {
2424
- const { pageCount, page } = instance;
2425
- const newPageIndex = functionalUpdate(action.pageIndex, state.pageIndex);
2426
- let canNavigate = false;
2427
-
2428
- if (newPageIndex > state.pageIndex) {
2429
- // next page
2430
- canNavigate =
2431
- pageCount === -1
2432
- ? page.length >= state.pageSize
2433
- : newPageIndex < pageCount;
2434
- } else if (newPageIndex < state.pageIndex) {
2435
- // prev page
2436
- canNavigate = newPageIndex > -1;
2437
- }
2438
-
2439
- if (!canNavigate) {
2440
- return state
2441
- }
2442
-
2443
- return {
2444
- ...state,
2445
- pageIndex: newPageIndex,
2446
- }
2447
- }
2448
-
2449
- if (action.type === actions.setPageSize) {
2450
- const { pageSize } = action;
2451
- const topRowIndex = state.pageSize * state.pageIndex;
2452
- const pageIndex = Math.floor(topRowIndex / pageSize);
2453
-
2454
- return {
2455
- ...state,
2456
- pageIndex,
2457
- pageSize,
2458
- }
2459
- }
2460
- }
2461
-
2462
- function useInstance$1(instance) {
2463
- const {
2464
- rows,
2465
- autoResetPage = true,
2466
- manualExpandedKey = 'expanded',
2467
- plugins,
2468
- pageCount: userPageCount,
2469
- paginateExpandedRows = true,
2470
- expandSubRows = true,
2471
- state: {
2472
- pageSize,
2473
- pageIndex,
2474
- expanded,
2475
- globalFilter,
2476
- filters,
2477
- groupBy,
2478
- sortBy,
2479
- },
2480
- dispatch,
2481
- data,
2482
- manualPagination,
2483
- } = instance;
2484
-
2485
- ensurePluginOrder(
2486
- plugins,
2487
- ['useGlobalFilter', 'useFilters', 'useGroupBy', 'useSortBy', 'useExpanded'],
2488
- 'usePagination'
2489
- );
2490
-
2491
- const getAutoResetPage = useGetLatest(autoResetPage);
2492
-
2493
- useMountedLayoutEffect(() => {
2494
- if (getAutoResetPage()) {
2495
- dispatch({ type: actions.resetPage });
2496
- }
2497
- }, [
2498
- dispatch,
2499
- manualPagination ? null : data,
2500
- globalFilter,
2501
- filters,
2502
- groupBy,
2503
- sortBy,
2504
- ]);
2505
-
2506
- const pageCount = manualPagination
2507
- ? userPageCount
2508
- : Math.ceil(rows.length / pageSize);
2509
-
2510
- const pageOptions = React__default.useMemo(
2511
- () =>
2512
- pageCount > 0
2513
- ? [...new Array(pageCount)].fill(null).map((d, i) => i)
2514
- : [],
2515
- [pageCount]
2516
- );
2517
-
2518
- const page = React__default.useMemo(() => {
2519
- let page;
2520
-
2521
- if (manualPagination) {
2522
- page = rows;
2523
- } else {
2524
- const pageStart = pageSize * pageIndex;
2525
- const pageEnd = pageStart + pageSize;
2526
-
2527
- page = rows.slice(pageStart, pageEnd);
2528
- }
2529
-
2530
- if (paginateExpandedRows) {
2531
- return page
2532
- }
2533
-
2534
- return expandRows(page, { manualExpandedKey, expanded, expandSubRows })
2535
- }, [
2536
- expandSubRows,
2537
- expanded,
2538
- manualExpandedKey,
2539
- manualPagination,
2540
- pageIndex,
2541
- pageSize,
2542
- paginateExpandedRows,
2543
- rows,
2544
- ]);
2545
-
2546
- const canPreviousPage = pageIndex > 0;
2547
- const canNextPage =
2548
- pageCount === -1 ? page.length >= pageSize : pageIndex < pageCount - 1;
2549
-
2550
- const gotoPage = React__default.useCallback(
2551
- pageIndex => {
2552
- dispatch({ type: actions.gotoPage, pageIndex });
2553
- },
2554
- [dispatch]
2555
- );
2556
-
2557
- const previousPage = React__default.useCallback(() => {
2558
- return gotoPage(old => old - 1)
2559
- }, [gotoPage]);
2560
-
2561
- const nextPage = React__default.useCallback(() => {
2562
- return gotoPage(old => old + 1)
2563
- }, [gotoPage]);
2564
-
2565
- const setPageSize = React__default.useCallback(
2566
- pageSize => {
2567
- dispatch({ type: actions.setPageSize, pageSize });
2568
- },
2569
- [dispatch]
2570
- );
2571
-
2572
- Object.assign(instance, {
2573
- pageOptions,
2574
- pageCount,
2575
- page,
2576
- canPreviousPage,
2577
- canNextPage,
2578
- gotoPage,
2579
- previousPage,
2580
- nextPage,
2581
- setPageSize,
2582
- });
2583
- }
2584
-
2585
- const reSplitAlphaNumeric = /([0-9]+)/gm;
2586
-
2587
- // Mixed sorting is slow, but very inclusive of many edge cases.
2588
- // It handles numbers, mixed alphanumeric combinations, and even
2589
- // null, undefined, and Infinity
2590
- const alphanumeric = (rowA, rowB, columnId) => {
2591
- let [a, b] = getRowValuesByColumnID(rowA, rowB, columnId);
2592
-
2593
- // Force to strings (or "" for unsupported types)
2594
- a = toString(a);
2595
- b = toString(b);
2596
-
2597
- // Split on number groups, but keep the delimiter
2598
- // Then remove falsey split values
2599
- a = a.split(reSplitAlphaNumeric).filter(Boolean);
2600
- b = b.split(reSplitAlphaNumeric).filter(Boolean);
2601
-
2602
- // While
2603
- while (a.length && b.length) {
2604
- let aa = a.shift();
2605
- let bb = b.shift();
2606
-
2607
- const an = parseInt(aa, 10);
2608
- const bn = parseInt(bb, 10);
2609
-
2610
- const combo = [an, bn].sort();
2611
-
2612
- // Both are string
2613
- if (isNaN(combo[0])) {
2614
- if (aa > bb) {
2615
- return 1
2616
- }
2617
- if (bb > aa) {
2618
- return -1
2619
- }
2620
- continue
2621
- }
2622
-
2623
- // One is a string, one is a number
2624
- if (isNaN(combo[1])) {
2625
- return isNaN(an) ? -1 : 1
2626
- }
2627
-
2628
- // Both are numbers
2629
- if (an > bn) {
2630
- return 1
2631
- }
2632
- if (bn > an) {
2633
- return -1
2634
- }
2635
- }
2636
-
2637
- return a.length - b.length
2638
- };
2639
- function datetime(rowA, rowB, columnId) {
2640
- let [a, b] = getRowValuesByColumnID(rowA, rowB, columnId);
2641
-
2642
- a = a.getTime();
2643
- b = b.getTime();
2644
-
2645
- return compareBasic(a, b)
2646
- }
2647
-
2648
- function basic(rowA, rowB, columnId) {
2649
- let [a, b] = getRowValuesByColumnID(rowA, rowB, columnId);
2650
-
2651
- return compareBasic(a, b)
2652
- }
2653
-
2654
- function string(rowA, rowB, columnId) {
2655
- let [a, b] = getRowValuesByColumnID(rowA, rowB, columnId);
2656
-
2657
- a = a.split('').filter(Boolean);
2658
- b = b.split('').filter(Boolean);
2659
-
2660
- while (a.length && b.length) {
2661
- let aa = a.shift();
2662
- let bb = b.shift();
2663
-
2664
- let alower = aa.toLowerCase();
2665
- let blower = bb.toLowerCase();
2666
-
2667
- // Case insensitive comparison until characters match
2668
- if (alower > blower) {
2669
- return 1
2670
- }
2671
- if (blower > alower) {
2672
- return -1
2673
- }
2674
- // If lowercase characters are identical
2675
- if (aa > bb) {
2676
- return 1
2677
- }
2678
- if (bb > aa) {
2679
- return -1
2680
- }
2681
- continue
2682
- }
2683
-
2684
- return a.length - b.length
2685
- }
2686
-
2687
- function number(rowA, rowB, columnId) {
2688
- let [a, b] = getRowValuesByColumnID(rowA, rowB, columnId);
2689
-
2690
- const replaceNonNumeric = /[^0-9.]/gi;
2691
-
2692
- a = Number(String(a).replace(replaceNonNumeric, ''));
2693
- b = Number(String(b).replace(replaceNonNumeric, ''));
2694
-
2695
- return compareBasic(a, b)
2696
- }
2697
-
2698
- // Utils
2699
-
2700
- function compareBasic(a, b) {
2701
- return a === b ? 0 : a > b ? 1 : -1
2702
- }
2703
-
2704
- function getRowValuesByColumnID(row1, row2, columnId) {
2705
- return [row1.values[columnId], row2.values[columnId]]
2706
- }
2707
-
2708
- function toString(a) {
2709
- if (typeof a === 'number') {
2710
- if (isNaN(a) || a === Infinity || a === -Infinity) {
2711
- return ''
2712
- }
2713
- return String(a)
2714
- }
2715
- if (typeof a === 'string') {
2716
- return a
2717
- }
2718
- return ''
2719
- }
2720
-
2721
- var sortTypes = /*#__PURE__*/Object.freeze({
2722
- __proto__: null,
2723
- alphanumeric: alphanumeric,
2724
- datetime: datetime,
2725
- basic: basic,
2726
- string: string,
2727
- number: number
2728
- });
2729
-
2730
- // Actions
2731
- actions.resetSortBy = 'resetSortBy';
2732
- actions.setSortBy = 'setSortBy';
2733
- actions.toggleSortBy = 'toggleSortBy';
2734
- actions.clearSortBy = 'clearSortBy';
2735
-
2736
- defaultColumn.sortType = 'alphanumeric';
2737
- defaultColumn.sortDescFirst = false;
2738
-
2739
- const useSortBy = hooks => {
2740
- hooks.getSortByToggleProps = [defaultGetSortByToggleProps];
2741
- hooks.stateReducers.push(reducer);
2742
- hooks.useInstance.push(useInstance);
2743
- };
2744
-
2745
- useSortBy.pluginName = 'useSortBy';
2746
-
2747
- const defaultGetSortByToggleProps = (props, { instance, column }) => {
2748
- const { isMultiSortEvent = e => e.shiftKey } = instance;
2749
-
2750
- return [
2751
- props,
2752
- {
2753
- onClick: column.canSort
2754
- ? e => {
2755
- e.persist();
2756
- column.toggleSortBy(
2757
- undefined,
2758
- !instance.disableMultiSort && isMultiSortEvent(e)
2759
- );
2760
- }
2761
- : undefined,
2762
- style: {
2763
- cursor: column.canSort ? 'pointer' : undefined,
2764
- },
2765
- title: column.canSort ? 'Toggle SortBy' : undefined,
2766
- },
2767
- ]
2768
- };
2769
-
2770
- // Reducer
2771
- function reducer(state, action, previousState, instance) {
2772
- if (action.type === actions.init) {
2773
- return {
2774
- sortBy: [],
2775
- ...state,
2776
- }
2777
- }
2778
-
2779
- if (action.type === actions.resetSortBy) {
2780
- return {
2781
- ...state,
2782
- sortBy: instance.initialState.sortBy || [],
2783
- }
2784
- }
2785
-
2786
- if (action.type === actions.clearSortBy) {
2787
- const { sortBy } = state;
2788
- const newSortBy = sortBy.filter(d => d.id !== action.columnId);
2789
-
2790
- return {
2791
- ...state,
2792
- sortBy: newSortBy,
2793
- }
2794
- }
2795
-
2796
- if (action.type === actions.setSortBy) {
2797
- const { sortBy } = action;
2798
- return {
2799
- ...state,
2800
- sortBy,
2801
- }
2802
- }
2803
-
2804
- if (action.type === actions.toggleSortBy) {
2805
- const { columnId, desc, multi } = action;
2806
-
2807
- const {
2808
- allColumns,
2809
- disableMultiSort,
2810
- disableSortRemove,
2811
- disableMultiRemove,
2812
- maxMultiSortColCount = Number.MAX_SAFE_INTEGER,
2813
- } = instance;
2814
-
2815
- const { sortBy } = state;
2816
-
2817
- // Find the column for this columnId
2818
- const column = allColumns.find(d => d.id === columnId);
2819
- const { sortDescFirst } = column;
2820
-
2821
- // Find any existing sortBy for this column
2822
- const existingSortBy = sortBy.find(d => d.id === columnId);
2823
- const existingIndex = sortBy.findIndex(d => d.id === columnId);
2824
- const hasDescDefined = typeof desc !== 'undefined' && desc !== null;
2825
-
2826
- let newSortBy = [];
2827
-
2828
- // What should we do with this sort action?
2829
- let sortAction;
2830
-
2831
- if (!disableMultiSort && multi) {
2832
- if (existingSortBy) {
2833
- sortAction = 'toggle';
2834
- } else {
2835
- sortAction = 'add';
2836
- }
2837
- } else {
2838
- // Normal mode
2839
- if (existingIndex !== sortBy.length - 1 || sortBy.length !== 1) {
2840
- sortAction = 'replace';
2841
- } else if (existingSortBy) {
2842
- sortAction = 'toggle';
2843
- } else {
2844
- sortAction = 'replace';
2845
- }
2846
- }
2847
-
2848
- // Handle toggle states that will remove the sortBy
2849
- if (
2850
- sortAction === 'toggle' && // Must be toggling
2851
- !disableSortRemove && // If disableSortRemove, disable in general
2852
- !hasDescDefined && // Must not be setting desc
2853
- (multi ? !disableMultiRemove : true) && // If multi, don't allow if disableMultiRemove
2854
- ((existingSortBy && // Finally, detect if it should indeed be removed
2855
- existingSortBy.desc &&
2856
- !sortDescFirst) ||
2857
- (!existingSortBy.desc && sortDescFirst))
2858
- ) {
2859
- sortAction = 'remove';
2860
- }
2861
-
2862
- if (sortAction === 'replace') {
2863
- newSortBy = [
2864
- {
2865
- id: columnId,
2866
- desc: hasDescDefined ? desc : sortDescFirst,
2867
- },
2868
- ];
2869
- } else if (sortAction === 'add') {
2870
- newSortBy = [
2871
- ...sortBy,
2872
- {
2873
- id: columnId,
2874
- desc: hasDescDefined ? desc : sortDescFirst,
2875
- },
2876
- ];
2877
- // Take latest n columns
2878
- newSortBy.splice(0, newSortBy.length - maxMultiSortColCount);
2879
- } else if (sortAction === 'toggle') {
2880
- // This flips (or sets) the
2881
- newSortBy = sortBy.map(d => {
2882
- if (d.id === columnId) {
2883
- return {
2884
- ...d,
2885
- desc: hasDescDefined ? desc : !existingSortBy.desc,
2886
- }
2887
- }
2888
- return d
2889
- });
2890
- } else if (sortAction === 'remove') {
2891
- newSortBy = sortBy.filter(d => d.id !== columnId);
2892
- }
2893
-
2894
- return {
2895
- ...state,
2896
- sortBy: newSortBy,
2897
- }
2898
- }
2899
- }
2900
-
2901
- function useInstance(instance) {
2902
- const {
2903
- data,
2904
- rows,
2905
- flatRows,
2906
- allColumns,
2907
- orderByFn = defaultOrderByFn,
2908
- sortTypes: userSortTypes,
2909
- manualSortBy,
2910
- defaultCanSort,
2911
- disableSortBy,
2912
- flatHeaders,
2913
- state: { sortBy },
2914
- dispatch,
2915
- plugins,
2916
- getHooks,
2917
- autoResetSortBy = true,
2918
- } = instance;
2919
-
2920
- ensurePluginOrder(
2921
- plugins,
2922
- ['useFilters', 'useGlobalFilter', 'useGroupBy', 'usePivotColumns'],
2923
- 'useSortBy'
2924
- );
2925
-
2926
- const setSortBy = React__default.useCallback(
2927
- sortBy => {
2928
- dispatch({ type: actions.setSortBy, sortBy });
2929
- },
2930
- [dispatch]
2931
- );
2932
-
2933
- // Updates sorting based on a columnId, desc flag and multi flag
2934
- const toggleSortBy = React__default.useCallback(
2935
- (columnId, desc, multi) => {
2936
- dispatch({ type: actions.toggleSortBy, columnId, desc, multi });
2937
- },
2938
- [dispatch]
2939
- );
2940
-
2941
- // use reference to avoid memory leak in #1608
2942
- const getInstance = useGetLatest(instance);
2943
-
2944
- // Add the getSortByToggleProps method to columns and headers
2945
- flatHeaders.forEach(column => {
2946
- const {
2947
- accessor,
2948
- canSort: defaultColumnCanSort,
2949
- disableSortBy: columnDisableSortBy,
2950
- id,
2951
- } = column;
2952
-
2953
- const canSort = accessor
2954
- ? getFirstDefined(
2955
- columnDisableSortBy === true ? false : undefined,
2956
- disableSortBy === true ? false : undefined,
2957
- true
2958
- )
2959
- : getFirstDefined(defaultCanSort, defaultColumnCanSort, false);
2960
-
2961
- column.canSort = canSort;
2962
-
2963
- if (column.canSort) {
2964
- column.toggleSortBy = (desc, multi) =>
2965
- toggleSortBy(column.id, desc, multi);
2966
-
2967
- column.clearSortBy = () => {
2968
- dispatch({ type: actions.clearSortBy, columnId: column.id });
2969
- };
2970
- }
2971
-
2972
- column.getSortByToggleProps = makePropGetter(
2973
- getHooks().getSortByToggleProps,
2974
- {
2975
- instance: getInstance(),
2976
- column,
2977
- }
2978
- );
2979
-
2980
- const columnSort = sortBy.find(d => d.id === id);
2981
- column.isSorted = !!columnSort;
2982
- column.sortedIndex = sortBy.findIndex(d => d.id === id);
2983
- column.isSortedDesc = column.isSorted ? columnSort.desc : undefined;
2984
- });
2985
-
2986
- const [sortedRows, sortedFlatRows] = React__default.useMemo(() => {
2987
- if (manualSortBy || !sortBy.length) {
2988
- return [rows, flatRows]
2989
- }
2990
-
2991
- const sortedFlatRows = [];
2992
-
2993
- // Filter out sortBys that correspond to non existing columns
2994
- const availableSortBy = sortBy.filter(sort =>
2995
- allColumns.find(col => col.id === sort.id)
2996
- );
2997
-
2998
- const sortData = rows => {
2999
- // Use the orderByFn to compose multiple sortBy's together.
3000
- // This will also perform a stable sorting using the row index
3001
- // if needed.
3002
- const sortedData = orderByFn(
3003
- rows,
3004
- availableSortBy.map(sort => {
3005
- // Support custom sorting methods for each column
3006
- const column = allColumns.find(d => d.id === sort.id);
3007
-
3008
- if (!column) {
3009
- throw new Error(
3010
- `React-Table: Could not find a column with id: ${sort.id} while sorting`
3011
- )
3012
- }
3013
-
3014
- const { sortType } = column;
3015
-
3016
- // Look up sortBy functions in this order:
3017
- // column function
3018
- // column string lookup on user sortType
3019
- // column string lookup on built-in sortType
3020
- // default function
3021
- // default string lookup on user sortType
3022
- // default string lookup on built-in sortType
3023
- const sortMethod =
3024
- isFunction(sortType) ||
3025
- (userSortTypes || {})[sortType] ||
3026
- sortTypes[sortType];
3027
-
3028
- if (!sortMethod) {
3029
- throw new Error(
3030
- `React-Table: Could not find a valid sortType of '${sortType}' for column '${sort.id}'.`
3031
- )
3032
- }
3033
-
3034
- // Return the correct sortFn.
3035
- // This function should always return in ascending order
3036
- return (a, b) => sortMethod(a, b, sort.id, sort.desc)
3037
- }),
3038
- // Map the directions
3039
- availableSortBy.map(sort => {
3040
- // Detect and use the sortInverted option
3041
- const column = allColumns.find(d => d.id === sort.id);
3042
-
3043
- if (column && column.sortInverted) {
3044
- return sort.desc
3045
- }
3046
-
3047
- return !sort.desc
3048
- })
3049
- );
3050
-
3051
- // If there are sub-rows, sort them
3052
- sortedData.forEach(row => {
3053
- sortedFlatRows.push(row);
3054
- if (!row.subRows || row.subRows.length === 0) {
3055
- return
3056
- }
3057
- row.subRows = sortData(row.subRows);
3058
- });
3059
-
3060
- return sortedData
3061
- };
3062
-
3063
- return [sortData(rows), sortedFlatRows]
3064
- }, [
3065
- manualSortBy,
3066
- sortBy,
3067
- rows,
3068
- flatRows,
3069
- allColumns,
3070
- orderByFn,
3071
- userSortTypes,
3072
- ]);
3073
-
3074
- const getAutoResetSortBy = useGetLatest(autoResetSortBy);
3075
-
3076
- useMountedLayoutEffect(() => {
3077
- if (getAutoResetSortBy()) {
3078
- dispatch({ type: actions.resetSortBy });
3079
- }
3080
- }, [manualSortBy ? null : data]);
3081
-
3082
- Object.assign(instance, {
3083
- preSortedRows: rows,
3084
- preSortedFlatRows: flatRows,
3085
- sortedRows,
3086
- sortedFlatRows,
3087
- rows: sortedRows,
3088
- flatRows: sortedFlatRows,
3089
- setSortBy,
3090
- toggleSortBy,
3091
- });
3092
- }
3093
-
3094
- function defaultOrderByFn(arr, funcs, dirs) {
3095
- return [...arr].sort((rowA, rowB) => {
3096
- for (let i = 0; i < funcs.length; i += 1) {
3097
- const sortFn = funcs[i];
3098
- const desc = dirs[i] === false || dirs[i] === 'desc';
3099
- const sortInt = sortFn(rowA, rowB);
3100
- if (sortInt !== 0) {
3101
- return desc ? -sortInt : sortInt
3102
- }
3103
- }
3104
- return dirs[0] ? rowA.index - rowB.index : rowB.index - rowA.index
3105
- })
3106
- }
3107
-
3108
- var TableFooter = function (props) {
3109
- return (React__default.createElement(Box, { display: "flex", justifyContent: "center", alignItems: "end", paddingTop: 3, paddingBottom: 4, flexGrow: 1 }, props.children));
3110
- };
3111
-
3112
- var TableHeader = function (props) {
3113
- var children = props.children, restProps = __rest(props, ["children"]);
3114
- return React__default.createElement("thead", __assign({}, restProps), children);
3115
- };
3116
-
3117
- var getWidth = function (props) {
3118
- var isActionColumn = props.column.isActionColumn, fullWidth = props.tableProps.fullWidth;
3119
- var width;
3120
- if (fullWidth && isActionColumn) {
3121
- width = '0.0000000001%';
3122
- }
3123
- if (fullWidth && !isActionColumn) {
3124
- width = '1%';
3125
- }
3126
- if (!fullWidth && isActionColumn) {
3127
- width = 72;
3128
- }
3129
- if (!fullWidth && !isActionColumn) {
3130
- width = undefined;
3131
- }
3132
- return width;
3133
- };
3134
- var useTableHeaderCellStyles = makeStyles(function (theme) { return ({
3135
- root: function (props) {
3136
- var width = getWidth(props);
3137
- return {
3138
- borderBottomStyle: 'solid',
3139
- borderBottomWidth: 2,
3140
- borderBottomColor: theme.palette.grey[100],
3141
- padding: theme.spacing(2),
3142
- textAlign: 'left',
3143
- fontWeight: 500,
3144
- width: width,
3145
- };
3146
- },
3147
- }); });
3148
-
3149
- var TableHeaderCell = function (props) {
3150
- var children = props.children, column = props.column; props.tableProps; var restProps = __rest(props, ["children", "column", "tableProps"]);
3151
- var root = useTableHeaderCellStyles(props).root;
3152
- var _a = useTheme(), palette = _a.palette, spacing = _a.spacing;
3153
- //@ts-expect-error @types/react-table issue
3154
- var canSort = column.canSort, isSorted = column.isSorted, isSortedDesc = column.isSortedDesc, isActionColumn = column.isActionColumn;
3155
- var showSortIndicator = canSort && !isActionColumn;
3156
- return (React__default.createElement("th", __assign({ className: root }, restProps),
3157
- React__default.createElement(Box, { display: "flex", alignItems: "center", gridGap: spacing(1) },
3158
- children,
3159
- showSortIndicator && (React__default.createElement(Icon, { icon: isSortedDesc ? SvgChevronDown : SvgChevronUp, color: isSorted ? palette.text.primary : palette.text.disabled, size: "large" })))));
3160
- };
3161
-
3162
- var TableHeaderRow = function (props) {
3163
- var children = props.children, restProps = __rest(props, ["children"]);
3164
- return React__default.createElement("tr", __assign({}, restProps), children);
3165
- };
3166
-
3167
- var useTableRowStyles = makeStyles(function (theme) { return ({
3168
- root: function () { return ({
3169
- '&:nth-child(even)': {
3170
- backgroundColor: theme.palette.grey[100],
3171
- },
3172
- }); },
3173
- }); });
3174
-
3175
- var TableRow = function (props) {
3176
- var children = props.children, restProps = __rest(props, ["children"]);
3177
- var root = useTableRowStyles(props).root;
3178
- return (React__default.createElement("tr", __assign({ className: root }, restProps), children));
3179
- };
3180
-
3181
- var TableBody = function (props) {
3182
- var children = props.children, restProps = __rest(props, ["children"]);
3183
- return React__default.createElement("tbody", __assign({}, restProps), children);
3184
- };
3185
-
3186
- var useTableCellStyles = makeStyles(function (theme) { return ({
3187
- root: function () { return ({
3188
- padding: theme.spacing(2),
3189
- }); },
3190
- }); });
3191
-
3192
- var TableCell = function (props) {
3193
- var children = props.children, restProps = __rest(props, ["children"]);
3194
- var root = useTableCellStyles(props).root;
3195
- return (React__default.createElement("td", __assign({ className: root }, restProps), children));
3196
- };
3197
-
3198
- var useTableStyles = makeStyles(function (_a) {
3199
- var typography = _a.typography;
3200
- return ({
3201
- root: function (_a) {
3202
- var fullWidth = _a.fullWidth;
3203
- return ({
3204
- display: fullWidth ? 'flex' : 'inline-flex',
3205
- flexDirection: 'column',
3206
- });
3207
- },
3208
- table: function (_a) {
3209
- var fullWidth = _a.fullWidth;
3210
- return (__assign(__assign({ borderCollapse: 'collapse' }, (fullWidth && { width: '100%' })), typography.body1));
3211
- },
3212
- tableWrap: function () { return ({
3213
- maxWidth: '100%',
3214
- overflowX: 'auto',
3215
- overflowY: 'hidden',
3216
- }); },
3217
- });
3218
- });
3219
-
3220
- var TableActionsCell = function (props) {
3221
- var _a = props.actions, primary = _a.primary, secondary = _a.secondary, intermediate = __rest(_a, ["primary", "secondary"]);
3222
- var tertiary = intermediate.tertiary, restActions = __rest(intermediate, ["tertiary"]);
3223
- var overflow = Object.keys(props.actions).length > 3;
3224
- var _b = React__default.useState(null), anchorEl = _b[0], setAnchorEl = _b[1];
3225
- var openMenu = function (event) {
3226
- setAnchorEl(event.currentTarget);
3227
- };
3228
- var closeMenu = function () {
3229
- setAnchorEl(null);
3230
- };
3231
- var handleItemClick = function (action) {
3232
- action(props.cell);
3233
- closeMenu();
3234
- };
3235
- return (React__default.createElement(Box, { display: "flex" },
3236
- primary && primary.icon && (React__default.createElement(IconButton, { size: "small", onClick: function () { return primary.action(props.cell); } },
3237
- React__default.createElement(Icon, { icon: primary.icon }))),
3238
- secondary && secondary.icon && (React__default.createElement(IconButton, { size: "small", onClick: function () { return secondary.action(props.cell); } },
3239
- React__default.createElement(Icon, { icon: secondary.icon }))),
3240
- !overflow && tertiary && tertiary.icon && (React__default.createElement(IconButton, { size: "small", onClick: function () { return tertiary.action(props.cell); } },
3241
- React__default.createElement(Icon, { icon: tertiary.icon }))),
3242
- overflow && restActions && (React__default.createElement(React__default.Fragment, null,
3243
- React__default.createElement(IconButton, { size: "small", onClick: openMenu },
3244
- React__default.createElement(Icon, { icon: SvgMore })),
3245
- React__default.createElement(Menu, { anchorEl: anchorEl, open: Boolean(anchorEl), onClose: closeMenu }, Object.values(__assign({ tertiary: tertiary }, restActions))
3246
- .filter(function (value) { return value; })
3247
- .map(function (_a, i) {
3248
- var label = _a.label, action = _a.action;
3249
- return (React__default.createElement(MenuItem, { key: i, onClick: function () { return handleItemClick(action); } }, label));
3250
- }))))));
3251
- };
3252
-
3253
- var makeColumns = function (config) {
3254
- var columns = config.columns, actions = config.actions, actionColumnId = config.actionColumnId;
3255
- var actionColumn;
3256
- var memoizedColumns = __spreadArray([], columns);
3257
- if (actions) {
3258
- var CellComponent = function (props) { return React__default.createElement(TableActionsCell, __assign({}, props, { actions: actions })); };
3259
- actionColumn = {
3260
- id: actionColumnId,
3261
- Header: function () { return null; },
3262
- Cell: CellComponent,
3263
- };
3264
- memoizedColumns = __spreadArray(__spreadArray([], columns), [actionColumn]);
3265
- }
3266
- return memoizedColumns;
3267
- };
3268
-
3269
- /* eslint-disable react/jsx-key */
3270
- var Table = function (props) {
3271
- var actionColumnId = 'table-actions-column';
3272
- var rawColumns = props.columns, data = props.data, actions = props.actions, sortable = props.sortable, emptyMessage = props.emptyMessage, EmptyImage = props.EmptyImage, isLoading = props.loading, enableMinHeight = props.enableMinHeight;
3273
- var classes = useTableStyles(props);
3274
- var columns = useMemo(function () { return makeColumns({ columns: rawColumns, actions: actions, actionColumnId: actionColumnId }); }, [rawColumns, actions]);
3275
- var instance = useTable({ columns: columns, data: data, disableSortBy: !sortable }, useSortBy, usePagination);
3276
- var getTableProps = instance.getTableProps, getTableBodyProps = instance.getTableBodyProps, headerGroups = instance.headerGroups, page = instance.page, prepareRow = instance.prepareRow, pageCount = instance.pageCount, gotoPage = instance.gotoPage, state = instance.state, rows = instance.rows;
3277
- var isPaginated = pageCount > 1;
3278
- var isEmpty = rows.length === 0;
3279
- var handlePagination = function (_e, pageNumber) {
3280
- gotoPage(pageNumber - 1);
3281
- };
3282
- return (React__default.createElement(Box, { className: classes.root, minHeight: (isLoading || isEmpty) && enableMinHeight ? 618 : 'unset' },
3283
- React__default.createElement(Box, { className: classes.tableWrap, minHeight: page.length > 0 && !isLoading && enableMinHeight ? 618 : 'unset' },
3284
- React__default.createElement("table", __assign({ className: classes.table }, getTableProps()),
3285
- React__default.createElement(TableHeader, null, headerGroups.map(function (headerGroup) { return (React__default.createElement(TableHeaderRow, __assign({}, headerGroup.getHeaderGroupProps()), headerGroup.headers.map(function (column) { return (React__default.createElement(TableHeaderCell, __assign({}, column.getHeaderProps(column.getSortByToggleProps()), { column: __assign(__assign({}, column), { isActionColumn: column.id === actionColumnId }), tableProps: props }), column.render('Header'))); }))); })),
3286
- !isEmpty && !isLoading && (React__default.createElement(TableBody, __assign({}, getTableBodyProps()), page.map(function (row) {
3287
- prepareRow(row);
3288
- return (React__default.createElement(TableRow, __assign({}, row.getRowProps()), row.cells.map(function (cell) { return (React__default.createElement(TableCell, __assign({}, cell.getCellProps()), cell.render('Cell'))); })));
3289
- }))))),
3290
- isEmpty && (React__default.createElement(Box, { display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "center", p: 2, flexGrow: 1 },
3291
- EmptyImage && EmptyImage(),
3292
- React__default.createElement(Typography, null, emptyMessage))),
3293
- isLoading && (React__default.createElement(Box, { display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "center", p: 2, flexGrow: 1 },
3294
- React__default.createElement(CircularProgress, { size: 80, color: "inherit" }))),
3295
- isPaginated && !isLoading && (React__default.createElement(TableFooter, null,
3296
- React__default.createElement(Pagination, { count: pageCount, page: state.pageIndex + 1, onChange: handlePagination })))));
3297
- };
3298
- Table.defaultProps = {
3299
- emptyMessage: 'No results.',
3300
- enableMinHeight: true,
3301
- };
3302
-
3303
993
  var useToggleButtonStyles = makeStyles$1(function (theme) { return ({
3304
994
  root: {
3305
995
  color: theme.palette.text.primary,
@@ -3378,5 +1068,5 @@ var useCollapsibleText = function () {
3378
1068
  };
3379
1069
  };
3380
1070
 
3381
- export { AudioPlayer, Avatar, Button, Checkbox, CollapsibleText, Divider, Icon, IconButton, Link, Paper, PaperContent, Radio, SplitInput, Switch, Table, ToggleButton, ToggleButtonGroup, Tooltip, Typography, useCollapsibleText };
1071
+ export { AudioPlayer, Avatar, Button, Checkbox, CollapsibleText, Divider, Icon, IconButton, Link, Paper, PaperContent, Radio, SplitInput, Switch, ToggleButton, ToggleButtonGroup, Tooltip, Typography, useCollapsibleText };
3382
1072
  //# sourceMappingURL=index.es.js.map