mirror of
https://github.com/gosticks/react-table.git
synced 2026-10-04 14:56:59 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
163233a487 |
@@ -1,6 +1,4 @@
|
||||

|
||||
|
||||
<img src='https://github.com/tannerlinsley/react-table/raw/master/media/logo.png' width='300'/>
|
||||
# React Table
|
||||
|
||||
Hooks for building **lightweight, fast and extendable datagrids** for React
|
||||
|
||||
@@ -48,8 +46,7 @@ Hooks for building **lightweight, fast and extendable datagrids** for React
|
||||
- [Concepts](./docs/concepts.md) - Read how React Table works and how you can use it better
|
||||
- [Examples](./docs/examples.md) - Experience and learn from some examples and guides of how to use React Table and implement common patterns
|
||||
- [API](./docs/api.md) - Get to know React Table's API, how to use it and how to extend its functionality
|
||||
- [Contributing](./CONTRIBUTING.md) - Become familiar with how to contribute back to React Table
|
||||
- [Code of Conduct](./CODE_OF_CONDUCT.md) - Be a good React Table citizen by following these repository rules
|
||||
- [Contributing](./CONTRIBUTORS.md) - Become familiar with how to contribute back to React Table
|
||||
|
||||
## Sponsors
|
||||
|
||||
@@ -65,12 +62,7 @@ Hooks for building **lightweight, fast and extendable datagrids** for React
|
||||
</td>
|
||||
<td align="center" valign="middle">
|
||||
<a href="https://tryretool.com/?utm_source=sponsor&utm_campaign=react_table" target="_blank">
|
||||
<img width='350' src="https://raw.githubusercontent.com/tannerlinsley/files/master/images/patreon/sponsor-retool.png">
|
||||
</a>
|
||||
</td>
|
||||
<td align="center" valign="middle">
|
||||
<a href="http://bjntech.com/index.html&utm_campaign=react_table" target="_blank">
|
||||
<img width='250' src="https://raw.githubusercontent.com/tannerlinsley/files/master/images/patreon/sponsor-bjn.png">
|
||||
<img width='480' src="https://raw.githubusercontent.com/tannerlinsley/files/master/images/patreon/sponsor-retool.png">
|
||||
</a>
|
||||
</td>
|
||||
</tr>
|
||||
@@ -125,6 +117,7 @@ Hooks for building **lightweight, fast and extendable datagrids** for React
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<div>Nicholas Kaufmann</div>
|
||||
<div><a href="https://www.metso.com/">Pekka</a></div>
|
||||
<div>Jon Eickmeier</div>
|
||||
</td>
|
||||
|
||||
+29
-42
@@ -143,17 +143,14 @@ The following options are supported on any column object you can pass to `column
|
||||
|
||||
The following properties are available on the table instance returned from `useTable`
|
||||
|
||||
- `headers[] Array<Column>`
|
||||
- A **nested** array of final column objects, similar in structure to the original columns configuration option.
|
||||
- See [Column Properties](#column-properties) for more information
|
||||
- `columns: Array<Column>`
|
||||
- A **flat** array of all final column objects computed from the original columns configuration option.
|
||||
- See [Column Properties](#column-properties) for more information
|
||||
- `headerGroups: Array<HeaderGroup>`
|
||||
- An array of normalized header groups, each containing a flattened array of final column objects for that row.
|
||||
- See [Header Group Properties](#headergroup-properties) for more information
|
||||
- `flatHeaders[] Array<Column>`
|
||||
- A **flat** array of final header objects found in each header group. Columns may be duplicated (if columns are not adjacent)
|
||||
- `columns: Array<Column>`
|
||||
- A **flat** array of all final column objects computed from the original columns configuration option.
|
||||
- See [Column Properties](#column-properties) for more information
|
||||
- `headers[] Array<Column>`
|
||||
- A **nested** array of final column objects, similar in structure to the original columns configuration option.
|
||||
- See [Column Properties](#column-properties) for more information
|
||||
- `rows: Array<Row>`
|
||||
- An array of **materialized row objects** from the original `data` array and `columns` passed into the table options
|
||||
@@ -201,7 +198,7 @@ The following properties are available on every `Column` object returned by the
|
||||
|
||||
- `id: String`
|
||||
- The resolved column ID from either the column's `accessor` or the column's hard-coded `id` property
|
||||
- `isVisible: Boolean`
|
||||
- `visible: Boolean`
|
||||
- The resolved visible state for the column, derived from the column's `show` property
|
||||
- `render: Function(type: String | Function | Component, ?props)`
|
||||
- This function is used to render content with the added context of a column.
|
||||
@@ -405,13 +402,12 @@ The following options are supported on any `Column` object passed to the `column
|
||||
- If set to `true`, the underlying sorting direction will be inverted, but the UI will not.
|
||||
- This may be useful in situations where positive and negative connotation is inverted, eg. a Golfing score where a lower score is considered more positive than a higher one.
|
||||
- `sortType: String | Function`
|
||||
- Used to compare 2 rows of data and order them correctly.
|
||||
- If a **function** is passed, it must be **memoized**
|
||||
- Defaults to [`alphanumeric`](TODO)
|
||||
- The resolved function from the this string/function will be used to sort the this column's data.
|
||||
- If a `string` is passed, the function with that name located on either the custom `sortTypes` option or the built-in sorting types object will be used. If
|
||||
- If a `function` is passed, it will be used.
|
||||
- For more information on sort types, see [Sorting](TODO)
|
||||
- For mor information on sort types, see [Sorting](TODO)
|
||||
|
||||
### Instance Properties
|
||||
|
||||
@@ -524,7 +520,7 @@ The following options are supported via the main options object passed to `useTa
|
||||
- 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 mor information on filter types, see [Filtering](TODO)
|
||||
- `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)
|
||||
@@ -533,7 +529,7 @@ The following options are supported via the main options object passed to `useTa
|
||||
- `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)
|
||||
- For mor information on filter types, see [Filtering](TODO)
|
||||
|
||||
### Column Options
|
||||
|
||||
@@ -553,7 +549,7 @@ The following options are supported on any `Column` object passed to the `column
|
||||
- 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 mor information on filter types, see [Filtering](TODO)
|
||||
- If a **function** is passed, it must be **memoized**
|
||||
|
||||
### Instance Properties
|
||||
@@ -692,7 +688,7 @@ The following properties are available on every `Column` object returned by the
|
||||
- `canGroupBy: Boolean`
|
||||
- If `true`, this column is able to be grouped.
|
||||
- This is resolved from the column having a valid accessor / data model, and not being manually disabled via other `useGroupBy` related options
|
||||
- `isGrouped: Boolean`
|
||||
- `grouped: Boolean`
|
||||
- If `true`, this column is currently being grouped
|
||||
- `groupedIndex: Int`
|
||||
- If this column is currently being grouped, this integer is the index of this column's ID in the table state's `groupBy` array.
|
||||
@@ -723,19 +719,17 @@ The following properties are available on every `Row` object returned by the tab
|
||||
- `path: Array<String|Int>`
|
||||
- Similar to normal `Row` objects, materialized grouping rows also have a path array. The keys inside it though are not integers like nested normal rows though. Since they are not rows that can be traced back to an original data row, they are given a unique path based on their `groupByVal`
|
||||
- If a row is a grouping row, it will have a path like `['Single']` or `['Complicated', 'Anderson']`, where `Single`, `Complicated`, and `Anderson` would all be derived from their row's `groupByVal`.
|
||||
- `isAggregated: Bool`
|
||||
- Will be `true` if the row is an aggregated row
|
||||
|
||||
### Cell Properties
|
||||
|
||||
The following additional properties are available on every `Cell` object returned in an array of `cells` on every row object.
|
||||
|
||||
- `isGrouped: Bool`
|
||||
- `grouped: Bool`
|
||||
- If `true`, this cell is a grouped cell, meaning it contains a grouping value and should usually display and expander.
|
||||
- `isRepeatedValue: Bool`
|
||||
- `repeatedValue: Bool`
|
||||
- If `true`, this cell is a repeated value cell, meaning it contains a value that is already being displayed elsewhere (usually by a parent row's cell).
|
||||
- Most of the time, this cell is not required to be displayed and can safely be hidden during rendering
|
||||
- `isAggregated: Bool`
|
||||
- `aggregated: Bool`
|
||||
- If `true`, this cell's value has been aggregated and should probably be rendered with the `Aggregated` cell renderer.
|
||||
|
||||
### Example
|
||||
@@ -924,6 +918,10 @@ The following options are supported via the main options object passed to `useTa
|
||||
- `subRowsKey: String`
|
||||
- Optional
|
||||
- See the [useTable hook](#table-options) for more details
|
||||
- `nestExpandedRows: Bool`
|
||||
- Optional
|
||||
- Defaults to `false`
|
||||
- If set to `false`, expanded rows will not be paginated. Thus, any expanded subrows would potentially increase the size of any given page by the amount of total expanded subrows on the page.
|
||||
- `manualExpandedKey: String`
|
||||
- Optional
|
||||
- Defaults to `expanded`
|
||||
@@ -1100,17 +1098,13 @@ The following options are supported via the main options object passed to `useTa
|
||||
- Defaults to `false`
|
||||
- Normally, any changes detected to `rows`, `state.filters`, `state.groupBy`, or `state.sortBy` will trigger the `pageIndex` to be reset to `0`
|
||||
- If set to `true`, the `pageIndex` will not be automatically set to `0` when these dependencies change.
|
||||
- `paginateExpandedRows: Bool`
|
||||
- Optional
|
||||
- Only applies when using the `useExpanded` plugin hook simultaneously
|
||||
- Defaults to `true`
|
||||
- If set to `true`, expanded rows are paginated along with normal rows. This results in stable page sizes across every page.
|
||||
- If set to `false`, expanded rows will be spliced in after pagination. This means that the total number of rows in a page can potentially be larger than the page size, depending on how many subrows are expanded.
|
||||
|
||||
### Instance Properties
|
||||
|
||||
The following values are provided to the table `instance`:
|
||||
|
||||
- `pages: Array<page>`
|
||||
- An array of every generated `page`, each containing its respective rows.
|
||||
- `page: Array<row>`
|
||||
- An array of rows for the **current** page, determined by the current `pageIndex` value.
|
||||
- `pageCount: Int`
|
||||
@@ -1125,7 +1119,7 @@ The following values are provided to the table `instance`:
|
||||
- If there are pages and the current `pageIndex` is less than `pageCount`, this will be `true`
|
||||
- `gotoPage: Function(pageIndex)`
|
||||
- This function, when called with a valid `pageIndex`, will set `pageIndex` to that value.
|
||||
- If the aginateassed index is outside of the valid `pageIndex` range, then this function will do nothing.
|
||||
- If the passed index is outside of the valid `pageIndex` range, then this function will do nothing.
|
||||
- `previousPage: Function`
|
||||
- This function decreases `state.pageIndex` by one.
|
||||
- If there are no pages or `canPreviousPage` is false, this function will do nothing.
|
||||
@@ -1341,7 +1335,7 @@ The following options are supported via the main options object passed to `useTa
|
||||
- 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.
|
||||
- `manualRowSelectedKey: String`
|
||||
- Optional
|
||||
- Defaults to `isSelected`
|
||||
- Defaults to `selected`
|
||||
- If this key is found on the **original** data row, and it is true, this row will be manually selected
|
||||
|
||||
### Instance Properties
|
||||
@@ -1361,20 +1355,10 @@ The following values are provided to the table `instance`:
|
||||
- `style.cursor: 'pointer'`
|
||||
- `checked: Bool`
|
||||
- `title: 'Toggle All Rows Selected'`
|
||||
- `isAllRowsSelected: Bool`
|
||||
- `allRowsSelected: Bool`
|
||||
- Will be `true` if all rows are selected.
|
||||
- If at least one row is not selected, will be `false`
|
||||
|
||||
### Row Properties
|
||||
|
||||
The following additional properties are available on every **prepared** `row` object returned by the table instance.
|
||||
|
||||
- `isSelected: Bool`
|
||||
- Will be `true` if the row is currently selected
|
||||
- `toggleRowSelected: Function(?set)`
|
||||
- Use this function to toggle this row's selected state.
|
||||
- Optionally pass `true` or `false` to set it to that state
|
||||
|
||||
### Example
|
||||
|
||||
```js
|
||||
@@ -1625,9 +1609,12 @@ export default function MyTable({ manualPageIndex }) {
|
||||
const state = useTableState(initialState, overrides)
|
||||
|
||||
// You can use effects to observe changes to the state
|
||||
React.useEffect(() => {
|
||||
console.log('Page Size Changed!', initialState.pageSize)
|
||||
}, [initialState.pageSize])
|
||||
React.useEffect(
|
||||
() => {
|
||||
console.log('Page Size Changed!', initialState.pageSize)
|
||||
},
|
||||
[initialState.pageSize]
|
||||
)
|
||||
|
||||
const { rows } = useTable({
|
||||
state,
|
||||
|
||||
@@ -28,10 +28,6 @@
|
||||
- Editable Data
|
||||
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/editable-data)
|
||||
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/editable-data)
|
||||
- **Complex**
|
||||
- The "Kitchen Sink"
|
||||
- [Source + Guide](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.
|
||||
- Pagination (Controlled)
|
||||
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/pagination-controlled)
|
||||
|
||||
@@ -1,17 +1,15 @@
|
||||
# Installation
|
||||
|
||||
Install the React Table v7 Alpha as a dependency using `npm` or `yarn`
|
||||
Install React Table as a dependency using `npm` or `yarn`
|
||||
|
||||
```bash
|
||||
# NPM
|
||||
$ npm install react-table@next
|
||||
$ npm install react-table
|
||||
|
||||
# Yarn
|
||||
$ yarn add react-table@next
|
||||
$ yarn add react-table
|
||||
```
|
||||
|
||||
> NOTE: `@next` is only required tempororarily while work on the alpha and beta versions are still shifting.
|
||||
|
||||
To import React Table:
|
||||
|
||||
```js
|
||||
|
||||
@@ -46,28 +46,20 @@ const Styles = styled.div`
|
||||
|
||||
// Create an editable cell renderer
|
||||
const EditableCell = ({
|
||||
cell: { value: initialValue },
|
||||
value: initialValue,
|
||||
row: { index },
|
||||
column: { id },
|
||||
updateMyData, // This is a custom function that we supplied to our table instance
|
||||
}) => {
|
||||
// We need to keep and update the state of the cell normally
|
||||
const [value, setValue] = React.useState(initialValue)
|
||||
|
||||
const onChange = e => {
|
||||
setValue(e.target.value)
|
||||
}
|
||||
|
||||
// We'll only update the external data when the input is blurred
|
||||
const onBlur = () => {
|
||||
updateMyData(index, id, value)
|
||||
}
|
||||
|
||||
// If the initialValue is changed externall, sync it up with our state
|
||||
React.useEffect(() => {
|
||||
setValue(initialValue)
|
||||
}, [initialValue])
|
||||
|
||||
return <input value={value} onChange={onChange} onBlur={onBlur} />
|
||||
}
|
||||
|
||||
@@ -229,7 +221,6 @@ function App() {
|
||||
)
|
||||
|
||||
const [data, setData] = React.useState(() => makeData(20))
|
||||
const [originalData] = React.useState(data)
|
||||
|
||||
// We need to keep the table from resetting the pageIndex when we
|
||||
// Update data. So we can keep track of that flag with a ref.
|
||||
@@ -241,8 +232,8 @@ function App() {
|
||||
const updateMyData = (rowIndex, columnID, value) => {
|
||||
// We also turn on the flag to not reset the page
|
||||
skipPageResetRef.current = true
|
||||
setData(old =>
|
||||
old.map((row, index) => {
|
||||
setData(old => {
|
||||
return old.filter((row, index) => {
|
||||
if (index === rowIndex) {
|
||||
return {
|
||||
...old[rowIndex],
|
||||
@@ -251,19 +242,22 @@ function App() {
|
||||
}
|
||||
return row
|
||||
})
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
// After data chagnes, we turn the flag back off
|
||||
// so that if data actually changes when we're not
|
||||
// editing it, the page is reset
|
||||
React.useEffect(() => {
|
||||
skipPageResetRef.current = false
|
||||
}, [data])
|
||||
React.useEffect(
|
||||
() => {
|
||||
skipPageResetRef.current = false
|
||||
},
|
||||
[data]
|
||||
)
|
||||
|
||||
// Let's add a data resetter/randomizer to help
|
||||
// illustrate that flow...
|
||||
const resetData = () => setData(originalData)
|
||||
const resetData = () => setData(makeData(20))
|
||||
|
||||
return (
|
||||
<Styles>
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"infiniteLoopProtection": false
|
||||
}
|
||||
@@ -36,9 +36,7 @@ const Styles = styled.div`
|
||||
`
|
||||
|
||||
// Define a default UI for filtering
|
||||
function DefaultColumnFilter({
|
||||
column: { filterValue, preFilteredRows, setFilter },
|
||||
}) {
|
||||
function DefaultColumnFilter({ filterValue, preFilteredRows, setFilter }) {
|
||||
const count = preFilteredRows.length
|
||||
|
||||
return (
|
||||
@@ -54,18 +52,19 @@ function DefaultColumnFilter({
|
||||
|
||||
// This is a custom filter UI for selecting
|
||||
// a unique option from a list
|
||||
function SelectColumnFilter({
|
||||
column: { filterValue, setFilter, preFilteredRows, id },
|
||||
}) {
|
||||
function SelectColumnFilter({ filterValue, setFilter, preFilteredRows, id }) {
|
||||
// Calculate the options for filtering
|
||||
// using the preFilteredRows
|
||||
const options = React.useMemo(() => {
|
||||
const options = new Set()
|
||||
preFilteredRows.forEach(row => {
|
||||
options.add(row.values[id])
|
||||
})
|
||||
return [...options.values()]
|
||||
}, [id, preFilteredRows])
|
||||
const options = React.useMemo(
|
||||
() => {
|
||||
const options = new Set()
|
||||
preFilteredRows.forEach(row => {
|
||||
options.add(row.values[id])
|
||||
})
|
||||
return [...options.values()]
|
||||
},
|
||||
[id, preFilteredRows]
|
||||
)
|
||||
|
||||
// Render a multi-select box
|
||||
return (
|
||||
@@ -88,21 +87,22 @@ function SelectColumnFilter({
|
||||
// This is a custom filter UI that uses a
|
||||
// slider to set the filter value between a column's
|
||||
// min and max values
|
||||
function SliderColumnFilter({
|
||||
column: { filterValue, setFilter, preFilteredRows, id },
|
||||
}) {
|
||||
function SliderColumnFilter({ filterValue, setFilter, preFilteredRows, id }) {
|
||||
// Calculate the min and max
|
||||
// using the preFilteredRows
|
||||
|
||||
const [min, max] = React.useMemo(() => {
|
||||
let min = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
|
||||
let max = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
|
||||
preFilteredRows.forEach(row => {
|
||||
min = Math.min(row.values[id], min)
|
||||
max = Math.max(row.values[id], max)
|
||||
})
|
||||
return [min, max]
|
||||
}, [id, preFilteredRows])
|
||||
const [min, max] = React.useMemo(
|
||||
() => {
|
||||
let min = 0
|
||||
let max = 0
|
||||
preFilteredRows.forEach(row => {
|
||||
min = Math.min(row.values[id], min)
|
||||
max = Math.max(row.values[id], max)
|
||||
})
|
||||
return [min, max]
|
||||
},
|
||||
[id, preFilteredRows]
|
||||
)
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -124,17 +124,23 @@ function SliderColumnFilter({
|
||||
// filter. It uses two number boxes and filters rows to
|
||||
// ones that have values between the two
|
||||
function NumberRangeColumnFilter({
|
||||
column: { filterValue = [], preFilteredRows, setFilter, id },
|
||||
filterValue = [],
|
||||
preFilteredRows,
|
||||
setFilter,
|
||||
id,
|
||||
}) {
|
||||
const [min, max] = React.useMemo(() => {
|
||||
let min = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
|
||||
let max = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
|
||||
preFilteredRows.forEach(row => {
|
||||
min = Math.min(row.values[id], min)
|
||||
max = Math.max(row.values[id], max)
|
||||
})
|
||||
return [min, max]
|
||||
}, [id, preFilteredRows])
|
||||
const [min, max] = React.useMemo(
|
||||
() => {
|
||||
let min = 0
|
||||
let max = 0
|
||||
preFilteredRows.forEach(row => {
|
||||
min = Math.min(row.values[id], min)
|
||||
max = Math.max(row.values[id], max)
|
||||
})
|
||||
return [min, max]
|
||||
},
|
||||
[id, preFilteredRows]
|
||||
)
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -220,9 +226,9 @@ function Table({ columns, data }) {
|
||||
useFilters // useFilters!
|
||||
)
|
||||
|
||||
// We don't want to render all of the rows for this example, so cap
|
||||
// it for this use case
|
||||
const firstPageRows = rows.slice(0, 10)
|
||||
// We don't want to render all 2000 rows for this example, so cap
|
||||
// it at 20 for this use case
|
||||
const firstPageRows = rows.slice(0, 20)
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -331,7 +337,7 @@ function App() {
|
||||
[]
|
||||
)
|
||||
|
||||
const data = React.useMemo(() => makeData(100000), [])
|
||||
const data = React.useMemo(() => makeData(10000), [])
|
||||
|
||||
return (
|
||||
<Styles>
|
||||
|
||||
@@ -68,7 +68,7 @@ function Table({ columns, data }) {
|
||||
{column.canGroupBy ? (
|
||||
// If the column can be grouped, let's add a toggle
|
||||
<span {...column.getGroupByToggleProps()}>
|
||||
{column.isGrouped ? '🛑 ' : '👊 '}
|
||||
{column.grouped ? '🛑 ' : '👊 '}
|
||||
</span>
|
||||
) : null}
|
||||
{column.render('Header')}
|
||||
@@ -90,16 +90,16 @@ function Table({ columns, data }) {
|
||||
// from the useGroupBy hook
|
||||
{...cell.getCellProps()}
|
||||
style={{
|
||||
background: cell.isGrouped
|
||||
background: cell.grouped
|
||||
? '#0aff0082'
|
||||
: cell.isAggregated
|
||||
: cell.aggregated
|
||||
? '#ffa50078'
|
||||
: cell.isRepeatedValue
|
||||
: cell.repeatedValue
|
||||
? '#ff000042'
|
||||
: 'white',
|
||||
}}
|
||||
>
|
||||
{cell.isGrouped ? (
|
||||
{cell.grouped ? (
|
||||
// If it's a grouped cell, add an expander and row count
|
||||
<>
|
||||
<span {...row.getExpandedToggleProps()}>
|
||||
@@ -107,11 +107,11 @@ function Table({ columns, data }) {
|
||||
</span>{' '}
|
||||
{cell.render('Cell')} ({row.subRows.length})
|
||||
</>
|
||||
) : cell.isAggregated ? (
|
||||
) : cell.aggregated ? (
|
||||
// If the cell is aggregated, use the Aggregated
|
||||
// renderer for cell
|
||||
cell.render('Aggregated')
|
||||
) : cell.isRepeatedValue ? null : ( // For cells with repeated values, render null
|
||||
) : cell.repeatedValue ? null : ( // For cells with repeated values, render null
|
||||
// Otherwise, just render the regular cell
|
||||
cell.render('Cell')
|
||||
)}
|
||||
@@ -196,7 +196,7 @@ function App() {
|
||||
// then sum any of those counts if they are
|
||||
// aggregated further
|
||||
aggregate: ['sum', 'count'],
|
||||
Aggregated: ({ cell: { value } }) => `${value} Names`,
|
||||
Aggregated: ({ value }) => `${value} Names`,
|
||||
},
|
||||
{
|
||||
Header: 'Last Name',
|
||||
@@ -206,7 +206,7 @@ function App() {
|
||||
// being aggregated, then sum those counts if
|
||||
// they are aggregated further
|
||||
aggregate: ['sum', 'uniqueCount'],
|
||||
Aggregated: ({ cell: { value } }) => `${value} Unique Names`,
|
||||
Aggregated: ({ value }) => `${value} Unique Names`,
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -218,14 +218,14 @@ function App() {
|
||||
accessor: 'age',
|
||||
// Aggregate the average age of visitors
|
||||
aggregate: 'average',
|
||||
Aggregated: ({ cell: { value } }) => `${value} (avg)`,
|
||||
Aggregated: ({ value }) => `${value} (avg)`,
|
||||
},
|
||||
{
|
||||
Header: 'Visits',
|
||||
accessor: 'visits',
|
||||
// Aggregate the sum of all visits
|
||||
aggregate: 'sum',
|
||||
Aggregated: ({ cell: { value } }) => `${value} (total)`,
|
||||
Aggregated: ({ value }) => `${value} (total)`,
|
||||
},
|
||||
{
|
||||
Header: 'Status',
|
||||
@@ -236,7 +236,7 @@ function App() {
|
||||
accessor: 'progress',
|
||||
// Use our custom roundedMedian aggregator
|
||||
aggregate: roundedMedian,
|
||||
Aggregated: ({ cell: { value } }) => `${value} (med)`,
|
||||
Aggregated: ({ value }) => `${value} (med)`,
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"presets": ["react-app"],
|
||||
"plugins": ["styled-components"]
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
SKIP_PREFLIGHT_CHECK=true
|
||||
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"extends": ["react-app", "prettier"],
|
||||
"rules": {
|
||||
// "eqeqeq": 0,
|
||||
// "jsx-a11y/anchor-is-valid": 0
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
# 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*
|
||||
@@ -1,29 +0,0 @@
|
||||
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,
|
||||
]
|
||||
@@ -1,4 +0,0 @@
|
||||
# Kitchen Sink
|
||||
|
||||
- [Open this example in a new CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/kitchen-sink)
|
||||
- `yarn` and `yarn start` to run and edit the example
|
||||
@@ -1,36 +0,0 @@
|
||||
{
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"start": "rescripts start",
|
||||
"build": "rescripts build",
|
||||
"test": "rescripts test",
|
||||
"eject": "rescripts eject"
|
||||
},
|
||||
"dependencies": {
|
||||
"match-sorter": "^4.0.1",
|
||||
"namor": "^1.1.2",
|
||||
"react": "^16.8.6",
|
||||
"react-dom": "^16.8.6",
|
||||
"react-scripts": "3.0.1",
|
||||
"react-table": "next",
|
||||
"styled-components": "^4.3.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@rescripts/cli": "^0.0.11",
|
||||
"@rescripts/rescript-use-babel-config": "^0.0.8",
|
||||
"@rescripts/rescript-use-eslint-config": "^0.0.9",
|
||||
"babel-eslint": "10.0.1"
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 3.8 KiB |
@@ -1,38 +0,0 @@
|
||||
<!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>
|
||||
@@ -1,15 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"infiniteLoopProtection": false
|
||||
}
|
||||
@@ -1,626 +0,0 @@
|
||||
import React from 'react'
|
||||
import styled from 'styled-components'
|
||||
import {
|
||||
useTable,
|
||||
usePagination,
|
||||
useSortBy,
|
||||
useFilters,
|
||||
useGroupBy,
|
||||
useExpanded,
|
||||
useRowSelect,
|
||||
useTableState,
|
||||
} from 'react-table'
|
||||
import matchSorter from 'match-sorter'
|
||||
|
||||
import makeData from './makeData'
|
||||
|
||||
const Styles = styled.div`
|
||||
padding: 1rem;
|
||||
|
||||
table {
|
||||
border-spacing: 0;
|
||||
border: 1px solid black;
|
||||
|
||||
tr {
|
||||
:last-child {
|
||||
td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
th,
|
||||
td {
|
||||
margin: 0;
|
||||
padding: 0.5rem;
|
||||
border-bottom: 1px solid black;
|
||||
border-right: 1px solid black;
|
||||
|
||||
:last-child {
|
||||
border-right: 0;
|
||||
}
|
||||
}
|
||||
|
||||
td {
|
||||
input {
|
||||
font-size: 1rem;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
border: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.pagination {
|
||||
padding: 0.5rem;
|
||||
}
|
||||
`
|
||||
|
||||
// Create an editable cell renderer
|
||||
const EditableCell = ({
|
||||
cell: { value: initialValue },
|
||||
row: { index },
|
||||
column: { id },
|
||||
updateMyData, // This is a custom function that we supplied to our table instance
|
||||
editable,
|
||||
}) => {
|
||||
// We need to keep and update the state of the cell normally
|
||||
const [value, setValue] = React.useState(initialValue)
|
||||
|
||||
const onChange = e => {
|
||||
setValue(e.target.value)
|
||||
}
|
||||
|
||||
// We'll only update the external data when the input is blurred
|
||||
const onBlur = () => {
|
||||
updateMyData(index, id, value)
|
||||
}
|
||||
|
||||
// If the initialValue is changed externall, sync it up with our state
|
||||
React.useEffect(() => {
|
||||
setValue(initialValue)
|
||||
}, [initialValue])
|
||||
|
||||
if (!editable) {
|
||||
return `${initialValue}`
|
||||
}
|
||||
|
||||
return <input value={value} onChange={onChange} onBlur={onBlur} />
|
||||
}
|
||||
|
||||
// Define a default UI for filtering
|
||||
function DefaultColumnFilter({
|
||||
column: { filterValue, preFilteredRows, setFilter },
|
||||
}) {
|
||||
const count = preFilteredRows.length
|
||||
|
||||
return (
|
||||
<input
|
||||
value={filterValue || ''}
|
||||
onChange={e => {
|
||||
setFilter(e.target.value || undefined) // Set undefined to remove the filter entirely
|
||||
}}
|
||||
placeholder={`Search ${count} records...`}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// This is a custom filter UI for selecting
|
||||
// a unique option from a list
|
||||
function SelectColumnFilter({
|
||||
column: { filterValue, setFilter, preFilteredRows, id },
|
||||
}) {
|
||||
// Calculate the options for filtering
|
||||
// using the preFilteredRows
|
||||
const options = React.useMemo(() => {
|
||||
const options = new Set()
|
||||
preFilteredRows.forEach(row => {
|
||||
options.add(row.values[id])
|
||||
})
|
||||
return [...options.values()]
|
||||
}, [id, preFilteredRows])
|
||||
|
||||
// Render a multi-select box
|
||||
return (
|
||||
<select
|
||||
value={filterValue}
|
||||
onChange={e => {
|
||||
setFilter(e.target.value || undefined)
|
||||
}}
|
||||
>
|
||||
<option value="">All</option>
|
||||
{options.map((option, i) => (
|
||||
<option key={i} value={option}>
|
||||
{option}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)
|
||||
}
|
||||
|
||||
// This is a custom filter UI that uses a
|
||||
// slider to set the filter value between a column's
|
||||
// min and max values
|
||||
function SliderColumnFilter({
|
||||
column: { filterValue, setFilter, preFilteredRows, id },
|
||||
}) {
|
||||
// Calculate the min and max
|
||||
// using the preFilteredRows
|
||||
|
||||
const [min, max] = React.useMemo(() => {
|
||||
let min = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
|
||||
let max = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
|
||||
preFilteredRows.forEach(row => {
|
||||
min = Math.min(row.values[id], min)
|
||||
max = Math.max(row.values[id], max)
|
||||
})
|
||||
return [min, max]
|
||||
}, [id, preFilteredRows])
|
||||
|
||||
return (
|
||||
<>
|
||||
<input
|
||||
type="range"
|
||||
min={min}
|
||||
max={max}
|
||||
value={filterValue || min}
|
||||
onChange={e => {
|
||||
setFilter(parseInt(e.target.value, 10))
|
||||
}}
|
||||
/>
|
||||
<button onClick={() => setFilter(undefined)}>Off</button>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// This is a custom UI for our 'between' or number range
|
||||
// filter. It uses two number boxes and filters rows to
|
||||
// ones that have values between the two
|
||||
function NumberRangeColumnFilter({
|
||||
column: { filterValue = [], preFilteredRows, setFilter, id },
|
||||
}) {
|
||||
const [min, max] = React.useMemo(() => {
|
||||
let min = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
|
||||
let max = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
|
||||
preFilteredRows.forEach(row => {
|
||||
min = Math.min(row.values[id], min)
|
||||
max = Math.max(row.values[id], max)
|
||||
})
|
||||
return [min, max]
|
||||
}, [id, preFilteredRows])
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
}}
|
||||
>
|
||||
<input
|
||||
value={filterValue[0] || ''}
|
||||
type="number"
|
||||
onChange={e => {
|
||||
const val = e.target.value
|
||||
setFilter((old = []) => [val ? parseInt(val, 10) : undefined, old[1]])
|
||||
}}
|
||||
placeholder={`Min (${min})`}
|
||||
style={{
|
||||
width: '70px',
|
||||
marginRight: '0.5rem',
|
||||
}}
|
||||
/>
|
||||
to
|
||||
<input
|
||||
value={filterValue[1] || ''}
|
||||
type="number"
|
||||
onChange={e => {
|
||||
const val = e.target.value
|
||||
setFilter((old = []) => [old[0], val ? parseInt(val, 10) : undefined])
|
||||
}}
|
||||
placeholder={`Max (${max})`}
|
||||
style={{
|
||||
width: '70px',
|
||||
marginLeft: '0.5rem',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function fuzzyTextFilterFn(rows, id, filterValue) {
|
||||
return matchSorter(rows, filterValue, { keys: [row => row.values[id]] })
|
||||
}
|
||||
|
||||
// Let the table remove the filter if the string is empty
|
||||
fuzzyTextFilterFn.autoRemove = val => !val
|
||||
|
||||
// Be sure to pass our updateMyData and the disablePageResetOnDataChange option
|
||||
function Table({ columns, data, updateMyData, disablePageResetOnDataChange }) {
|
||||
const filterTypes = React.useMemo(
|
||||
() => ({
|
||||
// Add a new fuzzyTextFilterFn filter type.
|
||||
fuzzyText: fuzzyTextFilterFn,
|
||||
// Or, override the default text filter to use
|
||||
// "startWith"
|
||||
text: (rows, id, filterValue) => {
|
||||
return rows.filter(row => {
|
||||
const rowValue = row.values[id]
|
||||
return rowValue !== undefined
|
||||
? String(rowValue)
|
||||
.toLowerCase()
|
||||
.startsWith(String(filterValue).toLowerCase())
|
||||
: true
|
||||
})
|
||||
},
|
||||
}),
|
||||
[]
|
||||
)
|
||||
|
||||
const defaultColumn = React.useMemo(
|
||||
() => ({
|
||||
// Let's set up our default Filter UI
|
||||
Filter: DefaultColumnFilter,
|
||||
// And also our default editable cell
|
||||
Cell: EditableCell,
|
||||
}),
|
||||
[]
|
||||
)
|
||||
|
||||
const tableState = useTableState({ pageIndex: 2 })
|
||||
|
||||
// Use the state and functions returned from useTable to build your UI
|
||||
const {
|
||||
getTableProps,
|
||||
headerGroups,
|
||||
prepareRow,
|
||||
page, // Instead of using 'rows', we'll use page,
|
||||
// which has only the rows for the active page
|
||||
|
||||
// The rest of these things are super handy, too ;)
|
||||
canPreviousPage,
|
||||
canNextPage,
|
||||
pageOptions,
|
||||
pageCount,
|
||||
gotoPage,
|
||||
nextPage,
|
||||
previousPage,
|
||||
setPageSize,
|
||||
state: [{ pageIndex, pageSize, groupBy, expanded, filters, selectedRows }],
|
||||
} = useTable(
|
||||
{
|
||||
columns,
|
||||
data,
|
||||
defaultColumn,
|
||||
filterTypes,
|
||||
// nestExpandedRows: true,
|
||||
state: tableState,
|
||||
// updateMyData isn't part of the API, but
|
||||
// anything we put into these options will
|
||||
// automatically be available on the instance.
|
||||
// That way we can call this function from our
|
||||
// cell renderer!
|
||||
updateMyData,
|
||||
// We also need to pass this so the page doesn't change
|
||||
// when we edit the data
|
||||
disablePageResetOnDataChange,
|
||||
},
|
||||
useFilters,
|
||||
useSortBy,
|
||||
useGroupBy,
|
||||
useExpanded,
|
||||
usePagination,
|
||||
useRowSelect
|
||||
)
|
||||
|
||||
// Render the UI for your table
|
||||
return (
|
||||
<>
|
||||
<table {...getTableProps()}>
|
||||
<thead>
|
||||
{headerGroups.map(headerGroup => (
|
||||
<tr {...headerGroup.getHeaderGroupProps()}>
|
||||
{headerGroup.headers.map(column => (
|
||||
<th {...column.getHeaderProps()}>
|
||||
<div>
|
||||
{column.canGroupBy ? (
|
||||
// If the column can be grouped, let's add a toggle
|
||||
<span {...column.getGroupByToggleProps()}>
|
||||
{column.isGrouped ? '🛑 ' : '👊 '}
|
||||
</span>
|
||||
) : null}
|
||||
<span {...column.getSortByToggleProps()}>
|
||||
{column.render('Header')}
|
||||
{/* Add a sort direction indicator */}
|
||||
{column.isSorted
|
||||
? column.isSortedDesc
|
||||
? ' 🔽'
|
||||
: ' 🔼'
|
||||
: ''}
|
||||
</span>
|
||||
</div>
|
||||
{/* Render the columns filter UI */}
|
||||
<div>{column.canFilter ? column.render('Filter') : null}</div>
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
<tbody>
|
||||
{page.map(
|
||||
row =>
|
||||
prepareRow(row) || (
|
||||
<tr {...row.getRowProps()}>
|
||||
{row.cells.map(cell => {
|
||||
return (
|
||||
<td {...cell.getCellProps()}>
|
||||
{cell.isGrouped ? (
|
||||
// If it's a grouped cell, add an expander and row count
|
||||
<>
|
||||
<span {...row.getExpandedToggleProps()}>
|
||||
{row.isExpanded ? '👇' : '👉'}
|
||||
</span>{' '}
|
||||
{cell.render('Cell', { editable: false })} (
|
||||
{row.subRows.length})
|
||||
</>
|
||||
) : cell.isAggregated ? (
|
||||
// If the cell is aggregated, use the Aggregated
|
||||
// renderer for cell
|
||||
cell.render('Aggregated')
|
||||
) : cell.isRepeatedValue ? null : ( // For cells with repeated values, render null
|
||||
// Otherwise, just render the regular cell
|
||||
cell.render('Cell', { editable: true })
|
||||
)}
|
||||
</td>
|
||||
)
|
||||
})}
|
||||
</tr>
|
||||
)
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
{/*
|
||||
Pagination can be built however you'd like.
|
||||
This is just a very basic UI implementation:
|
||||
*/}
|
||||
<div className="pagination">
|
||||
<button onClick={() => gotoPage(0)} disabled={!canPreviousPage}>
|
||||
{'<<'}
|
||||
</button>{' '}
|
||||
<button onClick={() => previousPage()} disabled={!canPreviousPage}>
|
||||
{'<'}
|
||||
</button>{' '}
|
||||
<button onClick={() => nextPage()} disabled={!canNextPage}>
|
||||
{'>'}
|
||||
</button>{' '}
|
||||
<button onClick={() => gotoPage(pageCount - 1)} disabled={!canNextPage}>
|
||||
{'>>'}
|
||||
</button>{' '}
|
||||
<span>
|
||||
Page{' '}
|
||||
<strong>
|
||||
{pageIndex + 1} of {pageOptions.length}
|
||||
</strong>{' '}
|
||||
</span>
|
||||
<span>
|
||||
| Go to page:{' '}
|
||||
<input
|
||||
type="number"
|
||||
defaultValue={pageIndex + 1}
|
||||
onChange={e => {
|
||||
const page = e.target.value ? Number(e.target.value) - 1 : 0
|
||||
gotoPage(page)
|
||||
}}
|
||||
style={{ width: '100px' }}
|
||||
/>
|
||||
</span>{' '}
|
||||
<select
|
||||
value={pageSize}
|
||||
onChange={e => {
|
||||
setPageSize(Number(e.target.value))
|
||||
}}
|
||||
>
|
||||
{[10, 20, 30, 40, 50].map(pageSize => (
|
||||
<option key={pageSize} value={pageSize}>
|
||||
Show {pageSize}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<pre>
|
||||
<code>
|
||||
{JSON.stringify(
|
||||
{
|
||||
pageIndex,
|
||||
pageSize,
|
||||
pageCount,
|
||||
canNextPage,
|
||||
canPreviousPage,
|
||||
groupBy,
|
||||
expanded,
|
||||
filters,
|
||||
selectedRows,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)}
|
||||
</code>
|
||||
</pre>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// Define a custom filter filter function!
|
||||
function filterGreaterThan(rows, id, filterValue) {
|
||||
return rows.filter(row => {
|
||||
const rowValue = row.values[id]
|
||||
return rowValue >= filterValue
|
||||
})
|
||||
}
|
||||
|
||||
// This is an autoRemove method on the filter function that
|
||||
// when given the new filter value and returns true, the filter
|
||||
// will be automatically removed. Normally this is just an undefined
|
||||
// check, but here, we want to remove the filter if it's not a number
|
||||
filterGreaterThan.autoRemove = val => typeof val !== 'number'
|
||||
|
||||
// This is a custom aggregator that
|
||||
// takes in an array of values and
|
||||
// returns the rounded median
|
||||
function roundedMedian(values) {
|
||||
let min = values[0] || ''
|
||||
let max = values[0] || ''
|
||||
|
||||
values.forEach(value => {
|
||||
min = Math.min(min, value)
|
||||
max = Math.max(max, value)
|
||||
})
|
||||
|
||||
return Math.round((min + max) / 2)
|
||||
}
|
||||
|
||||
function App() {
|
||||
const columns = React.useMemo(
|
||||
() => [
|
||||
{
|
||||
id: 'selection',
|
||||
// Make this column a groupByBoundary. This ensures that groupBy columns
|
||||
// are placed after it
|
||||
groupByBoundary: true,
|
||||
// The header can use the table's getToggleAllRowsSelectedProps method
|
||||
// to render a checkbox
|
||||
Header: ({ getToggleAllRowsSelectedProps }) => (
|
||||
<div>
|
||||
<input type="checkbox" {...getToggleAllRowsSelectedProps()} />
|
||||
</div>
|
||||
),
|
||||
// The cell can use the individual row's getToggleRowSelectedProps method
|
||||
// to the render a checkbox
|
||||
Cell: ({ row }) => (
|
||||
<div>
|
||||
<input type="checkbox" {...row.getToggleRowSelectedProps()} />
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
Header: 'Name',
|
||||
columns: [
|
||||
{
|
||||
Header: 'First Name',
|
||||
accessor: 'firstName',
|
||||
// Use a two-stage aggregator here to first
|
||||
// count the total rows being aggregated,
|
||||
// then sum any of those counts if they are
|
||||
// aggregated further
|
||||
aggregate: ['sum', 'count'],
|
||||
Aggregated: ({ cell: { value } }) => `${value} Names`,
|
||||
},
|
||||
{
|
||||
Header: 'Last Name',
|
||||
accessor: 'lastName',
|
||||
// Use our custom `fuzzyText` filter on this column
|
||||
filter: 'fuzzyText',
|
||||
// Use another two-stage aggregator here to
|
||||
// first count the UNIQUE values from the rows
|
||||
// being aggregated, then sum those counts if
|
||||
// they are aggregated further
|
||||
aggregate: ['sum', 'uniqueCount'],
|
||||
Aggregated: ({ cell: { value } }) => `${value} Unique Names`,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
Header: 'Info',
|
||||
columns: [
|
||||
{
|
||||
Header: 'Age',
|
||||
accessor: 'age',
|
||||
Filter: SliderColumnFilter,
|
||||
filter: 'equals',
|
||||
// Aggregate the average age of visitors
|
||||
aggregate: 'average',
|
||||
Aggregated: ({ cell: { value } }) => `${value} (avg)`,
|
||||
},
|
||||
{
|
||||
Header: 'Visits',
|
||||
accessor: 'visits',
|
||||
Filter: NumberRangeColumnFilter,
|
||||
filter: 'between',
|
||||
// Aggregate the sum of all visits
|
||||
aggregate: 'sum',
|
||||
Aggregated: ({ cell: { value } }) => `${value} (total)`,
|
||||
},
|
||||
{
|
||||
Header: 'Status',
|
||||
accessor: 'status',
|
||||
Filter: SelectColumnFilter,
|
||||
filter: 'includes',
|
||||
},
|
||||
{
|
||||
Header: 'Profile Progress',
|
||||
accessor: 'progress',
|
||||
Filter: SliderColumnFilter,
|
||||
filter: filterGreaterThan,
|
||||
// Use our custom roundedMedian aggregator
|
||||
aggregate: roundedMedian,
|
||||
Aggregated: ({ cell: { value } }) => `${value} (med)`,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
[]
|
||||
)
|
||||
|
||||
const [data, setData] = React.useState(() => makeData(10000))
|
||||
const [originalData] = React.useState(data)
|
||||
|
||||
// We need to keep the table from resetting the pageIndex when we
|
||||
// Update data. So we can keep track of that flag with a ref.
|
||||
const skipPageResetRef = React.useRef(false)
|
||||
|
||||
// When our cell renderer calls updateMyData, we'll use
|
||||
// the rowIndex, columnID and new value to update the
|
||||
// original data
|
||||
const updateMyData = (rowIndex, columnID, value) => {
|
||||
// We also turn on the flag to not reset the page
|
||||
skipPageResetRef.current = true
|
||||
setData(old =>
|
||||
old.map((row, index) => {
|
||||
if (index === rowIndex) {
|
||||
return {
|
||||
...row,
|
||||
[columnID]: value,
|
||||
}
|
||||
}
|
||||
return row
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
// After data chagnes, we turn the flag back off
|
||||
// so that if data actually changes when we're not
|
||||
// editing it, the page is reset
|
||||
React.useEffect(() => {
|
||||
skipPageResetRef.current = false
|
||||
}, [data])
|
||||
|
||||
// Let's add a data resetter/randomizer to help
|
||||
// illustrate that flow...
|
||||
const resetData = () => {
|
||||
// Don't reset the page when we do this
|
||||
skipPageResetRef.current = true
|
||||
setData(originalData)
|
||||
}
|
||||
|
||||
return (
|
||||
<Styles>
|
||||
<button onClick={resetData}>Reset Data</button>
|
||||
<Table
|
||||
columns={columns}
|
||||
data={data}
|
||||
updateMyData={updateMyData}
|
||||
disablePageResetOnDataChange={skipPageResetRef.current}
|
||||
/>
|
||||
</Styles>
|
||||
)
|
||||
}
|
||||
|
||||
export default App
|
||||
@@ -1,9 +0,0 @@
|
||||
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)
|
||||
})
|
||||
@@ -1,13 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
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()
|
||||
@@ -1,40 +0,0 @@
|
||||
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()
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
// 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
@@ -1,4 +0,0 @@
|
||||
{
|
||||
"presets": ["react-app"],
|
||||
"plugins": ["styled-components"]
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
SKIP_PREFLIGHT_CHECK=true
|
||||
@@ -1,7 +0,0 @@
|
||||
{
|
||||
"extends": ["react-app", "prettier"],
|
||||
"rules": {
|
||||
// "eqeqeq": 0,
|
||||
// "jsx-a11y/anchor-is-valid": 0
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
# 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*
|
||||
@@ -1,29 +0,0 @@
|
||||
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,
|
||||
]
|
||||
@@ -1,4 +0,0 @@
|
||||
# Kitchen Sink
|
||||
|
||||
- [Open this example in a new CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/kitchen-sink)
|
||||
- `yarn` and `yarn start` to run and edit the example
|
||||
@@ -1,36 +0,0 @@
|
||||
{
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"start": "rescripts start",
|
||||
"build": "rescripts build",
|
||||
"test": "rescripts test",
|
||||
"eject": "rescripts eject"
|
||||
},
|
||||
"dependencies": {
|
||||
"match-sorter": "^4.0.1",
|
||||
"namor": "^1.1.2",
|
||||
"react": "^16.8.6",
|
||||
"react-dom": "^16.8.6",
|
||||
"react-scripts": "3.0.1",
|
||||
"react-table": "next",
|
||||
"styled-components": "^4.3.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@rescripts/cli": "^0.0.11",
|
||||
"@rescripts/rescript-use-babel-config": "^0.0.8",
|
||||
"@rescripts/rescript-use-eslint-config": "^0.0.9",
|
||||
"babel-eslint": "10.0.1"
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 3.8 KiB |
@@ -1,38 +0,0 @@
|
||||
<!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>
|
||||
@@ -1,15 +0,0 @@
|
||||
{
|
||||
"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"
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"infiniteLoopProtection": false
|
||||
}
|
||||
@@ -1,626 +0,0 @@
|
||||
import React from 'react'
|
||||
import styled from 'styled-components'
|
||||
import {
|
||||
useTable,
|
||||
usePagination,
|
||||
useSortBy,
|
||||
useFilters,
|
||||
useGroupBy,
|
||||
useExpanded,
|
||||
useRowSelect,
|
||||
useTableState,
|
||||
} from 'react-table'
|
||||
import matchSorter from 'match-sorter'
|
||||
|
||||
import makeData from './makeData'
|
||||
|
||||
const Styles = styled.div`
|
||||
padding: 1rem;
|
||||
|
||||
table {
|
||||
border-spacing: 0;
|
||||
border: 1px solid black;
|
||||
|
||||
tr {
|
||||
:last-child {
|
||||
td {
|
||||
border-bottom: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
th,
|
||||
td {
|
||||
margin: 0;
|
||||
padding: 0.5rem;
|
||||
border-bottom: 1px solid black;
|
||||
border-right: 1px solid black;
|
||||
|
||||
:last-child {
|
||||
border-right: 0;
|
||||
}
|
||||
}
|
||||
|
||||
td {
|
||||
input {
|
||||
font-size: 1rem;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
border: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.pagination {
|
||||
padding: 0.5rem;
|
||||
}
|
||||
`
|
||||
|
||||
// Create an editable cell renderer
|
||||
const EditableCell = ({
|
||||
cell: { value: initialValue },
|
||||
row: { index },
|
||||
column: { id },
|
||||
updateMyData, // This is a custom function that we supplied to our table instance
|
||||
editable,
|
||||
}) => {
|
||||
// We need to keep and update the state of the cell normally
|
||||
const [value, setValue] = React.useState(initialValue)
|
||||
|
||||
const onChange = e => {
|
||||
setValue(e.target.value)
|
||||
}
|
||||
|
||||
// We'll only update the external data when the input is blurred
|
||||
const onBlur = () => {
|
||||
updateMyData(index, id, value)
|
||||
}
|
||||
|
||||
// If the initialValue is changed externall, sync it up with our state
|
||||
React.useEffect(() => {
|
||||
setValue(initialValue)
|
||||
}, [initialValue])
|
||||
|
||||
if (!editable) {
|
||||
return `${initialValue}`
|
||||
}
|
||||
|
||||
return <input value={value} onChange={onChange} onBlur={onBlur} />
|
||||
}
|
||||
|
||||
// Define a default UI for filtering
|
||||
function DefaultColumnFilter({
|
||||
column: { filterValue, preFilteredRows, setFilter },
|
||||
}) {
|
||||
const count = preFilteredRows.length
|
||||
|
||||
return (
|
||||
<input
|
||||
value={filterValue || ''}
|
||||
onChange={e => {
|
||||
setFilter(e.target.value || undefined) // Set undefined to remove the filter entirely
|
||||
}}
|
||||
placeholder={`Search ${count} records...`}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
// This is a custom filter UI for selecting
|
||||
// a unique option from a list
|
||||
function SelectColumnFilter({
|
||||
column: { filterValue, setFilter, preFilteredRows, id },
|
||||
}) {
|
||||
// Calculate the options for filtering
|
||||
// using the preFilteredRows
|
||||
const options = React.useMemo(() => {
|
||||
const options = new Set()
|
||||
preFilteredRows.forEach(row => {
|
||||
options.add(row.values[id])
|
||||
})
|
||||
return [...options.values()]
|
||||
}, [id, preFilteredRows])
|
||||
|
||||
// Render a multi-select box
|
||||
return (
|
||||
<select
|
||||
value={filterValue}
|
||||
onChange={e => {
|
||||
setFilter(e.target.value || undefined)
|
||||
}}
|
||||
>
|
||||
<option value="">All</option>
|
||||
{options.map((option, i) => (
|
||||
<option key={i} value={option}>
|
||||
{option}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
)
|
||||
}
|
||||
|
||||
// This is a custom filter UI that uses a
|
||||
// slider to set the filter value between a column's
|
||||
// min and max values
|
||||
function SliderColumnFilter({
|
||||
column: { filterValue, setFilter, preFilteredRows, id },
|
||||
}) {
|
||||
// Calculate the min and max
|
||||
// using the preFilteredRows
|
||||
|
||||
const [min, max] = React.useMemo(() => {
|
||||
let min = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
|
||||
let max = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
|
||||
preFilteredRows.forEach(row => {
|
||||
min = Math.min(row.values[id], min)
|
||||
max = Math.max(row.values[id], max)
|
||||
})
|
||||
return [min, max]
|
||||
}, [id, preFilteredRows])
|
||||
|
||||
return (
|
||||
<>
|
||||
<input
|
||||
type="range"
|
||||
min={min}
|
||||
max={max}
|
||||
value={filterValue || min}
|
||||
onChange={e => {
|
||||
setFilter(parseInt(e.target.value, 10))
|
||||
}}
|
||||
/>
|
||||
<button onClick={() => setFilter(undefined)}>Off</button>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// This is a custom UI for our 'between' or number range
|
||||
// filter. It uses two number boxes and filters rows to
|
||||
// ones that have values between the two
|
||||
function NumberRangeColumnFilter({
|
||||
column: { filterValue = [], preFilteredRows, setFilter, id },
|
||||
}) {
|
||||
const [min, max] = React.useMemo(() => {
|
||||
let min = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
|
||||
let max = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
|
||||
preFilteredRows.forEach(row => {
|
||||
min = Math.min(row.values[id], min)
|
||||
max = Math.max(row.values[id], max)
|
||||
})
|
||||
return [min, max]
|
||||
}, [id, preFilteredRows])
|
||||
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
}}
|
||||
>
|
||||
<input
|
||||
value={filterValue[0] || ''}
|
||||
type="number"
|
||||
onChange={e => {
|
||||
const val = e.target.value
|
||||
setFilter((old = []) => [val ? parseInt(val, 10) : undefined, old[1]])
|
||||
}}
|
||||
placeholder={`Min (${min})`}
|
||||
style={{
|
||||
width: '70px',
|
||||
marginRight: '0.5rem',
|
||||
}}
|
||||
/>
|
||||
to
|
||||
<input
|
||||
value={filterValue[1] || ''}
|
||||
type="number"
|
||||
onChange={e => {
|
||||
const val = e.target.value
|
||||
setFilter((old = []) => [old[0], val ? parseInt(val, 10) : undefined])
|
||||
}}
|
||||
placeholder={`Max (${max})`}
|
||||
style={{
|
||||
width: '70px',
|
||||
marginLeft: '0.5rem',
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function fuzzyTextFilterFn(rows, id, filterValue) {
|
||||
return matchSorter(rows, filterValue, { keys: [row => row.values[id]] })
|
||||
}
|
||||
|
||||
// Let the table remove the filter if the string is empty
|
||||
fuzzyTextFilterFn.autoRemove = val => !val
|
||||
|
||||
// Be sure to pass our updateMyData and the disablePageResetOnDataChange option
|
||||
function Table({ columns, data, updateMyData, disablePageResetOnDataChange }) {
|
||||
const filterTypes = React.useMemo(
|
||||
() => ({
|
||||
// Add a new fuzzyTextFilterFn filter type.
|
||||
fuzzyText: fuzzyTextFilterFn,
|
||||
// Or, override the default text filter to use
|
||||
// "startWith"
|
||||
text: (rows, id, filterValue) => {
|
||||
return rows.filter(row => {
|
||||
const rowValue = row.values[id]
|
||||
return rowValue !== undefined
|
||||
? String(rowValue)
|
||||
.toLowerCase()
|
||||
.startsWith(String(filterValue).toLowerCase())
|
||||
: true
|
||||
})
|
||||
},
|
||||
}),
|
||||
[]
|
||||
)
|
||||
|
||||
const defaultColumn = React.useMemo(
|
||||
() => ({
|
||||
// Let's set up our default Filter UI
|
||||
Filter: DefaultColumnFilter,
|
||||
// And also our default editable cell
|
||||
Cell: EditableCell,
|
||||
}),
|
||||
[]
|
||||
)
|
||||
|
||||
const tableState = useTableState({ pageIndex: 2 })
|
||||
|
||||
// Use the state and functions returned from useTable to build your UI
|
||||
const {
|
||||
getTableProps,
|
||||
headerGroups,
|
||||
prepareRow,
|
||||
page, // Instead of using 'rows', we'll use page,
|
||||
// which has only the rows for the active page
|
||||
|
||||
// The rest of these things are super handy, too ;)
|
||||
canPreviousPage,
|
||||
canNextPage,
|
||||
pageOptions,
|
||||
pageCount,
|
||||
gotoPage,
|
||||
nextPage,
|
||||
previousPage,
|
||||
setPageSize,
|
||||
state: [{ pageIndex, pageSize, groupBy, expanded, filters, selectedRows }],
|
||||
} = useTable(
|
||||
{
|
||||
columns,
|
||||
data,
|
||||
defaultColumn,
|
||||
filterTypes,
|
||||
// nestExpandedRows: true,
|
||||
state: tableState,
|
||||
// updateMyData isn't part of the API, but
|
||||
// anything we put into these options will
|
||||
// automatically be available on the instance.
|
||||
// That way we can call this function from our
|
||||
// cell renderer!
|
||||
updateMyData,
|
||||
// We also need to pass this so the page doesn't change
|
||||
// when we edit the data
|
||||
disablePageResetOnDataChange,
|
||||
},
|
||||
useFilters,
|
||||
useSortBy,
|
||||
useGroupBy,
|
||||
useExpanded,
|
||||
usePagination,
|
||||
useRowSelect
|
||||
)
|
||||
|
||||
// Render the UI for your table
|
||||
return (
|
||||
<>
|
||||
<table {...getTableProps()}>
|
||||
<thead>
|
||||
{headerGroups.map(headerGroup => (
|
||||
<tr {...headerGroup.getHeaderGroupProps()}>
|
||||
{headerGroup.headers.map(column => (
|
||||
<th {...column.getHeaderProps()}>
|
||||
<div>
|
||||
{column.canGroupBy ? (
|
||||
// If the column can be grouped, let's add a toggle
|
||||
<span {...column.getGroupByToggleProps()}>
|
||||
{column.isGrouped ? '🛑 ' : '👊 '}
|
||||
</span>
|
||||
) : null}
|
||||
<span {...column.getSortByToggleProps()}>
|
||||
{column.render('Header')}
|
||||
{/* Add a sort direction indicator */}
|
||||
{column.isSorted
|
||||
? column.isSortedDesc
|
||||
? ' 🔽'
|
||||
: ' 🔼'
|
||||
: ''}
|
||||
</span>
|
||||
</div>
|
||||
{/* Render the columns filter UI */}
|
||||
<div>{column.canFilter ? column.render('Filter') : null}</div>
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
<tbody>
|
||||
{page.map(
|
||||
row =>
|
||||
prepareRow(row) || (
|
||||
<tr {...row.getRowProps()}>
|
||||
{row.cells.map(cell => {
|
||||
return (
|
||||
<td {...cell.getCellProps()}>
|
||||
{cell.isGrouped ? (
|
||||
// If it's a grouped cell, add an expander and row count
|
||||
<>
|
||||
<span {...row.getExpandedToggleProps()}>
|
||||
{row.isExpanded ? '👇' : '👉'}
|
||||
</span>{' '}
|
||||
{cell.render('Cell', { editable: false })} (
|
||||
{row.subRows.length})
|
||||
</>
|
||||
) : cell.isAggregated ? (
|
||||
// If the cell is aggregated, use the Aggregated
|
||||
// renderer for cell
|
||||
cell.render('Aggregated')
|
||||
) : cell.isRepeatedValue ? null : ( // For cells with repeated values, render null
|
||||
// Otherwise, just render the regular cell
|
||||
cell.render('Cell', { editable: true })
|
||||
)}
|
||||
</td>
|
||||
)
|
||||
})}
|
||||
</tr>
|
||||
)
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
{/*
|
||||
Pagination can be built however you'd like.
|
||||
This is just a very basic UI implementation:
|
||||
*/}
|
||||
<div className="pagination">
|
||||
<button onClick={() => gotoPage(0)} disabled={!canPreviousPage}>
|
||||
{'<<'}
|
||||
</button>{' '}
|
||||
<button onClick={() => previousPage()} disabled={!canPreviousPage}>
|
||||
{'<'}
|
||||
</button>{' '}
|
||||
<button onClick={() => nextPage()} disabled={!canNextPage}>
|
||||
{'>'}
|
||||
</button>{' '}
|
||||
<button onClick={() => gotoPage(pageCount - 1)} disabled={!canNextPage}>
|
||||
{'>>'}
|
||||
</button>{' '}
|
||||
<span>
|
||||
Page{' '}
|
||||
<strong>
|
||||
{pageIndex + 1} of {pageOptions.length}
|
||||
</strong>{' '}
|
||||
</span>
|
||||
<span>
|
||||
| Go to page:{' '}
|
||||
<input
|
||||
type="number"
|
||||
defaultValue={pageIndex + 1}
|
||||
onChange={e => {
|
||||
const page = e.target.value ? Number(e.target.value) - 1 : 0
|
||||
gotoPage(page)
|
||||
}}
|
||||
style={{ width: '100px' }}
|
||||
/>
|
||||
</span>{' '}
|
||||
<select
|
||||
value={pageSize}
|
||||
onChange={e => {
|
||||
setPageSize(Number(e.target.value))
|
||||
}}
|
||||
>
|
||||
{[10, 20, 30, 40, 50].map(pageSize => (
|
||||
<option key={pageSize} value={pageSize}>
|
||||
Show {pageSize}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<pre>
|
||||
<code>
|
||||
{JSON.stringify(
|
||||
{
|
||||
pageIndex,
|
||||
pageSize,
|
||||
pageCount,
|
||||
canNextPage,
|
||||
canPreviousPage,
|
||||
groupBy,
|
||||
expanded,
|
||||
filters,
|
||||
selectedRows,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)}
|
||||
</code>
|
||||
</pre>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// Define a custom filter filter function!
|
||||
function filterGreaterThan(rows, id, filterValue) {
|
||||
return rows.filter(row => {
|
||||
const rowValue = row.values[id]
|
||||
return rowValue >= filterValue
|
||||
})
|
||||
}
|
||||
|
||||
// This is an autoRemove method on the filter function that
|
||||
// when given the new filter value and returns true, the filter
|
||||
// will be automatically removed. Normally this is just an undefined
|
||||
// check, but here, we want to remove the filter if it's not a number
|
||||
filterGreaterThan.autoRemove = val => typeof val !== 'number'
|
||||
|
||||
// This is a custom aggregator that
|
||||
// takes in an array of values and
|
||||
// returns the rounded median
|
||||
function roundedMedian(values) {
|
||||
let min = values[0] || ''
|
||||
let max = values[0] || ''
|
||||
|
||||
values.forEach(value => {
|
||||
min = Math.min(min, value)
|
||||
max = Math.max(max, value)
|
||||
})
|
||||
|
||||
return Math.round((min + max) / 2)
|
||||
}
|
||||
|
||||
function App() {
|
||||
const columns = React.useMemo(
|
||||
() => [
|
||||
{
|
||||
id: 'selection',
|
||||
// Make this column a groupByBoundary. This ensures that groupBy columns
|
||||
// are placed after it
|
||||
groupByBoundary: true,
|
||||
// The header can use the table's getToggleAllRowsSelectedProps method
|
||||
// to render a checkbox
|
||||
Header: ({ getToggleAllRowsSelectedProps }) => (
|
||||
<div>
|
||||
<input type="checkbox" {...getToggleAllRowsSelectedProps()} />
|
||||
</div>
|
||||
),
|
||||
// The cell can use the individual row's getToggleRowSelectedProps method
|
||||
// to the render a checkbox
|
||||
Cell: ({ row }) => (
|
||||
<div>
|
||||
<input type="checkbox" {...row.getToggleRowSelectedProps()} />
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
Header: 'Name',
|
||||
columns: [
|
||||
{
|
||||
Header: 'First Name',
|
||||
accessor: 'firstName',
|
||||
// Use a two-stage aggregator here to first
|
||||
// count the total rows being aggregated,
|
||||
// then sum any of those counts if they are
|
||||
// aggregated further
|
||||
aggregate: ['sum', 'count'],
|
||||
Aggregated: ({ cell: { value } }) => `${value} Names`,
|
||||
},
|
||||
{
|
||||
Header: 'Last Name',
|
||||
accessor: 'lastName',
|
||||
// Use our custom `fuzzyText` filter on this column
|
||||
filter: 'fuzzyText',
|
||||
// Use another two-stage aggregator here to
|
||||
// first count the UNIQUE values from the rows
|
||||
// being aggregated, then sum those counts if
|
||||
// they are aggregated further
|
||||
aggregate: ['sum', 'uniqueCount'],
|
||||
Aggregated: ({ cell: { value } }) => `${value} Unique Names`,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
Header: 'Info',
|
||||
columns: [
|
||||
{
|
||||
Header: 'Age',
|
||||
accessor: 'age',
|
||||
Filter: SliderColumnFilter,
|
||||
filter: 'equals',
|
||||
// Aggregate the average age of visitors
|
||||
aggregate: 'average',
|
||||
Aggregated: ({ cell: { value } }) => `${value} (avg)`,
|
||||
},
|
||||
{
|
||||
Header: 'Visits',
|
||||
accessor: 'visits',
|
||||
Filter: NumberRangeColumnFilter,
|
||||
filter: 'between',
|
||||
// Aggregate the sum of all visits
|
||||
aggregate: 'sum',
|
||||
Aggregated: ({ cell: { value } }) => `${value} (total)`,
|
||||
},
|
||||
{
|
||||
Header: 'Status',
|
||||
accessor: 'status',
|
||||
Filter: SelectColumnFilter,
|
||||
filter: 'includes',
|
||||
},
|
||||
{
|
||||
Header: 'Profile Progress',
|
||||
accessor: 'progress',
|
||||
Filter: SliderColumnFilter,
|
||||
filter: filterGreaterThan,
|
||||
// Use our custom roundedMedian aggregator
|
||||
aggregate: roundedMedian,
|
||||
Aggregated: ({ cell: { value } }) => `${value} (med)`,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
[]
|
||||
)
|
||||
|
||||
const [data, setData] = React.useState(() => makeData(10000))
|
||||
const [originalData] = React.useState(data)
|
||||
|
||||
// We need to keep the table from resetting the pageIndex when we
|
||||
// Update data. So we can keep track of that flag with a ref.
|
||||
const skipPageResetRef = React.useRef(false)
|
||||
|
||||
// When our cell renderer calls updateMyData, we'll use
|
||||
// the rowIndex, columnID and new value to update the
|
||||
// original data
|
||||
const updateMyData = (rowIndex, columnID, value) => {
|
||||
// We also turn on the flag to not reset the page
|
||||
skipPageResetRef.current = true
|
||||
setData(old =>
|
||||
old.map((row, index) => {
|
||||
if (index === rowIndex) {
|
||||
return {
|
||||
...row,
|
||||
[columnID]: value,
|
||||
}
|
||||
}
|
||||
return row
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
// After data chagnes, we turn the flag back off
|
||||
// so that if data actually changes when we're not
|
||||
// editing it, the page is reset
|
||||
React.useEffect(() => {
|
||||
skipPageResetRef.current = false
|
||||
}, [data])
|
||||
|
||||
// Let's add a data resetter/randomizer to help
|
||||
// illustrate that flow...
|
||||
const resetData = () => {
|
||||
// Don't reset the page when we do this
|
||||
skipPageResetRef.current = true
|
||||
setData(originalData)
|
||||
}
|
||||
|
||||
return (
|
||||
<Styles>
|
||||
<button onClick={resetData}>Reset Data</button>
|
||||
<Table
|
||||
columns={columns}
|
||||
data={data}
|
||||
updateMyData={updateMyData}
|
||||
disablePageResetOnDataChange={skipPageResetRef.current}
|
||||
/>
|
||||
</Styles>
|
||||
)
|
||||
}
|
||||
|
||||
export default App
|
||||
@@ -1,9 +0,0 @@
|
||||
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)
|
||||
})
|
||||
@@ -1,13 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
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()
|
||||
@@ -1,40 +0,0 @@
|
||||
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()
|
||||
}
|
||||
@@ -1,135 +0,0 @@
|
||||
// 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
@@ -37,7 +37,7 @@ function MyTable() {
|
||||
+ <th {...column.getHeaderProps(column.getSortByToggleProps())}>
|
||||
{column.render('Header')}
|
||||
+ <span>
|
||||
+ {column.isSorted ? (column.isSortedDesc ? ' 🔽' : ' 🔼') : ''}
|
||||
+ {column.sorted ? (column.sortedDesc ? ' 🔽' : ' 🔼') : ''}
|
||||
+ </span>
|
||||
</th>
|
||||
))}
|
||||
|
||||
@@ -33,11 +33,17 @@ const Styles = styled.div`
|
||||
}
|
||||
`
|
||||
|
||||
const defaultColumn = {
|
||||
sort: 'numeric',
|
||||
}
|
||||
|
||||
function Table({ columns, data }) {
|
||||
const { getTableProps, headerGroups, rows, prepareRow } = useTable(
|
||||
{
|
||||
columns,
|
||||
data,
|
||||
defaultColumn,
|
||||
debug: true,
|
||||
},
|
||||
useSortBy
|
||||
)
|
||||
@@ -59,11 +65,7 @@ function Table({ columns, data }) {
|
||||
{column.render('Header')}
|
||||
{/* Add a sort direction indicator */}
|
||||
<span>
|
||||
{column.isSorted
|
||||
? column.isSortedDesc
|
||||
? ' 🔽'
|
||||
: ' 🔼'
|
||||
: ''}
|
||||
{column.sorted ? (column.sortedDesc ? ' 🔽' : ' 🔼') : ''}
|
||||
</span>
|
||||
</th>
|
||||
))}
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 26 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 94 KiB |
Binary file not shown.
+1
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "react-table",
|
||||
"version": "7.0.0-alpha.26",
|
||||
"version": "7.0.0-alpha.22",
|
||||
"description": "A fast, lightweight, opinionated table and datagrid built on React",
|
||||
"license": "MIT",
|
||||
"homepage": "https://github.com/tannerlinsley/react-table#readme",
|
||||
@@ -80,7 +80,6 @@
|
||||
"jest-watch-select-projects": "^0.1.2",
|
||||
"jest-watch-typeahead": "^0.3.1",
|
||||
"lint-staged": "^9.2.1",
|
||||
"prettier": "^1.18.2",
|
||||
"prop-types": "^15.5.0",
|
||||
"react": "^16.9.0",
|
||||
"react-dom": "^16.9.0",
|
||||
|
||||
+143
-130
@@ -10,7 +10,6 @@ import {
|
||||
makeHeaderGroups,
|
||||
findMaxDepth,
|
||||
flattenBy,
|
||||
determineColumnVisibility,
|
||||
} from '../utils'
|
||||
|
||||
import { useTableState } from './useTableState'
|
||||
@@ -50,24 +49,27 @@ export const useTable = (props, ...plugins) => {
|
||||
|
||||
debug = process.env.NODE_ENV === 'production' ? false : debug
|
||||
|
||||
// Always provide a default table state
|
||||
// Always provide a default state
|
||||
const defaultState = useTableState()
|
||||
|
||||
// But use the users table state if provided
|
||||
// But use the users state if provided
|
||||
const state = userState || defaultState
|
||||
|
||||
// The table instance ref
|
||||
// The initial api
|
||||
let instanceRef = React.useRef({})
|
||||
|
||||
Object.assign(instanceRef.current, {
|
||||
...props,
|
||||
data, // The raw data
|
||||
state, // The resolved table state
|
||||
plugins, // All resolved plugins
|
||||
data,
|
||||
state,
|
||||
plugins,
|
||||
hooks: {
|
||||
columnsBeforeHeaderGroups: [],
|
||||
columnsBeforeHeaderGroupsDeps: [],
|
||||
useMain: [],
|
||||
useColumns: [],
|
||||
useHeaders: [],
|
||||
useHeaderGroups: [],
|
||||
useRows: [],
|
||||
prepareRow: [],
|
||||
getTableProps: [],
|
||||
@@ -80,54 +82,61 @@ export const useTable = (props, ...plugins) => {
|
||||
|
||||
// Allow plugins to register hooks
|
||||
if (process.env.NODE_ENV === 'development' && debug) console.time('plugins')
|
||||
|
||||
plugins.filter(Boolean).forEach(plugin => {
|
||||
plugin(instanceRef.current.hooks)
|
||||
})
|
||||
|
||||
if (process.env.NODE_ENV === 'development' && debug)
|
||||
console.timeEnd('plugins')
|
||||
|
||||
if (process.env.NODE_ENV === 'development' && debug)
|
||||
console.info('buildColumns/headerGroup/headers')
|
||||
// Decorate All the columns
|
||||
let headers = React.useMemo(
|
||||
let columnTree = React.useMemo(
|
||||
() => decorateColumnTree(userColumns, defaultColumn),
|
||||
[defaultColumn, userColumns]
|
||||
)
|
||||
|
||||
// Get the flat list of all columns
|
||||
let columns = React.useMemo(() => flattenBy(headers, 'columns'), [headers])
|
||||
let columns = React.useMemo(() => flattenBy(columnTree, 'columns'), [
|
||||
columnTree,
|
||||
])
|
||||
|
||||
// Allow hooks to decorate columns (and trigger this memoization via deps)
|
||||
columns = React.useMemo(() => {
|
||||
if (process.env.NODE_ENV === 'development' && debug)
|
||||
console.time('hooks.columnsBeforeHeaderGroups')
|
||||
|
||||
let newColumns = applyHooks(
|
||||
instanceRef.current.hooks.columnsBeforeHeaderGroups,
|
||||
columns = React.useMemo(
|
||||
() => {
|
||||
if (process.env.NODE_ENV === 'development' && debug)
|
||||
console.time('hooks.columnsBeforeHeaderGroups')
|
||||
const newColumns = applyHooks(
|
||||
instanceRef.current.hooks.columnsBeforeHeaderGroups,
|
||||
columns,
|
||||
instanceRef.current
|
||||
)
|
||||
if (process.env.NODE_ENV === 'development' && debug)
|
||||
console.timeEnd('hooks.columnsBeforeHeaderGroups')
|
||||
return newColumns
|
||||
},
|
||||
[
|
||||
columns,
|
||||
instanceRef.current
|
||||
)
|
||||
|
||||
if (process.env.NODE_ENV === 'development' && debug)
|
||||
console.timeEnd('hooks.columnsBeforeHeaderGroups')
|
||||
return newColumns
|
||||
}, [
|
||||
columns,
|
||||
debug,
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
...applyHooks(
|
||||
instanceRef.current.hooks.columnsBeforeHeaderGroupsDeps,
|
||||
[],
|
||||
instanceRef.current
|
||||
),
|
||||
])
|
||||
debug,
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
...applyHooks(
|
||||
instanceRef.current.hooks.columnsBeforeHeaderGroupsDeps,
|
||||
[],
|
||||
instanceRef.current
|
||||
),
|
||||
]
|
||||
)
|
||||
|
||||
// Make the headerGroups
|
||||
const headerGroups = React.useMemo(
|
||||
() => makeHeaderGroups(columns, findMaxDepth(headers), defaultColumn),
|
||||
[columns, defaultColumn, headers]
|
||||
() => makeHeaderGroups(columns, findMaxDepth(columnTree), defaultColumn),
|
||||
[columnTree, columns, defaultColumn]
|
||||
)
|
||||
|
||||
const headers = React.useMemo(() => flattenBy(headerGroups, 'headers'), [
|
||||
headerGroups,
|
||||
])
|
||||
|
||||
Object.assign(instanceRef.current, {
|
||||
columns,
|
||||
headerGroups,
|
||||
@@ -135,82 +144,84 @@ export const useTable = (props, ...plugins) => {
|
||||
})
|
||||
|
||||
// Access the row model
|
||||
const [rows, rowPaths, flatRows] = React.useMemo(() => {
|
||||
if (process.env.NODE_ENV === 'development' && debug)
|
||||
console.time('getAccessedRows')
|
||||
const [rows, rowPaths, flatRows] = React.useMemo(
|
||||
() => {
|
||||
if (process.env.NODE_ENV === 'development' && debug)
|
||||
console.time('getAccessedRows')
|
||||
|
||||
let flatRows = 0
|
||||
const rowPaths = []
|
||||
let flatRows = 0
|
||||
const rowPaths = []
|
||||
|
||||
// Access the row's data
|
||||
const accessRow = (originalRow, i, depth = 0, parentPath = []) => {
|
||||
// Keep the original reference around
|
||||
const original = originalRow
|
||||
// Access the row's data
|
||||
const accessRow = (originalRow, i, depth = 0, parentPath = []) => {
|
||||
// Keep the original reference around
|
||||
const original = originalRow
|
||||
|
||||
// Make the new path for the row
|
||||
const path = [...parentPath, i]
|
||||
// Make the new path for the row
|
||||
const path = [...parentPath, i]
|
||||
|
||||
flatRows++
|
||||
rowPaths.push(path.join('.'))
|
||||
flatRows++
|
||||
rowPaths.push(path.join('.'))
|
||||
|
||||
// Process any subRows
|
||||
const subRows = originalRow[subRowsKey]
|
||||
? originalRow[subRowsKey].map((d, i) =>
|
||||
accessRow(d, i, depth + 1, path)
|
||||
// Process any subRows
|
||||
const subRows = originalRow[subRowsKey]
|
||||
? originalRow[subRowsKey].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
|
||||
}
|
||||
|
||||
// Override common array functions (and the dummy cell's getCellProps function)
|
||||
// to show an error if it is accessed without calling prepareRow
|
||||
const unpreparedAccessWarning = () => {
|
||||
throw new Error(
|
||||
'React-Table: You have not called prepareRow(row) one or more rows you are attempting to render.'
|
||||
)
|
||||
: []
|
||||
}
|
||||
row.cells.map = unpreparedAccessWarning
|
||||
row.cells.filter = unpreparedAccessWarning
|
||||
row.cells.forEach = unpreparedAccessWarning
|
||||
row.cells[0].getCellProps = unpreparedAccessWarning
|
||||
|
||||
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
|
||||
// Create the cells and values
|
||||
row.values = {}
|
||||
instanceRef.current.columns.forEach(column => {
|
||||
row.values[column.id] = column.accessor
|
||||
? column.accessor(originalRow, i, { subRows, depth, data })
|
||||
: undefined
|
||||
})
|
||||
|
||||
return row
|
||||
}
|
||||
|
||||
// Override common array functions (and the dummy cell's getCellProps function)
|
||||
// to show an error if it is accessed without calling prepareRow
|
||||
const unpreparedAccessWarning = () => {
|
||||
throw new Error(
|
||||
'React-Table: You have not called prepareRow(row) one or more rows you are attempting to render.'
|
||||
)
|
||||
}
|
||||
row.cells.map = unpreparedAccessWarning
|
||||
row.cells.filter = unpreparedAccessWarning
|
||||
row.cells.forEach = unpreparedAccessWarning
|
||||
row.cells[0].getCellProps = unpreparedAccessWarning
|
||||
|
||||
// Create the cells and values
|
||||
row.values = {}
|
||||
columns.forEach(column => {
|
||||
row.values[column.id] = column.accessor
|
||||
? column.accessor(originalRow, i, { subRows, depth, data })
|
||||
: undefined
|
||||
})
|
||||
|
||||
return row
|
||||
}
|
||||
|
||||
// Use the resolved data
|
||||
const accessedData = data.map((d, i) => accessRow(d, i))
|
||||
if (process.env.NODE_ENV === 'development' && debug)
|
||||
console.timeEnd('getAccessedRows')
|
||||
return [accessedData, rowPaths, flatRows]
|
||||
}, [debug, data, columns, subRowsKey])
|
||||
// Use the resolved data
|
||||
const accessedData = data.map((d, i) => accessRow(d, i))
|
||||
if (process.env.NODE_ENV === 'development' && debug)
|
||||
console.timeEnd('getAccessedRows')
|
||||
return [accessedData, rowPaths, flatRows]
|
||||
},
|
||||
[debug, data, subRowsKey]
|
||||
)
|
||||
|
||||
instanceRef.current.rows = rows
|
||||
instanceRef.current.rowPaths = rowPaths
|
||||
instanceRef.current.flatRows = flatRows
|
||||
|
||||
// Determine column visibility
|
||||
determineColumnVisibility(instanceRef.current)
|
||||
|
||||
// Provide a flat header list for utilities
|
||||
instanceRef.current.flatHeaders = headerGroups.reduce(
|
||||
(all, headerGroup) => [...all, ...headerGroup.headers],
|
||||
[]
|
||||
)
|
||||
instanceRef.current.columns.forEach(column => {
|
||||
column.visible =
|
||||
typeof column.show === 'function'
|
||||
? column.show(instanceRef.current)
|
||||
: !!column.show
|
||||
})
|
||||
|
||||
if (process.env.NODE_ENV === 'development' && debug)
|
||||
console.time('hooks.useMain')
|
||||
@@ -220,42 +231,43 @@ export const useTable = (props, ...plugins) => {
|
||||
)
|
||||
if (process.env.NODE_ENV === 'development' && debug)
|
||||
console.timeEnd('hooks.useMain')
|
||||
;[...instanceRef.current.columns, ...instanceRef.current.headers].forEach(
|
||||
column => {
|
||||
// Give columns/headers rendering power
|
||||
column.render = (type, userProps = {}) => {
|
||||
const Comp = typeof type === 'string' ? column[type] : type
|
||||
|
||||
// Each materialized header needs to be assigned a render function and other
|
||||
// prop getter properties here.
|
||||
instanceRef.current.flatHeaders.forEach(column => {
|
||||
// Give columns/headers rendering power
|
||||
column.render = (type, userProps = {}) => {
|
||||
const Comp = typeof type === 'string' ? column[type] : type
|
||||
if (typeof Comp === 'undefined') {
|
||||
throw new Error(renderErr)
|
||||
}
|
||||
|
||||
if (typeof Comp === 'undefined') {
|
||||
throw new Error(renderErr)
|
||||
return flexRender(Comp, {
|
||||
...instanceRef.current,
|
||||
column,
|
||||
...userProps,
|
||||
})
|
||||
}
|
||||
|
||||
return flexRender(Comp, {
|
||||
...instanceRef.current,
|
||||
column,
|
||||
...userProps,
|
||||
})
|
||||
// Give columns/headers a default getHeaderProps
|
||||
column.getHeaderProps = props =>
|
||||
mergeProps(
|
||||
{
|
||||
key: ['header', column.id].join('_'),
|
||||
colSpan: column.columns
|
||||
? column.columns.filter(column => column.visible).length
|
||||
: 1,
|
||||
},
|
||||
applyPropHooks(
|
||||
instanceRef.current.hooks.getHeaderProps,
|
||||
column,
|
||||
instanceRef.current
|
||||
),
|
||||
props
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
// Give columns/headers a default getHeaderProps
|
||||
column.getHeaderProps = props =>
|
||||
mergeProps(
|
||||
{
|
||||
key: ['header', column.id].join('_'),
|
||||
colSpan: column.totalHeaderCount,
|
||||
},
|
||||
applyPropHooks(
|
||||
instanceRef.current.hooks.getHeaderProps,
|
||||
column,
|
||||
instanceRef.current
|
||||
),
|
||||
props
|
||||
)
|
||||
})
|
||||
|
||||
instanceRef.current.headerGroups.forEach((headerGroup, i) => {
|
||||
instanceRef.current.headerGroups.filter((headerGroup, i) => {
|
||||
// Filter out any headers and headerGroups that don't have visible columns
|
||||
headerGroup.headers = headerGroup.headers.filter(header => {
|
||||
const recurse = columns =>
|
||||
@@ -263,12 +275,12 @@ export const useTable = (props, ...plugins) => {
|
||||
if (column.columns) {
|
||||
return recurse(column.columns)
|
||||
}
|
||||
return column.isVisible
|
||||
return column.visible
|
||||
}).length
|
||||
if (header.columns) {
|
||||
return recurse(header.columns)
|
||||
}
|
||||
return header.isVisible
|
||||
return header.visible
|
||||
})
|
||||
|
||||
// Give headerGroups getRowProps
|
||||
@@ -285,9 +297,10 @@ export const useTable = (props, ...plugins) => {
|
||||
),
|
||||
props
|
||||
)
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
})
|
||||
|
||||
// Run the rows (this could be a dangerous hook with a ton of data)
|
||||
@@ -317,7 +330,7 @@ export const useTable = (props, ...plugins) => {
|
||||
)
|
||||
|
||||
const visibleColumns = instanceRef.current.columns.filter(
|
||||
column => column.isVisible
|
||||
column => column.visible
|
||||
)
|
||||
|
||||
// Build the cells for each row
|
||||
|
||||
@@ -9,4 +9,5 @@ export { useSortBy } from './plugin-hooks/useSortBy'
|
||||
export { usePagination } from './plugin-hooks/usePagination'
|
||||
export { useRowSelect } from './plugin-hooks/useRowSelect'
|
||||
export { useRowState } from './plugin-hooks/useRowState'
|
||||
export { useFlexLayout } from './plugin-hooks/useFlexLayout'
|
||||
export { actions, addActions } from './actions'
|
||||
|
||||
@@ -19,7 +19,7 @@ Snapshot Diff:
|
||||
</pre>
|
||||
<table
|
||||
class=""
|
||||
@@ -78,10 +80,53 @@
|
||||
@@ -82,10 +84,53 @@
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
@@ -73,7 +73,7 @@ Snapshot Diff:
|
||||
</span>
|
||||
</td>
|
||||
<td
|
||||
@@ -111,10 +156,139 @@
|
||||
@@ -115,10 +160,139 @@
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
@@ -235,7 +235,7 @@ Snapshot Diff:
|
||||
</code>
|
||||
</pre>
|
||||
<table
|
||||
@@ -123,10 +125,53 @@
|
||||
@@ -127,10 +129,53 @@
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
@@ -289,7 +289,7 @@ Snapshot Diff:
|
||||
</span>
|
||||
</td>
|
||||
<td
|
||||
@@ -156,10 +201,139 @@
|
||||
@@ -160,10 +205,139 @@
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
@@ -451,7 +451,7 @@ Snapshot Diff:
|
||||
}
|
||||
</code>
|
||||
</pre>
|
||||
@@ -168,10 +170,53 @@
|
||||
@@ -172,10 +174,53 @@
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
@@ -505,7 +505,7 @@ Snapshot Diff:
|
||||
</span>
|
||||
</td>
|
||||
<td
|
||||
@@ -201,10 +246,139 @@
|
||||
@@ -205,10 +250,139 @@
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
@@ -667,7 +667,7 @@ Snapshot Diff:
|
||||
}
|
||||
}
|
||||
</code>
|
||||
@@ -214,11 +216,11 @@
|
||||
@@ -218,11 +220,11 @@
|
||||
class=""
|
||||
>
|
||||
<span
|
||||
@@ -680,7 +680,7 @@ Snapshot Diff:
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
@@ -246,10 +248,30 @@
|
||||
@@ -250,10 +252,30 @@
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||
|
||||
exports[`renders a table with selectable rows 1`] = `
|
||||
exports[`renders a table with seletable rows 1`] = `
|
||||
Snapshot Diff:
|
||||
- First value
|
||||
+ Second value
|
||||
|
||||
@@ -101,11 +101,11 @@
|
||||
@@ -109,11 +109,11 @@
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
@@ -18,7 +18,7 @@ Snapshot Diff:
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
@@ -157,11 +157,11 @@
|
||||
@@ -165,11 +165,11 @@
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
@@ -31,7 +31,7 @@ Snapshot Diff:
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
@@ -213,11 +213,11 @@
|
||||
@@ -221,11 +221,11 @@
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
@@ -44,7 +44,7 @@ Snapshot Diff:
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
@@ -269,11 +269,11 @@
|
||||
@@ -277,11 +277,11 @@
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
@@ -57,40 +57,14 @@ Snapshot Diff:
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
@@ -325,11 +325,11 @@
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
<div>
|
||||
- Not Selected
|
||||
+ Selected
|
||||
</div>
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
@@ -381,11 +381,11 @@
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
<div>
|
||||
- Not Selected
|
||||
+ Selected
|
||||
</div>
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
@@ -418,15 +418,22 @@
|
||||
@@ -314,15 +314,20 @@
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p>
|
||||
- Selected Rows: 0
|
||||
+ Selected Rows: 6
|
||||
+ Selected Rows: 4
|
||||
</p>
|
||||
<pre>
|
||||
<code>
|
||||
@@ -100,8 +74,6 @@ Snapshot Diff:
|
||||
+ "0",
|
||||
+ "1",
|
||||
+ "2",
|
||||
+ "2.0",
|
||||
+ "2.1",
|
||||
+ "3"
|
||||
+ ]
|
||||
}
|
||||
@@ -110,12 +82,12 @@ Snapshot Diff:
|
||||
</DocumentFragment>
|
||||
`;
|
||||
|
||||
exports[`renders a table with selectable rows 2`] = `
|
||||
exports[`renders a table with seletable rows 2`] = `
|
||||
Snapshot Diff:
|
||||
- First value
|
||||
+ Second value
|
||||
|
||||
@@ -101,11 +101,11 @@
|
||||
@@ -109,11 +109,11 @@
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
@@ -128,7 +100,7 @@ Snapshot Diff:
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
@@ -157,11 +157,11 @@
|
||||
@@ -165,11 +165,11 @@
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
@@ -141,7 +113,7 @@ Snapshot Diff:
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
@@ -213,11 +213,11 @@
|
||||
@@ -221,11 +221,11 @@
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
@@ -154,7 +126,7 @@ Snapshot Diff:
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
@@ -269,11 +269,11 @@
|
||||
@@ -277,11 +277,11 @@
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
@@ -167,39 +139,13 @@ Snapshot Diff:
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
@@ -325,11 +325,11 @@
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
<div>
|
||||
- Selected
|
||||
+ Not Selected
|
||||
</div>
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
@@ -381,11 +381,11 @@
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
<div>
|
||||
- Selected
|
||||
+ Not Selected
|
||||
</div>
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
@@ -418,22 +418,15 @@
|
||||
@@ -314,20 +314,15 @@
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p>
|
||||
- Selected Rows: 6
|
||||
- Selected Rows: 4
|
||||
+ Selected Rows: 0
|
||||
</p>
|
||||
<pre>
|
||||
@@ -209,8 +155,6 @@ Snapshot Diff:
|
||||
- "0",
|
||||
- "1",
|
||||
- "2",
|
||||
- "2.0",
|
||||
- "2.1",
|
||||
- "3"
|
||||
- ]
|
||||
+ "selectedRows": []
|
||||
@@ -220,12 +164,12 @@ Snapshot Diff:
|
||||
</DocumentFragment>
|
||||
`;
|
||||
|
||||
exports[`renders a table with selectable rows 3`] = `
|
||||
exports[`renders a table with seletable rows 3`] = `
|
||||
Snapshot Diff:
|
||||
- First value
|
||||
+ Second value
|
||||
|
||||
@@ -101,11 +101,11 @@
|
||||
@@ -109,11 +109,11 @@
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
@@ -238,7 +182,7 @@ Snapshot Diff:
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
@@ -213,11 +213,11 @@
|
||||
@@ -221,11 +221,11 @@
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
@@ -251,40 +195,14 @@ Snapshot Diff:
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
@@ -269,11 +269,11 @@
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
<div>
|
||||
- Not Selected
|
||||
+ Selected
|
||||
</div>
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
@@ -325,11 +325,11 @@
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
<div>
|
||||
- Not Selected
|
||||
+ Selected
|
||||
</div>
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
@@ -418,15 +418,20 @@
|
||||
@@ -314,15 +314,18 @@
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p>
|
||||
- Selected Rows: 0
|
||||
+ Selected Rows: 4
|
||||
+ Selected Rows: 2
|
||||
</p>
|
||||
<pre>
|
||||
<code>
|
||||
@@ -292,234 +210,10 @@ Snapshot Diff:
|
||||
- "selectedRows": []
|
||||
+ "selectedRows": [
|
||||
+ "0",
|
||||
+ "2",
|
||||
+ "2.0",
|
||||
+ "2.1"
|
||||
+ "2"
|
||||
+ ]
|
||||
}
|
||||
</code>
|
||||
</pre>
|
||||
</DocumentFragment>
|
||||
`;
|
||||
|
||||
exports[`renders a table with selectable rows 4`] = `
|
||||
Snapshot Diff:
|
||||
- First value
|
||||
+ Second value
|
||||
|
||||
@@ -213,11 +213,11 @@
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
<div>
|
||||
- Selected
|
||||
+ Not Selected
|
||||
</div>
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
@@ -269,11 +269,11 @@
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
<div>
|
||||
- Selected
|
||||
+ Not Selected
|
||||
</div>
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
@@ -325,11 +325,11 @@
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
<div>
|
||||
- Selected
|
||||
+ Not Selected
|
||||
</div>
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
@@ -418,20 +418,17 @@
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p>
|
||||
- Selected Rows: 4
|
||||
+ Selected Rows: 1
|
||||
</p>
|
||||
<pre>
|
||||
<code>
|
||||
{
|
||||
"selectedRows": [
|
||||
- "0",
|
||||
- "2",
|
||||
- "2.0",
|
||||
- "2.1"
|
||||
+ "0"
|
||||
]
|
||||
}
|
||||
</code>
|
||||
</pre>
|
||||
</DocumentFragment>
|
||||
`;
|
||||
|
||||
exports[`renders a table with selectable rows 5`] = `
|
||||
Snapshot Diff:
|
||||
- First value
|
||||
+ Second value
|
||||
|
||||
@@ -269,11 +269,11 @@
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
<div>
|
||||
- Not Selected
|
||||
+ Selected
|
||||
</div>
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
@@ -418,17 +418,18 @@
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p>
|
||||
- Selected Rows: 1
|
||||
+ Selected Rows: 2
|
||||
</p>
|
||||
<pre>
|
||||
<code>
|
||||
{
|
||||
"selectedRows": [
|
||||
- "0"
|
||||
+ "0",
|
||||
+ "2.0"
|
||||
]
|
||||
}
|
||||
</code>
|
||||
</pre>
|
||||
</DocumentFragment>
|
||||
`;
|
||||
|
||||
exports[`renders a table with selectable rows 6`] = `
|
||||
Snapshot Diff:
|
||||
- First value
|
||||
+ Second value
|
||||
|
||||
@@ -213,11 +213,11 @@
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
<div>
|
||||
- Not Selected
|
||||
+ Selected
|
||||
</div>
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
@@ -325,11 +325,11 @@
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
<div>
|
||||
- Not Selected
|
||||
+ Selected
|
||||
</div>
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
@@ -418,18 +418,20 @@
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p>
|
||||
- Selected Rows: 2
|
||||
+ Selected Rows: 4
|
||||
</p>
|
||||
<pre>
|
||||
<code>
|
||||
{
|
||||
"selectedRows": [
|
||||
"0",
|
||||
- "2.0"
|
||||
+ "2.0",
|
||||
+ "2.1",
|
||||
+ "2"
|
||||
]
|
||||
}
|
||||
</code>
|
||||
</pre>
|
||||
</DocumentFragment>
|
||||
`;
|
||||
|
||||
exports[`renders a table with selectable rows 7`] = `
|
||||
Snapshot Diff:
|
||||
- First value
|
||||
+ Second value
|
||||
|
||||
@@ -213,11 +213,11 @@
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
<div>
|
||||
- Selected
|
||||
+ Not Selected
|
||||
</div>
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
@@ -325,11 +325,11 @@
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
<div>
|
||||
- Selected
|
||||
+ Not Selected
|
||||
</div>
|
||||
</td>
|
||||
<td
|
||||
class=""
|
||||
>
|
||||
@@ -418,20 +418,18 @@
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p>
|
||||
- Selected Rows: 4
|
||||
+ Selected Rows: 2
|
||||
</p>
|
||||
<pre>
|
||||
<code>
|
||||
{
|
||||
"selectedRows": [
|
||||
"0",
|
||||
- "2.0",
|
||||
- "2.1",
|
||||
- "2"
|
||||
+ "2.0"
|
||||
]
|
||||
}
|
||||
</code>
|
||||
</pre>
|
||||
</DocumentFragment>
|
||||
`;
|
||||
|
||||
@@ -73,7 +73,7 @@ function Table({ columns, data }) {
|
||||
{column.canGroupBy ? (
|
||||
// If the column can be grouped, let's add a toggle
|
||||
<span {...column.getGroupByToggleProps()}>
|
||||
{column.isGrouped ? '🛑' : '👊'}
|
||||
{column.grouped ? '🛑' : '👊'}
|
||||
</span>
|
||||
) : null}
|
||||
{column.render('Header')}
|
||||
@@ -90,7 +90,7 @@ function Table({ columns, data }) {
|
||||
{row.cells.map(cell => {
|
||||
return (
|
||||
<td {...cell.getCellProps()}>
|
||||
{cell.isGrouped ? (
|
||||
{cell.grouped ? (
|
||||
<>
|
||||
<span
|
||||
style={{
|
||||
@@ -102,9 +102,9 @@ function Table({ columns, data }) {
|
||||
</span>
|
||||
{cell.render('Cell')} ({row.subRows.length})
|
||||
</>
|
||||
) : cell.isAggregated ? (
|
||||
) : cell.aggregated ? (
|
||||
cell.render('Aggregated')
|
||||
) : cell.isRepeatedValue ? null : (
|
||||
) : cell.repeatedValue ? null : (
|
||||
cell.render('Cell')
|
||||
)}
|
||||
</td>
|
||||
|
||||
@@ -2,7 +2,6 @@ import React from 'react'
|
||||
import { render, fireEvent } from '@testing-library/react'
|
||||
import { useTable } from '../../hooks/useTable'
|
||||
import { useRowSelect } from '../useRowSelect'
|
||||
import { useExpanded } from '../useExpanded'
|
||||
|
||||
const data = [
|
||||
{
|
||||
@@ -28,25 +27,6 @@ const data = [
|
||||
visits: 20,
|
||||
status: 'Complicated',
|
||||
progress: 10,
|
||||
expanded: true,
|
||||
subRows: [
|
||||
{
|
||||
firstName: 'bob',
|
||||
lastName: 'ross',
|
||||
age: 52,
|
||||
visits: 40,
|
||||
status: 'In Relationship',
|
||||
progress: 30,
|
||||
},
|
||||
{
|
||||
firstName: 'john',
|
||||
lastName: 'smith',
|
||||
age: 21,
|
||||
visits: 30,
|
||||
status: 'Single',
|
||||
progress: 60,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
firstName: 'jaylen',
|
||||
@@ -71,8 +51,7 @@ function Table({ columns, data }) {
|
||||
columns,
|
||||
data,
|
||||
},
|
||||
useRowSelect,
|
||||
useExpanded
|
||||
useRowSelect
|
||||
)
|
||||
|
||||
// Render the UI for your table
|
||||
@@ -141,7 +120,7 @@ function App() {
|
||||
{
|
||||
id: 'selectedStatus',
|
||||
Cell: ({ row }) => (
|
||||
<div>{row.isSelected ? 'Selected' : 'Not Selected'}</div>
|
||||
<div>{row.selected ? 'Selected' : 'Not Selected'}</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -185,7 +164,7 @@ function App() {
|
||||
return <Table columns={columns} data={data} />
|
||||
}
|
||||
|
||||
test('renders a table with selectable rows', () => {
|
||||
test('renders a table with seletable rows', () => {
|
||||
const { getByLabelText, getAllByLabelText, asFragment } = render(<App />)
|
||||
|
||||
const fragment1 = asFragment()
|
||||
@@ -203,27 +182,7 @@ test('renders a table with selectable rows', () => {
|
||||
|
||||
const fragment4 = asFragment()
|
||||
|
||||
fireEvent.click(getAllByLabelText('Select Row')[2])
|
||||
|
||||
const fragment5 = asFragment()
|
||||
|
||||
fireEvent.click(getAllByLabelText('Select Row')[3])
|
||||
|
||||
const fragment6 = asFragment()
|
||||
fireEvent.click(getAllByLabelText('Select Row')[4])
|
||||
|
||||
const fragment7 = asFragment()
|
||||
|
||||
fireEvent.click(getAllByLabelText('Select Row')[4])
|
||||
|
||||
const fragment8 = asFragment()
|
||||
|
||||
|
||||
expect(fragment1).toMatchDiffSnapshot(fragment2)
|
||||
expect(fragment2).toMatchDiffSnapshot(fragment3)
|
||||
expect(fragment3).toMatchDiffSnapshot(fragment4)
|
||||
expect(fragment4).toMatchDiffSnapshot(fragment5)
|
||||
expect(fragment5).toMatchDiffSnapshot(fragment6)
|
||||
expect(fragment6).toMatchDiffSnapshot(fragment7)
|
||||
expect(fragment7).toMatchDiffSnapshot(fragment8)
|
||||
})
|
||||
|
||||
@@ -56,7 +56,7 @@ function Table({ columns, data }) {
|
||||
{column.render('Header')}
|
||||
{/* Add a sort direction indicator */}
|
||||
<span>
|
||||
{column.isSorted ? (column.isSortedDesc ? ' 🔽' : ' 🔼') : ''}
|
||||
{column.sorted ? (column.sortedDesc ? ' 🔽' : ' 🔼') : ''}
|
||||
</span>
|
||||
</th>
|
||||
))}
|
||||
|
||||
@@ -17,7 +17,7 @@ addActions('toggleExpanded', 'useExpanded')
|
||||
|
||||
const propTypes = {
|
||||
manualExpandedKey: PropTypes.string,
|
||||
paginateExpandedRows: PropTypes.bool,
|
||||
nestExpandedRows: PropTypes.bool,
|
||||
}
|
||||
|
||||
export const useExpanded = hooks => {
|
||||
@@ -34,16 +34,16 @@ function useMain(instance) {
|
||||
debug,
|
||||
rows,
|
||||
manualExpandedKey = 'expanded',
|
||||
paginateExpandedRows = true,
|
||||
hooks,
|
||||
state: [{ expanded }, setState],
|
||||
nestExpandedRows,
|
||||
} = instance
|
||||
|
||||
const toggleExpandedByPath = (path, set) => {
|
||||
return setState(old => {
|
||||
const { expanded } = old
|
||||
const existing = getBy(expanded, path)
|
||||
set = getFirstDefined(set, existing ? undefined : true)
|
||||
set = getFirstDefined(set, !existing)
|
||||
return {
|
||||
...old,
|
||||
expanded: setBy(expanded, path, set),
|
||||
@@ -85,16 +85,13 @@ function useMain(instance) {
|
||||
(row.original && row.original[manualExpandedKey]) ||
|
||||
getBy(expanded, row.path)
|
||||
|
||||
expandedRows.push(row)
|
||||
if (!nestExpandedRows || (nestExpandedRows && row.depth === 0)) {
|
||||
expandedRows.push(row)
|
||||
}
|
||||
|
||||
row.canExpand = row.subRows && !!row.subRows.length
|
||||
|
||||
if (
|
||||
paginateExpandedRows &&
|
||||
row.isExpanded &&
|
||||
row.subRows &&
|
||||
row.subRows.length
|
||||
) {
|
||||
if (row.isExpanded && row.subRows && row.subRows.length) {
|
||||
row.subRows.forEach(handleRow)
|
||||
}
|
||||
|
||||
@@ -104,7 +101,7 @@ function useMain(instance) {
|
||||
rows.forEach(handleRow)
|
||||
|
||||
return expandedRows
|
||||
}, [debug, rows, manualExpandedKey, expanded, paginateExpandedRows])
|
||||
}, [debug, rows, manualExpandedKey, expanded, nestExpandedRows])
|
||||
|
||||
const expandedDepth = findExpandedDepth(expanded)
|
||||
|
||||
|
||||
@@ -129,87 +129,92 @@ 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(() => {
|
||||
if (manualFilters || !Object.keys(filters).length) {
|
||||
return rows
|
||||
}
|
||||
const filteredRows = React.useMemo(
|
||||
() => {
|
||||
if (manualFilters || !Object.keys(filters).length) {
|
||||
return rows
|
||||
}
|
||||
|
||||
if (process.env.NODE_ENV === 'development' && debug)
|
||||
console.info('getFilteredRows')
|
||||
if (process.env.NODE_ENV === 'development' && debug)
|
||||
console.info('getFilteredRows')
|
||||
|
||||
// Filters top level and nested rows
|
||||
const filterRows = (rows, depth = 0) => {
|
||||
let filteredRows = rows
|
||||
// Filters top level and nested rows
|
||||
const filterRows = (rows, depth = 0) => {
|
||||
let filteredRows = rows
|
||||
|
||||
filteredRows = Object.entries(filters).reduce(
|
||||
(filteredSoFar, [columnID, filterValue]) => {
|
||||
// Find the filters column
|
||||
const column = columns.find(d => d.id === columnID)
|
||||
filteredRows = Object.entries(filters).reduce(
|
||||
(filteredSoFar, [columnID, filterValue]) => {
|
||||
// Find the filters column
|
||||
const column = columns.find(d => d.id === columnID)
|
||||
|
||||
if (!column) {
|
||||
return filteredSoFar
|
||||
}
|
||||
if (depth === 0) {
|
||||
column.preFilteredRows = filteredSoFar
|
||||
}
|
||||
|
||||
if (depth === 0) {
|
||||
column.preFilteredRows = filteredSoFar
|
||||
}
|
||||
if (!column) {
|
||||
return filteredSoFar
|
||||
}
|
||||
|
||||
const filterMethod = getFilterMethod(
|
||||
column.filter,
|
||||
userFilterTypes || {},
|
||||
filterTypes
|
||||
)
|
||||
|
||||
if (!filterMethod) {
|
||||
console.warn(
|
||||
`Could not find a valid 'column.filter' for column with the ID: ${column.id}.`
|
||||
const filterMethod = getFilterMethod(
|
||||
column.filter,
|
||||
userFilterTypes || {},
|
||||
filterTypes
|
||||
)
|
||||
return filteredSoFar
|
||||
}
|
||||
|
||||
// Pass the rows, id, filterValue and column to the filterMethod
|
||||
// to get the filtered rows back
|
||||
return filterMethod(filteredSoFar, columnID, filterValue, column)
|
||||
},
|
||||
rows
|
||||
if (!filterMethod) {
|
||||
console.warn(
|
||||
`Could not find a valid 'column.filter' for column with the ID: ${
|
||||
column.id
|
||||
}.`
|
||||
)
|
||||
return filteredSoFar
|
||||
}
|
||||
|
||||
// Pass the rows, id, filterValue and column to the filterMethod
|
||||
// to get the filtered rows back
|
||||
return filterMethod(filteredSoFar, columnID, filterValue, column)
|
||||
},
|
||||
rows
|
||||
)
|
||||
|
||||
// Apply the filter to any subRows
|
||||
// We technically could do this recursively in the above loop,
|
||||
// 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 => {
|
||||
if (!row.subRows) {
|
||||
return row
|
||||
}
|
||||
return {
|
||||
...row,
|
||||
subRows:
|
||||
row.subRows && row.subRows.length > 0
|
||||
? filterRows(row.subRows, depth + 1)
|
||||
: row.subRows,
|
||||
}
|
||||
})
|
||||
|
||||
return filteredRows
|
||||
}
|
||||
|
||||
const filteredRows = filterRows(rows)
|
||||
|
||||
// Now that each filtered column has it's partially filtered rows,
|
||||
// lets assign the final filtered rows to all of the other columns
|
||||
const nonFilteredColumns = columns.filter(
|
||||
column => !Object.keys(filters).includes(column.id)
|
||||
)
|
||||
|
||||
// Apply the filter to any subRows
|
||||
// We technically could do this recursively in the above loop,
|
||||
// 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 => {
|
||||
if (!row.subRows) {
|
||||
return row
|
||||
}
|
||||
return {
|
||||
...row,
|
||||
subRows:
|
||||
row.subRows && row.subRows.length > 0
|
||||
? filterRows(row.subRows, depth + 1)
|
||||
: row.subRows,
|
||||
}
|
||||
// This essentially enables faceted filter options to be built easily
|
||||
// using every column's preFilteredRows value
|
||||
nonFilteredColumns.forEach(column => {
|
||||
column.preFilteredRows = filteredRows
|
||||
})
|
||||
|
||||
return filteredRows
|
||||
}
|
||||
|
||||
return filterRows(rows)
|
||||
}, [manualFilters, filters, debug, rows, columns, userFilterTypes])
|
||||
|
||||
React.useMemo(() => {
|
||||
// Now that each filtered column has it's partially filtered rows,
|
||||
// lets assign the final filtered rows to all of the other columns
|
||||
const nonFilteredColumns = columns.filter(
|
||||
column => !Object.keys(filters).includes(column.id)
|
||||
)
|
||||
|
||||
// This essentially enables faceted filter options to be built easily
|
||||
// using every column's preFilteredRows value
|
||||
nonFilteredColumns.forEach(column => {
|
||||
column.preFilteredRows = filteredRows
|
||||
})
|
||||
}, [columns, filteredRows, filters])
|
||||
},
|
||||
[manualFilters, filters, debug, rows, columns, userFilterTypes]
|
||||
)
|
||||
|
||||
return {
|
||||
...instance,
|
||||
|
||||
Executable
+144
@@ -0,0 +1,144 @@
|
||||
import PropTypes from 'prop-types'
|
||||
|
||||
import { getFirstDefined, sum } from '../utils'
|
||||
|
||||
export const actions = {}
|
||||
|
||||
const propTypes = {
|
||||
defaultFlex: PropTypes.number,
|
||||
}
|
||||
|
||||
export const useFlexLayout = hooks => {
|
||||
hooks.useMain.push(useMain)
|
||||
}
|
||||
|
||||
function useMain(instance) {
|
||||
PropTypes.checkPropTypes(propTypes, instance, 'property', 'useFlexLayout')
|
||||
|
||||
const {
|
||||
defaultFlex = 1,
|
||||
hooks: {
|
||||
columns: columnsHooks,
|
||||
getRowProps,
|
||||
getHeaderGroupProps,
|
||||
getHeaderProps,
|
||||
getCellProps,
|
||||
},
|
||||
} = instance
|
||||
|
||||
columnsHooks.push((columns, api) => {
|
||||
const visibleColumns = columns.filter(column => column.visible)
|
||||
const columnMeasurements = {}
|
||||
|
||||
let sumWidth = 0
|
||||
visibleColumns.forEach(column => {
|
||||
const { width, minWidth } = getSizesForColumn(
|
||||
column,
|
||||
defaultFlex,
|
||||
undefined,
|
||||
undefined,
|
||||
api
|
||||
)
|
||||
if (width) {
|
||||
sumWidth += width
|
||||
} else if (minWidth) {
|
||||
sumWidth += minWidth
|
||||
} else {
|
||||
sumWidth += defaultFlex
|
||||
}
|
||||
})
|
||||
|
||||
const rowStyles = {
|
||||
style: {
|
||||
display: 'flex',
|
||||
minWidth: `${sumWidth}px`,
|
||||
},
|
||||
}
|
||||
|
||||
api.rowStyles = rowStyles
|
||||
|
||||
getRowProps.push(() => rowStyles)
|
||||
getHeaderGroupProps.push(() => rowStyles)
|
||||
|
||||
getHeaderProps.push(column => ({
|
||||
style: {
|
||||
boxSizing: 'border-box',
|
||||
...getStylesForColumn(column, columnMeasurements, defaultFlex, api),
|
||||
},
|
||||
}))
|
||||
|
||||
getCellProps.push(cell => {
|
||||
return {
|
||||
style: {
|
||||
...getStylesForColumn(
|
||||
cell.column,
|
||||
columnMeasurements,
|
||||
defaultFlex,
|
||||
undefined,
|
||||
api
|
||||
),
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
return columns
|
||||
})
|
||||
|
||||
return instance
|
||||
}
|
||||
|
||||
// Utils
|
||||
|
||||
function getStylesForColumn(column, columnMeasurements, defaultFlex, api) {
|
||||
const { flex, width, maxWidth } = getSizesForColumn(
|
||||
column,
|
||||
columnMeasurements,
|
||||
defaultFlex,
|
||||
api
|
||||
)
|
||||
|
||||
return {
|
||||
flex: `${flex} 0 auto`,
|
||||
width: `${width}px`,
|
||||
maxWidth: `${maxWidth}px`,
|
||||
}
|
||||
}
|
||||
|
||||
function getSizesForColumn(
|
||||
{ columns, id, width, minWidth, maxWidth },
|
||||
columnMeasurements,
|
||||
defaultFlex,
|
||||
api
|
||||
) {
|
||||
if (columns) {
|
||||
columns = columns
|
||||
.filter(col => col.show || col.visible)
|
||||
.map(column =>
|
||||
getSizesForColumn(column, columnMeasurements, defaultFlex, api)
|
||||
)
|
||||
.filter(Boolean)
|
||||
|
||||
if (!columns.length) {
|
||||
return false
|
||||
}
|
||||
|
||||
const flex = sum(columns.map(col => col.flex))
|
||||
const width = sum(columns.map(col => col.width))
|
||||
const maxWidth = sum(columns.map(col => col.maxWidth))
|
||||
|
||||
return {
|
||||
flex,
|
||||
width,
|
||||
maxWidth,
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
flex: width ? 0 : defaultFlex,
|
||||
width:
|
||||
width === 'auto'
|
||||
? columnMeasurements[id] || defaultFlex
|
||||
: getFirstDefined(width, minWidth, defaultFlex),
|
||||
maxWidth,
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
applyPropHooks,
|
||||
defaultGroupByFn,
|
||||
getFirstDefined,
|
||||
ensurePluginOrder,
|
||||
} from '../utils'
|
||||
|
||||
defaultState.groupBy = []
|
||||
@@ -51,18 +50,9 @@ useGroupBy.pluginName = 'useGroupBy'
|
||||
function columnsBeforeHeaderGroups(columns, { state: [{ groupBy }] }) {
|
||||
// Sort grouped columns to the start of the column list
|
||||
// before the headers are built
|
||||
|
||||
const groupByColumns = groupBy.map(g => columns.find(col => col.id === g))
|
||||
const nonGroupByColumns = columns.filter(col => !groupBy.includes(col.id))
|
||||
|
||||
// If a groupByBoundary column is found, place the groupBy's after it
|
||||
const groupByBoundaryColumnIndex =
|
||||
columns.findIndex(column => column.groupByBoundary) + 1
|
||||
|
||||
return [
|
||||
...nonGroupByColumns.slice(0, groupByBoundaryColumnIndex),
|
||||
...groupByColumns,
|
||||
...nonGroupByColumns.slice(groupByBoundaryColumnIndex),
|
||||
...groupBy.map(g => columns.find(col => col.id === g)),
|
||||
...columns.filter(col => !groupBy.includes(col.id)),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -79,15 +69,12 @@ function useMain(instance) {
|
||||
disableGrouping,
|
||||
aggregations: userAggregations = {},
|
||||
hooks,
|
||||
plugins,
|
||||
state: [{ groupBy }, setState],
|
||||
} = instance
|
||||
|
||||
ensurePluginOrder(plugins, [], 'useGroupBy', ['useExpanded'])
|
||||
|
||||
columns.forEach(column => {
|
||||
const { id, accessor, disableGrouping: columnDisableGrouping } = column
|
||||
column.isGrouped = groupBy.includes(id)
|
||||
column.grouped = groupBy.includes(id)
|
||||
column.groupedIndex = groupBy.indexOf(id)
|
||||
|
||||
column.canGroupBy = accessor
|
||||
@@ -150,12 +137,11 @@ function useMain(instance) {
|
||||
hooks.prepareRow.push(row => {
|
||||
row.cells.forEach(cell => {
|
||||
// Grouped cells are in the groupBy and the pivot cell for the row
|
||||
cell.isGrouped = cell.column.isGrouped && cell.column.id === row.groupByID
|
||||
cell.grouped = cell.column.grouped && cell.column.id === row.groupByID
|
||||
// Repeated cells are any columns in the groupBy that are not grouped
|
||||
cell.isRepeatedValue = !cell.isGrouped && cell.column.isGrouped
|
||||
cell.repeatedValue = !cell.grouped && cell.column.grouped
|
||||
// Aggregated cells are not grouped, not repeated, but still have subRows
|
||||
cell.isAggregated =
|
||||
!cell.isGrouped && !cell.isRepeatedValue && row.canExpand
|
||||
cell.aggregated = !cell.grouped && !cell.repeatedValue && row.canExpand
|
||||
})
|
||||
return row
|
||||
})
|
||||
@@ -232,7 +218,7 @@ function useMain(instance) {
|
||||
// Recurse to sub rows before aggregation
|
||||
groupedRows = Object.entries(groupedRows).map(
|
||||
([groupByVal, subRows], index) => {
|
||||
const path = [...parentPath, `${columnID}:${groupByVal}`]
|
||||
const path = [...parentPath, groupByVal]
|
||||
|
||||
subRows = groupRecursively(subRows, depth + 1, path)
|
||||
|
||||
@@ -242,7 +228,6 @@ function useMain(instance) {
|
||||
)
|
||||
|
||||
const row = {
|
||||
isAggregated: true,
|
||||
groupByID: columnID,
|
||||
groupByVal,
|
||||
values,
|
||||
|
||||
@@ -14,7 +14,6 @@ addActions('pageChange', 'pageSizeChange')
|
||||
const propTypes = {
|
||||
// General
|
||||
manualPagination: PropTypes.bool,
|
||||
paginateExpandedRows: PropTypes.bool,
|
||||
}
|
||||
|
||||
// SSR has issues with useLayoutEffect still, so use useEffect during SSR
|
||||
@@ -33,84 +32,75 @@ function useMain(instance) {
|
||||
PropTypes.checkPropTypes(propTypes, instance, 'property', 'usePagination')
|
||||
|
||||
const {
|
||||
data,
|
||||
rows,
|
||||
manualPagination,
|
||||
disablePageResetOnDataChange,
|
||||
debug,
|
||||
plugins,
|
||||
pageCount: userPageCount,
|
||||
paginateExpandedRows = true,
|
||||
state: [{ pageSize, pageIndex, filters, groupBy, sortBy }, setState],
|
||||
} = instance
|
||||
|
||||
ensurePluginOrder(
|
||||
plugins,
|
||||
['useFilters', 'useGroupBy', 'useSortBy', 'useExpanded'],
|
||||
['useFilters', 'useGroupBy', 'useSortBy'],
|
||||
'usePagination',
|
||||
[]
|
||||
)
|
||||
|
||||
const rowDep = manualPagination ? null : data
|
||||
const rowDep = manualPagination || disablePageResetOnDataChange ? null : rows
|
||||
|
||||
const isPageIndexMountedRef = React.useRef()
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (isPageIndexMountedRef.current && !disablePageResetOnDataChange) {
|
||||
setState(
|
||||
old => ({
|
||||
...old,
|
||||
pageIndex: 0,
|
||||
}),
|
||||
actions.pageChange
|
||||
)
|
||||
}
|
||||
isPageIndexMountedRef.current = true
|
||||
}, [setState, rowDep, filters, groupBy, sortBy, disablePageResetOnDataChange])
|
||||
useLayoutEffect(
|
||||
() => {
|
||||
if (isPageIndexMountedRef.current) {
|
||||
setState(
|
||||
old => ({
|
||||
...old,
|
||||
pageIndex: 0,
|
||||
}),
|
||||
actions.pageChange
|
||||
)
|
||||
}
|
||||
isPageIndexMountedRef.current = true
|
||||
},
|
||||
[setState, rowDep, filters, groupBy, sortBy]
|
||||
)
|
||||
|
||||
const pageCount = manualPagination
|
||||
? userPageCount
|
||||
: Math.ceil(rows.length / pageSize)
|
||||
const pages = React.useMemo(
|
||||
() => {
|
||||
if (manualPagination) {
|
||||
return undefined
|
||||
}
|
||||
if (process.env.NODE_ENV === 'development' && debug)
|
||||
console.info('getPages')
|
||||
|
||||
// Create a new pages with the first page ready to go.
|
||||
const pages = rows.length ? [] : [[]]
|
||||
|
||||
// Start the pageIndex and currentPage cursors
|
||||
let cursor = 0
|
||||
|
||||
while (cursor < rows.length) {
|
||||
const end = cursor + pageSize
|
||||
pages.push(rows.slice(cursor, end))
|
||||
cursor = end
|
||||
}
|
||||
|
||||
return pages
|
||||
},
|
||||
[debug, manualPagination, pageSize, rows]
|
||||
)
|
||||
|
||||
const pageCount = manualPagination ? userPageCount : pages.length
|
||||
|
||||
const pageOptions = React.useMemo(
|
||||
() => (pageCount > 0 ? [...new Array(pageCount)].map((d, i) => i) : []),
|
||||
[pageCount]
|
||||
)
|
||||
|
||||
const page = React.useMemo(() => {
|
||||
let page
|
||||
|
||||
if (manualPagination) {
|
||||
page = rows
|
||||
} else {
|
||||
if (process.env.NODE_ENV === 'development' && debug)
|
||||
console.info('getPage')
|
||||
|
||||
const pageStart = pageSize * pageIndex
|
||||
const pageEnd = pageStart + pageSize
|
||||
|
||||
page = rows.slice(pageStart, pageEnd)
|
||||
}
|
||||
|
||||
if (paginateExpandedRows) {
|
||||
return page
|
||||
}
|
||||
|
||||
const expandedPage = []
|
||||
|
||||
const handleRow = row => {
|
||||
expandedPage.push(row)
|
||||
|
||||
if (row.subRows && row.subRows.length && row.isExpanded) {
|
||||
row.subRows.forEach(handleRow)
|
||||
}
|
||||
}
|
||||
|
||||
page.forEach(handleRow)
|
||||
|
||||
return expandedPage
|
||||
}, [debug, manualPagination, pageIndex, pageSize, paginateExpandedRows, rows])
|
||||
|
||||
const page = manualPagination ? rows : pages[pageIndex]
|
||||
const canPreviousPage = pageIndex > 0
|
||||
const canNextPage = pageCount === -1 || pageIndex < pageCount - 1
|
||||
|
||||
@@ -150,6 +140,7 @@ function useMain(instance) {
|
||||
|
||||
return {
|
||||
...instance,
|
||||
pages,
|
||||
pageOptions,
|
||||
pageCount,
|
||||
page,
|
||||
|
||||
@@ -25,7 +25,7 @@ function useMain(instance) {
|
||||
|
||||
const {
|
||||
hooks,
|
||||
manualRowSelectedKey = 'isSelected',
|
||||
manualRowSelectedKey = 'selected',
|
||||
plugins,
|
||||
rowPaths,
|
||||
state: [{ selectedRows }, setState],
|
||||
@@ -38,11 +38,11 @@ function useMain(instance) {
|
||||
[]
|
||||
)
|
||||
|
||||
const isAllRowsSelected = rowPaths.length === selectedRows.length
|
||||
const allRowsSelected = rowPaths.length === selectedRows.length
|
||||
|
||||
const toggleRowSelectedAll = set => {
|
||||
setState(old => {
|
||||
const selectAll = typeof set !== 'undefined' ? set : !isAllRowsSelected
|
||||
const selectAll = typeof set !== 'undefined' ? set : !allRowsSelected
|
||||
return {
|
||||
...old,
|
||||
selectedRows: selectAll ? [...rowPaths] : [],
|
||||
@@ -50,24 +50,6 @@ function useMain(instance) {
|
||||
}, actions.toggleRowSelectedAll)
|
||||
}
|
||||
|
||||
const updateParentRow = (selectedRows, path) => {
|
||||
const parentPath = path.slice(0, path.length - 1)
|
||||
const parentKey = parentPath.join('.')
|
||||
const selected =
|
||||
rowPaths.filter(
|
||||
path =>
|
||||
path !== parentKey &&
|
||||
path.startsWith(parentKey) &&
|
||||
!selectedRows.has(path)
|
||||
).length === 0
|
||||
if (selected) {
|
||||
selectedRows.add(parentKey)
|
||||
} else {
|
||||
selectedRows.delete(parentKey)
|
||||
}
|
||||
if (parentPath.length > 1) updateParentRow(selectedRows, parentPath)
|
||||
}
|
||||
|
||||
const toggleRowSelected = (path, set) => {
|
||||
const key = path.join('.')
|
||||
|
||||
@@ -77,24 +59,16 @@ function useMain(instance) {
|
||||
// in a flat object
|
||||
const exists = old.selectedRows.includes(key)
|
||||
const shouldExist = typeof set !== 'undefined' ? set : !exists
|
||||
let newSelectedRows = new Set(old.selectedRows)
|
||||
let newSelectedRows = new Set(selectedRows)
|
||||
|
||||
if (!exists && shouldExist) {
|
||||
rowPaths.forEach(rowPath => {
|
||||
if (rowPath.startsWith(key)) newSelectedRows.add(rowPath)
|
||||
})
|
||||
newSelectedRows.add(key)
|
||||
} else if (exists && !shouldExist) {
|
||||
rowPaths.forEach(rowPath => {
|
||||
if (rowPath.startsWith(key)) newSelectedRows.delete(rowPath)
|
||||
})
|
||||
newSelectedRows.delete(key)
|
||||
} else {
|
||||
return old
|
||||
}
|
||||
|
||||
// If the row is a subRow update
|
||||
// its parent row to reflect changes
|
||||
if (path.length > 1) updateParentRow(newSelectedRows, path)
|
||||
|
||||
return {
|
||||
...old,
|
||||
selectedRows: [...newSelectedRows.values()],
|
||||
@@ -111,7 +85,7 @@ function useMain(instance) {
|
||||
style: {
|
||||
cursor: 'pointer',
|
||||
},
|
||||
checked: isAllRowsSelected,
|
||||
checked: allRowsSelected,
|
||||
title: 'Toggle All Rows Selected',
|
||||
},
|
||||
applyPropHooks(instance.hooks.getToggleAllRowsSelectedProps, instance),
|
||||
@@ -120,49 +94,10 @@ function useMain(instance) {
|
||||
}
|
||||
|
||||
hooks.prepareRow.push(row => {
|
||||
// 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
|
||||
console.log(subRowPaths)
|
||||
subRowPaths.forEach(path => {
|
||||
toggleRowSelected(path, set)
|
||||
})
|
||||
}
|
||||
row.getToggleRowSelectedProps = props => {
|
||||
let checked = false
|
||||
row.canSelect = !!row.original
|
||||
|
||||
if (row.original && row.original[manualRowSelectedKey]) {
|
||||
checked = true
|
||||
} else {
|
||||
checked = row.isSelected
|
||||
}
|
||||
|
||||
return mergeProps(
|
||||
{
|
||||
onChange: e => {
|
||||
row.toggleRowSelected(e.target.checked)
|
||||
},
|
||||
style: {
|
||||
cursor: 'pointer',
|
||||
},
|
||||
checked,
|
||||
title: 'Toggle Row Selected',
|
||||
},
|
||||
applyPropHooks(
|
||||
instance.hooks.getToggleRowSelectedProps,
|
||||
row,
|
||||
instance
|
||||
),
|
||||
props
|
||||
)
|
||||
}
|
||||
} else {
|
||||
row.isSelected = selectedRows.includes(row.path.join('.'))
|
||||
if (row.canSelect) {
|
||||
row.selected = selectedRows.includes(row.path.join('.'))
|
||||
row.toggleRowSelected = set => toggleRowSelected(row.path, set)
|
||||
row.getToggleRowSelectedProps = props => {
|
||||
let checked = false
|
||||
@@ -170,7 +105,7 @@ function useMain(instance) {
|
||||
if (row.original && row.original[manualRowSelectedKey]) {
|
||||
checked = true
|
||||
} else {
|
||||
checked = row.isSelected
|
||||
checked = selectedRows.includes(row.path.join('.'))
|
||||
}
|
||||
|
||||
return mergeProps(
|
||||
@@ -202,6 +137,6 @@ function useMain(instance) {
|
||||
toggleRowSelected,
|
||||
toggleRowSelectedAll,
|
||||
getToggleAllRowsSelectedProps,
|
||||
isAllRowsSelected,
|
||||
allRowsSelected,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,18 +72,21 @@ function useMain(instance) {
|
||||
const rowsMountedRef = React.useRef()
|
||||
|
||||
// When data changes, reset row and cell state
|
||||
React.useEffect(() => {
|
||||
if (rowsMountedRef.current) {
|
||||
setState(old => {
|
||||
return {
|
||||
...old,
|
||||
rowState: {},
|
||||
}
|
||||
}, actions.setRowState)
|
||||
}
|
||||
React.useEffect(
|
||||
() => {
|
||||
if (rowsMountedRef.current) {
|
||||
setState(old => {
|
||||
return {
|
||||
...old,
|
||||
rowState: {},
|
||||
}
|
||||
}, actions.setRowState)
|
||||
}
|
||||
|
||||
rowsMountedRef.current = true
|
||||
}, [rows, setState])
|
||||
rowsMountedRef.current = true
|
||||
},
|
||||
[rows, setState]
|
||||
)
|
||||
|
||||
hooks.prepareRow.push(row => {
|
||||
const pathKey = row.path.join('.')
|
||||
|
||||
@@ -59,13 +59,12 @@ function useMain(instance) {
|
||||
disableMultiSort,
|
||||
isMultiSortEvent = e => e.shiftKey,
|
||||
maxMultiSortColCount = Number.MAX_SAFE_INTEGER,
|
||||
flatHeaders,
|
||||
hooks,
|
||||
state: [{ sortBy }, setState],
|
||||
plugins,
|
||||
} = instance
|
||||
|
||||
ensurePluginOrder(plugins, ['useFilters'], 'useSortBy', [])
|
||||
ensurePluginOrder(plugins, [], 'useSortBy', ['useFilters'])
|
||||
// Add custom hooks
|
||||
hooks.getSortByToggleProps = []
|
||||
|
||||
@@ -158,7 +157,7 @@ function useMain(instance) {
|
||||
}
|
||||
|
||||
// Add the getSortByToggleProps method to columns and headers
|
||||
flatHeaders.forEach(column => {
|
||||
;[...instance.columns, ...instance.headers].forEach(column => {
|
||||
const { accessor, disableSorting: columnDisableSorting, id } = column
|
||||
|
||||
const canSort = accessor
|
||||
@@ -198,88 +197,77 @@ function useMain(instance) {
|
||||
)
|
||||
}
|
||||
|
||||
const columnSort = sortBy.find(d => d.id === id)
|
||||
column.isSorted = !!columnSort
|
||||
column.sorted = sortBy.find(d => d.id === id)
|
||||
column.sortedIndex = sortBy.findIndex(d => d.id === id)
|
||||
column.isSortedDesc = column.isSorted ? columnSort.desc : undefined
|
||||
column.sortedDesc = column.sorted ? column.sorted.desc : undefined
|
||||
})
|
||||
|
||||
const sortedRows = React.useMemo(() => {
|
||||
if (manualSorting || !sortBy.length) {
|
||||
return rows
|
||||
}
|
||||
if (process.env.NODE_ENV === 'development' && debug)
|
||||
console.time('getSortedRows')
|
||||
const sortedRows = React.useMemo(
|
||||
() => {
|
||||
if (manualSorting || !sortBy.length) {
|
||||
return rows
|
||||
}
|
||||
if (process.env.NODE_ENV === 'development' && debug)
|
||||
console.time('getSortedRows')
|
||||
|
||||
// Filter out sortBys that correspond to non existing columns
|
||||
const availableSortBy = sortBy.filter(sort =>
|
||||
columns.find(col => col.id === sort.id)
|
||||
)
|
||||
const sortData = rows => {
|
||||
// Use the orderByFn to compose multiple sortBy's together.
|
||||
// This will also perform a stable sorting using the row index
|
||||
// if needed.
|
||||
const sortedData = orderByFn(
|
||||
rows,
|
||||
sortBy.map(sort => {
|
||||
// Support custom sorting methods for each column
|
||||
const { sortType } = columns.find(d => d.id === sort.id)
|
||||
|
||||
const sortData = rows => {
|
||||
// Use the orderByFn to compose multiple sortBy's together.
|
||||
// This will also perform a stable sorting using the row index
|
||||
// if needed.
|
||||
const sortedData = orderByFn(
|
||||
rows,
|
||||
availableSortBy.map(sort => {
|
||||
// Support custom sorting methods for each column
|
||||
const column = columns.find(d => d.id === sort.id)
|
||||
// Look up sortBy functions in this order:
|
||||
// column function
|
||||
// column string lookup on user sortType
|
||||
// column string lookup on built-in sortType
|
||||
// default function
|
||||
// default string lookup on user sortType
|
||||
// default string lookup on built-in sortType
|
||||
const sortMethod =
|
||||
isFunction(sortType) ||
|
||||
(userSortTypes || {})[sortType] ||
|
||||
sortTypes[sortType] ||
|
||||
sortTypes.alphanumeric
|
||||
|
||||
if (!column) {
|
||||
throw new Error(
|
||||
`React-Table: Could not find a column with id: ${sort.id} while sorting`
|
||||
)
|
||||
// Return the correct sortFn
|
||||
return (a, b) =>
|
||||
sortMethod(a.values[sort.id], b.values[sort.id], sort.desc)
|
||||
}),
|
||||
// Map the directions
|
||||
sortBy.map(sort => {
|
||||
// Detect and use the sortInverted option
|
||||
const { sortInverted } = columns.find(d => d.id === sort.id)
|
||||
|
||||
if (sortInverted) {
|
||||
return sort.desc
|
||||
}
|
||||
|
||||
return !sort.desc
|
||||
})
|
||||
)
|
||||
|
||||
// If there are sub-rows, sort them
|
||||
sortedData.forEach(row => {
|
||||
if (!row.subRows || row.subRows.length <= 1) {
|
||||
return
|
||||
}
|
||||
|
||||
const { sortType } = column
|
||||
|
||||
// Look up sortBy functions in this order:
|
||||
// column function
|
||||
// column string lookup on user sortType
|
||||
// column string lookup on built-in sortType
|
||||
// default function
|
||||
// default string lookup on user sortType
|
||||
// default string lookup on built-in sortType
|
||||
const sortMethod =
|
||||
isFunction(sortType) ||
|
||||
(userSortTypes || {})[sortType] ||
|
||||
sortTypes[sortType] ||
|
||||
sortTypes.alphanumeric
|
||||
|
||||
// Return the correct sortFn.
|
||||
// This function should always return in ascending order
|
||||
return (a, b) => sortMethod(a, b, sort.id)
|
||||
}),
|
||||
// Map the directions
|
||||
availableSortBy.map(sort => {
|
||||
// Detect and use the sortInverted option
|
||||
const column = columns.find(d => d.id === sort.id)
|
||||
|
||||
if (column && column.sortInverted) {
|
||||
return sort.desc
|
||||
}
|
||||
|
||||
return !sort.desc
|
||||
row.subRows = sortData(row.subRows)
|
||||
})
|
||||
)
|
||||
|
||||
// If there are sub-rows, sort them
|
||||
sortedData.forEach(row => {
|
||||
if (!row.subRows || row.subRows.length <= 1) {
|
||||
return
|
||||
}
|
||||
row.subRows = sortData(row.subRows)
|
||||
})
|
||||
return sortedData
|
||||
}
|
||||
|
||||
return sortedData
|
||||
}
|
||||
if (process.env.NODE_ENV === 'development' && debug)
|
||||
console.timeEnd('getSortedRows')
|
||||
|
||||
if (process.env.NODE_ENV === 'development' && debug)
|
||||
console.timeEnd('getSortedRows')
|
||||
|
||||
return sortData(rows)
|
||||
}, [manualSorting, sortBy, debug, columns, rows, orderByFn, userSortTypes])
|
||||
return sortData(rows)
|
||||
},
|
||||
[manualSorting, sortBy, debug, columns, rows, orderByFn, userSortTypes]
|
||||
)
|
||||
|
||||
return {
|
||||
...instance,
|
||||
|
||||
+5
-22
@@ -3,9 +3,7 @@ const reSplitAlphaNumeric = /([0-9]+)/gm
|
||||
// Mixed sorting is slow, but very inclusive of many edge cases.
|
||||
// It handles numbers, mixed alphanumeric combinations, and even
|
||||
// null, undefined, and Infinity
|
||||
export const alphanumeric = (rowA, rowB, columnID) => {
|
||||
let a = getRowValueByColumnID(rowA, columnID)
|
||||
let b = getRowValueByColumnID(rowB, columnID)
|
||||
export const alphanumeric = (a, b) => {
|
||||
// Force to strings (or "" for unsupported types)
|
||||
a = toString(a)
|
||||
b = toString(b)
|
||||
@@ -53,32 +51,17 @@ export const alphanumeric = (rowA, rowB, columnID) => {
|
||||
return a.length - b.length
|
||||
}
|
||||
|
||||
export function datetime(rowA, rowB, columnID) {
|
||||
let a = getRowValueByColumnID(rowA, columnID)
|
||||
let b = getRowValueByColumnID(rowB, columnID)
|
||||
|
||||
export function datetime(a, b) {
|
||||
a = a.getTime()
|
||||
b = b.getTime()
|
||||
|
||||
return compareBasic(a, b)
|
||||
return numeric(a, b)
|
||||
}
|
||||
|
||||
export function basic(rowA, rowB, columnID) {
|
||||
let a = getRowValueByColumnID(rowA, columnID)
|
||||
let b = getRowValueByColumnID(rowB, columnID)
|
||||
|
||||
return compareBasic(a, b)
|
||||
}
|
||||
|
||||
// Utils
|
||||
|
||||
function compareBasic(a, b) {
|
||||
export function numeric(a, b) {
|
||||
return a === b ? 0 : a > b ? 1 : -1
|
||||
}
|
||||
|
||||
function getRowValueByColumnID(row, columnID) {
|
||||
return row.values[columnID]
|
||||
}
|
||||
// Utils
|
||||
|
||||
function toString(a) {
|
||||
if (typeof a === 'number') {
|
||||
|
||||
+19
-45
@@ -19,8 +19,8 @@ export function decorateColumn(column, defaultColumn, parent, depth, index) {
|
||||
|
||||
if (typeof accessor === 'string') {
|
||||
id = id || accessor
|
||||
const accessorPath = accessor.split('.')
|
||||
accessor = row => getBy(row, accessorPath)
|
||||
const accessorString = accessor
|
||||
accessor = row => getBy(row, accessorString)
|
||||
}
|
||||
|
||||
if (!id && typeof Header === 'string' && Header) {
|
||||
@@ -72,6 +72,14 @@ export function decorateColumnTree(columns, defaultColumn, parent, depth = 0) {
|
||||
export function makeHeaderGroups(columns, maxDepth, defaultColumn) {
|
||||
const headerGroups = []
|
||||
|
||||
const removeChildColumns = column => {
|
||||
delete column.columns
|
||||
if (column.parent) {
|
||||
removeChildColumns(column.parent)
|
||||
}
|
||||
}
|
||||
columns.forEach(removeChildColumns)
|
||||
|
||||
const buildGroup = (columns, depth = 0) => {
|
||||
const headerGroup = {
|
||||
headers: [],
|
||||
@@ -116,22 +124,15 @@ export function makeHeaderGroups(columns, maxDepth, defaultColumn) {
|
||||
}
|
||||
}
|
||||
|
||||
// Establish the new headers[] relationship on the parent
|
||||
// Establish the new columns[] relationship on the parent
|
||||
if (column.parent || hasParents) {
|
||||
latestParentColumn = [...parentColumns].reverse()[0]
|
||||
latestParentColumn.headers = latestParentColumn.headers || []
|
||||
if (!latestParentColumn.headers.includes(column)) {
|
||||
latestParentColumn.headers.push(column)
|
||||
latestParentColumn.columns = latestParentColumn.columns || []
|
||||
if (!latestParentColumn.columns.includes(column)) {
|
||||
latestParentColumn.columns.push(column)
|
||||
}
|
||||
}
|
||||
|
||||
column.totalHeaderCount = column.headers
|
||||
? column.headers.reduce(
|
||||
(sum, header) => sum + header.totalHeaderCount,
|
||||
0
|
||||
)
|
||||
: 1 // Leaf node columns take up at least one count
|
||||
|
||||
headerGroup.headers.push(column)
|
||||
})
|
||||
|
||||
@@ -147,25 +148,6 @@ export function makeHeaderGroups(columns, maxDepth, defaultColumn) {
|
||||
return headerGroups.reverse()
|
||||
}
|
||||
|
||||
export function determineColumnVisibility(instance) {
|
||||
const { headers } = instance
|
||||
|
||||
const handleColumn = (column, parentVisible) => {
|
||||
column.isVisible = parentVisible
|
||||
? typeof column.show === 'function'
|
||||
? column.show(instance)
|
||||
: !!column.show
|
||||
: false
|
||||
if (column.columns && column.columns.length) {
|
||||
column.columns.forEach(subColumn =>
|
||||
handleColumn(subColumn, column.isVisible)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
headers.forEach(subColumn => handleColumn(subColumn, true))
|
||||
}
|
||||
|
||||
export function getBy(obj, path, def) {
|
||||
if (!path) {
|
||||
return obj
|
||||
@@ -214,7 +196,6 @@ export function defaultGroupByFn(rows, columnID) {
|
||||
}
|
||||
|
||||
export function setBy(obj = {}, path, value) {
|
||||
path = makePathArray(path)
|
||||
const recurse = (obj, depth = 0) => {
|
||||
const key = path[depth]
|
||||
const target = typeof obj[key] !== 'object' ? {} : obj[key]
|
||||
@@ -366,18 +347,11 @@ This usually means you need to need to name your plugin hook by setting the 'plu
|
||||
//
|
||||
|
||||
function makePathArray(obj) {
|
||||
return (
|
||||
flattenDeep(obj)
|
||||
// remove all periods in parts
|
||||
.map(d => String(d).replace('.', '_'))
|
||||
// join parts using period
|
||||
.join('.')
|
||||
// replace brackets with periods
|
||||
.replace(/\[/g, '.')
|
||||
.replace(/\]/g, '')
|
||||
// split it back out on periods
|
||||
.split('.')
|
||||
)
|
||||
return flattenDeep(obj)
|
||||
.join('.')
|
||||
.replace(/\[/g, '.')
|
||||
.replace(/\]/g, '')
|
||||
.split('.')
|
||||
}
|
||||
|
||||
function flattenDeep(arr, newArr = []) {
|
||||
|
||||
@@ -6320,11 +6320,6 @@ prettier-linter-helpers@^1.0.0:
|
||||
dependencies:
|
||||
fast-diff "^1.1.2"
|
||||
|
||||
prettier@^1.18.2:
|
||||
version "1.18.2"
|
||||
resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.18.2.tgz#6823e7c5900017b4bd3acf46fe9ac4b4d7bda9ea"
|
||||
integrity sha512-OeHeMc0JhFE9idD4ZdtNibzY0+TPHSpSSb9h8FqtP+YnoZZ1sl8Vc9b1sasjfymH3SonAF4QcA2+mzHPhMvIiw==
|
||||
|
||||
pretty-format@^23.6.0:
|
||||
version "23.6.0"
|
||||
resolved "https://registry.yarnpkg.com/pretty-format/-/pretty-format-23.6.0.tgz#5eaac8eeb6b33b987b7fe6097ea6a8a146ab5760"
|
||||
|
||||
Reference in New Issue
Block a user