mirror of
https://github.com/gosticks/react-table.git
synced 2026-08-19 16:30:21 +00:00
Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cbb18368b2 | ||
|
|
4842bc061d | ||
|
|
0477ef26ca | ||
|
|
82734fc898 | ||
|
|
bbfc6428b7 | ||
|
|
280ef16a75 | ||
|
|
7db7d59b3d | ||
|
|
e43968c684 | ||
|
|
e5c04614c1 | ||
|
|
0ef0bc4126 | ||
|
|
ef67b15c07 | ||
|
|
d248be8877 | ||
|
|
ea0799763d | ||
|
|
98fffc3819 | ||
|
|
de7f5c9385 | ||
|
|
69e13b87c3 |
@@ -44,6 +44,7 @@ Hooks for building **lightweight, fast and extendable datagrids** for React
|
||||
- Column Ordering
|
||||
- Animatable
|
||||
- Virtualizable
|
||||
- Resizable
|
||||
- Server-side/controlled data/state
|
||||
- Extensible via hook-based plugin system
|
||||
- <a href="https://medium.com/@tannerlinsley/why-i-wrote-react-table-and-the-problems-it-has-solved-for-nozzle-others-445c4e93d4a8#.axza4ixba" target="\_parent">"Why I wrote React Table and the problems it has solved for Nozzle.io"</a> by Tanner Linsley
|
||||
|
||||
+121
-105
@@ -19,8 +19,7 @@ React Table is essentially a compatible collection of **custom React hooks**:
|
||||
- Layout Hooks
|
||||
- [`useBlockLayout`](#useBlockLayout)
|
||||
- [`useAbsoluteLayout`](#useAbsoluteLayout)
|
||||
- Utility Hooks
|
||||
- [`useTableState`](#useTableState)
|
||||
- [`useResizeColumns`](#useResizeColumns)
|
||||
- 3rd Party Plugin Hooks
|
||||
- Want your custom plugin hook listed here? [Submit a PR!](https://github.com/tannerlinsley/react-table/compare)
|
||||
|
||||
@@ -53,11 +52,11 @@ const instance = useTable(
|
||||
|
||||
This multi-stage process is the secret sauce that allows React Table plugin hooks to work together and compose nicely, while not stepping on each others toes.
|
||||
|
||||
To dive deeper into plugins, see [Plugins](TODO) and the [Plugin Guide](TODO)
|
||||
To dive deeper into plugins, see Plugins](TODO) and the [Plugin Guide
|
||||
|
||||
### Plugin Hook Order & Consistency
|
||||
|
||||
The order and usage of plugin hooks must follow [The Laws of Hooks](TODO), just like any other custom hook. They must always be unconditionally called in the same order.
|
||||
The order and usage of plugin hooks must follow The Laws of Hooks, just like any other custom hook. They must always be unconditionally called in the same order.
|
||||
|
||||
> **NOTE: In the event that you want to programmatically enable or disable plugin hooks, most of them provide options to disable their functionality, eg. `options.disableSorting`**
|
||||
|
||||
@@ -84,12 +83,19 @@ The following options are supported via the main options object passed to `useTa
|
||||
- Required
|
||||
- Must be **memoized**
|
||||
- The data array that you want to display on the table.
|
||||
- `state: TableStateTuple[stateObject, stateUpdater]`
|
||||
- `initialState: Object`
|
||||
- Optional
|
||||
- Must be **memoized** table state tuple. See [`useTableState`](#usetablestate) for more information.
|
||||
- The state/updater pair for the table instance. You would want to override this if you plan on controlling or hoisting table state into your own code.
|
||||
- Defaults to using an internal `useTableState()` instance if not defined.
|
||||
- See [Controlling and Hoisting Table State](#controlling-and-hoisting-table-state)
|
||||
- The initial state object for the table.
|
||||
- Upon table initialization, this object is **merged over the table's `defaultState` object** (eg. `{...defaultState, ...initialState}`) that React Table and its hooks use to register default state to produce the final initial state object passed to the `React.useState` hook internally.
|
||||
- `state: Object`
|
||||
- Optional
|
||||
- Must be **memoized**
|
||||
- When either the internal `state` or this `state` object change, this object is **always merged over the internal table state** (eg. `{...state, ...overrides}`) to produce the final state object that is then passed to the `useTable` options.
|
||||
- `reducer: Function(oldState, newState) => finalState`
|
||||
- Optional
|
||||
- Inspired by Kent C. Dodd's [State Reducer Pattern](https://kentcdodds.com/blog/the-state-reducer-pattern-with-react-hooks)
|
||||
- With every `setState` call to the table's internal `React.useState` instance, this reducer is called and is allowed to modify the final state object for updating.
|
||||
- It is passed the `oldState`, the `newState`, and when provided, an optional action `type`.
|
||||
- `defaultColumn: Object`
|
||||
- Optional
|
||||
- Defaults to `{}`
|
||||
@@ -119,7 +125,7 @@ The following options are supported via the main options object passed to `useTa
|
||||
- A flag to turn on debug mode.
|
||||
- Defaults to `false`
|
||||
|
||||
### `column` Options
|
||||
### Column Options
|
||||
|
||||
The following options are supported on any column object you can pass to `columns`.
|
||||
|
||||
@@ -174,6 +180,19 @@ 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`
|
||||
|
||||
- `state: Object`
|
||||
- **Memoized** - This object reference will not change unless either the internal state or the `state` overrides option provided change.
|
||||
- This is the final state object of the table, which is the product of the `initialState`, internal state, optional `state` overrides option and the `reducer` option (if applicable).
|
||||
- `setState: Function(updater, type) => void`
|
||||
- **Memoized** - This function reference will not change unless the internal state `reducer` is changed
|
||||
- This function is used both internally by React Table, and optionally by you (the developer) to update the table state programmatically.
|
||||
- `updater: Function`
|
||||
- This parameter is identical to the `setState` API exposed by `React.useState`.
|
||||
- If a function is passed, that function will be called with the previous state and is expected to return a new version of the state.
|
||||
- If a value is passed, it will replace the state entirely.
|
||||
- `type: String`
|
||||
- Optional
|
||||
- The action type corresponding to what action being taken against the state.
|
||||
- `columns: 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
|
||||
@@ -208,10 +227,6 @@ The following properties are available on the table instance returned from `useT
|
||||
- **Required**
|
||||
- This function is responsible for lazily preparing a row for rendering. Any row that you intend to render in your table needs to be passed to this function **before every render**.
|
||||
- **Why?** Since table data could potentially be very large, it can become very expensive to compute all of the necessary state for every row to be rendered regardless if it actually is rendered or not (for example if you are paginating or virtualizing the rows, you may only have a few rows visible at any given moment). This function allows only the rows you intend to display to be computed and prepped with the correct state.
|
||||
- `rowPaths: Array<string>`
|
||||
- An array containing the stringified `path` of every original row in the table. eg. If a row has a path of `[0, 3, 2]`, its stringified path would be `0.3.2`.
|
||||
- This array is used by many plugin hooks including `useRowSelect` to manage row selection state
|
||||
- Only rows that exist on the original `data` array will have a path in this array. Rows created by `useGroupBy`'s aggregations and grouping are not included in this array, since they do not reference an original data row.
|
||||
- `flatRows: Array<Row>`
|
||||
- An array of all rows, including subRows which have been flattened into the order in which they were detected (depth first)
|
||||
- This can be helpful in calculating total row counts that must include subRows
|
||||
@@ -336,9 +351,11 @@ The following additional properties are available on every `Cell` object returne
|
||||
|
||||
The following options are supported via the main options object passed to `useTable(options)`
|
||||
|
||||
- `state[0].sortBy: Array<Object<id: columnID, desc: Bool>>`
|
||||
- `state.sortBy: Array<Object<id: columnID, desc: Bool>>`
|
||||
- Must be **memoized**
|
||||
- An array of sorting objects. If there is more than one object in the array, multi-sorting will be enabled. Each sorting object should contain an `id` key with the corresponding column ID to sort by. An optional `desc` key may be set to true or false to indicated ascending or descending sorting for that column. This information is stored in state since the table is allowed to manipulate the filter through user interaction.
|
||||
- `initialState.sortBy`
|
||||
- Identical to the `state.sortBy` option above
|
||||
- `manualSorting: Bool`
|
||||
- Enables sorting detection functionality, but does not automatically perform row sorting. Turn this on if you wish to implement your own sorting outside of the table (eg. server-side or manual row grouping/nesting)
|
||||
- `disableSorting: Bool`
|
||||
@@ -356,12 +373,12 @@ The following options are supported via the main options object passed to `useTa
|
||||
- If true, the un-sorted state will not be available to multi-sorted columns.
|
||||
- `orderByFn: Function`
|
||||
- Must be **memoized**
|
||||
- Defaults to the built-in [default orderBy function](TODO)
|
||||
- Defaults to the built-in default orderBy function
|
||||
- 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>`
|
||||
- Must be **memoized**
|
||||
- Allows overriding or adding additional sort types for columns to use. If a column's sort type isn't found on this object, it will default to using the [built-in sort types](TODO).
|
||||
- For more information on sort types, see [Sorting](TODO)
|
||||
- Allows overriding or adding additional sort types for columns to use. If a column's sort type isn't found on this object, it will default to using the built-in sort types.
|
||||
- For more information on sort types, see Sorting
|
||||
|
||||
### Column Options
|
||||
|
||||
@@ -383,11 +400,11 @@ 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**
|
||||
- String options: `basic`, `datetime`, `alphanumeric`. Defaults to [`alphanumeric`](TODO).
|
||||
- String options: `basic`, `datetime`, `alphanumeric`. Defaults to `alphanumeric`.
|
||||
- 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 a `function` is passed, it will be used.
|
||||
- For more information on sort types, see [Sorting](TODO)
|
||||
- For more information on sort types, see Sorting
|
||||
|
||||
### Instance Properties
|
||||
|
||||
@@ -443,16 +460,18 @@ The following properties are available on every `Column` object returned by the
|
||||
|
||||
The following options are supported via the main options object passed to `useTable(options)`
|
||||
|
||||
- `state[0].filters: Object<columnID: filterValue>`
|
||||
- `state.filters: Object<columnID: filterValue>`
|
||||
- Must be **memoized**
|
||||
- An object of columnID's and their corresponding filter values. This information is stored in state since the table is allowed to manipulate the filter through user interaction.
|
||||
- `initialState.filters`
|
||||
- Identical to the `state.filters` option above
|
||||
- `defaultFilter: String | Function`
|
||||
- If a **function** is passed, it must be **memoized**
|
||||
- Defaults to [`text`](TODO)
|
||||
- Defaults to `text`
|
||||
- The function (or resolved function from the string) will be used as the default/fallback filter method for every column that has filtering enabled.
|
||||
- If a `string` is passed, the function with that name located on the `filterTypes` option object will be used.
|
||||
- If a `function` is passed, it will be used.
|
||||
- For more information on filter types, see [Filtering](TODO)
|
||||
- For more information on filter types, see Filtering
|
||||
- `manualFilters: Bool`
|
||||
- Enables filter detection functionality, but does not automatically perform row filtering.
|
||||
- Turn this on if you wish to implement your own row filter outside of the table (eg. server-side or manual row grouping/nesting)
|
||||
@@ -460,8 +479,8 @@ The following options are supported via the main options object passed to `useTa
|
||||
- Disables filtering for every column in the entire table.
|
||||
- `filterTypes: Object<filterKey: filterType>`
|
||||
- Must be **memoized**
|
||||
- Allows overriding or adding additional filter types for columns to use. If a column's filter type isn't found on this object, it will default to using the [built-in filter types](TODO).
|
||||
- For more information on filter types, see [Filtering](TODO)
|
||||
- Allows overriding or adding additional filter types for columns to use. If a column's filter type isn't found on this object, it will default to using the built-in filter types.
|
||||
- For more information on filter types, see Filtering
|
||||
|
||||
### Column Options
|
||||
|
||||
@@ -477,11 +496,11 @@ The following options are supported on any `Column` object passed to the `column
|
||||
- If set to `true`, will disable filtering for this column
|
||||
- `filter: String | Function`
|
||||
- Optional
|
||||
- Defaults to [`text`](TODO)
|
||||
- Defaults to `text`
|
||||
- The resolved function from the this string/function will be used to filter the this column's data.
|
||||
- If a `string` is passed, the function with that name located on either the custom `filterTypes` option or the built-in filtering types object will be used. If
|
||||
- If a `function` is passed, it will be used directly.
|
||||
- For more information on filter types, see [Filtering](TODO)
|
||||
- For more information on filter types, see Filtering
|
||||
- If a **function** is passed, it must be **memoized**
|
||||
|
||||
### Instance Properties
|
||||
@@ -508,9 +527,12 @@ The following properties are available on every `Column` object returned by the
|
||||
- An column-level function used to update the filter value for this column
|
||||
- `filterValue: any`
|
||||
- The current filter value for this column, resolved from the table state's `filters` object
|
||||
- `preFilteredColumnRows: Array<row>`
|
||||
- `preFilteredRows: Array<row>`
|
||||
- The array of rows that were originally passed to this columns filter **before** they were filtered.
|
||||
- This array of rows can be useful if building faceted filter options.
|
||||
- `filteredRows: Array<row>`
|
||||
- The resulting array of rows received from this columns filter **after** they were filtered.
|
||||
- This array of rows can be useful if building faceted filter options.
|
||||
|
||||
### Example
|
||||
|
||||
@@ -531,9 +553,11 @@ The following properties are available on every `Column` object returned by the
|
||||
|
||||
The following options are supported via the main options object passed to `useTable(options)`
|
||||
|
||||
- `state[0].groupBy: Array<String>`
|
||||
- `state.groupBy: Array<String>`
|
||||
- Must be **memoized**
|
||||
- An array of groupBy ID strings, controlling which columns are used to calculate row grouping and aggregation. This information is stored in state since the table is allowed to manipulate the groupBy through user interaction.
|
||||
- `initialState.groupBy`
|
||||
- Identical to the `state.groupBy` option above
|
||||
- `manualGroupBy: Bool`
|
||||
- Enables groupBy detection and functionality, but does not automatically perform row grouping.
|
||||
- Turn this on if you wish to implement your own row grouping outside of the table (eg. server-side or manual row grouping/nesting)
|
||||
@@ -541,10 +565,10 @@ The following options are supported via the main options object passed to `useTa
|
||||
- Disables groupBy for the entire table.
|
||||
- `aggregations: Object<aggregationKey: aggregationFn>`
|
||||
- Must be **memoized**
|
||||
- Allows overriding or adding additional aggregation functions for use when grouping/aggregating row values. If an aggregation key isn't found on this object, it will default to using the [built-in aggregation functions](TODO)
|
||||
- Allows overriding or adding additional aggregation functions for use when grouping/aggregating row values. If an aggregation key isn't found on this object, it will default to using the built-in aggregation functions
|
||||
- `groupByFn: Function`
|
||||
- Must be **memoized**
|
||||
- Defaults to [`defaultGroupByFn`](TODO)
|
||||
- Defaults to `defaultGroupByFn`
|
||||
- This function is responsible for grouping rows based on the `state.groupBy` keys provided. It's very rare you would need to customize this function.
|
||||
|
||||
### Column Options
|
||||
@@ -641,13 +665,15 @@ The following additional properties are available on every `Cell` object returne
|
||||
|
||||
The following options are supported via the main options object passed to `useTable(options)`
|
||||
|
||||
- `state[0].expanded: Array<pathKey: String>`
|
||||
- `state.expanded: Array<pathKey: String>`
|
||||
- Optional
|
||||
- Must be **memoized**
|
||||
- An array of expanded path keys.
|
||||
- If a row's path key (`row.path.join('.')`) is present in this array, that row will have an expanded state. For example, if `['3']` was passed as the `expanded` state, the **4th row in the original data array** would be expanded.
|
||||
- For nested expansion, you may **join the row path with a `.`** to expand sub rows. For example, if `['3', '3.5']` was passed as the `expanded` state, then the **6th subRow of the 4th row and also the 4th row of the original data array** would be expanded.
|
||||
- This information is stored in state since the table is allowed to manipulate the filter through user interaction.
|
||||
- `initialState.expanded`
|
||||
- Identical to the `state.expanded` option above
|
||||
- `getSubRows: Function(row, relativeIndex) => Rows[]`
|
||||
- Optional
|
||||
- See the [useTable hook](#table-options) for more details
|
||||
@@ -655,6 +681,11 @@ The following options are supported via the main options object passed to `useTa
|
||||
- Optional
|
||||
- Defaults to `expanded`
|
||||
- This string is used as the key to detect manual expanded state on any given row. For example, if a raw data row like `{ name: 'Tanner Linsley', friends: [...], expanded: true}` was detected, it would always be expanded, regardless of state.
|
||||
- `expandSubRows: Bool`
|
||||
- Optional
|
||||
- Defaults to `true`
|
||||
- If set to `true`, expanded rows are rendered along with normal rows.
|
||||
- If set to `false`, expanded rows will only be available through their parent row. This could be useful if you are implementing a custom expanded row view.
|
||||
|
||||
### Instance Properties
|
||||
|
||||
@@ -683,7 +714,7 @@ The following additional properties are available on every `row` object returned
|
||||
- Plugin Hook
|
||||
- Optional
|
||||
|
||||
`usePagination` is the hook that implements **row pagination**. It can be used for both client-side pagination or server-side pagination. For more information on pagination, see [Pagination](TODO)
|
||||
`usePagination` is the hook that implements **row pagination**. It can be used for both client-side pagination or server-side pagination. For more information on pagination, see Pagination
|
||||
|
||||
> **NOTE** Some server-side pagination implementations do not use page index and instead use **token based pagination**! If that's the case, please use the `useTokenPagination` plugin instead.
|
||||
|
||||
@@ -691,14 +722,18 @@ The following additional properties are available on every `row` object returned
|
||||
|
||||
The following options are supported via the main options object passed to `useTable(options)`
|
||||
|
||||
- `state[0].pageSize: Int`
|
||||
- `state.pageSize: Int`
|
||||
- **Required**
|
||||
- Defaults to `10`
|
||||
- Determines the amount of rows on any given page
|
||||
- `state[0].pageIndex: Int`
|
||||
- `initialState.pageSize`
|
||||
- Identical to the `state.pageSize` option above
|
||||
- `state.pageIndex: Int`
|
||||
- **Required**
|
||||
- Defaults to `0`
|
||||
- The index of the page that should be displayed via the `page` instance value
|
||||
- `initialState.pageIndex`
|
||||
- Identical to the `state.pageIndex` option above
|
||||
- `pageCount: Int`
|
||||
- **Required if `manualPagination` is set to `true`**
|
||||
- If `manualPagination` is `true`, then this value used to determine the amount of pages available. This amount is then used to materialize the `pageOptions` and also compute the `canNextPage` values on the table instance.
|
||||
@@ -763,7 +798,7 @@ The following values are provided to the table `instance`:
|
||||
- Plugin Hook
|
||||
- Optional
|
||||
|
||||
`useTokenPagination` is the hook that **aids in implementing row pagination using tokens**. It is useful for server-side pagination implementations that use **tokens** instead of page index. For more information on pagination, see [Pagination](TODO)
|
||||
`useTokenPagination` is the hook that **aids in implementing row pagination using tokens**. It is useful for server-side pagination implementations that use **tokens** instead of page index. For more information on pagination, see Pagination
|
||||
|
||||
> Documentation Coming Soon...
|
||||
|
||||
@@ -772,16 +807,18 @@ The following values are provided to the table `instance`:
|
||||
- Plugin Hook
|
||||
- Optional
|
||||
|
||||
`useRowSelect` is the hook that implements **basic row selection**. For more information on row selection, see [Row Selection](TODO)
|
||||
`useRowSelect` is the hook that implements **basic row selection**. For more information on row selection, see Row Selection
|
||||
|
||||
### Table Options
|
||||
|
||||
The following options are supported via the main options object passed to `useTable(options)`
|
||||
|
||||
- `state[0].selectedRows: Array<RowPathKey>`
|
||||
- `state.selectedRowPaths: Array<RowPathKey>`
|
||||
- Optional
|
||||
- Defaults to `[]`
|
||||
- If a row's path key (eg. a row path of `[1, 3, 2]` would have a path key of `1.3.2`) is found in this array, it will have a selected state.
|
||||
- `initialState.selectedRowPaths`
|
||||
- Identical to the `state.selectedRowPaths` option above
|
||||
- `manualRowSelectedKey: String`
|
||||
- Optional
|
||||
- Defaults to `isSelected`
|
||||
@@ -807,6 +844,8 @@ The following values are provided to the table `instance`:
|
||||
- `isAllRowsSelected: Bool`
|
||||
- Will be `true` if all rows are selected.
|
||||
- If at least one row is not selected, will be `false`
|
||||
- `selectedFlatRows: Array<Row>`
|
||||
- The flat array of rows that are currently selected
|
||||
|
||||
### Row Properties
|
||||
|
||||
@@ -834,12 +873,14 @@ The following additional properties are available on every **prepared** `row` ob
|
||||
|
||||
The following options are supported via the main options object passed to `useTable(options)`
|
||||
|
||||
- `state[0].rowState: Object<RowPathKey:Object<any, cellState: {columnID: Object}>>`
|
||||
- `state.rowState: Object<RowPathKey:Object<any, cellState: {columnID: Object}>>`
|
||||
- Optional
|
||||
- Defaults to `{}`
|
||||
- If a row's path key (eg. a row path of `[1, 3, 2]` would have a path key of `1.3.2`) is found in this array, it will have the state of the value corresponding to that key.
|
||||
- Individual row states can contain anything, but they also contain a `cellState` key, which provides cell-level state based on column ID's to every
|
||||
**prepared** cell in the table.
|
||||
- `initialState.rowState`
|
||||
- Identical to the `state.rowState` option above
|
||||
- `initialRowStateAccessor: Function`
|
||||
- Optional
|
||||
- This function may optionally return the initial state for a row.
|
||||
@@ -884,7 +925,7 @@ The following additional properties are available on every `Cell` object returne
|
||||
|
||||
`useBlocklayout` is a plugin hook that adds support for headers and cells to be rendered as `inline-block` `div`s (or other non-table elements) with explicit `width`. Similar to the `useAbsoluteLayout` hook, this becomes useful if and when you need to virtualize rows and cells for performance.
|
||||
|
||||
**NOTE:** Although no additional options are needed, the core column options `width`, `minWidth` and `maxWidth` are used to calculate column and cell widths and must be set. [See Column Options](#column-options) for more information on these options.
|
||||
**NOTE:** Although no additional options are needed for this plugin to work, the core column options `width`, `minWidth` and `maxWidth` are used to calculate column and cell widths and must be set. [See Column Options](#column-options) for more information on these options.
|
||||
|
||||
### Row Properties
|
||||
|
||||
@@ -916,7 +957,7 @@ The following additional properties are available on every `Cell` object returne
|
||||
|
||||
`useAbsoluteLayout` is a plugin hook that adds support for headers and cells to be rendered as absolutely positioned `div`s (or other non-table elements) with explicit `width`. Similar to the `useBlockLayout` hook, this becomes useful if and when you need to virtualize rows and cells for performance.
|
||||
|
||||
**NOTE:** Although no additional options are needed, the core column options `width`, `minWidth` and `maxWidth` are used to calculate column and cell widths and must be set. [See Column Options](#column-options) for more information on these options.
|
||||
**NOTE:** Although no additional options are needed for this plugin to work, the core column options `width`, `minWidth` and `maxWidth` are used to calculate column and cell widths and must be set. [See Column Options](#column-options) for more information on these options.
|
||||
|
||||
### Instance Properties
|
||||
|
||||
@@ -947,6 +988,42 @@ The following additional properties are available on every `Cell` object returne
|
||||
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/absolute-layout)
|
||||
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/absolute-layout)
|
||||
|
||||
# `useResizeColumns`
|
||||
|
||||
- Plugin Hook
|
||||
- Optional
|
||||
|
||||
`useResizeColumns` is a plugin hook that adds support for resizing headers and cells when using non-table elements for layout eg. the `useBlockLayout` and `useAbsoluteLayout` hooks. It even supports resizing column groups!
|
||||
|
||||
### Table Options
|
||||
|
||||
- `disableResizing: Bool`
|
||||
- Defaults to `false`
|
||||
- When set to `true`, resizing is disabled across the entire table
|
||||
|
||||
### Column Options
|
||||
|
||||
The core column options `width`, `minWidth` and `maxWidth` are used to calculate column and cell widths and must be set. [See Column Options](#column-options) for more information on these options.
|
||||
|
||||
- `disableResizing: Bool`
|
||||
- Defaults to `false`
|
||||
- When set to `true`, resizing is disabled for this column
|
||||
|
||||
### Header Properties
|
||||
|
||||
- `getResizerProps`
|
||||
- **Usage Required**
|
||||
- This core prop getter is required to to enable absolute layout for headers
|
||||
- `canResize: Bool`
|
||||
- Will be `true` if this column can be resized
|
||||
- `isResizing: Bool`
|
||||
- Will be `true` if this column is currently being resized
|
||||
|
||||
### Example
|
||||
|
||||
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/column-resizing)
|
||||
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/column-resizing)
|
||||
|
||||
# `useColumnOrder`
|
||||
|
||||
- Plugin Hook
|
||||
@@ -958,10 +1035,12 @@ The following additional properties are available on every `Cell` object returne
|
||||
|
||||
The following options are supported via the main options object passed to `useTable(options)`
|
||||
|
||||
- `state[0].columnOrder: Array<ColumnID>`
|
||||
- `state.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
|
||||
- `initialState.columnOrder`
|
||||
- Identical to the `state.columnOrder` option above
|
||||
|
||||
### Instance Properties
|
||||
|
||||
@@ -974,66 +1053,3 @@ The following values are provided to the table `instance`:
|
||||
|
||||
- [Source](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)
|
||||
|
||||
# `useTableState`
|
||||
|
||||
- Optional
|
||||
|
||||
`useTableState` is a hook that allows you to hoist the table state out of the table into your own code. You should use this hook if you need to:
|
||||
|
||||
- Know about the internal table state
|
||||
- React to changes to the internal table state
|
||||
- Manually control or override the internal table state
|
||||
|
||||
Some common use cases for this hook are:
|
||||
|
||||
- Reacting to `pageIndex` and `pageSize` changes for server-side pagination to fetch new data
|
||||
- Disallowing specific states via a custom state reducer
|
||||
- Enabling parent/unrelated components to manipulate the table state
|
||||
|
||||
### Hook Options
|
||||
|
||||
The following options are supported via the main options object passed to `useTable(options)`
|
||||
|
||||
- `initialState: Object`
|
||||
- Optional
|
||||
- The initial state object for the table.
|
||||
- This object is **merged over the `defaultState` object** (eg. `{...defaultState, ...initialState}`) that React Table and its hooks use to register default state to produce the final initial state object passed to the resolved `useState` hook.
|
||||
- `overrides: Object`
|
||||
- Optional
|
||||
- Must be **memoized**
|
||||
- This object is **merged over the current table state** (eg. `{...state, ...overrides}`) to produce the final state object that is then passed to the `useTable` options
|
||||
- `options: Object`
|
||||
- `reducer: Function(oldState, newState) => finalState`
|
||||
- Optional
|
||||
- Inspired by Kent C. Dodd's [State Reducer Pattern](https://kentcdodds.com/blog/the-state-reducer-pattern-with-react-hooks)
|
||||
- With every `setState` call to a table state (even internally), this reducer is called and is allowed to modify the final state object for updating.
|
||||
- It is passed the `oldState`, the `newState`, and an optional action `type`.
|
||||
- `useState`
|
||||
- Optional
|
||||
- Defaults to `React.useState`
|
||||
- This function, if defined will be used as the state hook internally instead of the default `React.useState`. This can be useful for implementing custom state storage hooks like useLocalStorage, etc.
|
||||
|
||||
### Output
|
||||
|
||||
- `tableStateTuple: [tableState, setTableState]`
|
||||
- Similar in structure to the result of `React.useState`
|
||||
- **Memoized** - This tuple array will not change between renders unless the state or `useTableState` options change.
|
||||
- `tableState: Object`
|
||||
- **Memoized** - This object reference will not change unless the state changes.
|
||||
- This is the final state object of the table, which is the product of the `initialState`, `overrides` and the `reducer` options (if applicable)
|
||||
- `setTableState: Function(updater, type) => void`
|
||||
- **Memoized** - This function reference will not change unless the internal state `reducer` is changed
|
||||
- This function is used both internally by React Table, and optionally by you (the developer) to update the table state programmatically.
|
||||
- `updater: Function`
|
||||
- This function signature is **almost** (see next point) identical to the functional API exposed by `React.setState`. It is passed the previous state and is expected to return a new version of the state.
|
||||
- **NOTE: `updater` must be a function. Passing a replacement object is not supported as it is with React.useState**
|
||||
- `type: String`
|
||||
- Optional
|
||||
- The [action type](TODO) corresponding to what action being taken against the state.
|
||||
|
||||
### Example
|
||||
|
||||
- As used in Controlled Pagination
|
||||
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/pagination-controlled)
|
||||
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/pagination-controlled)
|
||||
|
||||
+4
-1
@@ -31,11 +31,14 @@
|
||||
- Column Ordering
|
||||
- [Source](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)
|
||||
- Column Resizing
|
||||
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/column-resizing)
|
||||
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/column-resizing)
|
||||
- **Complex**
|
||||
- The "Kitchen Sink"
|
||||
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/kitchen-sink)
|
||||
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/kitchen-sink)
|
||||
- **Controlled via `useTableState`** - These examples are more advanced because they demonstrate how to manually control and respond to the state of the table using the `useTableState` hook.
|
||||
- **Controlled** - These examples are more advanced because they demonstrate how to manually control and respond to the state of the table.
|
||||
- Pagination (Controlled)
|
||||
- [Source](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)
|
||||
|
||||
@@ -294,7 +294,7 @@ function Table({ columns, data }) {
|
||||
</tbody>
|
||||
</table>
|
||||
<pre>
|
||||
<code>{JSON.stringify(state[0], null, 2)}</code>
|
||||
<code>{JSON.stringify(state, null, 2)}</code>
|
||||
</pre>
|
||||
</>
|
||||
)
|
||||
|
||||
@@ -95,7 +95,7 @@ function Table({ columns, data }) {
|
||||
</tbody>
|
||||
</table>
|
||||
<pre>
|
||||
<code>{JSON.stringify(state[0], null, 2)}</code>
|
||||
<code>{JSON.stringify(state, null, 2)}</code>
|
||||
</pre>
|
||||
</>
|
||||
)
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"presets": ["react-app"],
|
||||
"plugins": ["styled-components"]
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
SKIP_PREFLIGHT_CHECK=true
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": ["react-app", "prettier"],
|
||||
"rules": {
|
||||
// "eqeqeq": 0,
|
||||
// "jsx-a11y/anchor-is-valid": 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.js
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
@@ -0,0 +1,29 @@
|
||||
const path = require('path')
|
||||
const resolveFrom = require('resolve-from')
|
||||
|
||||
const fixLinkedDependencies = config => {
|
||||
config.resolve = {
|
||||
...config.resolve,
|
||||
alias: {
|
||||
...config.resolve.alias,
|
||||
react$: resolveFrom(path.resolve('node_modules'), 'react'),
|
||||
'react-dom$': resolveFrom(path.resolve('node_modules'), 'react-dom'),
|
||||
},
|
||||
}
|
||||
return config
|
||||
}
|
||||
|
||||
const includeSrcDirectory = config => {
|
||||
config.resolve = {
|
||||
...config.resolve,
|
||||
modules: [path.resolve('src'), ...config.resolve.modules],
|
||||
}
|
||||
return config
|
||||
}
|
||||
|
||||
module.exports = [
|
||||
['use-babel-config', '.babelrc'],
|
||||
['use-eslint-config', '.eslintrc'],
|
||||
fixLinkedDependencies,
|
||||
// includeSrcDirectory,
|
||||
]
|
||||
@@ -0,0 +1,6 @@
|
||||
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app) and Rescripts.
|
||||
|
||||
You can:
|
||||
|
||||
- [Open this example in a new CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/column-resizing)
|
||||
- `yarn` and `yarn start` to run and edit the example
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"start": "rescripts start",
|
||||
"build": "rescripts build",
|
||||
"test": "rescripts test",
|
||||
"eject": "rescripts eject"
|
||||
},
|
||||
"dependencies": {
|
||||
"namor": "^1.1.2",
|
||||
"react": "^16.8.6",
|
||||
"react-dom": "^16.8.6",
|
||||
"react-scripts": "3.0.1",
|
||||
"react-table": "next",
|
||||
"styled-components": "^4.3.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@rescripts/cli": "^0.0.11",
|
||||
"@rescripts/rescript-use-babel-config": "^0.0.8",
|
||||
"@rescripts/rescript-use-eslint-config": "^0.0.9",
|
||||
"babel-eslint": "10.0.1"
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 3.8 KiB |
@@ -0,0 +1,38 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="theme-color" content="#000000" />
|
||||
<!--
|
||||
manifest.json provides metadata used when your web app is installed on a
|
||||
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
|
||||
-->
|
||||
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
|
||||
<!--
|
||||
Notice the use of %PUBLIC_URL% in the tags above.
|
||||
It will be replaced with the URL of the `public` folder during the build.
|
||||
Only files inside the `public` folder can be referenced from the HTML.
|
||||
|
||||
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
|
||||
work correctly both with client-side routing and a non-root public URL.
|
||||
Learn how to configure a non-root public URL by running `npm run build`.
|
||||
-->
|
||||
<title>React App</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||
<div id="root"></div>
|
||||
<!--
|
||||
This HTML file is a template.
|
||||
If you open it directly in the browser, you will see an empty page.
|
||||
|
||||
You can add webfonts, meta tags, or analytics to this file.
|
||||
The build step will place the bundled scripts into the <body> tag.
|
||||
|
||||
To begin the development, run `npm start` or `yarn start`.
|
||||
To create a production bundle, use `npm run build` or `yarn build`.
|
||||
-->
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"short_name": "React App",
|
||||
"name": "Create React App Sample",
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicon.ico",
|
||||
"sizes": "64x64 32x32 24x24 16x16",
|
||||
"type": "image/x-icon"
|
||||
}
|
||||
],
|
||||
"start_url": ".",
|
||||
"display": "standalone",
|
||||
"theme_color": "#000000",
|
||||
"background_color": "#ffffff"
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
import React from 'react'
|
||||
import styled from 'styled-components'
|
||||
import { useTable, useBlockLayout, useResizeColumns } from 'react-table'
|
||||
|
||||
import makeData from './makeData'
|
||||
|
||||
const Styles = styled.div`
|
||||
padding: 1rem;
|
||||
|
||||
.table {
|
||||
display: inline-block;
|
||||
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;
|
||||
|
||||
${'' /* In this example we use an absolutely position resizer,
|
||||
so this is required. */}
|
||||
position: relative;
|
||||
|
||||
:last-child {
|
||||
border-right: 0;
|
||||
}
|
||||
|
||||
${'' /* The resizer styles! */}
|
||||
|
||||
.resizer {
|
||||
display: inline-block;
|
||||
background: blue;
|
||||
width: 5px;
|
||||
height: 100%;
|
||||
position: absolute;
|
||||
right: 0;
|
||||
top: 0;
|
||||
transform: translateX(50%);
|
||||
z-index: 1;
|
||||
|
||||
&.isResizing {
|
||||
background: red;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
function Table({ columns, data }) {
|
||||
const defaultColumn = React.useMemo(
|
||||
() => ({
|
||||
minWidth: 20,
|
||||
width: 150,
|
||||
maxWidth: 500,
|
||||
}),
|
||||
[]
|
||||
)
|
||||
|
||||
const {
|
||||
getTableProps,
|
||||
getTableBodyProps,
|
||||
headerGroups,
|
||||
rows,
|
||||
prepareRow,
|
||||
} = useTable(
|
||||
{
|
||||
columns,
|
||||
data,
|
||||
defaultColumn,
|
||||
},
|
||||
useBlockLayout,
|
||||
useResizeColumns
|
||||
)
|
||||
|
||||
return (
|
||||
<div {...getTableProps()} className="table">
|
||||
<div>
|
||||
{headerGroups.map(headerGroup => (
|
||||
<div {...headerGroup.getHeaderGroupProps()} className="tr">
|
||||
{headerGroup.headers.map(column => (
|
||||
<div {...column.getHeaderProps()} className="th">
|
||||
{column.render('Header')}
|
||||
{/* Use column.getResizerProps to hook up the events correctly */}
|
||||
<div
|
||||
{...column.getResizerProps()}
|
||||
className={`resizer ${column.isResizing ? 'isResizing' : ''}`}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div {...getTableBodyProps()}>
|
||||
{rows.map(
|
||||
(row, i) =>
|
||||
prepareRow(row) || (
|
||||
<div {...row.getRowProps()} className="tr">
|
||||
{row.cells.map(cell => {
|
||||
return (
|
||||
<div {...cell.getCellProps()} className="td">
|
||||
{cell.render('Cell')}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function App() {
|
||||
const columns = React.useMemo(
|
||||
() => [
|
||||
{
|
||||
Header: 'Name',
|
||||
columns: [
|
||||
{
|
||||
Header: 'First Name',
|
||||
accessor: 'firstName',
|
||||
},
|
||||
{
|
||||
Header: 'Last Name',
|
||||
accessor: 'lastName',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
Header: 'Info',
|
||||
columns: [
|
||||
{
|
||||
Header: 'Age',
|
||||
accessor: 'age',
|
||||
width: 50,
|
||||
},
|
||||
{
|
||||
Header: 'Visits',
|
||||
accessor: 'visits',
|
||||
width: 60,
|
||||
},
|
||||
{
|
||||
Header: 'Status',
|
||||
accessor: 'status',
|
||||
},
|
||||
{
|
||||
Header: 'Profile Progress',
|
||||
accessor: 'progress',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
[]
|
||||
)
|
||||
|
||||
const data = React.useMemo(() => makeData(20), [])
|
||||
|
||||
return (
|
||||
<Styles>
|
||||
<Table columns={columns} data={data} />
|
||||
</Styles>
|
||||
)
|
||||
}
|
||||
|
||||
export default App
|
||||
@@ -0,0 +1,9 @@
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom'
|
||||
import App from './App'
|
||||
|
||||
it('renders without crashing', () => {
|
||||
const div = document.createElement('div')
|
||||
ReactDOM.render(<App />, div)
|
||||
ReactDOM.unmountComponentAtNode(div)
|
||||
})
|
||||
@@ -0,0 +1,13 @@
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
|
||||
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
|
||||
sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
|
||||
monospace;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom'
|
||||
import './index.css'
|
||||
import App from './App'
|
||||
import * as serviceWorker from './serviceWorker'
|
||||
|
||||
ReactDOM.render(<App />, document.getElementById('root'))
|
||||
|
||||
// If you want your app to work offline and load faster, you can change
|
||||
// unregister() to register() below. Note this comes with some pitfalls.
|
||||
// Learn more about service workers: https://bit.ly/CRA-PWA
|
||||
serviceWorker.unregister()
|
||||
@@ -0,0 +1,40 @@
|
||||
import namor from 'namor'
|
||||
|
||||
const range = len => {
|
||||
const arr = []
|
||||
for (let i = 0; i < len; i++) {
|
||||
arr.push(i)
|
||||
}
|
||||
return arr
|
||||
}
|
||||
|
||||
const newPerson = () => {
|
||||
const statusChance = Math.random()
|
||||
return {
|
||||
firstName: namor.generate({ words: 1, numbers: 0 }),
|
||||
lastName: namor.generate({ words: 1, numbers: 0 }),
|
||||
age: Math.floor(Math.random() * 30),
|
||||
visits: Math.floor(Math.random() * 100),
|
||||
progress: Math.floor(Math.random() * 100),
|
||||
status:
|
||||
statusChance > 0.66
|
||||
? 'relationship'
|
||||
: statusChance > 0.33
|
||||
? 'complicated'
|
||||
: 'single',
|
||||
}
|
||||
}
|
||||
|
||||
export default function makeData(...lens) {
|
||||
const makeDataLevel = (depth = 0) => {
|
||||
const len = lens[depth]
|
||||
return range(len).map(d => {
|
||||
return {
|
||||
...newPerson(),
|
||||
subRows: lens[depth + 1] ? makeDataLevel(depth + 1) : undefined,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return makeDataLevel()
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
// This optional code is used to register a service worker.
|
||||
// register() is not called by default.
|
||||
|
||||
// This lets the app load faster on subsequent visits in production, and gives
|
||||
// it offline capabilities. However, it also means that developers (and users)
|
||||
// will only see deployed updates on subsequent visits to a page, after all the
|
||||
// existing tabs open on the page have been closed, since previously cached
|
||||
// resources are updated in the background.
|
||||
|
||||
// To learn more about the benefits of this model and instructions on how to
|
||||
// opt-in, read https://bit.ly/CRA-PWA
|
||||
|
||||
const isLocalhost = Boolean(
|
||||
window.location.hostname === 'localhost' ||
|
||||
// [::1] is the IPv6 localhost address.
|
||||
window.location.hostname === '[::1]' ||
|
||||
// 127.0.0.1/8 is considered localhost for IPv4.
|
||||
window.location.hostname.match(
|
||||
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
|
||||
)
|
||||
)
|
||||
|
||||
export function register(config) {
|
||||
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
|
||||
// The URL constructor is available in all browsers that support SW.
|
||||
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href)
|
||||
if (publicUrl.origin !== window.location.origin) {
|
||||
// Our service worker won't work if PUBLIC_URL is on a different origin
|
||||
// from what our page is served on. This might happen if a CDN is used to
|
||||
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
|
||||
return
|
||||
}
|
||||
|
||||
window.addEventListener('load', () => {
|
||||
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`
|
||||
|
||||
if (isLocalhost) {
|
||||
// This is running on localhost. Let's check if a service worker still exists or not.
|
||||
checkValidServiceWorker(swUrl, config)
|
||||
|
||||
// Add some additional logging to localhost, pointing developers to the
|
||||
// service worker/PWA documentation.
|
||||
navigator.serviceWorker.ready.then(() => {
|
||||
console.log(
|
||||
'This web app is being served cache-first by a service ' +
|
||||
'worker. To learn more, visit https://bit.ly/CRA-PWA'
|
||||
)
|
||||
})
|
||||
} else {
|
||||
// Is not localhost. Just register service worker
|
||||
registerValidSW(swUrl, config)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function registerValidSW(swUrl, config) {
|
||||
navigator.serviceWorker
|
||||
.register(swUrl)
|
||||
.then(registration => {
|
||||
registration.onupdatefound = () => {
|
||||
const installingWorker = registration.installing
|
||||
if (installingWorker == null) {
|
||||
return
|
||||
}
|
||||
installingWorker.onstatechange = () => {
|
||||
if (installingWorker.state === 'installed') {
|
||||
if (navigator.serviceWorker.controller) {
|
||||
// At this point, the updated precached content has been fetched,
|
||||
// but the previous service worker will still serve the older
|
||||
// content until all client tabs are closed.
|
||||
console.log(
|
||||
'New content is available and will be used when all ' +
|
||||
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
|
||||
)
|
||||
|
||||
// Execute callback
|
||||
if (config && config.onUpdate) {
|
||||
config.onUpdate(registration)
|
||||
}
|
||||
} else {
|
||||
// At this point, everything has been precached.
|
||||
// It's the perfect time to display a
|
||||
// "Content is cached for offline use." message.
|
||||
console.log('Content is cached for offline use.')
|
||||
|
||||
// Execute callback
|
||||
if (config && config.onSuccess) {
|
||||
config.onSuccess(registration)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error during service worker registration:', error)
|
||||
})
|
||||
}
|
||||
|
||||
function checkValidServiceWorker(swUrl, config) {
|
||||
// Check if the service worker can be found. If it can't reload the page.
|
||||
fetch(swUrl)
|
||||
.then(response => {
|
||||
// Ensure service worker exists, and that we really are getting a JS file.
|
||||
const contentType = response.headers.get('content-type')
|
||||
if (
|
||||
response.status === 404 ||
|
||||
(contentType != null && contentType.indexOf('javascript') === -1)
|
||||
) {
|
||||
// No service worker found. Probably a different app. Reload the page.
|
||||
navigator.serviceWorker.ready.then(registration => {
|
||||
registration.unregister().then(() => {
|
||||
window.location.reload()
|
||||
})
|
||||
})
|
||||
} else {
|
||||
// Service worker found. Proceed as normal.
|
||||
registerValidSW(swUrl, config)
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
console.log(
|
||||
'No internet connection found. App is running in offline mode.'
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
export function unregister() {
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker.ready.then(registration => {
|
||||
registration.unregister()
|
||||
})
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -95,7 +95,7 @@ function Table({ columns, data, updateMyData, disablePageResetOnDataChange }) {
|
||||
nextPage,
|
||||
previousPage,
|
||||
setPageSize,
|
||||
state: [{ pageIndex, pageSize }],
|
||||
state: { pageIndex, pageSize },
|
||||
} = useTable(
|
||||
{
|
||||
columns,
|
||||
|
||||
@@ -40,7 +40,7 @@ function Table({ columns: userColumns, data }) {
|
||||
headerGroups,
|
||||
rows,
|
||||
prepareRow,
|
||||
state: [{ expanded }],
|
||||
state: { expanded },
|
||||
} = useTable(
|
||||
{
|
||||
columns: userColumns,
|
||||
|
||||
@@ -235,7 +235,7 @@ function Table({ columns, data }) {
|
||||
<>
|
||||
<div>
|
||||
<pre>
|
||||
<code>{JSON.stringify(state[0].filters, null, 2)}</code>
|
||||
<code>{JSON.stringify(state.filters, null, 2)}</code>
|
||||
</pre>
|
||||
</div>
|
||||
<table {...getTableProps()}>
|
||||
|
||||
@@ -40,7 +40,7 @@ function Table({ columns, data }) {
|
||||
headerGroups,
|
||||
rows,
|
||||
prepareRow,
|
||||
state: [{ groupBy, expanded }],
|
||||
state: { groupBy, expanded },
|
||||
} = useTable(
|
||||
{
|
||||
columns,
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
useGroupBy,
|
||||
useExpanded,
|
||||
useRowSelect,
|
||||
useTableState,
|
||||
} from 'react-table'
|
||||
import matchSorter from 'match-sorter'
|
||||
|
||||
@@ -265,8 +264,6 @@ function Table({ columns, data, updateMyData, disablePageResetOnDataChange }) {
|
||||
[]
|
||||
)
|
||||
|
||||
const tableState = useTableState({ pageIndex: 2 })
|
||||
|
||||
// Use the state and functions returned from useTable to build your UI
|
||||
const {
|
||||
getTableProps,
|
||||
@@ -285,7 +282,14 @@ function Table({ columns, data, updateMyData, disablePageResetOnDataChange }) {
|
||||
nextPage,
|
||||
previousPage,
|
||||
setPageSize,
|
||||
state: [{ pageIndex, pageSize, groupBy, expanded, filters, selectedRows }],
|
||||
state: {
|
||||
pageIndex,
|
||||
pageSize,
|
||||
groupBy,
|
||||
expanded,
|
||||
filters,
|
||||
selectedRowPaths,
|
||||
},
|
||||
} = useTable(
|
||||
{
|
||||
columns,
|
||||
@@ -293,7 +297,7 @@ function Table({ columns, data, updateMyData, disablePageResetOnDataChange }) {
|
||||
defaultColumn,
|
||||
filterTypes,
|
||||
// nestExpandedRows: true,
|
||||
state: tableState,
|
||||
initialState: { pageIndex: 2 },
|
||||
// updateMyData isn't part of the API, but
|
||||
// anything we put into these options will
|
||||
// automatically be available on the instance.
|
||||
@@ -438,7 +442,7 @@ function Table({ columns, data, updateMyData, disablePageResetOnDataChange }) {
|
||||
groupBy,
|
||||
expanded,
|
||||
filters,
|
||||
selectedRows,
|
||||
selectedRowPaths,
|
||||
},
|
||||
null,
|
||||
2
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
useGroupBy,
|
||||
useExpanded,
|
||||
useRowSelect,
|
||||
useTableState,
|
||||
} from 'react-table'
|
||||
import matchSorter from 'match-sorter'
|
||||
|
||||
@@ -265,8 +264,6 @@ function Table({ columns, data, updateMyData, disablePageResetOnDataChange }) {
|
||||
[]
|
||||
)
|
||||
|
||||
const tableState = useTableState({ pageIndex: 2 })
|
||||
|
||||
// Use the state and functions returned from useTable to build your UI
|
||||
const {
|
||||
getTableProps,
|
||||
@@ -285,7 +282,14 @@ function Table({ columns, data, updateMyData, disablePageResetOnDataChange }) {
|
||||
nextPage,
|
||||
previousPage,
|
||||
setPageSize,
|
||||
state: [{ pageIndex, pageSize, groupBy, expanded, filters, selectedRows }],
|
||||
state: {
|
||||
pageIndex,
|
||||
pageSize,
|
||||
groupBy,
|
||||
expanded,
|
||||
filters,
|
||||
selectedRowPaths,
|
||||
},
|
||||
} = useTable(
|
||||
{
|
||||
columns,
|
||||
@@ -293,7 +297,7 @@ function Table({ columns, data, updateMyData, disablePageResetOnDataChange }) {
|
||||
defaultColumn,
|
||||
filterTypes,
|
||||
// nestExpandedRows: true,
|
||||
state: tableState,
|
||||
initialState: { pageIndex: 2 },
|
||||
// updateMyData isn't part of the API, but
|
||||
// anything we put into these options will
|
||||
// automatically be available on the instance.
|
||||
@@ -438,7 +442,7 @@ function Table({ columns, data, updateMyData, disablePageResetOnDataChange }) {
|
||||
groupBy,
|
||||
expanded,
|
||||
filters,
|
||||
selectedRows,
|
||||
selectedRowPaths,
|
||||
},
|
||||
null,
|
||||
2
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React from 'react'
|
||||
import styled from 'styled-components'
|
||||
import { useTable, useTableState, usePagination } from 'react-table'
|
||||
import { useTable, usePagination } from 'react-table'
|
||||
|
||||
import makeData from './makeData'
|
||||
|
||||
@@ -47,17 +47,6 @@ function Table({
|
||||
loading,
|
||||
pageCount: controlledPageCount,
|
||||
}) {
|
||||
// Use useTableState to hoist the state (and state updater) out of the table and control it
|
||||
const tableState = useTableState({ pageIndex: 0 })
|
||||
|
||||
// Now we can get our table state from the hoisted table state tuple
|
||||
const [{ pageIndex, pageSize }] = tableState
|
||||
|
||||
// Listen for changes in pagination and use the state to fetch our new data
|
||||
React.useEffect(() => {
|
||||
fetchData({ pageIndex, pageSize })
|
||||
}, [fetchData, pageIndex, pageSize])
|
||||
|
||||
const {
|
||||
getTableProps,
|
||||
getTableBodyProps,
|
||||
@@ -72,11 +61,13 @@ function Table({
|
||||
nextPage,
|
||||
previousPage,
|
||||
setPageSize,
|
||||
// Get the state from the instance
|
||||
state: { pageIndex, pageSize },
|
||||
} = useTable(
|
||||
{
|
||||
columns,
|
||||
data,
|
||||
state: tableState, // Pass our hoisted table state
|
||||
state: { pageIndex: 0 }, // Pass our hoisted table state
|
||||
manualPagination: true, // Tell the usePagination
|
||||
// hook that we'll handle our own data fetching
|
||||
// This means we'll also have to provide our own
|
||||
@@ -86,6 +77,13 @@ function Table({
|
||||
usePagination
|
||||
)
|
||||
|
||||
// Now we can get our table state from the hoisted table state tuple
|
||||
|
||||
// Listen for changes in pagination and use the state to fetch our new data
|
||||
React.useEffect(() => {
|
||||
fetchData({ pageIndex, pageSize })
|
||||
}, [fetchData, pageIndex, pageSize])
|
||||
|
||||
// Render the UI for your table
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -42,7 +42,7 @@ function MyTable(props) {
|
||||
prepareRow,
|
||||
+ pageOptions,
|
||||
+ page,
|
||||
+ state: [{ pageIndex, pageSize }],
|
||||
+ state: { pageIndex, pageSize },
|
||||
+ gotoPage,
|
||||
+ previousPage,
|
||||
+ nextPage,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React from 'react'
|
||||
import styled from 'styled-components'
|
||||
import { useTable, usePagination, useTableState } from 'react-table'
|
||||
import { useTable, usePagination } from 'react-table'
|
||||
|
||||
import makeData from './makeData'
|
||||
|
||||
@@ -38,8 +38,6 @@ const Styles = styled.div`
|
||||
`
|
||||
|
||||
function Table({ columns, data }) {
|
||||
const tableState = useTableState({ pageIndex: 2 })
|
||||
|
||||
// Use the state and functions returned from useTable to build your UI
|
||||
const {
|
||||
getTableProps,
|
||||
@@ -58,12 +56,12 @@ function Table({ columns, data }) {
|
||||
nextPage,
|
||||
previousPage,
|
||||
setPageSize,
|
||||
state: [{ pageIndex, pageSize }],
|
||||
state: { pageIndex, pageSize },
|
||||
} = useTable(
|
||||
{
|
||||
columns,
|
||||
data,
|
||||
state: tableState,
|
||||
initialState: { pageIndex: 2 },
|
||||
},
|
||||
usePagination
|
||||
)
|
||||
|
||||
@@ -41,7 +41,8 @@ function Table({ columns, data }) {
|
||||
headerGroups,
|
||||
rows,
|
||||
prepareRow,
|
||||
state: [{ selectedRows }],
|
||||
selectedFlatRows,
|
||||
state: { selectedRowPaths },
|
||||
} = useTable(
|
||||
{
|
||||
columns,
|
||||
@@ -78,9 +79,20 @@ function Table({ columns, data }) {
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
<p>Selected Rows: {selectedRows.length}</p>
|
||||
<p>Selected Rows: {selectedRowPaths.length}</p>
|
||||
<pre>
|
||||
<code>{JSON.stringify({ selectedRows }, null, 2)}</code>
|
||||
<code>
|
||||
{JSON.stringify(
|
||||
{
|
||||
selectedRowPaths,
|
||||
'selectedFlatRows[].original': selectedFlatRows.map(
|
||||
d => d.original
|
||||
),
|
||||
},
|
||||
null,
|
||||
2
|
||||
)}
|
||||
</code>
|
||||
</pre>
|
||||
</>
|
||||
)
|
||||
|
||||
@@ -44,7 +44,7 @@ function Table({ columns: userColumns, data, renderRowSubComponent }) {
|
||||
rows,
|
||||
prepareRow,
|
||||
flatColumns,
|
||||
state: [{ expanded }],
|
||||
state: { expanded },
|
||||
} = useTable(
|
||||
{
|
||||
columns: userColumns,
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"infiniteLoopProtection": false,
|
||||
"hardReloadOnChange": false,
|
||||
"view": "browser"
|
||||
}
|
||||
@@ -85,8 +85,6 @@ function Table({ columns, data }) {
|
||||
[prepareRow, rows]
|
||||
)
|
||||
|
||||
console.log(headerGroups)
|
||||
|
||||
// Render the UI for your table
|
||||
return (
|
||||
<div {...getTableProps()} className="table">
|
||||
|
||||
Vendored
+9
-16
@@ -202,15 +202,23 @@ declare module 'react-table' {
|
||||
getTableProps: (userProps?: any) => any
|
||||
getRowProps: (userProps?: any) => any
|
||||
prepareRow: (row: Row<D>) => any
|
||||
state: TableState<D>
|
||||
setState: SetState<D>
|
||||
}
|
||||
|
||||
export interface TableOptions<D = {}> {
|
||||
data: D[]
|
||||
columns: HeaderColumn<D>[]
|
||||
state: State<D>
|
||||
debug?: boolean
|
||||
loading: boolean
|
||||
defaultColumn?: Partial<Column<D>>
|
||||
initialState?: Partial<TableState<D>>
|
||||
state?: Partial<TableState<D>>
|
||||
reducer?: (
|
||||
oldState: TableState<D>,
|
||||
newState: TableState<D>,
|
||||
type: string
|
||||
) => any
|
||||
}
|
||||
|
||||
// The empty definition of TableState is not an error. It provides a definition
|
||||
@@ -232,8 +240,6 @@ declare module 'react-table' {
|
||||
actions: any
|
||||
) => void
|
||||
|
||||
export type State<D> = [TableState<D>, SetState<D>]
|
||||
|
||||
export function useTable<D = {}>(
|
||||
props: TableOptions<D>,
|
||||
...plugins: any[]
|
||||
@@ -267,19 +273,6 @@ declare module 'react-table' {
|
||||
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
|
||||
|
||||
Generated
+31
-9
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "react-table",
|
||||
"version": "7.0.0-alpha.29",
|
||||
"version": "7.0.0-beta.5",
|
||||
"lockfileVersion": 1,
|
||||
"requires": true,
|
||||
"dependencies": {
|
||||
@@ -10033,16 +10033,17 @@
|
||||
"integrity": "sha512-BmJMHUWQcvjS2dQMwJ7dzvdbwpRChnq4AYk2sTU/4aySt9Kumk8y8W3HhTHss31wxzKb0AC/wsiX1AqDcOBIEA==",
|
||||
"dev": true
|
||||
},
|
||||
"rollup-plugin-uglify": {
|
||||
"version": "6.0.2",
|
||||
"resolved": "https://registry.npmjs.org/rollup-plugin-uglify/-/rollup-plugin-uglify-6.0.2.tgz",
|
||||
"integrity": "sha512-qwz2Tryspn5QGtPUowq5oumKSxANKdrnfz7C0jm4lKxvRDsNe/hSGsB9FntUul7UeC4TsZEWKErVgE1qWSO0gw==",
|
||||
"rollup-plugin-terser": {
|
||||
"version": "5.1.2",
|
||||
"resolved": "https://registry.npmjs.org/rollup-plugin-terser/-/rollup-plugin-terser-5.1.2.tgz",
|
||||
"integrity": "sha512-sWKBCOS+vUkRtHtEiJPAf+WnBqk/C402fBD9AVHxSIXMqjsY7MnYWKYEUqGixtr0c8+1DjzUEPlNgOYQPVrS1g==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"@babel/code-frame": "^7.0.0",
|
||||
"jest-worker": "^24.0.0",
|
||||
"serialize-javascript": "^1.6.1",
|
||||
"uglify-js": "^3.4.9"
|
||||
"jest-worker": "^24.6.0",
|
||||
"rollup-pluginutils": "^2.8.1",
|
||||
"serialize-javascript": "^1.7.0",
|
||||
"terser": "^4.1.0"
|
||||
}
|
||||
},
|
||||
"rollup-pluginutils": {
|
||||
@@ -10781,6 +10782,25 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"terser": {
|
||||
"version": "4.3.4",
|
||||
"resolved": "https://registry.npmjs.org/terser/-/terser-4.3.4.tgz",
|
||||
"integrity": "sha512-Kcrn3RiW8NtHBP0ssOAzwa2MsIRQ8lJWiBG/K7JgqPlomA3mtb2DEmp4/hrUA+Jujx+WZ02zqd7GYD+QRBB/2Q==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"commander": "^2.20.0",
|
||||
"source-map": "~0.6.1",
|
||||
"source-map-support": "~0.5.12"
|
||||
},
|
||||
"dependencies": {
|
||||
"source-map": {
|
||||
"version": "0.6.1",
|
||||
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
|
||||
"integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
|
||||
"dev": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"test-exclude": {
|
||||
"version": "5.2.3",
|
||||
"resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-5.2.3.tgz",
|
||||
@@ -11062,6 +11082,7 @@
|
||||
"resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.6.0.tgz",
|
||||
"integrity": "sha512-W+jrUHJr3DXKhrsS7NUVxn3zqMOFn0hL/Ei6v0anCIMoKC93TjcflTagwIHLW7SfMFfiQuktQyFVCFHGUE0+yg==",
|
||||
"dev": true,
|
||||
"optional": true,
|
||||
"requires": {
|
||||
"commander": "~2.20.0",
|
||||
"source-map": "~0.6.1"
|
||||
@@ -11071,7 +11092,8 @@
|
||||
"version": "0.6.1",
|
||||
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
|
||||
"integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
|
||||
"dev": true
|
||||
"dev": true,
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "react-table",
|
||||
"version": "7.0.0-beta.5",
|
||||
"version": "7.0.0-beta.10",
|
||||
"description": "A fast, lightweight, opinionated table and datagrid built on React",
|
||||
"license": "MIT",
|
||||
"homepage": "https://github.com/tannerlinsley/react-table#readme",
|
||||
|
||||
+5
-1
@@ -44,7 +44,11 @@ includes.autoRemove = val => !val || !val.length
|
||||
export const includesAll = (rows, id, filterValue) => {
|
||||
return rows.filter(row => {
|
||||
const rowValue = row.values[id]
|
||||
return filterValue.every(val => rowValue.includes(val))
|
||||
return (
|
||||
rowValue &&
|
||||
rowValue.length &&
|
||||
filterValue.every(val => rowValue.includes(val))
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
+59
-26
@@ -12,8 +12,6 @@ import {
|
||||
determineHeaderVisibility,
|
||||
} from '../utils'
|
||||
|
||||
import { useTableState } from './useTableState'
|
||||
|
||||
const propTypes = {
|
||||
// General
|
||||
data: PropTypes.array.isRequired,
|
||||
@@ -27,8 +25,11 @@ const propTypes = {
|
||||
const renderErr =
|
||||
'You must specify a valid render component. This could be "column.Cell", "column.Header", "column.Filter", "column.Aggregated" or any other custom renderer component.'
|
||||
|
||||
const defaultColumnInstance = {}
|
||||
export const defaultState = {}
|
||||
|
||||
const defaultInitialState = {}
|
||||
const defaultColumnInstance = {}
|
||||
const defaultReducer = (old, newState) => newState
|
||||
const defaultGetSubRows = (row, index) => row.subRows || []
|
||||
const defaultGetRowID = (row, index) => index
|
||||
|
||||
@@ -39,21 +40,46 @@ export const useTable = (props, ...plugins) => {
|
||||
// Destructure props
|
||||
let {
|
||||
data,
|
||||
state: userState,
|
||||
columns: userColumns,
|
||||
initialState = defaultInitialState,
|
||||
state: userState,
|
||||
defaultColumn = defaultColumnInstance,
|
||||
getSubRows = defaultGetSubRows,
|
||||
getRowID = defaultGetRowID,
|
||||
reducer = defaultReducer,
|
||||
debug,
|
||||
} = props
|
||||
|
||||
debug = process.env.NODE_ENV === 'production' ? false : debug
|
||||
|
||||
// Always provide a default table state
|
||||
const defaultState = useTableState()
|
||||
|
||||
// But use the users table state if provided
|
||||
const state = userState || defaultState
|
||||
let [originalState, originalSetState] = React.useState({
|
||||
...defaultState,
|
||||
...initialState,
|
||||
})
|
||||
|
||||
const state = React.useMemo(() => {
|
||||
if (userState) {
|
||||
const newState = {
|
||||
...originalState,
|
||||
}
|
||||
Object.keys(userState).forEach(key => {
|
||||
newState[key] = userState[key]
|
||||
})
|
||||
return newState
|
||||
}
|
||||
return originalState
|
||||
}, [originalState, userState])
|
||||
|
||||
const setState = React.useCallback(
|
||||
(updater, type) => {
|
||||
return originalSetState(old => {
|
||||
const newState = typeof updater === 'function' ? updater(old) : updater
|
||||
return reducer(old, newState, type)
|
||||
})
|
||||
},
|
||||
[reducer]
|
||||
)
|
||||
|
||||
// The table instance ref
|
||||
let instanceRef = React.useRef({})
|
||||
@@ -61,11 +87,13 @@ export const useTable = (props, ...plugins) => {
|
||||
Object.assign(instanceRef.current, {
|
||||
...props,
|
||||
data, // The raw data
|
||||
state, // The resolved table state
|
||||
state,
|
||||
setState, // The resolved table state
|
||||
plugins, // All resolved plugins
|
||||
hooks: {
|
||||
columnsBeforeHeaderGroups: [],
|
||||
columnsBeforeHeaderGroupsDeps: [],
|
||||
useBeforeDimensions: [],
|
||||
useMain: [],
|
||||
useRows: [],
|
||||
prepareRow: [],
|
||||
@@ -136,12 +164,11 @@ export const useTable = (props, ...plugins) => {
|
||||
})
|
||||
|
||||
// Access the row model
|
||||
const [rows, rowPaths, flatRows] = React.useMemo(() => {
|
||||
const [rows, flatRows] = React.useMemo(() => {
|
||||
if (process.env.NODE_ENV === 'development' && debug)
|
||||
console.time('getAccessedRows')
|
||||
|
||||
let flatRows = 0
|
||||
const rowPaths = []
|
||||
let flatRows = []
|
||||
|
||||
// Access the row's data
|
||||
const accessRow = (originalRow, i, depth = 0, parentPath = []) => {
|
||||
@@ -153,23 +180,21 @@ export const useTable = (props, ...plugins) => {
|
||||
// Make the new path for the row
|
||||
const path = [...parentPath, rowID]
|
||||
|
||||
flatRows++
|
||||
rowPaths.push(path.join('.'))
|
||||
const row = {
|
||||
original,
|
||||
index: i,
|
||||
path, // used to create a key for each row even if not nested
|
||||
depth,
|
||||
cells: [{}], // This is a dummy cell
|
||||
}
|
||||
|
||||
flatRows.push(row)
|
||||
|
||||
// Process any subRows
|
||||
let subRows = getSubRows(originalRow, i)
|
||||
|
||||
if (subRows) {
|
||||
subRows = subRows.map((d, i) => accessRow(d, i, depth + 1, path))
|
||||
}
|
||||
|
||||
const row = {
|
||||
original,
|
||||
index: i,
|
||||
path, // used to create a key for each row even if not nested
|
||||
subRows,
|
||||
depth,
|
||||
cells: [{}], // This is a dummy cell
|
||||
row.subRows = subRows.map((d, i) => accessRow(d, i, depth + 1, path))
|
||||
}
|
||||
|
||||
// Override common array functions (and the dummy cell's getCellProps function)
|
||||
@@ -199,11 +224,10 @@ export const useTable = (props, ...plugins) => {
|
||||
const accessedData = data.map((d, i) => accessRow(d, i))
|
||||
if (process.env.NODE_ENV === 'development' && debug)
|
||||
console.timeEnd('getAccessedRows')
|
||||
return [accessedData, rowPaths, flatRows]
|
||||
return [accessedData, flatRows]
|
||||
}, [debug, data, getRowID, getSubRows, flatColumns])
|
||||
|
||||
instanceRef.current.rows = rows
|
||||
instanceRef.current.rowPaths = rowPaths
|
||||
instanceRef.current.flatRows = flatRows
|
||||
|
||||
// Determine column visibility
|
||||
@@ -215,6 +239,15 @@ export const useTable = (props, ...plugins) => {
|
||||
[]
|
||||
)
|
||||
|
||||
if (process.env.NODE_ENV === 'development' && debug)
|
||||
console.time('hooks.useBeforeDimensions')
|
||||
instanceRef.current = applyHooks(
|
||||
instanceRef.current.hooks.useBeforeDimensions,
|
||||
instanceRef.current
|
||||
)
|
||||
if (process.env.NODE_ENV === 'development' && debug)
|
||||
console.timeEnd('hooks.useBeforeDimensions')
|
||||
|
||||
calculateDimensions(instanceRef.current)
|
||||
|
||||
if (process.env.NODE_ENV === 'development' && debug)
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
import React from 'react'
|
||||
//
|
||||
export const defaultState = {}
|
||||
|
||||
const defaultReducer = (old, newState) => newState
|
||||
|
||||
export const useTableState = (
|
||||
initialState = {},
|
||||
overrides,
|
||||
{ reducer = defaultReducer, useState: userUseState = React.useState } = {}
|
||||
) => {
|
||||
let [state, setState] = userUseState({
|
||||
...defaultState,
|
||||
...initialState,
|
||||
})
|
||||
|
||||
const overriddenState = React.useMemo(() => {
|
||||
const newState = {
|
||||
...state,
|
||||
}
|
||||
if (overrides) {
|
||||
Object.keys(overrides).forEach(key => {
|
||||
newState[key] = overrides[key]
|
||||
})
|
||||
}
|
||||
return newState
|
||||
}, [overrides, state])
|
||||
|
||||
const overriddenStateRef = React.useRef()
|
||||
overriddenStateRef.current = overriddenState
|
||||
|
||||
const reducedSetState = React.useCallback(
|
||||
(updater, type) => {
|
||||
return setState(old => {
|
||||
const newState = updater(old)
|
||||
return reducer(old, newState, type)
|
||||
})
|
||||
},
|
||||
[reducer, setState]
|
||||
)
|
||||
|
||||
return React.useMemo(() => [overriddenState, reducedSetState], [
|
||||
overriddenState,
|
||||
reducedSetState,
|
||||
])
|
||||
}
|
||||
+2
-2
@@ -1,8 +1,7 @@
|
||||
import * as utils from './utils'
|
||||
export { utils }
|
||||
export { defaultColumn } from './utils'
|
||||
export { useTable } from './hooks/useTable'
|
||||
export { useTableState, defaultState } from './hooks/useTableState'
|
||||
export { useTable, defaultState } from './hooks/useTable'
|
||||
export { useExpanded } from './plugin-hooks/useExpanded'
|
||||
export { useFilters } from './plugin-hooks/useFilters'
|
||||
export { useGroupBy } from './plugin-hooks/useGroupBy'
|
||||
@@ -11,6 +10,7 @@ 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 { useResizeColumns } from './plugin-hooks/useResizeColumns'
|
||||
export { useAbsoluteLayout } from './plugin-hooks/useAbsoluteLayout'
|
||||
export { useBlockLayout } from './plugin-hooks/useBlockLayout'
|
||||
export { actions, addActions } from './actions'
|
||||
|
||||
@@ -8,7 +8,7 @@ exports[`renders a table 1`] = `
|
||||
<div>
|
||||
<div
|
||||
class="row"
|
||||
style="display: block; width: 1400px;"
|
||||
style="display: flex; width: 1400px;"
|
||||
>
|
||||
<div
|
||||
class="cell header"
|
||||
@@ -27,7 +27,7 @@ exports[`renders a table 1`] = `
|
||||
</div>
|
||||
<div
|
||||
class="row"
|
||||
style="display: block; width: 1400px;"
|
||||
style="display: flex; width: 1400px;"
|
||||
>
|
||||
<div
|
||||
class="cell header"
|
||||
@@ -78,7 +78,7 @@ exports[`renders a table 1`] = `
|
||||
>
|
||||
<div
|
||||
class="row"
|
||||
style="display: block; width: 1400px;"
|
||||
style="display: flex; width: 1400px;"
|
||||
>
|
||||
<div
|
||||
class="cell"
|
||||
@@ -119,7 +119,7 @@ exports[`renders a table 1`] = `
|
||||
</div>
|
||||
<div
|
||||
class="row"
|
||||
style="display: block; width: 1400px;"
|
||||
style="display: flex; width: 1400px;"
|
||||
>
|
||||
<div
|
||||
class="cell"
|
||||
@@ -160,7 +160,7 @@ exports[`renders a table 1`] = `
|
||||
</div>
|
||||
<div
|
||||
class="row"
|
||||
style="display: block; width: 1400px;"
|
||||
style="display: flex; width: 1400px;"
|
||||
>
|
||||
<div
|
||||
class="cell"
|
||||
|
||||
@@ -485,8 +485,8 @@ Snapshot Diff:
|
||||
<pre>
|
||||
<code>
|
||||
{
|
||||
- "selectedRows": []
|
||||
+ "selectedRows": [
|
||||
- "selectedRowPaths": []
|
||||
+ "selectedRowPaths": [
|
||||
+ "0",
|
||||
+ "1",
|
||||
+ "2",
|
||||
@@ -1015,7 +1015,7 @@ Snapshot Diff:
|
||||
<pre>
|
||||
<code>
|
||||
{
|
||||
- "selectedRows": [
|
||||
- "selectedRowPaths": [
|
||||
- "0",
|
||||
- "1",
|
||||
- "2",
|
||||
@@ -1053,7 +1053,7 @@ Snapshot Diff:
|
||||
- "22.1",
|
||||
- "23"
|
||||
- ]
|
||||
+ "selectedRows": []
|
||||
+ "selectedRowPaths": []
|
||||
}
|
||||
</code>
|
||||
</pre>
|
||||
@@ -1129,8 +1129,8 @@ Snapshot Diff:
|
||||
<pre>
|
||||
<code>
|
||||
{
|
||||
- "selectedRows": []
|
||||
+ "selectedRows": [
|
||||
- "selectedRowPaths": []
|
||||
+ "selectedRowPaths": [
|
||||
+ "0",
|
||||
+ "2",
|
||||
+ "2.0",
|
||||
@@ -1198,7 +1198,7 @@ Snapshot Diff:
|
||||
<pre>
|
||||
<code>
|
||||
{
|
||||
"selectedRows": [
|
||||
"selectedRowPaths": [
|
||||
- "0",
|
||||
- "2",
|
||||
- "2.0",
|
||||
@@ -1241,7 +1241,7 @@ Snapshot Diff:
|
||||
<pre>
|
||||
<code>
|
||||
{
|
||||
"selectedRows": [
|
||||
"selectedRowPaths": [
|
||||
- "0"
|
||||
+ "0",
|
||||
+ "2.0"
|
||||
@@ -1282,7 +1282,7 @@ Snapshot Diff:
|
||||
<pre>
|
||||
<code>
|
||||
{
|
||||
"selectedRows": [
|
||||
"selectedRowPaths": [
|
||||
"0",
|
||||
- "2.0"
|
||||
+ "2.0",
|
||||
@@ -1324,7 +1324,7 @@ Snapshot Diff:
|
||||
<pre>
|
||||
<code>
|
||||
{
|
||||
"selectedRows": [
|
||||
"selectedRowPaths": [
|
||||
"0",
|
||||
- "2.0",
|
||||
- "2.1"
|
||||
|
||||
@@ -52,7 +52,7 @@ function Table({ columns: userColumns, data, SubComponent }) {
|
||||
rows,
|
||||
prepareRow,
|
||||
flatColumns,
|
||||
state: [{ expanded }],
|
||||
state: { expanded },
|
||||
} = useTable(
|
||||
{
|
||||
columns: userColumns,
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import React from 'react'
|
||||
import { render, fireEvent } from '@testing-library/react'
|
||||
import { useTable } from '../../hooks/useTable'
|
||||
import { useTableState } from '../../hooks/useTableState'
|
||||
import { usePagination } from '../usePagination'
|
||||
|
||||
const data = [...new Array(100)].map((d, i) => ({
|
||||
@@ -14,8 +13,6 @@ const data = [...new Array(100)].map((d, i) => ({
|
||||
}))
|
||||
|
||||
function Table({ columns, data }) {
|
||||
const tableState = useTableState({ pageIndex: 2 })
|
||||
|
||||
const {
|
||||
getTableProps,
|
||||
getTableBodyProps,
|
||||
@@ -30,12 +27,12 @@ function Table({ columns, data }) {
|
||||
nextPage,
|
||||
previousPage,
|
||||
setPageSize,
|
||||
state: [{ pageIndex, pageSize }],
|
||||
state: { pageIndex, pageSize },
|
||||
} = useTable(
|
||||
{
|
||||
columns,
|
||||
data,
|
||||
state: tableState,
|
||||
initialState: { pageIndex: 2 },
|
||||
},
|
||||
usePagination
|
||||
)
|
||||
|
||||
@@ -75,7 +75,7 @@ function Table({ columns, data }) {
|
||||
headerGroups,
|
||||
rows,
|
||||
prepareRow,
|
||||
state: [{ selectedRows }],
|
||||
state: { selectedRowPaths },
|
||||
} = useTable(
|
||||
{
|
||||
columns,
|
||||
@@ -113,9 +113,9 @@ function Table({ columns, data }) {
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
<p>Selected Rows: {selectedRows.length}</p>
|
||||
<p>Selected Rows: {selectedRowPaths.length}</p>
|
||||
<pre>
|
||||
<code>{JSON.stringify({ selectedRows }, null, 2)}</code>
|
||||
<code>{JSON.stringify({ selectedRowPaths }, null, 2)}</code>
|
||||
</pre>
|
||||
</>
|
||||
)
|
||||
|
||||
@@ -18,7 +18,7 @@ const useMain = instance => {
|
||||
|
||||
const rowStyles = {
|
||||
style: {
|
||||
display: 'block',
|
||||
display: 'flex',
|
||||
width: `${totalColumnsWidth}px`,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import React from 'react'
|
||||
import PropTypes from 'prop-types'
|
||||
|
||||
import { addActions, actions } from '../actions'
|
||||
import { defaultState } from '../hooks/useTableState'
|
||||
import { defaultState } from '../hooks/useTable'
|
||||
|
||||
defaultState.columnOrder = []
|
||||
|
||||
@@ -14,7 +14,7 @@ const propTypes = {
|
||||
|
||||
export const useColumnOrder = hooks => {
|
||||
hooks.columnsBeforeHeaderGroupsDeps.push((deps, instance) => {
|
||||
return [...deps, instance.state[0].columnOrder]
|
||||
return [...deps, instance.state.columnOrder]
|
||||
})
|
||||
hooks.columnsBeforeHeaderGroups.push(columnsBeforeHeaderGroups)
|
||||
hooks.useMain.push(useMain)
|
||||
@@ -24,7 +24,7 @@ useColumnOrder.pluginName = 'useColumnOrder'
|
||||
|
||||
function columnsBeforeHeaderGroups(columns, instance) {
|
||||
const {
|
||||
state: [{ columnOrder }],
|
||||
state: { columnOrder },
|
||||
} = instance
|
||||
|
||||
// If there is no order, return the normal columns
|
||||
@@ -56,9 +56,7 @@ function columnsBeforeHeaderGroups(columns, instance) {
|
||||
function useMain(instance) {
|
||||
PropTypes.checkPropTypes(propTypes, instance, 'property', 'useColumnOrder')
|
||||
|
||||
const {
|
||||
state: [, setState],
|
||||
} = instance
|
||||
const { setState } = instance
|
||||
|
||||
const setColumnOrder = React.useCallback(
|
||||
updater => {
|
||||
|
||||
@@ -3,7 +3,7 @@ import PropTypes from 'prop-types'
|
||||
|
||||
import { mergeProps, applyPropHooks, expandRows } from '../utils'
|
||||
import { addActions, actions } from '../actions'
|
||||
import { defaultState } from '../hooks/useTableState'
|
||||
import { defaultState } from '../hooks/useTable'
|
||||
|
||||
defaultState.expanded = []
|
||||
|
||||
@@ -29,8 +29,10 @@ function useMain(instance) {
|
||||
rows,
|
||||
manualExpandedKey = 'expanded',
|
||||
paginateExpandedRows = true,
|
||||
expandSubRows = true,
|
||||
hooks,
|
||||
state: [{ expanded }, setState],
|
||||
state: { expanded },
|
||||
setState,
|
||||
} = instance
|
||||
|
||||
const toggleExpandedByPath = (path, set) => {
|
||||
@@ -82,11 +84,18 @@ function useMain(instance) {
|
||||
console.info('getExpandedRows')
|
||||
|
||||
if (paginateExpandedRows) {
|
||||
return expandRows(rows, { manualExpandedKey, expanded })
|
||||
return expandRows(rows, { manualExpandedKey, expanded, expandSubRows })
|
||||
}
|
||||
|
||||
return rows
|
||||
}, [debug, paginateExpandedRows, rows, manualExpandedKey, expanded])
|
||||
}, [
|
||||
debug,
|
||||
paginateExpandedRows,
|
||||
rows,
|
||||
manualExpandedKey,
|
||||
expanded,
|
||||
expandSubRows,
|
||||
])
|
||||
|
||||
const expandedDepth = findExpandedDepth(expanded)
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import PropTypes from 'prop-types'
|
||||
import { getFirstDefined, isFunction } from '../utils'
|
||||
import * as filterTypes from '../filterTypes'
|
||||
import { addActions, actions } from '../actions'
|
||||
import { defaultState } from '../hooks/useTableState'
|
||||
import { defaultState } from '../hooks/useTable'
|
||||
|
||||
defaultState.filters = {}
|
||||
|
||||
@@ -33,14 +33,17 @@ function useMain(instance) {
|
||||
const {
|
||||
debug,
|
||||
rows,
|
||||
flatRows,
|
||||
flatColumns,
|
||||
filterTypes: userFilterTypes,
|
||||
manualFilters,
|
||||
disableFilters,
|
||||
state: [{ filters }, setState],
|
||||
state: { filters },
|
||||
setState,
|
||||
} = instance
|
||||
|
||||
const preFilteredRows = rows
|
||||
const preFilteredFlatRows = flatRows
|
||||
|
||||
const setFilter = (id, updater) => {
|
||||
const column = flatColumns.find(d => d.id === id)
|
||||
@@ -129,11 +132,16 @@ function useMain(instance) {
|
||||
// cache for each row group (top-level rows, and each row's recursive subrows)
|
||||
// This would make multi-filtering a lot faster though. Too far?
|
||||
|
||||
const filteredRows = React.useMemo(() => {
|
||||
const { filteredRows, filteredFlatRows } = React.useMemo(() => {
|
||||
if (manualFilters || !Object.keys(filters).length) {
|
||||
return rows
|
||||
return {
|
||||
filteredRows: rows,
|
||||
filteredFlatRows: flatRows,
|
||||
}
|
||||
}
|
||||
|
||||
const filteredFlatRows = []
|
||||
|
||||
if (process.env.NODE_ENV === 'development' && debug)
|
||||
console.info('getFilteredRows')
|
||||
|
||||
@@ -169,7 +177,14 @@ function useMain(instance) {
|
||||
|
||||
// Pass the rows, id, filterValue and column to the filterMethod
|
||||
// to get the filtered rows back
|
||||
return filterMethod(filteredSoFar, columnID, filterValue, column)
|
||||
column.filteredRows = filterMethod(
|
||||
filteredSoFar,
|
||||
columnID,
|
||||
filterValue,
|
||||
column
|
||||
)
|
||||
|
||||
return column.filteredRows
|
||||
},
|
||||
rows
|
||||
)
|
||||
@@ -179,6 +194,7 @@ function useMain(instance) {
|
||||
// but that would severely hinder the API for the user, since they
|
||||
// would be required to do that recursion in some scenarios
|
||||
filteredRows = filteredRows.map(row => {
|
||||
filteredFlatRows.push(row)
|
||||
if (!row.subRows) {
|
||||
return row
|
||||
}
|
||||
@@ -194,8 +210,19 @@ function useMain(instance) {
|
||||
return filteredRows
|
||||
}
|
||||
|
||||
return filterRows(rows)
|
||||
}, [manualFilters, filters, debug, rows, flatColumns, userFilterTypes])
|
||||
return {
|
||||
filteredRows: filterRows(rows),
|
||||
filteredFlatRows,
|
||||
}
|
||||
}, [
|
||||
manualFilters,
|
||||
filters,
|
||||
debug,
|
||||
rows,
|
||||
flatRows,
|
||||
flatColumns,
|
||||
userFilterTypes,
|
||||
])
|
||||
|
||||
React.useMemo(() => {
|
||||
// Now that each filtered column has it's partially filtered rows,
|
||||
@@ -208,6 +235,7 @@ function useMain(instance) {
|
||||
// using every column's preFilteredRows value
|
||||
nonFilteredColumns.forEach(column => {
|
||||
column.preFilteredRows = filteredRows
|
||||
column.filteredRows = filteredRows
|
||||
})
|
||||
}, [filteredRows, filters, flatColumns])
|
||||
|
||||
@@ -216,7 +244,9 @@ function useMain(instance) {
|
||||
setFilter,
|
||||
setAllFilters,
|
||||
preFilteredRows,
|
||||
preFilteredFlatRows,
|
||||
rows: filteredRows,
|
||||
flatRows: filteredFlatRows,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import PropTypes from 'prop-types'
|
||||
|
||||
import * as aggregations from '../aggregations'
|
||||
import { addActions, actions } from '../actions'
|
||||
import { defaultState } from '../hooks/useTableState'
|
||||
import { defaultState } from '../hooks/useTable'
|
||||
import {
|
||||
mergeProps,
|
||||
applyPropHooks,
|
||||
@@ -40,7 +40,7 @@ const propTypes = {
|
||||
export const useGroupBy = hooks => {
|
||||
hooks.columnsBeforeHeaderGroups.push(columnsBeforeHeaderGroups)
|
||||
hooks.columnsBeforeHeaderGroupsDeps.push((deps, instance) => {
|
||||
deps.push(instance.state[0].groupBy)
|
||||
deps.push(instance.state.groupBy)
|
||||
return deps
|
||||
})
|
||||
hooks.useMain.push(useMain)
|
||||
@@ -48,7 +48,7 @@ export const useGroupBy = hooks => {
|
||||
|
||||
useGroupBy.pluginName = 'useGroupBy'
|
||||
|
||||
function columnsBeforeHeaderGroups(flatColumns, { state: [{ groupBy }] }) {
|
||||
function columnsBeforeHeaderGroups(flatColumns, { state: { groupBy } }) {
|
||||
// Sort grouped columns to the start of the column list
|
||||
// before the headers are built
|
||||
|
||||
@@ -80,7 +80,8 @@ function useMain(instance) {
|
||||
aggregations: userAggregations = {},
|
||||
hooks,
|
||||
plugins,
|
||||
state: [{ groupBy }, setState],
|
||||
state: { groupBy },
|
||||
setState,
|
||||
} = instance
|
||||
|
||||
ensurePluginOrder(plugins, [], 'useGroupBy', ['useSortBy', 'useExpanded'])
|
||||
|
||||
@@ -3,7 +3,7 @@ import PropTypes from 'prop-types'
|
||||
|
||||
//
|
||||
import { addActions, actions } from '../actions'
|
||||
import { defaultState } from '../hooks/useTableState'
|
||||
import { defaultState } from '../hooks/useTable'
|
||||
import { ensurePluginOrder, safeUseLayoutEffect, expandRows } from '../utils'
|
||||
|
||||
defaultState.pageSize = 10
|
||||
@@ -36,10 +36,9 @@ function useMain(instance) {
|
||||
plugins,
|
||||
pageCount: userPageCount,
|
||||
paginateExpandedRows = true,
|
||||
state: [
|
||||
{ pageSize, pageIndex, filters, groupBy, sortBy, expanded },
|
||||
setState,
|
||||
],
|
||||
expandSubRows = true,
|
||||
state: { pageSize, pageIndex, filters, groupBy, sortBy, expanded },
|
||||
setState,
|
||||
} = instance
|
||||
|
||||
ensurePluginOrder(
|
||||
@@ -101,9 +100,10 @@ function useMain(instance) {
|
||||
return page
|
||||
}
|
||||
|
||||
return expandRows(page, { manualExpandedKey, expanded })
|
||||
return expandRows(page, { manualExpandedKey, expanded, expandSubRows })
|
||||
}, [
|
||||
debug,
|
||||
expandSubRows,
|
||||
expanded,
|
||||
manualExpandedKey,
|
||||
manualPagination,
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
import PropTypes from 'prop-types'
|
||||
|
||||
//
|
||||
|
||||
import { defaultState } from '../hooks/useTable'
|
||||
import { defaultColumn, getFirstDefined } from '../utils'
|
||||
import { mergeProps, applyPropHooks } from '../utils'
|
||||
|
||||
defaultState.columnResizing = {
|
||||
columnWidths: {},
|
||||
}
|
||||
|
||||
defaultColumn.canResize = true
|
||||
|
||||
const propTypes = {}
|
||||
|
||||
export const useResizeColumns = hooks => {
|
||||
hooks.useBeforeDimensions.push(useBeforeDimensions)
|
||||
}
|
||||
|
||||
useResizeColumns.pluginName = 'useResizeColumns'
|
||||
|
||||
const useBeforeDimensions = instance => {
|
||||
PropTypes.checkPropTypes(propTypes, instance, 'property', 'useResizeColumns')
|
||||
|
||||
instance.hooks.getResizerProps = []
|
||||
|
||||
const {
|
||||
flatHeaders,
|
||||
disableResizing,
|
||||
hooks: { getHeaderProps },
|
||||
state: { columnResizing },
|
||||
setState,
|
||||
} = instance
|
||||
|
||||
getHeaderProps.push(() => {
|
||||
return {
|
||||
style: {
|
||||
position: 'relative',
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
const onMouseDown = (e, header) => {
|
||||
const headersToResize = getLeafHeaders(header)
|
||||
const startWidths = headersToResize.map(header => header.totalWidth)
|
||||
const startX = e.clientX
|
||||
|
||||
const onMouseMove = e => {
|
||||
const currentX = e.clientX
|
||||
const deltaX = currentX - startX
|
||||
|
||||
const percentageDeltaX = deltaX / headersToResize.length
|
||||
|
||||
const newColumnWidths = {}
|
||||
headersToResize.forEach((header, index) => {
|
||||
newColumnWidths[header.id] = Math.max(
|
||||
startWidths[index] + percentageDeltaX,
|
||||
0
|
||||
)
|
||||
})
|
||||
|
||||
setState(old => ({
|
||||
...old,
|
||||
columnResizing: {
|
||||
...old.columnResizing,
|
||||
columnWidths: {
|
||||
...old.columnResizing.columnWidths,
|
||||
...newColumnWidths,
|
||||
},
|
||||
},
|
||||
}))
|
||||
}
|
||||
|
||||
const onMouseUp = e => {
|
||||
document.removeEventListener('mousemove', onMouseMove)
|
||||
document.removeEventListener('mouseup', onMouseUp)
|
||||
|
||||
setState(old => ({
|
||||
...old,
|
||||
columnResizing: {
|
||||
...old.columnResizing,
|
||||
startX: null,
|
||||
isResizingColumn: null,
|
||||
},
|
||||
}))
|
||||
}
|
||||
|
||||
document.addEventListener('mousemove', onMouseMove)
|
||||
document.addEventListener('mouseup', onMouseUp)
|
||||
|
||||
setState(old => ({
|
||||
...old,
|
||||
columnResizing: {
|
||||
...old.columnResizing,
|
||||
startX,
|
||||
isResizingColumn: header.id,
|
||||
},
|
||||
}))
|
||||
}
|
||||
|
||||
flatHeaders.forEach(header => {
|
||||
const canResize = getFirstDefined(
|
||||
header.disableResizing === true ? false : undefined,
|
||||
disableResizing === true ? false : undefined,
|
||||
true
|
||||
)
|
||||
|
||||
header.canResize = canResize
|
||||
header.width = columnResizing.columnWidths[header.id] || header.width
|
||||
header.isResizing = columnResizing.isResizingColumn === header.id
|
||||
|
||||
if (canResize) {
|
||||
header.getResizerProps = userProps => {
|
||||
return mergeProps(
|
||||
{
|
||||
onMouseDown: e => e.persist() || onMouseDown(e, header),
|
||||
style: {
|
||||
cursor: 'ew-resize',
|
||||
},
|
||||
draggable: false,
|
||||
},
|
||||
applyPropHooks(instance.hooks.getResizerProps, header, instance),
|
||||
userProps
|
||||
)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
return instance
|
||||
}
|
||||
|
||||
function getLeafHeaders(header) {
|
||||
const leafHeaders = []
|
||||
const recurseHeader = header => {
|
||||
if (header.columns && header.columns.length) {
|
||||
header.columns.map(recurseHeader)
|
||||
}
|
||||
leafHeaders.push(header)
|
||||
}
|
||||
recurseHeader(header)
|
||||
return leafHeaders
|
||||
}
|
||||
@@ -1,10 +1,16 @@
|
||||
import React from 'react'
|
||||
import PropTypes from 'prop-types'
|
||||
|
||||
import { mergeProps, applyPropHooks, ensurePluginOrder } from '../utils'
|
||||
import {
|
||||
mergeProps,
|
||||
applyPropHooks,
|
||||
ensurePluginOrder,
|
||||
safeUseLayoutEffect,
|
||||
} from '../utils'
|
||||
import { addActions, actions } from '../actions'
|
||||
import { defaultState } from '../hooks/useTableState'
|
||||
import { defaultState } from '../hooks/useTable'
|
||||
|
||||
defaultState.selectedRows = []
|
||||
defaultState.selectedRowPaths = []
|
||||
|
||||
addActions('toggleRowSelected', 'toggleRowSelectedAll')
|
||||
|
||||
@@ -15,20 +21,53 @@ const propTypes = {
|
||||
export const useRowSelect = hooks => {
|
||||
hooks.getToggleRowSelectedProps = []
|
||||
hooks.getToggleAllRowsSelectedProps = []
|
||||
hooks.useRows.push(useRows)
|
||||
hooks.useMain.push(useMain)
|
||||
}
|
||||
|
||||
useRowSelect.pluginName = 'useRowSelect'
|
||||
|
||||
function useRows(rows, instance) {
|
||||
PropTypes.checkPropTypes(propTypes, instance, 'property', 'useRowSelect')
|
||||
|
||||
const {
|
||||
state: { selectedRowPaths },
|
||||
} = instance
|
||||
|
||||
instance.selectedFlatRows = React.useMemo(() => {
|
||||
const selectedFlatRows = []
|
||||
rows.forEach(row => {
|
||||
if (row.isAggregated) {
|
||||
const subRowPaths = row.subRows.map(row => row.path)
|
||||
row.isSelected = subRowPaths.every(path =>
|
||||
selectedRowPaths.includes(path.join('.'))
|
||||
)
|
||||
} else {
|
||||
row.isSelected = selectedRowPaths.includes(row.path.join('.'))
|
||||
}
|
||||
if (row.isSelected) {
|
||||
selectedFlatRows.push(row)
|
||||
}
|
||||
})
|
||||
|
||||
return selectedFlatRows
|
||||
}, [rows, selectedRowPaths])
|
||||
|
||||
return rows
|
||||
}
|
||||
|
||||
function useMain(instance) {
|
||||
PropTypes.checkPropTypes(propTypes, instance, 'property', 'useRowSelect')
|
||||
|
||||
const {
|
||||
hooks,
|
||||
manualRowSelectedKey = 'isSelected',
|
||||
disableSelectedRowsResetOnDataChange,
|
||||
plugins,
|
||||
rowPaths,
|
||||
state: [{ selectedRows }, setState],
|
||||
flatRows,
|
||||
data,
|
||||
state: { selectedRowPaths },
|
||||
setState,
|
||||
} = instance
|
||||
|
||||
ensurePluginOrder(
|
||||
@@ -38,34 +77,66 @@ function useMain(instance) {
|
||||
[]
|
||||
)
|
||||
|
||||
const isAllRowsSelected = rowPaths.length > 0 && rowPaths.length === selectedRows.length
|
||||
const flatRowPaths = flatRows.map(d => d.path.join('.'))
|
||||
|
||||
let isAllRowsSelected = !!flatRowPaths.length && !!selectedRowPaths.length
|
||||
|
||||
if (isAllRowsSelected) {
|
||||
if (flatRowPaths.some(d => !selectedRowPaths.includes(d))) {
|
||||
isAllRowsSelected = false
|
||||
}
|
||||
}
|
||||
|
||||
const isRowSelectedMountedRef = React.useRef()
|
||||
|
||||
// Bypass any effects from firing when this changes
|
||||
const disableSelectedRowsResetOnDataChangeRef = React.useRef()
|
||||
disableSelectedRowsResetOnDataChangeRef.current = disableSelectedRowsResetOnDataChange
|
||||
|
||||
safeUseLayoutEffect(() => {
|
||||
if (
|
||||
isRowSelectedMountedRef.current &&
|
||||
!disableSelectedRowsResetOnDataChangeRef.current
|
||||
) {
|
||||
setState(
|
||||
old => ({
|
||||
...old,
|
||||
selectedRowPaths: [],
|
||||
}),
|
||||
actions.pageChange
|
||||
)
|
||||
}
|
||||
isRowSelectedMountedRef.current = true
|
||||
}, [setState, data])
|
||||
|
||||
const toggleRowSelectedAll = set => {
|
||||
setState(old => {
|
||||
const selectAll = typeof set !== 'undefined' ? set : !isAllRowsSelected
|
||||
return {
|
||||
...old,
|
||||
selectedRows: selectAll ? [...rowPaths] : [],
|
||||
selectedRowPaths: selectAll ? flatRowPaths : [],
|
||||
}
|
||||
}, actions.toggleRowSelectedAll)
|
||||
}
|
||||
|
||||
const updateParentRow = (selectedRows, path) => {
|
||||
const updateParentRow = (selectedRowPaths, path) => {
|
||||
const parentPath = path.slice(0, path.length - 1)
|
||||
const parentKey = parentPath.join('.')
|
||||
const selected =
|
||||
rowPaths.filter(
|
||||
path =>
|
||||
flatRowPaths.filter(rowPath => {
|
||||
const path = rowPath
|
||||
return (
|
||||
path !== parentKey &&
|
||||
path.startsWith(parentKey) &&
|
||||
!selectedRows.has(path)
|
||||
).length === 0
|
||||
!selectedRowPaths.has(path)
|
||||
)
|
||||
}).length === 0
|
||||
if (selected) {
|
||||
selectedRows.add(parentKey)
|
||||
selectedRowPaths.add(parentKey)
|
||||
} else {
|
||||
selectedRows.delete(parentKey)
|
||||
selectedRowPaths.delete(parentKey)
|
||||
}
|
||||
if (parentPath.length > 1) updateParentRow(selectedRows, parentPath)
|
||||
if (parentPath.length > 1) updateParentRow(selectedRowPaths, parentPath)
|
||||
}
|
||||
|
||||
const toggleRowSelected = (path, set) => {
|
||||
@@ -76,18 +147,18 @@ function useMain(instance) {
|
||||
// Join the paths of deep rows
|
||||
// to make a key, then manage all of the keys
|
||||
// in a flat object
|
||||
const exists = old.selectedRows.includes(key)
|
||||
const exists = old.selectedRowPaths.includes(key)
|
||||
const shouldExist = typeof set !== 'undefined' ? set : !exists
|
||||
let newSelectedRows = new Set(old.selectedRows)
|
||||
let newSelectedRows = new Set(old.selectedRowPaths)
|
||||
|
||||
if (!exists && shouldExist) {
|
||||
rowPaths.forEach(rowPath => {
|
||||
flatRowPaths.forEach(rowPath => {
|
||||
if (rowPath === key || rowPath.startsWith(childRowPrefixKey)) {
|
||||
newSelectedRows.add(rowPath)
|
||||
}
|
||||
})
|
||||
} else if (exists && !shouldExist) {
|
||||
rowPaths.forEach(rowPath => {
|
||||
flatRowPaths.forEach(rowPath => {
|
||||
if (rowPath === key || rowPath.startsWith(childRowPrefixKey)) {
|
||||
newSelectedRows.delete(rowPath)
|
||||
}
|
||||
@@ -102,7 +173,7 @@ function useMain(instance) {
|
||||
|
||||
return {
|
||||
...old,
|
||||
selectedRows: [...newSelectedRows.values()],
|
||||
selectedRowPaths: [...newSelectedRows.values()],
|
||||
}
|
||||
}, actions.toggleRowSelected)
|
||||
}
|
||||
@@ -128,9 +199,6 @@ function useMain(instance) {
|
||||
// Aggregate rows have entirely different select logic
|
||||
if (row.isAggregated) {
|
||||
const subRowPaths = row.subRows.map(row => row.path)
|
||||
row.isSelected = subRowPaths.every(path =>
|
||||
selectedRows.includes(path.join('.'))
|
||||
)
|
||||
row.toggleRowSelected = set => {
|
||||
set = typeof set !== 'undefined' ? set : !row.isSelected
|
||||
subRowPaths.forEach(path => {
|
||||
@@ -166,7 +234,6 @@ function useMain(instance) {
|
||||
)
|
||||
}
|
||||
} else {
|
||||
row.isSelected = selectedRows.includes(row.path.join('.'))
|
||||
row.toggleRowSelected = set => toggleRowSelected(row.path, set)
|
||||
row.getToggleRowSelectedProps = props => {
|
||||
let checked = false
|
||||
|
||||
@@ -2,7 +2,7 @@ import React from 'react'
|
||||
import PropTypes from 'prop-types'
|
||||
|
||||
import { addActions, actions } from '../actions'
|
||||
import { defaultState } from '../hooks/useTableState'
|
||||
import { defaultState } from '../hooks/useTable'
|
||||
|
||||
defaultState.rowState = {}
|
||||
|
||||
@@ -25,7 +25,8 @@ function useMain(instance) {
|
||||
hooks,
|
||||
rows,
|
||||
initialRowStateAccessor,
|
||||
state: [{ rowState }, setState],
|
||||
state: { rowState },
|
||||
setState,
|
||||
} = instance
|
||||
|
||||
const setRowState = React.useCallback(
|
||||
|
||||
@@ -3,7 +3,7 @@ import PropTypes from 'prop-types'
|
||||
|
||||
import { ensurePluginOrder, defaultColumn } from '../utils'
|
||||
import { addActions, actions } from '../actions'
|
||||
import { defaultState } from '../hooks/useTableState'
|
||||
import { defaultState } from '../hooks/useTable'
|
||||
import * as sortTypes from '../sortTypes'
|
||||
import {
|
||||
mergeProps,
|
||||
@@ -63,7 +63,8 @@ function useMain(instance) {
|
||||
maxMultiSortColCount = Number.MAX_SAFE_INTEGER,
|
||||
flatHeaders,
|
||||
hooks,
|
||||
state: [{ sortBy }, setState],
|
||||
state: { sortBy },
|
||||
setState,
|
||||
plugins,
|
||||
} = instance
|
||||
|
||||
|
||||
+5
-2
@@ -402,7 +402,10 @@ This usually means you need to need to name your plugin hook by setting the 'plu
|
||||
})
|
||||
}
|
||||
|
||||
export function expandRows(rows, { manualExpandedKey, expanded }) {
|
||||
export function expandRows(
|
||||
rows,
|
||||
{ manualExpandedKey, expanded, expandSubRows = true }
|
||||
) {
|
||||
const expandedRows = []
|
||||
|
||||
const handleRow = row => {
|
||||
@@ -416,7 +419,7 @@ export function expandRows(rows, { manualExpandedKey, expanded }) {
|
||||
|
||||
expandedRows.push(row)
|
||||
|
||||
if (row.subRows && row.subRows.length && row.isExpanded) {
|
||||
if (expandSubRows && row.subRows && row.subRows.length && row.isExpanded) {
|
||||
row.subRows.forEach(handleRow)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user