feat(multiple): useRowState, fix useRowSelect/useSortBy/usePagination

This commit is contained in:
tannerlinsley 2019-08-06 19:57:48 -06:00
parent 110e04bf61
commit 8508a6567d
26 changed files with 11168 additions and 71 deletions

240
README.md
View File

@ -146,7 +146,6 @@ Hooks for building **lightweight, fast and extendable datagrids** for React
<img width="150" alt="" src="https://raw.githubusercontent.com/tannerlinsley/files/master/images/patreon/become-a-patron.png" />
</a>
# Documentation
- [Installation](#installation)
@ -190,6 +189,7 @@ import {
- [Row Selection - Client Side](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/row-selection-client-side)
- [Expanding - Client Side](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/expanding-client-side)
- [Sub Components](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/sub-components)
- [Editable Data](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/editable-cells)
# Concepts
@ -311,6 +311,11 @@ The following options are supported via the main options object passed to `useTa
- The default column object for every column passed to React Table.
- Column-specific properties will override the properties in this object, eg. `{ ...defaultColumn, ...userColumn }`
- This is particularly useful for adding global column properties. For instance, when using the `useFilters` plugin hook, add a default `Filter` renderer for every column, eg.`{ Filter: MyDefaultFilterComponent }`
- `initialRowStateKey: String`
- Optional
- 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.
- `debug: Bool`
- Optional
- A flag to turn on debug mode.
@ -384,6 +389,14 @@ The following properties are available on the table instance returned from `useT
- `flatRows: Array<Row>`
- An array of all rows, including subRows which have been flattened into the order in which they were detected (depth first)
- This can be helpful in calculating total row counts that must include subRows
- `setRowState: Function(rowPath, updater: Function | any) => void`
- This function can be used to update the internal state for any row.
- Pass it a valid `rowPath` array 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
- `setCellState: Function(rowPath, columnID, updater: Function | any) => void`
- This function can be used to update the internal state for any cell.
- 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
@ -439,6 +452,10 @@ The following additional properties are available on every `row` object returned
- This array is used with plugin hooks like `useExpanded` and `useGroupBy` to compute expanded states for individual rows.
- `subRows: Array<Row>`
- If subRows were detect on the original data object, this will be an array of those materialized row objects.
- `state: Object`
- The current state of the row. It's lifespan is attached to that of the original `data` array. When the raw `data` is changed, this state value is reset to the row's initial value (using the `initialRowStateKey` option).
- Can be updated via `instance.setRowState` or the row's `setState` function.
### Cell Properties
@ -1294,7 +1311,7 @@ The following options are supported via the main options object passed to `useTa
- 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.
### Instance Variables
### Instance Properties
The following values are provided to the table `instance`:
@ -1513,6 +1530,225 @@ function App() {
> Documentation Coming Soon...
## `useRowSelect`
- Plugin Hook
- Optional
`useRowSelect` is the hook that implements **basic row selection**. For more information on row selection, see [Row Selection](TODO)
### Table Options
The following options are supported via the main options object passed to `useTable(options)`
- `state[0].selectedRows: Array<RowPathKey>`
- Optional
- Defaults to `[]`
- If a row's path key (eg. a row path of `[1, 3, 2]` would have a path key of `1.3.2`) is found in this array, it will have a selected state.
- `manualRowSelectedKey: String`
- Optional
- 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
The following values are provided to the table `instance`:
- `toggleRowSelected: Function(rowPath: String, ?set: Bool) => void`
- Use this function to toggle a row's selected state.
- Optionally pass `true` or `false` to set it to that state
- `toggleRowSelectedAll: Function(?set: Bool) => void`
- Use this function to toggle all rows as select or not
- Optionally pass `true` or `false` to set all rows to that state
- `getToggleAllRowsSelectedProps: Function(props) => props`
- Use this function to get the props needed for a **select all checkbox**.
- Props:
- `onChange: Function()`
- `style.cursor: 'pointer'`
- `checked: Bool`
- `title: 'Toggle All Rows Selected'`
- `allRowsSelected: Bool`
- Will be `true` if all rows are selected.
- If at least one row is not selected, will be `false`
### Example
```js
function Table({ columns, data }) {
// Use the state and functions returned from useTable to build your UI
const {
getTableProps,
headerGroups,
rows,
prepareRow,
state: [{ selectedRows }],
} = useTable(
{
columns,
data,
},
useRowSelect
)
// Render the UI for your table
return (
<>
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>{column.render('Header')}</th>
))}
</tr>
))}
</thead>
<tbody>
{rows.map(
(row, i) =>
prepareRow(row) || (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return (
<td {...cell.getCellProps()}>{cell.render('Cell')}</td>
)
})}
</tr>
)
)}
</tbody>
</table>
<p>Selected Rows: {selectedRows.length}</p>
<pre>
<code>{JSON.stringify({ selectedRows }, null, 2)}</code>
</pre>
</>
)
}
function App() {
const columns = React.useMemo(
() => [
// Let's make a column for selection
{
id: 'selection',
// 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',
},
{
Header: 'Last Name',
accessor: 'lastName',
},
],
},
{
Header: 'Info',
columns: [
{
Header: 'Age',
accessor: 'age',
},
{
Header: 'Visits',
accessor: 'visits',
},
{
Header: 'Status',
accessor: 'status',
},
{
Header: 'Profile Progress',
accessor: 'progress',
},
],
},
],
[]
)
const data = React.useMemo(() => makeData(10), [])
return <Table columns={columns} data={data} />
}
```
## `useRowState`
- Plugin Hook
- Optional
`useRowState` is a plugin hook that implements **basic state management for _prepared_ rows and their cells**.
### Table Options
The following options are supported via the main options object passed to `useTable(options)`
- `state[0].rowState: Object<RowPathKey:Object<any, cellState: {columnID: Object}>>`
- Optional
- Defaults to `{}`
- If a row's path key (eg. a row path of `[1, 3, 2]` would have a path key of `1.3.2`) is found in this array, it will have the state of the value corresponding to that key.
- Individual row states can contain anything, but they also contain a `cellState` key, which provides cell-level state based on column ID's to every
**prepared** cell in the table.
- `initialRowStateAccessor: Function`
- Optional
- This function may optionally return the initial state for a row.
- If this function is defined, it will be passed a `Row` object, from which you can return a value to use as the initial state, eg. `row => row.original.initialState`
### Instance Properties
The following values are provided to the table `instance`:
- `setRowState: Function(rowPath: Array<string>, updater: Function | Any) => void`
- Use this function to programmatically update the state of a row.
- `updater` can be a function or value. If a `function` is passed, it will receive the current value and expect a new one to be returned.
- `setCellState: Function(rowPath: Array<string>, columnID: String, updater: Function | Any) => void`
- Use this function to programmatically update the cell of a row.
- `updater` can be a function or value. If a `function` is passed, it will receive the current value and expect a new one to be returned.
### Row Properties
The following additional properties are available on every **prepared** `row` object returned by the table instance.
- `state: Object`
- This is the state object for each row, pre-mapped to the row from the table state's `rowState` object via `rowState[row.path.join('.')]`
- May also contain a `cellState` key/value pair, which is used to provide individual cell states to this row's cells
- `setState: Function(updater: Function | any)`
- Use this function to programmatically update the state of a row.
- `updater` can be a function or value. If a `function` is passed, it will receive the current value and expect a new one to be returned.
### Cell Properties
The following additional properties are available on every `Cell` object returned in an array of `cells` on every row object.
- `state: Object`
- This is the state object for each cell, pre-mapped to the cell from the table state's `rowState` object via `rowState[row.path.join('.')].cellState[columnID]`
- `setState: Function(updater: Function | any)`
- Use this function to programmatically update the state of a cell.
- `updater` can be a function or value. If a `function` is passed, it will receive the current value and expect a new one to be returned.
### Example
> Have an example of using useRowState? Submit a PR to add it here!
## `useTableState`
- Optional

View File

@ -0,0 +1,4 @@
{
"presets": ["react-app"],
"plugins": ["styled-components"]
}

View File

@ -0,0 +1 @@
SKIP_PREFLIGHT_CHECK=true

View File

@ -0,0 +1,7 @@
{
"extends": ["react-app", "prettier"],
"rules": {
// "eqeqeq": 0,
// "jsx-a11y/anchor-is-valid": 0
}
}

23
examples/editable-data/.gitignore vendored Normal file
View File

@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*

View File

@ -0,0 +1,29 @@
const path = require('path')
const resolveFrom = require('resolve-from')
const fixLinkedDependencies = config => {
config.resolve = {
...config.resolve,
alias: {
...config.resolve.alias,
react$: resolveFrom(path.resolve('node_modules'), 'react'),
'react-dom$': resolveFrom(path.resolve('node_modules'), 'react-dom'),
},
}
return config
}
const includeSrcDirectory = config => {
config.resolve = {
...config.resolve,
modules: [path.resolve('src'), ...config.resolve.modules],
}
return config
}
module.exports = [
['use-babel-config', '.babelrc'],
['use-eslint-config', '.eslintrc'],
fixLinkedDependencies,
// includeSrcDirectory,
]

View File

@ -0,0 +1,6 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app) and Rescripts.
You can:
- [Open this example in a new CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/basic)
- `yarn` and `yarn start` to run and edit the example

View File

@ -0,0 +1,35 @@
{
"private": true,
"scripts": {
"start": "rescripts start",
"build": "rescripts build",
"test": "rescripts test",
"eject": "rescripts eject"
},
"dependencies": {
"namor": "^1.1.2",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "3.0.1",
"react-table": "next",
"styled-components": "^4.3.2"
},
"devDependencies": {
"@rescripts/cli": "^0.0.11",
"@rescripts/rescript-use-babel-config": "^0.0.8",
"@rescripts/rescript-use-eslint-config": "^0.0.9",
"babel-eslint": "10.0.1"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

@ -0,0 +1,38 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

View File

@ -0,0 +1,15 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}

View File

@ -0,0 +1,275 @@
import React from 'react'
import styled from 'styled-components'
import { useTable, usePagination } from 'react-table'
import makeData from './makeData'
const Styles = styled.div`
padding: 1rem;
table {
border-spacing: 0;
border: 1px solid black;
tr {
:last-child {
td {
border-bottom: 0;
}
}
}
th,
td {
margin: 0;
padding: 0.5rem;
border-bottom: 1px solid black;
border-right: 1px solid black;
:last-child {
border-right: 0;
}
input {
font-size: 1rem;
padding: 0;
margin: 0;
border: 0;
}
}
}
.pagination {
padding: 0.5rem;
}
`
// Create an editable cell renderer
const EditableCell = ({
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)
}
return <input value={value} onChange={onChange} onBlur={onBlur} />
}
// Set our editable cell renderer as the default Cell renderer
const defaultColumn = {
Cell: EditableCell,
}
// Be sure to pass our updateMyData and the disablePageResetOnDataChange option
function Table({ columns, data, updateMyData, disablePageResetOnDataChange }) {
// For this example, we're using pagination to illustrate how to stop
// the current page from resetting when our data changes
// Otherwise, nothing is different here.
const {
getTableProps,
headerGroups,
prepareRow,
page,
canPreviousPage,
canNextPage,
pageOptions,
pageCount,
gotoPage,
nextPage,
previousPage,
setPageSize,
state: [{ pageIndex, pageSize }],
} = useTable(
{
columns,
data,
defaultColumn,
disablePageResetOnDataChange,
// 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,
},
usePagination
)
// Render the UI for your table
return (
<>
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>{column.render('Header')}</th>
))}
</tr>
))}
</thead>
<tbody>
{page.map(
(row, i) =>
prepareRow(row) || (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return (
<td {...cell.getCellProps()}>{cell.render('Cell')}</td>
)
})}
</tr>
)
)}
</tbody>
</table>
<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>
</>
)
}
function App() {
const columns = React.useMemo(
() => [
{
Header: 'Name',
columns: [
{
Header: 'First Name',
accessor: 'firstName',
},
{
Header: 'Last Name',
accessor: 'lastName',
},
],
},
{
Header: 'Info',
columns: [
{
Header: 'Age',
accessor: 'age',
},
{
Header: 'Visits',
accessor: 'visits',
},
{
Header: 'Status',
accessor: 'status',
},
{
Header: 'Profile Progress',
accessor: 'progress',
},
],
},
],
[]
)
const [data, setData] = React.useState(() => makeData(20))
// 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 => {
return old.filter((row, index) => {
if (index === rowIndex) {
return {
...old[rowIndex],
[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 = () => setData(makeData(20))
return (
<Styles>
<button onClick={resetData}>Reset Data</button>
<Table
columns={columns}
data={data}
updateMyData={updateMyData}
disablePageResetOnDataChange={skipPageResetRef.current}
/>
</Styles>
)
}
export default App

View File

@ -0,0 +1,9 @@
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
it('renders without crashing', () => {
const div = document.createElement('div')
ReactDOM.render(<App />, div)
ReactDOM.unmountComponentAtNode(div)
})

View File

@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}

View File

@ -0,0 +1,12 @@
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import * as serviceWorker from './serviceWorker'
ReactDOM.render(<App />, document.getElementById('root'))
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister()

View File

@ -0,0 +1,40 @@
import namor from 'namor'
const range = len => {
const arr = []
for (let i = 0; i < len; i++) {
arr.push(i)
}
return arr
}
const newPerson = () => {
const statusChance = Math.random()
return {
firstName: namor.generate({ words: 1, numbers: 0 }),
lastName: namor.generate({ words: 1, numbers: 0 }),
age: Math.floor(Math.random() * 30),
visits: Math.floor(Math.random() * 100),
progress: Math.floor(Math.random() * 100),
status:
statusChance > 0.66
? 'relationship'
: statusChance > 0.33
? 'complicated'
: 'single',
}
}
export default function makeData(...lens) {
const makeDataLevel = (depth = 0) => {
const len = lens[depth]
return range(len).map(d => {
return {
...newPerson(),
subRows: lens[depth + 1] ? makeDataLevel(depth + 1) : undefined,
}
})
}
return makeDataLevel()
}

View File

@ -0,0 +1,135 @@
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
)
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href)
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config)
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://bit.ly/CRA-PWA'
)
})
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config)
}
})
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing
if (installingWorker == null) {
return
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
)
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration)
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.')
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration)
}
}
}
}
}
})
.catch(error => {
console.error('Error during service worker registration:', error)
})
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type')
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload()
})
})
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config)
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
)
})
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister()
})
}
}

File diff suppressed because it is too large Load Diff

View File

@ -43,6 +43,7 @@ function Table({ columns, data }) {
columns,
data,
defaultColumn,
debug: true,
},
useSortBy
)

View File

@ -27,7 +27,7 @@
"prepare": "yarn build",
"release": "yarn publish",
"releaseNext": "yarn publish --tag next",
"format": "prettier ./**{md,js,jsx,tsx} --write"
"format": "prettier ./src/**/*.{md,js,jsx,tsx} --write"
},
"files": [
"CHANGELOG.md",

View File

@ -16,17 +16,20 @@ export const useTableState = (
...initialState,
})
const overriddenState = React.useMemo(() => {
const newState = {
...state,
}
if (overrides) {
Object.keys(overrides).forEach(key => {
newState[key] = overrides[key]
})
}
return newState
}, [overrides, state])
const overriddenState = React.useMemo(
() => {
const newState = {
...state,
}
if (overrides) {
Object.keys(overrides).forEach(key => {
newState[key] = overrides[key]
})
}
return newState
},
[overrides, state]
)
const overriddenStateRef = React.useRef()
overriddenStateRef.current = overriddenState

View File

@ -8,6 +8,7 @@ export { useGroupBy } from './plugin-hooks/useGroupBy'
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 { useTokenPagination } from './utility-hooks/useTokenPagination'
export { actions, addActions } from './actions'

View File

@ -4,6 +4,7 @@ import PropTypes from 'prop-types'
//
import { addActions, actions } from '../actions'
import { defaultState } from '../hooks/useTableState'
import { ensurePluginOrder } from '../utils'
defaultState.pageSize = 10
defaultState.pageIndex = 0
@ -49,39 +50,12 @@ function useMain(instance) {
],
} = instance
// If usePagination should probably come after useFilters for
// the best performance, so let's hint to the user about that...
const pluginIndex = plugins.indexOf(usePagination)
if (process.env.NODE_ENV === 'development') {
const useFiltersIndex = plugins.findIndex(
plugin => plugin.name === 'useFilters'
)
const useGroupByIndex = plugins.findIndex(
plugin => plugin.name === 'useGroupBy'
)
const useSortByIndex = plugins.findIndex(
plugin => plugin.name === 'useSortBy'
)
if (useFiltersIndex > pluginIndex) {
throw new Error(
'React Table: The usePagination plugin hook must be placed before the useFilters plugin hook!'
)
}
if (useGroupByIndex > pluginIndex) {
throw new Error(
'React Table: The usePagination plugin hook must be placed before the useGroupBy plugin hook!'
)
}
if (useSortByIndex > pluginIndex) {
throw new Error(
'React Table: The usePagination plugin hook must be placed before the useSortBy plugin hook!'
)
}
}
ensurePluginOrder(
plugins,
['useFilters', 'useGroupBy', 'useSortBy'],
'usePagination',
[]
)
const rowDep = disablePageResetOnDataChange ? null : rows

View File

@ -50,7 +50,9 @@ function useMain(instance) {
}, actions.toggleRowSelectedAll)
}
const toggleRowSelected = (key, set) => {
const toggleRowSelected = (path, set) => {
const key = path.join('.')
return setState(old => {
// Join the paths of deep rows
// to make a key, then manage all of the keys
@ -74,10 +76,6 @@ function useMain(instance) {
}, actions.toggleRowSelected)
}
const toggleRowSelectedByPath = (path, set) => {
return toggleRowSelected(path.join('.'), set)
}
const getToggleAllRowsSelectedProps = props => {
return mergeProps(
{
@ -100,7 +98,7 @@ function useMain(instance) {
if (row.canSelect) {
row.selected = selectedRows.includes(row.path.join('.'))
row.toggleRowSelected = set => toggleRowSelectedByPath(row.path, set)
row.toggleRowSelected = set => toggleRowSelected(row.path, set)
row.getToggleRowSelectedProps = props => {
let checked = false
@ -137,7 +135,6 @@ function useMain(instance) {
return {
...instance,
toggleRowSelected,
toggleRowSelectedByPath,
toggleRowSelectedAll,
getToggleAllRowsSelectedProps,
allRowsSelected,

View File

@ -0,0 +1,115 @@
import React from 'react'
import PropTypes from 'prop-types'
import { addActions, actions } from '../actions'
import { defaultState } from '../hooks/useTableState'
defaultState.rowState = {}
addActions('setRowState', 'setCellState')
const propTypes = {
initialRowStateAccessor: PropTypes.func,
}
export const useRowState = hooks => {
hooks.useMain.push(useMain)
}
useRowState.pluginName = 'useRowState'
function useMain(instance) {
PropTypes.checkPropTypes(propTypes, instance, 'property', 'useRowState')
const {
hooks,
rows,
initialRowStateAccessor,
state: [{ rowState }, setState],
} = instance
const setRowState = React.useCallback(
(path, updater, action = actions.setRowState) => {
const pathKey = path.join('.')
return setState(old => {
return {
...old,
rowState: {
...old.rowState,
[pathKey]:
typeof updater === 'function'
? updater(old.rowState[pathKey])
: updater,
},
}
}, action)
},
[setState]
)
const setCellState = React.useCallback(
(rowPath, columnID, updater) => {
return setRowState(
rowPath,
old => {
return {
...old,
cellState: {
...old.cellState,
[columnID]:
typeof updater === 'function'
? updater(old.cellState[columnID])
: updater,
},
}
},
actions.setCellState
)
},
[setRowState]
)
// When data changes, reset row and cell state
React.useEffect(
() => {
setState(old => {
return {
...old,
rowState: {},
}
}, actions.setRowState)
},
[rows, setState]
)
hooks.prepareRow.push(row => {
const pathKey = row.path.join('.')
if (row.original) {
row.state =
(typeof rowState[pathKey] !== 'undefined'
? rowState[pathKey]
: initialRowStateAccessor && initialRowStateAccessor(row)) || {}
row.setState = updater => {
return setRowState(row.path, updater)
}
row.cells.forEach(cell => {
cell.state = row.state.cellState || {}
cell.setState = updater => {
return setCellState(row.path, cell.column.id, updater)
}
})
}
return row
})
return {
...instance,
setRowState,
setCellState,
}
}

View File

@ -61,23 +61,6 @@ function useMain(instance) {
} = instance
ensurePluginOrder(plugins, [], 'useSortBy', ['useFilters'])
if (process.env.NODE_ENV === 'development') {
// If useSortBy should probably come after useFilters for
// the best performance, so let's hint to the user about that...
const pluginIndex = plugins.indexOf(useSortBy)
const useFiltersIndex = plugins.findIndex(
plugin => plugin.name === 'useFilters'
)
if (useFiltersIndex > pluginIndex) {
console.warn(
'React Table: useSortBy should be placed before useFilters in your plugin list for better performance!'
)
}
}
// Add custom hooks
hooks.getSortByToggleProps = []