Compare commits

..
33 changed files with 12466 additions and 94 deletions
+4
View File
@@ -0,0 +1,4 @@
{
"presets": ["react-app"],
"plugins": ["styled-components"]
}
+1
View File
@@ -0,0 +1 @@
SKIP_PREFLIGHT_CHECK=true
+7
View File
@@ -0,0 +1,7 @@
{
"extends": ["react-app", "prettier"],
"rules": {
// "eqeqeq": 0,
// "jsx-a11y/anchor-is-valid": 0
}
}
+23
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*
@@ -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,
]
+6
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
@@ -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"
}
+168
View File
@@ -0,0 +1,168 @@
import React from 'react'
import styled from 'styled-components'
import { useTable, useExpanded } 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: userColumns, data, SubComponent }) {
const {
getTableProps,
headerGroups,
rows,
prepareRow,
columns,
state: [{ expanded }],
} = useTable(
{
columns: userColumns,
data,
},
useExpanded
)
return (
<>
<pre>
<code>{JSON.stringify({ expanded }, null, 2)}</code>
</pre>
<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>
{!row.subRows.length && row.isExpanded ? (
<tr>
<td colSpan={columns.length}>{SubComponent({ row })}</td>
</tr>
) : null}
</>
)
)}
</tbody>
</table>
<br />
<div>Showing the first 20 results of {rows.length} rows</div>
</>
)
}
function App() {
const columns = React.useMemo(
() => [
{
Header: () => null,
id: 'expander',
Cell: ({ row }) => (
<span
style={{
cursor: 'pointer',
paddingLeft: `${row.depth * 2}rem`,
}}
onClick={() => row.toggleExpanded()}
>
{row.isExpanded ? '👇' : '👉'}
</span>
),
},
{
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(5, 5, 5), [])
return (
<Styles>
<Table
columns={columns}
data={data}
SubComponent={({ row }) => (
<pre>
<code>{JSON.stringify({ values: row.values }, null, 2)}</code>
</pre>
)}
/>
</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
+11 -20
View File
@@ -58,26 +58,17 @@ function Table({ columns, data }) {
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(
column =>
console.log(column) || (
// Add the sorting props to control sorting. For this example
// we can add them into the header props
<th
{...column.getHeaderProps(column.getSortByToggleProps())}
>
{column.render('Header')}
{/* Add a sort direction indicator */}
<span>
{column.sorted
? column.sortedDesc
? ' 🔽'
: ' 🔼'
: ''}
</span>
</th>
)
)}
{headerGroup.headers.map(column => (
// Add the sorting props to control sorting. For this example
// we can add them into the header props
<th {...column.getHeaderProps(column.getSortByToggleProps())}>
{column.render('Header')}
{/* Add a sort direction indicator */}
<span>
{column.sorted ? (column.sortedDesc ? ' 🔽' : ' 🔼') : ''}
</span>
</th>
))}
</tr>
))}
</thead>
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "react-table",
"version": "7.0.0-alpha.15",
"version": "7.0.0-alpha.16",
"description": "A fast, lightweight, opinionated table and datagrid built on React",
"license": "MIT",
"homepage": "https://github.com/tannerlinsley/react-table#readme",
+5 -6
View File
@@ -1,12 +1,11 @@
export const text = (rows, id, filterValue) => {
return rows.filter(row => {
rows = rows.filter(row => {
const rowValue = row.values[id]
return rowValue !== undefined
? String(rowValue)
.toLowerCase()
.includes(String(filterValue).toLowerCase())
: true
return String(rowValue)
.toLowerCase()
.includes(String(filterValue).toLowerCase())
})
return rows
}
text.autoRemove = val => !val
-1
View File
@@ -1,6 +1,5 @@
import '@testing-library/react/cleanup-after-each'
import '@testing-library/jest-dom/extend-expect'
// NOTE: jest-dom adds handy assertions to Jest and is recommended, but not required
import React from 'react'
import { render } from '@testing-library/react'
+52 -35
View File
@@ -63,6 +63,7 @@ export const useTable = (props, ...plugins) => {
plugins,
hooks: {
columnsBeforeHeaderGroups: [],
columnsBeforeHeaderGroupsDeps: [],
useMain: [],
useColumns: [],
useHeaders: [],
@@ -84,64 +85,81 @@ export const useTable = (props, ...plugins) => {
})
if (debug) console.timeEnd('plugins')
// Compute columns, headerGroups and headers
const columnInfo = React.useMemo(
if (debug) console.info('buildColumns/headerGroup/headers')
// Decorate All the columns
let columnTree = React.useMemo(
() => decorateColumnTree(userColumns, defaultColumn),
[defaultColumn, userColumns]
)
// 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 (debug) console.info('buildColumns/headerGroup/headers')
// Decorate All the columns
let columnTree = decorateColumnTree(userColumns, defaultColumn)
// Get the flat list of all columns
let columns = flattenBy(columnTree, 'columns')
// Allow hooks to decorate columns
if (debug) console.time('hooks.columnsBeforeHeaderGroups')
columns = applyHooks(
const newColumns = applyHooks(
instanceRef.current.hooks.columnsBeforeHeaderGroups,
columns,
instanceRef.current
)
if (debug) console.timeEnd('hooks.columnsBeforeHeaderGroups')
// Make the headerGroups
const headerGroups = makeHeaderGroups(
columns,
findMaxDepth(columnTree),
defaultColumn
)
const headers = flattenBy(headerGroups, 'headers')
return {
columns,
headerGroups,
headers,
}
return newColumns
},
[debug, defaultColumn, userColumns]
[
columns,
debug,
// eslint-disable-next-line react-hooks/exhaustive-deps
...applyHooks(
instanceRef.current.hooks.columnsBeforeHeaderGroupsDeps,
[],
instanceRef.current
),
]
)
// Place the columns, headerGroups and headers on the api
Object.assign(instanceRef.current, columnInfo)
// Make the headerGroups
const headerGroups = React.useMemo(
() => makeHeaderGroups(columns, findMaxDepth(columnTree), defaultColumn),
[columnTree, columns, defaultColumn]
)
const headers = React.useMemo(() => flattenBy(headerGroups, 'headers'), [
headerGroups,
])
Object.assign(instanceRef.current, {
columns,
headerGroups,
headers,
})
// Access the row model
instanceRef.current.rows = React.useMemo(
() => {
if (debug) console.time('getAccessedRows')
// Access the row's data
const accessRow = (originalRow, i, depth = 0) => {
const accessRow = (originalRow, i, depth = 0, parentPath = []) => {
// Keep the original reference around
const original = originalRow
// Make the new path for the row
const path = [...parentPath, i]
// Process any subRows
const subRows = originalRow[subRowsKey]
? originalRow[subRowsKey].map((d, i) => accessRow(d, i, depth + 1))
? originalRow[subRowsKey].map((d, i) =>
accessRow(d, i, depth + 1, path)
)
: []
const row = {
original,
index: i,
path: [i], // used to create a key for each row even if not nested
path, // used to create a key for each row even if not nested
subRows,
depth,
cells: [{}], // This is a dummy cell
@@ -303,10 +321,9 @@ export const useTable = (props, ...plugins) => {
// any rows the user wishes to be displayed.
instanceRef.current.prepareRow = row => {
const { path } = row
row.getRowProps = props =>
mergeProps(
{ key: ['row', ...path].join('_') },
{ key: ['row', ...row.path].join('_') },
applyPropHooks(
instanceRef.current.hooks.getRowProps,
row,
@@ -329,7 +346,7 @@ export const useTable = (props, ...plugins) => {
// Give each cell a getCellProps base
cell.getCellProps = props => {
const columnPathStr = [...path, column.id].join('_')
const columnPathStr = [...row.path, column.id].join('_')
return mergeProps(
{
key: ['cell', columnPathStr].join('_'),
@@ -0,0 +1,714 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`renders an expandable table 1`] = `
"Snapshot Diff:
- First value
+ Second value
@@ -1,10 +1,12 @@
<DocumentFragment>
<pre>
<code>
{
- \\"expanded\\": {}
+ \\"expanded\\": {
+ \\"0\\": true
+ }
}
</code>
</pre>
<table
class=\\"\\"
@@ -82,10 +84,53 @@
<td
class=\\"\\"
>
<span
style=\\"cursor: pointer; padding-left: 0rem;\\"
+ >
+ 👇
+ </span>
+ </td>
+ <td
+ class=\\"\\"
+ >
+ tanner
+ </td>
+ <td
+ class=\\"\\"
+ >
+ linsley
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 29
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 100
+ </td>
+ <td
+ class=\\"\\"
+ >
+ In Relationship
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 50
+ </td>
+ </tr>
+ <tr
+ class=\\"\\"
+ >
+ <td
+ class=\\"\\"
+ >
+ <span
+ style=\\"cursor: pointer; padding-left: 2rem;\\"
>
👉
</span>
</td>
<td
@@ -115,10 +160,139 @@
</td>
<td
class=\\"\\"
>
50
+ </td>
+ </tr>
+ <tr
+ class=\\"\\"
+ >
+ <td
+ class=\\"\\"
+ >
+ <span
+ style=\\"cursor: pointer; padding-left: 2rem;\\"
+ >
+ 👉
+ </span>
+ </td>
+ <td
+ class=\\"\\"
+ >
+ derek
+ </td>
+ <td
+ class=\\"\\"
+ >
+ perkins
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 40
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 40
+ </td>
+ <td
+ class=\\"\\"
+ >
+ Single
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 80
+ </td>
+ </tr>
+ <tr
+ class=\\"\\"
+ >
+ <td
+ class=\\"\\"
+ >
+ <span
+ style=\\"cursor: pointer; padding-left: 2rem;\\"
+ >
+ 👉
+ </span>
+ </td>
+ <td
+ class=\\"\\"
+ >
+ joe
+ </td>
+ <td
+ class=\\"\\"
+ >
+ bergevin
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 45
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 20
+ </td>
+ <td
+ class=\\"\\"
+ >
+ Complicated
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 10
+ </td>
+ </tr>
+ <tr
+ class=\\"\\"
+ >
+ <td
+ class=\\"\\"
+ >
+ <span
+ style=\\"cursor: pointer; padding-left: 2rem;\\"
+ >
+ 👉
+ </span>
+ </td>
+ <td
+ class=\\"\\"
+ >
+ jaylen
+ </td>
+ <td
+ class=\\"\\"
+ >
+ linsley
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 26
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 99
+ </td>
+ <td
+ class=\\"\\"
+ >
+ In Relationship
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 70
</td>
</tr>
<tr
class=\\"\\"
>"
`;
exports[`renders an expandable table 2`] = `
"Snapshot Diff:
- First value
+ Second value
@@ -1,11 +1,13 @@
<DocumentFragment>
<pre>
<code>
{
\\"expanded\\": {
- \\"0\\": true
+ \\"0\\": {
+ \\"0\\": true
+ }
}
}
</code>
</pre>
<table
@@ -127,10 +129,53 @@
<td
class=\\"\\"
>
<span
style=\\"cursor: pointer; padding-left: 2rem;\\"
+ >
+ 👇
+ </span>
+ </td>
+ <td
+ class=\\"\\"
+ >
+ tanner
+ </td>
+ <td
+ class=\\"\\"
+ >
+ linsley
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 29
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 100
+ </td>
+ <td
+ class=\\"\\"
+ >
+ In Relationship
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 50
+ </td>
+ </tr>
+ <tr
+ class=\\"\\"
+ >
+ <td
+ class=\\"\\"
+ >
+ <span
+ style=\\"cursor: pointer; padding-left: 4rem;\\"
>
👉
</span>
</td>
<td
@@ -160,10 +205,139 @@
</td>
<td
class=\\"\\"
>
50
+ </td>
+ </tr>
+ <tr
+ class=\\"\\"
+ >
+ <td
+ class=\\"\\"
+ >
+ <span
+ style=\\"cursor: pointer; padding-left: 4rem;\\"
+ >
+ 👉
+ </span>
+ </td>
+ <td
+ class=\\"\\"
+ >
+ derek
+ </td>
+ <td
+ class=\\"\\"
+ >
+ perkins
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 40
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 40
+ </td>
+ <td
+ class=\\"\\"
+ >
+ Single
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 80
+ </td>
+ </tr>
+ <tr
+ class=\\"\\"
+ >
+ <td
+ class=\\"\\"
+ >
+ <span
+ style=\\"cursor: pointer; padding-left: 4rem;\\"
+ >
+ 👉
+ </span>
+ </td>
+ <td
+ class=\\"\\"
+ >
+ joe
+ </td>
+ <td
+ class=\\"\\"
+ >
+ bergevin
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 45
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 20
+ </td>
+ <td
+ class=\\"\\"
+ >
+ Complicated
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 10
+ </td>
+ </tr>
+ <tr
+ class=\\"\\"
+ >
+ <td
+ class=\\"\\"
+ >
+ <span
+ style=\\"cursor: pointer; padding-left: 4rem;\\"
+ >
+ 👉
+ </span>
+ </td>
+ <td
+ class=\\"\\"
+ >
+ jaylen
+ </td>
+ <td
+ class=\\"\\"
+ >
+ linsley
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 26
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 99
+ </td>
+ <td
+ class=\\"\\"
+ >
+ In Relationship
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 70
</td>
</tr>
<tr
class=\\"\\"
>"
`;
exports[`renders an expandable table 3`] = `
"Snapshot Diff:
- First value
+ Second value
@@ -2,11 +2,13 @@
<pre>
<code>
{
\\"expanded\\": {
\\"0\\": {
- \\"0\\": true
+ \\"0\\": {
+ \\"0\\": true
+ }
}
}
}
</code>
</pre>
@@ -172,10 +174,53 @@
<td
class=\\"\\"
>
<span
style=\\"cursor: pointer; padding-left: 4rem;\\"
+ >
+ 👇
+ </span>
+ </td>
+ <td
+ class=\\"\\"
+ >
+ tanner
+ </td>
+ <td
+ class=\\"\\"
+ >
+ linsley
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 29
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 100
+ </td>
+ <td
+ class=\\"\\"
+ >
+ In Relationship
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 50
+ </td>
+ </tr>
+ <tr
+ class=\\"\\"
+ >
+ <td
+ class=\\"\\"
+ >
+ <span
+ style=\\"cursor: pointer; padding-left: 6rem;\\"
>
👉
</span>
</td>
<td
@@ -205,10 +250,139 @@
</td>
<td
class=\\"\\"
>
50
+ </td>
+ </tr>
+ <tr
+ class=\\"\\"
+ >
+ <td
+ class=\\"\\"
+ >
+ <span
+ style=\\"cursor: pointer; padding-left: 6rem;\\"
+ >
+ 👉
+ </span>
+ </td>
+ <td
+ class=\\"\\"
+ >
+ derek
+ </td>
+ <td
+ class=\\"\\"
+ >
+ perkins
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 40
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 40
+ </td>
+ <td
+ class=\\"\\"
+ >
+ Single
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 80
+ </td>
+ </tr>
+ <tr
+ class=\\"\\"
+ >
+ <td
+ class=\\"\\"
+ >
+ <span
+ style=\\"cursor: pointer; padding-left: 6rem;\\"
+ >
+ 👉
+ </span>
+ </td>
+ <td
+ class=\\"\\"
+ >
+ joe
+ </td>
+ <td
+ class=\\"\\"
+ >
+ bergevin
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 45
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 20
+ </td>
+ <td
+ class=\\"\\"
+ >
+ Complicated
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 10
+ </td>
+ </tr>
+ <tr
+ class=\\"\\"
+ >
+ <td
+ class=\\"\\"
+ >
+ <span
+ style=\\"cursor: pointer; padding-left: 6rem;\\"
+ >
+ 👉
+ </span>
+ </td>
+ <td
+ class=\\"\\"
+ >
+ jaylen
+ </td>
+ <td
+ class=\\"\\"
+ >
+ linsley
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 26
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 99
+ </td>
+ <td
+ class=\\"\\"
+ >
+ In Relationship
+ </td>
+ <td
+ class=\\"\\"
+ >
+ 70
</td>
</tr>
<tr
class=\\"\\"
>"
`;
exports[`renders an expandable table 4`] = `
"Snapshot Diff:
- First value
+ Second value
@@ -3,11 +3,13 @@
<code>
{
\\"expanded\\": {
\\"0\\": {
\\"0\\": {
- \\"0\\": true
+ \\"0\\": {
+ \\"0\\": true
+ }
}
}
}
}
</code>
@@ -218,11 +220,11 @@
class=\\"\\"
>
<span
style=\\"cursor: pointer; padding-left: 6rem;\\"
>
- 👉
+ 👇
</span>
</td>
<td
class=\\"\\"
>
@@ -250,10 +252,30 @@
</td>
<td
class=\\"\\"
>
50
+ </td>
+ </tr>
+ <tr>
+ <td
+ colspan=\\"7\\"
+ >
+ <pre>
+ <code>
+ {
+ \\"values\\": {
+ \\"firstName\\": \\"tanner\\",
+ \\"lastName\\": \\"linsley\\",
+ \\"age\\": 29,
+ \\"visits\\": 100,
+ \\"status\\": \\"In Relationship\\",
+ \\"progress\\": 50
+ }
+ }
+ </code>
+ </pre>
</td>
</tr>
<tr
class=\\"\\"
>"
`;
@@ -1,11 +1,203 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`renders a sortable table 1`] = `
exports[`renders a filterable table 1`] = `
"Snapshot Diff:
Compared values have no visual difference."
- First value
+ Second value
@@ -37,11 +37,11 @@
colspan=\\"1\\"
>
Last Name
<input
placeholder=\\"Search...\\"
- value=\\"\\"
+ value=\\"l\\"
/>
</th>
<th
class=\\"\\"
colspan=\\"1\\"
@@ -115,78 +115,10 @@
</td>
<td
class=\\"\\"
>
progress: 50
- </td>
- </tr>
- <tr
- class=\\"\\"
- >
- <td
- class=\\"\\"
- >
- firstName: derek
- </td>
- <td
- class=\\"\\"
- >
- lastName: perkins
- </td>
- <td
- class=\\"\\"
- >
- age: 40
- </td>
- <td
- class=\\"\\"
- >
- visits: 40
- </td>
- <td
- class=\\"\\"
- >
- status: Single
- </td>
- <td
- class=\\"\\"
- >
- progress: 80
- </td>
- </tr>
- <tr
- class=\\"\\"
- >
- <td
- class=\\"\\"
- >
- firstName: joe
- </td>
- <td
- class=\\"\\"
- >
- lastName: bergevin
- </td>
- <td
- class=\\"\\"
- >
- age: 45
- </td>
- <td
- class=\\"\\"
- >
- visits: 20
- </td>
- <td
- class=\\"\\"
- >
- status: Complicated
- </td>
- <td
- class=\\"\\"
- >
- progress: 10
</td>
</tr>
<tr
class=\\"\\"
>"
`;
exports[`renders a sortable table 2`] = `
exports[`renders a filterable table 2`] = `
"Snapshot Diff:
Compared values have no visual difference."
- First value
+ Second value
@@ -37,11 +37,11 @@
colspan=\\"1\\"
>
Last Name
<input
placeholder=\\"Search...\\"
- value=\\"l\\"
+ value=\\"er\\"
/>
</th>
<th
class=\\"\\"
colspan=\\"1\\"
@@ -89,70 +89,70 @@
class=\\"\\"
>
<td
class=\\"\\"
>
- firstName: tanner
+ firstName: derek
</td>
<td
class=\\"\\"
>
- lastName: linsley
+ lastName: perkins
</td>
<td
class=\\"\\"
>
- age: 29
+ age: 40
</td>
<td
class=\\"\\"
>
- visits: 100
+ visits: 40
</td>
<td
class=\\"\\"
>
- status: In Relationship
+ status: Single
</td>
<td
class=\\"\\"
>
- progress: 50
+ progress: 80
</td>
</tr>
<tr
class=\\"\\"
>
<td
class=\\"\\"
>
- firstName: jaylen
+ firstName: joe
</td>
<td
class=\\"\\"
>
- lastName: linsley
+ lastName: bergevin
</td>
<td
class=\\"\\"
>
- age: 26
+ age: 45
</td>
<td
class=\\"\\"
>
- visits: 99
+ visits: 20
</td>
<td
class=\\"\\"
>
- status: In Relationship
+ status: Complicated
</td>
<td
class=\\"\\"
>
- progress: 70
+ progress: 10
</td>
</tr>
</tbody>
</table>
</DocumentFragment>"
`;
@@ -0,0 +1,371 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`renders a groupable table 1`] = `
"Snapshot Diff:
- First value
+ Second value
@@ -29,13 +29,13 @@
<span
class=\\"\\"
style=\\"cursor: pointer;\\"
title=\\"Toggle GroupBy\\"
>
- 👊
+ 🛑
</span>
- First Name
+ Last Name
</th>
<th
class=\\"\\"
colspan=\\"1\\"
>
@@ -44,11 +44,11 @@
style=\\"cursor: pointer;\\"
title=\\"Toggle GroupBy\\"
>
👊
</span>
- Last Name
+ First Name
</th>
<th
class=\\"\\"
colspan=\\"1\\"
>
@@ -107,138 +107,119 @@
class=\\"\\"
>
<td
class=\\"\\"
>
- firstName: tanner
- </td>
- <td
- class=\\"\\"
+ <span
+ style=\\"cursor: pointer;\\"
>
- lastName: linsley
- </td>
- <td
- class=\\"\\"
- >
- age: 29
- </td>
- <td
- class=\\"\\"
- >
- visits: 100
- </td>
- <td
- class=\\"\\"
- >
- status: In Relationship
+ 👉
+ </span>
+ lastName: linsley (2)
</td>
<td
class=\\"\\"
>
- progress: 50
- </td>
- </tr>
- <tr
- class=\\"\\"
- >
- <td
- class=\\"\\"
- >
- firstName: derek
- </td>
- <td
- class=\\"\\"
- >
- lastName: perkins
+ 2 Names
</td>
<td
class=\\"\\"
>
- age: 40
+ 27.5 (avg)
</td>
<td
class=\\"\\"
>
- visits: 40
+ 199 (total)
</td>
<td
class=\\"\\"
>
- status: Single
+ status: null
</td>
<td
class=\\"\\"
>
- progress: 80
+ 60 (med)
</td>
</tr>
<tr
class=\\"\\"
>
<td
class=\\"\\"
>
- firstName: joe
+ <span
+ style=\\"cursor: pointer;\\"
+ >
+ 👉
+ </span>
+ lastName: perkins (1)
</td>
<td
class=\\"\\"
>
- lastName: bergevin
+ 1 Names
</td>
<td
class=\\"\\"
>
- age: 45
+ 40 (avg)
</td>
<td
class=\\"\\"
>
- visits: 20
+ 40 (total)
</td>
<td
class=\\"\\"
>
- status: Complicated
+ status: null
</td>
<td
class=\\"\\"
>
- progress: 10
+ 80 (med)
</td>
</tr>
<tr
class=\\"\\"
>
<td
class=\\"\\"
>
- firstName: jaylen
+ <span
+ style=\\"cursor: pointer;\\"
+ >
+ 👉
+ </span>
+ lastName: bergevin (1)
</td>
<td
class=\\"\\"
>
- lastName: linsley
+ 1 Names
</td>
<td
class=\\"\\"
>
- age: 26
+ 45 (avg)
</td>
<td
class=\\"\\"
>
- visits: 99
+ 20 (total)
</td>
<td
class=\\"\\"
>
- status: In Relationship
+ status: null
</td>
<td
class=\\"\\"
>
- progress: 70
+ 10 (med)
</td>
</tr>
</tbody>
</table>
</DocumentFragment>"
`;
exports[`renders a groupable table 2`] = `
"Snapshot Diff:
- First value
+ Second value
@@ -6,17 +6,29 @@
<tr
class=\\"\\"
>
<th
class=\\"\\"
- colspan=\\"2\\"
+ colspan=\\"1\\"
>
Name
</th>
<th
class=\\"\\"
- colspan=\\"4\\"
+ colspan=\\"1\\"
+ >
+ Info
+ </th>
+ <th
+ class=\\"\\"
+ colspan=\\"1\\"
+ >
+ Name
+ </th>
+ <th
+ class=\\"\\"
+ colspan=\\"3\\"
>
Info
</th>
</tr>
<tr
@@ -42,13 +54,13 @@
<span
class=\\"\\"
style=\\"cursor: pointer;\\"
title=\\"Toggle GroupBy\\"
>
- 👊
+ 🛑
</span>
- First Name
+ Visits
</th>
<th
class=\\"\\"
colspan=\\"1\\"
>
@@ -57,11 +69,11 @@
style=\\"cursor: pointer;\\"
title=\\"Toggle GroupBy\\"
>
👊
</span>
- Age
+ First Name
</th>
<th
class=\\"\\"
colspan=\\"1\\"
>
@@ -70,11 +82,11 @@
style=\\"cursor: pointer;\\"
title=\\"Toggle GroupBy\\"
>
👊
</span>
- Visits
+ Age
</th>
<th
class=\\"\\"
colspan=\\"1\\"
>
@@ -114,10 +126,13 @@
>
👉
</span>
lastName: linsley (2)
</td>
+ <td
+ class=\\"\\"
+ />
<td
class=\\"\\"
>
2 Names
</td>
@@ -127,15 +142,10 @@
27.5 (avg)
</td>
<td
class=\\"\\"
>
- 199 (total)
- </td>
- <td
- class=\\"\\"
- >
status: null
</td>
<td
class=\\"\\"
>
@@ -155,22 +165,20 @@
</span>
lastName: perkins (1)
</td>
<td
class=\\"\\"
- >
- 1 Names
- </td>
+ />
<td
class=\\"\\"
>
- 40 (avg)
+ 1 Names
</td>
<td
class=\\"\\"
>
- 40 (total)
+ 40 (avg)
</td>
<td
class=\\"\\"
>
status: null
@@ -194,22 +202,20 @@
</span>
lastName: bergevin (1)
</td>
<td
class=\\"\\"
- >
- 1 Names
- </td>
+ />
<td
class=\\"\\"
>
- 45 (avg)
+ 1 Names
</td>
<td
class=\\"\\"
>
- 20 (total)
+ 45 (avg)
</td>
<td
class=\\"\\"
>
status: null"
`;
+207
View File
@@ -0,0 +1,207 @@
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 { useExpanded } from '../useExpanded'
const makeData = () => [
{
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,
},
]
const data = makeData()
data[0].subRows = makeData()
data[0].subRows[0].subRows = makeData()
data[0].subRows[0].subRows[0].subRows = makeData()
function Table({ columns: userColumns, data, SubComponent }) {
const {
getTableProps,
headerGroups,
rows,
prepareRow,
columns,
state: [{ expanded }],
} = useTable(
{
columns: userColumns,
data,
},
useExpanded
)
return (
<>
<pre>
<code>{JSON.stringify({ expanded }, null, 2)}</code>
</pre>
<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)
const { key, ...rowProps } = row.getRowProps()
return (
<React.Fragment key={key}>
<tr {...rowProps}>
{row.cells.map(cell => {
return (
<td {...cell.getCellProps()}>{cell.render('Cell')}</td>
)
})}
</tr>
{!row.subRows.length && row.isExpanded ? (
<tr>
<td colSpan={columns.length}>{SubComponent({ row })}</td>
</tr>
) : null}
</React.Fragment>
)
})}
</tbody>
</table>
</>
)
}
function App() {
const columns = React.useMemo(
() => [
{
Header: () => null,
id: 'expander',
Cell: ({ row }) => (
<span
style={{
cursor: 'pointer',
paddingLeft: `${row.depth * 2}rem`,
}}
onClick={() => row.toggleExpanded()}
>
{row.isExpanded ? '👇' : '👉'}
</span>
),
},
{
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}
SubComponent={({ row }) => (
<pre>
<code>{JSON.stringify({ values: row.values }, null, 2)}</code>
</pre>
)}
/>
)
}
test('renders an expandable table', () => {
const { getAllByText, asFragment } = render(<App />)
let expandButtons = getAllByText('👉')
const beforeGrouping = asFragment()
fireEvent.click(expandButtons[0])
const afterGrouping1 = asFragment()
expandButtons = getAllByText('👉')
fireEvent.click(expandButtons[0])
const afterGrouping2 = asFragment()
expandButtons = getAllByText('👉')
fireEvent.click(expandButtons[0])
const afterGrouping3 = asFragment()
expandButtons = getAllByText('👉')
fireEvent.click(expandButtons[0])
const afterGrouping4 = asFragment()
expect(beforeGrouping).toMatchDiffSnapshot(afterGrouping1)
expect(afterGrouping1).toMatchDiffSnapshot(afterGrouping2)
expect(afterGrouping2).toMatchDiffSnapshot(afterGrouping3)
expect(afterGrouping3).toMatchDiffSnapshot(afterGrouping4)
})
+12 -11
View File
@@ -1,6 +1,5 @@
import '@testing-library/react/cleanup-after-each'
import '@testing-library/jest-dom/extend-expect'
// NOTE: jest-dom adds handy assertions to Jest and is recommended, but not required
import React from 'react'
import { render, fireEvent } from '@testing-library/react'
@@ -73,7 +72,7 @@ function Table({ columns, data }) {
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>
{column.render('Header')}
{column.render('Filter')}
{column.canFilter ? column.render('Filter') : null}
</th>
))}
</tr>
@@ -139,19 +138,21 @@ function App() {
return <Table columns={columns} data={data} />
}
test('renders a sortable table', () => {
const { getByText, asFragment } = render(<App />)
test('renders a filterable table', () => {
const { getAllByPlaceholderText, asFragment } = render(<App />)
const beforeSort = asFragment()
const filterInputs = getAllByPlaceholderText('Search...')
fireEvent.click(getByText('First Name'))
const beforeFilter = asFragment()
const afterSort1 = asFragment()
fireEvent.change(filterInputs[1], { target: { value: 'l' } })
fireEvent.click(getByText('First Name'))
const afterFilter1 = asFragment()
const afterSort2 = asFragment()
fireEvent.change(filterInputs[1], { target: { value: 'er' } })
expect(beforeSort).toMatchDiffSnapshot(afterSort1)
expect(afterSort1).toMatchDiffSnapshot(afterSort2)
const afterFilter2 = asFragment()
expect(beforeFilter).toMatchDiffSnapshot(afterFilter1)
expect(afterFilter1).toMatchDiffSnapshot(afterFilter2)
})
+207
View File
@@ -0,0 +1,207 @@
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 { useGroupBy } from '../useGroupBy'
import { useExpanded } from '../useExpanded'
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,
},
]
const defaultColumn = {
Cell: ({ value, column: { id } }) => `${id}: ${value}`,
Filter: ({ filterValue, setFilter }) => (
<input
value={filterValue || ''}
onChange={e => {
setFilter(e.target.value || undefined) // Set undefined to remove the filter entirely
}}
placeholder="Search..."
/>
),
}
function Table({ columns, data }) {
const { getTableProps, headerGroups, rows, prepareRow } = useTable(
{
columns,
data,
defaultColumn,
},
useGroupBy,
useExpanded
)
return (
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>
{column.canGroupBy ? (
// If the column can be grouped, let's add a toggle
<span {...column.getGroupByToggleProps()}>
{column.grouped ? '🛑' : '👊'}
</span>
) : null}
{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.grouped ? (
<>
<span
style={{
cursor: 'pointer',
}}
onClick={() => row.toggleExpanded()}
>
{row.isExpanded ? '👇' : '👉'}
</span>
{cell.render('Cell')} ({row.subRows.length})
</>
) : cell.aggregated ? (
cell.render('Aggregated')
) : cell.repeatedValue ? null : (
cell.render('Cell')
)}
</td>
)
})}
</tr>
)
)}
</tbody>
</table>
)
}
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(
() => [
{
Header: 'Name',
columns: [
{
Header: 'First Name',
accessor: 'firstName',
aggregate: ['sum', 'count'],
Aggregated: ({ value }) => `${value} Names`,
},
{
Header: 'Last Name',
accessor: 'lastName',
aggregate: ['sum', 'uniqueCount'],
Aggregated: ({ value }) => `${value} Unique Names`,
},
],
},
{
Header: 'Info',
columns: [
{
Header: 'Age',
accessor: 'age',
aggregate: 'average',
Aggregated: ({ value }) => `${value} (avg)`,
},
{
Header: 'Visits',
accessor: 'visits',
aggregate: 'sum',
Aggregated: ({ value }) => `${value} (total)`,
},
{
Header: 'Status',
accessor: 'status',
},
{
Header: 'Profile Progress',
accessor: 'progress',
aggregate: roundedMedian,
Aggregated: ({ value }) => `${value} (med)`,
},
],
},
],
[]
)
return <Table columns={columns} data={data} />
}
test('renders a groupable table', () => {
const { getAllByText, asFragment } = render(<App />)
const groupByButtons = getAllByText('👊')
const beforeGrouping = asFragment()
fireEvent.click(groupByButtons[1])
const afterGrouping1 = asFragment()
fireEvent.click(groupByButtons[3])
const afterGrouping2 = asFragment()
expect(beforeGrouping).toMatchDiffSnapshot(afterGrouping1)
expect(afterGrouping1).toMatchDiffSnapshot(afterGrouping2)
})
-1
View File
@@ -1,6 +1,5 @@
import '@testing-library/react/cleanup-after-each'
import '@testing-library/jest-dom/extend-expect'
// NOTE: jest-dom adds handy assertions to Jest and is recommended, but not required
import React from 'react'
import { render, fireEvent } from '@testing-library/react'
+3 -4
View File
@@ -43,8 +43,7 @@ function useMain(instance) {
}
hooks.prepareRow.push(row => {
const { path } = row
row.toggleExpanded = set => toggleExpandedByPath(path, set)
row.toggleExpanded = set => toggleExpandedByPath(row.path, set)
return row
})
@@ -68,13 +67,13 @@ function useMain(instance) {
row.canExpand = row.subRows && !!row.subRows.length
if (row.isExpanded && row.subRows && row.subRows.length) {
row.subRows.forEach((row, i) => handleRow(row))
row.subRows.forEach(handleRow)
}
return row
}
rows.forEach(row => handleRow(row))
rows.forEach(handleRow)
return expandedRows
},
-8
View File
@@ -181,14 +181,6 @@ function useMain(instance) {
}
})
// then filter any rows without subcolumns because it would be strange to show
filteredRows = filteredRows.filter(row => {
if (!row.subRows) {
return true
}
return row.subRows.length > 0
})
return filteredRows
}
+4
View File
@@ -38,6 +38,10 @@ const propTypes = {
export const useGroupBy = hooks => {
hooks.columnsBeforeHeaderGroups.push(columnsBeforeHeaderGroups)
hooks.columnsBeforeHeaderGroupsDeps.push((deps, instance) => {
deps.push(instance.state[0].groupBy)
return deps
})
hooks.useMain.push(useMain)
}
+3 -3
View File
@@ -23,7 +23,7 @@ export function decorateColumn(column, defaultColumn, parent, depth, index) {
accessor = row => getBy(row, accessorString)
}
if (!id && typeof Header === 'string') {
if (!id && typeof Header === 'string' && Header) {
id = Header
}
@@ -38,8 +38,8 @@ export function decorateColumn(column, defaultColumn, parent, depth, index) {
}
column = {
Header: ({ id }) => id,
Cell: ({ value }) => typeof value !== 'undefined' ? value : '',
Header: () => null,
Cell: ({ value }) => (typeof value !== 'undefined' ? value : ''),
show: true,
...column,
id,