Compare commits

...
Author SHA1 Message Date
tannerlinsley 488da2ecc5 v7.0.0-beta.2 2019-09-30 07:32:56 -06:00
tannerlinsley 5f0e7cab8b fix: fix colspan prop to use column visibility
Fixes #1555
2019-09-30 07:31:43 -06:00
Nick OomsandTanner Linsley e2e67ed181 Added "in" to make the sentence more readable (#1554) 2019-09-28 06:44:01 -06:00
goldenLunchboxandTanner Linsley c8857a2871 Update api.md (#1551)
The state variable seemed to be missing in the useTable part (row 481) and I felt the need to comment on an additional import being needed.
2019-09-27 05:43:13 -06:00
Tanner LinsleyandGitHub 98583d35f3 Update README.md 2019-09-26 13:28:31 -06:00
tannerlinsley 0a1bf55a2c Merge branch 'master' of https://github.com/react-tools/react-table 2019-09-26 13:23:03 -06:00
tannerlinsley 54b4f8a5d1 v7.0.0-beta.1 2019-09-26 13:22:14 -06:00
tannerlinsley f552c94972 fix(usepagination): fix unstable callbacks
Closes #1549
2019-09-26 13:21:34 -06:00
ggascoigneandTanner Linsley 7ab6385839 TypeScript updates (#1521)
* TypeScript updates

I've found that trying to get solid TypeScript typings for this library
are a bit of a challenge.  The composable nature of the library means
that the types for the builtin functions are by their nature somewhat
minimal, and that the user needs to be able to extend those interfaces
to reflect the specific plugins that are in use.

With that in mind I propose something like this.

To get the best out of them, you then need to extend those interfaces
using declaration merging, see
https://www.typescriptlang.org/docs/handbook/declaration-merging.html

e.g.

```ts
declare module 'react-table-hooks' {
  export interface TableInstance<D = any>
    extends UseFiltersValues<D>,
      UsePaginationValues<D>,
      UseExpandedValues,
      UseGroupByValues {}

  export interface TableState<D = any>
    extends UsePaginationState,
      UseGroupByState,
      UseSortbyState<D>,
      UseFiltersState<D> {}
}
```

This also puts the ability to extend those types with any user defined
hooks completely in the users hands.

This gives the greatest flexibility, but I'll admit that it isn't
particularly obvious.  Perhaps a typescript readme and example is needed.

* fix useExpanded type

* fix module name

* fix typo

* address review feedback

* add IdType, update Filters definition
2019-09-20 09:37:45 -06:00
Tanner LinsleyandGitHub b8ed02cadc Update README.md 2019-09-17 15:44:02 -06:00
Tanner LinsleyandGitHub c3e917f13b Update README.md 2019-09-17 15:42:36 -06:00
tannerlinsley 7e6d719af4 docs(changelog): update changelog 2019-09-13 09:24:24 -06:00
tannerlinsley da678d0a61 Merge branch 'master' of https://github.com/react-tools/react-table 2019-09-13 09:22:09 -06:00
Tanner LinsleyandGitHub c3fe4c7fd8 Update README.md 2019-09-13 09:22:03 -06:00
tannerlinsley 45036054cb v7.0.0-beta.0 2019-09-13 09:09:44 -06:00
tannerlinsley 8d3a97c9a2 v7.0.0-alpha.36 2019-09-13 07:35:15 -06:00
tannerlinsley fb0eb3646a Merge branch 'master' of https://github.com/react-tools/react-table 2019-09-13 07:34:22 -06:00
tannerlinsley dfad9151c3 fix(expandedrows): fix in-page row expansion for paginateExpandedRows 2019-09-13 07:33:53 -06:00
Michael StramelandTanner Linsley c618542f6e Don't publish types (#1515) 2019-09-12 21:29:15 -06:00
Michael StramelandTanner Linsley 670a92734e Add typings (#1511) 2019-09-12 09:39:53 -06:00
Andrey NikonovandTanner Linsley c91130075b Fix typo (#1513) 2019-09-12 08:56:16 -06:00
Andrey NikonovandTanner Linsley c4a8eb147c Fix typo (#1512) 2019-09-12 08:56:04 -06:00
Tanner LinsleyandGitHub 388cb85f0a Update README.md 2019-09-10 13:17:12 -06:00
CodarandTanner Linsley aea76facf1 isAllRowsSelected can only be true if there are rows. (#1504) 2019-09-09 08:49:40 -06:00
tannerlinsley f829cd0222 v7.0.0-alpha.35 2019-09-09 08:25:09 -06:00
tannerlinsley 0a03ea3a75 fix: better flexRender utility (supports JSX elements now) 2019-09-09 08:24:08 -06:00
tannerlinsley 0aa55dac08 fix: fixed disablePageResetOnDataChangeRef dependencies
disablePageResetOnDataChangeRef will no longer trigger page resets when changed
2019-09-09 08:21:15 -06:00
Eddie HongandTanner Linsley 15778fe467 Fix typo in installation.md (#1498) 2019-09-06 10:59:47 -06:00
tannerlinsley ca23da0342 v7.0.0-alpha.34 2019-09-05 11:08:12 -06:00
tannerlinsley 072967b771 fix: fix defaultColumn.sortType, fix useGroupBy plugin order warning 2019-09-05 11:07:25 -06:00
tannerlinsley da9e94091f chore: removed unused example 2019-09-03 07:15:19 -06:00
Tanner LinsleyandGitHub a98ec48b20 Update README.md 2019-09-03 07:01:58 -06:00
Tanner LinsleyandGitHub 1e2ca74f96 Update README.md 2019-09-03 06:59:15 -06:00
Tanner LinsleyandGitHub aaa9459389 Update api.md 2019-09-03 06:33:07 -06:00
Tanner LinsleyandGitHub 7884f33486 Update README.md 2019-09-02 21:37:31 -06:00
Brian QianandTanner Linsley 6193a33c89 Changed docs to include sortType options for useSortBy (#1489)
* Update api.md

* Update README.md
2019-09-02 19:32:35 -06:00
tannerlinsley 0e54ef0005 v7.0.0-alpha.33 2019-08-29 09:27:31 -06:00
tannerlinsley b10446b8c4 fix: useExpanded uses flat array for state
useExpanded now uses a flat array of row path keys for tracking expanded state instead of nested
objects. This is both easier to use as a developer, but also enables expanding all rows or even
leaving nested rows in an expanded state, despite their parent rows' expanded state.

BREAKING CHANGE: See description
2019-08-29 09:14:11 -06:00
tannerlinsley 51165d92f6 v7.0.0-alpha.32 2019-08-28 10:51:51 -06:00
tannerlinsley bb8b10ca64 Merge branch 'master' of https://github.com/react-tools/react-table 2019-08-28 10:51:10 -06:00
gargrohandTanner Linsley 8742ce39c2 [useSort] Provide API to clear sorting at column level (#1476)
* [useSort] Provide API to clear sorting at column level

* updated docs
2019-08-28 10:51:04 -06:00
tannerlinsley 0486c5c787 fix: fix column-ordering example 2019-08-28 10:50:33 -06:00
dependabot[bot]andTanner Linsley f4b165d378 chore(deps): bump eslint-utils from 1.4.0 to 1.4.2 (#1477)
Bumps [eslint-utils](https://github.com/mysticatea/eslint-utils) from 1.4.0 to 1.4.2.
- [Release notes](https://github.com/mysticatea/eslint-utils/releases)
- [Commits](https://github.com/mysticatea/eslint-utils/compare/v1.4.0...v1.4.2)

Signed-off-by: dependabot[bot] <support@github.com>
2019-08-28 08:51:10 -06:00
tannerlinsley e7722b1d95 Merge branch 'master' of https://github.com/react-tools/react-table 2019-08-27 10:08:53 -06:00
tannerlinsley 25cdefb2a1 fix: clean up examples 2019-08-27 10:08:13 -06:00
Tanner LinsleyandGitHub 4e3d1dd10a Update README.md 2019-08-27 10:04:37 -06:00
Tanner LinsleyandGitHub f6a1203403 Update README.md 2019-08-27 10:04:22 -06:00
Tanner LinsleyandGitHub a810556e57 Update README.md 2019-08-27 10:03:39 -06:00
tannerlinsley 8bb85b99c3 v7.0.0-alpha.31 2019-08-27 10:00:39 -06:00
tannerlinsley b0d6169848 feat: added useColumnOrder + examples 2019-08-27 09:59:52 -06:00
tannerlinsley 9b7264fad4 fix: update package.json 2019-08-27 07:13:11 -06:00
tannerlinsley abe723a87d fix: fix header group and header placeholder IDs 2019-08-27 07:11:01 -06:00
tannerlinsley 8776d78edb v7.0.0-alpha.29 2019-08-26 09:38:53 -06:00
tannerlinsley f0293f5511 fix: getRowID instead of getRowPathID 2019-08-26 09:38:14 -06:00
tannerlinsley 16c5512c4f v7.0.0-alpha.28 2019-08-26 09:27:52 -06:00
tannerlinsley 3b42c72e7c fix: better naming, fix header regen, getSubRows, getRowPathID 2019-08-26 09:27:07 -06:00
tannerlinsley f40b8f5ca2 v7.0.0-alpha.27 2019-08-23 09:25:33 -06:00
tannerlinsley b61a8ed040 Merge branch 'master' of https://github.com/react-tools/react-table 2019-08-23 09:25:00 -06:00
tannerlinsley 4665006109 fix(use-row-select): fix selection issue casued by wrong startsWith key 2019-08-23 09:24:36 -06:00
Ashwin BhatandTanner Linsley c0aa9533e9 fix field names in useSortBy docs (#1475) 2019-08-22 16:08:40 -06:00
64 changed files with 24414 additions and 525 deletions
+11 -9
View File
@@ -1,7 +1,6 @@
---
name: Bug report
about: Create a report to help us improve
---
# Using v6?
@@ -10,13 +9,14 @@ v6 is now considered feature complete to its current abilities and limitations.
# Using v7?
Thanks for using the alpha version of React Table v7! We're very excited about it.
Thanks for using the beta version of React Table v7! We're very excited about it.
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
@@ -32,15 +32,17 @@ Use a new [react-table codesandbox](https://codesandbox.io/s/m5lxzzpz69) to repr
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
**Smartphone (please complete the following information):**
- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
**Additional context**
Add any other context about the problem here.
+4
View File
@@ -1,3 +1,7 @@
## 7.0.0-beta.0
- Massive changes to the entire project and library. Please consult the README and documentation for more information regarding these changes.
## 6.8.6
#### Fixes & Optimizations
+33 -4
View File
@@ -7,6 +7,9 @@ Hooks for building **lightweight, fast and extendable datagrids** for React
<a href="https://travis-ci.org/tannerlinsley/react-table" target="\_parent">
<img alt="" src="https://travis-ci.org/tannerlinsley/react-table.svg?branch=master" />
</a>
<a href="https://bundlephobia.com/result?p=react-table@next" target="\_parent">
<img alt="" src="https://badgen.net/bundlephobia/minzip/react-table@next" />
</a>
<a href="https://npmjs.com/package/react-table" target="\_parent">
<img alt="" src="https://img.shields.io/npm/dm/react-table.svg" />
</a>
@@ -30,18 +33,42 @@ Hooks for building **lightweight, fast and extendable datagrids** for React
## Features
- Lightweight (4kb - 10kb depending on features and tree-shaking)
- Lightweight (4kb - 9kb depending on features and tree-shaking)
- Headless (100% customizable, Bring-your-own-UI)
- Client-side & Server-side pagination support
- Auto out of the box, fully controllable API
- Sorting (Multi and Stable)
- Filters
- Pivoting & Aggregation
- Row Selection
- Row Expansion
- Fully controllable
- Column Ordering
- Animatable
- 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
## News / Q&A
#### What is the current state of React Table?
React Table v7 is still under active development, and its API is still changing, albeit only slightly. For this reason, it is currently in an **beta** release state. It's estimated that it will be fully released as a stable version sometime during October 2019.
#### Should I use v7@beta in production?
You can use it in production as long as you lock in the beta version in your package.json and also accept that there may be unlikely, but possible bug fixes and/or API changes before it's official release.
#### I'm still using v6, what should I do?
v6 is a great library and is still the default install for `react-table`, however, I do not intend on offering any long-term support for it. If you intend to keep using v6, I recommend maintaining your own fork of the library and keeping it up to date for your version of React.
#### Where are the docs for the older v6 version?
Please [visit the v6 branch](https://github.com/tannerlinsley/react-table/tree/v6)
#### I want to migrate from v6 to v7. How do I do that?
The differences between the 2 versions are incredibly massive. Unfortunately, I cannot write a one-to-one upgrade guide for any of v6's API, simply because much of it is irrelevant with v7's headless approach. The best approach for migrating to v7 is to learn its API by reading the documentation and then following some of the examples to begin building your own table component.
## Documentation
- [Installation](./docs/installation.md) - Walk through how to install React Table
@@ -69,7 +96,7 @@ Hooks for building **lightweight, fast and extendable datagrids** for React
</a>
</td>
<td align="center" valign="middle">
<a href="http://bjntech.com/index.html&utm_campaign=react_table" target="_blank">
<a href="http://bjntech.com/index.html?utm_campaign=react_table" target="_blank">
<img width='250' src="https://raw.githubusercontent.com/tannerlinsley/files/master/images/patreon/sponsor-bjn.png">
</a>
</td>
@@ -147,6 +174,8 @@ Hooks for building **lightweight, fast and extendable datagrids** for React
<div>Thomas Funk</div>
<div>Dan Houle</div>
<div>David Pickut</div>
<div>Jordan Soltman</div>
<div>Robert Tajnšek</div>
</td>
</tr>
</tbody>
+72 -25
View File
@@ -97,6 +97,19 @@ The following options are supported via the main options object passed to `useTa
- Defaults to `initialState`
- This key is used to look for the initial state of a row when initializing the `rowState` for a`data` array.
- If the value located at `row[initialRowStateKey]` is falsey, `{}` will be used instead.
- `getSubRows: Function(row, relativeIndex) => Rows[]`
- Optional
- Must be **memoized**
- Defaults to `(row) => row.subRows || []`
- Use this function to change how React Table detects subrows. You could even use this function to generate sub rows if you want.
- By default, it will attempt to return the `subRows` property on the row, or an empty array if that is not found.
- `getRowID: Function(row, relativeIndex) => string`
- Use this function to change how React Table detects unique rows and also how it constructs each row's underlying `path` property.
- Optional
- Must be **memoized**
- Defaults to `(row, relativeIndex) => relativeIndex`
- You may want to change this function if
- By default, it will use the `index` of the row within it's original array.
- `debug: Bool`
- Optional
- A flag to turn on debug mode.
@@ -134,7 +147,7 @@ The following options are supported on any column object you can pass to `column
- If a function/component is passed, it will be used for formatting the header value, eg. You can use a `Header` function to dynamically format the header using any table or column state.
- `Cell: Function | React.Component => JSX`
- Optional
- Defaults to `({ cell: { value } }) => value`
- Defaults to `({ cell: { value } }) => String(value)`
- Receives the table instance and cell model as props
- Must return valid JSX
- This function (or component) is primarily used for formatting the column value, eg. If your column accessor returns a date object, you can use a `Cell` function to format that date to a readable format.
@@ -143,17 +156,24 @@ The following options are supported on any column object you can pass to `column
The following properties are available on the table instance returned from `useTable`
- `headers[] Array<Column>`
- A **nested** array of final column objects, similar in structure to the original columns configuration option.
- See [Column Properties](#column-properties) for more information
- `columns: Array<Column>`
- A **flat** array of all final column objects computed from the original columns configuration option.
- A **nested** array of final column objects, **similar in structure to the original columns configuration option**.
- See [Column Properties](#column-properties) for more information
- `flatColumns: Array<Column>`
- A **flat** array of all final column objects.
- See [Column Properties](#column-properties) for more information
- `headerGroups: Array<HeaderGroup>`
- An array of normalized header groups, each containing a flattened array of final column objects for that row.
- **Some of these headers may be materialized as placeholders**
- See [Header Group Properties](#headergroup-properties) for more information
- `headers: Array<Column>`
- An **nested** array of final header objects, **similar in structure to the original columns configuration option, but rebuilt for ordering**
- Each contains the headers that are displayed underneath it.
- **Some of these headers may be materialized as placeholders**
- See [Column Properties](#column-properties) for more information
- `flatHeaders[] Array<Column>`
- A **flat** array of final header objects found in each header group. Columns may be duplicated (if columns are not adjacent)
- A **flat** array of final header objects found in each header group.
- **Some of these headers may be materialized as placeholders**
- See [Column Properties](#column-properties) for more information
- `rows: Array<Row>`
- An array of **materialized row objects** from the original `data` array and `columns` passed into the table options
@@ -182,7 +202,7 @@ The following properties are available on the table instance returned from `useT
- Pass it a valid `rowPath` array, `columnID` and `updater`. The `updater` may be a value or function, similar to `React.useState`'s usage.
- If `updater` is a function, it will be passed the previous value
### `HeaderGroup` Properties
### HeaderGroup Properties
The following additional properties are available on every `headerGroup` object returned by the table instance.
@@ -370,7 +390,7 @@ The following options are supported via the main options object passed to `useTa
- `disableMultiSort: Bool`
- Disables multi-sorting for the entire table.
- `isMultiSortEvent: Function`
- Allows to override default multisort behaviour(i.e. multisort applies when shift key is presssed), if this function is provided then returned boolean value from this function will make decision whether newly applied sort action will be considered as multisort or not.
- Allows to override default multisort behaviour(i.e. multisort applies when shift key is pressed), if this function is provided then returned boolean value from this function will make decision whether newly applied sort action will be considered as multisort or not.
- Receives `event` as argument.
- `maxMultiSortColCount: Number`
- Limit on max number of columns for multisort, e.g. if set to 3, and suppose table is sorted by `[A, B, C]` and then clicking `D` for sorting should result in table sorted by `[B, C , D]`
@@ -379,7 +399,7 @@ The following options are supported via the main options object passed to `useTa
- `disableMultiRemove: Bool`
- If true, the un-sorted state will not be available to multi-sorted columns.
- `orderByFn: Function`
- Must be **memoizd**
- Must be **memoized**
- Defaults to the built-in [default orderBy function](TODO)
- This function is responsible for composing multiple sorting functions together for multi-sorting, and also handles both the directional sorting and stable-sorting tie breaking. Rarely would you want to override this function unless you have a very advanced use-case that requires it.
- `sortTypes: Object<sortKey: sortType>`
@@ -393,7 +413,7 @@ The following options are supported on any `Column` object passed to the `column
- `disableSorting: Bool`
- Optional
- Defualts to `false`
- Defaults to `false`
- If set to `true`, the sorting for this column will be disabled
- `sortDescFirst: Bool`
- Optional
@@ -407,9 +427,9 @@ The following options are supported on any `Column` object passed to the `column
- `sortType: String | Function`
- Used to compare 2 rows of data and order them correctly.
- If a **function** is passed, it must be **memoized**
- Defaults to [`alphanumeric`](TODO)
- String options: `basic`, `datetime`, `alphanumeric`. Defaults to [`alphanumeric`](TODO).
- The resolved function from the this string/function will be used to sort the this column's data.
- If a `string` is passed, the function with that name located on either the custom `sortTypes` option or the built-in sorting types object will be used. If
- If a `string` is passed, the function with that name located on either the custom `sortTypes` option or the built-in sorting types object will be used.
- If a `function` is passed, it will be used.
- For more information on sort types, see [Sorting](TODO)
@@ -438,12 +458,14 @@ The following properties are available on every `Column` object returned by the
- This function is used to resolve any props needed for this column's UI that is responsible for toggling the sort direction when the user clicks it.
- You can use the `getSortByToggleProps` hook to extend its functionality.
- Custom props may be passed. **NOTE: Custom props may override built-in sortBy props, so be careful!**
- `sorted: Boolean`
- `clearSorting: Function() => void`
- This function can be used to programmatically clear the sorting for this column.
- `isSorted: Boolean`
- Denotes whether this column is currently being sorted
- `sortedIndex: Int`
- If the column is currently sorted, this integer will be the index in the `sortBy` array from state that corresponds to this column.
- If this column is not sorted, the index will always be `-1`
- `sortedDesc: Bool`
- `isSortedDesc: Bool`
- If the column is currently sorted, this denotes whether the column's sort direction is descending or not.
- If `true`, the column is sorted `descending`
- If `false`, the column is sorted `ascending`
@@ -453,13 +475,14 @@ The following properties are available on every `Column` object returned by the
```js
function Table({ columns, data }) {
// Set some default sorting state
// Set some default sorting state. For this an additional import of useTableState is needed
const state = useTableState({ sortBy: [{ id: 'firstName', desc: true }] })
const { getTableProps, headerGroups, rows, prepareRow } = useTable(
{
columns,
data,
state,
},
useSortBy // Use the sortBy hook
)
@@ -477,10 +500,14 @@ function Table({ columns, data }) {
<span>
{/* Add a sort direction indicator */}
<span>
{column.sorted ? (column.sortedDesc ? ' 🔽' : ' 🔼') : ''}
{column.isSorted
? column.isSortedDesc
? ' 🔽'
: ' 🔼'
: ''}
</span>
{/* Add a sort index indicator */}
<span>({column.sorted ? column.sortedIndex + 1 : ''})</span>
<span>({column.isSorted ? column.sortedIndex + 1 : ''})</span>
</span>
</th>
))}
@@ -908,20 +935,20 @@ function App() {
- Plugin Hook
- Optional
`useExpanded` is the hook that implements **row expanding**. It is most often used with `useGroupBy` to expand grouped rows or on its own with nested `subRows` in tree-li,ke `data` sets, but is not limited to these use-cases. It supports expanding rows both via internal table state and also via a hard-coded key on the raw row model.
`useExpanded` is the hook that implements **row expanding**. It is most often used with `useGroupBy` to expand grouped rows or on its own with nested `subRows` in tree-like `data` sets, but is not limited to these use-cases. It supports expanding rows both via internal table state and also via a hard-coded key on the raw row model.
### Table Options
The following options are supported via the main options object passed to `useTable(options)`
- `state[0].expanded: Object<[pathIndex]: Boolean | ExpandedStateObject>`
- `state[0].expanded: Array<pathKey: String>`
- Optional
- Must be **memoized**
- An nested object of expanded paths.
- A `pathIndex` can be set as the key and its value set to `true` to expand that row's subRows into view. For example, if `{ '3': true }` was passed as the `expanded` state, the **4th row in the original data array** would be expanded.
- For nested expansion, you may **use another object** instead of a Boolean to expand sub rows. For example, if `{ '3': { '5' : true }}` was passed as the `expanded` state, then the **6th subRow of the 4th row and the 4th row of the original data array** would be expanded.
- An array of expanded path keys.
- If a row's path key (`row.path.join('.')`) is present in this array, that row will have an expanded state. For example, if `['3']` was passed as the `expanded` state, the **4th row in the original data array** would be expanded.
- For nested expansion, you may **join the row path with a `.`** to expand sub rows. For example, if `['3', '3.5']` was passed as the `expanded` state, then the **6th subRow of the 4th row and also the 4th row of the original data array** would be expanded.
- This information is stored in state since the table is allowed to manipulate the filter through user interaction.
- `subRowsKey: String`
- `getSubRows: Function(row, relativeIndex) => Rows[]`
- Optional
- See the [useTable hook](#table-options) for more details
- `manualExpandedKey: String`
@@ -1549,9 +1576,29 @@ The following additional properties are available on every `Cell` object returne
- Use this function to programmatically update the state of a cell.
- `updater` can be a function or value. If a `function` is passed, it will receive the current value and expect a new one to be returned.
### Example
# `useColumnOrder`
> Have an example of using useRowState? Submit a PR to add it here!
- Plugin Hook
- Optional
`useColumnOrder` is a plugin hook that implements **basic column reordering**. As columns are reordered, their header groups are reverse-engineered so as to never have orphaned header groups.
### Table Options
The following options are supported via the main options object passed to `useTable(options)`
- `state[0].columnOrder: Array<ColumnID>`
- Optional
- Defaults to `[]`
- Any column ID's not represented in this array will be naturally ordered based on their position in the original table's `column` structure
### Instance Properties
The following values are provided to the table `instance`:
- `setColumnOrder: Function(updater: Function | Array<ColumnID>) => void`
- Use this function to programmatically update the columnOrder.
- `updater` can be a function or value. If a `function` is passed, it will receive the current value and expect a new one to be returned.
# `useTableState`
+6
View File
@@ -28,6 +28,9 @@
- Editable Data
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/editable-data)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/editable-data)
- Column Ordering
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/column-ordering)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/column-ordering)
- **Complex**
- The "Kitchen Sink"
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/kitchen-sink)
@@ -37,6 +40,9 @@
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/pagination-controlled)
- [Open in CodeSandobx](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/pagination-controlled)
- **UI** - These examples demonstrate how to use React Table with your favorite UI libraries or tools!
- Animated (Framer-Motion)
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/animated-framer-motion)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/animated-framer-motion)
- [ ] Styled-Components
- [ ] CSS
- [ ] Material-UI
+1 -1
View File
@@ -10,7 +10,7 @@ $ npm install react-table@next
$ yarn add react-table@next
```
> NOTE: `@next` is only required tempororarily while work on the alpha and beta versions are still shifting.
> NOTE: `@next` is only required temporarily while work on the alpha and beta versions are still shifting.
To import React Table:
+4
View File
@@ -0,0 +1,4 @@
{
"presets": ["react-app"],
"plugins": ["styled-components"]
}
+1
View File
@@ -0,0 +1 @@
SKIP_PREFLIGHT_CHECK=true
@@ -0,0 +1,7 @@
{
"extends": ["react-app", "prettier"],
"rules": {
// "eqeqeq": 0,
// "jsx-a11y/anchor-is-valid": 0
}
}
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
@@ -0,0 +1,29 @@
const path = require('path')
const resolveFrom = require('resolve-from')
const fixLinkedDependencies = config => {
config.resolve = {
...config.resolve,
alias: {
...config.resolve.alias,
react$: resolveFrom(path.resolve('node_modules'), 'react'),
'react-dom$': resolveFrom(path.resolve('node_modules'), 'react-dom'),
},
}
return config
}
const includeSrcDirectory = config => {
config.resolve = {
...config.resolve,
modules: [path.resolve('src'), ...config.resolve.modules],
}
return config
}
module.exports = [
['use-babel-config', '.babelrc'],
['use-eslint-config', '.eslintrc'],
fixLinkedDependencies,
// includeSrcDirectory,
]
@@ -0,0 +1,6 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app) and Rescripts.
You can:
- [Open this example in a new CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/animated-framer-motion)
- `yarn` and `yarn start` to run and edit the example
@@ -0,0 +1,37 @@
{
"private": true,
"scripts": {
"start": "rescripts start",
"build": "rescripts build",
"test": "rescripts test",
"eject": "rescripts eject"
},
"dependencies": {
"framer-motion": "^1.6.3",
"match-sorter": "^4.0.1",
"namor": "^1.1.2",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "3.0.1",
"react-table": "next",
"styled-components": "^4.3.2"
},
"devDependencies": {
"@rescripts/cli": "^0.0.11",
"@rescripts/rescript-use-babel-config": "^0.0.8",
"@rescripts/rescript-use-eslint-config": "^0.0.9",
"babel-eslint": "10.0.1"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

@@ -0,0 +1,38 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
@@ -0,0 +1,15 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
+382
View File
@@ -0,0 +1,382 @@
import React from 'react'
import styled from 'styled-components'
import { useTable, useSortBy, useFilters, useColumnOrder } from 'react-table'
import { motion, AnimatePresence } from 'framer-motion'
import matchSorter from 'match-sorter'
import makeData from './makeData'
const Styles = styled.div`
padding: 1rem;
table {
border-spacing: 0;
border: 1px solid black;
tr {
:last-child {
td {
border-bottom: 0;
}
}
}
th,
td {
margin: 0;
padding: 0.5rem;
border-bottom: 1px solid black;
border-right: 1px solid black;
background: white;
:last-child {
border-right: 0;
}
}
}
`
// Define a default UI for filtering
function DefaultColumnFilter({
column: { filterValue, preFilteredRows, setFilter },
}) {
const count = preFilteredRows.length
return (
<input
value={filterValue || ''}
onChange={e => {
setFilter(e.target.value || undefined) // Set undefined to remove the filter entirely
}}
placeholder={`Search ${count} records...`}
/>
)
}
// This is a custom filter UI for selecting
// a unique option from a list
function SelectColumnFilter({
column: { filterValue, setFilter, preFilteredRows, id },
}) {
// Calculate the options for filtering
// using the preFilteredRows
const options = React.useMemo(() => {
const options = new Set()
preFilteredRows.forEach(row => {
options.add(row.values[id])
})
return [...options.values()]
}, [id, preFilteredRows])
// Render a multi-select box
return (
<select
value={filterValue}
onChange={e => {
setFilter(e.target.value || undefined)
}}
>
<option value="">All</option>
{options.map((option, i) => (
<option key={i} value={option}>
{option}
</option>
))}
</select>
)
}
// This is a custom filter UI that uses a
// slider to set the filter value between a column's
// min and max values
function SliderColumnFilter({
column: { filterValue, setFilter, preFilteredRows, id },
}) {
// Calculate the min and max
// using the preFilteredRows
const [min, max] = React.useMemo(() => {
let min = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
let max = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
preFilteredRows.forEach(row => {
min = Math.min(row.values[id], min)
max = Math.max(row.values[id], max)
})
return [min, max]
}, [id, preFilteredRows])
return (
<>
<input
type="range"
min={min}
max={max}
value={filterValue || min}
onChange={e => {
setFilter(parseInt(e.target.value, 10))
}}
/>
<button onClick={() => setFilter(undefined)}>Off</button>
</>
)
}
// This is a custom UI for our 'between' or number range
// filter. It uses two number boxes and filters rows to
// ones that have values between the two
function NumberRangeColumnFilter({
column: { filterValue = [], preFilteredRows, setFilter, id },
}) {
const [min, max] = React.useMemo(() => {
let min = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
let max = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
preFilteredRows.forEach(row => {
min = Math.min(row.values[id], min)
max = Math.max(row.values[id], max)
})
return [min, max]
}, [id, preFilteredRows])
return (
<div
style={{
display: 'flex',
}}
>
<input
value={filterValue[0] || ''}
type="number"
onChange={e => {
const val = e.target.value
setFilter((old = []) => [val ? parseInt(val, 10) : undefined, old[1]])
}}
placeholder={`Min (${min})`}
style={{
width: '70px',
marginRight: '0.5rem',
}}
/>
to
<input
value={filterValue[1] || ''}
type="number"
onChange={e => {
const val = e.target.value
setFilter((old = []) => [old[0], val ? parseInt(val, 10) : undefined])
}}
placeholder={`Max (${max})`}
style={{
width: '70px',
marginLeft: '0.5rem',
}}
/>
</div>
)
}
function fuzzyTextFilterFn(rows, id, filterValue) {
return matchSorter(rows, filterValue, { keys: [row => row.values[id]] })
}
// Let the table remove the filter if the string is empty
fuzzyTextFilterFn.autoRemove = val => !val
function shuffle(arr) {
arr = [...arr]
const shuffled = []
while (arr.length) {
const rand = Math.floor(Math.random() * arr.length)
shuffled.push(arr.splice(rand, 1)[0])
}
return shuffled
}
function Table({ columns, data }) {
const defaultColumn = React.useMemo(
() => ({
// Let's set up our default Filter UI
Filter: DefaultColumnFilter,
}),
[]
)
const {
getTableProps,
headerGroups,
rows,
flatColumns,
prepareRow,
setColumnOrder,
state,
} = useTable(
{
columns,
data,
defaultColumn,
},
useColumnOrder,
useFilters,
useSortBy
)
const spring = React.useMemo(
() => ({
type: 'spring',
damping: 50,
stiffness: 100,
}),
[]
)
const randomizeColumns = () => {
setColumnOrder(shuffle(flatColumns.map(d => d.id)))
}
return (
<>
<button onClick={() => randomizeColumns({})}>Randomize Columns</button>
<table {...getTableProps()}>
<thead>
{headerGroups.map((headerGroup, i) => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<motion.th
{...column.getHeaderProps({
layoutTransition: spring,
style: {
minWidth: column.minWidth,
},
})}
>
<div {...column.getSortByToggleProps()}>
{column.render('Header')}
<span>
{column.isSorted
? column.isSortedDesc
? ' 🔽'
: ' 🔼'
: ''}
</span>
</div>
<div>{column.canFilter ? column.render('Filter') : null}</div>
</motion.th>
))}
</tr>
))}
</thead>
<tbody>
<AnimatePresence>
{rows.slice(0, 10).map(
(row, i) =>
prepareRow(row) || (
<motion.tr
{...row.getRowProps({
layoutTransition: spring,
exit: { opacity: 0, maxHeight: 0 },
})}
>
{row.cells.map((cell, i) => {
return (
<motion.td
{...cell.getCellProps({
layoutTransition: spring,
})}
>
{cell.render('Cell')}
</motion.td>
)
})}
</motion.tr>
)
)}
</AnimatePresence>
</tbody>
</table>
<pre>
<code>{JSON.stringify(state[0], null, 2)}</code>
</pre>
</>
)
}
// Define a custom filter filter function!
function filterGreaterThan(rows, id, filterValue) {
return rows.filter(row => {
const rowValue = row.values[id]
return rowValue >= filterValue
})
}
// This is an autoRemove method on the filter function that
// when given the new filter value and returns true, the filter
// will be automatically removed. Normally this is just an undefined
// check, but here, we want to remove the filter if it's not a number
filterGreaterThan.autoRemove = val => typeof val !== 'number'
function App() {
const columns = React.useMemo(
() => [
{
Header: 'Name',
columns: [
{
Header: 'First Name',
accessor: 'firstName',
minWidth: 150,
},
{
Header: 'Last Name',
accessor: 'lastName',
minWidth: 150,
// Use our custom `fuzzyText` filter on this column
filter: 'fuzzyText',
},
],
},
{
Header: 'Info',
columns: [
{
Header: 'Age',
accessor: 'age',
minWidth: 150,
Filter: SliderColumnFilter,
filter: 'equals',
},
{
Header: 'Visits',
accessor: 'visits',
minWidth: 150,
Filter: NumberRangeColumnFilter,
filter: 'between',
},
{
Header: 'Status',
accessor: 'status',
minWidth: 150,
Filter: SelectColumnFilter,
filter: 'includes',
},
{
Header: 'Profile Progress',
accessor: 'progress',
minWidth: 150,
Filter: SliderColumnFilter,
filter: filterGreaterThan,
},
],
},
],
[]
)
const data = React.useMemo(() => makeData(100), [])
return (
<Styles>
<Table columns={columns} data={data} />
</Styles>
)
}
export default App
@@ -0,0 +1,9 @@
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
it('renders without crashing', () => {
const div = document.createElement('div')
ReactDOM.render(<App />, div)
ReactDOM.unmountComponentAtNode(div)
})
@@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
@@ -0,0 +1,12 @@
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import * as serviceWorker from './serviceWorker'
ReactDOM.render(<App />, document.getElementById('root'))
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister()
@@ -0,0 +1,40 @@
import namor from 'namor'
const range = len => {
const arr = []
for (let i = 0; i < len; i++) {
arr.push(i)
}
return arr
}
const newPerson = () => {
const statusChance = Math.random()
return {
firstName: namor.generate({ words: 1, numbers: 0 }),
lastName: namor.generate({ words: 1, numbers: 0 }),
age: Math.floor(Math.random() * 30),
visits: Math.floor(Math.random() * 100),
progress: Math.floor(Math.random() * 100),
status:
statusChance > 0.66
? 'relationship'
: statusChance > 0.33
? 'complicated'
: 'single',
}
}
export default function makeData(...lens) {
const makeDataLevel = (depth = 0) => {
const len = lens[depth]
return range(len).map(d => {
return {
...newPerson(),
subRows: lens[depth + 1] ? makeDataLevel(depth + 1) : undefined,
}
})
}
return makeDataLevel()
}
@@ -0,0 +1,135 @@
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
)
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href)
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config)
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://bit.ly/CRA-PWA'
)
})
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config)
}
})
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing
if (installingWorker == null) {
return
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
)
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration)
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.')
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration)
}
}
}
}
}
})
.catch(error => {
console.error('Error during service worker registration:', error)
})
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type')
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload()
})
})
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config)
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
)
})
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister()
})
}
}
File diff suppressed because it is too large Load Diff
+4
View File
@@ -0,0 +1,4 @@
{
"presets": ["react-app"],
"plugins": ["styled-components"]
}
+1
View File
@@ -0,0 +1 @@
SKIP_PREFLIGHT_CHECK=true
+7
View File
@@ -0,0 +1,7 @@
{
"extends": ["react-app", "prettier"],
"rules": {
// "eqeqeq": 0,
// "jsx-a11y/anchor-is-valid": 0
}
}
+23
View File
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
+29
View File
@@ -0,0 +1,29 @@
const path = require('path')
const resolveFrom = require('resolve-from')
const fixLinkedDependencies = config => {
config.resolve = {
...config.resolve,
alias: {
...config.resolve.alias,
react$: resolveFrom(path.resolve('node_modules'), 'react'),
'react-dom$': resolveFrom(path.resolve('node_modules'), 'react-dom'),
},
}
return config
}
const includeSrcDirectory = config => {
config.resolve = {
...config.resolve,
modules: [path.resolve('src'), ...config.resolve.modules],
}
return config
}
module.exports = [
['use-babel-config', '.babelrc'],
['use-eslint-config', '.eslintrc'],
fixLinkedDependencies,
// includeSrcDirectory,
]
+6
View File
@@ -0,0 +1,6 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app) and Rescripts.
You can:
- [Open this example in a new CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/column-ordering)
- `yarn` and `yarn start` to run and edit the example
+35
View File
@@ -0,0 +1,35 @@
{
"private": true,
"scripts": {
"start": "rescripts start",
"build": "rescripts build",
"test": "rescripts test",
"eject": "rescripts eject"
},
"dependencies": {
"namor": "^1.1.2",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "3.0.1",
"react-table": "next",
"styled-components": "^4.3.2"
},
"devDependencies": {
"@rescripts/cli": "^0.0.11",
"@rescripts/rescript-use-babel-config": "^0.0.8",
"@rescripts/rescript-use-eslint-config": "^0.0.9",
"babel-eslint": "10.0.1"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

@@ -0,0 +1,38 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
@@ -0,0 +1,15 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
+153
View File
@@ -0,0 +1,153 @@
import React from 'react'
import styled from 'styled-components'
import { useTable, useColumnOrder } from 'react-table'
import makeData from './makeData'
const Styles = styled.div`
padding: 1rem;
table {
border-spacing: 0;
border: 1px solid black;
tr {
:last-child {
td {
border-bottom: 0;
}
}
}
th,
td {
margin: 0;
padding: 0.5rem;
border-bottom: 1px solid black;
border-right: 1px solid black;
background: white;
:last-child {
border-right: 0;
}
}
}
`
function shuffle(arr) {
arr = [...arr]
const shuffled = []
while (arr.length) {
const rand = Math.floor(Math.random() * arr.length)
shuffled.push(arr.splice(rand, 1)[0])
}
return shuffled
}
function Table({ columns, data }) {
const {
getTableProps,
headerGroups,
rows,
flatColumns,
prepareRow,
setColumnOrder,
state,
} = useTable(
{
columns,
data,
},
useColumnOrder
)
const randomizeColumns = () => {
setColumnOrder(shuffle(flatColumns.map(d => d.id)))
}
return (
<>
<button onClick={() => randomizeColumns({})}>Randomize Columns</button>
<table {...getTableProps()}>
<thead>
{headerGroups.map((headerGroup, i) => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>{column.render('Header')}</th>
))}
</tr>
))}
</thead>
<tbody>
{rows.slice(0, 10).map(
(row, i) =>
prepareRow(row) || (
<tr {...row.getRowProps()}>
{row.cells.map((cell, i) => {
return (
<td {...cell.getCellProps()}>{cell.render('Cell')}</td>
)
})}
</tr>
)
)}
</tbody>
</table>
<pre>
<code>{JSON.stringify(state[0], null, 2)}</code>
</pre>
</>
)
}
function App() {
const columns = React.useMemo(
() => [
{
Header: 'Name',
columns: [
{
Header: 'First Name',
accessor: 'firstName',
},
{
Header: 'Last Name',
accessor: 'lastName',
},
],
},
{
Header: 'Info',
columns: [
{
Header: 'Age',
accessor: 'age',
},
{
Header: 'Visits',
accessor: 'visits',
},
{
Header: 'Status',
accessor: 'status',
},
{
Header: 'Profile Progress',
accessor: 'progress',
},
],
},
],
[]
)
const data = React.useMemo(() => makeData(10), [])
return (
<Styles>
<Table columns={columns} data={data} />
</Styles>
)
}
export default App
+9
View File
@@ -0,0 +1,9 @@
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
it('renders without crashing', () => {
const div = document.createElement('div')
ReactDOM.render(<App />, div)
ReactDOM.unmountComponentAtNode(div)
})
+13
View File
@@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
+12
View File
@@ -0,0 +1,12 @@
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import * as serviceWorker from './serviceWorker'
ReactDOM.render(<App />, document.getElementById('root'))
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister()
+40
View File
@@ -0,0 +1,40 @@
import namor from 'namor'
const range = len => {
const arr = []
for (let i = 0; i < len; i++) {
arr.push(i)
}
return arr
}
const newPerson = () => {
const statusChance = Math.random()
return {
firstName: namor.generate({ words: 1, numbers: 0 }),
lastName: namor.generate({ words: 1, numbers: 0 }),
age: Math.floor(Math.random() * 30),
visits: Math.floor(Math.random() * 100),
progress: Math.floor(Math.random() * 100),
status:
statusChance > 0.66
? 'relationship'
: statusChance > 0.33
? 'complicated'
: 'single',
}
}
export default function makeData(...lens) {
const makeDataLevel = (depth = 0) => {
const len = lens[depth]
return range(len).map(d => {
return {
...newPerson(),
subRows: lens[depth + 1] ? makeDataLevel(depth + 1) : undefined,
}
})
}
return makeDataLevel()
}
@@ -0,0 +1,135 @@
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
)
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href)
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config)
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://bit.ly/CRA-PWA'
)
})
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config)
}
})
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing
if (installingWorker == null) {
return
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
)
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration)
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.')
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration)
}
}
}
}
}
})
.catch(error => {
console.error('Error during service worker registration:', error)
})
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type')
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload()
})
})
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config)
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
)
})
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister()
})
}
}
File diff suppressed because it is too large Load Diff
+4 -4
View File
@@ -230,17 +230,17 @@ function App() {
const [data, setData] = React.useState(() => makeData(20))
const [originalData] = React.useState(data)
const [skipPageReset, setSkipPageReset] = React.useState(false)
// We need to keep the table from resetting the pageIndex when we
// Update data. So we can keep track of that flag with a ref.
const skipPageResetRef = React.useRef(false)
// When our cell renderer calls updateMyData, we'll use
// the rowIndex, columnID and new value to update the
// original data
const updateMyData = (rowIndex, columnID, value) => {
// We also turn on the flag to not reset the page
skipPageResetRef.current = true
setSkipPageReset(true)
setData(old =>
old.map((row, index) => {
if (index === rowIndex) {
@@ -258,7 +258,7 @@ function App() {
// so that if data actually changes when we're not
// editing it, the page is reset
React.useEffect(() => {
skipPageResetRef.current = false
setSkipPageReset(false)
}, [data])
// Let's add a data resetter/randomizer to help
@@ -272,7 +272,7 @@ function App() {
columns={columns}
data={data}
updateMyData={updateMyData}
disablePageResetOnDataChange={skipPageResetRef.current}
disablePageResetOnDataChange={skipPageReset}
/>
</Styles>
)
+3 -3
View File
@@ -50,9 +50,6 @@ function Table({ columns: userColumns, data }) {
return (
<>
<pre>
<code>{JSON.stringify({ expanded }, null, 2)}</code>
</pre>
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
@@ -80,6 +77,9 @@ function Table({ columns: userColumns, data }) {
</table>
<br />
<div>Showing the first 20 results of {rows.length} rows</div>
<pre>
<code>{JSON.stringify({ expanded }, null, 2)}</code>
</pre>
</>
)
}
+1 -1
View File
@@ -304,8 +304,8 @@ function Table({ columns, data, updateMyData, disablePageResetOnDataChange }) {
disablePageResetOnDataChange,
},
useFilters,
useSortBy,
useGroupBy,
useSortBy,
useExpanded,
usePagination,
useRowSelect
+51 -1
View File
@@ -23,7 +23,6 @@ function MyTable() {
data,
columns,
},
- useSortBy
+ useSortBy
)
@@ -60,3 +59,54 @@ function MyTable() {
)
}
```
By default, the sorting will be `alphanumeric`. This can be changed in your `column` object.
Other options include `basic` and `datetime`.
Note that if you're planning on sorting numbers between 0 and 1, `basic` sorting will be more accurate.
More information can be found in the [API Docs](/docs/api.md#useSortBy)
````diff
const columns = React.useMemo(
() => [
{
Header: 'Name',
columns: [
{
Header: 'First Name',
accessor: 'firstName',
},
{
Header: 'Last Name',
accessor: 'lastName',
},
],
},
{
Header: 'Info',
columns: [
{
Header: 'Age',
accessor: 'age',
+ sortType: 'basic'
},
{
Header: 'Visits',
accessor: 'visits',
+ sortType: 'basic'
},
{
Header: 'Status',
accessor: 'status',
},
{
Header: 'Profile Progress',
accessor: 'progress',
+ sortType: 'basic'
},
],
},
],
[]
)```
````
+2 -2
View File
@@ -42,7 +42,7 @@ function Table({ columns: userColumns, data, renderRowSubComponent }) {
headerGroups,
rows,
prepareRow,
columns,
flatColumns,
state: [{ expanded }],
} = useTable(
{
@@ -87,7 +87,7 @@ function Table({ columns: userColumns, data, renderRowSubComponent }) {
*/}
{row.isExpanded ? (
<tr>
<td colSpan={columns.length}>
<td colSpan={flatColumns.length}>
{/*
Inside it, call our renderRowSubComponent function. In reality,
you coul pass whatever you want as props to
Vendored
+288
View File
@@ -0,0 +1,288 @@
declare module 'react-table' {
import { ReactNode, useState } from 'react'
type StringKey<D> = Extract<keyof D, string>
type IdType<D> = StringKey<D> | string
type SortingRule<D> = {
id: IdType<D>
desc: boolean
}
export type SortingRules<D> = SortingRule<D>[]
export type SortByFn = (a: any, b: any, desc: boolean) => 0 | 1 | -1
export type Filters<D> = Record<IdType<D>, string>
export interface Cell<D = {}> extends TableInstance<D> {
cell: { value: any }
column: Column<D>
row: Row<D>
render: (type: 'Cell' | 'Aggregated', userProps?: any) => any
isGrouped?: boolean
isAggregated?: boolean
isRepeatedValue?: boolean
getCellProps: () => any
}
export interface Row<D = {}> {
index: number
cells: Cell<D>[]
getRowProps: (userProps?: any) => any
original: D
path: any[]
values: any[]
depth: number
}
export interface UseExpandedRow<D = {}> {
subRows?: D[]
groupByID?: string | number
toggleExpanded?: () => any
isExpanded?: boolean
isAggregated?: boolean
}
export type AccessorFn<D> = (
originalRow: D,
index: number,
sub: {
subRows: [D]
depth: number
data: [D]
}
) => unknown
export interface HeaderColumn<D> {
/**
* This string/function is used to build the data model for your column.
*/
accessor: IdType<D> | AccessorFn<D>
Header?: ReactNode | ((props: TableInstance<D>) => ReactNode)
Filter?: ReactNode | ((props: TableInstance<D>) => ReactNode)
Cell?: ReactNode | ((cell: Cell<D>) => ReactNode)
/**
* This is the unique ID for the column. It is used by reference in things like sorting, grouping, filtering etc.
*/
id?: IdType<D>
minWidth?: string | number
maxWidth?: string | number
width?: string | number
disableSorting?: boolean
canSortBy?: boolean
sortByFn?: SortByFn
defaultSortDesc?: boolean
isAggregated?: any
}
export interface Column<D> extends HeaderColumn<D> {
show?: boolean | ((instance: TableInstance<D>) => boolean)
columns?: Column<D>[]
}
export type Page<D = {}> = Row<D>[]
export interface EnhancedColumn<D>
extends Omit<Column<D>, 'columns'>,
TableInstance<D> {
id: IdType<D>
column: Column<D>
render: (type: 'Header' | 'Filter', userProps?: any) => any
getHeaderProps: (userProps?: any) => any
getSortByToggleProps: (userProps?: any) => any
isSorted: boolean
isSortedDesc: boolean
sortedIndex: number
isVisible: boolean
canSort?: boolean
}
export interface HeaderGroup<D = {}> {
headers: EnhancedColumn<D>[]
getHeaderGroupProps: (userProps?: any) => any
}
export interface Hooks {
columnsBeforeHeaderGroups: any[]
columnsBeforeHeaderGroupsDeps: any[]
useMain: any[]
useColumns: any[]
useHeaders: any[]
useHeaderGroups: any[]
useRows: any[]
prepareRow: any[]
getTableProps: any[]
getRowProps: any[]
getHeaderGroupProps: any[]
getHeaderProps: any[]
getCellProps: any[]
}
export interface RowsProps {
subRowsKey: string
}
export interface FiltersProps {
filterFn: () => void
manualFilters: boolean
disableFilters: boolean
setFilter: () => any
setAllFilters: () => any
}
export interface UsePaginationState {
pageIndex: number
pageSize: number
pageCount: number
rowCount: number
}
export interface UsePaginationValues<D = {}> {
page: Page<D>
pageIndex: number // yes, this is on instance and state
pageSize: number // yes, this is on instance and state
canPreviousPage: boolean
canNextPage: boolean
nextPage: () => any
previousPage: () => any
setPageSize: (size: number) => any
pageOptions: any[]
manualPagination: boolean
paginateExpandedRows: boolean
disablePageResetOnDataChange: boolean
pageCount: number
gotoPage: (page: number) => any
}
export interface UseFiltersState<D> {
filters?: Filters<D>
}
export interface UseFiltersValues<D> {
setFilter: (columnID: keyof D, value: string) => void
setAllFilters: (values: Filters<D>) => void
disableFilters: boolean
}
export interface UseGroupByValues {
groupByFn: any
manualGroupBy: boolean
disableGrouping: boolean
aggregations: any
}
export interface UseGroupByState {
groupBy: string[]
isAggregated?: boolean
}
export interface UseExpandedValues {
toggleExpanded?: () => any
}
export interface UseSortbyOptions {
sortByFn?: SortByFn
manualSorting?: boolean
disableSorting?: boolean
defaultSortDesc?: boolean
disableMultiSort?: boolean
}
export interface UseSortbyState<D> {
sortBy?: SortingRules<D>
}
export interface TableInstance<D = {}> extends TableOptions<D> {
hooks: Hooks
rows: Row<D>[]
columns: EnhancedColumn<D>[]
headerGroups: HeaderGroup<D>[]
headers: HeaderGroup<D>[]
getTableProps: (userProps?: any) => any
getRowProps: (userProps?: any) => any
prepareRow: (row: Row<D>) => any
}
export interface TableOptions<D = {}> {
data: D[]
columns: HeaderColumn<D>[]
state: State<D>
debug?: boolean
loading: boolean
defaultColumn?: Partial<Column<D>>
}
// The empty definition of TableState is not an error. It provides a definition
// for the state, that can then be extended in the users code.
//
// e.g.
//
// export interface TableState<D = {}}>
// extends UsePaginationState,
// UseGroupByState,
// UseSortbyState<D>,
// UseFiltersState<D> {}
// eslint-disable-next-line @typescript-eslint/no-empty-interface
export interface TableState<D = {}> {}
export type SetState<D> = (
updater: (old: TableState<D>) => TableState<D>,
actions: any
) => void
export type State<D> = [TableState<D>, SetState<D>]
export function useTable<D = {}>(
props: TableOptions<D>,
...plugins: any[]
): TableInstance<D>
export function useFilters<D = {}>(
props: TableOptions<D>
): TableOptions<D> & {
rows: Row<D>[]
}
export function useSortBy<D = {}>(
props: TableOptions<D>
): TableOptions<D> & {
rows: Row<D>[]
}
export function useGroupBy<D = {}>(
props: TableOptions<D>
): TableOptions<D> & { rows: Row<D>[] }
export function usePagination<D = {}>(
props: TableOptions<D>
): UsePaginationValues<D>
export function useExpanded<D = {}>(
props: TableOptions<D>
): TableOptions<D> & {
toggleExpandedByPath: () => any
expandedDepth: []
rows: Row<D>[]
}
export function useTableState<D = {}>(
initialState?: Partial<TableState<D>>,
overriddenState?: Partial<TableState<D>>,
options?: {
reducer?: (
oldState: TableState<D>,
newState: TableState<D>,
type: string
) => any
useState?: typeof useState
}
): State<D>
export const actions: Record<string, string>
export function addActions(...actions: string[]): void
export const defaultState: Record<string, any>
}
Binary file not shown.
+175 -39
View File
@@ -1,6 +1,6 @@
{
"name": "react-table",
"version": "7.0.0-alpha.12",
"version": "7.0.0-alpha.29",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
@@ -1605,16 +1605,17 @@
}
},
"@testing-library/dom": {
"version": "5.6.0",
"resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-5.6.0.tgz",
"integrity": "sha512-nAsRvQLr/b6TGNjuHMEbWXCNPLrQYnzqa/KKQZL7wBOtfptUxsa4Ah9aqkHW0ZmCSFmUDj4nFUxWPVTeMu0iCw==",
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/@testing-library/dom/-/dom-6.1.0.tgz",
"integrity": "sha512-qivqFvnbVIH3DyArFofEU/jlOhkGIioIemOy9A9M/NQTpPyDDQmtVkAfoB18RKN581f0s/RJMRBbq9WfMIhFTw==",
"dev": true,
"requires": {
"@babel/runtime": "^7.4.5",
"@babel/runtime": "^7.5.5",
"@sheerun/mutationobserver-shim": "^0.3.2",
"@types/testing-library__dom": "^6.0.0",
"aria-query": "3.0.0",
"pretty-format": "^24.8.0",
"wait-for-expect": "^1.2.0"
"wait-for-expect": "^1.3.0"
}
},
"@testing-library/jest-dom": {
@@ -1635,13 +1636,14 @@
}
},
"@testing-library/react": {
"version": "8.0.7",
"resolved": "https://registry.npmjs.org/@testing-library/react/-/react-8.0.7.tgz",
"integrity": "sha512-6XoeWSr3UCdxMswbkW0BmuXYw8a6w+stt+5gg4D4zAcljfhXETQ5o28bjJFwNab4OPg8gBNK8KIVot86L4Q8Vg==",
"version": "9.1.3",
"resolved": "https://registry.npmjs.org/@testing-library/react/-/react-9.1.3.tgz",
"integrity": "sha512-qFVo6TsEbpEFpOmKjIxMHDujOKVdvVpcYFcUfJeWBqMO8eja5pN9SZnt6W6AzW3a1MRvRfw3X0Fhx3eXnBJxjA==",
"dev": true,
"requires": {
"@babel/runtime": "^7.5.4",
"@testing-library/dom": "^5.5.4"
"@babel/runtime": "^7.5.5",
"@testing-library/dom": "^6.0.0",
"@types/testing-library__react": "^9.1.0"
}
},
"@types/babel__core": {
@@ -1751,12 +1753,43 @@
"integrity": "sha512-f5j5b/Gf71L+dbqxIpQ4Z2WlmI/mPJ0fOkGGmFgtb6sAu97EPczzbS3/tJKxmcYDj55OX6ssqwDAWOHIYDRDGA==",
"dev": true
},
"@types/pretty-format": {
"version": "20.0.1",
"resolved": "https://registry.npmjs.org/@types/pretty-format/-/pretty-format-20.0.1.tgz",
"integrity": "sha512-Oh7wnvVUCtVIWnCHQWe9qDZKn0fGyk5AMq99jXml0x39K59P+z9qe31CNRtop9TceCpS7NmoK+J9eGeCnyFgnw==",
"dev": true
},
"@types/prop-types": {
"version": "15.7.1",
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.1.tgz",
"integrity": "sha512-CFzn9idOEpHrgdw8JsoTkaDDyRWk1jrzIV8djzcgpq0y9tG4B4lFT+Nxh52DVpDXV+n4+NPNv7M1Dj5uMp6XFg==",
"dev": true
},
"@types/q": {
"version": "1.5.2",
"resolved": "https://registry.npmjs.org/@types/q/-/q-1.5.2.tgz",
"integrity": "sha512-ce5d3q03Ex0sy4R14722Rmt6MT07Ua+k4FwDfdcToYJcMKNtRVQvJ6JCAPdAmAnbRb6CsX6aYb9m96NGod9uTw==",
"dev": true
},
"@types/react": {
"version": "16.9.2",
"resolved": "https://registry.npmjs.org/@types/react/-/react-16.9.2.tgz",
"integrity": "sha512-jYP2LWwlh+FTqGd9v7ynUKZzjj98T8x7Yclz479QdRhHfuW9yQ+0jjnD31eXSXutmBpppj5PYNLYLRfnZJvcfg==",
"dev": true,
"requires": {
"@types/prop-types": "*",
"csstype": "^2.2.0"
}
},
"@types/react-dom": {
"version": "16.9.0",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-16.9.0.tgz",
"integrity": "sha512-OL2lk7LYGjxn4b0efW3Pvf2KBVP0y1v3wip1Bp7nA79NkOpElH98q3WdCEdDj93b2b0zaeBG9DvriuKjIK5xDA==",
"dev": true,
"requires": {
"@types/react": "*"
}
},
"@types/resolve": {
"version": "0.0.8",
"resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-0.0.8.tgz",
@@ -1778,6 +1811,25 @@
"integrity": "sha512-l42BggppR6zLmpfU6fq9HEa2oGPEI8yrSPL3GITjfRInppYFahObbIQOQK3UGxEnyQpltZLaPe75046NOZQikw==",
"dev": true
},
"@types/testing-library__dom": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/@types/testing-library__dom/-/testing-library__dom-6.0.1.tgz",
"integrity": "sha512-j8wJmvER0VVrmDtab80SwA4MgF0vzFm6hSyk3j2bw9PXyJxgMjFDF8ihJDzo2gUOMP+HpEquHRZcUXOhLmYexA==",
"dev": true,
"requires": {
"@types/pretty-format": "*"
}
},
"@types/testing-library__react": {
"version": "9.1.1",
"resolved": "https://registry.npmjs.org/@types/testing-library__react/-/testing-library__react-9.1.1.tgz",
"integrity": "sha512-8/toTJaIlS3BC7JrK2ElTnbjH8tmFP7atdL2ZsIa1JDmH9RKSm/7Wp5oMDJzXoWr988Mv7ym/XZ8LRglyoGCGw==",
"dev": true,
"requires": {
"@types/react-dom": "*",
"@types/testing-library__dom": "*"
}
},
"@types/yargs": {
"version": "12.0.12",
"resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-12.0.12.tgz",
@@ -2334,6 +2386,12 @@
"regenerator-runtime": "^0.10.5"
},
"dependencies": {
"core-js": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/core-js/-/core-js-2.6.9.tgz",
"integrity": "sha512-HOpZf6eXmnl7la+cUdMnLvUxKNqLUzJvgIziQ0DiF3JwSImNphIqdGqzj6hIKyX04MmV0poclQ7+wjWvxQyR2A==",
"dev": true
},
"regenerator-runtime": {
"version": "0.10.5",
"resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.10.5.tgz",
@@ -2367,6 +2425,12 @@
"source-map-support": "^0.4.15"
},
"dependencies": {
"core-js": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/core-js/-/core-js-2.6.9.tgz",
"integrity": "sha512-HOpZf6eXmnl7la+cUdMnLvUxKNqLUzJvgIziQ0DiF3JwSImNphIqdGqzj6hIKyX04MmV0poclQ7+wjWvxQyR2A==",
"dev": true
},
"source-map-support": {
"version": "0.4.18",
"resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.4.18.tgz",
@@ -2388,6 +2452,12 @@
"regenerator-runtime": "^0.11.0"
},
"dependencies": {
"core-js": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/core-js/-/core-js-2.6.9.tgz",
"integrity": "sha512-HOpZf6eXmnl7la+cUdMnLvUxKNqLUzJvgIziQ0DiF3JwSImNphIqdGqzj6hIKyX04MmV0poclQ7+wjWvxQyR2A==",
"dev": true
},
"regenerator-runtime": {
"version": "0.11.1",
"resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.11.1.tgz",
@@ -3179,9 +3249,9 @@
"dev": true
},
"core-js": {
"version": "2.6.9",
"resolved": "https://registry.npmjs.org/core-js/-/core-js-2.6.9.tgz",
"integrity": "sha512-HOpZf6eXmnl7la+cUdMnLvUxKNqLUzJvgIziQ0DiF3JwSImNphIqdGqzj6hIKyX04MmV0poclQ7+wjWvxQyR2A==",
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/core-js/-/core-js-3.2.1.tgz",
"integrity": "sha512-Qa5XSVefSVPRxy2XfUC13WbvqkxhkwB3ve+pgCQveNgYzbM/UxZeu1dcOX/xr4UmfUd+muuvsaxilQzCyUurMw==",
"dev": true
},
"core-js-compat": {
@@ -3363,6 +3433,12 @@
"cssom": "0.3.x"
}
},
"csstype": {
"version": "2.6.6",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-2.6.6.tgz",
"integrity": "sha512-RpFbQGUE74iyPgvr46U9t1xoQBM8T4BL8SxrN66Le2xYAPSaDJJKeztV3awugusb3g3G9iL8StmkBBXhcbbXhg==",
"dev": true
},
"currently-unhandled": {
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/currently-unhandled/-/currently-unhandled-0.4.1.tgz",
@@ -4112,9 +4188,9 @@
}
},
"eslint-plugin-react-hooks": {
"version": "1.6.1",
"resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-1.6.1.tgz",
"integrity": "sha512-wHhmGJyVuijnYIJXZJHDUF2WM+rJYTjulUTqF9k61d3BTk8etydz+M4dXUVH7M76ZRS85rqBTCx0Es/lLsrjnA==",
"version": "1.7.0",
"resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-1.7.0.tgz",
"integrity": "sha512-iXTCFcOmlWvw4+TOE8CLWj6yX1GwzT0Y6cUfHHZqWnSk144VmVIRcVGtUAzrLES7C798lmvnt02C7rxaOX1HNA==",
"dev": true
},
"eslint-plugin-standard": {
@@ -4134,9 +4210,9 @@
}
},
"eslint-utils": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-1.4.0.tgz",
"integrity": "sha512-7ehnzPaP5IIEh1r1tkjuIrxqhNkzUJa9z3R92tLJdZIVdWaczEhr3EbhGtsMrVxi1KeR8qA7Off6SWc5WNQqyQ==",
"version": "1.4.2",
"resolved": "https://registry.npmjs.org/eslint-utils/-/eslint-utils-1.4.2.tgz",
"integrity": "sha512-eAZS2sEUMlIeCjBeubdj45dmBHQwPHWyBcT1VSYB7o9x9WRRqKxyUoiXlRjyAwzN7YEzHJlYg0NmzDRWx6GP4Q==",
"dev": true,
"requires": {
"eslint-visitor-keys": "^1.0.0"
@@ -5731,9 +5807,9 @@
}
},
"husky": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/husky/-/husky-3.0.2.tgz",
"integrity": "sha512-WXCtaME2x0o4PJlKY4ap8BzLA+D0zlvefqAvLCPriOOu+x0dpO5uc5tlB7CY6/0SE2EESmoZsj4jW5D09KrJoA==",
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/husky/-/husky-3.0.4.tgz",
"integrity": "sha512-7Rnt8aJfy+MlV28snmYK7O7vWwtOfeVxV6KhLpUFXlmx5ukQ1nQmNUB7QsAwSgdySB5X+bm7q7JIRgazqBUzKA==",
"dev": true,
"requires": {
"chalk": "^2.4.2",
@@ -5743,7 +5819,7 @@
"is-ci": "^2.0.0",
"opencollective-postinstall": "^2.0.2",
"pkg-dir": "^4.2.0",
"please-upgrade-node": "^3.1.1",
"please-upgrade-node": "^3.2.0",
"read-pkg": "^5.1.1",
"run-node": "^1.0.0",
"slash": "^3.0.0"
@@ -5765,15 +5841,6 @@
"integrity": "sha512-zRKcywvrXlXsA0v0i9Io4KDRaAw7+a1ZpjRwl9Wox8PFlVCCHra7E9c4kqXCoCM9nR5tBkaTTZRBoCm60bFqTQ==",
"dev": true
},
"is-ci": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/is-ci/-/is-ci-2.0.0.tgz",
"integrity": "sha512-YfJT7rkpQB0updsdHLGWrvhBJfcfzNNawYDNIyQXJz0IViGf75O8EBPKSdvw2rF+LGCsX4FZ8tcr3b19LcZq4w==",
"dev": true,
"requires": {
"ci-info": "^2.0.0"
}
},
"locate-path": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz",
@@ -5784,9 +5851,9 @@
}
},
"p-limit": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.2.0.tgz",
"integrity": "sha512-pZbTJpoUsCzV48Mc9Nh51VbwO0X9cuPFE8gYwx9BTCt9SF8/b7Zljd2fVgOxhIF/HDTKgpVzs+GPhyKfjLLFRQ==",
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.2.1.tgz",
"integrity": "sha512-85Tk+90UCVWvbDavCLKPOLC9vvY8OwEX/RtKF+/1OADJMVlFfEHOiMTPVyxg7mk/dKa+ipdHm0OUkTvCpMTuwg==",
"dev": true,
"requires": {
"p-try": "^2.0.0"
@@ -5834,6 +5901,15 @@
"find-up": "^4.0.0"
}
},
"please-upgrade-node": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/please-upgrade-node/-/please-upgrade-node-3.2.0.tgz",
"integrity": "sha512-gQR3WpIgNIKwBMVLkpMUeR3e1/E1y42bqDQZfql+kDeXd8COYfM8PQA4X6y7a8u9Ua9FHmsrrmirW2vHs45hWg==",
"dev": true,
"requires": {
"semver-compare": "^1.0.0"
}
},
"read-pkg": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-5.2.0.tgz",
@@ -6040,6 +6116,15 @@
"integrity": "sha512-r5p9sxJjYnArLjObpjA4xu5EKI3CuKHkJXMhT7kwbpUyIFD1n5PMAsoPvWnvtZiNz7LjkYDRZhd7FlI0eMijEA==",
"dev": true
},
"is-ci": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/is-ci/-/is-ci-2.0.0.tgz",
"integrity": "sha512-YfJT7rkpQB0updsdHLGWrvhBJfcfzNNawYDNIyQXJz0IViGf75O8EBPKSdvw2rF+LGCsX4FZ8tcr3b19LcZq4w==",
"dev": true,
"requires": {
"ci-info": "^2.0.0"
}
},
"is-ci-cli": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/is-ci-cli/-/is-ci-cli-1.1.1.tgz",
@@ -9346,6 +9431,12 @@
"integrity": "sha1-gV7R9uvGWSb4ZbMQwHE7yzMVzks=",
"dev": true
},
"prettier": {
"version": "1.18.2",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-1.18.2.tgz",
"integrity": "sha512-OeHeMc0JhFE9idD4ZdtNibzY0+TPHSpSSb9h8FqtP+YnoZZ1sl8Vc9b1sasjfymH3SonAF4QcA2+mzHPhMvIiw==",
"dev": true
},
"prettier-linter-helpers": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/prettier-linter-helpers/-/prettier-linter-helpers-1.0.0.tgz",
@@ -9477,6 +9568,29 @@
}
}
},
"react": {
"version": "16.9.0",
"resolved": "https://registry.npmjs.org/react/-/react-16.9.0.tgz",
"integrity": "sha512-+7LQnFBwkiw+BobzOF6N//BdoNw0ouwmSJTEm9cglOOmsg/TMiFHZLe2sEoN5M7LgJTj9oHH0gxklfnQe66S1w==",
"dev": true,
"requires": {
"loose-envify": "^1.1.0",
"object-assign": "^4.1.1",
"prop-types": "^15.6.2"
}
},
"react-dom": {
"version": "16.9.0",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-16.9.0.tgz",
"integrity": "sha512-YFT2rxO9hM70ewk9jq0y6sQk8cL02xm4+IzYBz75CQGlClQQ1Bxq0nhHF6OtSbit+AIahujJgb/CPRibFkMNJQ==",
"dev": true,
"requires": {
"loose-envify": "^1.1.0",
"object-assign": "^4.1.1",
"prop-types": "^15.6.2",
"scheduler": "^0.15.0"
}
},
"react-is": {
"version": "16.8.6",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.8.6.tgz",
@@ -10035,6 +10149,16 @@
"integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==",
"dev": true
},
"scheduler": {
"version": "0.15.0",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.15.0.tgz",
"integrity": "sha512-xAefmSfN6jqAa7Kuq7LIJY0bwAPG3xlCj0HMEBQk1lxYiDKZscY2xJ5U/61ZTrYbmNQbXa+gc7czPkVo11tnCg==",
"dev": true,
"requires": {
"loose-envify": "^1.1.0",
"object-assign": "^4.1.1"
}
},
"semver": {
"version": "5.7.0",
"resolved": "https://registry.npmjs.org/semver/-/semver-5.7.0.tgz",
@@ -10289,6 +10413,18 @@
"kind-of": "^3.2.0"
}
},
"snapshot-diff": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/snapshot-diff/-/snapshot-diff-0.5.2.tgz",
"integrity": "sha512-6cKemS91iEZCRRHQUjYBcPMIUz70lqWVoffqx7nhZ2XP/tG+EJKK0O8tANW0zHcmaEOfu00cfzKhsg08QdC9fg==",
"dev": true,
"requires": {
"jest-diff": "^24.0.0",
"jest-snapshot": "^24.0.0",
"pretty-format": "^24.0.0",
"strip-ansi": "^5.0.0"
}
},
"source-map": {
"version": "0.5.7",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.5.7.tgz",
@@ -11105,9 +11241,9 @@
}
},
"wait-for-expect": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/wait-for-expect/-/wait-for-expect-1.2.0.tgz",
"integrity": "sha512-EJhKpA+5UHixduMBEGhTFuLuVgQBKWxkFbefOdj2bbk2/OpA5Opsc4aUTGmF+qJ+v3kTGxDRNYwKaT4j6g5n8Q==",
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/wait-for-expect/-/wait-for-expect-1.3.0.tgz",
"integrity": "sha512-8fJU7jiA96HfGPt+P/UilelSAZfhMBJ52YhKzlmZQvKEZU2EcD1GQ0yqGB6liLdHjYtYAoGVigYwdxr5rktvzA==",
"dev": true
},
"walker": {
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "react-table",
"version": "7.0.0-alpha.26",
"version": "7.0.0-beta.2",
"description": "A fast, lightweight, opinionated table and datagrid built on React",
"license": "MIT",
"homepage": "https://github.com/tannerlinsley/react-table#readme",
@@ -27,11 +27,12 @@
"prepare": "yarn build",
"release": "yarn publish",
"releaseNext": "yarn publish --tag next",
"format": "prettier ./src/**/*.{md,js,jsx,tsx} --write"
"format": "prettier {src,src/**,examples/*/src,examples/*/src/**}/*.{md,js,jsx,tsx} --write"
},
"files": [
"CHANGELOG.md",
"src/**/*.js",
"index.d.ts",
"dist",
"LICENCE",
"package.json",
+80 -80
View File
@@ -8,9 +8,8 @@ import {
flexRender,
decorateColumnTree,
makeHeaderGroups,
findMaxDepth,
flattenBy,
determineColumnVisibility,
determineHeaderVisibility,
} from '../utils'
import { useTableState } from './useTableState'
@@ -18,14 +17,10 @@ import { useTableState } from './useTableState'
const propTypes = {
// General
data: PropTypes.array.isRequired,
columns: PropTypes.arrayOf(
PropTypes.shape({
Cell: PropTypes.any,
Header: PropTypes.any,
})
).isRequired,
columns: PropTypes.arrayOf(PropTypes.object).isRequired,
defaultColumn: PropTypes.object,
subRowsKey: PropTypes.string,
getSubRows: PropTypes.func,
getRowID: PropTypes.func,
debug: PropTypes.bool,
}
@@ -34,6 +29,9 @@ const renderErr =
const defaultColumnInstance = {}
const defaultGetSubRows = (row, index) => row.subRows || []
const defaultGetRowID = (row, index) => index
export const useTable = (props, ...plugins) => {
// Validate props
PropTypes.checkPropTypes(propTypes, props, 'property', 'useTable')
@@ -44,7 +42,8 @@ export const useTable = (props, ...plugins) => {
state: userState,
columns: userColumns,
defaultColumn = defaultColumnInstance,
subRowsKey = 'subRows',
getSubRows = defaultGetSubRows,
getRowID = defaultGetRowID,
debug,
} = props
@@ -89,22 +88,20 @@ export const useTable = (props, ...plugins) => {
console.timeEnd('plugins')
// Decorate All the columns
let headers = React.useMemo(
let columns = React.useMemo(
() => decorateColumnTree(userColumns, defaultColumn),
[defaultColumn, userColumns]
)
// Get the flat list of all columns
let columns = React.useMemo(() => flattenBy(headers, 'columns'), [headers])
// Allow hooks to decorate columns (and trigger this memoization via deps)
columns = React.useMemo(() => {
// Get the flat list of all columns andllow hooks to decorate
// those columns (and trigger this memoization via deps)
let flatColumns = React.useMemo(() => {
if (process.env.NODE_ENV === 'development' && debug)
console.time('hooks.columnsBeforeHeaderGroups')
let newColumns = applyHooks(
instanceRef.current.hooks.columnsBeforeHeaderGroups,
columns,
flattenBy(columns, 'columns'),
instanceRef.current
)
@@ -124,12 +121,15 @@ export const useTable = (props, ...plugins) => {
// Make the headerGroups
const headerGroups = React.useMemo(
() => makeHeaderGroups(columns, findMaxDepth(headers), defaultColumn),
[columns, defaultColumn, headers]
() => makeHeaderGroups(flatColumns, defaultColumn),
[defaultColumn, flatColumns]
)
const headers = React.useMemo(() => headerGroups[0].headers, [headerGroups])
Object.assign(instanceRef.current, {
columns,
flatColumns,
headerGroups,
headers,
})
@@ -147,18 +147,20 @@ export const useTable = (props, ...plugins) => {
// Keep the original reference around
const original = originalRow
const rowID = getRowID(originalRow, i)
// Make the new path for the row
const path = [...parentPath, i]
const path = [...parentPath, rowID]
flatRows++
rowPaths.push(path.join('.'))
// Process any subRows
const subRows = originalRow[subRowsKey]
? originalRow[subRowsKey].map((d, i) =>
accessRow(d, i, depth + 1, path)
)
: []
let subRows = getSubRows(originalRow, i)
if (subRows) {
subRows = subRows.map((d, i) => accessRow(d, i, depth + 1, path))
}
const row = {
original,
@@ -183,7 +185,7 @@ export const useTable = (props, ...plugins) => {
// Create the cells and values
row.values = {}
columns.forEach(column => {
flatColumns.forEach(column => {
row.values[column.id] = column.accessor
? column.accessor(originalRow, i, { subRows, depth, data })
: undefined
@@ -197,14 +199,14 @@ export const useTable = (props, ...plugins) => {
if (process.env.NODE_ENV === 'development' && debug)
console.timeEnd('getAccessedRows')
return [accessedData, rowPaths, flatRows]
}, [debug, data, columns, subRowsKey])
}, [debug, data, getRowID, getSubRows, flatColumns])
instanceRef.current.rows = rows
instanceRef.current.rowPaths = rowPaths
instanceRef.current.flatRows = flatRows
// Determine column visibility
determineColumnVisibility(instanceRef.current)
determineHeaderVisibility(instanceRef.current)
// Provide a flat header list for utilities
instanceRef.current.flatHeaders = headerGroups.reduce(
@@ -244,7 +246,7 @@ export const useTable = (props, ...plugins) => {
mergeProps(
{
key: ['header', column.id].join('_'),
colSpan: column.totalHeaderCount,
colSpan: column.totalVisibleHeaderCount,
},
applyPropHooks(
instanceRef.current.hooks.getHeaderProps,
@@ -258,15 +260,15 @@ export const useTable = (props, ...plugins) => {
instanceRef.current.headerGroups.forEach((headerGroup, i) => {
// Filter out any headers and headerGroups that don't have visible columns
headerGroup.headers = headerGroup.headers.filter(header => {
const recurse = columns =>
columns.filter(column => {
if (column.columns) {
return recurse(column.columns)
const recurse = headers =>
headers.filter(header => {
if (header.headers) {
return recurse(header.headers)
}
return column.isVisible
return header.isVisible
}).length
if (header.columns) {
return recurse(header.columns)
if (header.headers) {
return recurse(header.headers)
}
return header.isVisible
})
@@ -316,53 +318,51 @@ export const useTable = (props, ...plugins) => {
props
)
const visibleColumns = instanceRef.current.columns.filter(
column => column.isVisible
)
// Build the cells for each row
row.cells = visibleColumns.map(column => {
const cell = {
column,
row,
value: row.values[column.id],
}
// 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
)
}
// Give each cell a renderer function (supports multiple renderers)
cell.render = (type, userProps = {}) => {
const Comp = typeof type === 'string' ? column[type] : type
if (typeof Comp === 'undefined') {
throw new Error(renderErr)
}
return flexRender(Comp, {
...instanceRef.current,
// Build the visible cells for each row
row.cells = instanceRef.current.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 = props => {
const columnPathStr = [...row.path, column.id].join('_')
return mergeProps(
{
key: ['cell', columnPathStr].join('_'),
},
applyPropHooks(
instanceRef.current.hooks.getCellProps,
cell,
instanceRef.current
),
props
)
}
// Give each cell a renderer function (supports multiple renderers)
cell.render = (type, userProps = {}) => {
const Comp = typeof type === 'string' ? column[type] : type
if (typeof Comp === 'undefined') {
throw new Error(renderErr)
}
return flexRender(Comp, {
...instanceRef.current,
column,
row,
cell,
...userProps,
})
}
return cell
})
// need to apply any row specific hooks (useExpanded requires this)
applyHooks(instanceRef.current.hooks.prepareRow, row, instanceRef.current)
+2
View File
@@ -1,5 +1,6 @@
import * as utils from './utils'
export { utils }
export { defaultColumn } from './utils'
export { useTable } from './hooks/useTable'
export { useTableState, defaultState } from './hooks/useTableState'
export { useExpanded } from './plugin-hooks/useExpanded'
@@ -9,4 +10,5 @@ export { useSortBy } from './plugin-hooks/useSortBy'
export { usePagination } from './plugin-hooks/usePagination'
export { useRowSelect } from './plugin-hooks/useRowSelect'
export { useRowState } from './plugin-hooks/useRowState'
export { useColumnOrder } from './plugin-hooks/useColumnOrder'
export { actions, addActions } from './actions'
@@ -10,16 +10,16 @@ Snapshot Diff:
<pre>
<code>
{
- "expanded": {}
+ "expanded": {
+ "0": true
+ }
- "expanded": []
+ "expanded": [
+ "0"
+ ]
}
</code>
</pre>
<table
class=""
@@ -78,10 +80,53 @@
@@ -82,10 +84,53 @@
<td
class=""
>
@@ -73,7 +73,7 @@ Snapshot Diff:
</span>
</td>
<td
@@ -111,10 +156,139 @@
@@ -115,10 +160,139 @@
</td>
<td
class=""
@@ -220,22 +220,21 @@ Snapshot Diff:
- First value
+ Second value
@@ -1,11 +1,13 @@
@@ -1,11 +1,12 @@
<DocumentFragment>
<pre>
<code>
{
"expanded": {
- "0": true
+ "0": {
+ "0": true
+ }
}
"expanded": [
- "0"
+ "0",
+ "0.0"
]
}
</code>
</pre>
<table
@@ -123,10 +125,53 @@
@@ -127,11 +128,54 @@
<td
class=""
>
@@ -281,15 +280,16 @@ Snapshot Diff:
+ >
+ <td
+ class=""
+ >
>
+ <span
+ style="cursor: pointer; padding-left: 4rem;"
>
+ >
👉
</span>
</td>
<td
@@ -156,10 +201,139 @@
class=""
@@ -160,10 +204,139 @@
</td>
<td
class=""
@@ -436,22 +436,21 @@ Snapshot Diff:
- First value
+ Second value
@@ -2,11 +2,13 @@
@@ -2,11 +2,12 @@
<pre>
<code>
{
"expanded": {
"0": {
- "0": true
+ "0": {
+ "0": true
+ }
}
}
"expanded": [
"0",
- "0.0"
+ "0.0",
+ "0.0.0"
]
}
</code>
</pre>
@@ -168,10 +170,53 @@
<table
@@ -171,11 +172,54 @@
<td
class=""
>
@@ -497,15 +496,16 @@ Snapshot Diff:
+ >
+ <td
+ class=""
+ >
>
+ <span
+ style="cursor: pointer; padding-left: 6rem;"
>
+ >
👉
</span>
</td>
<td
@@ -201,10 +246,139 @@
class=""
@@ -204,10 +248,139 @@
</td>
<td
class=""
@@ -652,22 +652,21 @@ Snapshot Diff:
- First value
+ Second value
@@ -3,11 +3,13 @@
@@ -3,11 +3,12 @@
<code>
{
"expanded": {
"0": {
"0": {
- "0": true
+ "0": {
+ "0": true
+ }
}
}
}
"expanded": [
"0",
"0.0",
- "0.0.0"
+ "0.0.0",
+ "0.0.0.0"
]
}
</code>
@@ -214,11 +216,11 @@
</pre>
<table
@@ -216,11 +217,11 @@
class=""
>
<span
@@ -680,7 +679,7 @@ Snapshot Diff:
<td
class=""
>
@@ -246,10 +248,30 @@
@@ -248,10 +249,30 @@
</td>
<td
class=""
@@ -712,3 +711,587 @@ Snapshot Diff:
class=""
>
`;
exports[`renders an expandable table 5`] = `
Snapshot Diff:
- First value
+ Second value
@@ -1,15 +1,10 @@
<DocumentFragment>
<pre>
<code>
{
- "expanded": [
- "0",
- "0.0",
- "0.0.0",
- "0.0.0.0"
- ]
+ "expanded": []
}
</code>
</pre>
<table
class=""
@@ -88,140 +83,11 @@
class=""
>
<span
style="cursor: pointer; padding-left: 0rem;"
>
- 👇
- </span>
- </td>
- <td
- class=""
- >
- tanner
- </td>
- <td
- class=""
- >
- linsley
- </td>
- <td
- class=""
- >
- 29
- </td>
- <td
- class=""
- >
- 100
- </td>
- <td
- class=""
- >
- In Relationship
- </td>
- <td
- class=""
- >
- 50
- </td>
- </tr>
- <tr
- class=""
- >
- <td
- class=""
- >
- <span
- style="cursor: pointer; padding-left: 2rem;"
- >
- 👇
- </span>
- </td>
- <td
- class=""
- >
- tanner
- </td>
- <td
- class=""
- >
- linsley
- </td>
- <td
- class=""
- >
- 29
- </td>
- <td
- class=""
- >
- 100
- </td>
- <td
- class=""
- >
- In Relationship
- </td>
- <td
- class=""
- >
- 50
- </td>
- </tr>
- <tr
- class=""
- >
- <td
- class=""
- >
- <span
- style="cursor: pointer; padding-left: 4rem;"
- >
- 👇
- </span>
- </td>
- <td
- class=""
- >
- tanner
- </td>
- <td
- class=""
- >
- linsley
- </td>
- <td
- class=""
- >
- 29
- </td>
- <td
- class=""
- >
- 100
- </td>
- <td
- class=""
- >
- In Relationship
- </td>
- <td
- class=""
- >
- 50
- </td>
- </tr>
- <tr
- class=""
- >
- <td
- class=""
- >
- <span
- style="cursor: pointer; padding-left: 6rem;"
- >
- 👇
+ 👉
</span>
</td>
<td
class=""
>
@@ -249,417 +115,10 @@
</td>
<td
class=""
>
50
- </td>
- </tr>
- <tr>
- <td
- colspan="7"
- >
- <pre>
- <code>
- {
- "values": {
- "firstName": "tanner",
- "lastName": "linsley",
- "age": 29,
- "visits": 100,
- "status": "In Relationship",
- "progress": 50
- }
- }
- </code>
- </pre>
- </td>
- </tr>
- <tr
- class=""
- >
- <td
- class=""
- >
- <span
- style="cursor: pointer; padding-left: 6rem;"
- >
- 👉
- </span>
- </td>
- <td
- class=""
- >
- derek
- </td>
- <td
- class=""
- >
- perkins
- </td>
- <td
- class=""
- >
- 40
- </td>
- <td
- class=""
- >
- 40
- </td>
- <td
- class=""
- >
- Single
- </td>
- <td
- class=""
- >
- 80
- </td>
- </tr>
- <tr
- class=""
- >
- <td
- class=""
- >
- <span
- style="cursor: pointer; padding-left: 6rem;"
- >
- 👉
- </span>
- </td>
- <td
- class=""
- >
- joe
- </td>
- <td
- class=""
- >
- bergevin
- </td>
- <td
- class=""
- >
- 45
- </td>
- <td
- class=""
- >
- 20
- </td>
- <td
- class=""
- >
- Complicated
- </td>
- <td
- class=""
- >
- 10
- </td>
- </tr>
- <tr
- class=""
- >
- <td
- class=""
- >
- <span
- style="cursor: pointer; padding-left: 6rem;"
- >
- 👉
- </span>
- </td>
- <td
- class=""
- >
- jaylen
- </td>
- <td
- class=""
- >
- linsley
- </td>
- <td
- class=""
- >
- 26
- </td>
- <td
- class=""
- >
- 99
- </td>
- <td
- class=""
- >
- In Relationship
- </td>
- <td
- class=""
- >
- 70
- </td>
- </tr>
- <tr
- class=""
- >
- <td
- class=""
- >
- <span
- style="cursor: pointer; padding-left: 4rem;"
- >
- 👉
- </span>
- </td>
- <td
- class=""
- >
- derek
- </td>
- <td
- class=""
- >
- perkins
- </td>
- <td
- class=""
- >
- 40
- </td>
- <td
- class=""
- >
- 40
- </td>
- <td
- class=""
- >
- Single
- </td>
- <td
- class=""
- >
- 80
- </td>
- </tr>
- <tr
- class=""
- >
- <td
- class=""
- >
- <span
- style="cursor: pointer; padding-left: 4rem;"
- >
- 👉
- </span>
- </td>
- <td
- class=""
- >
- joe
- </td>
- <td
- class=""
- >
- bergevin
- </td>
- <td
- class=""
- >
- 45
- </td>
- <td
- class=""
- >
- 20
- </td>
- <td
- class=""
- >
- Complicated
- </td>
- <td
- class=""
- >
- 10
- </td>
- </tr>
- <tr
- class=""
- >
- <td
- class=""
- >
- <span
- style="cursor: pointer; padding-left: 4rem;"
- >
- 👉
- </span>
- </td>
- <td
- class=""
- >
- jaylen
- </td>
- <td
- class=""
- >
- linsley
- </td>
- <td
- class=""
- >
- 26
- </td>
- <td
- class=""
- >
- 99
- </td>
- <td
- class=""
- >
- In Relationship
- </td>
- <td
- class=""
- >
- 70
- </td>
- </tr>
- <tr
- class=""
- >
- <td
- class=""
- >
- <span
- style="cursor: pointer; padding-left: 2rem;"
- >
- 👉
- </span>
- </td>
- <td
- class=""
- >
- derek
- </td>
- <td
- class=""
- >
- perkins
- </td>
- <td
- class=""
- >
- 40
- </td>
- <td
- class=""
- >
- 40
- </td>
- <td
- class=""
- >
- Single
- </td>
- <td
- class=""
- >
- 80
- </td>
- </tr>
- <tr
- class=""
- >
- <td
- class=""
- >
- <span
- style="cursor: pointer; padding-left: 2rem;"
- >
- 👉
- </span>
- </td>
- <td
- class=""
- >
- joe
- </td>
- <td
- class=""
- >
- bergevin
- </td>
- <td
- class=""
- >
- 45
- </td>
- <td
- class=""
- >
- 20
- </td>
- <td
- class=""
- >
- Complicated
- </td>
- <td
- class=""
- >
- 10
- </td>
- </tr>
- <tr
- class=""
- >
- <td
- class=""
- >
- <span
- style="cursor: pointer; padding-left: 2rem;"
- >
- 👉
- </span>
- </td>
- <td
- class=""
- >
- jaylen
- </td>
- <td
- class=""
- >
- linsley
- </td>
- <td
- class=""
- >
- 26
- </td>
- <td
- class=""
- >
- 99
- </td>
- <td
- class=""
- >
- In Relationship
- </td>
- <td
- class=""
- >
- 70
</td>
</tr>
<tr
class=""
>
`;
File diff suppressed because it is too large Load Diff
+21 -11
View File
@@ -50,7 +50,7 @@ function Table({ columns: userColumns, data, SubComponent }) {
headerGroups,
rows,
prepareRow,
columns,
flatColumns,
state: [{ expanded }],
} = useTable(
{
@@ -90,7 +90,9 @@ function Table({ columns: userColumns, data, SubComponent }) {
</tr>
{!row.subRows.length && row.isExpanded ? (
<tr>
<td colSpan={columns.length}>{SubComponent({ row })}</td>
<td colSpan={flatColumns.length}>
{SubComponent({ row })}
</td>
</tr>
) : null}
</React.Fragment>
@@ -176,29 +178,37 @@ test('renders an expandable table', () => {
let expandButtons = getAllByText('👉')
const beforeGrouping = asFragment()
const before = asFragment()
fireEvent.click(expandButtons[0])
const afterGrouping1 = asFragment()
const after1 = asFragment()
expandButtons = getAllByText('👉')
fireEvent.click(expandButtons[0])
const afterGrouping2 = asFragment()
const after2 = asFragment()
expandButtons = getAllByText('👉')
fireEvent.click(expandButtons[0])
const afterGrouping3 = asFragment()
const after3 = asFragment()
expandButtons = getAllByText('👉')
fireEvent.click(expandButtons[0])
const afterGrouping4 = asFragment()
const after4 = asFragment()
expect(beforeGrouping).toMatchDiffSnapshot(afterGrouping1)
expect(afterGrouping1).toMatchDiffSnapshot(afterGrouping2)
expect(afterGrouping2).toMatchDiffSnapshot(afterGrouping3)
expect(afterGrouping3).toMatchDiffSnapshot(afterGrouping4)
expandButtons = getAllByText('👇')
expandButtons.reverse().forEach(button => {
fireEvent.click(button)
})
const after5 = asFragment()
expect(before).toMatchDiffSnapshot(after1)
expect(after1).toMatchDiffSnapshot(after2)
expect(after2).toMatchDiffSnapshot(after3)
expect(after3).toMatchDiffSnapshot(after4)
expect(after4).toMatchDiffSnapshot(after5)
})
+14 -3
View File
@@ -4,7 +4,7 @@ import { useTable } from '../../hooks/useTable'
import { useRowSelect } from '../useRowSelect'
import { useExpanded } from '../useExpanded'
const data = [
const dataPiece = [
{
firstName: 'tanner',
lastName: 'linsley',
@@ -58,6 +58,15 @@ const data = [
},
]
const data = [
...dataPiece,
...dataPiece,
...dataPiece,
...dataPiece,
...dataPiece,
...dataPiece,
]
function Table({ columns, data }) {
// Use the state and functions returned from useTable to build your UI
const {
@@ -141,7 +150,10 @@ function App() {
{
id: 'selectedStatus',
Cell: ({ row }) => (
<div>{row.isSelected ? 'Selected' : 'Not Selected'}</div>
<div>
Row {row.path.join('.')}{' '}
{row.isSelected ? 'Selected' : 'Not Selected'}
</div>
),
},
{
@@ -218,7 +230,6 @@ test('renders a table with selectable rows', () => {
const fragment8 = asFragment()
expect(fragment1).toMatchDiffSnapshot(fragment2)
expect(fragment2).toMatchDiffSnapshot(fragment3)
expect(fragment3).toMatchDiffSnapshot(fragment4)
+80
View File
@@ -0,0 +1,80 @@
import React from 'react'
import PropTypes from 'prop-types'
import { addActions, actions } from '../actions'
import { defaultState } from '../hooks/useTableState'
defaultState.columnOrder = []
addActions('setColumnOrder')
const propTypes = {
initialRowStateAccessor: PropTypes.func,
}
export const useColumnOrder = hooks => {
hooks.columnsBeforeHeaderGroupsDeps.push((deps, instance) => {
return [...deps, instance.state[0].columnOrder]
})
hooks.columnsBeforeHeaderGroups.push(columnsBeforeHeaderGroups)
hooks.useMain.push(useMain)
}
useColumnOrder.pluginName = 'useColumnOrder'
function columnsBeforeHeaderGroups(columns, instance) {
const {
state: [{ columnOrder }],
} = instance
// If there is no order, return the normal columns
if (!columnOrder || !columnOrder.length) {
return columns
}
const columnOrderCopy = [...columnOrder]
// If there is an order, make a copy of the columns
const columnsCopy = [...columns]
// And make a new ordered array of the columns
const columnsInOrder = []
// Loop over the columns and place them in order into the new array
while (columnsCopy.length && columnOrderCopy.length) {
const targetColumnID = columnOrderCopy.shift()
const foundIndex = columnsCopy.findIndex(d => d.id === targetColumnID)
if (foundIndex > -1) {
columnsInOrder.push(columnsCopy.splice(foundIndex, 1)[0])
}
}
// If there are any columns left, add them to the end
return [...columnsInOrder, ...columnsCopy]
}
function useMain(instance) {
PropTypes.checkPropTypes(propTypes, instance, 'property', 'useColumnOrder')
const {
state: [, setState],
} = instance
const setColumnOrder = React.useCallback(
updater => {
return setState(old => {
return {
...old,
columnOrder:
typeof updater === 'function' ? updater(old.columnOrder) : updater,
}
}, actions.setColumnOrder)
},
[setState]
)
return {
...instance,
setColumnOrder,
}
}
+30 -46
View File
@@ -1,17 +1,11 @@
import { useMemo } from 'react'
import PropTypes from 'prop-types'
import {
getBy,
getFirstDefined,
setBy,
mergeProps,
applyPropHooks,
} from '../utils'
import { mergeProps, applyPropHooks, expandRows } from '../utils'
import { addActions, actions } from '../actions'
import { defaultState } from '../hooks/useTableState'
defaultState.expanded = {}
defaultState.expanded = []
addActions('toggleExpanded', 'useExpanded')
@@ -40,13 +34,24 @@ function useMain(instance) {
} = instance
const toggleExpandedByPath = (path, set) => {
const key = path.join('.')
return setState(old => {
const { expanded } = old
const existing = getBy(expanded, path)
set = getFirstDefined(set, existing ? undefined : true)
const exists = old.expanded.includes(key)
const shouldExist = typeof set !== 'undefined' ? set : !exists
let newExpanded = new Set(old.expanded)
if (!exists && shouldExist) {
newExpanded.add(key)
} else if (exists && !shouldExist) {
newExpanded.delete(key)
} else {
return old
}
return {
...old,
expanded: setBy(expanded, path, set),
expanded: [...newExpanded.values()],
}
}, actions.toggleExpanded)
}
@@ -76,35 +81,12 @@ function useMain(instance) {
if (process.env.NODE_ENV === 'development' && debug)
console.info('getExpandedRows')
const expandedRows = []
// Here we do some mutation, but it's the last stage in the
// immutable process so this is safe
const handleRow = row => {
row.isExpanded =
(row.original && row.original[manualExpandedKey]) ||
getBy(expanded, row.path)
expandedRows.push(row)
row.canExpand = row.subRows && !!row.subRows.length
if (
paginateExpandedRows &&
row.isExpanded &&
row.subRows &&
row.subRows.length
) {
row.subRows.forEach(handleRow)
}
return row
if (paginateExpandedRows) {
return expandRows(rows, { manualExpandedKey, expanded })
}
rows.forEach(handleRow)
return expandedRows
}, [debug, rows, manualExpandedKey, expanded, paginateExpandedRows])
return rows
}, [debug, paginateExpandedRows, rows, manualExpandedKey, expanded])
const expandedDepth = findExpandedDepth(expanded)
@@ -116,11 +98,13 @@ function useMain(instance) {
}
}
function findExpandedDepth(obj, depth = 1) {
return Object.values(obj).reduce((prev, curr) => {
if (typeof curr === 'object') {
return Math.max(prev, findExpandedDepth(curr, depth + 1))
}
return depth
}, 0)
function findExpandedDepth(expanded) {
let maxDepth = 0
expanded.forEach(key => {
const path = key.split('.')
maxDepth = Math.max(maxDepth, path.length)
})
return maxDepth
}
+8 -8
View File
@@ -33,7 +33,7 @@ function useMain(instance) {
const {
debug,
rows,
columns,
flatColumns,
filterTypes: userFilterTypes,
manualFilters,
disableFilters,
@@ -43,7 +43,7 @@ function useMain(instance) {
const preFilteredRows = rows
const setFilter = (id, updater) => {
const column = columns.find(d => d.id === id)
const column = flatColumns.find(d => d.id === id)
if (!column) {
throw new Error(`React-Table: Could not find a column with id: ${id}`)
@@ -85,7 +85,7 @@ function useMain(instance) {
// Filter out undefined values
Object.keys(newFilters).forEach(id => {
const newFilter = newFilters[id]
const column = columns.find(d => d.id === id)
const column = flatColumns.find(d => d.id === id)
const filterMethod = getFilterMethod(
column.filter,
userFilterTypes || {},
@@ -104,7 +104,7 @@ function useMain(instance) {
}, actions.setAllFilters)
}
columns.forEach(column => {
flatColumns.forEach(column => {
const { id, accessor, disableFilters: columnDisableFilters } = column
// Determine if a column is filterable
@@ -144,7 +144,7 @@ function useMain(instance) {
filteredRows = Object.entries(filters).reduce(
(filteredSoFar, [columnID, filterValue]) => {
// Find the filters column
const column = columns.find(d => d.id === columnID)
const column = flatColumns.find(d => d.id === columnID)
if (!column) {
return filteredSoFar
@@ -195,12 +195,12 @@ function useMain(instance) {
}
return filterRows(rows)
}, [manualFilters, filters, debug, rows, columns, userFilterTypes])
}, [manualFilters, filters, debug, rows, flatColumns, userFilterTypes])
React.useMemo(() => {
// Now that each filtered column has it's partially filtered rows,
// lets assign the final filtered rows to all of the other columns
const nonFilteredColumns = columns.filter(
const nonFilteredColumns = flatColumns.filter(
column => !Object.keys(filters).includes(column.id)
)
@@ -209,7 +209,7 @@ function useMain(instance) {
nonFilteredColumns.forEach(column => {
column.preFilteredRows = filteredRows
})
}, [columns, filteredRows, filters])
}, [filteredRows, filters, flatColumns])
return {
...instance,
+15 -16
View File
@@ -48,16 +48,16 @@ export const useGroupBy = hooks => {
useGroupBy.pluginName = 'useGroupBy'
function columnsBeforeHeaderGroups(columns, { state: [{ groupBy }] }) {
function columnsBeforeHeaderGroups(flatColumns, { state: [{ groupBy }] }) {
// Sort grouped columns to the start of the column list
// before the headers are built
const groupByColumns = groupBy.map(g => columns.find(col => col.id === g))
const nonGroupByColumns = columns.filter(col => !groupBy.includes(col.id))
const groupByColumns = groupBy.map(g => flatColumns.find(col => col.id === g))
const nonGroupByColumns = flatColumns.filter(col => !groupBy.includes(col.id))
// If a groupByBoundary column is found, place the groupBy's after it
const groupByBoundaryColumnIndex =
columns.findIndex(column => column.groupByBoundary) + 1
flatColumns.findIndex(column => column.groupByBoundary) + 1
return [
...nonGroupByColumns.slice(0, groupByBoundaryColumnIndex),
@@ -72,8 +72,8 @@ function useMain(instance) {
const {
debug,
rows,
columns,
headers,
flatColumns,
flatHeaders,
groupByFn = defaultGroupByFn,
manualGroupBy,
disableGrouping,
@@ -83,9 +83,9 @@ function useMain(instance) {
state: [{ groupBy }, setState],
} = instance
ensurePluginOrder(plugins, [], 'useGroupBy', ['useExpanded'])
ensurePluginOrder(plugins, [], 'useGroupBy', ['useSortBy', 'useExpanded'])
columns.forEach(column => {
flatColumns.forEach(column => {
const { id, accessor, disableGrouping: columnDisableGrouping } = column
column.isGrouped = groupBy.includes(id)
column.groupedIndex = groupBy.indexOf(id)
@@ -124,16 +124,15 @@ function useMain(instance) {
hooks.getGroupByToggleProps = []
//
;[...columns, ...headers].forEach(column => {
const { canGroupBy } = column
column.getGroupByToggleProps = props => {
flatHeaders.forEach(header => {
const { canGroupBy } = header
header.getGroupByToggleProps = props => {
return mergeProps(
{
onClick: canGroupBy
? e => {
e.persist()
column.toggleGroupBy()
header.toggleGroupBy()
}
: undefined,
style: {
@@ -141,7 +140,7 @@ function useMain(instance) {
},
title: 'Toggle GroupBy',
},
applyPropHooks(instance.hooks.getGroupByToggleProps, column, instance),
applyPropHooks(instance.hooks.getGroupByToggleProps, header, instance),
props
)
}
@@ -173,7 +172,7 @@ function useMain(instance) {
const aggregateRowsToValues = (rows, isSourceRows) => {
const values = {}
columns.forEach(column => {
flatColumns.forEach(column => {
// Don't aggregate columns that are in the groupBy
if (groupBy.includes(column.id)) {
values[column.id] = rows[0] ? rows[0].values[column.id] : null
@@ -266,7 +265,7 @@ function useMain(instance) {
groupBy,
debug,
rows,
columns,
flatColumns,
userAggregations,
groupByFn,
])
+66 -55
View File
@@ -4,7 +4,7 @@ import PropTypes from 'prop-types'
//
import { addActions, actions } from '../actions'
import { defaultState } from '../hooks/useTableState'
import { ensurePluginOrder } from '../utils'
import { ensurePluginOrder, safeUseLayoutEffect, expandRows } from '../utils'
defaultState.pageSize = 10
defaultState.pageIndex = 0
@@ -17,12 +17,6 @@ const propTypes = {
paginateExpandedRows: PropTypes.bool,
}
// SSR has issues with useLayoutEffect still, so use useEffect during SSR
let useLayoutEffect =
typeof window !== 'undefined' && process.env.NODE_ENV === 'production'
? React.useLayoutEffect
: React.useEffect
export const usePagination = hooks => {
hooks.useMain.push(useMain)
}
@@ -37,11 +31,15 @@ function useMain(instance) {
rows,
manualPagination,
disablePageResetOnDataChange,
manualExpandedKey = 'expanded',
debug,
plugins,
pageCount: userPageCount,
paginateExpandedRows = true,
state: [{ pageSize, pageIndex, filters, groupBy, sortBy }, setState],
state: [
{ pageSize, pageIndex, filters, groupBy, sortBy, expanded },
setState,
],
} = instance
ensurePluginOrder(
@@ -55,8 +53,15 @@ function useMain(instance) {
const isPageIndexMountedRef = React.useRef()
useLayoutEffect(() => {
if (isPageIndexMountedRef.current && !disablePageResetOnDataChange) {
// Bypass any effects from firing when this changes
const disablePageResetOnDataChangeRef = React.useRef()
disablePageResetOnDataChangeRef.current = disablePageResetOnDataChange
safeUseLayoutEffect(() => {
if (
isPageIndexMountedRef.current &&
!disablePageResetOnDataChangeRef.current
) {
setState(
old => ({
...old,
@@ -66,7 +71,7 @@ function useMain(instance) {
)
}
isPageIndexMountedRef.current = true
}, [setState, rowDep, filters, groupBy, sortBy, disablePageResetOnDataChange])
}, [setState, rowDep, filters, groupBy, sortBy])
const pageCount = manualPagination
? userPageCount
@@ -96,57 +101,63 @@ function useMain(instance) {
return page
}
const expandedPage = []
const handleRow = row => {
expandedPage.push(row)
if (row.subRows && row.subRows.length && row.isExpanded) {
row.subRows.forEach(handleRow)
}
}
page.forEach(handleRow)
return expandedPage
}, [debug, manualPagination, pageIndex, pageSize, paginateExpandedRows, rows])
return expandRows(page, { manualExpandedKey, expanded })
}, [
debug,
expanded,
manualExpandedKey,
manualPagination,
pageIndex,
pageSize,
paginateExpandedRows,
rows,
])
const canPreviousPage = pageIndex > 0
const canNextPage = pageCount === -1 || pageIndex < pageCount - 1
const gotoPage = pageIndex => {
if (process.env.NODE_ENV === 'development' && debug)
console.info('gotoPage')
return setState(old => {
if (pageIndex < 0 || pageIndex > pageCount - 1) {
return old
}
return {
...old,
pageIndex,
}
}, actions.pageChange)
}
const gotoPage = React.useCallback(
updater => {
if (process.env.NODE_ENV === 'development' && debug)
console.info('gotoPage')
return setState(old => {
const newPageIndex =
typeof updater === 'function' ? updater(old.pageIndex) : updater
const previousPage = () => {
return gotoPage(pageIndex - 1)
}
if (newPageIndex < 0 || newPageIndex > pageCount - 1) {
return old
}
return {
...old,
pageIndex: newPageIndex,
}
}, actions.pageChange)
},
[debug, pageCount, setState]
)
const nextPage = () => {
return gotoPage(pageIndex + 1)
}
const previousPage = React.useCallback(() => {
return gotoPage(old => old - 1)
}, [gotoPage])
const setPageSize = pageSize => {
setState(old => {
const topRowIndex = old.pageSize * old.pageIndex
const pageIndex = Math.floor(topRowIndex / pageSize)
return {
...old,
pageIndex,
pageSize,
}
}, actions.pageSizeChange)
}
const nextPage = React.useCallback(() => {
return gotoPage(old => old + 1)
}, [gotoPage])
const setPageSize = React.useCallback(
pageSize => {
setState(old => {
const topRowIndex = old.pageSize * old.pageIndex
const pageIndex = Math.floor(topRowIndex / pageSize)
return {
...old,
pageIndex,
pageSize,
}
}, actions.pageSizeChange)
},
[setState]
)
return {
...instance,
+8 -4
View File
@@ -38,7 +38,7 @@ function useMain(instance) {
[]
)
const isAllRowsSelected = rowPaths.length === selectedRows.length
const isAllRowsSelected = rowPaths.length > 0 && rowPaths.length === selectedRows.length
const toggleRowSelectedAll = set => {
setState(old => {
@@ -70,6 +70,7 @@ function useMain(instance) {
const toggleRowSelected = (path, set) => {
const key = path.join('.')
const childRowPrefixKey = [key, '.'].join('')
return setState(old => {
// Join the paths of deep rows
@@ -81,11 +82,15 @@ function useMain(instance) {
if (!exists && shouldExist) {
rowPaths.forEach(rowPath => {
if (rowPath.startsWith(key)) newSelectedRows.add(rowPath)
if (rowPath === key || rowPath.startsWith(childRowPrefixKey)) {
newSelectedRows.add(rowPath)
}
})
} else if (exists && !shouldExist) {
rowPaths.forEach(rowPath => {
if (rowPath.startsWith(key)) newSelectedRows.delete(rowPath)
if (rowPath === key || rowPath.startsWith(childRowPrefixKey)) {
newSelectedRows.delete(rowPath)
}
})
} else {
return old
@@ -128,7 +133,6 @@ function useMain(instance) {
)
row.toggleRowSelected = set => {
set = typeof set !== 'undefined' ? set : !row.isSelected
console.log(subRowPaths)
subRowPaths.forEach(path => {
toggleRowSelected(path, set)
})
+35 -9
View File
@@ -1,7 +1,7 @@
import React from 'react'
import PropTypes from 'prop-types'
import { ensurePluginOrder } from '../utils'
import { ensurePluginOrder, defaultColumn } from '../utils'
import { addActions, actions } from '../actions'
import { defaultState } from '../hooks/useTableState'
import * as sortTypes from '../sortTypes'
@@ -14,6 +14,8 @@ import {
} from '../utils'
defaultState.sortBy = []
defaultColumn.sortType = 'alphanumeric'
defaultColumn.sortDescFirst = false
addActions('sortByChange')
@@ -49,7 +51,7 @@ function useMain(instance) {
const {
debug,
rows,
columns,
flatColumns,
orderByFn = defaultOrderByFn,
sortTypes: userSortTypes,
manualSorting,
@@ -75,7 +77,7 @@ function useMain(instance) {
const { sortBy } = old
// Find the column for this columnID
const column = columns.find(d => d.id === columnID)
const column = flatColumns.find(d => d.id === columnID)
const { sortDescFirst } = column
// Find any existing sortBy for this column
@@ -174,6 +176,17 @@ function useMain(instance) {
if (column.canSort) {
column.toggleSortBy = (desc, multi) =>
toggleSortBy(column.id, desc, multi)
column.clearSorting = () => {
return setState(old => {
const { sortBy } = old
const newSortBy = sortBy.filter(d => d.id !== column.id)
return {
...old,
sortBy: newSortBy,
}
}, actions.sortByChange)
}
}
column.getSortByToggleProps = props => {
@@ -213,7 +226,7 @@ function useMain(instance) {
// Filter out sortBys that correspond to non existing columns
const availableSortBy = sortBy.filter(sort =>
columns.find(col => col.id === sort.id)
flatColumns.find(col => col.id === sort.id)
)
const sortData = rows => {
@@ -224,7 +237,7 @@ function useMain(instance) {
rows,
availableSortBy.map(sort => {
// Support custom sorting methods for each column
const column = columns.find(d => d.id === sort.id)
const column = flatColumns.find(d => d.id === sort.id)
if (!column) {
throw new Error(
@@ -244,8 +257,13 @@ function useMain(instance) {
const sortMethod =
isFunction(sortType) ||
(userSortTypes || {})[sortType] ||
sortTypes[sortType] ||
sortTypes.alphanumeric
sortTypes[sortType]
if (!sortMethod) {
throw new Error(
`React-Table: Could not find a valid sortType of '${sortType}' for column '${sort.id}'.`
)
}
// Return the correct sortFn.
// This function should always return in ascending order
@@ -254,7 +272,7 @@ function useMain(instance) {
// Map the directions
availableSortBy.map(sort => {
// Detect and use the sortInverted option
const column = columns.find(d => d.id === sort.id)
const column = flatColumns.find(d => d.id === sort.id)
if (column && column.sortInverted) {
return sort.desc
@@ -279,7 +297,15 @@ function useMain(instance) {
console.timeEnd('getSortedRows')
return sortData(rows)
}, [manualSorting, sortBy, debug, columns, rows, orderByFn, userSortTypes])
}, [
manualSorting,
sortBy,
debug,
rows,
flatColumns,
orderByFn,
userSortTypes,
])
return {
...instance,
+103 -44
View File
@@ -1,5 +1,16 @@
import React from 'react'
export const defaultColumn = {
Cell: ({ cell: { value = '' } }) => String(value),
show: true,
}
// 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
// Find the depth of the columns
export function findMaxDepth(columns, depth = 0) {
return columns.reduce((prev, curr) => {
@@ -10,9 +21,15 @@ export function findMaxDepth(columns, depth = 0) {
}, 0)
}
export function decorateColumn(column, defaultColumn, parent, depth, index) {
// Apply the defaultColumn
column = { ...defaultColumn, ...column }
export function decorateColumn(
column,
userDefaultColumn,
parent,
depth,
index
) {
// Apply the userDefaultColumn
column = { ...defaultColumn, ...userDefaultColumn, ...column }
// First check for string accessor
let { id, accessor, Header } = column
@@ -38,10 +55,10 @@ export function decorateColumn(column, defaultColumn, parent, depth, index) {
}
column = {
// Make sure there is a fallback header, just in case
Header: () => null,
Cell: ({ cell: { value = '' } }) => value,
show: true,
...column,
// Materialize and override this stuff
id,
accessor,
parent,
@@ -69,42 +86,51 @@ export function decorateColumnTree(columns, defaultColumn, parent, depth = 0) {
}
// Build the header groups from the bottom up
export function makeHeaderGroups(columns, maxDepth, defaultColumn) {
export function makeHeaderGroups(flatColumns, defaultColumn) {
const headerGroups = []
const buildGroup = (columns, depth = 0) => {
// Build each header group from the bottom up
const buildGroup = (columns, depth) => {
const headerGroup = {
headers: [],
}
const parentColumns = []
// Do any of these columns have parents?
const hasParents = columns.some(col => col.parent)
columns.forEach(column => {
// Are we the first column in this group?
const isFirst = !parentColumns.length
// What is the latest (last) parent column?
let latestParentColumn = [...parentColumns].reverse()[0]
// If the column has a parent, add it if necessary
if (column.parent) {
const similarParentColumns = parentColumns.filter(
d => d.originalID === column.parent.id
)
if (isFirst || latestParentColumn.originalID !== column.parent.id) {
parentColumns.push({
...column.parent,
originalID: column.parent.id,
id: [column.parent.id, parentColumns.length].join('_'),
id: [column.parent.id, similarParentColumns.length].join('_'),
})
}
} else if (hasParents) {
// If other columns have parents, add a place holder if necessary
// If other columns have parents, we'll need to add a place holder if necessary
const originalID = [column.id, 'placeholder'].join('_')
const similarParentColumns = parentColumns.filter(
d => d.originalID === originalID
)
const placeholderColumn = decorateColumn(
{
originalID: [column.id, 'placeholder', maxDepth - depth].join('_'),
id: [
column.id,
'placeholder',
maxDepth - depth,
parentColumns.length,
].join('_'),
originalID,
id: [column.id, 'placeholder', similarParentColumns.length].join(
'_'
),
},
defaultColumn
)
@@ -131,23 +157,22 @@ export function makeHeaderGroups(columns, maxDepth, defaultColumn) {
0
)
: 1 // Leaf node columns take up at least one count
headerGroup.headers.push(column)
})
headerGroups.push(headerGroup)
if (parentColumns.length) {
buildGroup(parentColumns)
buildGroup(parentColumns, depth + 1)
}
}
buildGroup(columns)
buildGroup(flatColumns, 0)
return headerGroups.reverse()
}
export function determineColumnVisibility(instance) {
export function determineHeaderVisibility(instance) {
const { headers } = instance
const handleColumn = (column, parentVisible) => {
@@ -156,14 +181,28 @@ export function determineColumnVisibility(instance) {
? column.show(instance)
: !!column.show
: false
if (column.columns && column.columns.length) {
column.columns.forEach(subColumn =>
handleColumn(subColumn, column.isVisible)
let totalVisibleHeaderCount = 0
if (column.headers && column.headers.length) {
column.headers.forEach(
subColumn =>
(totalVisibleHeaderCount += handleColumn(subColumn, column.isVisible))
)
} else {
totalVisibleHeaderCount = column.isVisible ? 1 : 0
}
column.totalVisibleHeaderCount = totalVisibleHeaderCount
return totalVisibleHeaderCount
}
headers.forEach(subColumn => handleColumn(subColumn, true))
let totalVisibleHeaderCount = 0
headers.forEach(
subHeader => (totalVisibleHeaderCount += handleColumn(subHeader, true))
)
}
export function getBy(obj, path, def) {
@@ -213,22 +252,6 @@ export function defaultGroupByFn(rows, columnID) {
}, {})
}
export function setBy(obj = {}, path, value) {
path = makePathArray(path)
const recurse = (obj, depth = 0) => {
const key = path[depth]
const target = typeof obj[key] !== 'object' ? {} : obj[key]
const subValue =
depth === path.length - 1 ? value : recurse(target, depth + 1)
return {
...obj,
[key]: subValue,
}
}
return recurse(obj)
}
export function getElementDimensions(element) {
const rect = element.getBoundingClientRect()
const style = window.getComputedStyle(element)
@@ -255,10 +278,22 @@ export function getElementDimensions(element) {
}
export function flexRender(Comp, props) {
if (typeof Comp === 'function' || typeof Comp === 'object') {
return <Comp {...props} />
}
return Comp
return isReactComponent(Comp) ? <Comp {...props} /> : Comp
}
function isClassComponent(component) {
return (
typeof component === 'function' &&
!!Object.getPrototypeOf(component).isReactComponent
)
}
function isFunctionComponent(component) {
return typeof component === 'function'
}
function isReactComponent(component) {
return isClassComponent(component) || isFunctionComponent(component)
}
export const mergeProps = (...groups) => {
@@ -363,6 +398,30 @@ This usually means you need to need to name your plugin hook by setting the 'plu
})
}
export function expandRows(rows, { manualExpandedKey, expanded }) {
const expandedRows = []
const handleRow = row => {
const key = row.path.join('.')
row.isExpanded =
(row.original && row.original[manualExpandedKey]) ||
expanded.includes(key)
row.canExpand = row.subRows && !!row.subRows.length
expandedRows.push(row)
if (row.subRows && row.subRows.length && row.isExpanded) {
row.subRows.forEach(handleRow)
}
}
rows.forEach(handleRow)
return expandedRows
}
//
function makePathArray(obj) {
+6 -6
View File
@@ -2956,16 +2956,16 @@ eslint-scope@^4.0.3:
estraverse "^4.1.1"
eslint-utils@^1.3.0, 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.2"
resolved "https://registry.yarnpkg.com/eslint-utils/-/eslint-utils-1.4.2.tgz#166a5180ef6ab7eb462f162fd0e6f2463d7309ab"
integrity sha512-eAZS2sEUMlIeCjBeubdj45dmBHQwPHWyBcT1VSYB7o9x9WRRqKxyUoiXlRjyAwzN7YEzHJlYg0NmzDRWx6GP4Q==
dependencies:
eslint-visitor-keys "^1.0.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==
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.x, eslint@^5.6.0:
version "5.16.0"