Compare commits

..
Author SHA1 Message Date
Tanner Linsley 163233a487 Create CODE_OF_CONDUCT.md 2019-08-15 15:42:40 -06:00
70 changed files with 822 additions and 24360 deletions
View File
+4 -11
View File
@@ -1,6 +1,4 @@
![React Table Header](https://github.com/tannerlinsley/react-table/raw/master/media/header.png)
<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>
+34 -71
View File
@@ -97,19 +97,6 @@ The following options are supported via the main options object passed to `useTa
- Defaults to `initialState`
- This key is used to look for the initial state of a row when initializing the `rowState` for a`data` array.
- If the value located at `row[initialRowStateKey]` is falsey, `{}` will be used instead.
- `getSubRows: Function(row, relativeIndex) => Rows[]`
- Optional
- Must be **memoized**
- Defaults to `(row) => row.subRows || []`
- Use this function to change how React Table detects subrows. You could even use this function to generate sub rows if you want.
- By default, it will attempt to return the `subRows` property on the row, or an empty array if that is not found.
- `getRowID: Function(row, relativeIndex) => string`
- Use this function to change how React Table detects unique rows and also how it constructs each row's underlying `path` property.
- Optional
- Must be **memoized**
- Defaults to `(row, relativeIndex) => relativeIndex`
- You may want to change this function if
- By default, it will use the `index` of the row within it's original array.
- `debug: Bool`
- Optional
- A flag to turn on debug mode.
@@ -156,24 +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`
- `columns: Array<Column>`
- A **nested** array of final column objects, **similar in structure to the original columns configuration option**.
- See [Column Properties](#column-properties) for more information
- `flatColumns: Array<Column>`
- A **flat** array of all final column objects.
- See [Column Properties](#column-properties) for more information
- `headerGroups: Array<HeaderGroup>`
- An array of normalized header groups, each containing a flattened array of final column objects for that row.
- **Some of these headers may be materialized as placeholders**
- See [Header Group Properties](#headergroup-properties) for more information
- `headers: Array<Column>`
- An **nested** array of final header objects, **similar in structure to the original columns configuration option, but rebuilt for ordering**
- Each contains the headers that are displayed underneath it.
- **Some of these headers may be materialized as placeholders**
- `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
- `flatHeaders[] Array<Column>`
- A **flat** array of final header objects found in each header group.
- **Some of these headers may be materialized as placeholders**
- `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
@@ -202,7 +179,7 @@ The following properties are available on the table instance returned from `useT
- Pass it a valid `rowPath` array, `columnID` and `updater`. The `updater` may be a value or function, similar to `React.useState`'s usage.
- If `updater` is a function, it will be passed the previous value
### HeaderGroup Properties
### `HeaderGroup` Properties
The following additional properties are available on every `headerGroup` object returned by the table instance.
@@ -221,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.
@@ -425,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
@@ -458,12 +434,12 @@ The following properties are available on every `Column` object returned by the
- This function is used to resolve any props needed for this column's UI that is responsible for toggling the sort direction when the user clicks it.
- You can use the `getSortByToggleProps` hook to extend its functionality.
- Custom props may be passed. **NOTE: Custom props may override built-in sortBy props, so be careful!**
- `isSorted: Boolean`
- `sorted: Boolean`
- Denotes whether this column is currently being sorted
- `sortedIndex: Int`
- If the column is currently sorted, this integer will be the index in the `sortBy` array from state that corresponds to this column.
- If this column is not sorted, the index will always be `-1`
- `isSortedDesc: Bool`
- `sortedDesc: Bool`
- If the column is currently sorted, this denotes whether the column's sort direction is descending or not.
- If `true`, the column is sorted `descending`
- If `false`, the column is sorted `ascending`
@@ -497,14 +473,10 @@ function Table({ columns, data }) {
<span>
{/* Add a sort direction indicator */}
<span>
{column.isSorted
? column.isSortedDesc
? ' 🔽'
: ' 🔼'
: ''}
{column.sorted ? (column.sortedDesc ? ' 🔽' : ' 🔼') : ''}
</span>
{/* Add a sort index indicator */}
<span>({column.isSorted ? column.sortedIndex + 1 : ''})</span>
<span>({column.sorted ? column.sortedIndex + 1 : ''})</span>
</span>
</th>
))}
@@ -548,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)
@@ -557,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
@@ -577,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
@@ -716,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.
@@ -747,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
@@ -945,9 +915,13 @@ The following options are supported via the main options object passed to `useTa
- A `pathIndex` can be set as the key and its value set to `true` to expand that row's subRows into view. For example, if `{ '3': true }` was passed as the `expanded` state, the **4th row in the original data array** would be expanded.
- For nested expansion, you may **use another object** instead of a Boolean to expand sub rows. For example, if `{ '3': { '5' : true }}` was passed as the `expanded` state, then the **6th subRow of the 4th row and the 4th row of the original data array** would be expanded.
- This information is stored in state since the table is allowed to manipulate the filter through user interaction.
- `getSubRows: Function(row, relativeIndex) => Rows[]`
- `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`
@@ -1124,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`
@@ -1149,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.
@@ -1365,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
@@ -1385,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
@@ -1649,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,
-4
View File
@@ -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)
+3 -5
View File
@@ -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
+11 -17
View File
@@ -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>
-3
View File
@@ -1,3 +0,0 @@
{
"infiniteLoopProtection": false
}
+45 -39
View File
@@ -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>
+12 -12
View File
@@ -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
View File
@@ -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
}
-626
View File
@@ -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
-4
View File
@@ -1,4 +0,0 @@
{
"presets": ["react-app"],
"plugins": ["styled-components"]
}
-1
View File
@@ -1 +0,0 @@
SKIP_PREFLIGHT_CHECK=true
-7
View File
@@ -1,7 +0,0 @@
{
"extends": ["react-app", "prettier"],
"rules": {
// "eqeqeq": 0,
// "jsx-a11y/anchor-is-valid": 0
}
}
-23
View File
@@ -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*
-29
View File
@@ -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,
]
-4
View File
@@ -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
-36
View File
@@ -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

-38
View File
@@ -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
}
-626
View File
@@ -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
-9
View File
@@ -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)
})
-13
View File
@@ -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;
}
-12
View File
@@ -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()
-40
View File
@@ -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()
}
-135
View File
@@ -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 -1
View File
@@ -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>
))}
+7 -5
View File
@@ -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>
))}
+2 -2
View File
@@ -42,7 +42,7 @@ function Table({ columns: userColumns, data, renderRowSubComponent }) {
headerGroups,
rows,
prepareRow,
flatColumns,
columns,
state: [{ expanded }],
} = useTable(
{
@@ -87,7 +87,7 @@ function Table({ columns: userColumns, data, renderRowSubComponent }) {
*/}
{row.isExpanded ? (
<tr>
<td colSpan={flatColumns.length}>
<td colSpan={columns.length}>
{/*
Inside it, call our renderRowSubComponent function. In reality,
you coul pass whatever you want as props to
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.
+1 -2
View File
@@ -1,6 +1,6 @@
{
"name": "react-table",
"version": "7.0.0-alpha.29",
"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",
+203 -190
View File
@@ -8,8 +8,8 @@ import {
flexRender,
decorateColumnTree,
makeHeaderGroups,
findMaxDepth,
flattenBy,
determineHeaderVisibility,
} from '../utils'
import { useTableState } from './useTableState'
@@ -17,10 +17,14 @@ import { useTableState } from './useTableState'
const propTypes = {
// General
data: PropTypes.array.isRequired,
columns: PropTypes.arrayOf(PropTypes.object).isRequired,
columns: PropTypes.arrayOf(
PropTypes.shape({
Cell: PropTypes.any,
Header: PropTypes.any,
})
).isRequired,
defaultColumn: PropTypes.object,
getSubRows: PropTypes.func,
getRowID: PropTypes.func,
subRowsKey: PropTypes.string,
debug: PropTypes.bool,
}
@@ -29,9 +33,6 @@ const renderErr =
const defaultColumnInstance = {}
const defaultGetSubRows = (row, index) => row.subRows || []
const defaultGetRowID = (row, index) => index
export const useTable = (props, ...plugins) => {
// Validate props
PropTypes.checkPropTypes(propTypes, props, 'property', 'useTable')
@@ -42,31 +43,33 @@ export const useTable = (props, ...plugins) => {
state: userState,
columns: userColumns,
defaultColumn = defaultColumnInstance,
getSubRows = defaultGetSubRows,
getRowID = defaultGetRowID,
subRowsKey = 'subRows',
debug,
} = props
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: [],
@@ -79,140 +82,146 @@ 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 columns = React.useMemo(
let columnTree = React.useMemo(
() => decorateColumnTree(userColumns, defaultColumn),
[defaultColumn, userColumns]
)
// Get the flat list of all columns andllow hooks to decorate
// those columns (and trigger this memoization via deps)
let flatColumns = React.useMemo(() => {
if (process.env.NODE_ENV === 'development' && debug)
console.time('hooks.columnsBeforeHeaderGroups')
let newColumns = applyHooks(
instanceRef.current.hooks.columnsBeforeHeaderGroups,
flattenBy(columns, '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
),
// Get the flat list of all columns
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')
const newColumns = applyHooks(
instanceRef.current.hooks.columnsBeforeHeaderGroups,
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
),
]
)
// Make the headerGroups
const headerGroups = React.useMemo(
() => makeHeaderGroups(flatColumns, columns, defaultColumn),
[columns, defaultColumn, flatColumns]
() => makeHeaderGroups(columns, findMaxDepth(columnTree), defaultColumn),
[columnTree, columns, defaultColumn]
)
const headers = React.useMemo(() => headerGroups[0].headers, [headerGroups])
const headers = React.useMemo(() => flattenBy(headerGroups, 'headers'), [
headerGroups,
])
Object.assign(instanceRef.current, {
columns,
flatColumns,
headerGroups,
headers,
})
// 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
const rowID = getRowID(originalRow, i)
// Make the new path for the row
const path = [...parentPath, i]
// Make the new path for the row
const path = [...parentPath, rowID]
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
let subRows = getSubRows(originalRow, i)
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
}
if (subRows) {
subRows = subRows.map((d, i) => accessRow(d, i, depth + 1, path))
// 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 = {}
instanceRef.current.columns.forEach(column => {
row.values[column.id] = column.accessor
? column.accessor(originalRow, i, { subRows, depth, data })
: undefined
})
return row
}
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
// Create the cells and values
row.values = {}
flatColumns.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, getRowID, getSubRows, flatColumns])
// 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
determineHeaderVisibility(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')
@@ -222,55 +231,56 @@ 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 = headers =>
headers.filter(header => {
if (header.headers) {
return recurse(header.headers)
const recurse = columns =>
columns.filter(column => {
if (column.columns) {
return recurse(column.columns)
}
return header.isVisible
return column.visible
}).length
if (header.headers) {
return recurse(header.headers)
if (header.columns) {
return recurse(header.columns)
}
return header.isVisible
return header.visible
})
// Give headerGroups getRowProps
@@ -287,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)
@@ -318,51 +329,53 @@ export const useTable = (props, ...plugins) => {
props
)
// Build the visible cells for each row
row.cells = instanceRef.current.flatColumns
.filter(d => d.isVisible)
.map(column => {
const cell = {
const visibleColumns = instanceRef.current.columns.filter(
column => column.visible
)
// Build the cells for each row
row.cells = visibleColumns.map(column => {
const cell = {
column,
row,
value: row.values[column.id],
}
// Give each cell a getCellProps base
cell.getCellProps = props => {
const columnPathStr = [...row.path, column.id].join('_')
return mergeProps(
{
key: ['cell', columnPathStr].join('_'),
},
applyPropHooks(
instanceRef.current.hooks.getCellProps,
cell,
instanceRef.current
),
props
)
}
// Give each cell a renderer function (supports multiple renderers)
cell.render = (type, userProps = {}) => {
const Comp = typeof type === 'string' ? column[type] : type
if (typeof Comp === 'undefined') {
throw new Error(renderErr)
}
return flexRender(Comp, {
...instanceRef.current,
column,
row,
value: row.values[column.id],
}
cell,
...userProps,
})
}
// Give each cell a getCellProps base
cell.getCellProps = props => {
const columnPathStr = [...row.path, column.id].join('_')
return mergeProps(
{
key: ['cell', columnPathStr].join('_'),
},
applyPropHooks(
instanceRef.current.hooks.getCellProps,
cell,
instanceRef.current
),
props
)
}
// Give each cell a renderer function (supports multiple renderers)
cell.render = (type, userProps = {}) => {
const Comp = typeof type === 'string' ? column[type] : type
if (typeof Comp === 'undefined') {
throw new Error(renderErr)
}
return flexRender(Comp, {
...instanceRef.current,
column,
row,
cell,
...userProps,
})
}
return cell
})
return cell
})
// need to apply any row specific hooks (useExpanded requires this)
applyHooks(instanceRef.current.hooks.prepareRow, row, instanceRef.current)
+1
View File
@@ -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'
File diff suppressed because it is too large Load Diff
+2 -4
View File
@@ -50,7 +50,7 @@ function Table({ columns: userColumns, data, SubComponent }) {
headerGroups,
rows,
prepareRow,
flatColumns,
columns,
state: [{ expanded }],
} = useTable(
{
@@ -90,9 +90,7 @@ function Table({ columns: userColumns, data, SubComponent }) {
</tr>
{!row.subRows.length && row.isExpanded ? (
<tr>
<td colSpan={flatColumns.length}>
{SubComponent({ row })}
</td>
<td colSpan={columns.length}>{SubComponent({ row })}</td>
</tr>
) : null}
</React.Fragment>
+4 -4
View File
@@ -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>
+4 -56
View File
@@ -2,9 +2,8 @@ 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 dataPiece = [
const data = [
{
firstName: 'tanner',
lastName: 'linsley',
@@ -28,25 +27,6 @@ const dataPiece = [
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',
@@ -58,15 +38,6 @@ const dataPiece = [
},
]
const data = [
...dataPiece,
...dataPiece,
...dataPiece,
...dataPiece,
...dataPiece,
...dataPiece,
]
function Table({ columns, data }) {
// Use the state and functions returned from useTable to build your UI
const {
@@ -80,8 +51,7 @@ function Table({ columns, data }) {
columns,
data,
},
useRowSelect,
useExpanded
useRowSelect
)
// Render the UI for your table
@@ -150,10 +120,7 @@ function App() {
{
id: 'selectedStatus',
Cell: ({ row }) => (
<div>
Row {row.path.join('.')}{' '}
{row.isSelected ? 'Selected' : 'Not Selected'}
</div>
<div>{row.selected ? 'Selected' : 'Not Selected'}</div>
),
},
{
@@ -197,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()
@@ -215,26 +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)
})
+1 -1
View File
@@ -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>
))}
+8 -11
View File
@@ -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)
+77 -72
View File
@@ -33,7 +33,7 @@ function useMain(instance) {
const {
debug,
rows,
flatColumns,
columns,
filterTypes: userFilterTypes,
manualFilters,
disableFilters,
@@ -43,7 +43,7 @@ function useMain(instance) {
const preFilteredRows = rows
const setFilter = (id, updater) => {
const column = flatColumns.find(d => d.id === id)
const column = columns.find(d => d.id === id)
if (!column) {
throw new Error(`React-Table: Could not find a column with id: ${id}`)
@@ -85,7 +85,7 @@ function useMain(instance) {
// Filter out undefined values
Object.keys(newFilters).forEach(id => {
const newFilter = newFilters[id]
const column = flatColumns.find(d => d.id === id)
const column = columns.find(d => d.id === id)
const filterMethod = getFilterMethod(
column.filter,
userFilterTypes || {},
@@ -104,7 +104,7 @@ function useMain(instance) {
}, actions.setAllFilters)
}
flatColumns.forEach(column => {
columns.forEach(column => {
const { id, accessor, disableFilters: columnDisableFilters } = column
// Determine if a column is filterable
@@ -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 = flatColumns.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, flatColumns, userFilterTypes])
React.useMemo(() => {
// Now that each filtered column has it's partially filtered rows,
// lets assign the final filtered rows to all of the other columns
const nonFilteredColumns = flatColumns.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
})
}, [filteredRows, filters, flatColumns])
},
[manualFilters, filters, debug, rows, columns, userFilterTypes]
)
return {
...instance,
+144
View File
@@ -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,
}
}
+19 -33
View File
@@ -9,7 +9,6 @@ import {
applyPropHooks,
defaultGroupByFn,
getFirstDefined,
ensurePluginOrder,
} from '../utils'
defaultState.groupBy = []
@@ -48,21 +47,12 @@ export const useGroupBy = hooks => {
useGroupBy.pluginName = 'useGroupBy'
function columnsBeforeHeaderGroups(flatColumns, { state: [{ groupBy }] }) {
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 => flatColumns.find(col => col.id === g))
const nonGroupByColumns = flatColumns.filter(col => !groupBy.includes(col.id))
// If a groupByBoundary column is found, place the groupBy's after it
const groupByBoundaryColumnIndex =
flatColumns.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)),
]
}
@@ -72,22 +62,19 @@ function useMain(instance) {
const {
debug,
rows,
flatColumns,
flatHeaders,
columns,
headers,
groupByFn = defaultGroupByFn,
manualGroupBy,
disableGrouping,
aggregations: userAggregations = {},
hooks,
plugins,
state: [{ groupBy }, setState],
} = instance
ensurePluginOrder(plugins, [], 'useGroupBy', ['useExpanded'])
flatColumns.forEach(column => {
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
@@ -124,15 +111,16 @@ function useMain(instance) {
hooks.getGroupByToggleProps = []
flatHeaders.forEach(header => {
const { canGroupBy } = header
header.getGroupByToggleProps = props => {
//
;[...columns, ...headers].forEach(column => {
const { canGroupBy } = column
column.getGroupByToggleProps = props => {
return mergeProps(
{
onClick: canGroupBy
? e => {
e.persist()
header.toggleGroupBy()
column.toggleGroupBy()
}
: undefined,
style: {
@@ -140,7 +128,7 @@ function useMain(instance) {
},
title: 'Toggle GroupBy',
},
applyPropHooks(instance.hooks.getGroupByToggleProps, header, instance),
applyPropHooks(instance.hooks.getGroupByToggleProps, column, instance),
props
)
}
@@ -149,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
})
@@ -172,7 +159,7 @@ function useMain(instance) {
const aggregateRowsToValues = (rows, isSourceRows) => {
const values = {}
flatColumns.forEach(column => {
columns.forEach(column => {
// Don't aggregate columns that are in the groupBy
if (groupBy.includes(column.id)) {
values[column.id] = rows[0] ? rows[0].values[column.id] : null
@@ -231,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)
@@ -241,7 +228,6 @@ function useMain(instance) {
)
const row = {
isAggregated: true,
groupByID: columnID,
groupByVal,
values,
@@ -265,7 +251,7 @@ function useMain(instance) {
groupBy,
debug,
rows,
flatColumns,
columns,
userAggregations,
groupByFn,
])
+45 -54
View File
@@ -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,
+12 -81
View File
@@ -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,27 +50,8 @@ 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('.')
const childRowPrefixKey = [key, '.'].join('')
return setState(old => {
// Join the paths of deep rows
@@ -78,28 +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 === key || rowPath.startsWith(childRowPrefixKey)) {
newSelectedRows.add(rowPath)
}
})
newSelectedRows.add(key)
} else if (exists && !shouldExist) {
rowPaths.forEach(rowPath => {
if (rowPath === key || rowPath.startsWith(childRowPrefixKey)) {
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()],
@@ -116,7 +85,7 @@ function useMain(instance) {
style: {
cursor: 'pointer',
},
checked: isAllRowsSelected,
checked: allRowsSelected,
title: 'Toggle All Rows Selected',
},
applyPropHooks(instance.hooks.getToggleAllRowsSelectedProps, instance),
@@ -125,48 +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
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
@@ -174,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(
@@ -206,6 +137,6 @@ function useMain(instance) {
toggleRowSelected,
toggleRowSelectedAll,
getToggleAllRowsSelectedProps,
isAllRowsSelected,
allRowsSelected,
}
}
+14 -11
View File
@@ -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('.')
+64 -84
View File
@@ -49,7 +49,7 @@ function useMain(instance) {
const {
debug,
rows,
flatColumns,
columns,
orderByFn = defaultOrderByFn,
sortTypes: userSortTypes,
manualSorting,
@@ -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 = []
@@ -75,7 +74,7 @@ function useMain(instance) {
const { sortBy } = old
// Find the column for this columnID
const column = flatColumns.find(d => d.id === columnID)
const column = columns.find(d => d.id === columnID)
const { sortDescFirst } = column
// Find any existing sortBy for this column
@@ -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,96 +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 =>
flatColumns.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 = flatColumns.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 = flatColumns.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,
rows,
flatColumns,
orderByFn,
userSortTypes,
])
return sortData(rows)
},
[manualSorting, sortBy, debug, columns, rows, orderByFn, userSortTypes]
)
return {
...instance,
+5 -22
View File
@@ -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') {
+26 -63
View File
@@ -1,11 +1,5 @@
import React from 'react'
const columnFallbacks = {
Header: () => null,
Cell: ({ cell: { value = '' } }) => value,
show: true,
}
// Find the depth of the columns
export function findMaxDepth(columns, depth = 0) {
return columns.reduce((prev, curr) => {
@@ -25,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) {
@@ -44,7 +38,9 @@ export function decorateColumn(column, defaultColumn, parent, depth, index) {
}
column = {
...columnFallbacks,
Header: () => null,
Cell: ({ cell: { value = '' } }) => value,
show: true,
...column,
id,
accessor,
@@ -73,27 +69,28 @@ export function decorateColumnTree(columns, defaultColumn, parent, depth = 0) {
}
// Build the header groups from the bottom up
export function makeHeaderGroups(flatColumns, columns, defaultColumn) {
export function makeHeaderGroups(columns, maxDepth, defaultColumn) {
const headerGroups = []
const maxDepth = findMaxDepth(columns)
const removeChildColumns = column => {
delete column.columns
if (column.parent) {
removeChildColumns(column.parent)
}
}
columns.forEach(removeChildColumns)
// Build each header group from the bottom up
const buildGroup = (columns, depth) => {
const buildGroup = (columns, depth = 0) => {
const headerGroup = {
headers: [],
}
const parentColumns = []
// Do any of these columns have parents?
const hasParents = columns.some(col => col.parent)
columns.forEach(column => {
// Are we the first column in this group?
const isFirst = !parentColumns.length
// What is the latest (last) parent column?
let latestParentColumn = [...parentColumns].reverse()[0]
// If the column has a parent, add it if necessary
@@ -106,7 +103,7 @@ export function makeHeaderGroups(flatColumns, columns, defaultColumn) {
})
}
} else if (hasParents) {
// If other columns have parents, we'll need to add a place holder if necessary
// If other columns have parents, add a place holder if necessary
const placeholderColumn = decorateColumn(
{
originalID: [column.id, 'placeholder', maxDepth - depth].join('_'),
@@ -127,56 +124,30 @@ export function makeHeaderGroups(flatColumns, columns, 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)
})
headerGroups.push(headerGroup)
if (parentColumns.length) {
buildGroup(parentColumns, depth + 1)
buildGroup(parentColumns)
}
}
buildGroup(flatColumns, 0)
buildGroup(columns)
return headerGroups.reverse()
}
export function determineHeaderVisibility(instance) {
const { headers } = instance
const handleColumn = (column, parentVisible) => {
column.isVisible = parentVisible
? typeof column.show === 'function'
? column.show(instance)
: !!column.show
: false
if (column.headers && column.headers.length) {
column.headers.forEach(subColumn =>
handleColumn(subColumn, column.isVisible)
)
}
}
headers.forEach(subHeader => handleColumn(subHeader, true))
}
export function getBy(obj, path, def) {
if (!path) {
return obj
@@ -225,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]
@@ -377,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 = []) {
-5
View File
@@ -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"