mirror of
https://github.com/gosticks/react-table.git
synced 2026-08-19 08:20:30 +00:00
Compare commits
79
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ab32339bfa | ||
|
|
7fd8fa1dfc | ||
|
|
bc89ae3027 | ||
|
|
af739d91d0 | ||
|
|
35f78132f6 | ||
|
|
d7a4db0979 | ||
|
|
11167e5635 | ||
|
|
14a43b1a68 | ||
|
|
0375a7e7d5 | ||
|
|
6b70309f42 | ||
|
|
9b262676be | ||
|
|
1caad4cd8c | ||
|
|
dc73347003 | ||
|
|
66bfec34a8 | ||
|
|
6347157f80 | ||
|
|
b6db8775ad | ||
|
|
cadd8bf62a | ||
|
|
9f4746a7ac | ||
|
|
a0ca841287 | ||
|
|
52ee923675 | ||
|
|
24f6a2750d | ||
|
|
8988660618 | ||
|
|
a3e5cac298 | ||
|
|
47d2651b8d | ||
|
|
412f64cece | ||
|
|
933cc27e33 | ||
|
|
54be978268 | ||
|
|
90922f8637 | ||
|
|
fd8a686b30 | ||
|
|
a361a372ee | ||
|
|
563e809d05 | ||
|
|
7d267b3442 | ||
|
|
388b3ec2b9 | ||
|
|
b2abd82350 | ||
|
|
06a6d6fcc3 | ||
|
|
d8599817ad | ||
|
|
e1060db327 | ||
|
|
ea79cd8388 | ||
|
|
b2ed18696f | ||
|
|
9f8eab5777 | ||
|
|
4f13f32023 | ||
|
|
5bb2e49764 | ||
|
|
d1f26fe7bc | ||
|
|
c7d6562d04 | ||
|
|
e82d2d4b36 | ||
|
|
0716e234a1 | ||
|
|
824ee34ba9 | ||
|
|
514fbabb88 | ||
|
|
2ecf40518e | ||
|
|
fd64486286 | ||
|
|
34909305af | ||
|
|
5043af5071 | ||
|
|
2ca7f78d72 | ||
|
|
811cd015c2 | ||
|
|
9e37846a21 | ||
|
|
723720c8b1 | ||
|
|
2a20ad3ba4 | ||
|
|
c6d37e4834 | ||
|
|
a1a192052d | ||
|
|
455e0730bf | ||
|
|
1d4867fa2f | ||
|
|
c3da2a7c41 | ||
|
|
c3a52c5845 | ||
|
|
6dea8103d3 | ||
|
|
3bab8372d1 | ||
|
|
b85f457e62 | ||
|
|
c6871084d6 | ||
|
|
8946771563 | ||
|
|
fbc8032d29 | ||
|
|
6a3bc5559e | ||
|
|
91e28b93bf | ||
|
|
a6345dbe2b | ||
|
|
0b0de317ee | ||
|
|
0ed0c78286 | ||
|
|
fad6ac4014 | ||
|
|
8f142b3788 | ||
|
|
daff1f9ca3 | ||
|
|
96900f645a | ||
|
|
272a99fcd8 |
@@ -1,11 +1,16 @@
|
||||
{
|
||||
"presets": [
|
||||
[
|
||||
"@babel/env",
|
||||
"@babel/preset-env",
|
||||
{
|
||||
"modules": false
|
||||
}
|
||||
],
|
||||
"@babel/react"
|
||||
]
|
||||
],
|
||||
"env": {
|
||||
"test": {
|
||||
"presets": ["@babel/preset-env", "@babel/react"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,22 +1,3 @@
|
||||
{
|
||||
"parser": "babel-eslint",
|
||||
"extends": ["react-app", "prettier"],
|
||||
"plugins": [
|
||||
"react-hooks"
|
||||
],
|
||||
"env": {
|
||||
"es6": true
|
||||
},
|
||||
"parserOptions": {
|
||||
"sourceType": "module"
|
||||
},
|
||||
"rules": {
|
||||
"space-before-function-paren": 0,
|
||||
"react/jsx-boolean-value": 0
|
||||
},
|
||||
"settings": {
|
||||
"react": {
|
||||
"version": "latest"
|
||||
}
|
||||
}
|
||||
"extends": ["react-app", "prettier"]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: tannerlinsley
|
||||
patreon: tannerlinsley
|
||||
custom: https://youtube.com/tannerlinsley
|
||||
@@ -1,5 +1,6 @@
|
||||
module.exports = {
|
||||
hooks: {
|
||||
'pre-commit': 'lint-staged',
|
||||
'commit-msg': 'commitlint -E HUSKY_GIT_PARAMS',
|
||||
},
|
||||
}
|
||||
|
||||
+73
-73
@@ -2,58 +2,58 @@
|
||||
|
||||
#### Fixes & Optimizations
|
||||
|
||||
* Since `resolveData` is now capable of materializing data on it's own, the `data` prop is no longer required as a prop-type.
|
||||
- Since `resolveData` is now capable of materializing data on it's own, the `data` prop is no longer required as a prop-type.
|
||||
|
||||
## 6.8.4
|
||||
|
||||
#### Fixes & Optimizations
|
||||
|
||||
* Only run `resolveData` prop when `data` prop has changed, not any others.
|
||||
- Only run `resolveData` prop when `data` prop has changed, not any others.
|
||||
|
||||
## 6.8.3
|
||||
|
||||
#### Fixes & Optimizations
|
||||
|
||||
* Allow the `resolveData` prop to alter or materialize new data when the `data` prop changes.
|
||||
- Allow the `resolveData` prop to alter or materialize new data when the `data` prop changes.
|
||||
|
||||
## 6.8.1
|
||||
|
||||
#### Fixes & Optimizations
|
||||
|
||||
* Updated eslint and code formatting
|
||||
- Updated eslint and code formatting
|
||||
|
||||
## 6.7.5
|
||||
|
||||
#### Fixes & Optimizations
|
||||
|
||||
* Now passes `column` to `getResizerProps` (#667)
|
||||
* NOTE: `getResizerProps` is now only called if the column is resizable
|
||||
* Fixes the `className` ordering in defaultProps for ThComponent (#673)
|
||||
* NOTE: user supplied classNames now come at the end so they can extend the defaults
|
||||
- Now passes `column` to `getResizerProps` (#667)
|
||||
- NOTE: `getResizerProps` is now only called if the column is resizable
|
||||
- Fixes the `className` ordering in defaultProps for ThComponent (#673)
|
||||
- NOTE: user supplied classNames now come at the end so they can extend the defaults
|
||||
|
||||
## 6.7.4
|
||||
|
||||
#### Fixes & Optimizations
|
||||
|
||||
* Fix Prop types for columns
|
||||
- Fix Prop types for columns
|
||||
|
||||
## 6.7.3
|
||||
|
||||
#### Fixes & Optimizations
|
||||
|
||||
* Fix the rest of the proptypes
|
||||
- Fix the rest of the proptypes
|
||||
|
||||
## 6.7.2
|
||||
|
||||
#### Fixes & Optimizations
|
||||
|
||||
* `getPropTypes` proptype check
|
||||
- `getPropTypes` proptype check
|
||||
|
||||
## 6.7.1
|
||||
|
||||
#### Fixes & Optimizations
|
||||
|
||||
* `eslint-config` moved to dev deps
|
||||
- `eslint-config` moved to dev deps
|
||||
|
||||
## 6.7.0
|
||||
|
||||
@@ -61,113 +61,113 @@
|
||||
|
||||
#### New Features
|
||||
|
||||
* Expose page/pageSize to rows/cells
|
||||
* Supply sort direction to custom sort methods
|
||||
- Expose page/pageSize to rows/cells
|
||||
- Supply sort direction to custom sort methods
|
||||
|
||||
#### Fixes & Optimizations
|
||||
|
||||
* README updates
|
||||
* Linter cleanup
|
||||
* Added PropTypes node module
|
||||
* Deps, linting and style upgrades
|
||||
- README updates
|
||||
- Linter cleanup
|
||||
- Added PropTypes node module
|
||||
- Deps, linting and style upgrades
|
||||
|
||||
## 6.6.0
|
||||
|
||||
#### Fixes & Optimizations
|
||||
|
||||
* moved repo to react-tools
|
||||
* Doc examples moved to codesandbox.io
|
||||
* README updates
|
||||
* CSS refacting for rt-tfoot to match rt-thead
|
||||
* CSS more specific for input and select
|
||||
- moved repo to react-tools
|
||||
- Doc examples moved to codesandbox.io
|
||||
- README updates
|
||||
- CSS refacting for rt-tfoot to match rt-thead
|
||||
- CSS more specific for input and select
|
||||
|
||||
## 6.5.3
|
||||
|
||||
#### Fixes & Optimizations
|
||||
|
||||
* `onClick` proxying and eslint
|
||||
- `onClick` proxying and eslint
|
||||
|
||||
## 6.5.2
|
||||
|
||||
#### New Features
|
||||
|
||||
* Provide onClick handleOriginal function - #406
|
||||
- Provide onClick handleOriginal function - #406
|
||||
|
||||
#### Fixes & Optimizations
|
||||
|
||||
* README updates
|
||||
* `makePathArray` in utils - #326
|
||||
* Various fixes: #294, #376, #398, #415,
|
||||
- README updates
|
||||
- `makePathArray` in utils - #326
|
||||
- Various fixes: #294, #376, #398, #415,
|
||||
|
||||
## 6.5.1
|
||||
|
||||
#### Fixes & Optimizations
|
||||
|
||||
* `defaultExpanded` now works correctly - #372
|
||||
* `column.getProps().rest` props are now applied correctly
|
||||
* `makeTemplateComponent` now supports `displayName` - #289
|
||||
- `defaultExpanded` now works correctly - #372
|
||||
- `column.getProps().rest` props are now applied correctly
|
||||
- `makeTemplateComponent` now supports `displayName` - #289
|
||||
|
||||
## 6.5.0
|
||||
|
||||
##### New Features
|
||||
|
||||
* `column.filterAll` - defaults to `false`, but when set to `true` will provide the entire array of rows to `filterMethod` as opposed to one row at a time. This allows for more fine-grained filtering using any method you can dream up. See the [Custom Filtering example](https://react-table.js.org/#/story/custom-filtering) for more info.
|
||||
- `column.filterAll` - defaults to `false`, but when set to `true` will provide the entire array of rows to `filterMethod` as opposed to one row at a time. This allows for more fine-grained filtering using any method you can dream up. See the [Custom Filtering example](https://react-table.js.org/#/story/custom-filtering) for more info.
|
||||
|
||||
## 6.4.0
|
||||
|
||||
##### New Features
|
||||
|
||||
* `PadRowComponent` - the content rendered inside of a padding row. Defaults to a react component that renders ` `
|
||||
- `PadRowComponent` - the content rendered inside of a padding row. Defaults to a react component that renders ` `
|
||||
|
||||
## 6.3.0
|
||||
|
||||
##### New Features
|
||||
|
||||
* `defaultSortDesc` - allows you to set the default sorting direction for all columns to descending.
|
||||
* `column.defaultSortDesc` - allows you to set the default sorting direction for a specific column. Falls back to the global `defaultSortDesc` when not set at all.
|
||||
- `defaultSortDesc` - allows you to set the default sorting direction for all columns to descending.
|
||||
- `column.defaultSortDesc` - allows you to set the default sorting direction for a specific column. Falls back to the global `defaultSortDesc` when not set at all.
|
||||
|
||||
## 6.0.0
|
||||
|
||||
##### New Features
|
||||
|
||||
* New Renderers:
|
||||
* `Aggregated` - Custom renderer for aggregated cells
|
||||
* `Pivot` - Custom renderer for Pivoted Cells (utilizes `Expander` and `PivotValue`)
|
||||
* `PivotValue` - Custom renderer for Pivot cell values (deprecates the undocumented `pivotRender` option)
|
||||
* `Expander` - Custom renderer for Pivot cell Expander
|
||||
* Added custom sorting methods per table via `defaultSortMethod` and per column via `column.sortMethod`
|
||||
* Pivot columns are now visibly separate and sorted/filtered independently.
|
||||
* Added `column.resizable` to override global table `resizable` option for specific columns.
|
||||
* Added `column.sortable` to override global table `sortable` option for specific columns.
|
||||
* Added `column.filterable` to override global table `filterable` option for specific columns.
|
||||
* Added `defaultExpanded` table option.
|
||||
* All callbacks can now be utilized without needing to hoist and manage the piece of state they export. That is what their prop counterparts are for, so now the corresponding prop is used instead of the callback to detect a "fully controlled" state.
|
||||
* Prevent transitions while column resizing for a smoother resize effect.
|
||||
* Disable text selection while resizing columns.
|
||||
- New Renderers:
|
||||
- `Aggregated` - Custom renderer for aggregated cells
|
||||
- `Pivot` - Custom renderer for Pivoted Cells (utilizes `Expander` and `PivotValue`)
|
||||
- `PivotValue` - Custom renderer for Pivot cell values (deprecates the undocumented `pivotRender` option)
|
||||
- `Expander` - Custom renderer for Pivot cell Expander
|
||||
- Added custom sorting methods per table via `defaultSortMethod` and per column via `column.sortMethod`
|
||||
- Pivot columns are now visibly separate and sorted/filtered independently.
|
||||
- Added `column.resizable` to override global table `resizable` option for specific columns.
|
||||
- Added `column.sortable` to override global table `sortable` option for specific columns.
|
||||
- Added `column.filterable` to override global table `filterable` option for specific columns.
|
||||
- Added `defaultExpanded` table option.
|
||||
- All callbacks can now be utilized without needing to hoist and manage the piece of state they export. That is what their prop counterparts are for, so now the corresponding prop is used instead of the callback to detect a "fully controlled" state.
|
||||
- Prevent transitions while column resizing for a smoother resize effect.
|
||||
- Disable text selection while resizing columns.
|
||||
|
||||
##### Breaking API Changes
|
||||
|
||||
* New Renderers:
|
||||
* `Cell` - deprecates and replaces `render`
|
||||
* `Header` - deprecates and replaces `header`
|
||||
* `Footer` - deprecates and replaces `footer`
|
||||
* `Filter`- deprecates and replaces `filterRender`
|
||||
* Callbacks now provide the destination state as the primary parameter(s). This makes hoisting and controlling the state in redux or component state much easier. eg.
|
||||
* `onSorting` no longer requires you to build your own toggle logic
|
||||
* `onResize` no longer requires you to build your own resize logic
|
||||
* Renamed `onChange` callback -> `onFetchData` which will always fire when a new data model needs to be fetched (or if not using `manual`, when new data is materialized internally).
|
||||
* Renamed `filtering` -> `filtered`
|
||||
* Renamed `sorting` -> `sorted`
|
||||
* Renamed `expandedRows` -> `expanded`
|
||||
* Renamed `resizing` -> `resized`
|
||||
* Renamed `defaultResizing` -> `defaultResized`
|
||||
* Renamed `defaultFiltering` -> `defaultFiltered`
|
||||
* Renamed `defaultSorting` -> `defaultSorted`
|
||||
* Renamed `onSortingChange` -> `onSortedChange`
|
||||
* Renamed `onFilteringChange` -> `onFilteredChange`
|
||||
* Renamed `onResize` -> `onResizedChange`
|
||||
* Renamed `onExpandRow` -> `onExpandedChange`
|
||||
* Renamed `showFilters` -> `filterable`
|
||||
* Renamed `hideFilter` -> `filterable` (Column option. Note the true/false value is now flipped.)
|
||||
* `cellInfo.row` and `rowInfo.row` now reference the materialize data for the table. To reference the original row, use `cellInfo.original` and `rowInfo.original`
|
||||
* Removed `pivotRender` column option. You can now control how the value is displayed by overriding the `PivotValueComponent` or the individual column's `PivotValue` renderer. See [Pivoting Options Story](https://react-table.js.org/?selectedKind=2.%20Demos&selectedStory=Pivoting%20Options&full=0&down=1&left=1&panelRight=0&downPanel=kadirahq%2Fstorybook-addon-actions%2Factions-panel) for a reference on how to customize pivot column rendering.
|
||||
- New Renderers:
|
||||
- `Cell` - deprecates and replaces `render`
|
||||
- `Header` - deprecates and replaces `header`
|
||||
- `Footer` - deprecates and replaces `footer`
|
||||
- `Filter`- deprecates and replaces `filterRender`
|
||||
- Callbacks now provide the destination state as the primary parameter(s). This makes hoisting and controlling the state in redux or component state much easier. eg.
|
||||
- `onSorting` no longer requires you to build your own toggle logic
|
||||
- `onResize` no longer requires you to build your own resize logic
|
||||
- Renamed `onChange` callback -> `onFetchData` which will always fire when a new data model needs to be fetched (or if not using `manual`, when new data is materialized internally).
|
||||
- Renamed `filtering` -> `filtered`
|
||||
- Renamed `sorting` -> `sorted`
|
||||
- Renamed `expandedRows` -> `expanded`
|
||||
- Renamed `resizing` -> `resized`
|
||||
- Renamed `defaultResizing` -> `defaultResized`
|
||||
- Renamed `defaultFiltering` -> `defaultFiltered`
|
||||
- Renamed `defaultSorting` -> `defaultSorted`
|
||||
- Renamed `onSortingChange` -> `onSortedChange`
|
||||
- Renamed `onFilteringChange` -> `onFilteredChange`
|
||||
- Renamed `onResize` -> `onResizedChange`
|
||||
- Renamed `onExpandRow` -> `onExpandedChange`
|
||||
- Renamed `showFilters` -> `filterable`
|
||||
- Renamed `hideFilter` -> `filterable` (Column option. Note the true/false value is now flipped.)
|
||||
- `cellInfo.row` and `rowInfo.row` now reference the materialize data for the table. To reference the original row, use `cellInfo.original` and `rowInfo.original`
|
||||
- Removed `pivotRender` column option. You can now control how the value is displayed by overriding the `PivotValueComponent` or the individual column's `PivotValue` renderer. See [Pivoting Options Story](https://react-table.js.org/?selectedKind=2.%20Demos&selectedStory=Pivoting%20Options&full=0&down=1&left=1&panelRight=0&downPanel=kadirahq%2Fstorybook-addon-actions%2Factions-panel) for a reference on how to customize pivot column rendering.
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
module.exports = { extends: ['@commitlint/config-conventional'] }
|
||||
@@ -1,17 +1,16 @@
|
||||
const path = require('path');
|
||||
const path = require('path')
|
||||
|
||||
module.exports = {
|
||||
moduleDirectories: [
|
||||
'node_modules',
|
||||
/*
|
||||
* make 'test/utils' available in tests, e.g.
|
||||
* __dirname makes 'test/utils' available in tests, e.g.
|
||||
*
|
||||
* const {myModule} = require('utils/my-test-helper')
|
||||
*/
|
||||
__dirname,
|
||||
],
|
||||
|
||||
rootDir: path.resolve(__dirname, '../..'),
|
||||
|
||||
rootDir: path.resolve(__dirname, '../../'),
|
||||
roots: ['<rootDir>/src', __dirname],
|
||||
};
|
||||
transformIgnorePatterns: ['node_modules'],
|
||||
}
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
const commonConfig = require('./jest.common');
|
||||
const commonConfig = require('./jest.common')
|
||||
|
||||
module.exports = {
|
||||
...commonConfig,
|
||||
|
||||
displayName: 'unit',
|
||||
|
||||
coverageDirectory: '../../coverage',
|
||||
|
||||
testMatch: ['<rootDir>/tests/**/*.js'],
|
||||
|
||||
testMatch: ['<rootDir>/src/**/*.test.js'],
|
||||
transform: {
|
||||
// '^.+\\.js$': '<rootDir>/node_modules/babel-jest',
|
||||
'^.+\\.js$': '<rootDir>/node_modules/babel-jest',
|
||||
},
|
||||
};
|
||||
setupFilesAfterEnv: ['./configs/tests/setup.common.js'],
|
||||
}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
import 'snapshot-diff/extend-expect'
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"presets": ["react-app"],
|
||||
"plugins": ["styled-components"]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
SKIP_PREFLIGHT_CHECK=true
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": ["react-app", "prettier"],
|
||||
"rules": {
|
||||
// "eqeqeq": 0,
|
||||
// "jsx-a11y/anchor-is-valid": 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.js
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
@@ -0,0 +1,29 @@
|
||||
const path = require('path')
|
||||
const resolveFrom = require('resolve-from')
|
||||
|
||||
const fixLinkedDependencies = config => {
|
||||
config.resolve = {
|
||||
...config.resolve,
|
||||
alias: {
|
||||
...config.resolve.alias,
|
||||
react$: resolveFrom(path.resolve('node_modules'), 'react'),
|
||||
'react-dom$': resolveFrom(path.resolve('node_modules'), 'react-dom'),
|
||||
},
|
||||
}
|
||||
return config
|
||||
}
|
||||
|
||||
const includeSrcDirectory = config => {
|
||||
config.resolve = {
|
||||
...config.resolve,
|
||||
modules: [path.resolve('src'), ...config.resolve.modules],
|
||||
}
|
||||
return config
|
||||
}
|
||||
|
||||
module.exports = [
|
||||
['use-babel-config', '.babelrc'],
|
||||
['use-eslint-config', '.eslintrc'],
|
||||
fixLinkedDependencies,
|
||||
// includeSrcDirectory,
|
||||
]
|
||||
@@ -0,0 +1,6 @@
|
||||
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app) and Rescripts.
|
||||
|
||||
You can:
|
||||
|
||||
- [Open this example in a new CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/basic)
|
||||
- `yarn` and `yarn start` to run and edit the example
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"start": "rescripts start",
|
||||
"build": "rescripts build",
|
||||
"test": "rescripts test",
|
||||
"eject": "rescripts eject"
|
||||
},
|
||||
"dependencies": {
|
||||
"namor": "^1.1.2",
|
||||
"react": "^16.8.6",
|
||||
"react-dom": "^16.8.6",
|
||||
"react-scripts": "3.0.1",
|
||||
"react-table": "next",
|
||||
"styled-components": "^4.3.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@rescripts/cli": "^0.0.11",
|
||||
"@rescripts/rescript-use-babel-config": "^0.0.8",
|
||||
"@rescripts/rescript-use-eslint-config": "^0.0.9",
|
||||
"babel-eslint": "10.0.1"
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 3.8 KiB |
@@ -0,0 +1,38 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="theme-color" content="#000000" />
|
||||
<!--
|
||||
manifest.json provides metadata used when your web app is installed on a
|
||||
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
|
||||
-->
|
||||
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
|
||||
<!--
|
||||
Notice the use of %PUBLIC_URL% in the tags above.
|
||||
It will be replaced with the URL of the `public` folder during the build.
|
||||
Only files inside the `public` folder can be referenced from the HTML.
|
||||
|
||||
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
|
||||
work correctly both with client-side routing and a non-root public URL.
|
||||
Learn how to configure a non-root public URL by running `npm run build`.
|
||||
-->
|
||||
<title>React App</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||
<div id="root"></div>
|
||||
<!--
|
||||
This HTML file is a template.
|
||||
If you open it directly in the browser, you will see an empty page.
|
||||
|
||||
You can add webfonts, meta tags, or analytics to this file.
|
||||
The build step will place the bundled scripts into the <body> tag.
|
||||
|
||||
To begin the development, run `npm start` or `yarn start`.
|
||||
To create a production bundle, use `npm run build` or `yarn build`.
|
||||
-->
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"short_name": "React App",
|
||||
"name": "Create React App Sample",
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicon.ico",
|
||||
"sizes": "64x64 32x32 24x24 16x16",
|
||||
"type": "image/x-icon"
|
||||
}
|
||||
],
|
||||
"start_url": ".",
|
||||
"display": "standalone",
|
||||
"theme_color": "#000000",
|
||||
"background_color": "#ffffff"
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import React from 'react'
|
||||
import styled from 'styled-components'
|
||||
import { useTable } from 'react-table'
|
||||
|
||||
import makeData from './makeData'
|
||||
|
||||
const Styles = styled.div`
|
||||
padding: 1rem;
|
||||
|
||||
table {
|
||||
border-spacing: 0;
|
||||
border: 1px solid black;
|
||||
|
||||
tr {
|
||||
:last-child {
|
||||
td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
th,
|
||||
td {
|
||||
margin: 0;
|
||||
padding: 0.5rem;
|
||||
border-bottom: 1px solid black;
|
||||
border-right: 1px solid black;
|
||||
|
||||
:last-child {
|
||||
border-right: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
function Table({ columns, data }) {
|
||||
// Use the state and functions returned from useTable to build your UI
|
||||
const { getTableProps, headerGroups, rows, prepareRow } = useTable({
|
||||
columns,
|
||||
data,
|
||||
})
|
||||
|
||||
// Render the UI for your table
|
||||
return (
|
||||
<table {...getTableProps()}>
|
||||
<thead>
|
||||
{headerGroups.map(headerGroup => (
|
||||
<tr {...headerGroup.getHeaderGroupProps()}>
|
||||
{headerGroup.headers.map(column => (
|
||||
<th {...column.getHeaderProps()}>{column.render('Header')}</th>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map(
|
||||
(row, i) =>
|
||||
prepareRow(row) || (
|
||||
<tr {...row.getRowProps()}>
|
||||
{row.cells.map(cell => {
|
||||
return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
|
||||
})}
|
||||
</tr>
|
||||
)
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
)
|
||||
}
|
||||
|
||||
function App() {
|
||||
const columns = React.useMemo(
|
||||
() => [
|
||||
{
|
||||
Header: 'Name',
|
||||
columns: [
|
||||
{
|
||||
Header: 'First Name',
|
||||
accessor: 'firstName',
|
||||
},
|
||||
{
|
||||
Header: 'Last Name',
|
||||
accessor: 'lastName',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
Header: 'Info',
|
||||
columns: [
|
||||
{
|
||||
Header: 'Age',
|
||||
accessor: 'age',
|
||||
},
|
||||
{
|
||||
Header: 'Visits',
|
||||
accessor: 'visits',
|
||||
},
|
||||
{
|
||||
Header: 'Status',
|
||||
accessor: 'status',
|
||||
},
|
||||
{
|
||||
Header: 'Profile Progress',
|
||||
accessor: 'progress',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
[]
|
||||
)
|
||||
|
||||
const data = React.useMemo(() => makeData(20), [])
|
||||
|
||||
return (
|
||||
<Styles>
|
||||
<Table columns={columns} data={data} />
|
||||
</Styles>
|
||||
)
|
||||
}
|
||||
|
||||
export default App
|
||||
@@ -0,0 +1,9 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import App from './App';
|
||||
|
||||
it('renders without crashing', () => {
|
||||
const div = document.createElement('div');
|
||||
ReactDOM.render(<App />, div);
|
||||
ReactDOM.unmountComponentAtNode(div);
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
|
||||
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
|
||||
sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
|
||||
monospace;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import './index.css';
|
||||
import App from './App';
|
||||
import * as serviceWorker from './serviceWorker';
|
||||
|
||||
ReactDOM.render(<App />, document.getElementById('root'));
|
||||
|
||||
// If you want your app to work offline and load faster, you can change
|
||||
// unregister() to register() below. Note this comes with some pitfalls.
|
||||
// Learn more about service workers: https://bit.ly/CRA-PWA
|
||||
serviceWorker.unregister();
|
||||
@@ -0,0 +1,40 @@
|
||||
import namor from 'namor'
|
||||
|
||||
const range = len => {
|
||||
const arr = []
|
||||
for (let i = 0; i < len; i++) {
|
||||
arr.push(i)
|
||||
}
|
||||
return arr
|
||||
}
|
||||
|
||||
const newPerson = () => {
|
||||
const statusChance = Math.random()
|
||||
return {
|
||||
firstName: namor.generate({ words: 1, numbers: 0 }),
|
||||
lastName: namor.generate({ words: 1, numbers: 0 }),
|
||||
age: Math.floor(Math.random() * 30),
|
||||
visits: Math.floor(Math.random() * 100),
|
||||
progress: Math.floor(Math.random() * 100),
|
||||
status:
|
||||
statusChance > 0.66
|
||||
? 'relationship'
|
||||
: statusChance > 0.33
|
||||
? 'complicated'
|
||||
: 'single',
|
||||
}
|
||||
}
|
||||
|
||||
export default function makeData(...lens) {
|
||||
const makeDataLevel = (depth = 0) => {
|
||||
const len = lens[depth]
|
||||
return range(len).map(d => {
|
||||
return {
|
||||
...newPerson(),
|
||||
subRows: lens[depth + 1] ? makeDataLevel(depth + 1) : undefined,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return makeDataLevel()
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
// This optional code is used to register a service worker.
|
||||
// register() is not called by default.
|
||||
|
||||
// This lets the app load faster on subsequent visits in production, and gives
|
||||
// it offline capabilities. However, it also means that developers (and users)
|
||||
// will only see deployed updates on subsequent visits to a page, after all the
|
||||
// existing tabs open on the page have been closed, since previously cached
|
||||
// resources are updated in the background.
|
||||
|
||||
// To learn more about the benefits of this model and instructions on how to
|
||||
// opt-in, read https://bit.ly/CRA-PWA
|
||||
|
||||
const isLocalhost = Boolean(
|
||||
window.location.hostname === 'localhost' ||
|
||||
// [::1] is the IPv6 localhost address.
|
||||
window.location.hostname === '[::1]' ||
|
||||
// 127.0.0.1/8 is considered localhost for IPv4.
|
||||
window.location.hostname.match(
|
||||
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
|
||||
)
|
||||
);
|
||||
|
||||
export function register(config) {
|
||||
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
|
||||
// The URL constructor is available in all browsers that support SW.
|
||||
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
|
||||
if (publicUrl.origin !== window.location.origin) {
|
||||
// Our service worker won't work if PUBLIC_URL is on a different origin
|
||||
// from what our page is served on. This might happen if a CDN is used to
|
||||
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
|
||||
return;
|
||||
}
|
||||
|
||||
window.addEventListener('load', () => {
|
||||
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
|
||||
|
||||
if (isLocalhost) {
|
||||
// This is running on localhost. Let's check if a service worker still exists or not.
|
||||
checkValidServiceWorker(swUrl, config);
|
||||
|
||||
// Add some additional logging to localhost, pointing developers to the
|
||||
// service worker/PWA documentation.
|
||||
navigator.serviceWorker.ready.then(() => {
|
||||
console.log(
|
||||
'This web app is being served cache-first by a service ' +
|
||||
'worker. To learn more, visit https://bit.ly/CRA-PWA'
|
||||
);
|
||||
});
|
||||
} else {
|
||||
// Is not localhost. Just register service worker
|
||||
registerValidSW(swUrl, config);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function registerValidSW(swUrl, config) {
|
||||
navigator.serviceWorker
|
||||
.register(swUrl)
|
||||
.then(registration => {
|
||||
registration.onupdatefound = () => {
|
||||
const installingWorker = registration.installing;
|
||||
if (installingWorker == null) {
|
||||
return;
|
||||
}
|
||||
installingWorker.onstatechange = () => {
|
||||
if (installingWorker.state === 'installed') {
|
||||
if (navigator.serviceWorker.controller) {
|
||||
// At this point, the updated precached content has been fetched,
|
||||
// but the previous service worker will still serve the older
|
||||
// content until all client tabs are closed.
|
||||
console.log(
|
||||
'New content is available and will be used when all ' +
|
||||
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
|
||||
);
|
||||
|
||||
// Execute callback
|
||||
if (config && config.onUpdate) {
|
||||
config.onUpdate(registration);
|
||||
}
|
||||
} else {
|
||||
// At this point, everything has been precached.
|
||||
// It's the perfect time to display a
|
||||
// "Content is cached for offline use." message.
|
||||
console.log('Content is cached for offline use.');
|
||||
|
||||
// Execute callback
|
||||
if (config && config.onSuccess) {
|
||||
config.onSuccess(registration);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error during service worker registration:', error);
|
||||
});
|
||||
}
|
||||
|
||||
function checkValidServiceWorker(swUrl, config) {
|
||||
// Check if the service worker can be found. If it can't reload the page.
|
||||
fetch(swUrl)
|
||||
.then(response => {
|
||||
// Ensure service worker exists, and that we really are getting a JS file.
|
||||
const contentType = response.headers.get('content-type');
|
||||
if (
|
||||
response.status === 404 ||
|
||||
(contentType != null && contentType.indexOf('javascript') === -1)
|
||||
) {
|
||||
// No service worker found. Probably a different app. Reload the page.
|
||||
navigator.serviceWorker.ready.then(registration => {
|
||||
registration.unregister().then(() => {
|
||||
window.location.reload();
|
||||
});
|
||||
});
|
||||
} else {
|
||||
// Service worker found. Proceed as normal.
|
||||
registerValidSW(swUrl, config);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
console.log(
|
||||
'No internet connection found. App is running in offline mode.'
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function unregister() {
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker.ready.then(registration => {
|
||||
registration.unregister();
|
||||
});
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"presets": ["react-app"],
|
||||
"plugins": ["styled-components"]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
SKIP_PREFLIGHT_CHECK=true
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": ["react-app", "prettier"],
|
||||
"rules": {
|
||||
// "eqeqeq": 0,
|
||||
// "jsx-a11y/anchor-is-valid": 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.js
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
@@ -0,0 +1,29 @@
|
||||
const path = require('path')
|
||||
const resolveFrom = require('resolve-from')
|
||||
|
||||
const fixLinkedDependencies = config => {
|
||||
config.resolve = {
|
||||
...config.resolve,
|
||||
alias: {
|
||||
...config.resolve.alias,
|
||||
react$: resolveFrom(path.resolve('node_modules'), 'react'),
|
||||
'react-dom$': resolveFrom(path.resolve('node_modules'), 'react-dom'),
|
||||
},
|
||||
}
|
||||
return config
|
||||
}
|
||||
|
||||
const includeSrcDirectory = config => {
|
||||
config.resolve = {
|
||||
...config.resolve,
|
||||
modules: [path.resolve('src'), ...config.resolve.modules],
|
||||
}
|
||||
return config
|
||||
}
|
||||
|
||||
module.exports = [
|
||||
['use-babel-config', '.babelrc'],
|
||||
['use-eslint-config', '.eslintrc'],
|
||||
fixLinkedDependencies,
|
||||
// includeSrcDirectory,
|
||||
]
|
||||
@@ -0,0 +1,6 @@
|
||||
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app) and Rescripts.
|
||||
|
||||
You can:
|
||||
|
||||
- [Open this example in a new CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/basic)
|
||||
- `yarn` and `yarn start` to run and edit the example
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"start": "rescripts start",
|
||||
"build": "rescripts build",
|
||||
"test": "rescripts test",
|
||||
"eject": "rescripts eject"
|
||||
},
|
||||
"dependencies": {
|
||||
"match-sorter": "^4.0.0",
|
||||
"namor": "^1.1.2",
|
||||
"react": "^16.8.6",
|
||||
"react-dom": "^16.8.6",
|
||||
"react-scripts": "3.0.1",
|
||||
"react-table": "next",
|
||||
"styled-components": "^4.3.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@rescripts/cli": "^0.0.11",
|
||||
"@rescripts/rescript-use-babel-config": "^0.0.8",
|
||||
"@rescripts/rescript-use-eslint-config": "^0.0.9",
|
||||
"babel-eslint": "10.0.1"
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 3.8 KiB |
@@ -0,0 +1,38 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="theme-color" content="#000000" />
|
||||
<!--
|
||||
manifest.json provides metadata used when your web app is installed on a
|
||||
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
|
||||
-->
|
||||
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
|
||||
<!--
|
||||
Notice the use of %PUBLIC_URL% in the tags above.
|
||||
It will be replaced with the URL of the `public` folder during the build.
|
||||
Only files inside the `public` folder can be referenced from the HTML.
|
||||
|
||||
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
|
||||
work correctly both with client-side routing and a non-root public URL.
|
||||
Learn how to configure a non-root public URL by running `npm run build`.
|
||||
-->
|
||||
<title>React App</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||
<div id="root"></div>
|
||||
<!--
|
||||
This HTML file is a template.
|
||||
If you open it directly in the browser, you will see an empty page.
|
||||
|
||||
You can add webfonts, meta tags, or analytics to this file.
|
||||
The build step will place the bundled scripts into the <body> tag.
|
||||
|
||||
To begin the development, run `npm start` or `yarn start`.
|
||||
To create a production bundle, use `npm run build` or `yarn build`.
|
||||
-->
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"short_name": "React App",
|
||||
"name": "Create React App Sample",
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicon.ico",
|
||||
"sizes": "64x64 32x32 24x24 16x16",
|
||||
"type": "image/x-icon"
|
||||
}
|
||||
],
|
||||
"start_url": ".",
|
||||
"display": "standalone",
|
||||
"theme_color": "#000000",
|
||||
"background_color": "#ffffff"
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
import React from 'react'
|
||||
import styled from 'styled-components'
|
||||
import { useTable, useFilters } from 'react-table'
|
||||
// A great library for fuzzy filtering/sorting items
|
||||
import matchSorter from 'match-sorter'
|
||||
|
||||
import makeData from './makeData'
|
||||
|
||||
const Styles = styled.div`
|
||||
padding: 1rem;
|
||||
|
||||
table {
|
||||
border-spacing: 0;
|
||||
border: 1px solid black;
|
||||
|
||||
tr {
|
||||
:last-child {
|
||||
td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
th,
|
||||
td {
|
||||
margin: 0;
|
||||
padding: 0.5rem;
|
||||
border-bottom: 1px solid black;
|
||||
border-right: 1px solid black;
|
||||
|
||||
:last-child {
|
||||
border-right: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
// Define a default UI for filtering
|
||||
function DefaultColumnFilter({ filterValue, setFilter }) {
|
||||
return (
|
||||
<input
|
||||
value={filterValue || ''}
|
||||
onChange={e => {
|
||||
setFilter(e.target.value || undefined) // Set undefined to remove the filter entirely
|
||||
}}
|
||||
placeholder="Search..."
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// This is a custom filter UI for selecting
|
||||
// a unique option from a list
|
||||
function SelectColumnFilter({ filterValue, setFilter, preFilteredRows, id }) {
|
||||
// Calculate the options for filtering
|
||||
// using the preFilteredRows
|
||||
const options = React.useMemo(
|
||||
() => {
|
||||
const options = new Set()
|
||||
preFilteredRows.forEach(row => {
|
||||
options.add(row.values[id])
|
||||
})
|
||||
return [...options.values()]
|
||||
},
|
||||
[id, preFilteredRows]
|
||||
)
|
||||
|
||||
// Render a multi-select box
|
||||
return (
|
||||
<select
|
||||
value={filterValue}
|
||||
onChange={e => {
|
||||
setFilter(e.target.value || undefined)
|
||||
}}
|
||||
>
|
||||
<option value="">All</option>
|
||||
{options.map((option, i) => (
|
||||
<option key={i} value={option}>
|
||||
{option}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)
|
||||
}
|
||||
|
||||
// This is a custom filter UI that uses a
|
||||
// slider to set the filter value between a column's
|
||||
// min and max values
|
||||
function SliderColumnFilter({ filterValue, setFilter, preFilteredRows, id }) {
|
||||
// Calculate the min and max
|
||||
// using the preFilteredRows
|
||||
const [min, max] = React.useMemo(
|
||||
() => {
|
||||
let min = 0
|
||||
let max = 0
|
||||
preFilteredRows.forEach(row => {
|
||||
min = Math.min(row.values[id], min)
|
||||
max = Math.max(row.values[id], max)
|
||||
})
|
||||
return [min, max]
|
||||
},
|
||||
[id, preFilteredRows]
|
||||
)
|
||||
|
||||
return (
|
||||
<>
|
||||
<input
|
||||
type="range"
|
||||
min={min}
|
||||
max={max}
|
||||
value={filterValue || min}
|
||||
onChange={e => {
|
||||
setFilter(parseInt(e.target.value, 10))
|
||||
}}
|
||||
/>
|
||||
<button onClick={() => setFilter(undefined)}>Off</button>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// This is a custom UI for our 'between' or number range
|
||||
// filter. It uses two number boxes and filters rows to
|
||||
// ones that have values between the two
|
||||
function NumberRangeColumnFilter({ filterValue = [], setFilter }) {
|
||||
return (
|
||||
<div
|
||||
css={`
|
||||
display: flex;
|
||||
`}
|
||||
>
|
||||
<input
|
||||
value={filterValue[0] || ''}
|
||||
type="number"
|
||||
onChange={e => {
|
||||
const val = e.target.value
|
||||
setFilter((old = []) => [val ? parseInt(val, 10) : undefined, old[1]])
|
||||
}}
|
||||
placeholder="Min"
|
||||
css={`
|
||||
width: 70px;
|
||||
margin-right: 0.5rem;
|
||||
`}
|
||||
/>
|
||||
to
|
||||
<input
|
||||
value={filterValue[1] || ''}
|
||||
type="number"
|
||||
onChange={e => {
|
||||
const val = e.target.value
|
||||
setFilter((old = []) => [old[0], val ? parseInt(val, 10) : undefined])
|
||||
}}
|
||||
placeholder="Max"
|
||||
css={`
|
||||
width: 70px;
|
||||
margin-left: 0.5rem;
|
||||
`}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function fuzzyTextFilterFn(rows, id, filterValue) {
|
||||
return matchSorter(rows, filterValue, { keys: [row => row.values[id]] })
|
||||
}
|
||||
|
||||
// Let the table remove the filter if the string is empty
|
||||
fuzzyTextFilterFn.autoRemove = val => !val
|
||||
|
||||
// Our table component
|
||||
function Table({ columns, data }) {
|
||||
const filterTypes = React.useMemo(
|
||||
() => ({
|
||||
// Add a new fuzzyTextFilterFn filter type.
|
||||
fuzzyText: fuzzyTextFilterFn,
|
||||
// Or, override the default text filter to use
|
||||
// "startWith"
|
||||
text: (rows, id, filterValue) => {
|
||||
return rows.filter(row => {
|
||||
const rowValue = row.values[id]
|
||||
return rowValue !== undefined
|
||||
? String(rowValue)
|
||||
.toLowerCase()
|
||||
.startsWith(String(filterValue).toLowerCase())
|
||||
: true
|
||||
})
|
||||
},
|
||||
}),
|
||||
[]
|
||||
)
|
||||
|
||||
const defaultColumn = React.useMemo(
|
||||
() => ({
|
||||
// Let's set up our default Filter UI
|
||||
Filter: DefaultColumnFilter,
|
||||
}),
|
||||
[]
|
||||
)
|
||||
|
||||
const { getTableProps, headerGroups, rows, prepareRow, state } = useTable(
|
||||
{
|
||||
columns,
|
||||
data,
|
||||
defaultColumn, // Be sure to pass the defaultColumn option
|
||||
filterTypes,
|
||||
},
|
||||
useFilters // useFilters!
|
||||
)
|
||||
|
||||
// We don't want to render all 2000 rows for this example, so cap
|
||||
// it at 20 for this use case
|
||||
const firstPageRows = rows.slice(0, 20)
|
||||
|
||||
return (
|
||||
<>
|
||||
<div>
|
||||
<pre>
|
||||
<code>{JSON.stringify(state[0].filters, null, 2)}</code>
|
||||
</pre>
|
||||
</div>
|
||||
<table {...getTableProps()}>
|
||||
<thead>
|
||||
{headerGroups.map(headerGroup => (
|
||||
<tr {...headerGroup.getHeaderGroupProps()}>
|
||||
{headerGroup.headers.map(column => (
|
||||
<th {...column.getHeaderProps()}>
|
||||
{column.render('Header')}
|
||||
{/* Render the columns filter UI */}
|
||||
<div>{column.canFilter ? column.render('Filter') : null}</div>
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
<tbody>
|
||||
{firstPageRows.map(
|
||||
(row, i) =>
|
||||
prepareRow(row) || (
|
||||
<tr {...row.getRowProps()}>
|
||||
{row.cells.map(cell => {
|
||||
return (
|
||||
<td {...cell.getCellProps()}>{cell.render('Cell')}</td>
|
||||
)
|
||||
})}
|
||||
</tr>
|
||||
)
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
<br />
|
||||
<div>Showing the first 20 results of {rows.length} rows</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// Define a custom filter filter function!
|
||||
function filterGreaterThan(rows, id, filterValue) {
|
||||
return rows.filter(row => {
|
||||
const rowValue = row.values[id]
|
||||
return rowValue >= filterValue
|
||||
})
|
||||
}
|
||||
|
||||
// This is an autoRemove method on the filter function that
|
||||
// when given the new filter value and returns true, the filter
|
||||
// will be automatically removed. Normally this is just an undefined
|
||||
// check, but here, we want to remove the filter if it's not a number
|
||||
filterGreaterThan.autoRemove = val => typeof val !== 'number'
|
||||
|
||||
function App() {
|
||||
const columns = React.useMemo(
|
||||
() => [
|
||||
{
|
||||
Header: 'Name',
|
||||
columns: [
|
||||
{
|
||||
Header: 'First Name',
|
||||
accessor: 'firstName',
|
||||
},
|
||||
{
|
||||
Header: 'Last Name',
|
||||
accessor: 'lastName',
|
||||
// Use our custom `fuzzyText` filter on this column
|
||||
filter: 'fuzzyText',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
Header: 'Info',
|
||||
columns: [
|
||||
{
|
||||
Header: 'Age',
|
||||
accessor: 'age',
|
||||
Filter: SliderColumnFilter,
|
||||
filter: 'equals',
|
||||
},
|
||||
{
|
||||
Header: 'Visits',
|
||||
accessor: 'visits',
|
||||
Filter: NumberRangeColumnFilter,
|
||||
filter: 'between',
|
||||
},
|
||||
{
|
||||
Header: 'Status',
|
||||
accessor: 'status',
|
||||
Filter: SelectColumnFilter,
|
||||
filter: 'includes',
|
||||
},
|
||||
{
|
||||
Header: 'Profile Progress',
|
||||
accessor: 'progress',
|
||||
Filter: SliderColumnFilter,
|
||||
filter: filterGreaterThan,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
[]
|
||||
)
|
||||
|
||||
const data = React.useMemo(() => makeData(10000), [])
|
||||
|
||||
return (
|
||||
<Styles>
|
||||
<Table columns={columns} data={data} />
|
||||
</Styles>
|
||||
)
|
||||
}
|
||||
|
||||
export default App
|
||||
@@ -0,0 +1,9 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import App from './App';
|
||||
|
||||
it('renders without crashing', () => {
|
||||
const div = document.createElement('div');
|
||||
ReactDOM.render(<App />, div);
|
||||
ReactDOM.unmountComponentAtNode(div);
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
|
||||
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
|
||||
sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
|
||||
monospace;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import './index.css';
|
||||
import App from './App';
|
||||
import * as serviceWorker from './serviceWorker';
|
||||
|
||||
ReactDOM.render(<App />, document.getElementById('root'));
|
||||
|
||||
// If you want your app to work offline and load faster, you can change
|
||||
// unregister() to register() below. Note this comes with some pitfalls.
|
||||
// Learn more about service workers: https://bit.ly/CRA-PWA
|
||||
serviceWorker.unregister();
|
||||
@@ -0,0 +1,40 @@
|
||||
import namor from 'namor'
|
||||
|
||||
const range = len => {
|
||||
const arr = []
|
||||
for (let i = 0; i < len; i++) {
|
||||
arr.push(i)
|
||||
}
|
||||
return arr
|
||||
}
|
||||
|
||||
const newPerson = () => {
|
||||
const statusChance = Math.random()
|
||||
return {
|
||||
firstName: namor.generate({ words: 1, numbers: 0 }),
|
||||
lastName: namor.generate({ words: 1, numbers: 0 }),
|
||||
age: Math.floor(Math.random() * 30),
|
||||
visits: Math.floor(Math.random() * 100),
|
||||
progress: Math.floor(Math.random() * 100),
|
||||
status:
|
||||
statusChance > 0.66
|
||||
? 'relationship'
|
||||
: statusChance > 0.33
|
||||
? 'complicated'
|
||||
: 'single',
|
||||
}
|
||||
}
|
||||
|
||||
export default function makeData(...lens) {
|
||||
const makeDataLevel = (depth = 0) => {
|
||||
const len = lens[depth]
|
||||
return range(len).map(d => {
|
||||
return {
|
||||
...newPerson(),
|
||||
subRows: lens[depth + 1] ? makeDataLevel(depth + 1) : undefined,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return makeDataLevel()
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
// This optional code is used to register a service worker.
|
||||
// register() is not called by default.
|
||||
|
||||
// This lets the app load faster on subsequent visits in production, and gives
|
||||
// it offline capabilities. However, it also means that developers (and users)
|
||||
// will only see deployed updates on subsequent visits to a page, after all the
|
||||
// existing tabs open on the page have been closed, since previously cached
|
||||
// resources are updated in the background.
|
||||
|
||||
// To learn more about the benefits of this model and instructions on how to
|
||||
// opt-in, read https://bit.ly/CRA-PWA
|
||||
|
||||
const isLocalhost = Boolean(
|
||||
window.location.hostname === 'localhost' ||
|
||||
// [::1] is the IPv6 localhost address.
|
||||
window.location.hostname === '[::1]' ||
|
||||
// 127.0.0.1/8 is considered localhost for IPv4.
|
||||
window.location.hostname.match(
|
||||
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
|
||||
)
|
||||
);
|
||||
|
||||
export function register(config) {
|
||||
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
|
||||
// The URL constructor is available in all browsers that support SW.
|
||||
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
|
||||
if (publicUrl.origin !== window.location.origin) {
|
||||
// Our service worker won't work if PUBLIC_URL is on a different origin
|
||||
// from what our page is served on. This might happen if a CDN is used to
|
||||
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
|
||||
return;
|
||||
}
|
||||
|
||||
window.addEventListener('load', () => {
|
||||
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
|
||||
|
||||
if (isLocalhost) {
|
||||
// This is running on localhost. Let's check if a service worker still exists or not.
|
||||
checkValidServiceWorker(swUrl, config);
|
||||
|
||||
// Add some additional logging to localhost, pointing developers to the
|
||||
// service worker/PWA documentation.
|
||||
navigator.serviceWorker.ready.then(() => {
|
||||
console.log(
|
||||
'This web app is being served cache-first by a service ' +
|
||||
'worker. To learn more, visit https://bit.ly/CRA-PWA'
|
||||
);
|
||||
});
|
||||
} else {
|
||||
// Is not localhost. Just register service worker
|
||||
registerValidSW(swUrl, config);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function registerValidSW(swUrl, config) {
|
||||
navigator.serviceWorker
|
||||
.register(swUrl)
|
||||
.then(registration => {
|
||||
registration.onupdatefound = () => {
|
||||
const installingWorker = registration.installing;
|
||||
if (installingWorker == null) {
|
||||
return;
|
||||
}
|
||||
installingWorker.onstatechange = () => {
|
||||
if (installingWorker.state === 'installed') {
|
||||
if (navigator.serviceWorker.controller) {
|
||||
// At this point, the updated precached content has been fetched,
|
||||
// but the previous service worker will still serve the older
|
||||
// content until all client tabs are closed.
|
||||
console.log(
|
||||
'New content is available and will be used when all ' +
|
||||
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
|
||||
);
|
||||
|
||||
// Execute callback
|
||||
if (config && config.onUpdate) {
|
||||
config.onUpdate(registration);
|
||||
}
|
||||
} else {
|
||||
// At this point, everything has been precached.
|
||||
// It's the perfect time to display a
|
||||
// "Content is cached for offline use." message.
|
||||
console.log('Content is cached for offline use.');
|
||||
|
||||
// Execute callback
|
||||
if (config && config.onSuccess) {
|
||||
config.onSuccess(registration);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error during service worker registration:', error);
|
||||
});
|
||||
}
|
||||
|
||||
function checkValidServiceWorker(swUrl, config) {
|
||||
// Check if the service worker can be found. If it can't reload the page.
|
||||
fetch(swUrl)
|
||||
.then(response => {
|
||||
// Ensure service worker exists, and that we really are getting a JS file.
|
||||
const contentType = response.headers.get('content-type');
|
||||
if (
|
||||
response.status === 404 ||
|
||||
(contentType != null && contentType.indexOf('javascript') === -1)
|
||||
) {
|
||||
// No service worker found. Probably a different app. Reload the page.
|
||||
navigator.serviceWorker.ready.then(registration => {
|
||||
registration.unregister().then(() => {
|
||||
window.location.reload();
|
||||
});
|
||||
});
|
||||
} else {
|
||||
// Service worker found. Proceed as normal.
|
||||
registerValidSW(swUrl, config);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
console.log(
|
||||
'No internet connection found. App is running in offline mode.'
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function unregister() {
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker.ready.then(registration => {
|
||||
registration.unregister();
|
||||
});
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"presets": ["react-app"],
|
||||
"plugins": ["styled-components"]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
SKIP_PREFLIGHT_CHECK=true
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": ["react-app", "prettier"],
|
||||
"rules": {
|
||||
// "eqeqeq": 0,
|
||||
// "jsx-a11y/anchor-is-valid": 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.js
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
@@ -0,0 +1,29 @@
|
||||
const path = require('path')
|
||||
const resolveFrom = require('resolve-from')
|
||||
|
||||
const fixLinkedDependencies = config => {
|
||||
config.resolve = {
|
||||
...config.resolve,
|
||||
alias: {
|
||||
...config.resolve.alias,
|
||||
react$: resolveFrom(path.resolve('node_modules'), 'react'),
|
||||
'react-dom$': resolveFrom(path.resolve('node_modules'), 'react-dom'),
|
||||
},
|
||||
}
|
||||
return config
|
||||
}
|
||||
|
||||
const includeSrcDirectory = config => {
|
||||
config.resolve = {
|
||||
...config.resolve,
|
||||
modules: [path.resolve('src'), ...config.resolve.modules],
|
||||
}
|
||||
return config
|
||||
}
|
||||
|
||||
module.exports = [
|
||||
['use-babel-config', '.babelrc'],
|
||||
['use-eslint-config', '.eslintrc'],
|
||||
fixLinkedDependencies,
|
||||
// includeSrcDirectory,
|
||||
]
|
||||
@@ -0,0 +1,6 @@
|
||||
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app) and Rescripts.
|
||||
|
||||
You can:
|
||||
|
||||
- [Open this example in a new CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/basic)
|
||||
- `yarn` and `yarn start` to run and edit the example
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"start": "rescripts start",
|
||||
"build": "rescripts build",
|
||||
"test": "rescripts test",
|
||||
"eject": "rescripts eject"
|
||||
},
|
||||
"dependencies": {
|
||||
"namor": "^1.1.2",
|
||||
"react": "^16.8.6",
|
||||
"react-dom": "^16.8.6",
|
||||
"react-scripts": "3.0.1",
|
||||
"react-table": "next",
|
||||
"styled-components": "^4.3.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@rescripts/cli": "^0.0.11",
|
||||
"@rescripts/rescript-use-babel-config": "^0.0.8",
|
||||
"@rescripts/rescript-use-eslint-config": "^0.0.9",
|
||||
"babel-eslint": "10.0.1"
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 3.8 KiB |
@@ -0,0 +1,38 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="theme-color" content="#000000" />
|
||||
<!--
|
||||
manifest.json provides metadata used when your web app is installed on a
|
||||
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
|
||||
-->
|
||||
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
|
||||
<!--
|
||||
Notice the use of %PUBLIC_URL% in the tags above.
|
||||
It will be replaced with the URL of the `public` folder during the build.
|
||||
Only files inside the `public` folder can be referenced from the HTML.
|
||||
|
||||
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
|
||||
work correctly both with client-side routing and a non-root public URL.
|
||||
Learn how to configure a non-root public URL by running `npm run build`.
|
||||
-->
|
||||
<title>React App</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||
<div id="root"></div>
|
||||
<!--
|
||||
This HTML file is a template.
|
||||
If you open it directly in the browser, you will see an empty page.
|
||||
|
||||
You can add webfonts, meta tags, or analytics to this file.
|
||||
The build step will place the bundled scripts into the <body> tag.
|
||||
|
||||
To begin the development, run `npm start` or `yarn start`.
|
||||
To create a production bundle, use `npm run build` or `yarn build`.
|
||||
-->
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"short_name": "React App",
|
||||
"name": "Create React App Sample",
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicon.ico",
|
||||
"sizes": "64x64 32x32 24x24 16x16",
|
||||
"type": "image/x-icon"
|
||||
}
|
||||
],
|
||||
"start_url": ".",
|
||||
"display": "standalone",
|
||||
"theme_color": "#000000",
|
||||
"background_color": "#ffffff"
|
||||
}
|
||||
@@ -0,0 +1,260 @@
|
||||
import React from 'react'
|
||||
import styled from 'styled-components'
|
||||
import { useTable, useGroupBy, useExpanded } from 'react-table'
|
||||
|
||||
import makeData from './makeData'
|
||||
|
||||
const Styles = styled.div`
|
||||
padding: 1rem;
|
||||
|
||||
table {
|
||||
border-spacing: 0;
|
||||
border: 1px solid black;
|
||||
|
||||
tr {
|
||||
:last-child {
|
||||
td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
th,
|
||||
td {
|
||||
margin: 0;
|
||||
padding: 0.5rem;
|
||||
border-bottom: 1px solid black;
|
||||
border-right: 1px solid black;
|
||||
|
||||
:last-child {
|
||||
border-right: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
function Table({ columns, data }) {
|
||||
const {
|
||||
getTableProps,
|
||||
headerGroups,
|
||||
rows,
|
||||
prepareRow,
|
||||
state: [{ groupBy, expanded }],
|
||||
} = useTable(
|
||||
{
|
||||
columns,
|
||||
data,
|
||||
},
|
||||
useGroupBy,
|
||||
useExpanded
|
||||
)
|
||||
|
||||
// We don't want to render all 2000 rows for this example, so cap
|
||||
// it at 20 for this use case
|
||||
const firstPageRows = rows.slice()
|
||||
|
||||
return (
|
||||
<>
|
||||
<pre>
|
||||
<code>{JSON.stringify({ groupBy, expanded }, null, 2)}</code>
|
||||
</pre>
|
||||
<Legend />
|
||||
<table {...getTableProps()}>
|
||||
<thead>
|
||||
{headerGroups.map(headerGroup => (
|
||||
<tr {...headerGroup.getHeaderGroupProps()}>
|
||||
{headerGroup.headers.map(column => (
|
||||
// Add the sorting props to control sorting. For this example
|
||||
// we can add them into the header props
|
||||
<th {...column.getHeaderProps()}>
|
||||
{column.canGroupBy ? (
|
||||
<span {...column.getGroupByToggleProps()}>
|
||||
{column.grouped ? '🛑' : '👊'}
|
||||
</span>
|
||||
) : null}
|
||||
{column.render('Header')}
|
||||
{/* Add a sort direction indicator */}
|
||||
<span>
|
||||
{column.sorted ? (column.sortedDesc ? ' 🔽' : ' 🔼') : ''}
|
||||
</span>
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
<tbody>
|
||||
{firstPageRows.map(
|
||||
(row, i) =>
|
||||
prepareRow(row) || (
|
||||
<tr {...row.getRowProps()}>
|
||||
{row.cells.map(cell => {
|
||||
return (
|
||||
<td
|
||||
{...cell.getCellProps()}
|
||||
style={{
|
||||
background: cell.grouped
|
||||
? '#0aff0082'
|
||||
: cell.aggregated
|
||||
? '#ffa50078'
|
||||
: cell.repeatedValue
|
||||
? '#ff000042'
|
||||
: 'white',
|
||||
}}
|
||||
>
|
||||
{cell.grouped ? (
|
||||
// Add an expander and row count to the grouped cell
|
||||
<>
|
||||
<span
|
||||
style={{
|
||||
cursor: 'pointer',
|
||||
}}
|
||||
onClick={() => row.toggleExpanded()}
|
||||
>
|
||||
{row.isExpanded ? '👇' : '👉'}
|
||||
</span>
|
||||
{cell.render('Cell')} ({row.subRows.length})
|
||||
</>
|
||||
) : cell.aggregated ? (
|
||||
// Use the Aggregated renderer for cells that have
|
||||
// aggregated values
|
||||
cell.render('Aggregated')
|
||||
) : cell.repeatedValue ? null : ( // For cells with repeated values, render null
|
||||
// Otherwise, just render the regular cell
|
||||
cell.render('Cell')
|
||||
)}
|
||||
</td>
|
||||
)
|
||||
})}
|
||||
</tr>
|
||||
)
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
<br />
|
||||
<div>Showing the first 20 results of {rows.length} rows</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function Legend() {
|
||||
return (
|
||||
<div
|
||||
css={`
|
||||
padding: 0.5rem 0;
|
||||
`}
|
||||
>
|
||||
<span
|
||||
css={`
|
||||
display: inline-block;
|
||||
background: #0aff0082;
|
||||
padding: 0.5rem;
|
||||
`}
|
||||
>
|
||||
Grouped
|
||||
</span>{' '}
|
||||
<span
|
||||
css={`
|
||||
display: inline-block;
|
||||
background: #ffa50078;
|
||||
padding: 0.5rem;
|
||||
`}
|
||||
>
|
||||
Aggregated
|
||||
</span>{' '}
|
||||
<span
|
||||
css={`
|
||||
display: inline-block;
|
||||
background: #ff000042;
|
||||
padding: 0.5rem;
|
||||
`}
|
||||
>
|
||||
Repeated Value
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function roundedMedian(values) {
|
||||
let min = values[0] || ''
|
||||
let max = values[0] || ''
|
||||
|
||||
values.forEach(value => {
|
||||
min = Math.min(min, value)
|
||||
max = Math.max(max, value)
|
||||
})
|
||||
|
||||
return Math.round((min + max) / 2)
|
||||
}
|
||||
|
||||
function App() {
|
||||
const columns = React.useMemo(
|
||||
() => [
|
||||
{
|
||||
Header: 'Name',
|
||||
columns: [
|
||||
{
|
||||
Header: 'First Name',
|
||||
accessor: 'firstName',
|
||||
// Use a two-stage aggregator here to first
|
||||
// count the total rows being aggregated,
|
||||
// then sum any of those counts if they are
|
||||
// aggregated further
|
||||
aggregate: ['sum', 'count'],
|
||||
Aggregated: ({ value }) => `${value} Names`,
|
||||
},
|
||||
{
|
||||
Header: 'Last Name',
|
||||
accessor: 'lastName',
|
||||
// Use another two-stage aggregator here to
|
||||
// first count the UNIQUE values from the rows
|
||||
// being aggregated, then sum those counts if
|
||||
// they are aggregated further
|
||||
aggregate: ['sum', 'uniqueCount'],
|
||||
Aggregated: ({ value }) => `${value} Unique Names`,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
Header: 'Info',
|
||||
columns: [
|
||||
{
|
||||
Header: 'Age',
|
||||
accessor: 'age',
|
||||
// Aggregate the average age of visitors
|
||||
aggregate: 'average',
|
||||
Aggregated: ({ value }) => `${value} (avg)`,
|
||||
},
|
||||
{
|
||||
Header: 'Visits',
|
||||
accessor: 'visits',
|
||||
// Aggregate the sum of all visits
|
||||
aggregate: 'sum',
|
||||
Aggregated: ({ value }) => `${value} (total)`,
|
||||
},
|
||||
{
|
||||
Header: 'Status',
|
||||
accessor: 'status',
|
||||
},
|
||||
{
|
||||
Header: 'Profile Progress',
|
||||
accessor: 'progress',
|
||||
// Use our custom roundedMedian aggregator
|
||||
aggregate: roundedMedian,
|
||||
Aggregated: ({ value }) => `${value} (med)`,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
[]
|
||||
)
|
||||
|
||||
const data = React.useMemo(() => makeData(100), [])
|
||||
|
||||
return (
|
||||
<Styles>
|
||||
<Table columns={columns} data={data} />
|
||||
</Styles>
|
||||
)
|
||||
}
|
||||
|
||||
export default App
|
||||
@@ -0,0 +1,9 @@
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom'
|
||||
import App from './App'
|
||||
|
||||
it('renders without crashing', () => {
|
||||
const div = document.createElement('div')
|
||||
ReactDOM.render(<App />, div)
|
||||
ReactDOM.unmountComponentAtNode(div)
|
||||
})
|
||||
@@ -0,0 +1,13 @@
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
|
||||
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
|
||||
sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
|
||||
monospace;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom'
|
||||
import './index.css'
|
||||
import App from './App'
|
||||
import * as serviceWorker from './serviceWorker'
|
||||
|
||||
ReactDOM.render(<App />, document.getElementById('root'))
|
||||
|
||||
// If you want your app to work offline and load faster, you can change
|
||||
// unregister() to register() below. Note this comes with some pitfalls.
|
||||
// Learn more about service workers: https://bit.ly/CRA-PWA
|
||||
serviceWorker.unregister()
|
||||
@@ -0,0 +1,40 @@
|
||||
import namor from 'namor'
|
||||
|
||||
const range = len => {
|
||||
const arr = []
|
||||
for (let i = 0; i < len; i++) {
|
||||
arr.push(i)
|
||||
}
|
||||
return arr
|
||||
}
|
||||
|
||||
const newPerson = () => {
|
||||
const statusChance = Math.random()
|
||||
return {
|
||||
firstName: namor.generate({ words: 1, numbers: 0 }),
|
||||
lastName: namor.generate({ words: 1, numbers: 0 }),
|
||||
age: Math.floor(Math.random() * 30),
|
||||
visits: Math.floor(Math.random() * 100),
|
||||
progress: Math.floor(Math.random() * 100),
|
||||
status:
|
||||
statusChance > 0.66
|
||||
? 'relationship'
|
||||
: statusChance > 0.33
|
||||
? 'complicated'
|
||||
: 'single',
|
||||
}
|
||||
}
|
||||
|
||||
export default function makeData(...lens) {
|
||||
const makeDataLevel = (depth = 0) => {
|
||||
const len = lens[depth]
|
||||
return range(len).map(d => {
|
||||
return {
|
||||
...newPerson(),
|
||||
subRows: lens[depth + 1] ? makeDataLevel(depth + 1) : undefined,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return makeDataLevel()
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
// This optional code is used to register a service worker.
|
||||
// register() is not called by default.
|
||||
|
||||
// This lets the app load faster on subsequent visits in production, and gives
|
||||
// it offline capabilities. However, it also means that developers (and users)
|
||||
// will only see deployed updates on subsequent visits to a page, after all the
|
||||
// existing tabs open on the page have been closed, since previously cached
|
||||
// resources are updated in the background.
|
||||
|
||||
// To learn more about the benefits of this model and instructions on how to
|
||||
// opt-in, read https://bit.ly/CRA-PWA
|
||||
|
||||
const isLocalhost = Boolean(
|
||||
window.location.hostname === 'localhost' ||
|
||||
// [::1] is the IPv6 localhost address.
|
||||
window.location.hostname === '[::1]' ||
|
||||
// 127.0.0.1/8 is considered localhost for IPv4.
|
||||
window.location.hostname.match(
|
||||
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
|
||||
)
|
||||
)
|
||||
|
||||
export function register(config) {
|
||||
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
|
||||
// The URL constructor is available in all browsers that support SW.
|
||||
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href)
|
||||
if (publicUrl.origin !== window.location.origin) {
|
||||
// Our service worker won't work if PUBLIC_URL is on a different origin
|
||||
// from what our page is served on. This might happen if a CDN is used to
|
||||
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
|
||||
return
|
||||
}
|
||||
|
||||
window.addEventListener('load', () => {
|
||||
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`
|
||||
|
||||
if (isLocalhost) {
|
||||
// This is running on localhost. Let's check if a service worker still exists or not.
|
||||
checkValidServiceWorker(swUrl, config)
|
||||
|
||||
// Add some additional logging to localhost, pointing developers to the
|
||||
// service worker/PWA documentation.
|
||||
navigator.serviceWorker.ready.then(() => {
|
||||
console.log(
|
||||
'This web app is being served cache-first by a service ' +
|
||||
'worker. To learn more, visit https://bit.ly/CRA-PWA'
|
||||
)
|
||||
})
|
||||
} else {
|
||||
// Is not localhost. Just register service worker
|
||||
registerValidSW(swUrl, config)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function registerValidSW(swUrl, config) {
|
||||
navigator.serviceWorker
|
||||
.register(swUrl)
|
||||
.then(registration => {
|
||||
registration.onupdatefound = () => {
|
||||
const installingWorker = registration.installing
|
||||
if (installingWorker == null) {
|
||||
return
|
||||
}
|
||||
installingWorker.onstatechange = () => {
|
||||
if (installingWorker.state === 'installed') {
|
||||
if (navigator.serviceWorker.controller) {
|
||||
// At this point, the updated precached content has been fetched,
|
||||
// but the previous service worker will still serve the older
|
||||
// content until all client tabs are closed.
|
||||
console.log(
|
||||
'New content is available and will be used when all ' +
|
||||
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
|
||||
)
|
||||
|
||||
// Execute callback
|
||||
if (config && config.onUpdate) {
|
||||
config.onUpdate(registration)
|
||||
}
|
||||
} else {
|
||||
// At this point, everything has been precached.
|
||||
// It's the perfect time to display a
|
||||
// "Content is cached for offline use." message.
|
||||
console.log('Content is cached for offline use.')
|
||||
|
||||
// Execute callback
|
||||
if (config && config.onSuccess) {
|
||||
config.onSuccess(registration)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error during service worker registration:', error)
|
||||
})
|
||||
}
|
||||
|
||||
function checkValidServiceWorker(swUrl, config) {
|
||||
// Check if the service worker can be found. If it can't reload the page.
|
||||
fetch(swUrl)
|
||||
.then(response => {
|
||||
// Ensure service worker exists, and that we really are getting a JS file.
|
||||
const contentType = response.headers.get('content-type')
|
||||
if (
|
||||
response.status === 404 ||
|
||||
(contentType != null && contentType.indexOf('javascript') === -1)
|
||||
) {
|
||||
// No service worker found. Probably a different app. Reload the page.
|
||||
navigator.serviceWorker.ready.then(registration => {
|
||||
registration.unregister().then(() => {
|
||||
window.location.reload()
|
||||
})
|
||||
})
|
||||
} else {
|
||||
// Service worker found. Proceed as normal.
|
||||
registerValidSW(swUrl, config)
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
console.log(
|
||||
'No internet connection found. App is running in offline mode.'
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
export function unregister() {
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker.ready.then(registration => {
|
||||
registration.unregister()
|
||||
})
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"presets": ["react-app"],
|
||||
"plugins": ["styled-components"]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
SKIP_PREFLIGHT_CHECK=true
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": ["react-app", "prettier"],
|
||||
"rules": {
|
||||
// "eqeqeq": 0,
|
||||
// "jsx-a11y/anchor-is-valid": 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.js
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
@@ -0,0 +1,29 @@
|
||||
const path = require('path')
|
||||
const resolveFrom = require('resolve-from')
|
||||
|
||||
const fixLinkedDependencies = config => {
|
||||
config.resolve = {
|
||||
...config.resolve,
|
||||
alias: {
|
||||
...config.resolve.alias,
|
||||
react$: resolveFrom(path.resolve('node_modules'), 'react'),
|
||||
'react-dom$': resolveFrom(path.resolve('node_modules'), 'react-dom'),
|
||||
},
|
||||
}
|
||||
return config
|
||||
}
|
||||
|
||||
const includeSrcDirectory = config => {
|
||||
config.resolve = {
|
||||
...config.resolve,
|
||||
modules: [path.resolve('src'), ...config.resolve.modules],
|
||||
}
|
||||
return config
|
||||
}
|
||||
|
||||
module.exports = [
|
||||
['use-babel-config', '.babelrc'],
|
||||
['use-eslint-config', '.eslintrc'],
|
||||
fixLinkedDependencies,
|
||||
// includeSrcDirectory,
|
||||
]
|
||||
@@ -0,0 +1,6 @@
|
||||
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app) and Rescripts.
|
||||
|
||||
You can:
|
||||
|
||||
- [Open this example in a new CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/basic)
|
||||
- `yarn` and `yarn start` to run and edit the example
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"start": "rescripts start",
|
||||
"build": "rescripts build",
|
||||
"test": "rescripts test",
|
||||
"eject": "rescripts eject"
|
||||
},
|
||||
"dependencies": {
|
||||
"namor": "^1.1.2",
|
||||
"react": "^16.8.6",
|
||||
"react-dom": "^16.8.6",
|
||||
"react-scripts": "3.0.1",
|
||||
"react-table": "next",
|
||||
"styled-components": "^4.3.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@rescripts/cli": "^0.0.11",
|
||||
"@rescripts/rescript-use-babel-config": "^0.0.8",
|
||||
"@rescripts/rescript-use-eslint-config": "^0.0.9",
|
||||
"babel-eslint": "10.0.1"
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 3.8 KiB |
@@ -0,0 +1,38 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="theme-color" content="#000000" />
|
||||
<!--
|
||||
manifest.json provides metadata used when your web app is installed on a
|
||||
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
|
||||
-->
|
||||
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
|
||||
<!--
|
||||
Notice the use of %PUBLIC_URL% in the tags above.
|
||||
It will be replaced with the URL of the `public` folder during the build.
|
||||
Only files inside the `public` folder can be referenced from the HTML.
|
||||
|
||||
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
|
||||
work correctly both with client-side routing and a non-root public URL.
|
||||
Learn how to configure a non-root public URL by running `npm run build`.
|
||||
-->
|
||||
<title>React App</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||
<div id="root"></div>
|
||||
<!--
|
||||
This HTML file is a template.
|
||||
If you open it directly in the browser, you will see an empty page.
|
||||
|
||||
You can add webfonts, meta tags, or analytics to this file.
|
||||
The build step will place the bundled scripts into the <body> tag.
|
||||
|
||||
To begin the development, run `npm start` or `yarn start`.
|
||||
To create a production bundle, use `npm run build` or `yarn build`.
|
||||
-->
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"short_name": "React App",
|
||||
"name": "Create React App Sample",
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicon.ico",
|
||||
"sizes": "64x64 32x32 24x24 16x16",
|
||||
"type": "image/x-icon"
|
||||
}
|
||||
],
|
||||
"start_url": ".",
|
||||
"display": "standalone",
|
||||
"theme_color": "#000000",
|
||||
"background_color": "#ffffff"
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import React from 'react'
|
||||
import styled from 'styled-components'
|
||||
import { useTable, useSortBy } from 'react-table'
|
||||
|
||||
import makeData from './makeData'
|
||||
|
||||
const Styles = styled.div`
|
||||
padding: 1rem;
|
||||
|
||||
table {
|
||||
border-spacing: 0;
|
||||
border: 1px solid black;
|
||||
|
||||
tr {
|
||||
:last-child {
|
||||
td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
th,
|
||||
td {
|
||||
margin: 0;
|
||||
padding: 0.5rem;
|
||||
border-bottom: 1px solid black;
|
||||
border-right: 1px solid black;
|
||||
|
||||
:last-child {
|
||||
border-right: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
const defaultColumn = {
|
||||
sort: 'numeric',
|
||||
}
|
||||
|
||||
function Table({ columns, data }) {
|
||||
const { getTableProps, headerGroups, rows, prepareRow } = useTable(
|
||||
{
|
||||
columns,
|
||||
data,
|
||||
defaultColumn,
|
||||
debug: true,
|
||||
},
|
||||
useSortBy
|
||||
)
|
||||
|
||||
// We don't want to render all 2000 rows for this example, so cap
|
||||
// it at 20 for this use case
|
||||
const firstPageRows = rows.slice(0, 20)
|
||||
|
||||
return (
|
||||
<>
|
||||
<table {...getTableProps()}>
|
||||
<thead>
|
||||
{headerGroups.map(headerGroup => (
|
||||
<tr {...headerGroup.getHeaderGroupProps()}>
|
||||
{headerGroup.headers.map(
|
||||
column =>
|
||||
console.log(column) || (
|
||||
// Add the sorting props to control sorting. For this example
|
||||
// we can add them into the header props
|
||||
<th
|
||||
{...column.getHeaderProps(column.getSortByToggleProps())}
|
||||
>
|
||||
{column.render('Header')}
|
||||
{/* Add a sort direction indicator */}
|
||||
<span>
|
||||
{column.sorted
|
||||
? column.sortedDesc
|
||||
? ' 🔽'
|
||||
: ' 🔼'
|
||||
: ''}
|
||||
</span>
|
||||
</th>
|
||||
)
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
<tbody>
|
||||
{firstPageRows.map(
|
||||
(row, i) =>
|
||||
prepareRow(row) || (
|
||||
<tr {...row.getRowProps()}>
|
||||
{row.cells.map(cell => {
|
||||
return (
|
||||
<td {...cell.getCellProps()}>{cell.render('Cell')}</td>
|
||||
)
|
||||
})}
|
||||
</tr>
|
||||
)
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
<br />
|
||||
<div>Showing the first 20 results of {rows.length} rows</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function App() {
|
||||
const columns = React.useMemo(
|
||||
() => [
|
||||
{
|
||||
Header: 'Name',
|
||||
columns: [
|
||||
{
|
||||
Header: 'First Name',
|
||||
accessor: 'firstName',
|
||||
},
|
||||
{
|
||||
Header: 'Last Name',
|
||||
accessor: 'lastName',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
Header: 'Info',
|
||||
columns: [
|
||||
{
|
||||
Header: 'Age',
|
||||
accessor: 'age',
|
||||
},
|
||||
{
|
||||
Header: 'Visits',
|
||||
accessor: 'visits',
|
||||
},
|
||||
{
|
||||
Header: 'Status',
|
||||
accessor: 'status',
|
||||
},
|
||||
{
|
||||
Header: 'Profile Progress',
|
||||
accessor: 'progress',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
[]
|
||||
)
|
||||
|
||||
const data = React.useMemo(() => makeData(2000), [])
|
||||
|
||||
return (
|
||||
<Styles>
|
||||
<Table columns={columns} data={data} />
|
||||
</Styles>
|
||||
)
|
||||
}
|
||||
|
||||
export default App
|
||||
@@ -0,0 +1,9 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import App from './App';
|
||||
|
||||
it('renders without crashing', () => {
|
||||
const div = document.createElement('div');
|
||||
ReactDOM.render(<App />, div);
|
||||
ReactDOM.unmountComponentAtNode(div);
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
|
||||
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
|
||||
sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
|
||||
monospace;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import './index.css';
|
||||
import App from './App';
|
||||
import * as serviceWorker from './serviceWorker';
|
||||
|
||||
ReactDOM.render(<App />, document.getElementById('root'));
|
||||
|
||||
// If you want your app to work offline and load faster, you can change
|
||||
// unregister() to register() below. Note this comes with some pitfalls.
|
||||
// Learn more about service workers: https://bit.ly/CRA-PWA
|
||||
serviceWorker.unregister();
|
||||
@@ -0,0 +1,40 @@
|
||||
import namor from 'namor'
|
||||
|
||||
const range = len => {
|
||||
const arr = []
|
||||
for (let i = 0; i < len; i++) {
|
||||
arr.push(i)
|
||||
}
|
||||
return arr
|
||||
}
|
||||
|
||||
const newPerson = () => {
|
||||
const statusChance = Math.random()
|
||||
return {
|
||||
firstName: namor.generate({ words: 1, numbers: 0 }),
|
||||
lastName: namor.generate({ words: 1, numbers: 0 }),
|
||||
age: Math.floor(Math.random() * 30),
|
||||
visits: Math.floor(Math.random() * 100),
|
||||
progress: Math.floor(Math.random() * 100),
|
||||
status:
|
||||
statusChance > 0.66
|
||||
? 'relationship'
|
||||
: statusChance > 0.33
|
||||
? 'complicated'
|
||||
: 'single',
|
||||
}
|
||||
}
|
||||
|
||||
export default function makeData(...lens) {
|
||||
const makeDataLevel = (depth = 0) => {
|
||||
const len = lens[depth]
|
||||
return range(len).map(d => {
|
||||
return {
|
||||
...newPerson(),
|
||||
subRows: lens[depth + 1] ? makeDataLevel(depth + 1) : undefined,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return makeDataLevel()
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
// This optional code is used to register a service worker.
|
||||
// register() is not called by default.
|
||||
|
||||
// This lets the app load faster on subsequent visits in production, and gives
|
||||
// it offline capabilities. However, it also means that developers (and users)
|
||||
// will only see deployed updates on subsequent visits to a page, after all the
|
||||
// existing tabs open on the page have been closed, since previously cached
|
||||
// resources are updated in the background.
|
||||
|
||||
// To learn more about the benefits of this model and instructions on how to
|
||||
// opt-in, read https://bit.ly/CRA-PWA
|
||||
|
||||
const isLocalhost = Boolean(
|
||||
window.location.hostname === 'localhost' ||
|
||||
// [::1] is the IPv6 localhost address.
|
||||
window.location.hostname === '[::1]' ||
|
||||
// 127.0.0.1/8 is considered localhost for IPv4.
|
||||
window.location.hostname.match(
|
||||
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
|
||||
)
|
||||
);
|
||||
|
||||
export function register(config) {
|
||||
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
|
||||
// The URL constructor is available in all browsers that support SW.
|
||||
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
|
||||
if (publicUrl.origin !== window.location.origin) {
|
||||
// Our service worker won't work if PUBLIC_URL is on a different origin
|
||||
// from what our page is served on. This might happen if a CDN is used to
|
||||
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
|
||||
return;
|
||||
}
|
||||
|
||||
window.addEventListener('load', () => {
|
||||
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
|
||||
|
||||
if (isLocalhost) {
|
||||
// This is running on localhost. Let's check if a service worker still exists or not.
|
||||
checkValidServiceWorker(swUrl, config);
|
||||
|
||||
// Add some additional logging to localhost, pointing developers to the
|
||||
// service worker/PWA documentation.
|
||||
navigator.serviceWorker.ready.then(() => {
|
||||
console.log(
|
||||
'This web app is being served cache-first by a service ' +
|
||||
'worker. To learn more, visit https://bit.ly/CRA-PWA'
|
||||
);
|
||||
});
|
||||
} else {
|
||||
// Is not localhost. Just register service worker
|
||||
registerValidSW(swUrl, config);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function registerValidSW(swUrl, config) {
|
||||
navigator.serviceWorker
|
||||
.register(swUrl)
|
||||
.then(registration => {
|
||||
registration.onupdatefound = () => {
|
||||
const installingWorker = registration.installing;
|
||||
if (installingWorker == null) {
|
||||
return;
|
||||
}
|
||||
installingWorker.onstatechange = () => {
|
||||
if (installingWorker.state === 'installed') {
|
||||
if (navigator.serviceWorker.controller) {
|
||||
// At this point, the updated precached content has been fetched,
|
||||
// but the previous service worker will still serve the older
|
||||
// content until all client tabs are closed.
|
||||
console.log(
|
||||
'New content is available and will be used when all ' +
|
||||
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
|
||||
);
|
||||
|
||||
// Execute callback
|
||||
if (config && config.onUpdate) {
|
||||
config.onUpdate(registration);
|
||||
}
|
||||
} else {
|
||||
// At this point, everything has been precached.
|
||||
// It's the perfect time to display a
|
||||
// "Content is cached for offline use." message.
|
||||
console.log('Content is cached for offline use.');
|
||||
|
||||
// Execute callback
|
||||
if (config && config.onSuccess) {
|
||||
config.onSuccess(registration);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error during service worker registration:', error);
|
||||
});
|
||||
}
|
||||
|
||||
function checkValidServiceWorker(swUrl, config) {
|
||||
// Check if the service worker can be found. If it can't reload the page.
|
||||
fetch(swUrl)
|
||||
.then(response => {
|
||||
// Ensure service worker exists, and that we really are getting a JS file.
|
||||
const contentType = response.headers.get('content-type');
|
||||
if (
|
||||
response.status === 404 ||
|
||||
(contentType != null && contentType.indexOf('javascript') === -1)
|
||||
) {
|
||||
// No service worker found. Probably a different app. Reload the page.
|
||||
navigator.serviceWorker.ready.then(registration => {
|
||||
registration.unregister().then(() => {
|
||||
window.location.reload();
|
||||
});
|
||||
});
|
||||
} else {
|
||||
// Service worker found. Proceed as normal.
|
||||
registerValidSW(swUrl, config);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
console.log(
|
||||
'No internet connection found. App is running in offline mode.'
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function unregister() {
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker.ready.then(registration => {
|
||||
registration.unregister();
|
||||
});
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
+4
-4
@@ -1,7 +1,7 @@
|
||||
const path = require('path');
|
||||
const path = require('path')
|
||||
|
||||
const lintProject = require('./configs/tests/jest.lint');
|
||||
const unitProject = require('./configs/tests/jest.unit');
|
||||
const lintProject = require('./configs/tests/jest.lint')
|
||||
const unitProject = require('./configs/tests/jest.unit')
|
||||
|
||||
module.exports = {
|
||||
...require('./configs/tests/jest.common'),
|
||||
@@ -13,4 +13,4 @@ module.exports = {
|
||||
'jest-watch-typeahead/testname',
|
||||
'jest-watch-select-projects',
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
module.exports = {
|
||||
'*.js': ['prettier --write', 'git add'],
|
||||
'*.{md,js,ts,jsx,tsx}': ['prettier --write --no-editorconfig', 'git add'],
|
||||
}
|
||||
|
||||
Generated
+3269
-1780
File diff suppressed because it is too large
Load Diff
+37
-17
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "react-table",
|
||||
"version": "7.0.0-alpha.7",
|
||||
"version": "7.0.0-alpha.13",
|
||||
"description": "A fast, lightweight, opinionated table and datagrid built on React",
|
||||
"license": "MIT",
|
||||
"homepage": "https://github.com/tannerlinsley/react-table#readme",
|
||||
@@ -18,6 +18,7 @@
|
||||
"module": "dist/index.es.js",
|
||||
"jsnext:main": "dist/index.es.js",
|
||||
"scripts": {
|
||||
"commit": "git add . && git-cz",
|
||||
"test": "is-ci 'test:ci' 'test:dev'",
|
||||
"test:dev": "jest --watch",
|
||||
"test:ci": "jest",
|
||||
@@ -25,7 +26,8 @@
|
||||
"start": "rollup -c -w",
|
||||
"prepare": "yarn build",
|
||||
"release": "yarn publish",
|
||||
"releaseNext": "yarn publish --tag next"
|
||||
"releaseNext": "yarn publish --tag next",
|
||||
"format": "prettier ./**{md,js,jsx,tsx} --write"
|
||||
},
|
||||
"files": [
|
||||
"src/",
|
||||
@@ -42,40 +44,58 @@
|
||||
"react-dom": "^16.8.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/plugin-proposal-class-properties": "^7.2.1",
|
||||
"@babel/preset-env": "^7.2.0",
|
||||
"@babel/core": "^7.5.5",
|
||||
"@babel/plugin-proposal-class-properties": "^7.5.5",
|
||||
"@babel/preset-env": "^7.5.5",
|
||||
"@babel/preset-react": "^7.0.0",
|
||||
"@babel/runtime": "^7.2.0",
|
||||
"@svgr/rollup": "^4.1.0",
|
||||
"@testing-library/react": "^8.0.4",
|
||||
"babel-core": "7.0.0-bridge.0",
|
||||
"@babel/runtime": "^7.5.5",
|
||||
"@commitlint/cli": "^8.1.0",
|
||||
"@commitlint/config-conventional": "^8.1.0",
|
||||
"@svgr/rollup": "^4.3.2",
|
||||
"@testing-library/dom": "^5.6.0",
|
||||
"@testing-library/jest-dom": "^4.0.0",
|
||||
"@testing-library/react": "^8.0.7",
|
||||
"babel-eslint": "9.x",
|
||||
"cross-env": "^5.1.4",
|
||||
"commitizen": "^4.0.3",
|
||||
"core-js": "3",
|
||||
"cross-env": "^5.2.0",
|
||||
"eslint": "5.x",
|
||||
"eslint-config-prettier": "^4.3.0",
|
||||
"eslint-config-react-app": "^4.0.1",
|
||||
"eslint-config-standard": "^12.0.0",
|
||||
"eslint-config-standard-react": "^7.0.2",
|
||||
"eslint-plugin-flowtype": "2.x",
|
||||
"eslint-plugin-import": "2.x",
|
||||
"eslint-plugin-jsx-a11y": "6.x",
|
||||
"eslint-plugin-import": "2.18.2",
|
||||
"eslint-plugin-jsx-a11y": "6.2.3",
|
||||
"eslint-plugin-node": "^8.0.0",
|
||||
"eslint-plugin-prettier": "^3.1.0",
|
||||
"eslint-plugin-promise": "^4.0.0",
|
||||
"eslint-plugin-react": "7.x",
|
||||
"eslint-plugin-react-hooks": "1.5.0",
|
||||
"eslint-plugin-promise": "^4.2.1",
|
||||
"eslint-plugin-react": "7.14.3",
|
||||
"eslint-plugin-react-hooks": "1.6.1",
|
||||
"eslint-plugin-standard": "^4.0.0",
|
||||
"husky": "^3.0.2",
|
||||
"is-ci-cli": "^1.1.1",
|
||||
"jest": "^24.8.0",
|
||||
"jest-cli": "^24.8.0",
|
||||
"jest-runner-eslint": "^0.7.4",
|
||||
"jest-watch-select-projects": "^0.1.2",
|
||||
"jest-watch-typeahead": "^0.3.1",
|
||||
"lint-staged": "^9.2.1",
|
||||
"prop-types": "^15.5.0",
|
||||
"react": "^16.8.3",
|
||||
"react-dom": "^16.8.3",
|
||||
"rollup": "^0.68.0",
|
||||
"rollup-plugin-babel": "^4.1.0",
|
||||
"rollup-plugin-babel": "^4.3.3",
|
||||
"rollup-plugin-commonjs": "^9.1.3",
|
||||
"rollup-plugin-node-resolve": "^4.0.0",
|
||||
"rollup-plugin-peer-deps-external": "^2.2.0",
|
||||
"rollup-plugin-uglify": "^6.0.2"
|
||||
}
|
||||
"rollup-plugin-uglify": "^6.0.2",
|
||||
"snapshot-diff": "^0.5.2"
|
||||
},
|
||||
"config": {
|
||||
"commitizen": {
|
||||
"path": "node_modules/cz-conventional-changelog"
|
||||
}
|
||||
},
|
||||
"browserslist": "> 0.25%, not dead"
|
||||
}
|
||||
|
||||
+7
-1
@@ -1,6 +1,12 @@
|
||||
module.exports = {
|
||||
trailingComma: 'es5',
|
||||
printWidth: 80,
|
||||
tabWidth: 2,
|
||||
useTabs: false,
|
||||
semi: false,
|
||||
singleQuote: true,
|
||||
trailingComma: 'es5',
|
||||
bracketSpacing: true,
|
||||
jsxBracketSameLine: false,
|
||||
arrowParens: 'avoid',
|
||||
endOfLine: 'auto',
|
||||
}
|
||||
|
||||
+9
-9
@@ -12,17 +12,17 @@ export default [
|
||||
output: {
|
||||
file: pkg.main,
|
||||
format: 'cjs',
|
||||
sourcemap: true
|
||||
sourcemap: true,
|
||||
},
|
||||
plugins: [
|
||||
external(),
|
||||
babel({
|
||||
exclude: 'node_modules/**'
|
||||
exclude: 'node_modules/**',
|
||||
}),
|
||||
resolve(),
|
||||
commonjs(),
|
||||
uglify()
|
||||
]
|
||||
uglify(),
|
||||
],
|
||||
},
|
||||
{
|
||||
input: 'src/index.js',
|
||||
@@ -30,12 +30,12 @@ export default [
|
||||
output: {
|
||||
file: pkg.module,
|
||||
format: 'es',
|
||||
sourcemap: true
|
||||
sourcemap: true,
|
||||
},
|
||||
plugins: [
|
||||
babel({
|
||||
exclude: ['/**/node_modules/**']
|
||||
})
|
||||
]
|
||||
}
|
||||
exclude: ['/**/node_modules/**'],
|
||||
}),
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
+15
-4
@@ -1,9 +1,20 @@
|
||||
const actions = {}
|
||||
const types = {}
|
||||
|
||||
export { actions }
|
||||
export { actions, types }
|
||||
|
||||
export const addActions = acts => {
|
||||
Object.keys(acts).forEach(key => {
|
||||
actions[key] = acts[key]
|
||||
export const addActions = (...acts) => {
|
||||
acts.forEach(action => {
|
||||
if (actions[action]) {
|
||||
throw new Error(
|
||||
`An React Table action type called ${action} has already been registered!`
|
||||
)
|
||||
}
|
||||
// Action values are formatted this way to discourage
|
||||
// you (the dev) from interacting with them in any way
|
||||
// other than importing `{ actions } from 'react-table'`
|
||||
// and referencing an action via `actions[actionName]`
|
||||
actions[action] = `React Table Action: ${action}`
|
||||
types[actions[action]] = true
|
||||
})
|
||||
}
|
||||
|
||||
@@ -5,3 +5,23 @@ export function sum(values, rows) {
|
||||
export function average(values, rows) {
|
||||
return Math.round((sum(values, rows) / values.length) * 100) / 100
|
||||
}
|
||||
|
||||
export function median(values) {
|
||||
let min = values[0] || ''
|
||||
let max = values[0] || ''
|
||||
|
||||
values.forEach(value => {
|
||||
min = Math.min(min, value)
|
||||
max = Math.max(max, value)
|
||||
})
|
||||
|
||||
return (min + max) / 2
|
||||
}
|
||||
|
||||
export function uniqueCount(values) {
|
||||
return new Set(values).size
|
||||
}
|
||||
|
||||
export function count(values) {
|
||||
return values.length
|
||||
}
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
export const text = (rows, id, filterValue) => {
|
||||
return rows.filter(row => {
|
||||
const rowValue = row.values[id]
|
||||
return rowValue !== undefined
|
||||
? String(rowValue)
|
||||
.toLowerCase()
|
||||
.includes(String(filterValue).toLowerCase())
|
||||
: true
|
||||
})
|
||||
}
|
||||
|
||||
text.autoRemove = val => !val
|
||||
|
||||
export const exactText = (rows, id, filterValue) => {
|
||||
return rows.filter(row => {
|
||||
const rowValue = row.values[id]
|
||||
return rowValue !== undefined
|
||||
? String(rowValue).toLowerCase() === String(filterValue).toLowerCase()
|
||||
: true
|
||||
})
|
||||
}
|
||||
|
||||
exactText.autoRemove = val => !val
|
||||
|
||||
export const exactTextCase = (rows, id, filterValue) => {
|
||||
return rows.filter(row => {
|
||||
const rowValue = row.values[id]
|
||||
return rowValue !== undefined
|
||||
? String(rowValue) === String(filterValue)
|
||||
: true
|
||||
})
|
||||
}
|
||||
|
||||
exactTextCase.autoRemove = val => !val
|
||||
|
||||
export const includes = (rows, id, filterValue) => {
|
||||
return rows.filter(row => {
|
||||
const rowValue = row.values[id]
|
||||
return filterValue.includes(rowValue)
|
||||
})
|
||||
}
|
||||
|
||||
includes.autoRemove = val => !val || !val.length
|
||||
|
||||
export const includesAll = (rows, id, filterValue) => {
|
||||
return rows.filter(row => {
|
||||
const rowValue = row.values[id]
|
||||
return filterValue.every(val => rowValue.includes(val))
|
||||
})
|
||||
}
|
||||
|
||||
includesAll.autoRemove = val => !val || !val.length
|
||||
|
||||
export const exact = (rows, id, filterValue) => {
|
||||
return rows.filter(row => {
|
||||
const rowValue = row.values[id]
|
||||
return rowValue === filterValue
|
||||
})
|
||||
}
|
||||
|
||||
exact.autoRemove = val => typeof val === 'undefined'
|
||||
|
||||
export const equals = (rows, id, filterValue) => {
|
||||
return rows.filter(row => {
|
||||
const rowValue = row.values[id]
|
||||
// eslint-disable-next-line eqeqeq
|
||||
return rowValue == filterValue
|
||||
})
|
||||
}
|
||||
|
||||
equals.autoRemove = val => val == null
|
||||
|
||||
export const between = (rows, id, filterValue) => {
|
||||
let [min, max] = filterValue || []
|
||||
|
||||
min = typeof min === 'number' ? min : -Infinity
|
||||
max = typeof max === 'number' ? max : Infinity
|
||||
|
||||
if (min > max) {
|
||||
const temp = min
|
||||
min = max
|
||||
max = temp
|
||||
}
|
||||
|
||||
return rows.filter(row => {
|
||||
const rowValue = row.values[id]
|
||||
return rowValue >= min && rowValue <= max
|
||||
})
|
||||
}
|
||||
|
||||
between.autoRemove = val =>
|
||||
!val || (typeof val[0] !== 'number' && typeof val[1] !== 'number')
|
||||
@@ -0,0 +1,172 @@
|
||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||
|
||||
exports[`renders a basic table 1`] = `
|
||||
<DocumentFragment>
|
||||
<table
|
||||
class=""
|
||||
>
|
||||
<thead>
|
||||
<tr
|
||||
class=""
|
||||
>
|
||||
<th
|
||||
class=""
|
||||
colspan="2"
|
||||
>
|
||||
Name
|
||||
</th>
|
||||
<th
|
||||
class=""
|
||||
colspan="4"
|
||||
>
|
||||
Info
|
||||
</th>
|
||||
</tr>
|
||||
<tr
|
||||
class=""
|
||||
>
|
||||
<th
|
||||
class=""
|
||||
colspan="1"
|
||||
>
|
||||
First Name
|
||||
</th>
|
||||
<th
|
||||
class=""
|
||||
colspan="1"
|
||||
>
|
||||
Last Name
|
||||
</th>
|
||||
<th
|
||||
class=""
|
||||
colspan="1"
|
||||
>
|
||||
Age
|
||||
</th>
|
||||
<th
|
||||
class=""
|
||||
colspan="1"
|
||||
>
|
||||
Visits
|
||||
</th>
|
||||
<th
|
||||
class=""
|
||||
colspan="1"
|
||||
>
|
||||
Status
|
||||
</th>
|
||||
<th
|
||||
class=""
|
||||
colspan="1"
|
||||
>
|
||||
Profile Progress
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr
|
||||
class=""
|
||||
>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
tanner
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
linsley
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
29
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
100
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
In Relationship
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
50
|
||||
</td>
|
||||
</tr>
|
||||
<tr
|
||||
class=""
|
||||
>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
derek
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
perkins
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
40
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
40
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
Single
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
80
|
||||
</td>
|
||||
</tr>
|
||||
<tr
|
||||
class=""
|
||||
>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
joe
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
bergevin
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
45
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
20
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
Complicated
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
10
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</DocumentFragment>
|
||||
`;
|
||||
@@ -0,0 +1,126 @@
|
||||
import '@testing-library/react/cleanup-after-each'
|
||||
import '@testing-library/jest-dom/extend-expect'
|
||||
// NOTE: jest-dom adds handy assertions to Jest and is recommended, but not required
|
||||
|
||||
import React from 'react'
|
||||
import { render } from '@testing-library/react'
|
||||
import { useTable } from '../useTable'
|
||||
|
||||
const data = [
|
||||
{
|
||||
firstName: 'tanner',
|
||||
lastName: 'linsley',
|
||||
age: 29,
|
||||
visits: 100,
|
||||
status: 'In Relationship',
|
||||
progress: 50,
|
||||
},
|
||||
{
|
||||
firstName: 'derek',
|
||||
lastName: 'perkins',
|
||||
age: 40,
|
||||
visits: 40,
|
||||
status: 'Single',
|
||||
progress: 80,
|
||||
},
|
||||
{
|
||||
firstName: 'joe',
|
||||
lastName: 'bergevin',
|
||||
age: 45,
|
||||
visits: 20,
|
||||
status: 'Complicated',
|
||||
progress: 10,
|
||||
},
|
||||
]
|
||||
|
||||
function Table({ columns, data }) {
|
||||
// Use the state and functions returned from useTable to build your UI
|
||||
const { getTableProps, headerGroups, rows, prepareRow } = useTable({
|
||||
columns,
|
||||
data,
|
||||
})
|
||||
|
||||
// Render the UI for your table
|
||||
return (
|
||||
<table {...getTableProps()}>
|
||||
<thead>
|
||||
{headerGroups.map(headerGroup => (
|
||||
<tr {...headerGroup.getHeaderGroupProps()}>
|
||||
{headerGroup.headers.map(column => (
|
||||
<th {...column.getHeaderProps()}>{column.render('Header')}</th>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map(
|
||||
(row, i) =>
|
||||
prepareRow(row) || (
|
||||
<tr {...row.getRowProps()}>
|
||||
{row.cells.map(cell => {
|
||||
return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
|
||||
})}
|
||||
</tr>
|
||||
)
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
)
|
||||
}
|
||||
|
||||
function App() {
|
||||
const columns = React.useMemo(
|
||||
() => [
|
||||
{
|
||||
Header: 'Name',
|
||||
columns: [
|
||||
{
|
||||
Header: 'First Name',
|
||||
accessor: 'firstName',
|
||||
},
|
||||
{
|
||||
Header: 'Last Name',
|
||||
accessor: 'lastName',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
Header: 'Info',
|
||||
columns: [
|
||||
{
|
||||
Header: 'Age',
|
||||
accessor: 'age',
|
||||
},
|
||||
{
|
||||
Header: 'Visits',
|
||||
accessor: 'visits',
|
||||
},
|
||||
{
|
||||
Header: 'Status',
|
||||
accessor: 'status',
|
||||
},
|
||||
{
|
||||
Header: 'Profile Progress',
|
||||
accessor: 'progress',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
[]
|
||||
)
|
||||
|
||||
return <Table columns={columns} data={data} />
|
||||
}
|
||||
|
||||
test('renders a basic table', () => {
|
||||
const { getByText, asFragment } = render(<App />)
|
||||
|
||||
expect(getByText('tanner')).toBeInTheDocument()
|
||||
expect(getByText('linsley')).toBeInTheDocument()
|
||||
expect(getByText('29')).toBeInTheDocument()
|
||||
expect(getByText('100')).toBeInTheDocument()
|
||||
expect(getByText('In Relationship')).toBeInTheDocument()
|
||||
expect(getByText('50')).toBeInTheDocument()
|
||||
|
||||
expect(asFragment()).toMatchSnapshot()
|
||||
})
|
||||
@@ -1,205 +0,0 @@
|
||||
import { useMemo } from 'react'
|
||||
import PropTypes from 'prop-types'
|
||||
|
||||
import { getBy } from '../utils'
|
||||
|
||||
const propTypes = {
|
||||
// General
|
||||
columns: PropTypes.arrayOf(
|
||||
PropTypes.shape({
|
||||
Cell: PropTypes.any,
|
||||
Header: PropTypes.any,
|
||||
})
|
||||
),
|
||||
}
|
||||
|
||||
// Find the depth of the columns
|
||||
function findMaxDepth(columns, depth = 0) {
|
||||
return columns.reduce((prev, curr) => {
|
||||
if (curr.columns) {
|
||||
return Math.max(prev, findMaxDepth(curr.columns, depth + 1))
|
||||
}
|
||||
return depth
|
||||
}, 0)
|
||||
}
|
||||
|
||||
function decorateColumn(column, parent) {
|
||||
// First check for string accessor
|
||||
let { id, accessor, Header } = column
|
||||
|
||||
if (typeof accessor === 'string') {
|
||||
id = id || accessor
|
||||
const accessorString = accessor
|
||||
accessor = row => getBy(row, accessorString)
|
||||
}
|
||||
|
||||
if (!id && typeof Header === 'string') {
|
||||
id = Header
|
||||
}
|
||||
|
||||
if (!id) {
|
||||
// Accessor, but no column id? This is bad.
|
||||
console.error(column)
|
||||
throw new Error('A column id is required!')
|
||||
}
|
||||
|
||||
column = {
|
||||
Header: '',
|
||||
Cell: cell => cell.value,
|
||||
show: true,
|
||||
...column,
|
||||
id,
|
||||
accessor,
|
||||
parent,
|
||||
}
|
||||
|
||||
return column
|
||||
}
|
||||
|
||||
// Build the visible columns, headers and flat column list
|
||||
function decorateColumnTree(columns, parent, depth = 0) {
|
||||
return columns.map(column => {
|
||||
column = decorateColumn(column, parent)
|
||||
if (column.columns) {
|
||||
column.columns = decorateColumnTree(column.columns, column, depth + 1)
|
||||
}
|
||||
return column
|
||||
})
|
||||
}
|
||||
|
||||
// Build the header groups from the bottom up
|
||||
function makeHeaderGroups(columns, maxDepth) {
|
||||
const headerGroups = []
|
||||
|
||||
const removeChildColumns = column => {
|
||||
delete column.columns
|
||||
if (column.parent) {
|
||||
removeChildColumns(column.parent)
|
||||
}
|
||||
}
|
||||
columns.forEach(removeChildColumns)
|
||||
|
||||
const buildGroup = (columns, depth = 0) => {
|
||||
const headerGroup = {
|
||||
headers: [],
|
||||
}
|
||||
|
||||
const parentColumns = []
|
||||
|
||||
const hasParents = columns.some(col => col.parent)
|
||||
|
||||
columns.forEach(column => {
|
||||
const isFirst = !parentColumns.length
|
||||
let latestParentColumn = [...parentColumns].reverse()[0]
|
||||
|
||||
// If the column has a parent, add it if necessary
|
||||
if (column.parent) {
|
||||
if (isFirst || latestParentColumn.originalID !== column.parent.id) {
|
||||
parentColumns.push({
|
||||
...column.parent,
|
||||
originalID: column.parent.id,
|
||||
id: [column.parent.id, parentColumns.length].join('_'),
|
||||
})
|
||||
}
|
||||
} else if (hasParents) {
|
||||
// If other columns have parents, add a place holder if necessary
|
||||
const placeholderColumn = decorateColumn({
|
||||
originalID: [column.id, 'placeholder', maxDepth - depth].join('_'),
|
||||
id: [
|
||||
column.id,
|
||||
'placeholder',
|
||||
maxDepth - depth,
|
||||
parentColumns.length,
|
||||
].join('_'),
|
||||
})
|
||||
if (
|
||||
isFirst ||
|
||||
latestParentColumn.originalID !== placeholderColumn.originalID
|
||||
) {
|
||||
parentColumns.push(placeholderColumn)
|
||||
}
|
||||
}
|
||||
|
||||
// Establish the new columns[] relationship on the parent
|
||||
if (column.parent || hasParents) {
|
||||
latestParentColumn = [...parentColumns].reverse()[0]
|
||||
latestParentColumn.columns = latestParentColumn.columns || []
|
||||
if (!latestParentColumn.columns.includes(column)) {
|
||||
latestParentColumn.columns.push(column)
|
||||
}
|
||||
}
|
||||
|
||||
headerGroup.headers.push(column)
|
||||
})
|
||||
|
||||
headerGroups.push(headerGroup)
|
||||
|
||||
if (parentColumns.length) {
|
||||
buildGroup(parentColumns)
|
||||
}
|
||||
}
|
||||
|
||||
buildGroup(columns)
|
||||
|
||||
return headerGroups.reverse()
|
||||
}
|
||||
|
||||
export const useColumns = props => {
|
||||
const {
|
||||
debug,
|
||||
columns: userColumns,
|
||||
state: [{ groupBy }],
|
||||
} = props
|
||||
|
||||
PropTypes.checkPropTypes(propTypes, props, 'property', 'useColumns')
|
||||
|
||||
const { columns, headerGroups, headers } = useMemo(() => {
|
||||
if (debug) console.info('getColumns')
|
||||
|
||||
// Decorate All the columns
|
||||
let columnTree = decorateColumnTree(userColumns)
|
||||
|
||||
// Get the flat list of all columns
|
||||
let columns = flattenBy(columnTree, 'columns')
|
||||
|
||||
columns = [
|
||||
...groupBy.map(g => columns.find(col => col.id === g)),
|
||||
...columns.filter(col => !groupBy.includes(col.id)),
|
||||
]
|
||||
|
||||
// Get headerGroups
|
||||
const headerGroups = makeHeaderGroups(columns, findMaxDepth(columnTree))
|
||||
const headers = flattenBy(headerGroups, 'headers')
|
||||
|
||||
return {
|
||||
columns,
|
||||
headerGroups,
|
||||
headers,
|
||||
}
|
||||
}, [debug, groupBy, userColumns])
|
||||
|
||||
return {
|
||||
...props,
|
||||
columns,
|
||||
headerGroups,
|
||||
headers,
|
||||
}
|
||||
|
||||
function flattenBy(columns, childKey) {
|
||||
const flatColumns = []
|
||||
|
||||
const recurse = columns => {
|
||||
columns.forEach(d => {
|
||||
if (!d[childKey]) {
|
||||
flatColumns.push(d)
|
||||
} else {
|
||||
recurse(d[childKey])
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
recurse(columns)
|
||||
|
||||
return flatColumns
|
||||
}
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
import { useMemo } from 'react'
|
||||
import PropTypes from 'prop-types'
|
||||
|
||||
import { getBy, getFirstDefined, setBy } from '../utils'
|
||||
import { addActions, actions } from '../actions'
|
||||
import { defaultState } from './useTableState'
|
||||
|
||||
defaultState.expanded = {}
|
||||
|
||||
addActions({
|
||||
toggleExpanded: '__toggleExpanded__',
|
||||
useExpanded: '__useExpanded__',
|
||||
})
|
||||
|
||||
const propTypes = {
|
||||
expandedKey: PropTypes.string,
|
||||
paginateSubRows: PropTypes.bool,
|
||||
}
|
||||
|
||||
export const useExpanded = props => {
|
||||
PropTypes.checkPropTypes(propTypes, props, 'property', 'useExpanded')
|
||||
|
||||
const {
|
||||
debug,
|
||||
rows,
|
||||
expandedKey = 'expanded',
|
||||
hooks,
|
||||
state: [{ expanded }, setState],
|
||||
paginateSubRows = true,
|
||||
} = props
|
||||
|
||||
const toggleExpandedByPath = (path, set) => {
|
||||
return setState(old => {
|
||||
const { expanded } = old
|
||||
const existing = getBy(expanded, path)
|
||||
set = getFirstDefined(set, !existing)
|
||||
return {
|
||||
...old,
|
||||
expanded: setBy(expanded, path, set),
|
||||
}
|
||||
}, actions.toggleExpanded)
|
||||
}
|
||||
|
||||
hooks.row.push(row => {
|
||||
const { path } = row
|
||||
row.toggleExpanded = set => toggleExpandedByPath(path, set)
|
||||
})
|
||||
|
||||
const expandedRows = useMemo(() => {
|
||||
if (debug) console.info('getExpandedRows')
|
||||
|
||||
const expandedRows = []
|
||||
|
||||
// Here we do some mutation, but it's the last stage in the
|
||||
// immutable process so this is safe
|
||||
const handleRow = (row, index, depth = 0, parentPath = []) => {
|
||||
// Compute some final state for the row
|
||||
const path = [...parentPath, index]
|
||||
|
||||
row.path = path
|
||||
row.depth = depth
|
||||
|
||||
row.isExpanded =
|
||||
(row.original && row.original[expandedKey]) || getBy(expanded, path)
|
||||
|
||||
if (paginateSubRows || (!paginateSubRows && row.depth === 0)) {
|
||||
expandedRows.push(row)
|
||||
}
|
||||
|
||||
if (row.isExpanded && row.subRows && row.subRows.length) {
|
||||
row.subRows.forEach((row, i) => handleRow(row, i, depth + 1, path))
|
||||
}
|
||||
|
||||
return row
|
||||
}
|
||||
|
||||
rows.forEach((row, i) => handleRow(row, i))
|
||||
|
||||
return expandedRows
|
||||
}, [debug, rows, expandedKey, expanded, paginateSubRows])
|
||||
|
||||
const expandedDepth = findExpandedDepth(expanded)
|
||||
|
||||
return {
|
||||
...props,
|
||||
toggleExpandedByPath,
|
||||
expandedDepth,
|
||||
rows: expandedRows,
|
||||
}
|
||||
}
|
||||
|
||||
function findExpandedDepth(obj, depth = 1) {
|
||||
return Object.values(obj).reduce((prev, curr) => {
|
||||
if (typeof curr === 'object') {
|
||||
return Math.max(prev, findExpandedDepth(curr, depth + 1))
|
||||
}
|
||||
return depth
|
||||
}, 0)
|
||||
}
|
||||
@@ -1,161 +0,0 @@
|
||||
import { useMemo } from 'react'
|
||||
import PropTypes from 'prop-types'
|
||||
|
||||
import { defaultFilterFn, getFirstDefined } from '../utils'
|
||||
import { addActions, actions } from '../actions'
|
||||
import { defaultState } from './useTableState'
|
||||
|
||||
defaultState.filters = {}
|
||||
addActions({
|
||||
setFilter: '__setFilter__',
|
||||
setAllFilters: '__setAllFilters__',
|
||||
})
|
||||
|
||||
const propTypes = {
|
||||
// General
|
||||
columns: PropTypes.arrayOf(
|
||||
PropTypes.shape({
|
||||
filterFn: PropTypes.func,
|
||||
filterAll: PropTypes.bool,
|
||||
canFilter: PropTypes.bool,
|
||||
Filter: PropTypes.any,
|
||||
})
|
||||
),
|
||||
|
||||
filterFn: PropTypes.func,
|
||||
manualFilters: PropTypes.bool,
|
||||
}
|
||||
|
||||
export const useFilters = props => {
|
||||
PropTypes.checkPropTypes(propTypes, props, 'property', 'useFilters')
|
||||
|
||||
const {
|
||||
debug,
|
||||
rows,
|
||||
columns,
|
||||
filterFn = defaultFilterFn,
|
||||
manualFilters,
|
||||
disableFilters,
|
||||
hooks,
|
||||
state: [{ filters }, setState],
|
||||
} = props
|
||||
|
||||
columns.forEach(column => {
|
||||
const { id, accessor, canFilter } = column
|
||||
column.canFilter = accessor
|
||||
? getFirstDefined(
|
||||
canFilter,
|
||||
disableFilters === true ? false : undefined,
|
||||
true
|
||||
)
|
||||
: false
|
||||
// Was going to add this to the filter hook
|
||||
column.filterValue = filters[id]
|
||||
})
|
||||
|
||||
const setFilter = (id, val) => {
|
||||
return setState(old => {
|
||||
if (typeof val === 'undefined') {
|
||||
const { [id]: prev, ...rest } = filters
|
||||
return {
|
||||
...old,
|
||||
filters: {
|
||||
...rest,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
...old,
|
||||
filters: {
|
||||
...filters,
|
||||
[id]: val,
|
||||
},
|
||||
}
|
||||
}, actions.setFilter)
|
||||
}
|
||||
|
||||
const setAllFilters = filters => {
|
||||
return setState(old => {
|
||||
return {
|
||||
...old,
|
||||
filters,
|
||||
}
|
||||
}, actions.setAllFilters)
|
||||
}
|
||||
|
||||
hooks.columns.push(columns => {
|
||||
columns.forEach(column => {
|
||||
if (column.canFilter) {
|
||||
column.setFilter = val => setFilter(column.id, val)
|
||||
}
|
||||
})
|
||||
return columns
|
||||
})
|
||||
|
||||
const filteredRows = useMemo(() => {
|
||||
if (manualFilters || !Object.keys(filters).length) {
|
||||
return rows
|
||||
}
|
||||
|
||||
if (debug) console.info('getFilteredRows')
|
||||
|
||||
// Filters top level and nested rows
|
||||
const filterRows = rows => {
|
||||
let filteredRows = rows
|
||||
|
||||
filteredRows = Object.entries(filters).reduce(
|
||||
(filteredSoFar, [columnID, filterValue]) => {
|
||||
// Find the filters column
|
||||
const column = columns.find(d => d.id === columnID)
|
||||
|
||||
// Don't filter hidden columns or columns that have had their filters disabled
|
||||
if (!column || column.filterable === false) {
|
||||
return filteredSoFar
|
||||
}
|
||||
|
||||
const filterMethod = column.filterMethod || filterFn
|
||||
|
||||
// If 'filterAll' is set to true, pass the entire dataset to the filter method
|
||||
if (column.filterAll) {
|
||||
return filterMethod(filteredSoFar, columnID, filterValue, column)
|
||||
}
|
||||
return filteredSoFar.filter(row =>
|
||||
filterMethod(row, columnID, filterValue, column)
|
||||
)
|
||||
},
|
||||
rows
|
||||
)
|
||||
|
||||
// Apply the filter to any subRows
|
||||
filteredRows = filteredRows.map(row => {
|
||||
if (!row.subRows) {
|
||||
return row
|
||||
}
|
||||
return {
|
||||
...row,
|
||||
subRows: filterRows(row.subRows),
|
||||
}
|
||||
})
|
||||
|
||||
// then filter any rows without subcolumns because it would be strange to show
|
||||
filteredRows = filteredRows.filter(row => {
|
||||
if (!row.subRows) {
|
||||
return true
|
||||
}
|
||||
return row.subRows.length > 0
|
||||
})
|
||||
|
||||
return filteredRows
|
||||
}
|
||||
|
||||
return filterRows(rows)
|
||||
}, [manualFilters, filters, debug, rows, columns, filterFn])
|
||||
|
||||
return {
|
||||
...props,
|
||||
setFilter,
|
||||
setAllFilters,
|
||||
rows: filteredRows,
|
||||
}
|
||||
}
|
||||
@@ -1,197 +0,0 @@
|
||||
import { useMemo } from 'react'
|
||||
import PropTypes from 'prop-types'
|
||||
|
||||
import * as aggregations from '../aggregations'
|
||||
import { addActions, actions } from '../actions'
|
||||
import { defaultState } from './useTableState'
|
||||
import {
|
||||
mergeProps,
|
||||
applyPropHooks,
|
||||
defaultGroupByFn,
|
||||
getFirstDefined,
|
||||
} from '../utils'
|
||||
|
||||
defaultState.groupBy = []
|
||||
|
||||
addActions({
|
||||
toggleGroupBy: '__toggleGroupBy__',
|
||||
})
|
||||
|
||||
const propTypes = {
|
||||
// General
|
||||
columns: PropTypes.arrayOf(
|
||||
PropTypes.shape({
|
||||
aggregate: PropTypes.func,
|
||||
canGroupBy: PropTypes.bool,
|
||||
Aggregated: PropTypes.any,
|
||||
})
|
||||
),
|
||||
groupByFn: PropTypes.func,
|
||||
manualGrouping: PropTypes.bool,
|
||||
aggregations: PropTypes.object,
|
||||
}
|
||||
|
||||
export const useGroupBy = props => {
|
||||
PropTypes.checkPropTypes(propTypes, props, 'property', 'useGroupBy')
|
||||
|
||||
const {
|
||||
debug,
|
||||
rows,
|
||||
columns,
|
||||
groupByFn = defaultGroupByFn,
|
||||
manualGroupBy,
|
||||
disableGrouping,
|
||||
aggregations: userAggregations = {},
|
||||
hooks,
|
||||
state: [{ groupBy }, setState],
|
||||
} = props
|
||||
|
||||
columns.forEach(column => {
|
||||
const { id, accessor, canGroupBy } = column
|
||||
column.grouped = groupBy.includes(id)
|
||||
|
||||
column.canGroupBy = accessor
|
||||
? getFirstDefined(
|
||||
canGroupBy,
|
||||
disableGrouping === true ? false : undefined,
|
||||
true
|
||||
)
|
||||
: false
|
||||
|
||||
column.Aggregated = column.Aggregated || column.Cell
|
||||
})
|
||||
|
||||
const toggleGroupBy = (id, toggle) => {
|
||||
return setState(old => {
|
||||
const resolvedToggle =
|
||||
typeof toggle !== 'undefined' ? toggle : !groupBy.includes(id)
|
||||
if (resolvedToggle) {
|
||||
return {
|
||||
...old,
|
||||
groupBy: [...groupBy, id],
|
||||
}
|
||||
}
|
||||
return {
|
||||
...old,
|
||||
groupBy: groupBy.filter(d => d !== id),
|
||||
}
|
||||
}, actions.toggleGroupBy)
|
||||
}
|
||||
|
||||
hooks.columns.push(columns => {
|
||||
columns.forEach(column => {
|
||||
if (column.canGroupBy) {
|
||||
column.toggleGroupBy = () => toggleGroupBy(column.id)
|
||||
}
|
||||
})
|
||||
return columns
|
||||
})
|
||||
|
||||
hooks.getGroupByToggleProps = []
|
||||
|
||||
const addGroupByToggleProps = (columns, api) => {
|
||||
columns.forEach(column => {
|
||||
const { canGroupBy } = column
|
||||
column.getGroupByToggleProps = props => {
|
||||
return mergeProps(
|
||||
{
|
||||
onClick: canGroupBy
|
||||
? e => {
|
||||
e.persist()
|
||||
column.toggleGroupBy()
|
||||
}
|
||||
: undefined,
|
||||
style: {
|
||||
cursor: canGroupBy ? 'pointer' : undefined,
|
||||
},
|
||||
title: 'Toggle GroupBy',
|
||||
},
|
||||
applyPropHooks(api.hooks.getGroupByToggleProps, column, api),
|
||||
props
|
||||
)
|
||||
}
|
||||
})
|
||||
return columns
|
||||
}
|
||||
|
||||
hooks.columns.push(addGroupByToggleProps)
|
||||
hooks.headers.push(addGroupByToggleProps)
|
||||
|
||||
const groupedRows = useMemo(() => {
|
||||
if (manualGroupBy || !groupBy.length) {
|
||||
return rows
|
||||
}
|
||||
if (debug) console.info('getGroupedRows')
|
||||
// Find the columns that can or are aggregating
|
||||
|
||||
// Uses each column to aggregate rows into a single value
|
||||
const aggregateRowsToValues = rows => {
|
||||
const values = {}
|
||||
columns.forEach(column => {
|
||||
const columnValues = rows.map(d => d.values[column.id])
|
||||
let aggregate =
|
||||
userAggregations[column.aggregate] ||
|
||||
aggregations[column.aggregate] ||
|
||||
column.aggregate
|
||||
if (typeof aggregate === 'function') {
|
||||
values[column.id] = aggregate(columnValues, rows)
|
||||
} else if (aggregate) {
|
||||
throw new Error(
|
||||
`Invalid aggregate "${aggregate}" passed to column with ID: "${
|
||||
column.id
|
||||
}"`
|
||||
)
|
||||
} else {
|
||||
values[column.id] = columnValues[0]
|
||||
}
|
||||
})
|
||||
return values
|
||||
}
|
||||
|
||||
// Recursively group the data
|
||||
const groupRecursively = (rows, groupBy, depth = 0) => {
|
||||
// This is the last level, just return the rows
|
||||
if (depth >= groupBy.length) {
|
||||
return rows
|
||||
}
|
||||
|
||||
// Group the rows together for this level
|
||||
let groupedRows = Object.entries(groupByFn(rows, groupBy[depth])).map(
|
||||
([groupByVal, subRows], index) => {
|
||||
// Recurse to sub rows before aggregation
|
||||
subRows = groupRecursively(subRows, groupBy, depth + 1)
|
||||
|
||||
const values = aggregateRowsToValues(subRows)
|
||||
|
||||
const row = {
|
||||
groupByID: groupBy[depth],
|
||||
groupByVal,
|
||||
values,
|
||||
subRows,
|
||||
depth,
|
||||
index,
|
||||
}
|
||||
return row
|
||||
}
|
||||
)
|
||||
|
||||
return groupedRows
|
||||
}
|
||||
|
||||
// Assign the new data
|
||||
return groupRecursively(rows, groupBy)
|
||||
}, [
|
||||
manualGroupBy,
|
||||
groupBy,
|
||||
debug,
|
||||
rows,
|
||||
columns,
|
||||
userAggregations,
|
||||
groupByFn,
|
||||
])
|
||||
|
||||
return {
|
||||
...props,
|
||||
rows: groupedRows,
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
import { useMemo } from 'react'
|
||||
import PropTypes from 'prop-types'
|
||||
|
||||
const propTypes = {
|
||||
subRowsKey: PropTypes.string,
|
||||
}
|
||||
|
||||
export const useRows = props => {
|
||||
PropTypes.checkPropTypes(propTypes, props, 'property', 'useRows')
|
||||
|
||||
const { debug, columns, subRowsKey = 'subRows', data } = props
|
||||
|
||||
const accessedRows = useMemo(() => {
|
||||
if (debug) console.info('getAccessedRows')
|
||||
|
||||
// Access the row's data
|
||||
const accessRow = (originalRow, i, depth = 0) => {
|
||||
// Keep the original reference around
|
||||
const original = originalRow
|
||||
|
||||
// Process any subRows
|
||||
const subRows = originalRow[subRowsKey]
|
||||
? originalRow[subRowsKey].map((d, i) => accessRow(d, i, depth + 1))
|
||||
: undefined
|
||||
|
||||
const row = {
|
||||
original,
|
||||
index: i,
|
||||
path: [i], // used to create a key for each row even if not nested
|
||||
subRows,
|
||||
depth,
|
||||
cells: [{}], // This is a dummy cell
|
||||
}
|
||||
|
||||
// Override common array functions (and the dummy cell's getCellProps function)
|
||||
// to show an error if it is accessed without calling prepareRow
|
||||
const unpreparedAccessWarning = () => {
|
||||
throw new Error(
|
||||
'React-Table: You have not called prepareRow(row) one or more rows you are attempting to render.'
|
||||
)
|
||||
}
|
||||
row.cells.map = unpreparedAccessWarning
|
||||
row.cells.filter = unpreparedAccessWarning
|
||||
row.cells.forEach = unpreparedAccessWarning
|
||||
row.cells[0].getCellProps = unpreparedAccessWarning
|
||||
|
||||
// Create the cells and values
|
||||
row.values = {}
|
||||
columns.forEach(column => {
|
||||
row.values[column.id] = column.accessor
|
||||
? column.accessor(originalRow, i, { subRows, depth, data })
|
||||
: undefined
|
||||
})
|
||||
|
||||
return row
|
||||
}
|
||||
|
||||
// Use the resolved data
|
||||
return data.map((d, i) => accessRow(d, i))
|
||||
}, [debug, data, subRowsKey, columns])
|
||||
|
||||
return {
|
||||
...props,
|
||||
rows: accessedRows,
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
export const useSimpleLayout = props => {
|
||||
const {
|
||||
hooks: { columns: columnsHooks, getHeaderProps, getCellProps },
|
||||
} = props
|
||||
|
||||
columnsHooks.push(columns => {
|
||||
getHeaderProps.push(column => ({
|
||||
style: {
|
||||
boxSizing: 'border-box',
|
||||
width: column.width !== undefined ? `${column.width}px` : 'auto',
|
||||
},
|
||||
}))
|
||||
|
||||
getCellProps.push(cell => {
|
||||
return {
|
||||
style: {
|
||||
boxSizing: 'border-box',
|
||||
width:
|
||||
cell.column.width !== undefined ? `${cell.column.width}px` : 'auto',
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
return columns
|
||||
})
|
||||
|
||||
return props
|
||||
}
|
||||
@@ -1,261 +0,0 @@
|
||||
import { useMemo } from 'react'
|
||||
import PropTypes from 'prop-types'
|
||||
|
||||
import { addActions, actions } from '../actions'
|
||||
import { defaultState } from './useTableState'
|
||||
import {
|
||||
mergeProps,
|
||||
applyPropHooks,
|
||||
getFirstDefined,
|
||||
defaultOrderByFn,
|
||||
defaultSortByFn,
|
||||
} from '../utils'
|
||||
|
||||
defaultState.sortBy = []
|
||||
|
||||
addActions({
|
||||
sortByChange: '__sortByChange__',
|
||||
})
|
||||
|
||||
const propTypes = {
|
||||
// General
|
||||
columns: PropTypes.arrayOf(
|
||||
PropTypes.shape({
|
||||
sortByFn: PropTypes.func,
|
||||
defaultSortDesc: PropTypes.bool,
|
||||
})
|
||||
),
|
||||
sortByFn: PropTypes.func,
|
||||
manualSorting: PropTypes.bool,
|
||||
disableSorting: PropTypes.bool,
|
||||
defaultSortDesc: PropTypes.bool,
|
||||
disableMultiSort: PropTypes.bool,
|
||||
disableSortRemove: PropTypes.bool,
|
||||
}
|
||||
|
||||
export const useSortBy = props => {
|
||||
PropTypes.checkPropTypes(propTypes, props, 'property', 'useSortBy')
|
||||
|
||||
const {
|
||||
debug,
|
||||
rows,
|
||||
columns,
|
||||
orderByFn = defaultOrderByFn,
|
||||
sortByFn = defaultSortByFn,
|
||||
manualSorting,
|
||||
disableSorting,
|
||||
defaultSortDesc,
|
||||
disableSortRemove,
|
||||
hooks,
|
||||
state: [{ sortBy }, setState],
|
||||
} = props
|
||||
|
||||
columns.forEach(column => {
|
||||
const { accessor, canSortBy } = column
|
||||
column.canSortBy = accessor
|
||||
? getFirstDefined(
|
||||
canSortBy,
|
||||
disableSorting === true ? false : undefined,
|
||||
true
|
||||
)
|
||||
: false
|
||||
})
|
||||
|
||||
// Updates sorting based on a columnID, desc flag and multi flag
|
||||
const toggleSortByID = (columnID, desc, multi) => {
|
||||
return setState(old => {
|
||||
const { sortBy } = old
|
||||
|
||||
// Find the column for this columnID
|
||||
const column = columns.find(d => d.id === columnID)
|
||||
const resolvedDefaultSortDesc = getFirstDefined(
|
||||
column.defaultSortDesc,
|
||||
defaultSortDesc
|
||||
)
|
||||
|
||||
// Find any existing sortBy for this column
|
||||
const existingSortBy = sortBy.find(d => d.id === columnID)
|
||||
const hasDescDefined = typeof desc !== 'undefined' && desc !== null
|
||||
|
||||
let newSortBy = []
|
||||
|
||||
// What should we do with this filter?
|
||||
let action
|
||||
|
||||
if (!multi) {
|
||||
if (sortBy.length <= 1 && existingSortBy) {
|
||||
if (
|
||||
(existingSortBy.desc && !resolvedDefaultSortDesc) ||
|
||||
(!existingSortBy.desc && resolvedDefaultSortDesc)
|
||||
) {
|
||||
action = disableSortRemove ? 'toggle' : 'remove'
|
||||
} else {
|
||||
action = 'toggle'
|
||||
}
|
||||
} else {
|
||||
action = 'replace'
|
||||
}
|
||||
} else {
|
||||
if (!existingSortBy) {
|
||||
action = 'add'
|
||||
} else {
|
||||
if (hasDescDefined) {
|
||||
action = 'set'
|
||||
} else {
|
||||
action = 'toggle'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (action === 'replace') {
|
||||
newSortBy = [
|
||||
{
|
||||
id: columnID,
|
||||
desc: hasDescDefined ? desc : resolvedDefaultSortDesc,
|
||||
},
|
||||
]
|
||||
} else if (action === 'add') {
|
||||
newSortBy = [
|
||||
...sortBy,
|
||||
{
|
||||
id: columnID,
|
||||
desc: hasDescDefined ? desc : resolvedDefaultSortDesc,
|
||||
},
|
||||
]
|
||||
} else if (action === 'set') {
|
||||
newSortBy = sortBy.map(d => {
|
||||
if (d.id === columnID) {
|
||||
return {
|
||||
...d,
|
||||
desc,
|
||||
}
|
||||
}
|
||||
return d
|
||||
})
|
||||
} else if (action === 'toggle') {
|
||||
newSortBy = sortBy.map(d => {
|
||||
if (d.id === columnID) {
|
||||
return {
|
||||
...d,
|
||||
desc: !existingSortBy.desc,
|
||||
}
|
||||
}
|
||||
return d
|
||||
})
|
||||
} else if (action === 'remove') {
|
||||
newSortBy = []
|
||||
}
|
||||
|
||||
return {
|
||||
...old,
|
||||
sortBy: newSortBy,
|
||||
}
|
||||
}, actions.sortByChange)
|
||||
}
|
||||
|
||||
hooks.columns.push(columns => {
|
||||
columns.forEach(column => {
|
||||
if (column.canSortBy) {
|
||||
column.toggleSortBy = (desc, multi) =>
|
||||
toggleSortByID(column.id, desc, multi)
|
||||
}
|
||||
})
|
||||
return columns
|
||||
})
|
||||
|
||||
hooks.getSortByToggleProps = []
|
||||
|
||||
const addSortByToggleProps = (columns, api) => {
|
||||
columns.forEach(column => {
|
||||
const { canSortBy } = column
|
||||
column.getSortByToggleProps = props => {
|
||||
return mergeProps(
|
||||
{
|
||||
onClick: canSortBy
|
||||
? e => {
|
||||
e.persist()
|
||||
column.toggleSortBy(
|
||||
undefined,
|
||||
!api.disableMultiSort && e.shiftKey
|
||||
)
|
||||
}
|
||||
: undefined,
|
||||
style: {
|
||||
cursor: canSortBy ? 'pointer' : undefined,
|
||||
},
|
||||
title: 'Toggle SortBy',
|
||||
},
|
||||
applyPropHooks(api.hooks.getSortByToggleProps, column, api),
|
||||
props
|
||||
)
|
||||
}
|
||||
})
|
||||
return columns
|
||||
}
|
||||
|
||||
hooks.columns.push(addSortByToggleProps)
|
||||
hooks.headers.push(addSortByToggleProps)
|
||||
|
||||
// Mutate columns to reflect sorting state
|
||||
columns.forEach(column => {
|
||||
const { id } = column
|
||||
column.sorted = sortBy.find(d => d.id === id)
|
||||
column.sortedIndex = sortBy.findIndex(d => d.id === id)
|
||||
column.sortedDesc = column.sorted ? column.sorted.desc : undefined
|
||||
})
|
||||
|
||||
const sortedRows = useMemo(() => {
|
||||
if (manualSorting || !sortBy.length) {
|
||||
return rows
|
||||
}
|
||||
if (debug) console.info('getSortedRows')
|
||||
|
||||
const sortMethodsByColumnID = {}
|
||||
|
||||
columns
|
||||
.filter(col => col.sortMethod)
|
||||
.forEach(col => {
|
||||
sortMethodsByColumnID[col.id] = col.sortMethod
|
||||
})
|
||||
|
||||
const sortData = rows => {
|
||||
// Use the orderByFn to compose multiple sortBy's together.
|
||||
// This will also perform a stable sorting using the row index
|
||||
// if needed.
|
||||
const sortedData = orderByFn(
|
||||
rows,
|
||||
sortBy.map(sort => {
|
||||
// Support custom sorting methods for each column
|
||||
const columnSortBy = sortMethodsByColumnID[sort.id]
|
||||
|
||||
// Return the correct sortFn
|
||||
return (a, b) =>
|
||||
(columnSortBy || sortByFn)(
|
||||
a.values[sort.id],
|
||||
b.values[sort.id],
|
||||
sort.desc
|
||||
)
|
||||
}),
|
||||
// Map the directions
|
||||
sortBy.map(d => !d.desc)
|
||||
)
|
||||
|
||||
// TODO: this should be optimized. Not good to loop again
|
||||
sortedData.forEach(row => {
|
||||
if (!row.subRows) {
|
||||
return
|
||||
}
|
||||
row.subRows = sortData(row.subRows)
|
||||
})
|
||||
|
||||
return sortedData
|
||||
}
|
||||
|
||||
return sortData(rows)
|
||||
}, [manualSorting, sortBy, debug, columns, rows, orderByFn, sortByFn])
|
||||
|
||||
return {
|
||||
...props,
|
||||
rows: sortedRows,
|
||||
}
|
||||
}
|
||||
+270
-97
@@ -1,24 +1,49 @@
|
||||
import React from 'react'
|
||||
import PropTypes from 'prop-types'
|
||||
//
|
||||
import { flexRender, applyHooks, applyPropHooks, mergeProps } from '../utils'
|
||||
import {
|
||||
applyHooks,
|
||||
applyPropHooks,
|
||||
mergeProps,
|
||||
flexRender,
|
||||
decorateColumnTree,
|
||||
makeHeaderGroups,
|
||||
findMaxDepth,
|
||||
flattenBy,
|
||||
} from '../utils'
|
||||
|
||||
import { useTableState } from './useTableState'
|
||||
|
||||
const renderErr =
|
||||
'You must specify a render "type". This could be "Header", "Filter", or any other custom renderers you have set on your column.'
|
||||
|
||||
const propTypes = {
|
||||
// General
|
||||
data: PropTypes.array.isRequired,
|
||||
columns: PropTypes.arrayOf(
|
||||
PropTypes.shape({
|
||||
Cell: PropTypes.any,
|
||||
Header: PropTypes.any,
|
||||
})
|
||||
).isRequired,
|
||||
defaultColumn: PropTypes.object,
|
||||
subRowsKey: PropTypes.string,
|
||||
debug: PropTypes.bool,
|
||||
}
|
||||
|
||||
const renderErr =
|
||||
'You must specify a valid render component. This could be "column.Cell", "column.Header", "column.Filter", "column.Aggregated" or any other custom renderer component.'
|
||||
|
||||
export const useTable = (props, ...plugins) => {
|
||||
// Validate props
|
||||
PropTypes.checkPropTypes(propTypes, props, 'property', 'useTable')
|
||||
|
||||
// Destructure props
|
||||
let { data = [], state: userState, debug } = props
|
||||
let {
|
||||
data,
|
||||
state: userState,
|
||||
columns: userColumns,
|
||||
defaultColumn = {},
|
||||
subRowsKey = 'subRows',
|
||||
debug,
|
||||
} = props
|
||||
|
||||
debug = process.env.NODE_ENV === 'production' ? false : debug
|
||||
|
||||
@@ -28,83 +53,207 @@ export const useTable = (props, ...plugins) => {
|
||||
// But use the users state if provided
|
||||
const state = userState || defaultState
|
||||
|
||||
// These are hooks that plugins can use right before render
|
||||
const hooks = {
|
||||
beforeRender: [],
|
||||
columns: [],
|
||||
headers: [],
|
||||
headerGroups: [],
|
||||
rows: [],
|
||||
row: [],
|
||||
renderableRows: [],
|
||||
getTableProps: [],
|
||||
getRowProps: [],
|
||||
getHeaderRowProps: [],
|
||||
getHeaderProps: [],
|
||||
getCellProps: [],
|
||||
}
|
||||
|
||||
// The initial api
|
||||
let api = {
|
||||
let instanceRef = React.useRef({})
|
||||
|
||||
Object.assign(instanceRef.current, {
|
||||
...props,
|
||||
data,
|
||||
state,
|
||||
hooks,
|
||||
}
|
||||
|
||||
if (debug) console.time('hooks')
|
||||
// Loop through plugins to build the api out
|
||||
api = plugins.filter(Boolean).reduce((prev, next) => next(prev), api)
|
||||
if (debug) console.timeEnd('hooks')
|
||||
|
||||
// Run the beforeRender hook
|
||||
if (debug) console.time('hooks.beforeRender')
|
||||
applyHooks(api.hooks.beforeRender, undefined, api)
|
||||
if (debug) console.timeEnd('hooks.beforeRender')
|
||||
|
||||
api.columns.forEach(column => {
|
||||
column.visible =
|
||||
typeof column.show === 'function' ? column.show(api) : !!column.show
|
||||
plugins,
|
||||
hooks: {
|
||||
columnsBeforeHeaderGroups: [],
|
||||
useMain: [],
|
||||
useColumns: [],
|
||||
useHeaders: [],
|
||||
useHeaderGroups: [],
|
||||
useRows: [],
|
||||
prepareRow: [],
|
||||
getTableProps: [],
|
||||
getRowProps: [],
|
||||
getHeaderGroupProps: [],
|
||||
getHeaderProps: [],
|
||||
getCellProps: [],
|
||||
},
|
||||
})
|
||||
|
||||
if (debug) console.time('hooks.columns')
|
||||
api.columns = applyHooks(api.hooks.columns, api.columns, api)
|
||||
if (debug) console.timeEnd('hooks.columns')
|
||||
// Allow plugins to register hooks
|
||||
if (debug) console.time('plugins')
|
||||
plugins.filter(Boolean).forEach(plugin => {
|
||||
plugin(instanceRef.current.hooks)
|
||||
})
|
||||
if (debug) console.timeEnd('plugins')
|
||||
|
||||
if (debug) console.time('hooks.headers')
|
||||
api.headers = applyHooks(api.hooks.headers, api.headers, api)
|
||||
if (debug) console.timeEnd('hooks.headers')
|
||||
;[...api.columns, ...api.headers].forEach(column => {
|
||||
// Give columns/headers rendering power
|
||||
column.render = (type, userProps = {}) => {
|
||||
if (!type) {
|
||||
throw new Error(renderErr)
|
||||
}
|
||||
return flexRender(column[type], {
|
||||
...api,
|
||||
...column,
|
||||
...userProps,
|
||||
})
|
||||
}
|
||||
// Compute columns, headerGroups and headers
|
||||
const columnInfo = React.useMemo(
|
||||
() => {
|
||||
if (debug) console.info('buildColumns/headerGroup/headers')
|
||||
// Decorate All the columns
|
||||
let columnTree = decorateColumnTree(userColumns, defaultColumn)
|
||||
|
||||
// Give columns/headers getHeaderProps
|
||||
column.getHeaderProps = props =>
|
||||
mergeProps(
|
||||
{
|
||||
key: ['header', column.id].join('_'),
|
||||
colSpan: column.columns ? column.columns.length : 1,
|
||||
},
|
||||
applyPropHooks(api.hooks.getHeaderProps, column, api),
|
||||
props
|
||||
// Get the flat list of all columns
|
||||
let columns = flattenBy(columnTree, 'columns')
|
||||
|
||||
// Allow hooks to decorate columns
|
||||
if (debug) console.time('hooks.columnsBeforeHeaderGroups')
|
||||
columns = applyHooks(
|
||||
instanceRef.current.hooks.columnsBeforeHeaderGroups,
|
||||
columns,
|
||||
instanceRef.current
|
||||
)
|
||||
if (debug) console.timeEnd('hooks.columnsBeforeHeaderGroups')
|
||||
|
||||
// Make the headerGroups
|
||||
const headerGroups = makeHeaderGroups(
|
||||
columns,
|
||||
findMaxDepth(columnTree),
|
||||
defaultColumn
|
||||
)
|
||||
|
||||
const headers = flattenBy(headerGroups, 'headers')
|
||||
|
||||
return {
|
||||
columns,
|
||||
headerGroups,
|
||||
headers,
|
||||
}
|
||||
},
|
||||
[debug, defaultColumn, userColumns]
|
||||
)
|
||||
|
||||
// Place the columns, headerGroups and headers on the api
|
||||
Object.assign(instanceRef.current, columnInfo)
|
||||
|
||||
// Access the row model
|
||||
instanceRef.current.rows = React.useMemo(
|
||||
() => {
|
||||
if (debug) console.time('getAccessedRows')
|
||||
// Access the row's data
|
||||
const accessRow = (originalRow, i, depth = 0) => {
|
||||
// Keep the original reference around
|
||||
const original = originalRow
|
||||
|
||||
// Process any subRows
|
||||
const subRows = originalRow[subRowsKey]
|
||||
? originalRow[subRowsKey].map((d, i) => accessRow(d, i, depth + 1))
|
||||
: []
|
||||
|
||||
const row = {
|
||||
original,
|
||||
index: i,
|
||||
path: [i], // used to create a key for each row even if not nested
|
||||
subRows,
|
||||
depth,
|
||||
cells: [{}], // This is a dummy cell
|
||||
}
|
||||
|
||||
// Override common array functions (and the dummy cell's getCellProps function)
|
||||
// to show an error if it is accessed without calling prepareRow
|
||||
const unpreparedAccessWarning = () => {
|
||||
throw new Error(
|
||||
'React-Table: You have not called prepareRow(row) one or more rows you are attempting to render.'
|
||||
)
|
||||
}
|
||||
row.cells.map = unpreparedAccessWarning
|
||||
row.cells.filter = unpreparedAccessWarning
|
||||
row.cells.forEach = unpreparedAccessWarning
|
||||
row.cells[0].getCellProps = unpreparedAccessWarning
|
||||
|
||||
// Create the cells and values
|
||||
row.values = {}
|
||||
instanceRef.current.columns.forEach(column => {
|
||||
row.values[column.id] = column.accessor
|
||||
? column.accessor(originalRow, i, { subRows, depth, data })
|
||||
: undefined
|
||||
})
|
||||
|
||||
return row
|
||||
}
|
||||
|
||||
// Use the resolved data
|
||||
const accessedData = data.map((d, i) => accessRow(d, i))
|
||||
if (debug) console.timeEnd('getAccessedRows')
|
||||
return accessedData
|
||||
},
|
||||
[debug, data, subRowsKey]
|
||||
)
|
||||
|
||||
// Determine column visibility
|
||||
instanceRef.current.columns.forEach(column => {
|
||||
column.visible =
|
||||
typeof column.show === 'function'
|
||||
? column.show(instanceRef.current)
|
||||
: !!column.show
|
||||
})
|
||||
|
||||
if (debug) console.time('hooks.headerGroups')
|
||||
api.headerGroups = applyHooks(
|
||||
api.hooks.headerGroups,
|
||||
api.headerGroups,
|
||||
api
|
||||
).filter((headerGroup, i) => {
|
||||
if (debug) console.time('hooks.useMain')
|
||||
instanceRef.current = applyHooks(
|
||||
instanceRef.current.hooks.useMain,
|
||||
instanceRef.current
|
||||
)
|
||||
if (debug)
|
||||
console.timeEnd('hooks.useMain')
|
||||
|
||||
// // Allow hooks to decorate columns
|
||||
// if (debug) console.time('hooks.useColumns')
|
||||
// instanceRef.current.columns = applyHooks(
|
||||
// instanceRef.current.hooks.useColumns,
|
||||
// instanceRef.current.columns,
|
||||
// instanceRef.current
|
||||
// )
|
||||
// if (debug) console.timeEnd('hooks.useColumns')
|
||||
|
||||
// // Allow hooks to decorate headers
|
||||
// if (debug) console.time('hooks.useHeaders')
|
||||
// instanceRef.current.headers = applyHooks(
|
||||
// instanceRef.current.hooks.useHeaders,
|
||||
// instanceRef.current.headers,
|
||||
// instanceRef.current
|
||||
// )
|
||||
// if (debug) console.timeEnd('hooks.useHeaders')
|
||||
;[...instanceRef.current.columns, ...instanceRef.current.headers].forEach(
|
||||
column => {
|
||||
// Give columns/headers rendering power
|
||||
column.render = (type, userProps = {}) => {
|
||||
const Comp = typeof type === 'string' ? column[type] : type
|
||||
|
||||
if (typeof Comp === 'undefined') {
|
||||
throw new Error(renderErr)
|
||||
}
|
||||
|
||||
return flexRender(Comp, {
|
||||
...instanceRef.current,
|
||||
...column,
|
||||
...userProps,
|
||||
})
|
||||
}
|
||||
|
||||
// Give columns/headers a default getHeaderProps
|
||||
column.getHeaderProps = props =>
|
||||
mergeProps(
|
||||
{
|
||||
key: ['header', column.id].join('_'),
|
||||
colSpan: column.columns ? column.columns.length : 1,
|
||||
},
|
||||
applyPropHooks(
|
||||
instanceRef.current.hooks.getHeaderProps,
|
||||
column,
|
||||
instanceRef.current
|
||||
),
|
||||
props
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
// // Allow hooks to decorate headerGroups
|
||||
// if (debug) console.time('hooks.useHeaderGroups')
|
||||
// instanceRef.current.headerGroups = applyHooks(
|
||||
// instanceRef.current.hooks.useHeaderGroups,
|
||||
// instanceRef.current.headerGroups,
|
||||
// instanceRef.current
|
||||
// )
|
||||
|
||||
instanceRef.current.headerGroups.filter((headerGroup, i) => {
|
||||
// Filter out any headers and headerGroups that don't have visible columns
|
||||
headerGroup.headers = headerGroup.headers.filter(header => {
|
||||
const recurse = columns =>
|
||||
@@ -122,12 +271,16 @@ export const useTable = (props, ...plugins) => {
|
||||
|
||||
// Give headerGroups getRowProps
|
||||
if (headerGroup.headers.length) {
|
||||
headerGroup.getRowProps = (props = {}) =>
|
||||
headerGroup.getHeaderGroupProps = (props = {}) =>
|
||||
mergeProps(
|
||||
{
|
||||
key: [`header${i}`].join('_'),
|
||||
},
|
||||
applyPropHooks(api.hooks.getHeaderRowProps, headerGroup, api),
|
||||
applyPropHooks(
|
||||
instanceRef.current.hooks.getHeaderGroupProps,
|
||||
headerGroup,
|
||||
instanceRef.current
|
||||
),
|
||||
props
|
||||
)
|
||||
return true
|
||||
@@ -135,29 +288,36 @@ export const useTable = (props, ...plugins) => {
|
||||
|
||||
return false
|
||||
})
|
||||
if (debug) console.timeEnd('hooks.headerGroups')
|
||||
// if (debug) console.timeEnd('hooks.useHeaderGroups')
|
||||
|
||||
// Run the rows (this could be a dangerous hook with a ton of data)
|
||||
if (debug) console.time('hooks.rows')
|
||||
api.rows = applyHooks(api.hooks.rows, api.rows, api)
|
||||
if (debug) console.timeEnd('hooks.rows')
|
||||
if (debug) console.time('hooks.useRows')
|
||||
instanceRef.current.rows = applyHooks(
|
||||
instanceRef.current.hooks.useRows,
|
||||
instanceRef.current.rows,
|
||||
instanceRef.current
|
||||
)
|
||||
if (debug) console.timeEnd('hooks.useRows')
|
||||
|
||||
// The prepareRow function is absolutely necessary and MUST be called on
|
||||
// any rows the user wishes to be displayed.
|
||||
|
||||
api.prepareRow = row => {
|
||||
instanceRef.current.prepareRow = row => {
|
||||
const { path } = row
|
||||
row.getRowProps = props =>
|
||||
mergeProps(
|
||||
{ key: ['row', ...path].join('_') },
|
||||
applyPropHooks(api.hooks.getRowProps, row, api),
|
||||
applyPropHooks(
|
||||
instanceRef.current.hooks.getRowProps,
|
||||
row,
|
||||
instanceRef.current
|
||||
),
|
||||
props
|
||||
)
|
||||
|
||||
// need to apply any row specific hooks (useExpanded requires this)
|
||||
applyHooks(api.hooks.row, row, api)
|
||||
|
||||
const visibleColumns = api.columns.filter(column => column.visible)
|
||||
const visibleColumns = instanceRef.current.columns.filter(
|
||||
column => column.visible
|
||||
)
|
||||
|
||||
// Build the cells for each row
|
||||
row.cells = visibleColumns.map(column => {
|
||||
@@ -167,25 +327,32 @@ export const useTable = (props, ...plugins) => {
|
||||
value: row.values[column.id],
|
||||
}
|
||||
|
||||
// Give each cell a getCellProps base
|
||||
cell.getCellProps = props => {
|
||||
const columnPathStr = [path, column.id].join('_')
|
||||
const columnPathStr = [...path, column.id].join('_')
|
||||
return mergeProps(
|
||||
{
|
||||
key: ['cell', columnPathStr].join('_'),
|
||||
},
|
||||
applyPropHooks(api.hooks.getCellProps, cell, api),
|
||||
applyPropHooks(
|
||||
instanceRef.current.hooks.getCellProps,
|
||||
cell,
|
||||
instanceRef.current
|
||||
),
|
||||
props
|
||||
)
|
||||
}
|
||||
|
||||
// Give each cell a renderer function (supports multiple renderers)
|
||||
cell.render = (type, userProps = {}) => {
|
||||
if (!type) {
|
||||
throw new Error(
|
||||
'You must specify a render "type". This could be "Cell", "Header", "Filter", "Aggregated" or any other custom renderers you have set on your column.'
|
||||
)
|
||||
const Comp = typeof type === 'string' ? column[type] : type
|
||||
|
||||
if (typeof Comp === 'undefined') {
|
||||
throw new Error(renderErr)
|
||||
}
|
||||
return flexRender(column[type], {
|
||||
...api,
|
||||
|
||||
return flexRender(Comp, {
|
||||
...instanceRef.current,
|
||||
...cell,
|
||||
...userProps,
|
||||
})
|
||||
@@ -193,13 +360,19 @@ export const useTable = (props, ...plugins) => {
|
||||
|
||||
return cell
|
||||
})
|
||||
|
||||
// need to apply any row specific hooks (useExpanded requires this)
|
||||
applyHooks(instanceRef.current.hooks.prepareRow, row, instanceRef.current)
|
||||
}
|
||||
|
||||
api.getTableProps = userProps =>
|
||||
mergeProps(applyPropHooks(api.hooks.getTableProps, api), userProps)
|
||||
instanceRef.current.getTableProps = userProps =>
|
||||
mergeProps(
|
||||
applyPropHooks(
|
||||
instanceRef.current.hooks.getTableProps,
|
||||
instanceRef.current
|
||||
),
|
||||
userProps
|
||||
)
|
||||
|
||||
api.getRowProps = userProps =>
|
||||
mergeProps(applyPropHooks(api.hooks.getRowProps, undefined, api), userProps)
|
||||
|
||||
return api
|
||||
return instanceRef.current
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import React from 'react'
|
||||
//
|
||||
import { types } from '../actions'
|
||||
|
||||
export const defaultState = {}
|
||||
|
||||
@@ -24,15 +26,26 @@ export const useTableState = (
|
||||
})
|
||||
}
|
||||
return newState
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [overrides, state])
|
||||
|
||||
const overriddenStateRef = React.useRef()
|
||||
overriddenStateRef.current = overriddenState
|
||||
|
||||
const reducedSetState = React.useCallback(
|
||||
(updater, type) =>
|
||||
setState(old => {
|
||||
(updater, type) => {
|
||||
if (!types[type]) {
|
||||
console.info({
|
||||
stateUpdaterFn: updater,
|
||||
actionType: type,
|
||||
currentState: overriddenStateRef.current,
|
||||
})
|
||||
throw new Error('Detected an unknown table action! (Details Above)')
|
||||
}
|
||||
return setState(old => {
|
||||
const newState = updater(old)
|
||||
return reducer(old, newState, type)
|
||||
}),
|
||||
})
|
||||
},
|
||||
[reducer, setState]
|
||||
)
|
||||
|
||||
|
||||
+11
-12
@@ -1,13 +1,12 @@
|
||||
import * as utils from './utils'
|
||||
export { utils }
|
||||
export { useTable } from './hooks/useTable'
|
||||
export { useColumns } from './hooks/useColumns'
|
||||
export { useRows } from './hooks/useRows'
|
||||
export { useSimpleLayout } from './hooks/useSimpleLayout'
|
||||
export { useExpanded } from './hooks/useExpanded'
|
||||
export { useFilters } from './hooks/useFilters'
|
||||
export { useGroupBy } from './hooks/useGroupBy'
|
||||
export { useSortBy } from './hooks/useSortBy'
|
||||
export { usePagination } from './hooks/usePagination'
|
||||
export { useTableState } from './hooks/useTableState'
|
||||
export { useFlexLayout } from './hooks/useFlexLayout'
|
||||
export { useTokenPagination } from './hooks/useTokenPagination'
|
||||
export { actions } from './actions'
|
||||
export { useTableState, defaultState } from './hooks/useTableState'
|
||||
export { useExpanded } from './plugin-hooks/useExpanded'
|
||||
export { useFilters } from './plugin-hooks/useFilters'
|
||||
export { useGroupBy } from './plugin-hooks/useGroupBy'
|
||||
export { useSortBy } from './plugin-hooks/useSortBy'
|
||||
export { usePagination } from './plugin-hooks/usePagination'
|
||||
export { useFlexLayout } from './plugin-hooks/useFlexLayout'
|
||||
export { useTokenPagination } from './plugin-hooks/useTokenPagination'
|
||||
export { actions, addActions } from './actions'
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||
|
||||
exports[`renders a sortable table 1`] = `
|
||||
"Snapshot Diff:
|
||||
- First value
|
||||
+ Second value
|
||||
|
||||
@@ -31,11 +31,13 @@
|
||||
colspan=\\"1\\"
|
||||
style=\\"cursor: pointer;\\"
|
||||
title=\\"Toggle SortBy\\"
|
||||
>
|
||||
First Name
|
||||
- <span />
|
||||
+ <span>
|
||||
+ 🔼
|
||||
+ </span>
|
||||
</th>
|
||||
<th
|
||||
class=\\"\\"
|
||||
colspan=\\"1\\"
|
||||
style=\\"cursor: pointer;\\"
|
||||
@@ -87,104 +89,104 @@
|
||||
class=\\"\\"
|
||||
>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- firstName: tanner
|
||||
+ firstName: derek
|
||||
</td>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- lastName: linsley
|
||||
+ lastName: perkins
|
||||
</td>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- age: 29
|
||||
+ age: 40
|
||||
</td>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- visits: 100
|
||||
+ visits: 40
|
||||
</td>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- status: In Relationship
|
||||
+ status: Single
|
||||
</td>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- progress: 50
|
||||
+ progress: 80
|
||||
</td>
|
||||
</tr>
|
||||
<tr
|
||||
class=\\"\\"
|
||||
>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- firstName: derek
|
||||
+ firstName: joe
|
||||
</td>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- lastName: perkins
|
||||
+ lastName: bergevin
|
||||
</td>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- age: 40
|
||||
+ age: 45
|
||||
</td>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- visits: 40
|
||||
+ visits: 20
|
||||
</td>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- status: Single
|
||||
+ status: Complicated
|
||||
</td>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- progress: 80
|
||||
+ progress: 10
|
||||
</td>
|
||||
</tr>
|
||||
<tr
|
||||
class=\\"\\"
|
||||
>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- firstName: joe
|
||||
+ firstName: tanner
|
||||
</td>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- lastName: bergevin
|
||||
+ lastName: linsley
|
||||
</td>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- age: 45
|
||||
+ age: 29
|
||||
</td>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- visits: 20
|
||||
+ visits: 100
|
||||
</td>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- status: Complicated
|
||||
+ status: In Relationship
|
||||
</td>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- progress: 10
|
||||
+ progress: 50
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</DocumentFragment>"
|
||||
`;
|
||||
|
||||
exports[`renders a sortable table 2`] = `
|
||||
"Snapshot Diff:
|
||||
- First value
|
||||
+ Second value
|
||||
|
||||
@@ -32,11 +32,11 @@
|
||||
style=\\"cursor: pointer;\\"
|
||||
title=\\"Toggle SortBy\\"
|
||||
>
|
||||
First Name
|
||||
<span>
|
||||
- 🔼
|
||||
+ 🔽
|
||||
</span>
|
||||
</th>
|
||||
<th
|
||||
class=\\"\\"
|
||||
colspan=\\"1\\"
|
||||
@@ -89,36 +89,36 @@
|
||||
class=\\"\\"
|
||||
>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- firstName: derek
|
||||
+ firstName: tanner
|
||||
</td>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- lastName: perkins
|
||||
+ lastName: linsley
|
||||
</td>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- age: 40
|
||||
+ age: 29
|
||||
</td>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- visits: 40
|
||||
+ visits: 100
|
||||
</td>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- status: Single
|
||||
+ status: In Relationship
|
||||
</td>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- progress: 80
|
||||
+ progress: 50
|
||||
</td>
|
||||
</tr>
|
||||
<tr
|
||||
class=\\"\\"
|
||||
>
|
||||
@@ -157,36 +157,36 @@
|
||||
class=\\"\\"
|
||||
>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- firstName: tanner
|
||||
+ firstName: derek
|
||||
</td>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- lastName: linsley
|
||||
+ lastName: perkins
|
||||
</td>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- age: 29
|
||||
+ age: 40
|
||||
</td>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- visits: 100
|
||||
+ visits: 40
|
||||
</td>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- status: In Relationship
|
||||
+ status: Single
|
||||
</td>
|
||||
<td
|
||||
class=\\"\\"
|
||||
>
|
||||
- progress: 50
|
||||
+ progress: 80
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</DocumentFragment>"
|
||||
`;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user