feat(use-row-select): added useRowSelect plugin hook + related

This commit is contained in:
tannerlinsley
2019-08-03 14:20:08 -06:00
parent 6ad0d4e0c0
commit 037c32345f
30 changed files with 11284 additions and 32 deletions
+7
View File
@@ -355,6 +355,13 @@ The following properties are available on the table instance returned from `useT
- **Required**
- This function is responsible for lazily preparing a row for rendering. Any row that you intend to render in your table needs to be passed to this function **before every render**.
- **Why?** Since table data could potentially be very large, it can become very expensive to compute all of the necessary state for every row to be rendered regardless if it actually is rendered or not (for example if you are paginating or virtualizing the rows, you may only have a few rows visible at any given moment). This function allows only the rows you intend to display to be computed and prepped with the correct state.
- `rowPaths: Array<string>`
- An array containing the stringified `path` of every original row in the table. eg. If a row has a path of `[0, 3, 2]`, its stringified path would be `0.3.2`.
- This array is used by many plugin hooks including `useRowSelect` to manage row selection state
- Only rows that exist on the original `data` array will have a path in this array. Rows created by `useGroupBy`'s aggregations and grouping are not included in this array, since they do not reference an original data row.
- `flatRows: Array<Row>`
- An array of all rows, including subRows which have been flattened into the order in which they were detected (depth first)
- This can be helpful in calculating total row counts that must include subRows
### `HeaderGroup` Properties
-2
View File
@@ -53,8 +53,6 @@ function Table({ columns, data }) {
// it at 20 for this use case
const firstPageRows = rows.slice(0, 100)
console.log(firstPageRows)
return (
<>
<pre>
@@ -0,0 +1,4 @@
{
"presets": ["react-app"],
"plugins": ["styled-components"]
}
+1
View File
@@ -0,0 +1 @@
SKIP_PREFLIGHT_CHECK=true
@@ -0,0 +1,7 @@
{
"extends": ["react-app", "prettier"],
"rules": {
// "eqeqeq": 0,
// "jsx-a11y/anchor-is-valid": 0
}
}
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
@@ -0,0 +1,29 @@
const path = require('path')
const resolveFrom = require('resolve-from')
const fixLinkedDependencies = config => {
config.resolve = {
...config.resolve,
alias: {
...config.resolve.alias,
react$: resolveFrom(path.resolve('node_modules'), 'react'),
'react-dom$': resolveFrom(path.resolve('node_modules'), 'react-dom'),
},
}
return config
}
const includeSrcDirectory = config => {
config.resolve = {
...config.resolve,
modules: [path.resolve('src'), ...config.resolve.modules],
}
return config
}
module.exports = [
['use-babel-config', '.babelrc'],
['use-eslint-config', '.eslintrc'],
fixLinkedDependencies,
// includeSrcDirectory,
]
@@ -0,0 +1,6 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app) and Rescripts.
You can:
- [Open this example in a new CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/basic)
- `yarn` and `yarn start` to run and edit the example
@@ -0,0 +1,35 @@
{
"private": true,
"scripts": {
"start": "rescripts start",
"build": "rescripts build",
"test": "rescripts test",
"eject": "rescripts eject"
},
"dependencies": {
"namor": "^1.1.2",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "3.0.1",
"react-table": "next",
"styled-components": "^4.3.2"
},
"devDependencies": {
"@rescripts/cli": "^0.0.11",
"@rescripts/rescript-use-babel-config": "^0.0.8",
"@rescripts/rescript-use-eslint-config": "^0.0.9",
"babel-eslint": "10.0.1"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

@@ -0,0 +1,38 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
@@ -0,0 +1,15 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
@@ -0,0 +1,156 @@
import React from 'react'
import styled from 'styled-components'
import { useTable, useRowSelect } 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;
}
}
}
`
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 (
<Styles>
<Table columns={columns} data={data} />
</Styles>
)
}
export default App
@@ -0,0 +1,9 @@
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
it('renders without crashing', () => {
const div = document.createElement('div')
ReactDOM.render(<App />, div)
ReactDOM.unmountComponentAtNode(div)
})
@@ -0,0 +1,13 @@
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
code {
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
monospace;
}
@@ -0,0 +1,12 @@
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import * as serviceWorker from './serviceWorker'
ReactDOM.render(<App />, document.getElementById('root'))
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister()
@@ -0,0 +1,40 @@
import namor from 'namor'
const range = len => {
const arr = []
for (let i = 0; i < len; i++) {
arr.push(i)
}
return arr
}
const newPerson = () => {
const statusChance = Math.random()
return {
firstName: namor.generate({ words: 1, numbers: 0 }),
lastName: namor.generate({ words: 1, numbers: 0 }),
age: Math.floor(Math.random() * 30),
visits: Math.floor(Math.random() * 100),
progress: Math.floor(Math.random() * 100),
status:
statusChance > 0.66
? 'relationship'
: statusChance > 0.33
? 'complicated'
: 'single',
}
}
export default function makeData(...lens) {
const makeDataLevel = (depth = 0) => {
const len = lens[depth]
return range(len).map(d => {
return {
...newPerson(),
subRows: lens[depth + 1] ? makeDataLevel(depth + 1) : undefined,
}
})
}
return makeDataLevel()
}
@@ -0,0 +1,135 @@
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
)
export function register(config) {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href)
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config)
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, visit https://bit.ly/CRA-PWA'
)
})
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config)
}
})
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing
if (installingWorker == null) {
return
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
)
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration)
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.')
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration)
}
}
}
}
}
})
.catch(error => {
console.error('Error during service worker registration:', error)
})
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type')
if (
response.status === 404 ||
(contentType != null && contentType.indexOf('javascript') === -1)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload()
})
})
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config)
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
)
})
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister()
})
}
}
File diff suppressed because it is too large Load Diff
+14 -30
View File
@@ -142,10 +142,14 @@ export const useTable = (props, ...plugins) => {
})
// Access the row model
instanceRef.current.rows = React.useMemo(
const [rows, rowPaths, flatRows] = React.useMemo(
() => {
if (process.env.NODE_ENV === 'development' && debug)
console.time('getAccessedRows')
let flatRows = 0
const rowPaths = []
// Access the row's data
const accessRow = (originalRow, i, depth = 0, parentPath = []) => {
// Keep the original reference around
@@ -154,6 +158,9 @@ export const useTable = (props, ...plugins) => {
// Make the new path for the row
const path = [...parentPath, i]
flatRows++
rowPaths.push(path.join('.'))
// Process any subRows
const subRows = originalRow[subRowsKey]
? originalRow[subRowsKey].map((d, i) =>
@@ -197,11 +204,15 @@ export const useTable = (props, ...plugins) => {
const accessedData = data.map((d, i) => accessRow(d, i))
if (process.env.NODE_ENV === 'development' && debug)
console.timeEnd('getAccessedRows')
return accessedData
return [accessedData, rowPaths, flatRows]
},
[debug, data, subRowsKey]
)
instanceRef.current.rows = rows
instanceRef.current.rowPaths = rowPaths
instanceRef.current.flatRows = flatRows
// Determine column visibility
instanceRef.current.columns.forEach(column => {
column.visible =
@@ -216,26 +227,8 @@ export const useTable = (props, ...plugins) => {
instanceRef.current.hooks.useMain,
instanceRef.current
)
if (debug)
if (process.env.NODE_ENV === 'development' && debug)
console.timeEnd('hooks.useMain')
// // Allow hooks to decorate columns
// if (process.env.NODE_ENV === 'development' && debug) console.time('hooks.useColumns')
// instanceRef.current.columns = applyHooks(
// instanceRef.current.hooks.useColumns,
// instanceRef.current.columns,
// instanceRef.current
// )
// if (process.env.NODE_ENV === 'development' && debug) console.timeEnd('hooks.useColumns')
// // Allow hooks to decorate headers
// if (process.env.NODE_ENV === 'development' && debug) console.time('hooks.useHeaders')
// instanceRef.current.headers = applyHooks(
// instanceRef.current.hooks.useHeaders,
// instanceRef.current.headers,
// instanceRef.current
// )
// if (process.env.NODE_ENV === 'development' && debug) console.timeEnd('hooks.useHeaders')
;[...instanceRef.current.columns, ...instanceRef.current.headers].forEach(
column => {
// Give columns/headers rendering power
@@ -270,14 +263,6 @@ export const useTable = (props, ...plugins) => {
}
)
// // Allow hooks to decorate headerGroups
// if (process.env.NODE_ENV === 'development' && debug) console.time('hooks.useHeaderGroups')
// instanceRef.current.headerGroups = applyHooks(
// instanceRef.current.hooks.useHeaderGroups,
// instanceRef.current.headerGroups,
// instanceRef.current
// )
instanceRef.current.headerGroups.filter((headerGroup, i) => {
// Filter out any headers and headerGroups that don't have visible columns
headerGroup.headers = headerGroup.headers.filter(header => {
@@ -313,7 +298,6 @@ export const useTable = (props, ...plugins) => {
return false
})
// if (process.env.NODE_ENV === 'development' && debug) console.timeEnd('hooks.useHeaderGroups')
// Run the rows (this could be a dangerous hook with a ton of data)
if (process.env.NODE_ENV === 'development' && debug)
+1
View File
@@ -7,6 +7,7 @@ export { useFilters } from './plugin-hooks/useFilters'
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 { useFlexLayout } from './plugin-hooks/useFlexLayout'
export { useTokenPagination } from './utility-hooks/useTokenPagination'
export { actions, addActions } from './actions'
@@ -0,0 +1,219 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`renders a table with seletable rows 1`] = `
"Snapshot Diff:
- First value
+ Second value
@@ -109,11 +109,11 @@
</td>
<td
class=\\"\\"
>
<div>
- Not Selected
+ Selected
</div>
</td>
<td
class=\\"\\"
>
@@ -165,11 +165,11 @@
</td>
<td
class=\\"\\"
>
<div>
- Not Selected
+ Selected
</div>
</td>
<td
class=\\"\\"
>
@@ -221,11 +221,11 @@
</td>
<td
class=\\"\\"
>
<div>
- Not Selected
+ Selected
</div>
</td>
<td
class=\\"\\"
>
@@ -277,11 +277,11 @@
</td>
<td
class=\\"\\"
>
<div>
- Not Selected
+ Selected
</div>
</td>
<td
class=\\"\\"
>
@@ -314,15 +314,20 @@
</td>
</tr>
</tbody>
</table>
<p>
- Selected Rows: 0
+ Selected Rows: 4
</p>
<pre>
<code>
{
- \\"selectedRows\\": []
+ \\"selectedRows\\": [
+ \\"0\\",
+ \\"1\\",
+ \\"2\\",
+ \\"3\\"
+ ]
}
</code>
</pre>
</DocumentFragment>"
`;
exports[`renders a table with seletable rows 2`] = `
"Snapshot Diff:
- First value
+ Second value
@@ -109,11 +109,11 @@
</td>
<td
class=\\"\\"
>
<div>
- Selected
+ Not Selected
</div>
</td>
<td
class=\\"\\"
>
@@ -165,11 +165,11 @@
</td>
<td
class=\\"\\"
>
<div>
- Selected
+ Not Selected
</div>
</td>
<td
class=\\"\\"
>
@@ -221,11 +221,11 @@
</td>
<td
class=\\"\\"
>
<div>
- Selected
+ Not Selected
</div>
</td>
<td
class=\\"\\"
>
@@ -277,11 +277,11 @@
</td>
<td
class=\\"\\"
>
<div>
- Selected
+ Not Selected
</div>
</td>
<td
class=\\"\\"
>
@@ -314,20 +314,15 @@
</td>
</tr>
</tbody>
</table>
<p>
- Selected Rows: 4
+ Selected Rows: 0
</p>
<pre>
<code>
{
- \\"selectedRows\\": [
- \\"0\\",
- \\"1\\",
- \\"2\\",
- \\"3\\"
- ]
+ \\"selectedRows\\": []
}
</code>
</pre>
</DocumentFragment>"
`;
exports[`renders a table with seletable rows 3`] = `
"Snapshot Diff:
- First value
+ Second value
@@ -109,11 +109,11 @@
</td>
<td
class=\\"\\"
>
<div>
- Not Selected
+ Selected
</div>
</td>
<td
class=\\"\\"
>
@@ -221,11 +221,11 @@
</td>
<td
class=\\"\\"
>
<div>
- Not Selected
+ Selected
</div>
</td>
<td
class=\\"\\"
>
@@ -314,15 +314,18 @@
</td>
</tr>
</tbody>
</table>
<p>
- Selected Rows: 0
+ Selected Rows: 2
</p>
<pre>
<code>
{
- \\"selectedRows\\": []
+ \\"selectedRows\\": [
+ \\"0\\",
+ \\"2\\"
+ ]
}
</code>
</pre>
</DocumentFragment>"
`;
+191
View File
@@ -0,0 +1,191 @@
import '@testing-library/react/cleanup-after-each'
import '@testing-library/jest-dom/extend-expect'
import React from 'react'
import { render, fireEvent } from '@testing-library/react'
import { useTable } from '../../hooks/useTable'
import { useRowSelect } from '../useRowSelect'
const data = [
{
firstName: 'tanner',
lastName: 'linsley',
age: 29,
visits: 100,
status: 'In Relationship',
progress: 50,
},
{
firstName: 'derek',
lastName: 'perkins',
age: 40,
visits: 40,
status: 'Single',
progress: 80,
},
{
firstName: 'joe',
lastName: 'bergevin',
age: 45,
visits: 20,
status: 'Complicated',
progress: 10,
},
{
firstName: 'jaylen',
lastName: 'linsley',
age: 26,
visits: 99,
status: 'In Relationship',
progress: 70,
},
]
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>
<label>
<input type="checkbox" {...getToggleAllRowsSelectedProps()} />{' '}
Select All
</label>
</div>
),
// The cell can use the individual row's getToggleRowSelectedProps method
// to the render a checkbox
Cell: ({ row }) => (
<div>
<label>
<input type="checkbox" {...row.getToggleRowSelectedProps()} />{' '}
Select Row
</label>
</div>
),
},
{
id: 'selectedStatus',
Cell: ({ row }) => (
<div>{row.selected ? 'Selected' : 'Not Selected'}</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',
},
],
},
],
[]
)
return <Table columns={columns} data={data} />
}
test('renders a table with seletable rows', () => {
const { getByLabelText, getAllByLabelText, asFragment } = render(<App />)
const fragment1 = asFragment()
fireEvent.click(getByLabelText('Select All'))
const fragment2 = asFragment()
fireEvent.click(getByLabelText('Select All'))
const fragment3 = asFragment()
fireEvent.click(getAllByLabelText('Select Row')[0])
fireEvent.click(getAllByLabelText('Select Row')[2])
const fragment4 = asFragment()
expect(fragment1).toMatchDiffSnapshot(fragment2)
expect(fragment2).toMatchDiffSnapshot(fragment3)
expect(fragment3).toMatchDiffSnapshot(fragment4)
})
+2
View File
@@ -25,6 +25,8 @@ export const useExpanded = hooks => {
hooks.useMain.push(useMain)
}
useExpanded.pluginName = 'useExpanded'
function useMain(instance) {
PropTypes.checkPropTypes(propTypes, instance, 'property', 'useExpanded')
+2
View File
@@ -26,6 +26,8 @@ export const useFilters = hooks => {
hooks.useMain.push(useMain)
}
useFilters.pluginName = 'useFilters'
function useMain(instance) {
PropTypes.checkPropTypes(propTypes, instance, 'property', 'useFilters')
+2
View File
@@ -45,6 +45,8 @@ export const useGroupBy = hooks => {
hooks.useMain.push(useMain)
}
useGroupBy.pluginName = 'useGroupBy'
function columnsBeforeHeaderGroups(columns, { state: [{ groupBy }] }) {
// Sort grouped columns to the start of the column list
// before the headers are built
+2
View File
@@ -25,6 +25,8 @@ export const usePagination = hooks => {
hooks.useMain.push(useMain)
}
usePagination.pluginName = 'usePagination'
function useMain(instance) {
PropTypes.checkPropTypes(propTypes, instance, 'property', 'usePagination')
+145
View File
@@ -0,0 +1,145 @@
import PropTypes from 'prop-types'
import { mergeProps, applyPropHooks, ensurePluginOrder } from '../utils'
import { addActions, actions } from '../actions'
import { defaultState } from '../hooks/useTableState'
defaultState.selectedRows = []
addActions('toggleRowSelected', 'toggleRowSelectedAll')
const propTypes = {
manualRowSelectedKey: PropTypes.string,
}
export const useRowSelect = hooks => {
hooks.getToggleRowSelectedProps = []
hooks.getToggleAllRowsSelectedProps = []
hooks.useMain.push(useMain)
}
useRowSelect.pluginName = 'useRowSelect'
function useMain(instance) {
PropTypes.checkPropTypes(propTypes, instance, 'property', 'useRowSelect')
const {
hooks,
manualRowSelectedKey = 'selected',
plugins,
rowPaths,
state: [{ selectedRows }, setState],
} = instance
ensurePluginOrder(
plugins,
['useFilters', 'useGroupBy', 'useSortBy'],
'useRowSelect',
[]
)
const allRowsSelected = rowPaths.length === selectedRows.length
const toggleRowSelectedAll = set => {
setState(old => {
const selectAll = typeof set !== 'undefined' ? set : !allRowsSelected
return {
...old,
selectedRows: selectAll ? [...rowPaths] : [],
}
}, actions.toggleRowSelectedAll)
}
const toggleRowSelected = (key, set) => {
return setState(old => {
// Join the paths of deep rows
// to make a key, then manage all of the keys
// in a flat object
const exists = old.selectedRows.includes(key)
const shouldExist = typeof set !== 'undefined' ? set : !exists
let newSelectedRows = new Set(selectedRows)
if (!exists && shouldExist) {
newSelectedRows.add(key)
} else if (exists && !shouldExist) {
newSelectedRows.delete(key)
} else {
return old
}
return {
...old,
selectedRows: [...newSelectedRows.values()],
}
}, actions.toggleRowSelected)
}
const toggleRowSelectedByPath = (path, set) => {
return toggleRowSelected(path.join('.'), set)
}
const getToggleAllRowsSelectedProps = props => {
return mergeProps(
{
onChange: e => {
toggleRowSelectedAll(e.target.checked)
},
style: {
cursor: 'pointer',
},
checked: allRowsSelected,
title: 'Toggle All Rows Selected',
},
applyPropHooks(instance.hooks.getToggleAllRowsSelectedProps, instance),
props
)
}
hooks.prepareRow.push(row => {
row.canSelect = !!row.original
if (row.canSelect) {
row.selected = selectedRows.includes(row.path.join('.'))
row.toggleRowSelected = set => toggleRowSelectedByPath(row.path, set)
row.getToggleRowSelectedProps = props => {
let checked = false
if (row.original && row.original[manualRowSelectedKey]) {
checked = true
} else {
checked = selectedRows.includes(row.path.join('.'))
}
return mergeProps(
{
onChange: e => {
row.toggleRowSelected(e.target.checked)
},
style: {
cursor: 'pointer',
},
checked,
title: 'Toggle Row Selected',
},
applyPropHooks(
instance.hooks.getToggleRowSelectedProps,
row,
instance
),
props
)
}
}
return row
})
return {
...instance,
toggleRowSelected,
toggleRowSelectedByPath,
toggleRowSelectedAll,
getToggleAllRowsSelectedProps,
allRowsSelected,
}
}
+5
View File
@@ -1,6 +1,7 @@
import React from 'react'
import PropTypes from 'prop-types'
import { ensurePluginOrder } from '../utils'
import { addActions, actions } from '../actions'
import { defaultState } from '../hooks/useTableState'
import * as sortTypes from '../sortTypes'
@@ -38,6 +39,8 @@ export const useSortBy = hooks => {
hooks.useMain.push(useMain)
}
useSortBy.pluginName = 'useSortBy'
function useMain(instance) {
PropTypes.checkPropTypes(propTypes, instance, 'property', 'useSortBy')
@@ -57,6 +60,8 @@ function useMain(instance) {
plugins,
} = 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...
+26
View File
@@ -310,6 +310,32 @@ export function flattenBy(columns, childKey) {
return flatColumns
}
export function ensurePluginOrder(plugins, befores, plugin, afters) {
const pluginIndex = plugins.findIndex(
plugin => plugin.pluginName === 'useFilters'
)
befores.forEach(before => {
const beforeIndex = plugins.findIndex(
plugin => plugin.pluginName === before
)
if (beforeIndex > pluginIndex) {
throw new Error(
`React Table: The ${plugin} plugin hook must be placed after the ${before} plugin hook!`
)
}
})
afters.forEach(after => {
const afterIndex = plugins.findIndex(plugin => plugin.pluginName === after)
if (afterIndex < pluginIndex) {
throw new Error(
`React Table: The ${plugin} plugin hook must be placed before the ${after} plugin hook!`
)
}
})
}
//
function makePathArray(obj) {