Compare commits

...
35 Commits
Author SHA1 Message Date
Tanner Linsley b517ee13d5 v7.0.0-rc.9 2019-12-10 23:05:57 -07:00
Tanner Linsley ddfa0fa227 Death of the path, fix some hooks, fix selectedRows
- Fixed an issue where dependency hooks were not being reduced properly, thus the table would rerender unnecessarily
- Renamed `toggleRowSelectedAll` to `toggleAllRowsSelected`. Duh...
- Added an `indeterminate` boolean prop to the default props for row selection toggle prop getters
- Renamed `selectedRowPaths` to `selectedRowIds`, which also no longer contains paths, but row IDs
- Grouped or nested row selection actions and state are now derived, instead of tracked in state.
- Rows now have a new property called `id`, which existed before and was derived from the `getRowId` option
- Rows now also have an `isSomeSelected` prop when using the `useRowSelect` hook, which denotes that at least one subRow is selected (if applicable)
- Rows' `path` property has been deprecated in favor of `id`
- Expanded state is now tracked with row IDs instead of paths
- RowState is now tracked with row IDs instead of paths
- `toggleExpandedByPath` has been renamed to `toggleExpandedById`, and thus accepts a row ID now, instead of a row path
2019-12-10 23:04:34 -07:00
Tanner Linsley 42b78d52ca v7.0.0-rc.8 2019-12-10 16:35:19 -07:00
Tanner Linsley 68fd89af3c Fix props clobbering
Fixes #1755
2019-12-10 16:34:23 -07:00
Tanner Linsley 0c43e19091 Fix useResizeColumns bug 2019-12-10 14:58:31 -07:00
size-plugin[bot]andGitHub 08bb50ae48 🧑🏻‍🤝‍🧑🏻 🔔 update sizes-es.json 👍 2019-12-10 19:44:09 +00:00
size-plugin[bot]andGitHub 0fcc9e608c 🇰🇪 🍐 update sizes-cjs.json 👍 2019-12-10 19:44:08 +00:00
Tanner Linsley 15125f9326 Update useColumnVisibility.js 2019-12-10 12:42:19 -07:00
Tanner Linsley b8701f260a Update CHANGELOG.md 2019-12-10 12:33:44 -07:00
Tanner Linsley 70bdd272e5 Merge branch 'master' of https://github.com/react-tools/react-table 2019-12-10 11:59:39 -07:00
size-plugin[bot]andGitHub 5ad648d9da 🇧🇸 👮🏽‍♂️ update sizes-es.json 👍 2019-12-10 18:58:59 +00:00
size-plugin[bot]andGitHub 117dc54439 💻 🙍🏾‍♀️ update sizes-cjs.json 👍 2019-12-10 18:58:58 +00:00
Tanner Linsley d8f0174d80 v7.0.0-rc.7 2019-12-10 11:57:54 -07:00
Tanner Linsley cf9517fe7a Merge branch 'master' of https://github.com/react-tools/react-table 2019-12-10 11:57:21 -07:00
Tanner Linsley e1fd921f07 Add useFinalInstance plugin hook 2019-12-10 11:56:41 -07:00
dependabot[bot]andTanner Linsley 7222c1cb2b Bump eslint-utils from 1.4.0 to 1.4.3 in /examples/row-selection (#1754)
Bumps [eslint-utils](https://github.com/mysticatea/eslint-utils) from 1.4.0 to 1.4.3.
- [Release notes](https://github.com/mysticatea/eslint-utils/releases)
- [Commits](https://github.com/mysticatea/eslint-utils/compare/v1.4.0...v1.4.3)

Signed-off-by: dependabot[bot] <support@github.com>
2019-12-10 11:51:39 -07:00
size-plugin[bot]andGitHub e984934e92 👩🏽‍⚖️ 🕵🏾‍♀️ update sizes-es.json 👍 2019-12-10 18:44:23 +00:00
size-plugin[bot]andGitHub 938bdd9885 🧏🏾 ✡️ update sizes-cjs.json 👍 2019-12-10 18:44:22 +00:00
Tanner Linsley 88a0d86d60 Update .size-snapshot.json 2019-12-10 11:42:31 -07:00
Tanner Linsley 690190081f Merge branch 'master' of https://github.com/react-tools/react-table 2019-12-10 11:37:07 -07:00
Tanner Linsley 4a3311035d Added/updated hooks reorganization of hooks, new hook rules
- The exported (but undocumented) `applyHooks` function has been deprecated. Please use either `reduceHooks` or `loopHooks` utilities in your custom plugins now.
- The exported (but undocumented) `applyPropHooks` function has been deprecated. Please use the `makePropGetter` utility in your custom plugins now.
- Added the `reduceHooks` exported utility which is used to reduce a value through a collection of hooks. Each hook must return a value (mutation is discouraged)
- Added the `loopHooks` exported utility which is used to loop over a collection of hooks. Hooks are not allowed to return a value (mutation is encouraged)
- Prop-getter hook functions now support returning an array (in addition to the typical object of props). When an array is returned, each item in the array is smart-merged into a new props object (meaning it will intelligently compose and override styles and className)
- Added the `makePropGetter` exported utility which is used to create prop getters from a prop getter hook.
- Prop-getter function supplied to the table have 2 new overloaded options (in addition to the typical object of props):
  - `Function(props, instance, ...row/col/context) => Array<props> | props` - If a function is passed to a prop getter function, it will receive the previous props, the table instance, and potentially more context arguments. It is then be expected to return either an array of new props (to be smart-merged with styles and classes, the latest values taking priority over the previous values) or a props object (which will replace all previous props)
  - `Array<props>` - If an array is passed to a prop getter function, each prop object in the array will be smart-merged with styles and classes into the props from previous hooks (with the latest values taking priority over the previous values).
- Extracted default hooks into separate file.
- Added the `useOptions` plugin hook, which allows a plugin to reduce/modify the initial options being passed to the table
- Converted almost all usages of `instanceRef.current` to use `useGetLatest(instanceRef.current)` to help with avoiding memory leaks and to be more terse.
- Converted all previous prop-getter definitions to use the new `makePropGetter`
- Reorganized plugin hooks to declare as many hooks in the main plugin function as opposed to in the `useInstance` hook.
- Changed the `useInstanceBeforeDimensions` hook to be a `loopHooks` call instead of a reducer. An error will be thrown now if any of these hook functions returns a value (to discourage mutation of the instance)
- Changed the `useInstance` hook to be a `loopHooks` call instead of a reducer. An error will be thrown now if any of these hook functions returns a value (to discourage mutation of the instance)
- Change the `prepareRow` hook to be a `loopHooks` call instead of a reducer. An error will be thrown now if any of these hook functions returns a value (to discourage mutation of the row)
2019-12-10 11:35:05 -07:00
size-plugin[bot]andGitHub a73ee145b3 💍 ️ update sizes-cjs.json 👍 2019-12-10 13:42:08 +00:00
size-plugin[bot]andGitHub b0d2044e22 🤫 💪🏻 update sizes-es.json 👍 2019-12-10 13:42:07 +00:00
Jakob Hjelmer NielsenandTanner Linsley ccc89379da .add touch events to useResizeColumns (#1748)
.add onTouchStart to mergeProps
.add touch-action css to resizer
.mod increase resizer width or it is very hard to activate using touch devices
2019-12-10 06:39:02 -07:00
Tanner Linsley 9563dae006 Update README.md 2019-12-09 10:51:07 -07:00
Tanner Linsley d35d190708 Merge branch 'master' of https://github.com/react-tools/react-table 2019-12-09 10:51:05 -07:00
Tanner Linsley 614f40f47d Fix controlled pagination example 2019-12-09 10:12:36 -07:00
size-plugin[bot]andGitHub 5846c86605 👨‍💻 🛹 update sizes-es.json 👍 2019-12-09 17:02:19 +00:00
size-plugin[bot]andGitHub c5fb154d9b ⛹🏻‍♂️ 🏋🏼‍♀️ update sizes-cjs.json 👍 2019-12-09 17:02:18 +00:00
Tanner Linsley 5e6952db93 v7.0.0-rc.6 2019-12-09 09:53:29 -07:00
Tanner Linsley ac43ef2e38 Merge branch 'master' of https://github.com/react-tools/react-table 2019-12-09 09:52:50 -07:00
Tanner Linsley 9de699bfd3 Add/rename a few hooks, fix useColumnVisibility header deps
- The `columnsBeforeHeaderGroups` and `columnsBeforeHeaderGroupsDeps` hooks have been renamed to `flatColumns` and `flatColumnsDeps` respectively, which better reflects what they are used for, rather than their order, which can remain implicit.
- Added `headerGroups` and `headerGroupDeps` hooks, which, similar to `flatColumns`, allow you to decorate (and trigger) the memoized header group generation.
- Added `columns` and `columnsDeps` hooks, which, similar to `flatColumns` and `headerGroups`, allow you to decorate (and trigger) the memoized column generation/decoration.
- The new hook order is as follows: `columns/columnsDeps` => `flatColumns/flatColumnsDeps` => `headerGroups/headerGroupsDeps`
- `useColumnVisibility` now uses the new `headerGroupsDeps` hook to trigger header group regeneration when visibility changes
2019-12-09 09:52:27 -07:00
size-plugin[bot]andGitHub 38d82a0397 📘 🍫 update sizes-es.json 👍 2019-12-09 02:40:17 +00:00
size-plugin[bot]andGitHub 863bf50206 🍊 👨🏾‍🎨 update sizes-cjs.json 👍 2019-12-09 02:40:16 +00:00
Tanner Linsley 492ba8a4f9 Update Changelog 2019-12-08 19:35:55 -07:00
39 changed files with 1287 additions and 853 deletions
+26 -7
View File
@@ -1,20 +1,39 @@
{
"dist/index.js": {
"bundled": 100428,
"minified": 47447,
"gzipped": 12335
"bundled": 107809,
"minified": 51216,
"gzipped": 13492
},
"dist/index.es.js": {
"bundled": 99612,
"minified": 46722,
"gzipped": 12189,
"bundled": 106966,
"minified": 50466,
"gzipped": 13339,
"treeshaked": {
"rollup": {
"code": 80,
"import_statements": 21
},
"webpack": {
"code": 8457
"code": 8902
}
}
},
"dist\\index.js": {
"bundled": 105386,
"minified": 49565,
"gzipped": 13008
},
"dist\\index.es.js": {
"bundled": 104543,
"minified": 48815,
"gzipped": 12856,
"treeshaked": {
"rollup": {
"code": 80,
"import_statements": 21
},
"webpack": {
"code": 8444
}
}
}
+61 -1
View File
@@ -1,3 +1,63 @@
## 7.0.0-rc.9
- Fixed an issue where dependency hooks were not being reduced properly, thus the table would rerender unnecessarily
- Renamed `toggleRowSelectedAll` to `toggleAllRowsSelected`. Duh...
- Added an `indeterminate` boolean prop to the default props for row selection toggle prop getters
- Renamed `selectedRowPaths` to `selectedRowIds`, which also no longer contains paths, but row IDs
- Grouped or nested row selection actions and state are now derived, instead of tracked in state.
- Rows now have a new property called `id`, which existed before and was derived from the `getRowId` option
- Rows now also have an `isSomeSelected` prop when using the `useRowSelect` hook, which denotes that at least one subRow is selected (if applicable)
- Rows' `path` property has been deprecated in favor of `id`
- Expanded state is now tracked with row IDs instead of paths
- RowState is now tracked with row IDs instead of paths
- `toggleExpandedByPath` has been renamed to `toggleExpandedById`, and thus accepts a row ID now, instead of a row path
## 7.0.0-rc.8
- Fix an issue where `useResizeColumns` would crash when using the resizer prop getter
- Fix an issue where `useBlockLayout` was clobbering props sent to headers
## 7.0.0-rc.7
Removed:
- `applyHooks` (exported but undocumented) function has been deprecated. Please use either `reduceHooks` or `loopHooks` utilities in your custom plugins now.
- `applyPropHooks` (exported but undocumented) function has been deprecated. Please use the `makePropGetter` utility in your custom plugins now.
Added:
- `reduceHooks` exported utility which is used to reduce a value through a collection of hooks. Each hook must return a value (mutation is discouraged)
- `loopHooks` exported utility which is used to loop over a collection of hooks. Hooks are not allowed to return a value (mutation is encouraged)
- `makePropGetter` exported utility which is used to create prop getters from a prop getter hook.
- `useOptions` plugin hook, which allows a plugin to reduce/modify the initial options being passed to the table
- `useFinalInstance` plugin hook, which allows a plugin access to the final table instance before it is returned to the user.
Modified:
- Prop-getter hook functions now support returning an array (in addition to the typical object of props). When an array is returned, each item in the array is smart-merged into a new props object (meaning it will intelligently compose and override styles and className)
- Prop-getter function supplied to the table have 2 new overloaded options (in addition to the typical object of props):
- `Function(props, instance, ...row/col/context) => Array<props> | props` - If a function is passed to a prop getter function, it will receive the previous props, the table instance, and potentially more context arguments. It is then be expected to return either an array of new props (to be smart-merged with styles and classes, the latest values taking priority over the previous values) or a props object (which will replace all previous props)
- `Array<props>` - If an array is passed to a prop getter function, each prop object in the array will be smart-merged with styles and classes into the props from previous hooks (with the latest values taking priority over the previous values).
- Extracted default hooks into separate file.
- Converted almost all usages of `instanceRef.current` to use `useGetLatest(instanceRef.current)` to help with avoiding memory leaks and to be more terse.
- Converted all previous prop-getter definitions to use the new `makePropGetter`
- Reorganized plugin hooks to declare as many hooks in the main plugin function as opposed to in the `useInstance` hook.
- Changed the `useInstanceBeforeDimensions` hook to be a `loopHooks` call instead of a reducer. An error will be thrown now if any of these hook functions returns a value (to encourage mutation of the instance)
- Changed the `useInstance` hook to be a `loopHooks` call instead of a reducer. An error will be thrown now if any of these hook functions returns a value (to encourage mutation of the instance)
- Change the `prepareRow` hook to be a `loopHooks` call instead of a reducer. An error will be thrown now if any of these hook functions returns a value (to encourage mutation of the row)
## 7.0.0-rc.6
- The `columnsBeforeHeaderGroups` and `columnsBeforeHeaderGroupsDeps` hooks have been renamed to `flatColumns` and `flatColumnsDeps` respectively, which better reflects what they are used for, rather than their order, which can remain implicit.
- Added `headerGroups` and `headerGroupDeps` hooks, which, similar to `flatColumns`, allow you to decorate (and trigger) the memoized header group generation.
- Added `columns` and `columnsDeps` hooks, which, similar to `flatColumns` and `headerGroups`, allow you to decorate (and trigger) the memoized column generation/decoration.
- The new hook order is as follows: `columns/columnsDeps` => `flatColumns/flatColumnsDeps` => `headerGroups/headerGroupsDeps`
- `useColumnVisibility` now uses the new `headerGroupsDeps` hook to trigger header group regeneration when visibility changes
## 7.0.0-rc.5
- Fixed an issue where the exported `useAsyncDebounce` method would crash if its promise throw an error.
## 7.0.0-rc.4
- A maintenance release, purely intended to update the @latest tag (which was overwritten by a v6 publish)
@@ -55,7 +115,7 @@
## 7.0.0-beta.24
- Changed `selectedRowPaths` to use a `Set()` instead of an array for performance.
- Changed `selectedRowIds` to use a `Set()` instead of an array for performance.
- Removed types and related files from the repo. The community will now maintain types externally on Definitely Typed
## 7.0.0-beta.23
+1 -2
View File
@@ -21,7 +21,7 @@ Enjoy this library? Try them all! [React Query](https://github.com/tannerlinsley
## Features
- Lightweight (4kb - 11kb depending on features and tree-shaking)
- Lightweight (5kb - 12kb+ depending on features used and tree-shaking)
- Headless (100% customizable, Bring-your-own-UI)
- Auto out of the box, fully controllable API
- Sorting (Multi and Stable)
@@ -35,7 +35,6 @@ Enjoy this library? Try them all! [React Query](https://github.com/tannerlinsley
- Resizable
- Server-side/controlled data/state
- Extensible via hook-based plugin system
- <a href="https://medium.com/@tannerlinsley/why-i-wrote-react-table-and-the-problems-it-has-solved-for-nozzle-others-445c4e93d4a8#.axza4ixba" target="\_parent">"Why I wrote React Table and the problems it has solved for Nozzle.io"</a> by Tanner Linsley
## Documentation
+4 -4
View File
@@ -9,12 +9,12 @@
The following options are supported via the main options object passed to `useTable(options)`
- `state.expanded: Array<pathKey: String>`
- `state.expanded: Array<rowId: String>`
- Optional
- Must be **memoized**
- An array of expanded path keys.
- If a row's path key (`row.path.join('.')`) is present in this array, that row will have an expanded state. For example, if `['3']` was passed as the `expanded` state, the **4th row in the original data array** would be expanded.
- For nested expansion, you may **join the row path with a `.`** to expand sub rows. For example, if `['3', '3.5']` was passed as the `expanded` state, then the **6th subRow of the 4th row and also the 4th row of the original data array** would be expanded.
- An array of expanded row IDs.
- If a row's id is present in this array, that row will have an expanded state. For example, if `['3']` was passed as the `expanded` state, by default the **4th row in the original data array** would be expanded, since it would have that ID
- For nested expansion, you can **use nested IDs like `1.3`** to expand sub rows. For example, if `['3', '3.5']` was passed as the `expanded` state, then the **the 4th row would be expanded, along with the 6th subRow of the 4th row as well**.
- This information is stored in state since the table is allowed to manipulate the filter through user interaction.
- `initialState.expanded`
- Identical to the `state.expanded` option above
+5 -3
View File
@@ -96,9 +96,11 @@ The following properties are available on every `Row` object returned by the tab
- If the row is a materialized group row, this property is the array of materialized subRows that were grouped inside of this row.
- `depth: Int`
- If the row is a materialized group row, this is the grouping depth at which this row was created.
- `path: Array<String|Int>`
- Similar to normal `Row` objects, materialized grouping rows also have a path array. The keys inside it though are not integers like nested normal rows though. Since they are not rows that can be traced back to an original data row, they are given a unique path based on their `groupByVal`
- If a row is a grouping row, it will have a path like `['Single']` or `['Complicated', 'Anderson']`, where `Single`, `Complicated`, and `Anderson` would all be derived from their row's `groupByVal`.
- `id: String`
- The unique ID for this row.
- This ID is unique across all rows, including sub rows
- Derived from the `getRowId` function, which defaults to chaining parent IDs and joining with a `.`
- If a row is a materialized grouping row, it will have an ID in the format of `columnId:groupByVal`.
- `isAggregated: Bool`
- Will be `true` if the row is an aggregated row
+5 -5
View File
@@ -9,12 +9,10 @@
The following options are supported via the main options object passed to `useTable(options)`
- `state.selectedRowPaths: Set<RowPathKey>`
- `initialState.selectedRowIds: Set<RowPathKey>`
- Optional
- Defaults to `new Set()`
- If a row's path key (eg. a row path of `[1, 3, 2]` would have a path key of `1.3.2`) is found in this array, it will have a selected state.
- `initialState.selectedRowPaths`
- Identical to the `state.selectedRowPaths` option above
- If a row's ID is found in this array, it will have a selected state.
- `manualRowSelectedKey: String`
- Optional
- Defaults to `isSelected`
@@ -33,7 +31,7 @@ The following values are provided to the table `instance`:
- `toggleRowSelected: Function(rowPath: String, ?set: Bool) => void`
- Use this function to toggle a row's selected state.
- Optionally pass `true` or `false` to set it to that state
- `toggleRowSelectedAll: Function(?set: Bool) => void`
- `toggleAllRowsSelected: Function(?set: Bool) => void`
- Use this function to toggle all rows as select or not
- Optionally pass `true` or `false` to set all rows to that state
- `getToggleAllRowsSelectedProps: Function(props) => props`
@@ -55,6 +53,8 @@ The following additional properties are available on every **prepared** `row` ob
- `isSelected: Bool`
- Will be `true` if the row is currently selected
- `isSomeSelected: Bool`
- Will be `true` if the row has subRows and at least one of them is currently selected
- `toggleRowSelected: Function(?set)`
- Use this function to toggle this row's selected state.
- Optionally pass `true` or `false` to set it to that state
+3 -3
View File
@@ -12,7 +12,7 @@ The following options are supported via the main options object passed to `useTa
- `state.rowState: Object<RowPathKey:Object<any, cellState: {columnId: Object}>>`
- Optional
- Defaults to `{}`
- If a row's path key (eg. a row path of `[1, 3, 2]` would have a path key of `1.3.2`) is found in this array, it will have the state of the value corresponding to that key.
- If a row's ID is found in this array, it will have the state of the value corresponding to that key.
- Individual row states can contain anything, but they also contain a `cellState` key, which provides cell-level state based on column ID's to every
**prepared** cell in the table.
- `initialState.rowState`
@@ -44,7 +44,7 @@ The following values are provided to the table `instance`:
The following additional properties are available on every **prepared** `row` object returned by the table instance.
- `state: Object`
- This is the state object for each row, pre-mapped to the row from the table state's `rowState` object via `rowState[row.path.join('.')]`
- This is the state object for each row, pre-mapped to the row from the table state's `rowState` object via `rowState[row.id]`
- May also contain a `cellState` key/value pair, which is used to provide individual cell states to this row's cells
- `setState: Function(updater: Function | any)`
- Use this function to programmatically update the state of a row.
@@ -55,7 +55,7 @@ The following additional properties are available on every **prepared** `row` ob
The following additional properties are available on every `Cell` object returned in an array of `cells` on every row object.
- `state: Object`
- This is the state object for each cell, pre-mapped to the cell from the table state's `rowState` object via `rowState[row.path.join('.')].cellState[columnId]`
- This is the state object for each cell, pre-mapped to the cell from the table state's `rowState` object via `rowState[row.id].cellState[columnId]`
- `setState: Function(updater: Function | any)`
- Use this function to programmatically update the state of a cell.
- `updater` can be a function or value. If a `function` is passed, it will receive the current value and expect a new one to be returned.
+3 -8
View File
@@ -53,13 +53,11 @@ The following options are supported via the main options object passed to `useTa
- Defaults to `(row) => row.subRows || []`
- Use this function to change how React Table detects subrows. You could even use this function to generate sub rows if you want.
- By default, it will attempt to return the `subRows` property on the row, or an empty array if that is not found.
- `getRowId: Function(row, relativeIndex) => string`
- Use this function to change how React Table detects unique rows and also how it constructs each row's underlying `path` property.
- `getRowId: Function(row, relativeIndex, ?parent) => string`
- Use this function to change how React Table detects unique rows and also how it constructs each row's underlying `id` property.
- Optional
- Must be **memoized**
- Defaults to `(row, relativeIndex) => relativeIndex`
- You may want to change this function if
- By default, it will use the `index` of the row within it's original array.
- Defaults to `(row, relativeIndex, parent) => parent ? [parent.id, relativeIndex].join('.') : relativeIndex`
- `debug: Bool`
- Optional
- A flag to turn on debug mode.
@@ -255,9 +253,6 @@ The following additional properties are available on every `row` object returned
- The index of the original row in the `data` array that was passed to `useTable`. If this row is a subRow, it is the original index within the parent row's subRows array
- `original: Object`
- The original row object from the `data` array that was used to materialize this row.
- `path: Array<string>`
- This array is the sequential path of indices one could use to navigate to it, eg. a row path of `[3, 1, 0]` would mean that it is the **first** subRow of a parent that is the **second** subRow of a parent that is the **fourth** row in the original `data` array.
- This array is used with plugin hooks like `useExpanded` and `useGroupBy` to compute expanded states for individual rows.
- `subRows: Array<Row>`
- If subRows were detect on the original data object, this will be an array of those materialized row objects.
- `state: Object`
+12 -13
View File
@@ -92,19 +92,18 @@ function Table({ columns, data }) {
</div>
<div className="rows" {...getTableBodyProps()}>
{rows.map(
(row, i) => {
prepareRow(row);
return (
<div {...row.getRowProps()} className="row body">
{row.cells.map((cell,index) => (
<div {...cell.getCellProps()} key={index} className="cell">
{cell.render('Cell')}
</div>
))}
</div>
)}
)}
{rows.map((row, i) => {
prepareRow(row)
return (
<div {...row.getRowProps()} className="row body">
{row.cells.map((cell, index) => (
<div {...cell.getCellProps()} key={index} className="cell">
{cell.render('Cell')}
</div>
))}
</div>
)
})}
</div>
</div>
)
+3 -3
View File
@@ -35,18 +35,18 @@ const Styles = styled.div`
border-right: 0;
}
${'' /* The resizer styles! */}
.resizer {
display: inline-block;
background: blue;
width: 5px;
width: 10px;
height: 100%;
position: absolute;
right: 0;
top: 0;
transform: translateX(50%);
z-index: 1;
${'' /* prevents from scrolling while dragging on touch devices */}
touch-action:none;
&.isResizing {
background: red;
+4 -4
View File
@@ -8087,10 +8087,10 @@ react-scripts@3.0.1:
optionalDependencies:
fsevents "2.0.6"
react-table@next:
version "7.0.0-alpha.7"
resolved "https://registry.yarnpkg.com/react-table/-/react-table-7.0.0-alpha.7.tgz#0cb6da6f32adb397e68505b7cdd4880d15d73017"
integrity sha512-oXE9RRkE2CFk1OloNCSTPQ9qxOdujgkCoW5b/srbJsBog/ySkWuozBTQkxH1wGNmnSxGyTrTxJqXdXPQam7VAw==
react-table@latest:
version "7.0.0-rc.7"
resolved "https://registry.yarnpkg.com/react-table/-/react-table-7.0.0-rc.7.tgz#1bf3e248cdef22213821c021236e895bdc3cb5d2"
integrity sha512-24Yofwkh822NyCmnpsrChV8SNOCENQWpV4A5f/MzapTi6iwje644Q11/wbLIgJdPnUJJ0/JbhjsDjxlB6yFV7Q==
react@^16.8.6:
version "16.8.6"
@@ -1,6 +1,6 @@
import React from 'react'
import styled from 'styled-components'
import { useTable, mergeProps } from 'react-table'
import { useTable } from 'react-table'
import makeData from './makeData'
@@ -68,16 +68,15 @@ function Table({
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th
// Merge all of the header Props
{...mergeProps(
column.getHeaderProps(),
// Return an array of prop objects and react-table will merge them appropriately
{...column.getHeaderProps([
{
className: column.className,
style: column.style,
},
getColumnProps(column),
getHeaderProps(column)
)}
getHeaderProps(column),
])}
>
{column.render('Header')}
</th>
@@ -89,21 +88,20 @@ function Table({
{rows.map((row, i) => {
prepareRow(row)
return (
// Merge row props
<tr {...mergeProps(row.getRowProps(), getRowProps(row))}>
// Merge user row props in
<tr {...row.getRowProps(getRowProps(row))}>
{row.cells.map(cell => {
return (
<td
// Merge cell props
{...mergeProps(
cell.getCellProps(),
// Return an array of prop objects and react-table will merge them appropriately
{...cell.getCellProps([
{
className: cell.column.className,
style: cell.column.style,
},
getColumnProps(cell.column),
getCellProps(cell)
)}
getCellProps(cell),
])}
>
{cell.render('Cell')}
</td>
+2 -9
View File
@@ -282,14 +282,7 @@ function Table({ columns, data, updateMyData, skipPageReset }) {
nextPage,
previousPage,
setPageSize,
state: {
pageIndex,
pageSize,
groupBy,
expanded,
filters,
selectedRowPaths,
},
state: { pageIndex, pageSize, groupBy, expanded, filters, selectedRowIds },
} = useTable(
{
columns,
@@ -442,7 +435,7 @@ function Table({ columns, data, updateMyData, skipPageReset }) {
groupBy,
expanded,
filters,
selectedRowPaths: [...selectedRowPaths.values()],
selectedRowIds: [...selectedRowIds.values()],
},
null,
2
+21 -11
View File
@@ -282,14 +282,7 @@ function Table({ columns, data, updateMyData, skipReset }) {
nextPage,
previousPage,
setPageSize,
state: {
pageIndex,
pageSize,
groupBy,
expanded,
filters,
selectedRowPaths,
},
state: { pageIndex, pageSize, groupBy, expanded, filters, selectedRowIds },
} = useTable(
{
columns,
@@ -441,7 +434,7 @@ function Table({ columns, data, updateMyData, skipReset }) {
groupBy,
expanded,
filters,
selectedRowPaths: [...selectedRowPaths.values()],
selectedRowIds: [...selectedRowIds.values()],
},
null,
2
@@ -481,6 +474,23 @@ function roundedMedian(values) {
return Math.round((min + max) / 2)
}
const IndeterminateCheckbox = React.forwardRef(
({ indeterminate, ...rest }, ref) => {
const defaultRef = React.useRef()
const resolvedRef = ref || defaultRef
React.useEffect(() => {
resolvedRef.current.indeterminate = indeterminate
}, [resolvedRef, indeterminate])
return (
<>
<input type="checkbox" ref={resolvedRef} {...rest} />
</>
)
}
)
function App() {
const columns = React.useMemo(
() => [
@@ -493,14 +503,14 @@ function App() {
// to render a checkbox
Header: ({ getToggleAllRowsSelectedProps }) => (
<div>
<input type="checkbox" {...getToggleAllRowsSelectedProps()} />
<IndeterminateCheckbox {...getToggleAllRowsSelectedProps()} />
</div>
),
// The cell can use the individual row's getToggleRowSelectedProps method
// to the render a checkbox
Cell: ({ row }) => (
<div>
<input type="checkbox" {...row.getToggleRowSelectedProps()} />
<IndeterminateCheckbox {...row.getToggleRowSelectedProps()} />
</div>
),
},
+4 -4
View File
@@ -8218,10 +8218,10 @@ react-scripts@3.0.1:
optionalDependencies:
fsevents "2.0.6"
react-table@next:
version "7.0.0-beta.19"
resolved "https://registry.yarnpkg.com/react-table/-/react-table-7.0.0-beta.19.tgz#8563ae56f693cbffa10060772ba1f1cd4e926bb2"
integrity sha512-BRt7zW7PGyg67fR2CK9M2fwP6BocjQN870w3P+K+vDJMkpewGjSPDscCU5sJMBqCEjKWg85k2pVkiwQPg9ofgQ==
react-table@latest:
version "7.0.0-rc.6"
resolved "https://registry.yarnpkg.com/react-table/-/react-table-7.0.0-rc.6.tgz#3cb43919e31166659d6aa223bd3dfee765981f6b"
integrity sha512-iFgxMla6JnxjZwKG3eiHHOlIIANiK/HzvRFWXT8LV78N9bEOGC5A5N44S/xQ1PaZN/1c+NDBz5fBazhx/vG7/A==
react@^16.8.6:
version "16.12.0"
+3 -3
View File
@@ -105,7 +105,7 @@ function Table({
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps(column.getSortByToggleProps())}>
<th {...column.getHeaderProps()}>
{column.render('Header')}
<span>
{column.isSorted
@@ -133,9 +133,9 @@ function Table({
<tr>
{loading ? (
// Use our custom loading state to show a loading indicator
<td>Loading...</td>
<td colSpan="10000">Loading...</td>
) : (
<td>
<td colSpan="10000">
Showing {page.length} of ~{controlledPageCount * pageSize}{' '}
results
</td>
+23 -6
View File
@@ -33,6 +33,23 @@ const Styles = styled.div`
}
`
const IndeterminateCheckbox = React.forwardRef(
({ indeterminate, ...rest }, ref) => {
const defaultRef = React.useRef()
const resolvedRef = ref || defaultRef
React.useEffect(() => {
resolvedRef.current.indeterminate = indeterminate
}, [resolvedRef, indeterminate])
return (
<>
<input type="checkbox" ref={resolvedRef} {...rest} />
</>
)
}
)
function Table({ columns, data }) {
// Use the state and functions returned from useTable to build your UI
const {
@@ -42,7 +59,7 @@ function Table({ columns, data }) {
rows,
prepareRow,
selectedFlatRows,
state: { selectedRowPaths },
state: { selectedRowIds },
} = useTable(
{
columns,
@@ -77,12 +94,12 @@ function Table({ columns, data }) {
})}
</tbody>
</table>
<p>Selected Rows: {selectedRowPaths.size}</p>
<p>Selected Rows: {selectedRowIds.size}</p>
<pre>
<code>
{JSON.stringify(
{
selectedRowPaths: [...selectedRowPaths.values()],
selectedRowIds: [...selectedRowIds.values()],
'selectedFlatRows[].original': selectedFlatRows.map(
d => d.original
),
@@ -106,14 +123,14 @@ function App() {
// to render a checkbox
Header: ({ getToggleAllRowsSelectedProps }) => (
<div>
<input type="checkbox" {...getToggleAllRowsSelectedProps()} />
<IndeterminateCheckbox {...getToggleAllRowsSelectedProps()} />
</div>
),
// The cell can use the individual row's getToggleRowSelectedProps method
// to the render a checkbox
Cell: ({ row }) => (
<div>
<input type="checkbox" {...row.getToggleRowSelectedProps()} />
<IndeterminateCheckbox {...row.getToggleRowSelectedProps()} />
</div>
),
},
@@ -155,7 +172,7 @@ function App() {
[]
)
const data = React.useMemo(() => makeData(10), [])
const data = React.useMemo(() => makeData(10, 3), [])
return (
<Styles>
+12 -12
View File
@@ -3652,16 +3652,16 @@ eslint-scope@^4.0.0, eslint-scope@^4.0.3:
estraverse "^4.1.1"
eslint-utils@^1.3.1:
version "1.4.0"
resolved "https://registry.yarnpkg.com/eslint-utils/-/eslint-utils-1.4.0.tgz#e2c3c8dba768425f897cf0f9e51fe2e241485d4c"
integrity sha512-7ehnzPaP5IIEh1r1tkjuIrxqhNkzUJa9z3R92tLJdZIVdWaczEhr3EbhGtsMrVxi1KeR8qA7Off6SWc5WNQqyQ==
version "1.4.3"
resolved "https://registry.yarnpkg.com/eslint-utils/-/eslint-utils-1.4.3.tgz#74fec7c54d0776b6f67e0251040b5806564e981f"
integrity sha512-fbBN5W2xdY45KulGXmLHZ3c3FHfVYmKg0IrAKGOkT/464PQsx2UeIzfz1RmEci+KLm1bBaAzZAh8+/E+XAeZ8Q==
dependencies:
eslint-visitor-keys "^1.0.0"
eslint-visitor-keys "^1.1.0"
eslint-visitor-keys@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.0.0.tgz#3f3180fb2e291017716acb4c9d6d5b5c34a6a81d"
integrity sha512-qzm/XxIbxm/FHyH341ZrbnMUpe+5Bocte9xkmFMzPMjRaZMcXww+MpBptFvtU+79L362nqiLhekCxCxDPaUMBQ==
eslint-visitor-keys@^1.0.0, eslint-visitor-keys@^1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.1.0.tgz#e2a82cea84ff246ad6fb57f9bde5b46621459ec2"
integrity sha512-8y9YjtM1JBJU/A9Kc+SbaOV4y29sSWckBwMHa+FGtVj5gN/sbnKDf6xJUl+8g7FAij9LVaP8C24DUiH/f/2Z9A==
eslint@^5.16.0:
version "5.16.0"
@@ -8087,10 +8087,10 @@ react-scripts@3.0.1:
optionalDependencies:
fsevents "2.0.6"
react-table@next:
version "7.0.0-alpha.7"
resolved "https://registry.yarnpkg.com/react-table/-/react-table-7.0.0-alpha.7.tgz#0cb6da6f32adb397e68505b7cdd4880d15d73017"
integrity sha512-oXE9RRkE2CFk1OloNCSTPQ9qxOdujgkCoW5b/srbJsBog/ySkWuozBTQkxH1wGNmnSxGyTrTxJqXdXPQam7VAw==
react-table@latest:
version "7.0.0-rc.6"
resolved "https://registry.yarnpkg.com/react-table/-/react-table-7.0.0-rc.6.tgz#3cb43919e31166659d6aa223bd3dfee765981f6b"
integrity sha512-iFgxMla6JnxjZwKG3eiHHOlIIANiK/HzvRFWXT8LV78N9bEOGC5A5N44S/xQ1PaZN/1c+NDBz5fBazhx/vG7/A==
react@^16.8.6:
version "16.8.6"
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "react-table",
"version": "7.0.0-rc.5",
"version": "7.0.0-rc.9",
"description": "Hooks for building lightweight, fast and extendable datagrids for React",
"license": "MIT",
"homepage": "https://github.com/tannerlinsley/react-table#readme",
+60
View File
@@ -1,4 +1,64 @@
[
{
"timestamp": 1576007021431,
"files": [
{
"filename": "index.js",
"size": 22643,
"delta": -7
}
]
},
{
"timestamp": 1576004320856,
"files": [
{
"filename": "index.js",
"size": 22650,
"delta": 30
}
]
},
{
"timestamp": 1576003432935,
"files": [
{
"filename": "index.js",
"size": 22620,
"delta": 652
}
]
},
{
"timestamp": 1575985310396,
"files": [
{
"filename": "index.js",
"size": 21968,
"delta": 323
}
]
},
{
"timestamp": 1575910923566,
"files": [
{
"filename": "index.js",
"size": 21645,
"delta": 56
}
]
},
{
"timestamp": 1575859193604,
"files": [
{
"filename": "index.js",
"size": 21589,
"delta": 563
}
]
},
{
"timestamp": 1575690248030,
"files": [
+60
View File
@@ -1,4 +1,64 @@
[
{
"timestamp": 1576007027792,
"files": [
{
"filename": "index.es.js",
"size": 22461,
"delta": -7
}
]
},
{
"timestamp": 1576004327554,
"files": [
{
"filename": "index.es.js",
"size": 22468,
"delta": 30
}
]
},
{
"timestamp": 1576003439933,
"files": [
{
"filename": "index.es.js",
"size": 22438,
"delta": 656
}
]
},
{
"timestamp": 1575985317929,
"files": [
{
"filename": "index.es.js",
"size": 21782,
"delta": 324
}
]
},
{
"timestamp": 1575910931774,
"files": [
{
"filename": "index.es.js",
"size": 21458,
"delta": 55
}
]
},
{
"timestamp": 1575859200604,
"files": [
{
"filename": "index.es.js",
"size": 21403,
"delta": 561
}
]
},
{
"timestamp": 1575675317538,
"files": [
+70 -57
View File
@@ -3,9 +3,9 @@ import React from 'react'
import {
actions,
functionalUpdate,
mergeProps,
applyPropHooks,
useGetLatest,
useConsumeHookGetter,
makePropGetter,
} from '../utils'
actions.resetHiddenColumns = 'resetHiddenColumns'
@@ -14,12 +14,12 @@ actions.setHiddenColumns = 'setHiddenColumns'
actions.toggleHideAllColumns = 'toggleHideAllColumns'
export const useColumnVisibility = hooks => {
hooks.getToggleHiddenProps = []
hooks.getToggleHideAllColumnsProps = []
hooks.getToggleHiddenProps = [defaultGetToggleHiddenProps]
hooks.getToggleHideAllColumnsProps = [defaultGetToggleHideAllColumnsProps]
hooks.stateReducers.push(reducer)
hooks.useInstanceBeforeDimensions.push(useInstanceBeforeDimensions)
hooks.columnsBeforeHeaderGroupsDeps.push((deps, instance) => [
hooks.headerGroupsDeps.push((deps, instance) => [
...deps,
instance.state.hiddenColumns,
])
@@ -28,6 +28,36 @@ export const useColumnVisibility = hooks => {
useColumnVisibility.pluginName = 'useColumnVisibility'
const defaultGetToggleHiddenProps = (props, instance, column) => [
props,
{
onChange: e => {
column.toggleHidden(!e.target.checked)
},
style: {
cursor: 'pointer',
},
checked: column.isVisible,
title: 'Toggle Column Visible',
},
]
const defaultGetToggleHideAllColumnsProps = (props, instance) => [
props,
{
onChange: e => {
instance.toggleHideAllColumns(!e.target.checked)
},
style: {
cursor: 'pointer',
},
checked: !instance.allColumnsHidden && !instance.state.hiddenColumns.length,
title: 'Toggle All Columns Hidden',
indeterminate:
!instance.allColumnsHidden && instance.state.hiddenColumns.length,
},
]
function reducer(state, action, previousState, instanceRef) {
if (action.type === actions.init) {
return {
@@ -111,8 +141,6 @@ function useInstanceBeforeDimensions(instance) {
headers.forEach(
subHeader => (totalVisibleHeaderCount += handleColumn(subHeader, true))
)
return instance
}
function useInstance(instance) {
@@ -127,33 +155,6 @@ function useInstance(instance) {
const allColumnsHidden = flatColumns.length === hiddenColumns.length
flatHeaders.forEach(column => {
column.toggleHidden = value => {
dispatch({
type: actions.toggleHideColumn,
columnId: column.id,
value,
})
}
column.getToggleHiddenProps = props => {
return mergeProps(
{
onChange: e => {
column.toggleHidden(!e.target.checked)
},
style: {
cursor: 'pointer',
},
checked: column.isVisible,
title: 'Toggle Column Visible',
},
applyPropHooks(getInstance().hooks.getToggleHiddenProps, getInstance()),
props
)
}
})
const toggleHideColumn = React.useCallback(
(columnId, value) =>
dispatch({ type: actions.toggleHideColumn, columnId, value }),
@@ -170,32 +171,44 @@ function useInstance(instance) {
[dispatch]
)
const getToggleHideAllColumnsProps = props => {
return mergeProps(
{
onChange: e => {
toggleHideAllColumns(!e.target.checked)
},
style: {
cursor: 'pointer',
},
checked: !allColumnsHidden && !hiddenColumns.length,
title: 'Toggle All Columns Hidden',
indeterminate: !allColumnsHidden && hiddenColumns.length,
},
applyPropHooks(
getInstance().hooks.getToggleHideAllColumnsProps,
getInstance()
),
props
)
}
// Snapshot hook and disallow more from being added
const getToggleHideAllColumnsPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getToggleHideAllColumnsProps'
)
return {
...instance,
const getToggleHideAllColumnsProps = makePropGetter(
getToggleHideAllColumnsPropsHooks(),
getInstance()
)
// Snapshot hook and disallow more from being added
const getToggleHiddenPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getToggleHiddenProps'
)
flatHeaders.forEach(column => {
column.toggleHidden = value => {
dispatch({
type: actions.toggleHideColumn,
columnId: column.id,
value,
})
}
column.getToggleHiddenProps = makePropGetter(
getToggleHiddenPropsHooks(),
getInstance(),
column
)
})
Object.assign(instance, {
allColumnsHidden,
toggleHideColumn,
setHiddenColumns,
toggleHideAllColumns,
getToggleHideAllColumnsProps,
}
})
}
+225 -193
View File
@@ -3,9 +3,9 @@ import React from 'react'
//
import {
actions,
applyHooks,
applyPropHooks,
mergeProps,
reduceHooks,
loopHooks,
makePropGetter,
flexRender,
decorateColumnTree,
makeHeaderGroups,
@@ -14,6 +14,8 @@ import {
useConsumeHookGetter,
} from '../utils'
import makeDefaultPluginHooks from '../makeDefaultPluginHooks'
import { useColumnVisibility } from './useColumnVisibility'
let renderErr = 'Renderer Error'
@@ -22,63 +24,87 @@ const defaultInitialState = {}
const defaultColumnInstance = {}
const defaultReducer = (state, action, prevState) => state
const defaultGetSubRows = (row, index) => row.subRows || []
const defaultGetRowId = (row, index) => index
const defaultGetRowId = (row, index, parent) =>
`${parent ? [parent.id, index].join('.') : index}`
const defaultUseControlledState = d => d
export const useTable = (props, ...plugins) => {
// Destructure props
let {
data,
columns: userColumns,
function applyDefaults(props) {
const {
initialState = defaultInitialState,
defaultColumn = defaultColumnInstance,
getSubRows = defaultGetSubRows,
getRowId = defaultGetRowId,
stateReducer: userStateReducer = defaultReducer,
stateReducer = defaultReducer,
useControlledState = defaultUseControlledState,
...rest
} = props
return {
...rest,
initialState,
defaultColumn,
getSubRows,
getRowId,
stateReducer,
useControlledState,
}
}
export const useTable = (props, ...plugins) => {
// Apply default props
props = applyDefaults(props)
// Add core plugins
plugins = [useColumnVisibility, ...plugins]
// The table instance
// Create the table instance
let instanceRef = React.useRef({})
Object.assign(instanceRef.current, {
// Create a getter for the instance (helps avoid a lot of potential memory leaks)
const getInstance = useGetLatest(instanceRef.current)
// Assign the props, plugins and hooks to the instance
Object.assign(getInstance(), {
...props,
plugins,
data,
hooks: {
stateReducers: [],
columnsBeforeHeaderGroups: [],
columnsBeforeHeaderGroupsDeps: [],
useInstanceBeforeDimensions: [],
useInstance: [],
useRows: [],
prepareRow: [],
getTableProps: [],
getTableBodyProps: [],
getRowProps: [],
getHeaderGroupProps: [],
getFooterGroupProps: [],
getHeaderProps: [],
getFooterProps: [],
getCellProps: [],
},
hooks: makeDefaultPluginHooks(),
})
// Allow plugins to register hooks as early as possible
plugins.filter(Boolean).forEach(plugin => {
plugin(instanceRef.current.hooks)
plugin(getInstance().hooks)
})
const getUseOptionsHooks = useConsumeHookGetter(
getInstance().hooks,
'useOptions'
)
// Allow useOptions hooks to modify the options coming into the table
Object.assign(
getInstance(),
reduceHooks(getUseOptionsHooks(), applyDefaults(props))
)
const {
data,
columns: userColumns,
initialState,
defaultColumn,
getSubRows,
getRowId,
stateReducer,
useControlledState,
} = getInstance()
// Snapshot hook and disallow more from being added
const getStateReducers = useConsumeHookGetter(
instanceRef.current.hooks,
getInstance().hooks,
'stateReducers'
)
// Setup user reducer ref
const getUserStateReducer = useGetLatest(userStateReducer)
const getStateReducer = useGetLatest(stateReducer)
// Build the reducer
const reducer = React.useCallback(
@@ -93,15 +119,15 @@ export const useTable = (props, ...plugins) => {
return [
...getStateReducers(),
// Allow the user to add their own state reducer(s)
...(Array.isArray(getUserStateReducer())
? getUserStateReducer()
: [getUserStateReducer()]),
...(Array.isArray(getStateReducer())
? getStateReducer()
: [getStateReducer()]),
].reduce(
(s, handler) => handler(s, action, state, instanceRef) || s,
state
)
},
[getStateReducers, getUserStateReducer]
[getStateReducers, getStateReducer]
)
// Start the reducer
@@ -112,82 +138,126 @@ export const useTable = (props, ...plugins) => {
// Allow the user to control the final state with hooks
const state = useControlledState(reducerState)
Object.assign(instanceRef.current, {
state, // The state dispatcher
dispatch, // The resolved table state
Object.assign(getInstance(), {
state,
dispatch,
})
// Snapshot hook and disallow more from being added
const getColumnsHooks = useConsumeHookGetter(getInstance().hooks, 'columns')
// Snapshot hook and disallow more from being added
const getColumnsDepsHooks = useConsumeHookGetter(
getInstance().hooks,
'columnsDeps'
)
// Decorate All the columns
let columns = React.useMemo(
() => decorateColumnTree(userColumns, defaultColumn),
[defaultColumn, userColumns]
() =>
reduceHooks(
getColumnsHooks(),
decorateColumnTree(userColumns, defaultColumn),
getInstance()
),
[
defaultColumn,
getColumnsHooks,
getInstance,
userColumns,
// eslint-disable-next-line react-hooks/exhaustive-deps
...reduceHooks(getColumnsDepsHooks(), [], getInstance()),
]
)
getInstance().columns = columns
// Snapshot hook and disallow more from being added
const getFlatColumns = useConsumeHookGetter(
getInstance().hooks,
'flatColumns'
)
// Snapshot hook and disallow more from being added
const getColumnsBeforeHeaderGroups = useConsumeHookGetter(
instanceRef.current.hooks,
'columnsBeforeHeaderGroups'
)
// Snapshot hook and disallow more from being added
const getColumnsBeforeHeaderGroupsDeps = useConsumeHookGetter(
instanceRef.current.hooks,
'columnsBeforeHeaderGroupsDeps'
const getFlatColumnsDeps = useConsumeHookGetter(
getInstance().hooks,
'flatColumnsDeps'
)
// Get the flat list of all columns and allow hooks to decorate
// those columns (and trigger this memoization via deps)
let flatColumns = React.useMemo(() => {
let newColumns = applyHooks(
getColumnsBeforeHeaderGroups(),
flattenBy(columns, 'columns'),
instanceRef.current
)
let flatColumns = React.useMemo(
() =>
reduceHooks(
getFlatColumns(),
flattenBy(columns, 'columns'),
getInstance()
),
[
columns,
getFlatColumns,
getInstance,
// eslint-disable-next-line react-hooks/exhaustive-deps
...reduceHooks(getFlatColumnsDeps(), [], getInstance()),
]
)
return newColumns
}, [
columns,
getColumnsBeforeHeaderGroups,
// eslint-disable-next-line react-hooks/exhaustive-deps
...getColumnsBeforeHeaderGroupsDeps(),
])
getInstance().flatColumns = flatColumns
// Snapshot hook and disallow more from being added
const getHeaderGroups = useConsumeHookGetter(
getInstance().hooks,
'headerGroups'
)
// Snapshot hook and disallow more from being added
const getHeaderGroupsDeps = useConsumeHookGetter(
getInstance().hooks,
'headerGroupsDeps'
)
// Make the headerGroups
const headerGroups = React.useMemo(
() => makeHeaderGroups(flatColumns, defaultColumn),
[defaultColumn, flatColumns]
() =>
reduceHooks(
getHeaderGroups(),
makeHeaderGroups(flatColumns, defaultColumn),
getInstance()
),
[
defaultColumn,
flatColumns,
getHeaderGroups,
getInstance,
// eslint-disable-next-line react-hooks/exhaustive-deps
...reduceHooks(getHeaderGroupsDeps(), [], getInstance()),
]
)
getInstance().headerGroups = headerGroups
const headers = React.useMemo(
() => (headerGroups.length ? headerGroups[0].headers : []),
[headerGroups]
)
Object.assign(instanceRef.current, {
columns,
flatColumns,
headerGroups,
headers,
})
getInstance().headers = headers
// Access the row model
const [rows, flatRows] = React.useMemo(() => {
let flatRows = []
// Access the row's data
const accessRow = (originalRow, i, depth = 0, parentPath = []) => {
const accessRow = (originalRow, i, depth = 0, parent) => {
// Keep the original reference around
const original = originalRow
const rowId = getRowId(originalRow, i)
// Make the new path for the row
const path = [...parentPath, rowId]
const id = getRowId(originalRow, i, parent)
const row = {
id,
original,
index: i,
path, // used to create a key for each row even if not nested
depth,
cells: [{}], // This is a dummy cell
}
@@ -198,7 +268,7 @@ export const useTable = (props, ...plugins) => {
let subRows = getSubRows(originalRow, i)
if (subRows) {
row.subRows = subRows.map((d, i) => accessRow(d, i, depth + 1, path))
row.subRows = subRows.map((d, i) => accessRow(d, i, depth + 1, row))
}
// Override common array functions (and the dummy cell's getCellProps function)
@@ -228,54 +298,51 @@ export const useTable = (props, ...plugins) => {
const accessedData = data.map((d, i) => accessRow(d, i))
return [accessedData, flatRows]
}, [data, getRowId, getSubRows, flatColumns])
}, [data, flatColumns, getRowId, getSubRows])
instanceRef.current.rows = rows
instanceRef.current.flatRows = flatRows
getInstance().rows = rows
getInstance().flatRows = flatRows
// Provide a flat header list for utilities
instanceRef.current.flatHeaders = headerGroups.reduce(
getInstance().flatHeaders = headerGroups.reduce(
(all, headerGroup) => [...all, ...headerGroup.headers],
[]
)
// Snapshot hook and disallow more from being added
const getUseInstanceBeforeDimensions = useConsumeHookGetter(
instanceRef.current.hooks,
getInstance().hooks,
'useInstanceBeforeDimensions'
)
instanceRef.current = applyHooks(
getUseInstanceBeforeDimensions(),
instanceRef.current
)
loopHooks(getUseInstanceBeforeDimensions(), getInstance())
// Header Visibility is needed by this point
calculateDimensions(instanceRef.current)
getInstance().totalColumnsWidth = calculateHeaderWidths(headers)
// Snapshot hook and disallow more from being added
const getUseInstance = useConsumeHookGetter(
instanceRef.current.hooks,
getInstance().hooks,
'useInstance'
)
instanceRef.current = applyHooks(getUseInstance(), instanceRef.current)
loopHooks(getUseInstance(), getInstance())
// Snapshot hook and disallow more from being added
const getHeaderPropsHooks = useConsumeHookGetter(
instanceRef.current.hooks,
getInstance().hooks,
'getHeaderProps'
)
// Snapshot hook and disallow more from being added
const getFooterPropsHooks = useConsumeHookGetter(
instanceRef.current.hooks,
getInstance().hooks,
'getFooterProps'
)
// Each materialized header needs to be assigned a render function and other
// prop getter properties here.
instanceRef.current.flatHeaders.forEach(column => {
getInstance().flatHeaders.forEach(column => {
// Give columns/headers rendering power
column.render = (type, userProps = {}) => {
const Comp = typeof type === 'string' ? column[type] : type
@@ -285,48 +352,40 @@ export const useTable = (props, ...plugins) => {
}
return flexRender(Comp, {
...instanceRef.current,
...getInstance(),
column,
...userProps,
})
}
// Give columns/headers a default getHeaderProps
column.getHeaderProps = props =>
mergeProps(
{
key: ['header', column.id].join('_'),
colSpan: column.totalVisibleHeaderCount,
},
applyPropHooks(getHeaderPropsHooks(), column, instanceRef.current),
props
)
column.getHeaderProps = makePropGetter(
getHeaderPropsHooks(),
getInstance(),
column
)
// Give columns/headers a default getFooterProps
column.getFooterProps = props =>
mergeProps(
{
key: ['footer', column.id].join('_'),
colSpan: column.totalVisibleHeaderCount,
},
applyPropHooks(getFooterPropsHooks(), column, instanceRef.current),
props
)
column.getFooterProps = makePropGetter(
getFooterPropsHooks(),
getInstance(),
column
)
})
// Snapshot hook and disallow more from being added
const getHeaderGroupPropsHooks = useConsumeHookGetter(
instanceRef.current.hooks,
getInstance().hooks,
'getHeaderGroupProps'
)
// Snapshot hook and disallow more from being added
const getFooterGroupsPropsHooks = useConsumeHookGetter(
instanceRef.current.hooks,
const getFooterGroupPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getFooterGroupProps'
)
instanceRef.current.headerGroups = instanceRef.current.headerGroups.filter(
getInstance().headerGroups = getInstance().headerGroups.filter(
(headerGroup, i) => {
// Filter out any headers and headerGroups that don't have visible columns
headerGroup.headers = headerGroup.headers.filter(column => {
@@ -345,31 +404,19 @@ export const useTable = (props, ...plugins) => {
// Give headerGroups getRowProps
if (headerGroup.headers.length) {
headerGroup.getHeaderGroupProps = (props = {}) =>
mergeProps(
{
key: [`header${i}`].join('_'),
},
applyPropHooks(
getHeaderGroupPropsHooks(),
headerGroup,
instanceRef.current
),
props
)
headerGroup.getHeaderGroupProps = makePropGetter(
getHeaderGroupPropsHooks(),
getInstance(),
headerGroup,
i
)
headerGroup.getFooterGroupProps = (props = {}) =>
mergeProps(
{
key: [`footer${i}`].join('_'),
},
applyPropHooks(
getFooterGroupsPropsHooks(),
headerGroup,
instanceRef.current
),
props
)
headerGroup.getFooterGroupProps = makePropGetter(
getFooterGroupPropsHooks(),
getInstance(),
headerGroup,
i
)
return true
}
@@ -378,22 +425,17 @@ export const useTable = (props, ...plugins) => {
}
)
instanceRef.current.footerGroups = [
...instanceRef.current.headerGroups,
].reverse()
getInstance().footerGroups = [...getInstance().headerGroups].reverse()
// Run the rows (this could be a dangerous hook with a ton of data)
// Snapshot hook and disallow more from being added
const getUseRowsHooks = useConsumeHookGetter(
instanceRef.current.hooks,
'useRows'
)
const getUseRowsHooks = useConsumeHookGetter(getInstance().hooks, 'useRows')
instanceRef.current.rows = applyHooks(
getInstance().rows = reduceHooks(
getUseRowsHooks(),
instanceRef.current.rows,
instanceRef.current
getInstance().rows,
getInstance()
)
// The prepareRow function is absolutely necessary and MUST be called on
@@ -401,34 +443,29 @@ export const useTable = (props, ...plugins) => {
// Snapshot hook and disallow more from being added
const getPrepareRowHooks = useConsumeHookGetter(
instanceRef.current.hooks,
getInstance().hooks,
'prepareRow'
)
// Snapshot hook and disallow more from being added
const getRowPropsHooks = useConsumeHookGetter(
instanceRef.current.hooks,
getInstance().hooks,
'getRowProps'
)
// Snapshot hook and disallow more from being added
const getCellPropsHooks = useConsumeHookGetter(
instanceRef.current.hooks,
getInstance().hooks,
'getCellProps'
)
instanceRef.current.prepareRow = React.useCallback(
getInstance().prepareRow = React.useCallback(
row => {
row.getRowProps = props =>
mergeProps(
{ key: ['row', ...row.path].join('_') },
applyPropHooks(getRowPropsHooks(), row, instanceRef.current),
props
)
row.getRowProps = makePropGetter(getRowPropsHooks(), getInstance(), row)
// Build the visible cells for each row
row.cells = instanceRef.current.flatColumns
.filter(d => d.isVisible)
row.cells = getInstance()
.flatColumns.filter(d => d.isVisible)
.map(column => {
const cell = {
column,
@@ -437,16 +474,11 @@ export const useTable = (props, ...plugins) => {
}
// Give each cell a getCellProps base
cell.getCellProps = props => {
const columnPathStr = [...row.path, column.id].join('_')
return mergeProps(
{
key: ['cell', columnPathStr].join('_'),
},
applyPropHooks(getCellPropsHooks(), cell, instanceRef.current),
props
)
}
cell.getCellProps = makePropGetter(
getCellPropsHooks(),
getInstance(),
cell
)
// Give each cell a renderer function (supports multiple renderers)
cell.render = (type, userProps = {}) => {
@@ -457,7 +489,7 @@ export const useTable = (props, ...plugins) => {
}
return flexRender(Comp, {
...instanceRef.current,
...getInstance(),
column,
row,
cell,
@@ -469,42 +501,42 @@ export const useTable = (props, ...plugins) => {
})
// need to apply any row specific hooks (useExpanded requires this)
applyHooks(getPrepareRowHooks(), row, instanceRef.current)
loopHooks(getPrepareRowHooks(), row, getInstance())
},
[getCellPropsHooks, getPrepareRowHooks, getRowPropsHooks]
[getCellPropsHooks, getInstance, getPrepareRowHooks, getRowPropsHooks]
)
// Snapshot hook and disallow more from being added
const getTablePropsHooks = useConsumeHookGetter(
instanceRef.current.hooks,
getInstance().hooks,
'getTableProps'
)
instanceRef.current.getTableProps = userProps =>
mergeProps(
applyPropHooks(getTablePropsHooks(), instanceRef.current),
userProps
)
getInstance().getTableProps = makePropGetter(
getTablePropsHooks(),
getInstance()
)
// Snapshot hook and disallow more from being added
const getTableBodyPropsHooks = useConsumeHookGetter(
instanceRef.current.hooks,
getInstance().hooks,
'getTableBodyProps'
)
instanceRef.current.getTableBodyProps = userProps =>
mergeProps(
applyPropHooks(getTableBodyPropsHooks(), instanceRef.current),
userProps
)
getInstance().getTableBodyProps = makePropGetter(
getTableBodyPropsHooks(),
getInstance()
)
return instanceRef.current
}
// Snapshot hook and disallow more from being added
const getUseFinalInstanceHooks = useConsumeHookGetter(
getInstance().hooks,
'useFinalInstance'
)
function calculateDimensions(instance) {
const { headers } = instance
loopHooks(getUseFinalInstanceHooks(), [], getInstance())
instance.totalColumnsWidth = calculateHeaderWidths(headers)
return getInstance()
}
function calculateHeaderWidths(headers, left = 0) {
+57
View File
@@ -0,0 +1,57 @@
const defaultGetHeaderProps = (props, instance, column) => ({
key: ['header', column.id].join('_'),
colSpan: column.totalVisibleHeaderCount,
...props,
})
const defaultGetFooterProps = (props, instance, column) => ({
key: ['footer', column.id].join('_'),
colSpan: column.totalVisibleHeaderCount,
...props,
})
const defaultGetHeaderGroupProps = (props, instance, headerGroup, index) => ({
key: ['header', index].join('_'),
...props,
})
const defaultGetFooterGroupProps = (props, instance, headerGroup, index) => ({
key: ['footer', index].join('_'),
...props,
})
const defaultGetRowProps = (props, instance, row) => ({
key: ['row', row.id].join('_'),
...props,
})
const defaultGetCellProps = (props, instance, cell) => ({
...props,
key: ['cell', cell.row.id, cell.column.id].join('_'),
})
export default function makeDefaultPluginHooks() {
return {
useOptions: [],
stateReducers: [],
columns: [],
columnsDeps: [],
flatColumns: [],
flatColumnsDeps: [],
headerGroups: [],
headerGroupsDeps: [],
useInstanceBeforeDimensions: [],
useInstance: [],
useRows: [],
prepareRow: [],
getTableProps: [],
getTableBodyProps: [],
getHeaderGroupProps: [defaultGetHeaderGroupProps],
getFooterGroupProps: [defaultGetFooterGroupProps],
getHeaderProps: [defaultGetHeaderProps],
getFooterProps: [defaultGetFooterProps],
getRowProps: [defaultGetRowProps],
getCellProps: [defaultGetCellProps],
useFinalInstance: [],
}
}
@@ -485,8 +485,8 @@ Snapshot Diff:
<pre>
<code>
{
- "selectedRowPaths": []
+ "selectedRowPaths": [
- "selectedRowIds": []
+ "selectedRowIds": [
+ "0",
+ "1",
+ "2",
@@ -1015,7 +1015,7 @@ Snapshot Diff:
<pre>
<code>
{
- "selectedRowPaths": [
- "selectedRowIds": [
- "0",
- "1",
- "2",
@@ -1053,7 +1053,7 @@ Snapshot Diff:
- "22.1",
- "23"
- ]
+ "selectedRowPaths": []
+ "selectedRowIds": []
}
</code>
</pre>
@@ -1129,8 +1129,8 @@ Snapshot Diff:
<pre>
<code>
{
- "selectedRowPaths": []
+ "selectedRowPaths": [
- "selectedRowIds": []
+ "selectedRowIds": [
+ "0",
+ "2",
+ "2.0",
@@ -1198,7 +1198,7 @@ Snapshot Diff:
<pre>
<code>
{
"selectedRowPaths": [
"selectedRowIds": [
- "0",
- "2",
- "2.0",
@@ -1241,7 +1241,7 @@ Snapshot Diff:
<pre>
<code>
{
"selectedRowPaths": [
"selectedRowIds": [
- "0"
+ "0",
+ "2.0"
@@ -1257,6 +1257,19 @@ Snapshot Diff:
- First value
+ Second value
@@ -163,11 +163,11 @@
</label>
</div>
</td>
<td>
<div>
- Row 2 Not Selected
+ Row 2 Selected
</div>
</td>
<td>
joe
</td>
@@ -237,11 +237,11 @@
</label>
</div>
@@ -1282,7 +1295,7 @@ Snapshot Diff:
<pre>
<code>
{
"selectedRowPaths": [
"selectedRowIds": [
"0",
- "2.0"
+ "2.0",
@@ -1299,6 +1312,19 @@ Snapshot Diff:
- First value
+ Second value
@@ -163,11 +163,11 @@
</label>
</div>
</td>
<td>
<div>
- Row 2 Selected
+ Row 2 Not Selected
</div>
</td>
<td>
joe
</td>
@@ -237,11 +237,11 @@
</label>
</div>
@@ -1324,7 +1350,7 @@ Snapshot Diff:
<pre>
<code>
{
"selectedRowPaths": [
"selectedRowIds": [
"0",
- "2.0",
- "2.1"
+19 -7
View File
@@ -75,7 +75,7 @@ function Table({ columns, data }) {
headerGroups,
rows,
prepareRow,
state: { selectedRowPaths },
state: { selectedRowIds },
} = useTable(
{
columns,
@@ -113,11 +113,11 @@ function Table({ columns, data }) {
)}
</tbody>
</table>
<p>Selected Rows: {selectedRowPaths.size}</p>
<p>Selected Rows: {selectedRowIds.size}</p>
<pre>
<code>
{JSON.stringify(
{ selectedRowPaths: [...selectedRowPaths.values()] },
{ selectedRowIds: [...selectedRowIds.values()] },
null,
2
)}
@@ -127,6 +127,19 @@ function Table({ columns, data }) {
)
}
const IndeterminateCheckbox = React.forwardRef(
({ indeterminate, ...rest }, ref) => {
const defaultRef = React.useRef()
const resolvedRef = ref || defaultRef
React.useEffect(() => {
resolvedRef.current.indeterminate = indeterminate
}, [resolvedRef, indeterminate])
return <input type="checkbox" ref={resolvedRef} {...rest} />
}
)
function App() {
const columns = React.useMemo(
() => [
@@ -138,7 +151,7 @@ function App() {
Header: ({ getToggleAllRowsSelectedProps }) => (
<div>
<label>
<input type="checkbox" {...getToggleAllRowsSelectedProps()} />{' '}
<IndeterminateCheckbox {...getToggleAllRowsSelectedProps()} />{' '}
Select All
</label>
</div>
@@ -148,7 +161,7 @@ function App() {
Cell: ({ row }) => (
<div>
<label>
<input type="checkbox" {...row.getToggleRowSelectedProps()} />{' '}
<IndeterminateCheckbox {...row.getToggleRowSelectedProps()} />{' '}
Select Row
</label>
</div>
@@ -158,8 +171,7 @@ function App() {
id: 'selectedStatus',
Cell: ({ row }) => (
<div>
Row {row.path.join('.')}{' '}
{row.isSelected ? 'Selected' : 'Not Selected'}
Row {row.id} {row.isSelected ? 'Selected' : 'Not Selected'}
</div>
),
},
+30 -42
View File
@@ -1,57 +1,45 @@
export const useAbsoluteLayout = hooks => {
hooks.useInstance.push(useInstance)
// Calculating column/cells widths
const cellStyles = {
position: 'absolute',
top: 0,
}
useAbsoluteLayout.pluginName = 'useAbsoluteLayout'
export const useAbsoluteLayout = hooks => {
hooks.getTableBodyProps.push(getRowStyles)
hooks.getRowProps.push(getRowStyles)
hooks.getHeaderGroupProps.push(getRowStyles)
const useInstance = instance => {
const {
totalColumnsWidth,
hooks: {
getRowProps,
getTableBodyProps,
getHeaderGroupProps,
getHeaderProps,
getCellProps,
},
} = instance
const rowStyles = {
style: {
position: 'relative',
width: `${totalColumnsWidth}px`,
},
}
getTableBodyProps.push(() => rowStyles)
getRowProps.push(() => rowStyles)
getHeaderGroupProps.push(() => rowStyles)
// Calculating column/cells widths
const cellStyles = {
position: 'absolute',
top: 0,
}
getHeaderProps.push(header => {
return {
hooks.getHeaderProps.push((props, instance, header) => [
props,
{
style: {
...cellStyles,
left: `${header.totalLeft}px`,
width: `${header.totalWidth}px`,
},
}
})
},
])
getCellProps.push(cell => {
return {
hooks.getCellProps.push((props, instance, cell) => [
props,
{
style: {
...cellStyles,
left: `${cell.column.totalLeft}px`,
width: `${cell.column.totalWidth}px`,
},
}
})
return instance
},
])
}
useAbsoluteLayout.pluginName = 'useAbsoluteLayout'
const getRowStyles = (props, instance) => [
props,
{
style: {
position: 'relative',
width: `${instance.totalColumnsWidth}px`,
},
},
]
+24 -30
View File
@@ -1,47 +1,41 @@
export const useBlockLayout = hooks => {
hooks.useInstance.push(useInstance)
const cellStyles = {
display: 'inline-block',
boxSizing: 'border-box',
}
useBlockLayout.pluginName = 'useBlockLayout'
const useInstance = instance => {
const {
totalColumnsWidth,
hooks: { getRowProps, getHeaderGroupProps, getHeaderProps, getCellProps },
} = instance
const rowStyles = {
const getRowStyles = (props, instance) => [
props,
{
style: {
display: 'flex',
width: `${totalColumnsWidth}px`,
width: `${instance.totalColumnsWidth}px`,
},
}
},
]
getRowProps.push(() => rowStyles)
getHeaderGroupProps.push(() => rowStyles)
export const useBlockLayout = hooks => {
hooks.getRowProps.push(getRowStyles)
hooks.getHeaderGroupProps.push(getRowStyles)
const cellStyles = {
display: 'inline-block',
boxSizing: 'border-box',
}
getHeaderProps.push(header => {
return {
hooks.getHeaderProps.push((props, instance, header) => [
props,
{
style: {
...cellStyles,
width: `${header.totalWidth}px`,
},
}
})
},
])
getCellProps.push(cell => {
return {
hooks.getCellProps.push((props, instance, cell) => [
props,
{
style: {
...cellStyles,
width: `${cell.column.totalWidth}px`,
},
}
})
return instance
},
])
}
useBlockLayout.pluginName = 'useBlockLayout'
+4 -9
View File
@@ -8,10 +8,10 @@ actions.setColumnOrder = 'setColumnOrder'
export const useColumnOrder = hooks => {
hooks.stateReducers.push(reducer)
hooks.columnsBeforeHeaderGroupsDeps.push((deps, instance) => {
hooks.flatColumnsDeps.push((deps, instance) => {
return [...deps, instance.state.columnOrder]
})
hooks.columnsBeforeHeaderGroups.push(columnsBeforeHeaderGroups)
hooks.flatColumns.push(flatColumns)
hooks.useInstance.push(useInstance)
}
@@ -40,7 +40,7 @@ function reducer(state, action) {
}
}
function columnsBeforeHeaderGroups(columns, instance) {
function flatColumns(columns, instance) {
const {
state: { columnOrder },
} = instance
@@ -74,15 +74,10 @@ function columnsBeforeHeaderGroups(columns, instance) {
function useInstance(instance) {
const { dispatch } = instance
const setColumnOrder = React.useCallback(
instance.setColumnOrder = React.useCallback(
columnOrder => {
return dispatch({ type: actions.setColumnOrder, columnOrder })
},
[dispatch]
)
return {
...instance,
setColumnOrder,
}
}
+47 -45
View File
@@ -2,26 +2,39 @@ import React from 'react'
import {
actions,
mergeProps,
applyPropHooks,
makePropGetter,
expandRows,
useMountedLayoutEffect,
useGetLatest,
} from '../utils'
import { useConsumeHookGetter } from '../publicUtils'
// Actions
actions.toggleExpandedByPath = 'toggleExpandedByPath'
actions.toggleExpandedById = 'toggleExpandedById'
actions.resetExpanded = 'resetExpanded'
export const useExpanded = hooks => {
hooks.getExpandedToggleProps = []
hooks.getExpandedToggleProps = [defaultGetExpandedToggleProps]
hooks.stateReducers.push(reducer)
hooks.useInstance.push(useInstance)
}
useExpanded.pluginName = 'useExpanded'
const defaultGetExpandedToggleProps = (props, instance, row) => [
props,
{
onClick: e => {
e.persist()
row.toggleExpanded()
},
style: {
cursor: 'pointer',
},
title: 'Toggle Expanded',
},
]
// Reducer
function reducer(state, action) {
if (action.type === actions.init) {
@@ -38,17 +51,16 @@ function reducer(state, action) {
}
}
if (action.type === actions.toggleExpandedByPath) {
const { path, expanded } = action
const key = path.join('.')
const exists = state.expanded.includes(key)
if (action.type === actions.toggleExpandedById) {
const { id, expanded } = action
const exists = state.expanded.includes(id)
const shouldExist = typeof expanded !== 'undefined' ? expanded : !exists
let newExpanded = new Set(state.expanded)
if (!exists && shouldExist) {
newExpanded.add(key)
newExpanded.add(id)
} else if (exists && !shouldExist) {
newExpanded.delete(key)
newExpanded.delete(id)
} else {
return state
}
@@ -82,37 +94,26 @@ function useInstance(instance) {
}
}, [dispatch, data])
const toggleExpandedByPath = (path, expanded) => {
dispatch({ type: actions.toggleExpandedByPath, path, expanded })
const toggleExpandedById = (id, expanded) => {
dispatch({ type: actions.toggleExpandedById, id, expanded })
}
// use reference to avoid memory leak in #1608
const instanceRef = React.useRef()
instanceRef.current = instance
const getInstance = useGetLatest(instance)
const getExpandedTogglePropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getExpandedToggleProps'
)
hooks.prepareRow.push(row => {
row.toggleExpanded = set => toggleExpandedByPath(row.path, set)
row.getExpandedToggleProps = props => {
return mergeProps(
{
onClick: e => {
e.persist()
row.toggleExpanded()
},
style: {
cursor: 'pointer',
},
title: 'Toggle Expanded',
},
applyPropHooks(
instanceRef.current.hooks.getExpandedToggleProps,
row,
instanceRef.current
),
props
)
}
return row
row.toggleExpanded = set => instance.toggleExpandedById(row.id, set)
row.getExpandedToggleProps = makePropGetter(
getExpandedTogglePropsHooks(),
getInstance(),
row
)
})
const expandedRows = React.useMemo(() => {
@@ -125,20 +126,21 @@ function useInstance(instance) {
const expandedDepth = findExpandedDepth(expanded)
return {
...instance,
toggleExpandedByPath,
expandedDepth,
Object.assign(instance, {
toggleExpandedById,
preExpandedRows: rows,
expandedRows,
rows: expandedRows,
}
expandedDepth,
})
}
function findExpandedDepth(expanded) {
let maxDepth = 0
expanded.forEach(key => {
const path = key.split('.')
maxDepth = Math.max(maxDepth, path.length)
expanded.forEach(id => {
const splitId = id.split('.')
maxDepth = Math.max(maxDepth, splitId.length)
})
return maxDepth
+6 -8
View File
@@ -117,9 +117,6 @@ function useInstance(instance) {
autoResetFilters = true,
} = instance
const preFilteredRows = rows
const preFilteredFlatRows = flatRows
const setFilter = (columnId, filterValue) => {
dispatch({ type: actions.setFilter, columnId, filterValue })
}
@@ -265,15 +262,16 @@ function useInstance(instance) {
}
}, [dispatch, manualFilters ? null : data])
return {
...instance,
Object.assign(instance, {
setFilter,
setAllFilters,
preFilteredRows,
preFilteredFlatRows,
preFilteredRows: rows,
preFilteredFlatRows: flatRows,
filteredRows,
filteredFlatRows,
rows: filteredRows,
flatRows: filteredFlatRows,
}
})
}
function shouldAutoRemove(autoRemove, value) {
+41 -44
View File
@@ -3,31 +3,48 @@ import React from 'react'
import * as aggregations from '../aggregations'
import {
actions,
mergeProps,
applyPropHooks,
makePropGetter,
defaultGroupByFn,
getFirstDefined,
ensurePluginOrder,
useMountedLayoutEffect,
useGetLatest,
} from '../utils'
import { useConsumeHookGetter } from '../publicUtils'
// Actions
actions.resetGroupBy = 'resetGroupBy'
actions.toggleGroupBy = 'toggleGroupBy'
export const useGroupBy = hooks => {
hooks.getGroupByToggleProps = [defaultGetGroupByToggleProps]
hooks.stateReducers.push(reducer)
hooks.columnsBeforeHeaderGroupsDeps.push((deps, instance) => [
hooks.flatColumnsDeps.push((deps, instance) => [
...deps,
instance.state.groupBy,
])
hooks.columnsBeforeHeaderGroups.push(columnsBeforeHeaderGroups)
hooks.flatColumns.push(flatColumns)
hooks.useInstance.push(useInstance)
}
useGroupBy.pluginName = 'useGroupBy'
const defaultGetGroupByToggleProps = (props, instance, header) => [
props,
{
onClick: header.canGroupBy
? e => {
e.persist()
header.toggleGroupBy()
}
: undefined,
style: {
cursor: header.canGroupBy ? 'pointer' : undefined,
},
title: 'Toggle GroupBy',
},
]
// Reducer
function reducer(state, action) {
if (action.type === actions.init) {
@@ -64,7 +81,7 @@ function reducer(state, action) {
}
}
function columnsBeforeHeaderGroups(flatColumns, { state: { groupBy } }) {
function flatColumns(flatColumns, { state: { groupBy } }) {
// Sort grouped columns to the start of the column list
// before the headers are built
@@ -106,6 +123,8 @@ function useInstance(instance) {
ensurePluginOrder(plugins, [], 'useGroupBy', ['useSortBy', 'useExpanded'])
const getInstance = useGetLatest(instance)
flatColumns.forEach(column => {
const {
id,
@@ -135,36 +154,17 @@ function useInstance(instance) {
dispatch({ type: actions.toggleGroupBy, columnId, toggle })
}
hooks.getGroupByToggleProps = []
// use reference to avoid memory leak in #1608
const instanceRef = React.useRef()
instanceRef.current = instance
const getGroupByTogglePropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getGroupByToggleProps'
)
flatHeaders.forEach(header => {
const { canGroupBy } = header
header.getGroupByToggleProps = props => {
return mergeProps(
{
onClick: canGroupBy
? e => {
e.persist()
header.toggleGroupBy()
}
: undefined,
style: {
cursor: canGroupBy ? 'pointer' : undefined,
},
title: 'Toggle GroupBy',
},
applyPropHooks(
instanceRef.current.hooks.getGroupByToggleProps,
header,
instanceRef.current
),
props
)
}
header.getGroupByToggleProps = makePropGetter(
getGroupByTogglePropsHooks(),
getInstance(),
header
)
})
hooks.prepareRow.push(row => {
@@ -177,7 +177,6 @@ function useInstance(instance) {
cell.isAggregated =
!cell.isGrouped && !cell.isRepeatedValue && row.canExpand
})
return row
})
const [groupedRows, groupedFlatRows] = React.useMemo(() => {
@@ -237,12 +236,9 @@ function useInstance(instance) {
let groupedFlatRows = []
// Recursively group the data
const groupRecursively = (rows, depth = 0, parentPath = []) => {
const groupRecursively = (rows, depth = 0) => {
// This is the last level, just return the rows
if (depth >= groupBy.length) {
rows.forEach(row => {
row.path = [...parentPath, ...row.path]
})
groupedFlatRows = groupedFlatRows.concat(rows)
return rows
}
@@ -255,13 +251,14 @@ function useInstance(instance) {
// Recurse to sub rows before aggregation
groupedRows = Object.entries(groupedRows).map(
([groupByVal, subRows], index) => {
const path = [...parentPath, `${columnId}:${groupByVal}`]
const id = `${columnId}:${groupByVal}`
subRows = groupRecursively(subRows, depth + 1, path)
subRows = groupRecursively(subRows, depth + 1)
const values = aggregateRowsToValues(subRows, depth < groupBy.length)
const row = {
id,
isAggregated: true,
groupByID: columnId,
groupByVal,
@@ -269,7 +266,6 @@ function useInstance(instance) {
subRows,
depth,
index,
path,
}
groupedFlatRows.push(row)
@@ -303,11 +299,12 @@ function useInstance(instance) {
}
}, [dispatch, manaulGroupBy ? null : data])
return {
...instance,
Object.assign(instance, {
groupedRows,
groupedFlatRows,
toggleGroupBy,
rows: groupedRows,
flatRows: groupedFlatRows,
preGroupedRows: rows,
}
})
}
+2 -5
View File
@@ -168,8 +168,7 @@ function useInstance(instance) {
[dispatch]
)
return {
...instance,
Object.assign(instance, {
pageOptions,
pageCount,
page,
@@ -179,7 +178,5 @@ function useInstance(instance) {
previousPage,
nextPage,
setPageSize,
pageIndex,
pageSize,
}
})
}
+113 -62
View File
@@ -2,10 +2,10 @@ import {
actions,
defaultColumn,
getFirstDefined,
mergeProps,
applyPropHooks,
makePropGetter,
useGetLatest,
} from '../utils'
import { useConsumeHookGetter } from '../publicUtils'
// Default Column
defaultColumn.canResize = true
@@ -16,10 +16,107 @@ actions.columnResizing = 'columnResizing'
actions.columnDoneResizing = 'columnDoneResizing'
export const useResizeColumns = hooks => {
hooks.getResizerProps = [defaultGetResizerProps]
hooks.stateReducers.push(reducer)
hooks.useInstanceBeforeDimensions.push(useInstanceBeforeDimensions)
}
const defaultGetResizerProps = (props, instance, header) => {
const { dispatch } = instance
const onResizeStart = (e, header) => {
let isTouchEvent = false
if (e.type === 'touchstart') {
// lets not respond to multiple touches (e.g. 2 or 3 fingers)
if (e.touches && e.touches.length > 1) {
return
}
isTouchEvent = true
}
const headersToResize = getLeafHeaders(header)
const headerIdWidths = headersToResize.map(d => [d.id, d.totalWidth])
const clientX = isTouchEvent ? Math.round(e.touches[0].clientX) : e.clientX
const dispatchMove = clientXPos => {
dispatch({ type: actions.columnResizing, clientX: clientXPos })
}
const dispatchEnd = () => dispatch({ type: actions.columnDoneResizing })
const handlersAndEvents = {
mouse: {
moveEvent: 'mousemove',
moveHandler: e => dispatchMove(e.clientX),
upEvent: 'mouseup',
upHandler: e => {
document.removeEventListener(
'mousemove',
handlersAndEvents.mouse.moveHandler
)
document.removeEventListener(
'mouseup',
handlersAndEvents.mouse.upHandler
)
dispatchEnd()
},
},
touch: {
moveEvent: 'touchmove',
moveHandler: e => {
if (e.cancelable) {
e.preventDefault()
e.stopPropagation()
}
dispatchMove(e.touches[0].clientX)
return false
},
upEvent: 'touchend',
upHandler: e => {
document.removeEventListener(
handlersAndEvents.touch.moveEvent,
handlersAndEvents.touch.moveHandler
)
document.removeEventListener(
handlersAndEvents.touch.upEvent,
handlersAndEvents.touch.moveHandler
)
dispatchEnd()
},
},
}
const events = isTouchEvent
? handlersAndEvents.touch
: handlersAndEvents.mouse
document.addEventListener(events.moveEvent, events.moveHandler, {
passive: false,
})
document.addEventListener(events.upEvent, events.upHandler, {
passive: false,
})
dispatch({
type: actions.columnStartResizing,
columnId: header.id,
columnWidth: header.totalWidth,
headerIdWidths,
clientX,
})
}
return [
props,
{
onMouseDown: e => e.persist() || onResizeStart(e, header),
onTouchStart: e => e.persist() || onResizeStart(e, header),
style: {
cursor: 'ew-resize',
},
draggable: false,
},
]
}
useResizeColumns.pluginName = 'useResizeColumns'
function reducer(state, action) {
@@ -88,58 +185,26 @@ function reducer(state, action) {
}
const useInstanceBeforeDimensions = instance => {
instance.hooks.getResizerProps = []
const {
flatHeaders,
disableResizing,
hooks: { getHeaderProps },
state: { columnResizing },
dispatch,
} = instance
getHeaderProps.push(() => {
return {
style: {
position: 'relative',
},
}
getHeaderProps.push({
style: {
position: 'relative',
},
})
const onMouseDown = (e, header) => {
const headersToResize = getLeafHeaders(header)
const headerIdWidths = headersToResize.map(d => [d.id, d.totalWidth])
const clientX = e.clientX
const onMouseMove = e => {
const clientX = e.clientX
dispatch({ type: actions.columnResizing, clientX })
}
const onMouseUp = e => {
document.removeEventListener('mousemove', onMouseMove)
document.removeEventListener('mouseup', onMouseUp)
dispatch({ type: actions.columnDoneResizing })
}
document.addEventListener('mousemove', onMouseMove)
document.addEventListener('mouseup', onMouseUp)
dispatch({
type: actions.columnStartResizing,
columnId: header.id,
columnWidth: header.totalWidth,
headerIdWidths,
clientX,
})
}
// use reference to avoid memory leak in #1608
const getInstance = useGetLatest(instance)
const getResizerPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getResizerProps'
)
flatHeaders.forEach(header => {
const canResize = getFirstDefined(
header.disableResizing === true ? false : undefined,
@@ -152,27 +217,13 @@ const useInstanceBeforeDimensions = instance => {
header.isResizing = columnResizing.isResizingColumn === header.id
if (canResize) {
header.getResizerProps = userProps => {
return mergeProps(
{
onMouseDown: e => e.persist() || onMouseDown(e, header),
style: {
cursor: 'ew-resize',
},
draggable: false,
},
applyPropHooks(
getInstance().hooks.getResizerProps,
header,
getInstance()
),
userProps
)
}
header.getResizerProps = makePropGetter(
getResizerPropsHooks(),
getInstance(),
header
)
}
})
return instance
}
function getLeafHeaders(header) {
+152 -131
View File
@@ -2,24 +2,23 @@ import React from 'react'
import {
actions,
mergeProps,
applyPropHooks,
makePropGetter,
ensurePluginOrder,
useGetLatest,
useMountedLayoutEffect,
useConsumeHookGetter,
} from '../utils'
const pluginName = 'useRowSelect'
// Actions
actions.resetSelectedRows = 'resetSelectedRows'
actions.toggleRowSelectedAll = 'toggleRowSelectedAll'
actions.toggleAllRowsSelected = 'toggleAllRowsSelected'
actions.toggleRowSelected = 'toggleRowSelected'
export const useRowSelect = hooks => {
hooks.getToggleRowSelectedProps = []
hooks.getToggleAllRowsSelectedProps = []
hooks.getToggleRowSelectedProps = [defaultGetToggleRowSelectedProps]
hooks.getToggleAllRowsSelectedProps = [defaultGetToggleAllRowsSelectedProps]
hooks.stateReducers.push(reducer)
hooks.useRows.push(useRows)
hooks.useInstance.push(useInstance)
@@ -27,10 +26,53 @@ export const useRowSelect = hooks => {
useRowSelect.pluginName = pluginName
const defaultGetToggleRowSelectedProps = (props, instance, row) => {
const { manualRowSelectedKey = 'isSelected' } = instance
let checked = false
if (row.original && row.original[manualRowSelectedKey]) {
checked = true
} else {
checked = row.isSelected
}
return [
props,
{
onChange: e => {
row.toggleRowSelected(e.target.checked)
},
style: {
cursor: 'pointer',
},
checked,
title: 'Toggle Row Selected',
indeterminate: row.isSomeSelected,
},
]
}
const defaultGetToggleAllRowsSelectedProps = (props, instance) => [
props,
{
onChange: e => {
instance.toggleAllRowsSelected(e.target.checked)
},
style: {
cursor: 'pointer',
},
checked: instance.isAllRowsSelected,
title: 'Toggle All Rows Selected',
indeterminate: Boolean(
!instance.isAllRowsSelected && instance.state.selectedRowIds.size
),
},
]
function reducer(state, action, previousState, instanceRef) {
if (action.type === actions.init) {
return {
selectedRowPaths: new Set(),
selectedRowIds: new Set(),
...state,
}
}
@@ -38,103 +80,85 @@ function reducer(state, action, previousState, instanceRef) {
if (action.type === actions.resetSelectedRows) {
return {
...state,
selectedRowPaths: new Set(),
selectedRowIds: new Set(),
}
}
if (action.type === actions.toggleRowSelectedAll) {
if (action.type === actions.toggleAllRowsSelected) {
const { selected } = action
const { isAllRowsSelected, flatRowPaths } = instanceRef.current
const { isAllRowsSelected, flatRowsById } = instanceRef.current
const selectAll =
typeof selected !== 'undefined' ? selected : !isAllRowsSelected
return {
...state,
selectedRowPaths: selectAll ? new Set(flatRowPaths) : new Set(),
selectedRowIds: selectAll ? new Set(flatRowsById.keys()) : new Set(),
}
}
if (action.type === actions.toggleRowSelected) {
const { path, selected } = action
const { flatRowPaths } = instanceRef.current
const { id, selected } = action
const { flatGroupedRowsById } = instanceRef.current
const key = path.join('.')
const childRowPrefixKey = [key, '.'].join('')
// Join the paths of deep rows
// Join the ids of deep rows
// to make a key, then manage all of the keys
// in a flat object
const exists = state.selectedRowPaths.has(key)
const shouldExist = typeof set !== 'undefined' ? selected : !exists
const row = flatGroupedRowsById.get(id)
const isSelected = row.isSelected
const shouldExist = typeof set !== 'undefined' ? selected : !isSelected
let newSelectedRowPaths = new Set(state.selectedRowPaths)
if (!exists && shouldExist) {
flatRowPaths.forEach(rowPath => {
if (rowPath === key || rowPath.startsWith(childRowPrefixKey)) {
newSelectedRowPaths.add(rowPath)
}
})
} else if (exists && !shouldExist) {
flatRowPaths.forEach(rowPath => {
if (rowPath === key || rowPath.startsWith(childRowPrefixKey)) {
newSelectedRowPaths.delete(rowPath)
}
})
} else {
if (isSelected === shouldExist) {
return state
}
const updateParentRow = (selectedRowPaths, path) => {
const parentPath = path.slice(0, path.length - 1)
const parentKey = parentPath.join('.')
const selected =
flatRowPaths.filter(rowPath => {
const path = rowPath
return (
path !== parentKey &&
path.startsWith(parentKey) &&
!selectedRowPaths.has(path)
)
}).length === 0
if (selected) {
selectedRowPaths.add(parentKey)
} else {
selectedRowPaths.delete(parentKey)
let newSelectedRowPaths = new Set(state.selectedRowIds)
const handleRowById = id => {
const row = flatGroupedRowsById.get(id)
if (!row.isAggregated) {
if (!isSelected && shouldExist) {
newSelectedRowPaths.add(id)
} else if (isSelected && !shouldExist) {
newSelectedRowPaths.delete(id)
}
}
if (row.subRows) {
return row.subRows.forEach(row => handleRowById(row.id))
}
if (parentPath.length > 1) updateParentRow(selectedRowPaths, parentPath)
}
// If the row is a subRow update
// its parent row to reflect changes
if (path.length > 1) updateParentRow(newSelectedRowPaths, path)
handleRowById(id)
return {
...state,
selectedRowPaths: newSelectedRowPaths,
selectedRowIds: newSelectedRowPaths,
}
}
}
function useRows(rows, instance) {
const {
state: { selectedRowPaths },
state: { selectedRowIds },
} = instance
instance.selectedFlatRows = React.useMemo(() => {
const selectedFlatRows = []
rows.forEach(row => {
row.isSelected = getRowIsSelected(row, selectedRowPaths)
const isSelected = getRowIsSelected(row, selectedRowIds)
row.isSelected = !!isSelected
row.isSomeSelected = isSelected === null
if (row.isSelected) {
if (isSelected) {
selectedFlatRows.push(row)
}
})
return selectedFlatRows
}, [rows, selectedRowPaths])
}, [rows, selectedRowIds])
return rows
}
@@ -143,11 +167,10 @@ function useInstance(instance) {
const {
data,
hooks,
manualRowSelectedKey = 'isSelected',
plugins,
flatRows,
autoResetSelectedRows = true,
state: { selectedRowPaths },
state: { selectedRowIds },
dispatch,
} = instance
@@ -158,12 +181,24 @@ function useInstance(instance) {
[]
)
const flatRowPaths = flatRows.map(d => d.path.join('.'))
const [flatRowsById, flatGroupedRowsById] = React.useMemo(() => {
const map = new Map()
const groupedMap = new Map()
let isAllRowsSelected = !!flatRowPaths.length && !!selectedRowPaths.size
flatRows.forEach(row => {
if (!row.isAggregated) {
map.set(row.id, row)
}
groupedMap.set(row.id, row)
})
return [map, groupedMap]
}, [flatRows])
let isAllRowsSelected = Boolean(flatRowsById.size && selectedRowIds.size)
if (isAllRowsSelected) {
if (flatRowPaths.some(d => !selectedRowPaths.has(d))) {
if ([...flatRowsById.keys()].some(d => !selectedRowIds.has(d))) {
isAllRowsSelected = false
}
}
@@ -176,86 +211,72 @@ function useInstance(instance) {
}
}, [dispatch, data])
const toggleRowSelectedAll = selected =>
dispatch({ type: actions.toggleRowSelectedAll, selected })
const toggleAllRowsSelected = selected =>
dispatch({ type: actions.toggleAllRowsSelected, selected })
const toggleRowSelected = (path, selected) =>
dispatch({ type: actions.toggleRowSelected, path, selected })
const toggleRowSelected = (id, selected) =>
dispatch({ type: actions.toggleRowSelected, id, selected })
// use reference to avoid memory leak in #1608
const instanceRef = React.useRef()
instanceRef.current = instance
const getInstance = useGetLatest(instance)
const getToggleAllRowsSelectedProps = props => {
return mergeProps(
{
onChange: e => {
toggleRowSelectedAll(e.target.checked)
},
style: {
cursor: 'pointer',
},
checked: isAllRowsSelected,
title: 'Toggle All Rows Selected',
},
applyPropHooks(
instanceRef.current.hooks.getToggleAllRowsSelectedProps,
instanceRef.current
),
props
)
}
const getToggleAllRowsSelectedPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getToggleAllRowsSelectedProps'
)
const getToggleAllRowsSelectedProps = makePropGetter(
getToggleAllRowsSelectedPropsHooks(),
getInstance()
)
const getToggleRowSelectedPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getToggleRowSelectedProps'
)
hooks.prepareRow.push(row => {
row.toggleRowSelected = set => toggleRowSelected(row.path, set)
row.getToggleRowSelectedProps = props => {
let checked = false
row.toggleRowSelected = set => toggleRowSelected(row.id, set)
if (row.original && row.original[manualRowSelectedKey]) {
checked = true
} else {
checked = row.isSelected
}
return mergeProps(
{
onChange: e => {
row.toggleRowSelected(e.target.checked)
},
style: {
cursor: 'pointer',
},
checked,
title: 'Toggle Row Selected',
},
applyPropHooks(
instanceRef.current.hooks.getToggleRowSelectedProps,
row,
instanceRef.current
),
props
)
}
return row
row.getToggleRowSelectedProps = makePropGetter(
getToggleRowSelectedPropsHooks(),
getInstance(),
row
)
})
return {
...instance,
flatRowPaths,
Object.assign(instance, {
flatRowsById,
flatGroupedRowsById,
toggleRowSelected,
toggleRowSelectedAll,
toggleAllRowsSelected,
getToggleAllRowsSelectedProps,
isAllRowsSelected,
}
})
}
function getRowIsSelected(row, selectedRowPaths) {
if (row.isAggregated) {
return row.subRows.every(subRow =>
getRowIsSelected(subRow, selectedRowPaths)
)
function getRowIsSelected(row, selectedRowIds) {
if (selectedRowIds.has(row.id)) {
return true
}
return selectedRowPaths.has(row.path.join('.'))
if (row.isAggregated || (row.subRows && row.subRows.length)) {
let allChildrenSelected = true
let someSelected = false
row.subRows.forEach(subRow => {
// Bail out early if we know both of these
if (someSelected && !allChildrenSelected) {
return
}
if (getRowIsSelected(subRow, selectedRowIds)) {
someSelected = true
} else {
allChildrenSelected = false
}
})
return allChildrenSelected ? true : someSelected ? null : false
}
return false
}
+27 -34
View File
@@ -34,15 +34,13 @@ function reducer(state, action) {
}
if (action.type === actions.setRowState) {
const { path, value } = action
const pathKey = path.join('.')
const { id, value } = action
return {
...state,
rowState: {
...state.rowState,
[pathKey]: functionalUpdate(value, state.rowState[pathKey] || {}),
[id]: functionalUpdate(value, state.rowState[id] || {}),
},
}
}
@@ -59,10 +57,10 @@ function useInstance(instance) {
} = instance
const setRowState = React.useCallback(
(path, value, columnId) =>
(id, value, columnId) =>
dispatch({
type: actions.setRowState,
path,
id,
value,
columnId,
}),
@@ -91,6 +89,27 @@ function useInstance(instance) {
[setRowState]
)
hooks.prepareRow.push(row => {
if (row.original) {
row.state =
(typeof rowState[row.id] !== 'undefined'
? rowState[row.id]
: initialRowStateAccessor && initialRowStateAccessor(row)) || {}
row.setState = updater => {
return setRowState(row.id, updater)
}
row.cells.forEach(cell => {
cell.state = row.state.cellState || {}
cell.setState = updater => {
return setCellState(row.id, cell.column.id, updater)
}
})
}
})
const getAutoResetRowState = useGetLatest(autoResetRowState)
useMountedLayoutEffect(() => {
@@ -99,34 +118,8 @@ function useInstance(instance) {
}
}, [data])
hooks.prepareRow.push(row => {
const pathKey = row.path.join('.')
if (row.original) {
row.state =
(typeof rowState[pathKey] !== 'undefined'
? rowState[pathKey]
: initialRowStateAccessor && initialRowStateAccessor(row)) || {}
row.setState = updater => {
return setRowState(row.path, updater)
}
row.cells.forEach(cell => {
cell.state = row.state.cellState || {}
cell.setState = updater => {
return setCellState(row.path, cell.column.id, updater)
}
})
}
return row
})
return {
...instance,
Object.assign(instance, {
setRowState,
setCellState,
}
})
}
+40 -35
View File
@@ -4,8 +4,8 @@ import {
actions,
ensurePluginOrder,
defaultColumn,
mergeProps,
applyPropHooks,
makePropGetter,
useConsumeHookGetter,
getFirstDefined,
defaultOrderByFn,
isFunction,
@@ -24,12 +24,36 @@ defaultColumn.sortType = 'alphanumeric'
defaultColumn.sortDescFirst = false
export const useSortBy = hooks => {
hooks.getSortByToggleProps = [defaultGetSortByToggleProps]
hooks.stateReducers.push(reducer)
hooks.useInstance.push(useInstance)
}
useSortBy.pluginName = 'useSortBy'
const defaultGetSortByToggleProps = (props, instance, column) => {
const { isMultiSortEvent = e => e.shiftKey } = instance
return [
props,
{
onClick: column.canSort
? e => {
e.persist()
column.toggleSortBy(
undefined,
!instance.disableMultiSort && isMultiSortEvent(e)
)
}
: undefined,
style: {
cursor: column.canSort ? 'pointer' : undefined,
},
title: column.canSort ? 'Toggle SortBy' : undefined,
},
]
}
// Reducer
function reducer(state, action, previousState, instanceRef) {
if (action.type === actions.init) {
@@ -163,9 +187,7 @@ function useInstance(instance) {
manualSortBy,
defaultCanSort,
disableSortBy,
isMultiSortEvent = e => e.shiftKey,
flatHeaders,
hooks,
state: { sortBy },
dispatch,
plugins,
@@ -173,8 +195,6 @@ function useInstance(instance) {
} = instance
ensurePluginOrder(plugins, ['useFilters'], 'useSortBy', [])
// Add custom hooks
hooks.getSortByToggleProps = []
// Updates sorting based on a columnId, desc flag and multi flag
const toggleSortBy = (columnId, desc, multi) => {
@@ -184,6 +204,11 @@ function useInstance(instance) {
// use reference to avoid memory leak in #1608
const getInstance = useGetLatest(instance)
const getSortByTogglePropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getSortByToggleProps'
)
// Add the getSortByToggleProps method to columns and headers
flatHeaders.forEach(column => {
const {
@@ -212,31 +237,11 @@ function useInstance(instance) {
}
}
column.getSortByToggleProps = props => {
return mergeProps(
{
onClick: canSort
? e => {
e.persist()
column.toggleSortBy(
undefined,
!getInstance().disableMultiSort && isMultiSortEvent(e)
)
}
: undefined,
style: {
cursor: canSort ? 'pointer' : undefined,
},
title: canSort ? 'Toggle SortBy' : undefined,
},
applyPropHooks(
getInstance().hooks.getSortByToggleProps,
column,
getInstance()
),
props
)
}
column.getSortByToggleProps = makePropGetter(
getSortByTogglePropsHooks(),
getInstance(),
column
)
const columnSort = sortBy.find(d => d.id === id)
column.isSorted = !!columnSort
@@ -329,10 +334,10 @@ function useInstance(instance) {
}
}, [manualSortBy ? null : data])
return {
...instance,
Object.assign(instance, {
toggleSortBy,
rows: sortedRows,
preSortedRows: rows,
}
sortedRows,
rows: sortedRows,
})
}
+69 -26
View File
@@ -36,41 +36,77 @@ export function defaultGroupByFn(rows, columnId) {
}, {})
}
export const mergeProps = (...groups) => {
let props = {}
function mergeProps(...propList) {
return propList.reduce((props, next) => {
const { style, className, ...rest } = next
groups.forEach(({ style = {}, className, ...rest } = {}) => {
props = {
...props,
...rest,
style: {
...(props.style || {}),
...style,
...(style || {}),
},
className: [props.className, className].filter(Boolean).join(' '),
}
})
if (props.className === '') {
delete props.className
}
if (props.className === '') {
delete props.className
}
return props
return props
}, {})
}
export const applyHooks = (hooks, initial, ...args) =>
function handlePropGetter(prevProps, userProps, ...meta) {
// Handle a lambda, pass it the previous props
if (typeof userProps === 'function') {
return handlePropGetter({}, userProps(prevProps, ...meta))
}
// Handle an array, merge each item as separate props
if (Array.isArray(userProps)) {
return mergeProps(prevProps, ...userProps)
}
// Handle an object by default, merge the two objects
return mergeProps(prevProps, userProps)
}
export const makePropGetter = (hooks, ...meta) => {
return (userProps = {}) =>
[...hooks, userProps].reduce(
(prev, next) => handlePropGetter(prev, next, ...meta),
{}
)
}
export const reduceHooks = (hooks, initial, ...args) =>
hooks.reduce((prev, next) => {
const nextValue = next(prev, ...args)
if (typeof nextValue === 'undefined') {
throw new Error(
'React Table: A hook just returned undefined! This is not allowed.'
)
if (process.env.NODE_ENV !== 'production') {
if (typeof nextValue === 'undefined') {
console.info(next)
throw new Error(
'React Table: A reducer hook ☝️ just returned undefined! This is not allowed.'
)
}
}
return nextValue
}, initial)
export const applyPropHooks = (hooks, ...args) =>
hooks.reduce((prev, next) => mergeProps(prev, next(...args)), {})
export const loopHooks = (hooks, ...args) =>
hooks.forEach(hook => {
const nextValue = hook(...args)
if (process.env.NODE_ENV !== 'production') {
if (typeof nextValue !== 'undefined') {
console.info(hook, nextValue)
throw new Error(
'React Table: A loop-type hook ☝️ just returned a value! This is not allowed.'
)
}
}
})
export function ensurePluginOrder(plugins, befores, pluginName, afters) {
const pluginIndex = plugins.findIndex(
@@ -78,11 +114,13 @@ export function ensurePluginOrder(plugins, befores, pluginName, afters) {
)
if (pluginIndex === -1) {
throw new Error(`The plugin ${pluginName} was not found in the plugin list!
if (process.env.NODE_ENV !== 'production') {
throw new Error(`The plugin "${pluginName}" was not found in the plugin list!
This usually means you need to need to name your plugin hook by setting the 'pluginName' property of the hook function, eg:
${pluginName}.pluginName = '${pluginName}'
`)
}
}
befores.forEach(before => {
@@ -90,18 +128,22 @@ This usually means you need to need to name your plugin hook by setting the 'plu
plugin => plugin.pluginName === before
)
if (beforeIndex > -1 && beforeIndex > pluginIndex) {
throw new Error(
`React Table: The ${pluginName} plugin hook must be placed after the ${before} plugin hook!`
)
if (process.env.NODE_ENV !== 'production') {
throw new Error(
`React Table: The ${pluginName} plugin hook must be placed after the ${before} plugin hook!`
)
}
}
})
afters.forEach(after => {
const afterIndex = plugins.findIndex(plugin => plugin.pluginName === after)
if (afterIndex > -1 && afterIndex < pluginIndex) {
throw new Error(
`React Table: The ${pluginName} plugin hook must be placed before the ${after} plugin hook!`
)
if (process.env.NODE_ENV !== 'production') {
if (afterIndex > -1 && afterIndex < pluginIndex) {
throw new Error(
`React Table: The ${pluginName} plugin hook must be placed before the ${after} plugin hook!`
)
}
}
})
}
@@ -133,7 +175,7 @@ export function useMountedLayoutEffect(fn, deps) {
}, deps)
}
export default function useAsyncDebounce(defaultFn, defaultWait = 0) {
export function useAsyncDebounce(defaultFn, defaultWait = 0) {
const debounceRef = React.useRef({})
debounceRef.current.defaultFn = defaultFn
debounceRef.current.defaultWait = defaultWait
@@ -144,8 +186,9 @@ export default function useAsyncDebounce(defaultFn, defaultWait = 0) {
wait = debounceRef.current.defaultWait
) => {
if (!debounceRef.current.promise) {
debounceRef.current.promise = new Promise(resolve => {
debounceRef.current.promise = new Promise((resolve, reject) => {
debounceRef.current.resolve = resolve
debounceRef.current.reject = reject
})
}
+1 -3
View File
@@ -272,11 +272,9 @@ export function expandRows(
const expandedRows = []
const handleRow = row => {
const key = row.path.join('.')
row.isExpanded =
(row.original && row.original[manualExpandedKey]) ||
expanded.includes(key)
expanded.includes(row.id)
row.canExpand = row.subRows && !!row.subRows.length