Compare commits

...
53 Commits
Author SHA1 Message Date
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
Tanner Linsley e0ad323bd8 v7.0.0-rc.5 2019-12-08 19:32:45 -07:00
Tanner Linsley c1e4fb8956 v7.0.0-rc.4 2019-12-08 19:26:49 -07:00
Bart NagelandTanner Linsley 1ac1d99f23 Fix link in documentation (#1733) 2019-12-06 21:51:34 -07:00
size-plugin[bot]andGitHub e5b991751a 🏊🏿‍♂️ 🧜🏻‍♂️ update sizes-cjs.json 👍 2019-12-07 03:49:50 +00:00
Bart NagelandTanner Linsley 8dc6559e64 Fix row.toggleExpanded(bool) (#1732)
The wrong variable was being checked against `undefined`, so the row was
always being toggled, rather than taking the parameter into account.
2019-12-06 20:39:45 -07:00
dependabot[bot]andTanner Linsley 2955335df1 Bump eslint-utils from 1.4.0 to 1.4.3 in /examples/grouping (#1730)
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-06 16:42:41 -07:00
Tanner Linsley 8c090a734b Merge branch 'master' of https://github.com/react-tools/react-table 2019-12-06 16:36:50 -07:00
Tanner Linsley 439ebad063 Update faq.md 2019-12-06 16:36:17 -07:00
size-plugin[bot]andGitHub 2ef6e13657 🧎🏼 🤳🏽 update sizes-es.json 👍 2019-12-06 23:35:30 +00:00
size-plugin[bot]andGitHub 6338b32bd8 🧝🏽‍♂️ 🇲🇦 update sizes-cjs.json 👍 2019-12-06 23:35:29 +00:00
Tanner Linsley 67544d33ff v7.0.0-rc.3 2019-12-06 16:33:41 -07:00
Tanner Linsley 3fa2cdf388 Merge branch 'master' of https://github.com/react-tools/react-table 2019-12-06 16:30:42 -07:00
Tanner Linsley 562a2feaef v7.0.0-rc.2 2019-12-06 16:30:08 -07:00
AlbericoandTanner Linsley 176986a07a docs(docs/api/readme.md): fix to useTable link that was giving 404 (#1726)
In the /docs/api/README.md the useTable link was linking to the file ./usetable.md that doesn't
exist, now it links to ./useTable
2019-12-06 10:25:15 -05:00
size-plugin[bot]andGitHub f824fea2ef 🙍🏿 ♟️ update sizes-es.json 👍 2019-12-06 08:21:02 +00:00
size-plugin[bot]andGitHub ace8f56371 🇦🇪 💨 update sizes-cjs.json 👍 2019-12-06 08:21:01 +00:00
gargrohandTanner Linsley 3d5249b716 [useSortBy] updating missed key rename (#1724) 2019-12-06 03:19:28 -05:00
ggascoigneandTanner Linsley 546cb4e076 put useFilters docs in correct file (#1723) 2019-12-06 01:18:48 -05:00
size-plugin[bot]andGitHub d1677dfebb 🇻🇨 🤰🏻 update sizes-es.json 👍 2019-12-06 04:37:44 +00:00
size-plugin[bot]andGitHub 4868d7835f 😖 💇🏾‍♀️ update sizes-cjs.json 👍 2019-12-06 04:37:43 +00:00
46 changed files with 1840 additions and 1349 deletions
+27 -8
View File
@@ -1,20 +1,39 @@
{
"dist/index.js": {
"bundled": 102847,
"minified": 50399,
"gzipped": 12909
"bundled": 108184,
"minified": 51333,
"gzipped": 13486
},
"dist/index.es.js": {
"bundled": 101791,
"minified": 49456,
"gzipped": 12726,
"bundled": 107341,
"minified": 50583,
"gzipped": 13333,
"treeshaked": {
"rollup": {
"code": 78,
"code": 80,
"import_statements": 21
},
"webpack": {
"code": 14193
"code": 8904
}
}
},
"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
}
}
}
+74
View File
@@ -1,3 +1,77 @@
## 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)
## 7.0.0-rc.3
- Fixed an issue where `column.clearSortBy` would crash
## 7.0.0-rc.2
- `reducerHandlers` has been deprecated in favor of the new `stateReducers` hook.
- The `previousState` and `instanceRef` are now both generally available in state reducers for convenience.
- The global action property `action.instanceRef` has been deprecated.
- The `reducer` option has been renamed to `stateReducer` and in addition to passing a single reducer function now also supports passing an array of reducers
- Renamed `manualSorting` to be `manualSortBy` to be consistent with other naming conventions
- Removed the `getResetPageDeps` option in favor of the new `autoResetPage` option.
- Removed the `getResetFilterDeps` option in favor of the new `autoResetFilters` option.
- Removed the `getResetSortByDeps` option in favor of the new `autoResetSortBy` option.
- Removed the `getResetGroupByDeps` option in favor of the new `autoResetGroupBy` option.
- Removed the `getResetExpandedDeps` option in favor of the new `autoResetExpanded` option.
- Added a new exported utility called `useAsyncDebounce` to aid with external async side-effects.
- A new `useGetLatest` hook is used internally to track latest instances in a less ref-driven and verbose way.
- A new `useMountedLayoutEffect` hooks is now used internally to handle post-mount side-effects, mostly dealing with autoReset functionality
- Plugin hooks are now "consumed" using an internal `useConsumeHookGetter` hook. When they are consumed, they can no longer be manipulated past that point in the table lifecycle. This should help ensure people are using them in a relatively safe order with consistent expectations.
- Drastically "reduced" the reducer logic itself to be easier to understand and to be a stable reference for the life of the table. This change also means that the reducer must no longer be double-run/back-compared by React for changes in closure, thus actions and stateReducers (including user state reducers) will only fire once per action.
- Removed `debug` and related logging. It has been somewhat useful during development, but is now very noisy in the code. We can debug lifecycle and performance as needed from here on out.
- Removed unnecessary exports from `./utils.js` and moved all intentionally exported utilities to a new `./publicUtils.js` file.
## 7.0.0-rc.1
- Minor regex optimizations during row path creation
+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
+1 -1
View File
@@ -5,7 +5,7 @@ React Table uses React Hooks both internally and externally for almost all of it
React Table is essentially a compatible collection of **custom React hooks**:
- The primary React Table hook
- [`useTable`](./usetable.md)
- [`useTable`](./useTable.md)
- Plugin Hooks
- Core Plugin Hooks
- [`useGroupBy`](./useGroupBy.md)
+5 -8
View File
@@ -30,15 +30,12 @@ The following options are supported via the main options object passed to `useTa
- Defaults to `true`
- If set to `true`, expanded rows are rendered along with normal rows.
- If set to `false`, expanded rows will only be available through their parent row. This could be useful if you are implementing a custom expanded row view.
- `getResetExpandedDeps: Function(instance) => [...useEffectDependencies]`
- Optional
- Defaults to resetting the `expanded` state to `[]` when the dependencies below change
- ```js
const getResetExpandedDeps = ({ data }) => [data]
```
- If set, the dependencies returned from this function will be used to determine when the effect to reset the `expanded` state is fired.
- `autoResetExpanded: Boolean`
- Defaults to `true`
- When `true`, the `expanded` state will automatically reset if any of the following conditions are met:
- `data` is changed
- To disable, set to `false`
- For more information see the FAQ ["How do I stop my table state from automatically resetting when my data changes?"](./faq#how-do-i-stop-my-table-state-from-automatically-resetting-when-my-data-changes)
- For more information see the FAQ ["How do I stop my table state from automatically resetting when my data changes?"](../faq.md#how-do-i-stop-my-table-state-from-automatically-resetting-when-my-data-changes)
### Instance Properties
+96
View File
@@ -0,0 +1,96 @@
# `useFilters`
- Plugin Hook
- Optional
`useFilters` is the hook that implements **row filtering**.
### Table Options
The following options are supported via the main options object passed to `useTable(options)`
- `state.filters: Object<columnId: filterValue>`
- Must be **memoized**
- An object of columnId's and their corresponding filter values. This information is stored in state since the table is allowed to manipulate the filter through user interaction.
- `initialState.filters`
- Identical to the `state.filters` option above
- `manualFilters: Bool`
- Enables filter detection functionality, but does not automatically perform row filtering.
- Turn this on if you wish to implement your own row filter outside of the table (eg. server-side or manual row grouping/nesting)
- `disableFilters: Bool`
- Disables filtering for every column in the entire table.
- `defaultCanFilter: Bool`
- Optional
- Defaults to `false`
- If set to `true`, all columns will be filterable, regardless if they have a valid `accessor`
- `filterTypes: Object<filterKey: filterType>`
- Must be **memoized**
- Allows overriding or adding additional filter types for columns to use. If a column's filter type isn't found on this object, it will default to using the built-in filter types.
- For more information on filter types, see Filtering
- `autoResetFilters: Boolean`
- Defaults to `true`
- When `true`, the `filters` state will automatically reset if any of the following conditions are met:
- `data` is changed
- To disable, set to `false`
- For more information see the FAQ ["How do I stop my table state from automatically resetting when my data changes?"](./faq#how-do-i-stop-my-table-state-from-automatically-resetting-when-my-data-changes)
### Column Options
The following options are supported on any `Column` object passed to the `columns` options in `useTable()`
- `Filter: Function | React.Component => JSX`
- **Required**
- Receives the table instance and column model as props
- Must return valid JSX
- This function (or component) is used to render this column's filter UI, eg.
- `disableFilters: Bool`
- Optional
- If set to `true`, will disable filtering for this column
- `defaultCanFilter: Bool`
- Optional
- Defaults to `false`
- If set to `true`, this column will be filterable, regardless if it has a valid `accessor`
- `filter: String | Function`
- Optional
- Defaults to `text`
- The resolved function from the this string/function will be used to filter the this column's data.
- If a `string` is passed, the function with that name located on either the custom `filterTypes` option or the built-in filtering types object will be used. If
- If a `function` is passed, it will be used directly.
- For more information on filter types, see Filtering
- If a **function** is passed, it must be **memoized**
### Instance Properties
The following values are provided to the table `instance`:
- `rows: Array<Row>`
- An array of **filtered** rows.
- `preFilteredRows: Array<Row>`
- The array of rows **used right before filtering**.
- Among many other use-cases, these rows are directly useful for building option lists in filters, since the resulting filtered `rows` do not contain every possible option.
- `setFilter: Function(columnId, filterValue) => void`
- An instance-level function used to update the filter value for a specific column.
- `setAllFilters: Function(filtersObject) => void`
- An instance-level function used to update the values for **all** filters on the table, all at once.
### Column Properties
The following properties are available on every `Column` object returned by the table instance.
- `canFilter: Bool`
- Denotes whether a column is filterable or not depending on if it has a valid accessor/data model or is manually disabled via an option.
- `setFilter: Function(filterValue) => void`
- A column-level function used to update the filter value for this column
- `filterValue: any`
- The current filter value for this column, resolved from the table state's `filters` object
- `preFilteredRows: Array<row>`
- The array of rows that were originally passed to this columns filter **before** they were filtered.
- This array of rows can be useful if building faceted filter options.
- `filteredRows: Array<row>`
- The resulting array of rows received from this columns filter **after** they were filtered.
- This array of rows can be useful if building faceted filter options.
### Example
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/filtering)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/filtering)
+7 -12
View File
@@ -29,18 +29,13 @@ The following options are supported via the main options object passed to `useTa
- `manualPagination: Bool`
- Enables pagination functionality, but does not automatically perform row pagination.
- Turn this on if you wish to implement your own pagination outside of the table (eg. server-side pagination or any other manual pagination technique)
- `getResetPageDeps: Function(instance) => [...useEffectDependencies]`
- Optional
- Defaults to resetting the `pageIndex` to `0` when the dependencies below change
- ```js
const getResetPageDeps = ({
rows,
manualPagination,
state: { filters, groupBy, sortBy },
}) => [manualPagination ? null : rows, filters, groupBy, sortBy]
```
- Note that if `manualPagination` is set to `true`, then the pageIndex should not be reset when `rows` change
- If set, the dependencies returned from this function will be used to determine when the effect to reset the `pageIndex` state is fired.
- `autoResetPage: Boolean`
- Defaults to `true`
- When `true`, the `expanded` state will automatically reset if `manualPagination` is `false` and any of the following conditions are met:
- `data` is changed
- `manualSortBy` is `false` and `state.sortBy` is changed
- `manualFilters` is `false` and `state.filters` is changed
- `manualGroupBy` is `false` and `state.groupBy` is changed
- To disable, set to `false`
- For more information see the FAQ ["How do I stop my table state from automatically resetting when my data changes?"](./faq#how-do-i-stop-my-table-state-from-automatically-resetting-when-my-data-changes)
- `paginateExpandedRows: Bool`
+4 -7
View File
@@ -19,13 +19,10 @@ The following options are supported via the main options object passed to `useTa
- Optional
- Defaults to `isSelected`
- If this key is found on the **original** data row, and it is true, this row will be manually selected
- `getResetSelectedRowPathsDeps: Function(instance) => [...useEffectDependencies]`
- Optional
- Defaults to resetting the `expanded` state to `[]` when the dependencies below change
- ```js
const getResetSelectedRowPathsDeps = ({ rows }) => [rows]
```
- If set, the dependencies returned from this function will be used to determine when the effect to reset the `selectedRowPaths` state is fired.
- `autoResetSelectedRows: Boolean`
- Defaults to `true`
- When `true`, the `expanded` state will automatically reset if any of the following conditions are met:
- `data` is changed
- To disable, set to `false`
- For more information see the FAQ ["How do I stop my table state from automatically resetting when my data changes?"](./faq#how-do-i-stop-my-table-state-from-automatically-resetting-when-my-data-changes)
+4 -7
View File
@@ -21,13 +21,10 @@ The following options are supported via the main options object passed to `useTa
- Optional
- This function may optionally return the initial state for a row.
- If this function is defined, it will be passed a `Row` object, from which you can return a value to use as the initial state, eg. `row => row.original.initialState`
- `getResetRowStateDeps: Function(instance) => [...useEffectDependencies]`
- Optional
- Defaults to resetting the `rowState` state to `{}` when the dependencies below change
- ```js
const getResetRowStateDeps = ({ data }) => [data]
```
- If set, the dependencies returned from this function will be used to determine when the effect to reset the `rowState` state is fired.
- `autoResetRowState: Boolean`
- Defaults to `true`
- When `true`, the `rowState` state will automatically reset if any of the following conditions are met:
- `data` is changed
- To disable, set to `false`
- For more information see the FAQ ["How do I stop my table state from automatically resetting when my data changes?"](./faq#how-do-i-stop-my-table-state-from-automatically-resetting-when-my-data-changes)
+4 -101
View File
@@ -46,10 +46,10 @@ The following options are supported via the main options object passed to `useTa
- Must be **memoized**
- Allows overriding or adding additional sort types for columns to use. If a column's sort type isn't found on this object, it will default to using the built-in sort types.
- For more information on sort types, see Sorting
- `getResetSortByDeps: Function(instance) => [...useEffectDependencies]`
- Optional
- Defaults to `false`
- If set, the dependencies returned from this function will be used to determine when the effect to reset the `sortBy` state is fired.
- `autoResetSortBy: Boolean`
- Defaults to `true`
- When `true`, the `sortBy` state will automatically reset if any of the following conditions are met:
- `data` is changed
- To disable, set to `false`
- For more information see the FAQ ["How do I stop my table state from automatically resetting when my data changes?"](./faq#how-do-i-stop-my-table-state-from-automatically-resetting-when-my-data-changes)
@@ -125,100 +125,3 @@ The following properties are available on every `Column` object returned by the
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/sorting)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/sorting)
# `useFilters`
- Plugin Hook
- Optional
`useFilters` is the hook that implements **row filtering**.
### Table Options
The following options are supported via the main options object passed to `useTable(options)`
- `state.filters: Object<columnId: filterValue>`
- Must be **memoized**
- An object of columnId's and their corresponding filter values. This information is stored in state since the table is allowed to manipulate the filter through user interaction.
- `initialState.filters`
- Identical to the `state.filters` option above
- `manualFilters: Bool`
- Enables filter detection functionality, but does not automatically perform row filtering.
- Turn this on if you wish to implement your own row filter outside of the table (eg. server-side or manual row grouping/nesting)
- `disableFilters: Bool`
- Disables filtering for every column in the entire table.
- `defaultCanFilter: Bool`
- Optional
- Defaults to `false`
- If set to `true`, all columns will be filterable, regardless if they have a valid `accessor`
- `filterTypes: Object<filterKey: filterType>`
- Must be **memoized**
- Allows overriding or adding additional filter types for columns to use. If a column's filter type isn't found on this object, it will default to using the built-in filter types.
- For more information on filter types, see Filtering
- `getResetFiltersDeps: Function(instance) => [...useEffectDependencies]`
- Optional
- Defaults to `false`
- If set, the dependencies returned from this function will be used to determine when the effect to reset the `filters` state is fired.
- To disable, set to `false`
- For more information see the FAQ ["How do I stop my table state from automatically resetting when my data changes?"](./faq#how-do-i-stop-my-table-state-from-automatically-resetting-when-my-data-changes)
### Column Options
The following options are supported on any `Column` object passed to the `columns` options in `useTable()`
- `Filter: Function | React.Component => JSX`
- **Required**
- Receives the table instance and column model as props
- Must return valid JSX
- This function (or component) is used to render this column's filter UI, eg.
- `disableFilters: Bool`
- Optional
- If set to `true`, will disable filtering for this column
- `defaultCanFilter: Bool`
- Optional
- Defaults to `false`
- If set to `true`, this column will be filterable, regardless if it has a valid `accessor`
- `filter: String | Function`
- Optional
- Defaults to `text`
- The resolved function from the this string/function will be used to filter the this column's data.
- If a `string` is passed, the function with that name located on either the custom `filterTypes` option or the built-in filtering types object will be used. If
- If a `function` is passed, it will be used directly.
- For more information on filter types, see Filtering
- If a **function** is passed, it must be **memoized**
### Instance Properties
The following values are provided to the table `instance`:
- `rows: Array<Row>`
- An array of **filtered** rows.
- `preFilteredRows: Array<Row>`
- The array of rows **used right before filtering**.
- Among many other use-cases, these rows are directly useful for building option lists in filters, since the resulting filtered `rows` do not contain every possible option.
- `setFilter: Function(columnId, filterValue) => void`
- An instance-level function used to update the filter value for a specific column.
- `setAllFilters: Function(filtersObject) => void`
- An instance-level function used to update the values for **all** filters on the table, all at once.
### Column Properties
The following properties are available on every `Column` object returned by the table instance.
- `canFilter: Bool`
- Denotes whether a column is filterable or not depending on if it has a valid accessor/data model or is manually disabled via an option.
- `setFilter: Function(filterValue) => void`
- A column-level function used to update the filter value for this column
- `filterValue: any`
- The current filter value for this column, resolved from the table state's `filters` object
- `preFilteredRows: Array<row>`
- The array of rows that were originally passed to this columns filter **before** they were filtered.
- This array of rows can be useful if building faceted filter options.
- `filteredRows: Array<row>`
- The resulting array of rows received from this columns filter **after** they were filtered.
- This array of rows can be useful if building faceted filter options.
### Example
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/filtering)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/filtering)
+68 -8
View File
@@ -26,36 +26,96 @@ useTable({
})
```
**It's important that the state override is done within a `useMemo` call to prevent the state variable from changing on every render. It's also just as important that you always use the `state` in any memoization dependencies to ensure that you do not block normal state updates.**
> **It's important that the state override is done within a `useMemo` call to prevent the state variable from changing on every render. It's also extremely important that you always use the `state` in any dependencies to ensure that you do not block normal state updates.**
## How can I use the table state to fetch new data?
When managing your data externally or asynchronously (eg. server-side pagination/sorting/grouping/etc), you will need to fetch new data as the internal table state changes. With React Hooks, this is fantastically easier than it was before now that we have the `React.useEffect` hook. We can use this hook to "watch" the table state for specific changes and use those effects to trigger fetches for new data (or synchronize any other state you may be managing externally from your table component):
```js
function Table({ data, onFetchData }) {
const {
state: { pageIndex, pageSize, sortBy, filters },
} = useTable({
data,
})
// When the these table states change, fetch new data!
React.useEffect(() => {
onFetchData({ pageIndex, pageSize, sortBy, filters })
}, [fetchData, pageIndex, pageSize, sortBy, filters])
return </>
}
```
Using this approach, you can respond and trigger any type of side-effect using the table instance!
## How can I debounce rapid table state changes?
React Table has a few built-in side-effects of it's own (most of which are meant for resetting parts of the state when `data` changes). By default, these state side-effects are on and when their conditions are met, they immediately fire off actions that will manipulate the table state. Sometimes, this may result in multiple rapid rerenders (usually just 2, or one more than normal), and could cause any side-effects you have watching the table state to also fire multiple times in-a-row. To alleviate this edge-case, React Table exports a `useAsyncDebounce` function that will allow you to debounce rapid side-effects and only use the latest one.
A good example of this when doing server-side pagination and sorting, a user changes the `sortBy` for a table and the `pageIndex` is automatically reset to `0` via an internal side effect. This would normally cause our effect below to fire 2 times, but with `useAsyncDebounce` we can make sure our data fetch function only gets called once:
```js
import { useTable, useAsyncDebounce } from 'react-table'
function Table({ data, onFetchData }) {
const {
state: { pageIndex, pageSize, sortBy, filters },
} = useTable({
data,
})
// Debounce our onFetchData call for 100ms
const onFetchDataDebounced = useAsyncDebounce(onFetchData, 100)
// When the these table states changes, fetch new data!
React.useEffect(() => {
// Every change will call our debounced function
onFetchDataDebounced({ pageIndex, pageSize, sortBy, filters })
// Only the last call after the 100ms debounce is over will be fired!
}, [onFetchDataDebounced, pageIndex, pageSize, sortBy, filters])
return </>
}
```
## How do I stop my table state from automatically resetting when my data changes?
Most plugins use state that _should_ normally reset when the data sources changes, but sometimes you need to suppress that from happening if you are filtering your data externally, or immutably editing your data while looking at it, or simply doing anything external with your data that you don't want to trigger a piece of table state to reset automatically.
For those situations, each plugin provides options like `getResetPageDeps` or `getResetExpandedDeps`, so and an so forth. These functions are provided the table `instance` and allowed to return an array of variables that will be injected into the `React.useEffect`'s dependency array that is responsible for watching and resetting those states. By returning a new array in one of these arrays, you can either stop the automatic resets from being triggered, or even trigger them more based on what you are returning. You can also return `false` for any of these options to disable the automatic resets completely, or pass `undefined` to allow the default dependendies to be used.
For those situations, each plugin provides a way to disable the state from automatically resetting internally when data or other dependencies for a piece of state change. By setting any of them to `false`, you can stop the automatic resets from being triggered.
Here is an example of completely disabling the page from resetting when data changes:
Here is an example of stopping basically every piece of state from changing as they normally do while we edit the `data` source for a table:
```js
const [data, setData] = React.useState([])
const skipPageResetRef = React.useRef()
const updateData = newData => {
// When data gets updated with this function, disable the
// page from resetting
// When data gets updated with this function, set a flag
// to disable all of the auto resetting
skipPageResetRef.current = true
setData(newData)
}
React.useEffect(() => {
// After the table has updated, always remove the flag
skipPageResetRef.current = false
})
useTable({
data,
getResetPageDeps: skipPageReset ? false : undefined,
...
autoResetPage: !skipPageReset,
autoResetExpanded: !skipPageReset,
autoResetGroupBy: !skipPageReset,
autoResetSelectedRows: !skipPageReset,
autoResetSortBy: !skipPageReset,
autoResetFilters: !skipPageReset,
autoResetRowState: !skipPageReset,
})
```
<!-- ## How can I hide/show columns? -->
Now, when we update our data, the above table states will not automatically reset!
+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>
+1 -1
View File
@@ -102,7 +102,7 @@ function Table({ columns, data, updateMyData, skipPageReset }) {
data,
defaultColumn,
// use the skipPageReset option to disable page resetting temporarily
getResetPageDeps: skipPageReset ? false : undefined,
autoResetPage: !skipPageReset,
// updateMyData isn't part of the API, but
// anything we put into these options will
// automatically be available on the instance.
+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.1"
resolved "https://registry.yarnpkg.com/react-table/-/react-table-7.0.0-rc.1.tgz#33f61b904d246d862a46a05ac4d8eda6343ea83b"
integrity sha512-tAuZg+TY64UUgBPRts/q+0JguGZpliYdoQZl7lAnLAQ/reU/5c04sCx54QcpH7n/PYVHMJEYkIU0ito8ZZ011w==
react@^16.8.6:
version "16.8.6"
+1 -1
View File
@@ -306,7 +306,7 @@ function Table({ columns, data, updateMyData, skipPageReset }) {
updateMyData,
// We also need to pass this so the page doesn't change
// when we edit the data, undefined means using the default
getResetPageDeps: skipPageReset ? false : undefined,
autoResetPage: !skipPageReset,
},
useGroupBy,
useFilters,
+3 -3
View File
@@ -303,9 +303,9 @@ function Table({ columns, data, updateMyData, skipReset }) {
// cell renderer!
updateMyData,
// We also need to pass this so the page doesn't change
// when we edit the data. Undefined tells it to use the default
getResetPageDeps: skipReset ? false : undefined,
getResetSelectedRowPathsDeps: skipReset ? false : undefined,
// when we edit the data.
autoResetPage: !skipReset,
autoResetSelectedRows: !skipReset,
},
useFilters,
useGroupBy,
+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"
+12 -5
View File
@@ -77,8 +77,6 @@ function Table({
usePagination
)
// Now we can get our table state from the hoisted table state tuple
// Listen for changes in pagination and use the state to fetch our new data
React.useEffect(() => {
fetchData({ pageIndex, pageSize })
@@ -107,7 +105,16 @@ function Table({
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>{column.render('Header')}</th>
<th {...column.getHeaderProps()}>
{column.render('Header')}
<span>
{column.isSorted
? column.isSortedDesc
? ' 🔽'
: ' 🔼'
: ''}
</span>
</th>
))}
</tr>
))}
@@ -126,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>
+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.1"
resolved "https://registry.yarnpkg.com/react-table/-/react-table-7.0.0-rc.1.tgz#33f61b904d246d862a46a05ac4d8eda6343ea83b"
integrity sha512-tAuZg+TY64UUgBPRts/q+0JguGZpliYdoQZl7lAnLAQ/reU/5c04sCx54QcpH7n/PYVHMJEYkIU0ito8ZZ011w==
react@^16.8.6:
version "16.8.6"
-1
View File
@@ -62,7 +62,6 @@ function Table({ columns, data }) {
columns,
data,
initialState: { pageIndex: 2 },
debug: true,
},
usePagination
)
+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.1"
resolved "https://registry.yarnpkg.com/react-table/-/react-table-7.0.0-rc.1.tgz#33f61b904d246d862a46a05ac4d8eda6343ea83b"
integrity sha512-tAuZg+TY64UUgBPRts/q+0JguGZpliYdoQZl7lAnLAQ/reU/5c04sCx54QcpH7n/PYVHMJEYkIU0ito8ZZ011w==
react@^16.8.6:
version "16.8.6"
-1
View File
@@ -47,7 +47,6 @@ function Table({ columns, data }) {
{
columns,
data,
debug: true,
},
useRowSelect
)
+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"
+2 -2
View File
@@ -1,7 +1,7 @@
{
"name": "react-table",
"version": "7.0.0-rc.1",
"description": "A fast, lightweight, opinionated table and datagrid built on React",
"version": "7.0.0-rc.8",
"description": "Hooks for building lightweight, fast and extendable datagrids for React",
"license": "MIT",
"homepage": "https://github.com/tannerlinsley/react-table#readme",
"repository": {
+100
View File
@@ -1,4 +1,104 @@
[
{
"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": [
{
"filename": "index.js",
"size": 21026,
"delta": 1
}
]
},
{
"timestamp": 1575675308812,
"files": [
{
"filename": "index.js",
"size": 21025,
"delta": -421
}
]
},
{
"timestamp": 1575620433902,
"files": [
{
"filename": "index.js",
"size": 21446,
"delta": -1
}
]
},
{
"timestamp": 1575607054721,
"files": [
{
"filename": "index.js",
"size": 21447,
"delta": 26
}
]
},
{
"timestamp": 1575605755429,
"files": [
+90
View File
@@ -1,4 +1,94 @@
[
{
"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": [
{
"filename": "index.es.js",
"size": 20842,
"delta": -383
}
]
},
{
"timestamp": 1575620442742,
"files": [
{
"filename": "index.es.js",
"size": 21225,
"delta": -1
}
]
},
{
"timestamp": 1575607059725,
"files": [
{
"filename": "index.es.js",
"size": 21226,
"delta": 26
}
]
},
{
"timestamp": 1575605764195,
"files": [
+86 -77
View File
@@ -2,20 +2,63 @@ import React from 'react'
import {
actions,
reducerHandlers,
functionalUpdate,
mergeProps,
applyPropHooks,
useGetLatest,
useConsumeHookGetter,
makePropGetter,
} from '../utils'
const pluginName = 'useColumnVisibility'
actions.resetHiddenColumns = 'resetHiddenColumns'
actions.toggleHideColumn = 'toggleHideColumn'
actions.setHiddenColumns = 'setHiddenColumns'
actions.toggleHideAllColumns = 'toggleHideAllColumns'
reducerHandlers[pluginName] = (state, action) => {
export const useColumnVisibility = hooks => {
hooks.getToggleHiddenProps = [defaultGetToggleHiddenProps]
hooks.getToggleHideAllColumnsProps = [defaultGetToggleHideAllColumnsProps]
hooks.stateReducers.push(reducer)
hooks.useInstanceBeforeDimensions.push(useInstanceBeforeDimensions)
hooks.headerGroupsDeps.push((deps, instance) => [
...deps,
instance.state.hiddenColumns,
])
hooks.useInstance.push(useInstance)
}
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 {
hiddenColumns: [],
@@ -62,25 +105,12 @@ reducerHandlers[pluginName] = (state, action) => {
return {
...state,
hiddenColumns: shouldAll
? action.instanceRef.current.flatColumns.map(d => d.id)
? instanceRef.current.flatColumns.map(d => d.id)
: [],
}
}
}
export const useColumnVisibility = hooks => {
hooks.columnsBeforeHeaderGroupsDeps.push((deps, instance) => [
...deps,
instance.state.hiddenColumns,
])
hooks.useInstanceBeforeDimensions.push(useInstanceBeforeDimensions)
hooks.useInstance.push(useInstance)
hooks.getToggleHiddenProps = []
hooks.getToggleHideAllColumnsProps = []
}
useColumnVisibility.pluginName = pluginName
function useInstanceBeforeDimensions(instance) {
const {
headers,
@@ -111,8 +141,6 @@ function useInstanceBeforeDimensions(instance) {
headers.forEach(
subHeader => (totalVisibleHeaderCount += handleColumn(subHeader, true))
)
return instance
}
function useInstance(instance) {
@@ -123,41 +151,10 @@ function useInstance(instance) {
state: { hiddenColumns },
} = instance
const instanceRef = React.useRef()
instanceRef.current = instance
const getInstance = useGetLatest(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(
instanceRef.current.hooks.getToggleHiddenProps,
instanceRef.current
),
props
)
}
})
const toggleHideColumn = React.useCallback(
(columnId, value) =>
dispatch({ type: actions.toggleHideColumn, columnId, value }),
@@ -174,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(
instanceRef.current.hooks.getToggleHideAllColumnsProps,
instanceRef.current
),
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,
}
})
}
+344 -273
View File
@@ -3,25 +3,23 @@ import React from 'react'
//
import {
actions,
reducerHandlers,
applyHooks,
applyPropHooks,
mergeProps,
reduceHooks,
loopHooks,
makePropGetter,
flexRender,
decorateColumnTree,
makeHeaderGroups,
flattenBy,
useGetLatest,
useConsumeHookGetter,
} from '../utils'
import makeDefaultPluginHooks from '../makeDefaultPluginHooks'
import { useColumnVisibility } from './useColumnVisibility'
let renderErr = 'Renderer Error'
if (process.env.NODE_ENV !== 'production') {
renderErr =
'You must specify a valid render component. This could be "column.Cell", "column.Header", "column.Filter", "column.Aggregated" or any other custom renderer component.'
}
const defaultInitialState = {}
const defaultColumnInstance = {}
const defaultReducer = (state, action, prevState) => state
@@ -29,150 +27,223 @@ const defaultGetSubRows = (row, index) => row.subRows || []
const defaultGetRowId = (row, index) => 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,
reducer: userReducer = defaultReducer,
stateReducer = defaultReducer,
useControlledState = defaultUseControlledState,
debug,
...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]
debug = process.env.NODE_ENV === 'production' ? false : debug
const reducer = (state, action) => {
let nextState = Object.keys(reducerHandlers)
.map(key => reducerHandlers[key])
.reduce((state, handler) => handler(state, action) || state, state)
nextState = userReducer(nextState, action, state)
if (process.env.NODE_ENV !== 'production' && debug) {
console.info('')
console.info('React Table Action: ', action)
console.info('New State: ', nextState)
}
return nextState
}
// But use the users table state if provided
const [reducerState, originalDispatch] = React.useReducer(
reducer,
undefined,
() => reducer(initialState, { type: actions.init })
)
const state = useControlledState(reducerState)
// The table instance ref
// Create the table instance
let instanceRef = React.useRef({})
const dispatch = React.useCallback(action => {
if (!action.type) {
if (process.env.NODE_ENV !== 'production') {
console.info({ action })
throw new Error('Unknown Action Type! 👆')
}
throw new Error()
}
originalDispatch({ ...action, instanceRef })
}, [])
// Create a getter for the instance (helps avoid a lot of potential memory leaks)
const getInstance = useGetLatest(instanceRef.current)
Object.assign(instanceRef.current, {
// Assign the props, plugins and hooks to the instance
Object.assign(getInstance(), {
...props,
data, // The raw data
state, // The state dispatcher
dispatch, // The resolved table state
plugins, // All resolved plugins
hooks: {
columnsBeforeHeaderGroups: [],
columnsBeforeHeaderGroupsDeps: [],
useInstanceBeforeDimensions: [],
useInstance: [],
useRows: [],
prepareRow: [],
getTableProps: [],
getTableBodyProps: [],
getRowProps: [],
getHeaderGroupProps: [],
getFooterGroupProps: [],
getHeaderProps: [],
getFooterProps: [],
getCellProps: [],
},
plugins,
hooks: makeDefaultPluginHooks(),
})
// Allow plugins to register hooks
if (process.env.NODE_ENV !== 'production' && debug) console.time('plugins')
// Allow plugins to register hooks as early as possible
plugins.filter(Boolean).forEach(plugin => {
plugin(instanceRef.current.hooks)
plugin(getInstance().hooks)
})
if (process.env.NODE_ENV !== 'production' && debug) console.timeEnd('plugins')
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(
getInstance().hooks,
'stateReducers'
)
// Setup user reducer ref
const getStateReducer = useGetLatest(stateReducer)
// Build the reducer
const reducer = React.useCallback(
(state, action) => {
// Detect invalid actions
if (!action.type) {
console.info({ action })
throw new Error('Unknown Action 👆')
}
// Reduce the state from all plugin reducers
return [
...getStateReducers(),
// Allow the user to add their own state reducer(s)
...(Array.isArray(getStateReducer())
? getStateReducer()
: [getStateReducer()]),
].reduce(
(s, handler) => handler(s, action, state, instanceRef) || s,
state
)
},
[getStateReducers, getStateReducer]
)
// Start the reducer
const [reducerState, dispatch] = React.useReducer(reducer, undefined, () =>
reducer(initialState, { type: actions.init })
)
// Allow the user to control the final state with hooks
const state = useControlledState(reducerState)
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
...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 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(() => {
if (process.env.NODE_ENV !== 'production' && debug)
console.time('hooks.columnsBeforeHeaderGroups')
let flatColumns = React.useMemo(
() =>
reduceHooks(
getFlatColumns(),
flattenBy(columns, 'columns'),
getInstance()
),
[
columns,
getFlatColumns,
getInstance,
// eslint-disable-next-line react-hooks/exhaustive-deps
getFlatColumnsDeps(getInstance()),
]
)
let newColumns = applyHooks(
instanceRef.current.hooks.columnsBeforeHeaderGroups,
flattenBy(columns, 'columns'),
instanceRef.current
)
getInstance().flatColumns = flatColumns
if (process.env.NODE_ENV !== 'production' && debug)
console.timeEnd('hooks.columnsBeforeHeaderGroups')
return newColumns
}, [
columns,
debug,
// eslint-disable-next-line react-hooks/exhaustive-deps
...applyHooks(
instanceRef.current.hooks.columnsBeforeHeaderGroupsDeps,
[],
instanceRef.current
),
])
// 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
...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(() => {
if (process.env.NODE_ENV !== 'production' && debug)
console.time('getAccessedRows')
let flatRows = []
// Access the row's data
@@ -227,44 +298,53 @@ export const useTable = (props, ...plugins) => {
// Use the resolved data
const accessedData = data.map((d, i) => accessRow(d, i))
if (process.env.NODE_ENV !== 'production' && debug)
console.timeEnd('getAccessedRows')
return [accessedData, flatRows]
}, [debug, data, getRowId, getSubRows, flatColumns])
instanceRef.current.rows = rows
instanceRef.current.flatRows = flatRows
return [accessedData, flatRows]
}, [data, flatColumns, getRowId, getSubRows])
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],
[]
)
if (process.env.NODE_ENV !== 'production' && debug)
console.time('hooks.useInstanceBeforeDimensions')
instanceRef.current = applyHooks(
instanceRef.current.hooks.useInstanceBeforeDimensions,
instanceRef.current
// Snapshot hook and disallow more from being added
const getUseInstanceBeforeDimensions = useConsumeHookGetter(
getInstance().hooks,
'useInstanceBeforeDimensions'
)
if (process.env.NODE_ENV !== 'production' && debug)
console.timeEnd('hooks.useInstanceBeforeDimensions')
loopHooks(getUseInstanceBeforeDimensions(), getInstance())
// Header Visibility is needed by this point
calculateDimensions(instanceRef.current)
getInstance().totalColumnsWidth = calculateHeaderWidths(headers)
if (process.env.NODE_ENV !== 'production' && debug)
console.time('hooks.useInstance')
instanceRef.current = applyHooks(
instanceRef.current.hooks.useInstance,
instanceRef.current
// Snapshot hook and disallow more from being added
const getUseInstance = useConsumeHookGetter(
getInstance().hooks,
'useInstance'
)
loopHooks(getUseInstance(), getInstance())
// Snapshot hook and disallow more from being added
const getHeaderPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getHeaderProps'
)
// Snapshot hook and disallow more from being added
const getFooterPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getFooterProps'
)
if (process.env.NODE_ENV !== 'production' && debug)
console.timeEnd('hooks.useInstance')
// 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
@@ -274,44 +354,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(
instanceRef.current.hooks.getHeaderProps,
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(
instanceRef.current.hooks.getFooterProps,
column,
instanceRef.current
),
props
)
column.getFooterProps = makePropGetter(
getFooterPropsHooks(),
getInstance(),
column
)
})
instanceRef.current.headerGroups = instanceRef.current.headerGroups.filter(
// Snapshot hook and disallow more from being added
const getHeaderGroupPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getHeaderGroupProps'
)
// Snapshot hook and disallow more from being added
const getFooterGroupPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getFooterGroupProps'
)
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 => {
@@ -330,31 +406,19 @@ export const useTable = (props, ...plugins) => {
// Give headerGroups getRowProps
if (headerGroup.headers.length) {
headerGroup.getHeaderGroupProps = (props = {}) =>
mergeProps(
{
key: [`header${i}`].join('_'),
},
applyPropHooks(
instanceRef.current.hooks.getHeaderGroupProps,
headerGroup,
instanceRef.current
),
props
)
headerGroup.getHeaderGroupProps = makePropGetter(
getHeaderGroupPropsHooks(),
getInstance(),
headerGroup,
i
)
headerGroup.getFooterGroupProps = (props = {}) =>
mergeProps(
{
key: [`footer${i}`].join('_'),
},
applyPropHooks(
instanceRef.current.hooks.getFooterGroupProps,
headerGroup,
instanceRef.current
),
props
)
headerGroup.getFooterGroupProps = makePropGetter(
getFooterGroupPropsHooks(),
getInstance(),
headerGroup,
i
)
return true
}
@@ -363,111 +427,118 @@ 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)
if (process.env.NODE_ENV !== 'production' && debug)
console.time('hooks.useRows')
instanceRef.current.rows = applyHooks(
instanceRef.current.hooks.useRows,
instanceRef.current.rows,
instanceRef.current
// Snapshot hook and disallow more from being added
const getUseRowsHooks = useConsumeHookGetter(getInstance().hooks, 'useRows')
getInstance().rows = reduceHooks(
getUseRowsHooks(),
getInstance().rows,
getInstance()
)
if (process.env.NODE_ENV !== 'production' && debug)
console.timeEnd('hooks.useRows')
// The prepareRow function is absolutely necessary and MUST be called on
// any rows the user wishes to be displayed.
instanceRef.current.prepareRow = React.useCallback(row => {
row.getRowProps = props =>
mergeProps(
{ key: ['row', ...row.path].join('_') },
applyPropHooks(
instanceRef.current.hooks.getRowProps,
row,
instanceRef.current
),
props
)
// Snapshot hook and disallow more from being added
const getPrepareRowHooks = useConsumeHookGetter(
getInstance().hooks,
'prepareRow'
)
// Build the visible cells for each row
row.cells = instanceRef.current.flatColumns
.filter(d => d.isVisible)
.map(column => {
const cell = {
column,
row,
value: row.values[column.id],
}
// Snapshot hook and disallow more from being added
const getRowPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getRowProps'
)
// Give each cell a getCellProps base
cell.getCellProps = props => {
const columnPathStr = [...row.path, column.id].join('_')
return mergeProps(
{
key: ['cell', columnPathStr].join('_'),
},
applyPropHooks(
instanceRef.current.hooks.getCellProps,
cell,
instanceRef.current
),
props
)
}
// Snapshot hook and disallow more from being added
const getCellPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getCellProps'
)
// Give each cell a renderer function (supports multiple renderers)
cell.render = (type, userProps = {}) => {
const Comp = typeof type === 'string' ? column[type] : type
getInstance().prepareRow = React.useCallback(
row => {
row.getRowProps = makePropGetter(getRowPropsHooks(), getInstance(), row)
if (typeof Comp === 'undefined') {
throw new Error(renderErr)
}
return flexRender(Comp, {
...instanceRef.current,
// Build the visible cells for each row
row.cells = getInstance()
.flatColumns.filter(d => d.isVisible)
.map(column => {
const cell = {
column,
row,
cell,
...userProps,
})
}
value: row.values[column.id],
}
return cell
})
// Give each cell a getCellProps base
cell.getCellProps = makePropGetter(
getCellPropsHooks(),
getInstance(),
cell
)
// need to apply any row specific hooks (useExpanded requires this)
applyHooks(instanceRef.current.hooks.prepareRow, row, instanceRef.current)
}, [])
// Give each cell a renderer function (supports multiple renderers)
cell.render = (type, userProps = {}) => {
const Comp = typeof type === 'string' ? column[type] : type
instanceRef.current.getTableProps = userProps =>
mergeProps(
applyPropHooks(
instanceRef.current.hooks.getTableProps,
instanceRef.current
),
userProps
)
if (typeof Comp === 'undefined') {
throw new Error(renderErr)
}
instanceRef.current.getTableBodyProps = userProps =>
mergeProps(
applyPropHooks(
instanceRef.current.hooks.getTableBodyProps,
instanceRef.current
),
userProps
)
return flexRender(Comp, {
...getInstance(),
column,
row,
cell,
...userProps,
})
}
return instanceRef.current
}
return cell
})
function calculateDimensions(instance) {
const { headers } = instance
// need to apply any row specific hooks (useExpanded requires this)
loopHooks(getPrepareRowHooks(), row, getInstance())
},
[getCellPropsHooks, getInstance, getPrepareRowHooks, getRowPropsHooks]
)
instance.totalColumnsWidth = calculateHeaderWidths(headers)
// Snapshot hook and disallow more from being added
const getTablePropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getTableProps'
)
getInstance().getTableProps = makePropGetter(
getTablePropsHooks(),
getInstance()
)
// Snapshot hook and disallow more from being added
const getTableBodyPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getTableBodyProps'
)
getInstance().getTableBodyProps = makePropGetter(
getTableBodyPropsHooks(),
getInstance()
)
// Snapshot hook and disallow more from being added
const getUseFinalInstanceHooks = useConsumeHookGetter(
getInstance().hooks,
'useFinalInstance'
)
loopHooks(getUseFinalInstanceHooks(), getInstance())
return getInstance()
}
function calculateHeaderWidths(headers, left = 0) {
+1 -1
View File
@@ -1,4 +1,4 @@
export * from './utils'
export * from './publicUtils'
export { useTable } from './hooks/useTable'
export { useExpanded } from './plugin-hooks/useExpanded'
export { useFilters } from './plugin-hooks/useFilters'
+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.path].join('_'),
...props,
})
const defaultGetCellProps = (props, instance, cell) => ({
...props,
key: ['cell', ...cell.row.path, 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: [],
}
}
+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'
+15 -22
View File
@@ -1,15 +1,23 @@
import React from 'react'
import { reducerHandlers, functionalUpdate, actions } from '../utils'
const pluginName = 'useColumnOrder'
import { functionalUpdate, actions } from '../utils'
// Actions
actions.resetColumnOrder = 'resetColumnOrder'
actions.setColumnOrder = 'setColumnOrder'
// Reducer
reducerHandlers[pluginName] = (state, action) => {
export const useColumnOrder = hooks => {
hooks.stateReducers.push(reducer)
hooks.flatColumnsDeps.push((deps, instance) => {
return [...deps, instance.state.columnOrder]
})
hooks.flatColumns.push(flatColumns)
hooks.useInstance.push(useInstance)
}
useColumnOrder.pluginName = 'useColumnOrder'
function reducer(state, action) {
if (action.type === actions.init) {
return {
columnOrder: [],
@@ -32,17 +40,7 @@ reducerHandlers[pluginName] = (state, action) => {
}
}
export const useColumnOrder = hooks => {
hooks.columnsBeforeHeaderGroupsDeps.push((deps, instance) => {
return [...deps, instance.state.columnOrder]
})
hooks.columnsBeforeHeaderGroups.push(columnsBeforeHeaderGroups)
hooks.useInstance.push(useInstance)
}
useColumnOrder.pluginName = pluginName
function columnsBeforeHeaderGroups(columns, instance) {
function flatColumns(columns, instance) {
const {
state: { columnOrder },
} = instance
@@ -76,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,
}
}
+54 -66
View File
@@ -2,21 +2,41 @@ import React from 'react'
import {
actions,
reducerHandlers,
mergeProps,
applyPropHooks,
makePropGetter,
expandRows,
safeUseLayoutEffect,
useMountedLayoutEffect,
useGetLatest,
} from '../utils'
const pluginName = 'useExpanded'
import { useConsumeHookGetter } from '../publicUtils'
// Actions
actions.toggleExpandedByPath = 'toggleExpandedByPath'
actions.resetExpanded = 'resetExpanded'
export const useExpanded = hooks => {
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
reducerHandlers[pluginName] = (state, action) => {
function reducer(state, action) {
if (action.type === actions.init) {
return {
expanded: [],
@@ -35,7 +55,7 @@ reducerHandlers[pluginName] = (state, action) => {
const { path, expanded } = action
const key = path.join('.')
const exists = state.expanded.includes(key)
const shouldExist = typeof set !== 'undefined' ? expanded : !exists
const shouldExist = typeof expanded !== 'undefined' ? expanded : !exists
let newExpanded = new Set(state.expanded)
if (!exists && shouldExist) {
@@ -53,99 +73,67 @@ reducerHandlers[pluginName] = (state, action) => {
}
}
export const useExpanded = hooks => {
hooks.getExpandedToggleProps = []
hooks.useInstance.push(useInstance)
}
useExpanded.pluginName = pluginName
const defaultGetResetExpandedDeps = ({ data }) => [data]
function useInstance(instance) {
const {
debug,
data,
rows,
manualExpandedKey = 'expanded',
paginateExpandedRows = true,
expandSubRows = true,
hooks,
autoResetExpanded = true,
state: { expanded },
dispatch,
getResetExpandedDeps = defaultGetResetExpandedDeps,
} = instance
const getAutoResetExpanded = useGetLatest(autoResetExpanded)
// Bypass any effects from firing when this changes
const isMountedRef = React.useRef()
safeUseLayoutEffect(() => {
if (isMountedRef.current) {
useMountedLayoutEffect(() => {
if (getAutoResetExpanded()) {
dispatch({ type: actions.resetExpanded })
}
isMountedRef.current = true
}, [
dispatch,
...(getResetExpandedDeps ? getResetExpandedDeps(instance) : []),
])
}, [dispatch, data])
const toggleExpandedByPath = (path, expanded) => {
dispatch({ type: actions.toggleExpandedByPath, path, 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.toggleExpandedByPath(row.path, set)
row.getExpandedToggleProps = makePropGetter(
getExpandedTogglePropsHooks(),
getInstance(),
row
)
})
const expandedRows = React.useMemo(() => {
if (process.env.NODE_ENV !== 'production' && debug)
console.info('getExpandedRows')
if (paginateExpandedRows) {
return expandRows(rows, { manualExpandedKey, expanded, expandSubRows })
}
return rows
}, [
debug,
paginateExpandedRows,
rows,
manualExpandedKey,
expanded,
expandSubRows,
])
}, [paginateExpandedRows, rows, manualExpandedKey, expanded, expandSubRows])
const expandedDepth = findExpandedDepth(expanded)
return {
...instance,
Object.assign(instance, {
toggleExpandedByPath,
expandedDepth,
preExpandedRows: rows,
expandedRows,
rows: expandedRows,
}
expandedDepth,
})
}
function findExpandedDepth(expanded) {
+28 -66
View File
@@ -2,23 +2,27 @@ import React from 'react'
import {
actions,
reducerHandlers,
getFirstDefined,
isFunction,
safeUseLayoutEffect,
useMountedLayoutEffect,
functionalUpdate,
useGetLatest,
} from '../utils'
import * as filterTypes from '../filterTypes'
const pluginName = 'useFilters'
// Actions
actions.resetFilters = 'resetFilters'
actions.setFilter = 'setFilter'
actions.setAllFilters = 'setAllFilters'
// Reducer
reducerHandlers[pluginName] = (state, action) => {
export const useFilters = hooks => {
hooks.stateReducers.push(reducer)
hooks.useInstance.push(useInstance)
}
useFilters.pluginName = 'useFilters'
function reducer(state, action, previousState, instanceRef) {
if (action.type === actions.init) {
return {
filters: {},
@@ -34,14 +38,8 @@ reducerHandlers[pluginName] = (state, action) => {
}
if (action.type === actions.setFilter) {
const {
columnId,
filterValue,
instanceRef: {
current: { flatColumns, userFilterTypes },
},
} = action
const { columnId, filterValue } = action
const { flatColumns, userFilterTypes } = instanceRef.current
const column = flatColumns.find(d => d.id === columnId)
if (!column) {
@@ -78,13 +76,8 @@ reducerHandlers[pluginName] = (state, action) => {
}
if (action.type === actions.setAllFilters) {
const {
filters,
instanceRef: {
current: { flatColumns, filterTypes: userFilterTypes },
},
} = action
const { filters } = action
const { flatColumns, filterTypes: userFilterTypes } = instanceRef.current
const newFilters = functionalUpdate(filters, state.filters)
// Filter out undefined values
@@ -109,15 +102,9 @@ reducerHandlers[pluginName] = (state, action) => {
}
}
export const useFilters = hooks => {
hooks.useInstance.push(useInstance)
}
useFilters.pluginName = pluginName
function useInstance(instance) {
const {
debug,
data,
rows,
flatRows,
flatColumns,
@@ -127,12 +114,9 @@ function useInstance(instance) {
disableFilters,
state: { filters },
dispatch,
getResetFiltersDeps = false,
autoResetFilters = true,
} = instance
const preFilteredRows = rows
const preFilteredFlatRows = flatRows
const setFilter = (columnId, filterValue) => {
dispatch({ type: actions.setFilter, columnId, filterValue })
}
@@ -184,9 +168,6 @@ function useInstance(instance) {
const filteredFlatRows = []
if (process.env.NODE_ENV !== 'production' && debug)
console.info('getFilteredRows')
// Filters top level and nested rows
const filterRows = (rows, depth = 0) => {
let filteredRows = rows
@@ -256,15 +237,7 @@ function useInstance(instance) {
filteredRows: filterRows(rows),
filteredFlatRows,
}
}, [
manualFilters,
filters,
debug,
rows,
flatRows,
flatColumns,
userFilterTypes,
])
}, [manualFilters, filters, rows, flatRows, flatColumns, userFilterTypes])
React.useMemo(() => {
// Now that each filtered column has it's partially filtered rows,
@@ -281,35 +254,24 @@ function useInstance(instance) {
})
}, [filteredRows, filters, flatColumns])
// Bypass any effects from firing when this changes
const isMountedRef = React.useRef()
safeUseLayoutEffect(() => {
if (isMountedRef.current) {
const getAutoResetFilters = useGetLatest(autoResetFilters)
useMountedLayoutEffect(() => {
if (getAutoResetFilters()) {
dispatch({ type: actions.resetFilters })
}
isMountedRef.current = true
}, [
dispatch,
...(getResetFiltersDeps
? getResetFiltersDeps({
...instance,
preFilteredRows,
preFilteredFlatRows,
rows: filteredRows,
flatRows: filteredFlatRows,
})
: []),
])
}, [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) {
+61 -55
View File
@@ -3,22 +3,50 @@ import React from 'react'
import * as aggregations from '../aggregations'
import {
actions,
reducerHandlers,
mergeProps,
applyPropHooks,
makePropGetter,
defaultGroupByFn,
getFirstDefined,
ensurePluginOrder,
useMountedLayoutEffect,
useGetLatest,
} from '../utils'
const pluginName = 'useGroupBy'
import { useConsumeHookGetter } from '../publicUtils'
// Actions
actions.resetGroupBy = 'resetGroupBy'
actions.toggleGroupBy = 'toggleGroupBy'
export const useGroupBy = hooks => {
hooks.getGroupByToggleProps = [defaultGetGroupByToggleProps]
hooks.stateReducers.push(reducer)
hooks.flatColumnsDeps.push((deps, instance) => [
...deps,
instance.state.groupBy,
])
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
reducerHandlers[pluginName] = (state, action) => {
function reducer(state, action) {
if (action.type === actions.init) {
return {
groupBy: [],
@@ -53,18 +81,7 @@ reducerHandlers[pluginName] = (state, action) => {
}
}
export const useGroupBy = hooks => {
hooks.columnsBeforeHeaderGroups.push(columnsBeforeHeaderGroups)
hooks.columnsBeforeHeaderGroupsDeps.push((deps, instance) => {
deps.push(instance.state.groupBy)
return deps
})
hooks.useInstance.push(useInstance)
}
useGroupBy.pluginName = pluginName
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
@@ -86,7 +103,7 @@ const defaultUserAggregations = {}
function useInstance(instance) {
const {
debug,
data,
rows,
flatRows,
flatColumns,
@@ -100,10 +117,14 @@ function useInstance(instance) {
plugins,
state: { groupBy },
dispatch,
autoResetGroupBy = true,
manaulGroupBy,
} = instance
ensurePluginOrder(plugins, [], 'useGroupBy', ['useSortBy', 'useExpanded'])
const getInstance = useGetLatest(instance)
flatColumns.forEach(column => {
const {
id,
@@ -133,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 => {
@@ -175,7 +177,6 @@ function useInstance(instance) {
cell.isAggregated =
!cell.isGrouped && !cell.isRepeatedValue && row.canExpand
})
return row
})
const [groupedRows, groupedFlatRows] = React.useMemo(() => {
@@ -183,10 +184,7 @@ function useInstance(instance) {
return [rows, flatRows]
}
if (process.env.NODE_ENV !== 'production' && debug)
console.info('getGroupedRows')
// Find the columns that can or are aggregating
// Uses each column to aggregate rows into a single value
const aggregateRowsToValues = (rows, isAggregated) => {
const values = {}
@@ -289,7 +287,6 @@ function useInstance(instance) {
}, [
manualGroupBy,
groupBy,
debug,
rows,
flatRows,
flatColumns,
@@ -297,11 +294,20 @@ function useInstance(instance) {
groupByFn,
])
return {
...instance,
const getAutoResetGroupBy = useGetLatest(autoResetGroupBy)
useMountedLayoutEffect(() => {
if (getAutoResetGroupBy()) {
dispatch({ type: actions.resetGroupBy })
}
}, [dispatch, manaulGroupBy ? null : data])
Object.assign(instance, {
groupedRows,
groupedFlatRows,
toggleGroupBy,
rows: groupedRows,
flatRows: groupedFlatRows,
preGroupedRows: rows,
}
})
}
+31 -36
View File
@@ -4,11 +4,11 @@ import React from 'react'
import {
actions,
reducerHandlers,
ensurePluginOrder,
safeUseLayoutEffect,
expandRows,
functionalUpdate,
useMountedLayoutEffect,
useGetLatest,
} from '../utils'
const pluginName = 'usePagination'
@@ -18,8 +18,14 @@ actions.resetPage = 'resetPage'
actions.gotoPage = 'gotoPage'
actions.setPageSize = 'setPageSize'
// Reducer
reducerHandlers[pluginName] = (state, action) => {
export const usePagination = hooks => {
hooks.stateReducers.push(reducer)
hooks.useInstance.push(useInstance)
}
usePagination.pluginName = pluginName
function reducer(state, action, previousState, instanceRef) {
if (action.type === actions.init) {
return {
pageSize: 10,
@@ -36,7 +42,7 @@ reducerHandlers[pluginName] = (state, action) => {
}
if (action.type === actions.gotoPage) {
const { pageCount } = action.instanceRef.current
const { pageCount } = instanceRef.current
const newPageIndex = functionalUpdate(action.pageIndex, state.pageIndex)
if (newPageIndex < 0 || newPageIndex > pageCount - 1) {
@@ -61,31 +67,22 @@ reducerHandlers[pluginName] = (state, action) => {
}
}
export const usePagination = hooks => {
hooks.useInstance.push(useInstance)
}
usePagination.pluginName = pluginName
const defaultGetResetPageDeps = ({
data,
manualPagination,
state: { filters, groupBy, sortBy },
}) => [manualPagination ? null : data, filters, groupBy, sortBy]
function useInstance(instance) {
const {
rows,
manualPagination,
getResetPageDeps = defaultGetResetPageDeps,
autoResetPage = true,
manualExpandedKey = 'expanded',
debug,
plugins,
pageCount: userPageCount,
paginateExpandedRows = true,
expandSubRows = true,
state: { pageSize, pageIndex, expanded },
state: { pageSize, pageIndex, expanded, filters, groupBy, sortBy },
dispatch,
data,
manualPagination,
manualFilters,
manualGroupBy,
manualSortBy,
} = instance
ensurePluginOrder(
@@ -95,14 +92,19 @@ function useInstance(instance) {
[]
)
// Bypass any effects from firing when this changes
const isMountedRef = React.useRef()
safeUseLayoutEffect(() => {
if (isMountedRef.current) {
const getAutoResetPage = useGetLatest(autoResetPage)
useMountedLayoutEffect(() => {
if (getAutoResetPage()) {
dispatch({ type: actions.resetPage })
}
isMountedRef.current = true
}, [dispatch, ...(getResetPageDeps ? getResetPageDeps(instance) : [])])
}, [
dispatch,
manualPagination ? null : data,
manualPagination || manualFilters ? null : filters,
manualPagination || manualGroupBy ? null : groupBy,
manualPagination || manualSortBy ? null : sortBy,
])
const pageCount = manualPagination
? userPageCount
@@ -119,9 +121,6 @@ function useInstance(instance) {
if (manualPagination) {
page = rows
} else {
if (process.env.NODE_ENV !== 'production' && debug)
console.info('getPage')
const pageStart = pageSize * pageIndex
const pageEnd = pageStart + pageSize
@@ -134,7 +133,6 @@ function useInstance(instance) {
return expandRows(page, { manualExpandedKey, expanded, expandSubRows })
}, [
debug,
expandSubRows,
expanded,
manualExpandedKey,
@@ -170,8 +168,7 @@ function useInstance(instance) {
[dispatch]
)
return {
...instance,
Object.assign(instance, {
pageOptions,
pageCount,
page,
@@ -181,7 +178,5 @@ function useInstance(instance) {
previousPage,
nextPage,
setPageSize,
pageIndex,
pageSize,
}
})
}
+122 -76
View File
@@ -1,15 +1,11 @@
import React from 'react'
import {
actions,
reducerHandlers,
defaultColumn,
getFirstDefined,
mergeProps,
applyPropHooks,
makePropGetter,
useGetLatest,
} from '../utils'
const pluginName = 'useResizeColumns'
import { useConsumeHookGetter } from '../publicUtils'
// Default Column
defaultColumn.canResize = true
@@ -19,8 +15,111 @@ actions.columnStartResizing = 'columnStartResizing'
actions.columnResizing = 'columnResizing'
actions.columnDoneResizing = 'columnDoneResizing'
// Reducer
reducerHandlers[pluginName] = (state, action) => {
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) {
if (action.type === actions.init) {
return {
columnResizing: {
@@ -85,65 +184,26 @@ reducerHandlers[pluginName] = (state, action) => {
}
}
export const useResizeColumns = hooks => {
hooks.useInstanceBeforeDimensions.push(useInstanceBeforeDimensions)
}
useResizeColumns.pluginName = pluginName
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 getInstance = useGetLatest(instance)
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 instanceRef = React.useRef()
instanceRef.current = instance
const getResizerPropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getResizerProps'
)
flatHeaders.forEach(header => {
const canResize = getFirstDefined(
@@ -157,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(
instanceRef.current.hooks.getResizerProps,
header,
instanceRef.current
),
userProps
)
}
header.getResizerProps = makePropGetter(
getResizerPropsHooks(),
getInstance(),
header
)
}
})
return instance
}
function getLeafHeaders(header) {
+87 -96
View File
@@ -2,11 +2,11 @@ import React from 'react'
import {
actions,
reducerHandlers,
mergeProps,
applyPropHooks,
makePropGetter,
ensurePluginOrder,
safeUseLayoutEffect,
useGetLatest,
useMountedLayoutEffect,
useConsumeHookGetter,
} from '../utils'
const pluginName = 'useRowSelect'
@@ -16,8 +16,56 @@ actions.resetSelectedRows = 'resetSelectedRows'
actions.toggleRowSelectedAll = 'toggleRowSelectedAll'
actions.toggleRowSelected = 'toggleRowSelected'
// Reducer
reducerHandlers[pluginName] = (state, action) => {
export const useRowSelect = hooks => {
hooks.getToggleRowSelectedProps = [defaultGetToggleRowSelectedProps]
hooks.getToggleAllRowsSelectedProps = [defaultGetToggleAllRowsSelectedProps]
hooks.stateReducers.push(reducer)
hooks.useRows.push(useRows)
hooks.useInstance.push(useInstance)
}
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',
},
]
}
const defaultGetToggleAllRowsSelectedProps = (props, instance) => [
props,
{
onChange: e => {
instance.toggleRowSelectedAll(e.target.checked)
},
style: {
cursor: 'pointer',
},
checked: instance.isAllRowsSelected,
title: 'Toggle All Rows Selected',
},
]
function reducer(state, action, previousState, instanceRef) {
if (action.type === actions.init) {
return {
selectedRowPaths: new Set(),
@@ -33,12 +81,8 @@ reducerHandlers[pluginName] = (state, action) => {
}
if (action.type === actions.toggleRowSelectedAll) {
const {
selected,
instanceRef: {
current: { isAllRowsSelected, flatRowPaths },
},
} = action
const { selected } = action
const { isAllRowsSelected, flatRowPaths } = instanceRef.current
const selectAll =
typeof selected !== 'undefined' ? selected : !isAllRowsSelected
@@ -50,13 +94,8 @@ reducerHandlers[pluginName] = (state, action) => {
}
if (action.type === actions.toggleRowSelected) {
const {
path,
selected,
instanceRef: {
current: { flatRowPaths },
},
} = action
const { path, selected } = action
const { flatRowPaths } = instanceRef.current
const key = path.join('.')
const childRowPrefixKey = [key, '.'].join('')
@@ -116,15 +155,6 @@ reducerHandlers[pluginName] = (state, action) => {
}
}
export const useRowSelect = hooks => {
hooks.getToggleRowSelectedProps = []
hooks.getToggleAllRowsSelectedProps = []
hooks.useRows.push(useRows)
hooks.useInstance.push(useInstance)
}
useRowSelect.pluginName = pluginName
function useRows(rows, instance) {
const {
state: { selectedRowPaths },
@@ -147,15 +177,13 @@ function useRows(rows, instance) {
return rows
}
const defaultGetResetSelectedRowPathsDeps = ({ data }) => [data]
function useInstance(instance) {
const {
data,
hooks,
manualRowSelectedKey = 'isSelected',
plugins,
flatRows,
getResetSelectedRowPathsDeps = defaultGetResetSelectedRowPathsDeps,
autoResetSelectedRows = true,
state: { selectedRowPaths },
dispatch,
} = instance
@@ -177,19 +205,13 @@ function useInstance(instance) {
}
}
// Bypass any effects from firing when this changes
const isMountedRef = React.useRef()
safeUseLayoutEffect(() => {
if (isMountedRef.current) {
const getAutoResetSelectedRows = useGetLatest(autoResetSelectedRows)
useMountedLayoutEffect(() => {
if (getAutoResetSelectedRows()) {
dispatch({ type: actions.resetSelectedRows })
}
isMountedRef.current = true
}, [
dispatch,
...(getResetSelectedRowPathsDeps
? getResetSelectedRowPathsDeps(instance)
: []),
])
}, [dispatch, data])
const toggleRowSelectedAll = selected =>
dispatch({ type: actions.toggleRowSelectedAll, selected })
@@ -198,71 +220,40 @@ function useInstance(instance) {
dispatch({ type: actions.toggleRowSelected, path, 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
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,
Object.assign(instance, {
flatRowPaths,
toggleRowSelected,
toggleRowSelectedAll,
getToggleAllRowsSelectedProps,
isAllRowsSelected,
}
})
}
function getRowIsSelected(row, selectedRowPaths) {
+22 -34
View File
@@ -2,19 +2,23 @@ import React from 'react'
import {
actions,
reducerHandlers,
functionalUpdate,
safeUseLayoutEffect,
useMountedLayoutEffect,
useGetLatest,
} from '../utils'
const pluginName = 'useRowState'
// Actions
actions.setRowState = 'setRowState'
actions.resetRowState = 'resetRowState'
// Reducer
reducerHandlers[pluginName] = (state, action) => {
export const useRowState = hooks => {
hooks.stateReducers.push(reducer)
hooks.useInstance.push(useInstance)
}
useRowState.pluginName = 'useRowState'
function reducer(state, action) {
if (action.type === actions.init) {
return {
rowState: {},
@@ -44,20 +48,13 @@ reducerHandlers[pluginName] = (state, action) => {
}
}
export const useRowState = hooks => {
hooks.useInstance.push(useInstance)
}
useRowState.pluginName = pluginName
const defaultGetResetRowStateDeps = ({ data }) => [data]
function useInstance(instance) {
const {
hooks,
initialRowStateAccessor,
getResetRowStateDeps = defaultGetResetRowStateDeps,
autoResetRowState = true,
state: { rowState },
data,
dispatch,
} = instance
@@ -94,20 +91,6 @@ function useInstance(instance) {
[setRowState]
)
const rowsMountedRef = React.useRef()
// When data changes, reset row and cell state
safeUseLayoutEffect(() => {
if (rowsMountedRef.current) {
dispatch({ type: actions.resetRowState })
}
rowsMountedRef.current = true
}, [
dispatch,
...(getResetRowStateDeps ? getResetRowStateDeps(instance) : []),
])
hooks.prepareRow.push(row => {
const pathKey = row.path.join('.')
@@ -129,13 +112,18 @@ function useInstance(instance) {
}
})
}
return row
})
return {
...instance,
const getAutoResetRowState = useGetLatest(autoResetRowState)
useMountedLayoutEffect(() => {
if (getAutoResetRowState()) {
dispatch({ type: actions.resetRowState })
}
}, [data])
Object.assign(instance, {
setRowState,
setCellState,
}
})
}
+74 -99
View File
@@ -2,28 +2,60 @@ import React from 'react'
import {
actions,
reducerHandlers,
ensurePluginOrder,
defaultColumn,
safeUseLayoutEffect,
mergeProps,
applyPropHooks,
makePropGetter,
useConsumeHookGetter,
getFirstDefined,
defaultOrderByFn,
isFunction,
useGetLatest,
useMountedLayoutEffect,
} from '../utils'
import * as sortTypes from '../sortTypes'
const pluginName = 'useSortBy'
// Actions
actions.resetSortBy = 'resetSortBy'
actions.toggleSortBy = 'toggleSortBy'
actions.clearSortBy = 'clearSortBy'
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
reducerHandlers[pluginName] = (state, action) => {
function reducer(state, action, previousState, instanceRef) {
if (action.type === actions.init) {
return {
sortBy: [],
@@ -40,7 +72,7 @@ reducerHandlers[pluginName] = (state, action) => {
if (action.type === actions.clearSortBy) {
const { sortBy } = state
const newSortBy = sortBy.filter(d => d.id !== action.columnID)
const newSortBy = sortBy.filter(d => d.id !== action.columnId)
return {
...state,
@@ -49,20 +81,16 @@ reducerHandlers[pluginName] = (state, action) => {
}
if (action.type === actions.toggleSortBy) {
const { columnId, desc, multi } = action
const {
columnId,
desc,
multi,
instanceRef: {
current: {
flatColumns,
disableMultiSort,
disableSortRemove,
disableMultiRemove,
maxMultiSortColCount = Number.MAX_SAFE_INTEGER,
},
},
} = action
flatColumns,
disableMultiSort,
disableSortRemove,
disableMultiRemove,
maxMultiSortColCount = Number.MAX_SAFE_INTEGER,
} = instanceRef.current
const { sortBy } = state
// Find the column for this columnId
@@ -149,37 +177,24 @@ reducerHandlers[pluginName] = (state, action) => {
}
}
defaultColumn.sortType = 'alphanumeric'
defaultColumn.sortDescFirst = false
export const useSortBy = hooks => {
hooks.useInstance.push(useInstance)
}
useSortBy.pluginName = pluginName
function useInstance(instance) {
const {
debug,
data,
rows,
flatColumns,
orderByFn = defaultOrderByFn,
sortTypes: userSortTypes,
manualSorting,
manualSortBy,
defaultCanSort,
disableSortBy,
isMultiSortEvent = e => e.shiftKey,
flatHeaders,
hooks,
state: { sortBy },
dispatch,
plugins,
getResetSortByDeps = false,
autoResetSortBy = true,
} = 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) => {
@@ -187,8 +202,12 @@ function useInstance(instance) {
}
// use reference to avoid memory leak in #1608
const instanceRef = React.useRef()
instanceRef.current = instance
const getInstance = useGetLatest(instance)
const getSortByTogglePropsHooks = useConsumeHookGetter(
getInstance().hooks,
'getSortByToggleProps'
)
// Add the getSortByToggleProps method to columns and headers
flatHeaders.forEach(column => {
@@ -218,31 +237,11 @@ function useInstance(instance) {
}
}
column.getSortByToggleProps = props => {
return mergeProps(
{
onClick: canSort
? e => {
e.persist()
column.toggleSortBy(
undefined,
!instanceRef.current.disableMultiSort && isMultiSortEvent(e)
)
}
: undefined,
style: {
cursor: canSort ? 'pointer' : undefined,
},
title: canSort ? 'Toggle SortBy' : undefined,
},
applyPropHooks(
instanceRef.current.hooks.getSortByToggleProps,
column,
instanceRef.current
),
props
)
}
column.getSortByToggleProps = makePropGetter(
getSortByTogglePropsHooks(),
getInstance(),
column
)
const columnSort = sortBy.find(d => d.id === id)
column.isSorted = !!columnSort
@@ -251,11 +250,9 @@ function useInstance(instance) {
})
const sortedRows = React.useMemo(() => {
if (manualSorting || !sortBy.length) {
if (manualSortBy || !sortBy.length) {
return rows
}
if (process.env.NODE_ENV !== 'production' && debug)
console.time('getSortedRows')
// Filter out sortBys that correspond to non existing columns
const availableSortBy = sortBy.filter(sort =>
@@ -326,43 +323,21 @@ function useInstance(instance) {
return sortedData
}
if (process.env.NODE_ENV !== 'production' && debug)
console.timeEnd('getSortedRows')
return sortData(rows)
}, [
manualSorting,
sortBy,
debug,
rows,
flatColumns,
orderByFn,
userSortTypes,
])
}, [manualSortBy, sortBy, rows, flatColumns, orderByFn, userSortTypes])
// Bypass any effects from firing when this changes
const isMountedRef = React.useRef()
safeUseLayoutEffect(() => {
if (isMountedRef.current) {
const getAutoResetSortBy = useGetLatest(autoResetSortBy)
useMountedLayoutEffect(() => {
if (getAutoResetSortBy()) {
dispatch({ type: actions.resetSortBy })
}
isMountedRef.current = true
}, [
dispatch,
...(getResetSortByDeps
? getResetSortByDeps({
...instance,
toggleSortBy,
rows: sortedRows,
preSortedRows: rows,
})
: []),
])
}, [manualSortBy ? null : data])
return {
...instance,
Object.assign(instance, {
toggleSortBy,
rows: sortedRows,
preSortedRows: rows,
}
sortedRows,
rows: sortedRows,
})
}
+222
View File
@@ -0,0 +1,222 @@
import React from 'react'
export const actions = {
init: 'init',
}
export const defaultColumn = {
Cell: ({ cell: { value = '' } }) => String(value),
width: 150,
minWidth: 0,
maxWidth: Number.MAX_SAFE_INTEGER,
}
export function defaultOrderByFn(arr, funcs, dirs) {
return [...arr].sort((rowA, rowB) => {
for (let i = 0; i < funcs.length; i += 1) {
const sortFn = funcs[i]
const desc = dirs[i] === false || dirs[i] === 'desc'
const sortInt = sortFn(rowA, rowB)
if (sortInt !== 0) {
return desc ? -sortInt : sortInt
}
}
return dirs[0] ? rowA.index - rowB.index : rowB.index - rowA.index
})
}
export function defaultGroupByFn(rows, columnId) {
return rows.reduce((prev, row, i) => {
// TODO: Might want to implement a key serializer here so
// irregular column values can still be grouped if needed?
const resKey = `${row.values[columnId]}`
prev[resKey] = Array.isArray(prev[resKey]) ? prev[resKey] : []
prev[resKey].push(row)
return prev
}, {})
}
function mergeProps(...propList) {
return propList.reduce((props, next) => {
const { style, className, ...rest } = next
props = {
...props,
...rest,
style: {
...(props.style || {}),
...(style || {}),
},
className: [props.className, className].filter(Boolean).join(' '),
}
if (props.className === '') {
delete props.className
}
return props
}, {})
}
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 (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 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(
plugin => plugin.pluginName === pluginName
)
if (pluginIndex === -1) {
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 => {
const beforeIndex = plugins.findIndex(
plugin => plugin.pluginName === before
)
if (beforeIndex > -1 && beforeIndex > pluginIndex) {
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 (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!`
)
}
}
})
}
export function functionalUpdate(updater, old) {
return typeof updater === 'function' ? updater(old) : updater
}
export function useGetLatest(obj) {
const ref = React.useRef()
ref.current = obj
return React.useCallback(() => ref.current, [])
}
// SSR has issues with useLayoutEffect still, so use useEffect during SSR
export const safeUseLayoutEffect =
typeof document !== 'undefined' ? React.useLayoutEffect : React.useEffect
export function useMountedLayoutEffect(fn, deps) {
const mountedRef = React.useRef(false)
safeUseLayoutEffect(() => {
if (mountedRef.current) {
fn()
}
mountedRef.current = true
// eslint-disable-next-line
}, deps)
}
export function useAsyncDebounce(defaultFn, defaultWait = 0) {
const debounceRef = React.useRef({})
debounceRef.current.defaultFn = defaultFn
debounceRef.current.defaultWait = defaultWait
const debounce = React.useCallback(
async (
fn = debounceRef.current.defaultFn,
wait = debounceRef.current.defaultWait
) => {
if (!debounceRef.current.promise) {
debounceRef.current.promise = new Promise((resolve, reject) => {
debounceRef.current.resolve = resolve
debounceRef.current.reject = reject
})
}
if (debounceRef.current.timeout) {
clearTimeout(debounceRef.current.timeout)
}
debounceRef.current.timeout = setTimeout(async () => {
delete debounceRef.current.timeout
try {
debounceRef.current.resolve(await fn())
} catch (err) {
debounceRef.current.reject(err)
} finally {
delete debounceRef.current.promise
}
}, wait)
return debounceRef.current.promise
},
[]
)
return debounce
}
export function useConsumeHookGetter(hooks, hookName) {
const getter = useGetLatest(hooks[hookName])
hooks[hookName] = undefined
return getter
}
+16 -139
View File
@@ -1,23 +1,7 @@
import React from 'react'
import { defaultColumn } from './publicUtils'
export const actions = {
init: 'init',
}
export const reducerHandlers = {}
export const defaultColumn = {
Cell: ({ cell: { value = '' } }) => String(value),
width: 150,
minWidth: 0,
maxWidth: Number.MAX_SAFE_INTEGER,
}
// SSR has issues with useLayoutEffect still, so use useEffect during SSR
export const safeUseLayoutEffect =
typeof window !== 'undefined' && process.env.NODE_ENV === 'production'
? React.useLayoutEffect
: React.useEffect
export * from './publicUtils'
// Find the depth of the columns
export function findMaxDepth(columns, depth = 0) {
@@ -29,13 +13,7 @@ export function findMaxDepth(columns, depth = 0) {
}, 0)
}
export function decorateColumn(
column,
userDefaultColumn,
parent,
depth,
index
) {
function decorateColumn(column, userDefaultColumn, parent, depth, index) {
// Apply the userDefaultColumn
column = { ...defaultColumn, ...userDefaultColumn, ...column }
@@ -182,12 +160,24 @@ export function makeHeaderGroups(flatColumns, defaultColumn) {
return headerGroups.reverse()
}
const pathObjCache = new Map()
export function getBy(obj, path, def) {
if (!path) {
return obj
}
const pathObj = makePathArray(path)
const cacheKey = typeof path === 'function' ? path : JSON.stringify(path)
const pathObj =
pathObjCache.get(cacheKey) ||
(() => {
const pathObj = makePathArray(path)
pathObjCache.set(cacheKey, pathObj)
return pathObj
})()
let val
try {
val = pathObj.reduce((cursor, pathPart) => cursor[pathPart], obj)
} catch (e) {
@@ -196,20 +186,6 @@ export function getBy(obj, path, def) {
return typeof val !== 'undefined' ? val : def
}
export function defaultOrderByFn(arr, funcs, dirs) {
return [...arr].sort((rowA, rowB) => {
for (let i = 0; i < funcs.length; i += 1) {
const sortFn = funcs[i]
const desc = dirs[i] === false || dirs[i] === 'desc'
const sortInt = sortFn(rowA, rowB)
if (sortInt !== 0) {
return desc ? -sortInt : sortInt
}
}
return dirs[0] ? rowA.index - rowB.index : rowB.index - rowA.index
})
}
export function getFirstDefined(...args) {
for (let i = 0; i < args.length; i += 1) {
if (typeof args[i] !== 'undefined') {
@@ -218,17 +194,6 @@ export function getFirstDefined(...args) {
}
}
export function defaultGroupByFn(rows, columnId) {
return rows.reduce((prev, row, i) => {
// TODO: Might want to implement a key serializer here so
// irregular column values can still be grouped if needed?
const resKey = `${row.values[columnId]}`
prev[resKey] = Array.isArray(prev[resKey]) ? prev[resKey] : []
prev[resKey].push(row)
return prev
}, {})
}
export function getElementDimensions(element) {
const rect = element.getBoundingClientRect()
const style = window.getComputedStyle(element)
@@ -276,56 +241,6 @@ function isReactComponent(component) {
return isClassComponent(component) || isFunctionComponent(component)
}
export const mergeProps = (...groups) => {
let props = {}
groups.forEach(({ style = {}, className, ...rest } = {}) => {
props = {
...props,
...rest,
style: {
...(props.style || {}),
...style,
},
className: [props.className, className].filter(Boolean).join(' '),
}
})
if (props.className === '') {
delete props.className
}
return props
}
export const applyHooks = (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.'
)
}
return nextValue
}, initial)
export const applyPropHooks = (hooks, ...args) =>
hooks.reduce((prev, next) => mergeProps(prev, next(...args)), {})
export const warnUnknownProps = props => {
if (Object.keys(props).length) {
throw new Error(
`Unknown options passed to useReactTable:
${JSON.stringify(props, null, 2)}`
)
}
}
export function sum(arr) {
return arr.reduce((prev, curr) => prev + curr, 0)
}
export function isFunction(a) {
if (typeof a === 'function') {
return a
@@ -350,40 +265,6 @@ export function flattenBy(columns, childKey) {
return flatColumns
}
export function ensurePluginOrder(plugins, befores, pluginName, afters) {
const pluginIndex = plugins.findIndex(
plugin => plugin.pluginName === pluginName
)
if (pluginIndex === -1) {
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 => {
const beforeIndex = plugins.findIndex(
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!`
)
}
})
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!`
)
}
})
}
export function expandRows(
rows,
{ manualExpandedKey, expanded, expandSubRows = true }
@@ -411,10 +292,6 @@ export function expandRows(
return expandedRows
}
export function functionalUpdate(updater, old) {
return typeof updater === 'function' ? updater(old) : updater
}
//
const reOpenBracket = /\[/g