Compare commits

...
Author SHA1 Message Date
tannerlinsley 944b75c709 v7.0.0-alpha.26 2019-08-22 14:52:37 -06:00
tannerlinsley 4537f28a8d fix: fix header regeneration and colspan, better sorting 2019-08-22 14:46:33 -06:00
tannerlinsley 7ae4c4f9c7 v7.0.0-alpha.25 2019-08-20 12:56:36 -06:00
tannerlinsley 785b524d3c fix: removed useFlexLayout, fixed dot notation for accessors 2019-08-20 12:55:50 -06:00
tannerlinsley 16aa1143e6 chore: update logo source 2019-08-20 10:56:20 -06:00
tannerlinsley 5100d76ec2 docs: update Logo & Readme 2019-08-20 10:31:15 -06:00
Tanner LinsleyandGitHub c8c99265af Update README.md 2019-08-20 09:36:24 -06:00
tannerlinsley 5293bb7d34 chore: update logo 2019-08-20 09:35:37 -06:00
tannerlinsley aab49949db fix: rename some booleans to use 'is' prefix, added new logo 2019-08-20 09:31:11 -06:00
Tanner LinsleyandGitHub 3eaf4eb605 Update installation.md 2019-08-20 07:51:35 -06:00
tannerlinsley 89dd6747be docs: update kitchen-sink readme 2019-08-19 16:49:22 -06:00
tannerlinsley 196fb3c198 docs: added kitchen sink to the examples list 2019-08-19 16:48:06 -06:00
tannerlinsley 516aae55eb fix: update package.json 2019-08-19 16:42:21 -06:00
tannerlinsley 4a45cd6574 Merge branch 'master' of https://github.com/react-tools/react-table 2019-08-19 16:41:49 -06:00
tannerlinsley f59efde6fe fix: fix path getters, better plugin hook integration, renaming things 2019-08-19 16:38:42 -06:00
tannerlinsley 93524d0701 docs: add kitch sink example 2019-08-19 15:33:07 -06:00
DomenuchandTanner Linsley 64e9d91e3c Allow row generator to listen for column changes (#1442)
* added column dependency to row generator memo listeners

* added assertion to stop an infinite loop inside usePagination
2019-08-19 15:00:33 -06:00
Tanner LinsleyandGitHub 16df48f950 Update README.md 2019-08-19 10:17:17 -06:00
Tanner LinsleyandGitHub 37e2e1363d Update README.md 2019-08-19 10:14:19 -06:00
CodarandTanner Linsley af37eead5b Sub rows are selected if the parent row is selected. (#1444)
* Sub rows are selected if the parent row is selected.

* Parent rows are updated accordingly if a subRow is selected.

* Updated useRowSelect snapshot tests to test subRow selection.
2019-08-18 17:40:02 -06:00
Paweł DąbrowskiandTanner Linsley 3f0bb0a0dd fix(use-sort-by): sorting now ignores column ids that no longer exist (#1454)
* fix(use-sort-by): sorting now ignores column ids that no longer exist

* fix(use-filters): filtering no longer fails when column doesn't exist

* fix(use-sortby): filtering out invalid sortBys before sorting
2019-08-16 09:14:30 -06:00
tannerlinsley afbdb3e572 chore: update package.json 2019-08-16 08:03:32 -06:00
tannerlinsley 40884e9a44 style: lock prettier version, fix sorting example 2019-08-16 07:20:52 -06:00
tannerlinsley 4712cf8af5 docs: docs 2019-08-15 15:44:47 -06:00
Tanner LinsleyandGitHub 44193e415d Create CODE_OF_CONDUCT.md (#1452) 2019-08-15 15:42:50 -06:00
tannerlinsley 317e6befe0 docs: docs 2019-08-15 15:38:51 -06:00
tannerlinsley 650ecbcf9e docs: docs 2019-08-15 15:37:16 -06:00
tannerlinsley 008ea6f930 docs: docs 2019-08-15 15:36:13 -06:00
tannerlinsley 8a8c18feca docs(docs): docs 2019-08-15 15:33:39 -06:00
tannerlinsley 98466e6414 docs(docs): improve docs 2019-08-15 15:32:03 -06:00
73 changed files with 25336 additions and 2794 deletions
+76
View File
@@ -0,0 +1,76 @@
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at TANNERLINSLEY@GMAIL.COM. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
+28
View File
@@ -0,0 +1,28 @@
# Contributing
## Questions
If you have questions about implementation details, help or support, then please use our dedicated community forum at [Spectrum.chat/react-table](https://spectrum.chat/react-table) **PLEASE NOTE:** If you choose to instead open an issue for your question, your issue will be immediately closed and redirected to the forum.
## Reporting Issues
If you have found what you think is a bug, please [file an issue](https://github.com/tannerlinsley/react-table/issues/new). **PLEASE NOTE:** Issues that are identified as implementation questions or non-issues will be immediately closed and redirected to [Spectrum.chat/react-table](https://spectrum.chat/react-table)
## Suggesting new features
If you are here to suggest a feature, first create an issue if it does not already exist. From there, we will discuss use-cases for the feature and then finally discuss how it could be implemented.
## Development
If you have been assigned to fix an issue or develop a new feature, please follow these steps to get started:
- Fork this repository
- Install dependencies by running `$ yarn`
- Link `react-table` locally by running `$ yarn link`
- Auto-build files as you edit by running `$ yarn start`
- Implement your changes and tests to files in the `src/` directory and corresponding test files
- To run examples, follow their individual directions. Usually this is just `$ yarn && yarn start`.
- To run examples using your local build, link to the local `react-table` by running `$ yarn link react-table` from the example's directory
- Document your changes in the root `README.md`
- To stage a commit, run `yarn commit`
- Submit PR for review
+18 -2111
View File
File diff suppressed because it is too large Load Diff
+1
View File
@@ -0,0 +1 @@
To get started with React Table, [click here](../README.md), or select a specific document from this directory.
+1636
View File
File diff suppressed because it is too large Load Diff
+33
View File
@@ -0,0 +1,33 @@
# Concepts
## React Table is a "headless" UI library
React Table is a headless utility, which means out of the box, it doesn't render or supply any actual UI elements. You are in charge of utilizing the state and callbacks of the hooks provided by this library to render your own table markup. [Read this article to understand why React Table is built this way.](https://medium.com/merrickchristensen/headless-user-interface-components-565b0c0f2e18). If you don't want to, then here's a quick rundown anyway:
- Separation of Concerns - Not that superficial kind you read about all the time. The real kind. React Table as a library honestly has no business being in charge of your UI. The look, feel, and overall experience of your table is what makes your app or product great. The less React Table gets in the way of that, the better!
- Maintenance - By removing the massive (and seemingly endless) API surface area required to support every UI use-case, React Table can remain small, easy-to-use and simple to update/maintain.
- Extensibility - UI presents countless edge cases for a library simply because it's a creative medium, and one where every developer does things differently. By not dictating UI concerns, React Table empowers the developer to design and extend the UI based on their unique use-case.
## The React Table instance
At the heart of every React Table is the `useTable` hook and the table `instance` object that it returns. This `instance` object contains everything you'll ever need to build a table and interact with it's state. This includes, but is not limited to:
- Columns
- Materialized Data
- Sorting
- Filtering
- Grouping
- Pagination
- Expanded State
- Any functionality provided by custom plugin hooks, too!
## Rendering your own UI
As of React Table v7, **you the developer** are responsible for rendering your own UI, but don't let that intimidate you! Table UI's are fun and React Table makes it so easy to wire up your own table UI. The easiest way to learn how to build your own table UI is to [see some existing React Table examples](./examples.md)!
---
After reading about React Table's concepts, you should:
- [Check Out Some Examples](./examples.md)
- [Study the API](./api.md)
+44
View File
@@ -0,0 +1,44 @@
# Examples
- **Simple** - All of these examples use automatic state management, meaning, they don't hoist any state out of the table or manually control anything. Start here for understanding the basics about how to build your table UI.
- Basic
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/basic)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/basic)
- Sorting
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/sorting)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/sorting)
- Filtering
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/filtering)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/filtering)
- Grouping
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/grouping)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/grouping)
- Pagination
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/pagination)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/pagination)
- Row Selection
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/row-selection)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/row-selection)
- Expanding
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/expanding)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/expanding)
- Sub Components
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/sub-components)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/sub-components)
- Editable Data
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/editable-data)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/editable-data)
- **Complex**
- The "Kitchen Sink"
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/kitchen-sink)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/kitchen-sink)
- **Controlled via `useTableState`** - These examples are more advanced because they demonstrate how to manually control and respond to the state of the table using the `useTableState` hook.
- Pagination (Controlled)
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/pagination-controlled)
- [Open in CodeSandobx](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/pagination-controlled)
- **UI** - These examples demonstrate how to use React Table with your favorite UI libraries or tools!
- [ ] Styled-Components
- [ ] CSS
- [ ] Material-UI
- [ ] Bootstrap
- Want to write one of these examples or add another? [Submit a PR!](https://github.com/tannerlinsley/react-table/compare)
+29
View File
@@ -0,0 +1,29 @@
# Installation
Install the React Table v7 Alpha as a dependency using `npm` or `yarn`
```bash
# NPM
$ npm install react-table@next
# Yarn
$ yarn add react-table@next
```
> NOTE: `@next` is only required tempororarily while work on the alpha and beta versions are still shifting.
To import React Table:
```js
import {
useTable,
useGroupBy,
useFilters,
useSortBy,
useExpanded,
usePagination,
...
} from 'react-table'
```
Once you've installed React Table, continue to [Concepts](./concepts.md) to read more about how to utilize its API
+17 -11
View File
@@ -46,20 +46,28 @@ const Styles = styled.div`
// Create an editable cell renderer
const EditableCell = ({
value: initialValue,
cell: { value: initialValue },
row: { index },
column: { id },
updateMyData, // This is a custom function that we supplied to our table instance
}) => {
// We need to keep and update the state of the cell normally
const [value, setValue] = React.useState(initialValue)
const onChange = e => {
setValue(e.target.value)
}
// We'll only update the external data when the input is blurred
const onBlur = () => {
updateMyData(index, id, value)
}
// If the initialValue is changed externall, sync it up with our state
React.useEffect(() => {
setValue(initialValue)
}, [initialValue])
return <input value={value} onChange={onChange} onBlur={onBlur} />
}
@@ -221,6 +229,7 @@ function App() {
)
const [data, setData] = React.useState(() => makeData(20))
const [originalData] = React.useState(data)
// We need to keep the table from resetting the pageIndex when we
// Update data. So we can keep track of that flag with a ref.
@@ -232,8 +241,8 @@ function App() {
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) => {
setData(old =>
old.map((row, index) => {
if (index === rowIndex) {
return {
...old[rowIndex],
@@ -242,22 +251,19 @@ function App() {
}
return row
})
})
)
}
// After data chagnes, we turn the flag back off
// so that if data actually changes when we're not
// editing it, the page is reset
React.useEffect(
() => {
skipPageResetRef.current = false
},
[data]
)
React.useEffect(() => {
skipPageResetRef.current = false
}, [data])
// Let's add a data resetter/randomizer to help
// illustrate that flow...
const resetData = () => setData(makeData(20))
const resetData = () => setData(originalData)
return (
<Styles>
+3
View File
@@ -0,0 +1,3 @@
{
"infiniteLoopProtection": false
}
+39 -45
View File
@@ -36,7 +36,9 @@ const Styles = styled.div`
`
// Define a default UI for filtering
function DefaultColumnFilter({ filterValue, preFilteredRows, setFilter }) {
function DefaultColumnFilter({
column: { filterValue, preFilteredRows, setFilter },
}) {
const count = preFilteredRows.length
return (
@@ -52,19 +54,18 @@ function DefaultColumnFilter({ filterValue, preFilteredRows, setFilter }) {
// This is a custom filter UI for selecting
// a unique option from a list
function SelectColumnFilter({ filterValue, setFilter, preFilteredRows, id }) {
function SelectColumnFilter({
column: { filterValue, setFilter, preFilteredRows, id },
}) {
// Calculate the options for filtering
// using the preFilteredRows
const options = React.useMemo(
() => {
const options = new Set()
preFilteredRows.forEach(row => {
options.add(row.values[id])
})
return [...options.values()]
},
[id, preFilteredRows]
)
const options = React.useMemo(() => {
const options = new Set()
preFilteredRows.forEach(row => {
options.add(row.values[id])
})
return [...options.values()]
}, [id, preFilteredRows])
// Render a multi-select box
return (
@@ -87,22 +88,21 @@ function SelectColumnFilter({ filterValue, setFilter, preFilteredRows, id }) {
// This is a custom filter UI that uses a
// slider to set the filter value between a column's
// min and max values
function SliderColumnFilter({ filterValue, setFilter, preFilteredRows, id }) {
function SliderColumnFilter({
column: { filterValue, setFilter, preFilteredRows, id },
}) {
// Calculate the min and max
// using the preFilteredRows
const [min, max] = React.useMemo(
() => {
let min = 0
let max = 0
preFilteredRows.forEach(row => {
min = Math.min(row.values[id], min)
max = Math.max(row.values[id], max)
})
return [min, max]
},
[id, preFilteredRows]
)
const [min, max] = React.useMemo(() => {
let min = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
let max = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
preFilteredRows.forEach(row => {
min = Math.min(row.values[id], min)
max = Math.max(row.values[id], max)
})
return [min, max]
}, [id, preFilteredRows])
return (
<>
@@ -124,23 +124,17 @@ function SliderColumnFilter({ filterValue, setFilter, preFilteredRows, id }) {
// filter. It uses two number boxes and filters rows to
// ones that have values between the two
function NumberRangeColumnFilter({
filterValue = [],
preFilteredRows,
setFilter,
id,
column: { filterValue = [], preFilteredRows, setFilter, id },
}) {
const [min, max] = React.useMemo(
() => {
let min = 0
let max = 0
preFilteredRows.forEach(row => {
min = Math.min(row.values[id], min)
max = Math.max(row.values[id], max)
})
return [min, max]
},
[id, preFilteredRows]
)
const [min, max] = React.useMemo(() => {
let min = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
let max = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
preFilteredRows.forEach(row => {
min = Math.min(row.values[id], min)
max = Math.max(row.values[id], max)
})
return [min, max]
}, [id, preFilteredRows])
return (
<div
@@ -226,9 +220,9 @@ function Table({ columns, data }) {
useFilters // useFilters!
)
// We don't want to render all 2000 rows for this example, so cap
// it at 20 for this use case
const firstPageRows = rows.slice(0, 20)
// We don't want to render all of the rows for this example, so cap
// it for this use case
const firstPageRows = rows.slice(0, 10)
return (
<>
@@ -337,7 +331,7 @@ function App() {
[]
)
const data = React.useMemo(() => makeData(10000), [])
const data = React.useMemo(() => makeData(100000), [])
return (
<Styles>
+12 -12
View File
@@ -68,7 +68,7 @@ function Table({ columns, data }) {
{column.canGroupBy ? (
// If the column can be grouped, let's add a toggle
<span {...column.getGroupByToggleProps()}>
{column.grouped ? '🛑 ' : '👊 '}
{column.isGrouped ? '🛑 ' : '👊 '}
</span>
) : null}
{column.render('Header')}
@@ -90,16 +90,16 @@ function Table({ columns, data }) {
// from the useGroupBy hook
{...cell.getCellProps()}
style={{
background: cell.grouped
background: cell.isGrouped
? '#0aff0082'
: cell.aggregated
: cell.isAggregated
? '#ffa50078'
: cell.repeatedValue
: cell.isRepeatedValue
? '#ff000042'
: 'white',
}}
>
{cell.grouped ? (
{cell.isGrouped ? (
// If it's a grouped cell, add an expander and row count
<>
<span {...row.getExpandedToggleProps()}>
@@ -107,11 +107,11 @@ function Table({ columns, data }) {
</span>{' '}
{cell.render('Cell')} ({row.subRows.length})
</>
) : cell.aggregated ? (
) : cell.isAggregated ? (
// If the cell is aggregated, use the Aggregated
// renderer for cell
cell.render('Aggregated')
) : cell.repeatedValue ? null : ( // For cells with repeated values, render null
) : cell.isRepeatedValue ? null : ( // For cells with repeated values, render null
// Otherwise, just render the regular cell
cell.render('Cell')
)}
@@ -196,7 +196,7 @@ function App() {
// then sum any of those counts if they are
// aggregated further
aggregate: ['sum', 'count'],
Aggregated: ({ value }) => `${value} Names`,
Aggregated: ({ cell: { value } }) => `${value} Names`,
},
{
Header: 'Last Name',
@@ -206,7 +206,7 @@ function App() {
// being aggregated, then sum those counts if
// they are aggregated further
aggregate: ['sum', 'uniqueCount'],
Aggregated: ({ value }) => `${value} Unique Names`,
Aggregated: ({ cell: { value } }) => `${value} Unique Names`,
},
],
},
@@ -218,14 +218,14 @@ function App() {
accessor: 'age',
// Aggregate the average age of visitors
aggregate: 'average',
Aggregated: ({ value }) => `${value} (avg)`,
Aggregated: ({ cell: { value } }) => `${value} (avg)`,
},
{
Header: 'Visits',
accessor: 'visits',
// Aggregate the sum of all visits
aggregate: 'sum',
Aggregated: ({ value }) => `${value} (total)`,
Aggregated: ({ cell: { value } }) => `${value} (total)`,
},
{
Header: 'Status',
@@ -236,7 +236,7 @@ function App() {
accessor: 'progress',
// Use our custom roundedMedian aggregator
aggregate: roundedMedian,
Aggregated: ({ value }) => `${value} (med)`,
Aggregated: ({ cell: { value } }) => `${value} (med)`,
},
],
},
@@ -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,4 @@
# Kitchen Sink
- [Open this example in a new CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/kitchen-sink)
- `yarn` and `yarn start` to run and edit the example
@@ -0,0 +1,36 @@
{
"private": true,
"scripts": {
"start": "rescripts start",
"build": "rescripts build",
"test": "rescripts test",
"eject": "rescripts eject"
},
"dependencies": {
"match-sorter": "^4.0.1",
"namor": "^1.1.2",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "3.0.1",
"react-table": "next",
"styled-components": "^4.3.2"
},
"devDependencies": {
"@rescripts/cli": "^0.0.11",
"@rescripts/rescript-use-babel-config": "^0.0.8",
"@rescripts/rescript-use-eslint-config": "^0.0.9",
"babel-eslint": "10.0.1"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Binary file not shown.

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,3 @@
{
"infiniteLoopProtection": false
}
+626
View File
@@ -0,0 +1,626 @@
import React from 'react'
import styled from 'styled-components'
import {
useTable,
usePagination,
useSortBy,
useFilters,
useGroupBy,
useExpanded,
useRowSelect,
useTableState,
} from 'react-table'
import matchSorter from 'match-sorter'
import makeData from './makeData'
const Styles = styled.div`
padding: 1rem;
table {
border-spacing: 0;
border: 1px solid black;
tr {
:last-child {
td {
border-bottom: 0;
}
}
}
th,
td {
margin: 0;
padding: 0.5rem;
border-bottom: 1px solid black;
border-right: 1px solid black;
:last-child {
border-right: 0;
}
}
td {
input {
font-size: 1rem;
padding: 0;
margin: 0;
border: 0;
}
}
}
.pagination {
padding: 0.5rem;
}
`
// Create an editable cell renderer
const EditableCell = ({
cell: { value: initialValue },
row: { index },
column: { id },
updateMyData, // This is a custom function that we supplied to our table instance
editable,
}) => {
// We need to keep and update the state of the cell normally
const [value, setValue] = React.useState(initialValue)
const onChange = e => {
setValue(e.target.value)
}
// We'll only update the external data when the input is blurred
const onBlur = () => {
updateMyData(index, id, value)
}
// If the initialValue is changed externall, sync it up with our state
React.useEffect(() => {
setValue(initialValue)
}, [initialValue])
if (!editable) {
return `${initialValue}`
}
return <input value={value} onChange={onChange} onBlur={onBlur} />
}
// Define a default UI for filtering
function DefaultColumnFilter({
column: { filterValue, preFilteredRows, setFilter },
}) {
const count = preFilteredRows.length
return (
<input
value={filterValue || ''}
onChange={e => {
setFilter(e.target.value || undefined) // Set undefined to remove the filter entirely
}}
placeholder={`Search ${count} records...`}
/>
)
}
// This is a custom filter UI for selecting
// a unique option from a list
function SelectColumnFilter({
column: { filterValue, setFilter, preFilteredRows, id },
}) {
// Calculate the options for filtering
// using the preFilteredRows
const options = React.useMemo(() => {
const options = new Set()
preFilteredRows.forEach(row => {
options.add(row.values[id])
})
return [...options.values()]
}, [id, preFilteredRows])
// Render a multi-select box
return (
<select
value={filterValue}
onChange={e => {
setFilter(e.target.value || undefined)
}}
>
<option value="">All</option>
{options.map((option, i) => (
<option key={i} value={option}>
{option}
</option>
))}
</select>
)
}
// This is a custom filter UI that uses a
// slider to set the filter value between a column's
// min and max values
function SliderColumnFilter({
column: { filterValue, setFilter, preFilteredRows, id },
}) {
// Calculate the min and max
// using the preFilteredRows
const [min, max] = React.useMemo(() => {
let min = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
let max = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
preFilteredRows.forEach(row => {
min = Math.min(row.values[id], min)
max = Math.max(row.values[id], max)
})
return [min, max]
}, [id, preFilteredRows])
return (
<>
<input
type="range"
min={min}
max={max}
value={filterValue || min}
onChange={e => {
setFilter(parseInt(e.target.value, 10))
}}
/>
<button onClick={() => setFilter(undefined)}>Off</button>
</>
)
}
// This is a custom UI for our 'between' or number range
// filter. It uses two number boxes and filters rows to
// ones that have values between the two
function NumberRangeColumnFilter({
column: { filterValue = [], preFilteredRows, setFilter, id },
}) {
const [min, max] = React.useMemo(() => {
let min = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
let max = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
preFilteredRows.forEach(row => {
min = Math.min(row.values[id], min)
max = Math.max(row.values[id], max)
})
return [min, max]
}, [id, preFilteredRows])
return (
<div
style={{
display: 'flex',
}}
>
<input
value={filterValue[0] || ''}
type="number"
onChange={e => {
const val = e.target.value
setFilter((old = []) => [val ? parseInt(val, 10) : undefined, old[1]])
}}
placeholder={`Min (${min})`}
style={{
width: '70px',
marginRight: '0.5rem',
}}
/>
to
<input
value={filterValue[1] || ''}
type="number"
onChange={e => {
const val = e.target.value
setFilter((old = []) => [old[0], val ? parseInt(val, 10) : undefined])
}}
placeholder={`Max (${max})`}
style={{
width: '70px',
marginLeft: '0.5rem',
}}
/>
</div>
)
}
function fuzzyTextFilterFn(rows, id, filterValue) {
return matchSorter(rows, filterValue, { keys: [row => row.values[id]] })
}
// Let the table remove the filter if the string is empty
fuzzyTextFilterFn.autoRemove = val => !val
// Be sure to pass our updateMyData and the disablePageResetOnDataChange option
function Table({ columns, data, updateMyData, disablePageResetOnDataChange }) {
const filterTypes = React.useMemo(
() => ({
// Add a new fuzzyTextFilterFn filter type.
fuzzyText: fuzzyTextFilterFn,
// Or, override the default text filter to use
// "startWith"
text: (rows, id, filterValue) => {
return rows.filter(row => {
const rowValue = row.values[id]
return rowValue !== undefined
? String(rowValue)
.toLowerCase()
.startsWith(String(filterValue).toLowerCase())
: true
})
},
}),
[]
)
const defaultColumn = React.useMemo(
() => ({
// Let's set up our default Filter UI
Filter: DefaultColumnFilter,
// And also our default editable cell
Cell: EditableCell,
}),
[]
)
const tableState = useTableState({ pageIndex: 2 })
// Use the state and functions returned from useTable to build your UI
const {
getTableProps,
headerGroups,
prepareRow,
page, // Instead of using 'rows', we'll use page,
// which has only the rows for the active page
// The rest of these things are super handy, too ;)
canPreviousPage,
canNextPage,
pageOptions,
pageCount,
gotoPage,
nextPage,
previousPage,
setPageSize,
state: [{ pageIndex, pageSize, groupBy, expanded, filters, selectedRows }],
} = useTable(
{
columns,
data,
defaultColumn,
filterTypes,
// nestExpandedRows: true,
state: tableState,
// updateMyData isn't part of the API, but
// anything we put into these options will
// automatically be available on the instance.
// That way we can call this function from our
// cell renderer!
updateMyData,
// We also need to pass this so the page doesn't change
// when we edit the data
disablePageResetOnDataChange,
},
useFilters,
useSortBy,
useGroupBy,
useExpanded,
usePagination,
useRowSelect
)
// Render the UI for your table
return (
<>
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>
<div>
{column.canGroupBy ? (
// If the column can be grouped, let's add a toggle
<span {...column.getGroupByToggleProps()}>
{column.isGrouped ? '🛑 ' : '👊 '}
</span>
) : null}
<span {...column.getSortByToggleProps()}>
{column.render('Header')}
{/* Add a sort direction indicator */}
{column.isSorted
? column.isSortedDesc
? ' 🔽'
: ' 🔼'
: ''}
</span>
</div>
{/* Render the columns filter UI */}
<div>{column.canFilter ? column.render('Filter') : null}</div>
</th>
))}
</tr>
))}
</thead>
<tbody>
{page.map(
row =>
prepareRow(row) || (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return (
<td {...cell.getCellProps()}>
{cell.isGrouped ? (
// If it's a grouped cell, add an expander and row count
<>
<span {...row.getExpandedToggleProps()}>
{row.isExpanded ? '👇' : '👉'}
</span>{' '}
{cell.render('Cell', { editable: false })} (
{row.subRows.length})
</>
) : cell.isAggregated ? (
// If the cell is aggregated, use the Aggregated
// renderer for cell
cell.render('Aggregated')
) : cell.isRepeatedValue ? null : ( // For cells with repeated values, render null
// Otherwise, just render the regular cell
cell.render('Cell', { editable: true })
)}
</td>
)
})}
</tr>
)
)}
</tbody>
</table>
{/*
Pagination can be built however you'd like.
This is just a very basic UI implementation:
*/}
<div className="pagination">
<button onClick={() => gotoPage(0)} disabled={!canPreviousPage}>
{'<<'}
</button>{' '}
<button onClick={() => previousPage()} disabled={!canPreviousPage}>
{'<'}
</button>{' '}
<button onClick={() => nextPage()} disabled={!canNextPage}>
{'>'}
</button>{' '}
<button onClick={() => gotoPage(pageCount - 1)} disabled={!canNextPage}>
{'>>'}
</button>{' '}
<span>
Page{' '}
<strong>
{pageIndex + 1} of {pageOptions.length}
</strong>{' '}
</span>
<span>
| Go to page:{' '}
<input
type="number"
defaultValue={pageIndex + 1}
onChange={e => {
const page = e.target.value ? Number(e.target.value) - 1 : 0
gotoPage(page)
}}
style={{ width: '100px' }}
/>
</span>{' '}
<select
value={pageSize}
onChange={e => {
setPageSize(Number(e.target.value))
}}
>
{[10, 20, 30, 40, 50].map(pageSize => (
<option key={pageSize} value={pageSize}>
Show {pageSize}
</option>
))}
</select>
</div>
<pre>
<code>
{JSON.stringify(
{
pageIndex,
pageSize,
pageCount,
canNextPage,
canPreviousPage,
groupBy,
expanded,
filters,
selectedRows,
},
null,
2
)}
</code>
</pre>
</>
)
}
// Define a custom filter filter function!
function filterGreaterThan(rows, id, filterValue) {
return rows.filter(row => {
const rowValue = row.values[id]
return rowValue >= filterValue
})
}
// This is an autoRemove method on the filter function that
// when given the new filter value and returns true, the filter
// will be automatically removed. Normally this is just an undefined
// check, but here, we want to remove the filter if it's not a number
filterGreaterThan.autoRemove = val => typeof val !== 'number'
// This is a custom aggregator that
// takes in an array of values and
// returns the rounded median
function roundedMedian(values) {
let min = values[0] || ''
let max = values[0] || ''
values.forEach(value => {
min = Math.min(min, value)
max = Math.max(max, value)
})
return Math.round((min + max) / 2)
}
function App() {
const columns = React.useMemo(
() => [
{
id: 'selection',
// Make this column a groupByBoundary. This ensures that groupBy columns
// are placed after it
groupByBoundary: true,
// The header can use the table's getToggleAllRowsSelectedProps method
// to render a checkbox
Header: ({ getToggleAllRowsSelectedProps }) => (
<div>
<input type="checkbox" {...getToggleAllRowsSelectedProps()} />
</div>
),
// The cell can use the individual row's getToggleRowSelectedProps method
// to the render a checkbox
Cell: ({ row }) => (
<div>
<input type="checkbox" {...row.getToggleRowSelectedProps()} />
</div>
),
},
{
Header: 'Name',
columns: [
{
Header: 'First Name',
accessor: 'firstName',
// Use a two-stage aggregator here to first
// count the total rows being aggregated,
// then sum any of those counts if they are
// aggregated further
aggregate: ['sum', 'count'],
Aggregated: ({ cell: { value } }) => `${value} Names`,
},
{
Header: 'Last Name',
accessor: 'lastName',
// Use our custom `fuzzyText` filter on this column
filter: 'fuzzyText',
// Use another two-stage aggregator here to
// first count the UNIQUE values from the rows
// being aggregated, then sum those counts if
// they are aggregated further
aggregate: ['sum', 'uniqueCount'],
Aggregated: ({ cell: { value } }) => `${value} Unique Names`,
},
],
},
{
Header: 'Info',
columns: [
{
Header: 'Age',
accessor: 'age',
Filter: SliderColumnFilter,
filter: 'equals',
// Aggregate the average age of visitors
aggregate: 'average',
Aggregated: ({ cell: { value } }) => `${value} (avg)`,
},
{
Header: 'Visits',
accessor: 'visits',
Filter: NumberRangeColumnFilter,
filter: 'between',
// Aggregate the sum of all visits
aggregate: 'sum',
Aggregated: ({ cell: { value } }) => `${value} (total)`,
},
{
Header: 'Status',
accessor: 'status',
Filter: SelectColumnFilter,
filter: 'includes',
},
{
Header: 'Profile Progress',
accessor: 'progress',
Filter: SliderColumnFilter,
filter: filterGreaterThan,
// Use our custom roundedMedian aggregator
aggregate: roundedMedian,
Aggregated: ({ cell: { value } }) => `${value} (med)`,
},
],
},
],
[]
)
const [data, setData] = React.useState(() => makeData(10000))
const [originalData] = React.useState(data)
// We need to keep the table from resetting the pageIndex when we
// Update data. So we can keep track of that flag with a ref.
const skipPageResetRef = React.useRef(false)
// When our cell renderer calls updateMyData, we'll use
// the rowIndex, columnID and new value to update the
// original data
const updateMyData = (rowIndex, columnID, value) => {
// We also turn on the flag to not reset the page
skipPageResetRef.current = true
setData(old =>
old.map((row, index) => {
if (index === rowIndex) {
return {
...row,
[columnID]: value,
}
}
return row
})
)
}
// After data chagnes, we turn the flag back off
// so that if data actually changes when we're not
// editing it, the page is reset
React.useEffect(() => {
skipPageResetRef.current = false
}, [data])
// Let's add a data resetter/randomizer to help
// illustrate that flow...
const resetData = () => {
// Don't reset the page when we do this
skipPageResetRef.current = true
setData(originalData)
}
return (
<Styles>
<button onClick={resetData}>Reset Data</button>
<Table
columns={columns}
data={data}
updateMyData={updateMyData}
disablePageResetOnDataChange={skipPageResetRef.current}
/>
</Styles>
)
}
export default App
@@ -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
+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*
+29
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,
]
+4
View File
@@ -0,0 +1,4 @@
# Kitchen Sink
- [Open this example in a new CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/kitchen-sink)
- `yarn` and `yarn start` to run and edit the example
+36
View File
@@ -0,0 +1,36 @@
{
"private": true,
"scripts": {
"start": "rescripts start",
"build": "rescripts build",
"test": "rescripts test",
"eject": "rescripts eject"
},
"dependencies": {
"match-sorter": "^4.0.1",
"namor": "^1.1.2",
"react": "^16.8.6",
"react-dom": "^16.8.6",
"react-scripts": "3.0.1",
"react-table": "next",
"styled-components": "^4.3.2"
},
"devDependencies": {
"@rescripts/cli": "^0.0.11",
"@rescripts/rescript-use-babel-config": "^0.0.8",
"@rescripts/rescript-use-eslint-config": "^0.0.9",
"babel-eslint": "10.0.1"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

+38
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>
@@ -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,3 @@
{
"infiniteLoopProtection": false
}
+626
View File
@@ -0,0 +1,626 @@
import React from 'react'
import styled from 'styled-components'
import {
useTable,
usePagination,
useSortBy,
useFilters,
useGroupBy,
useExpanded,
useRowSelect,
useTableState,
} from 'react-table'
import matchSorter from 'match-sorter'
import makeData from './makeData'
const Styles = styled.div`
padding: 1rem;
table {
border-spacing: 0;
border: 1px solid black;
tr {
:last-child {
td {
border-bottom: 0;
}
}
}
th,
td {
margin: 0;
padding: 0.5rem;
border-bottom: 1px solid black;
border-right: 1px solid black;
:last-child {
border-right: 0;
}
}
td {
input {
font-size: 1rem;
padding: 0;
margin: 0;
border: 0;
}
}
}
.pagination {
padding: 0.5rem;
}
`
// Create an editable cell renderer
const EditableCell = ({
cell: { value: initialValue },
row: { index },
column: { id },
updateMyData, // This is a custom function that we supplied to our table instance
editable,
}) => {
// We need to keep and update the state of the cell normally
const [value, setValue] = React.useState(initialValue)
const onChange = e => {
setValue(e.target.value)
}
// We'll only update the external data when the input is blurred
const onBlur = () => {
updateMyData(index, id, value)
}
// If the initialValue is changed externall, sync it up with our state
React.useEffect(() => {
setValue(initialValue)
}, [initialValue])
if (!editable) {
return `${initialValue}`
}
return <input value={value} onChange={onChange} onBlur={onBlur} />
}
// Define a default UI for filtering
function DefaultColumnFilter({
column: { filterValue, preFilteredRows, setFilter },
}) {
const count = preFilteredRows.length
return (
<input
value={filterValue || ''}
onChange={e => {
setFilter(e.target.value || undefined) // Set undefined to remove the filter entirely
}}
placeholder={`Search ${count} records...`}
/>
)
}
// This is a custom filter UI for selecting
// a unique option from a list
function SelectColumnFilter({
column: { filterValue, setFilter, preFilteredRows, id },
}) {
// Calculate the options for filtering
// using the preFilteredRows
const options = React.useMemo(() => {
const options = new Set()
preFilteredRows.forEach(row => {
options.add(row.values[id])
})
return [...options.values()]
}, [id, preFilteredRows])
// Render a multi-select box
return (
<select
value={filterValue}
onChange={e => {
setFilter(e.target.value || undefined)
}}
>
<option value="">All</option>
{options.map((option, i) => (
<option key={i} value={option}>
{option}
</option>
))}
</select>
)
}
// This is a custom filter UI that uses a
// slider to set the filter value between a column's
// min and max values
function SliderColumnFilter({
column: { filterValue, setFilter, preFilteredRows, id },
}) {
// Calculate the min and max
// using the preFilteredRows
const [min, max] = React.useMemo(() => {
let min = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
let max = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
preFilteredRows.forEach(row => {
min = Math.min(row.values[id], min)
max = Math.max(row.values[id], max)
})
return [min, max]
}, [id, preFilteredRows])
return (
<>
<input
type="range"
min={min}
max={max}
value={filterValue || min}
onChange={e => {
setFilter(parseInt(e.target.value, 10))
}}
/>
<button onClick={() => setFilter(undefined)}>Off</button>
</>
)
}
// This is a custom UI for our 'between' or number range
// filter. It uses two number boxes and filters rows to
// ones that have values between the two
function NumberRangeColumnFilter({
column: { filterValue = [], preFilteredRows, setFilter, id },
}) {
const [min, max] = React.useMemo(() => {
let min = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
let max = preFilteredRows.length ? preFilteredRows[0].values[id] : 0
preFilteredRows.forEach(row => {
min = Math.min(row.values[id], min)
max = Math.max(row.values[id], max)
})
return [min, max]
}, [id, preFilteredRows])
return (
<div
style={{
display: 'flex',
}}
>
<input
value={filterValue[0] || ''}
type="number"
onChange={e => {
const val = e.target.value
setFilter((old = []) => [val ? parseInt(val, 10) : undefined, old[1]])
}}
placeholder={`Min (${min})`}
style={{
width: '70px',
marginRight: '0.5rem',
}}
/>
to
<input
value={filterValue[1] || ''}
type="number"
onChange={e => {
const val = e.target.value
setFilter((old = []) => [old[0], val ? parseInt(val, 10) : undefined])
}}
placeholder={`Max (${max})`}
style={{
width: '70px',
marginLeft: '0.5rem',
}}
/>
</div>
)
}
function fuzzyTextFilterFn(rows, id, filterValue) {
return matchSorter(rows, filterValue, { keys: [row => row.values[id]] })
}
// Let the table remove the filter if the string is empty
fuzzyTextFilterFn.autoRemove = val => !val
// Be sure to pass our updateMyData and the disablePageResetOnDataChange option
function Table({ columns, data, updateMyData, disablePageResetOnDataChange }) {
const filterTypes = React.useMemo(
() => ({
// Add a new fuzzyTextFilterFn filter type.
fuzzyText: fuzzyTextFilterFn,
// Or, override the default text filter to use
// "startWith"
text: (rows, id, filterValue) => {
return rows.filter(row => {
const rowValue = row.values[id]
return rowValue !== undefined
? String(rowValue)
.toLowerCase()
.startsWith(String(filterValue).toLowerCase())
: true
})
},
}),
[]
)
const defaultColumn = React.useMemo(
() => ({
// Let's set up our default Filter UI
Filter: DefaultColumnFilter,
// And also our default editable cell
Cell: EditableCell,
}),
[]
)
const tableState = useTableState({ pageIndex: 2 })
// Use the state and functions returned from useTable to build your UI
const {
getTableProps,
headerGroups,
prepareRow,
page, // Instead of using 'rows', we'll use page,
// which has only the rows for the active page
// The rest of these things are super handy, too ;)
canPreviousPage,
canNextPage,
pageOptions,
pageCount,
gotoPage,
nextPage,
previousPage,
setPageSize,
state: [{ pageIndex, pageSize, groupBy, expanded, filters, selectedRows }],
} = useTable(
{
columns,
data,
defaultColumn,
filterTypes,
// nestExpandedRows: true,
state: tableState,
// updateMyData isn't part of the API, but
// anything we put into these options will
// automatically be available on the instance.
// That way we can call this function from our
// cell renderer!
updateMyData,
// We also need to pass this so the page doesn't change
// when we edit the data
disablePageResetOnDataChange,
},
useFilters,
useSortBy,
useGroupBy,
useExpanded,
usePagination,
useRowSelect
)
// Render the UI for your table
return (
<>
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>
<div>
{column.canGroupBy ? (
// If the column can be grouped, let's add a toggle
<span {...column.getGroupByToggleProps()}>
{column.isGrouped ? '🛑 ' : '👊 '}
</span>
) : null}
<span {...column.getSortByToggleProps()}>
{column.render('Header')}
{/* Add a sort direction indicator */}
{column.isSorted
? column.isSortedDesc
? ' 🔽'
: ' 🔼'
: ''}
</span>
</div>
{/* Render the columns filter UI */}
<div>{column.canFilter ? column.render('Filter') : null}</div>
</th>
))}
</tr>
))}
</thead>
<tbody>
{page.map(
row =>
prepareRow(row) || (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return (
<td {...cell.getCellProps()}>
{cell.isGrouped ? (
// If it's a grouped cell, add an expander and row count
<>
<span {...row.getExpandedToggleProps()}>
{row.isExpanded ? '👇' : '👉'}
</span>{' '}
{cell.render('Cell', { editable: false })} (
{row.subRows.length})
</>
) : cell.isAggregated ? (
// If the cell is aggregated, use the Aggregated
// renderer for cell
cell.render('Aggregated')
) : cell.isRepeatedValue ? null : ( // For cells with repeated values, render null
// Otherwise, just render the regular cell
cell.render('Cell', { editable: true })
)}
</td>
)
})}
</tr>
)
)}
</tbody>
</table>
{/*
Pagination can be built however you'd like.
This is just a very basic UI implementation:
*/}
<div className="pagination">
<button onClick={() => gotoPage(0)} disabled={!canPreviousPage}>
{'<<'}
</button>{' '}
<button onClick={() => previousPage()} disabled={!canPreviousPage}>
{'<'}
</button>{' '}
<button onClick={() => nextPage()} disabled={!canNextPage}>
{'>'}
</button>{' '}
<button onClick={() => gotoPage(pageCount - 1)} disabled={!canNextPage}>
{'>>'}
</button>{' '}
<span>
Page{' '}
<strong>
{pageIndex + 1} of {pageOptions.length}
</strong>{' '}
</span>
<span>
| Go to page:{' '}
<input
type="number"
defaultValue={pageIndex + 1}
onChange={e => {
const page = e.target.value ? Number(e.target.value) - 1 : 0
gotoPage(page)
}}
style={{ width: '100px' }}
/>
</span>{' '}
<select
value={pageSize}
onChange={e => {
setPageSize(Number(e.target.value))
}}
>
{[10, 20, 30, 40, 50].map(pageSize => (
<option key={pageSize} value={pageSize}>
Show {pageSize}
</option>
))}
</select>
</div>
<pre>
<code>
{JSON.stringify(
{
pageIndex,
pageSize,
pageCount,
canNextPage,
canPreviousPage,
groupBy,
expanded,
filters,
selectedRows,
},
null,
2
)}
</code>
</pre>
</>
)
}
// Define a custom filter filter function!
function filterGreaterThan(rows, id, filterValue) {
return rows.filter(row => {
const rowValue = row.values[id]
return rowValue >= filterValue
})
}
// This is an autoRemove method on the filter function that
// when given the new filter value and returns true, the filter
// will be automatically removed. Normally this is just an undefined
// check, but here, we want to remove the filter if it's not a number
filterGreaterThan.autoRemove = val => typeof val !== 'number'
// This is a custom aggregator that
// takes in an array of values and
// returns the rounded median
function roundedMedian(values) {
let min = values[0] || ''
let max = values[0] || ''
values.forEach(value => {
min = Math.min(min, value)
max = Math.max(max, value)
})
return Math.round((min + max) / 2)
}
function App() {
const columns = React.useMemo(
() => [
{
id: 'selection',
// Make this column a groupByBoundary. This ensures that groupBy columns
// are placed after it
groupByBoundary: true,
// The header can use the table's getToggleAllRowsSelectedProps method
// to render a checkbox
Header: ({ getToggleAllRowsSelectedProps }) => (
<div>
<input type="checkbox" {...getToggleAllRowsSelectedProps()} />
</div>
),
// The cell can use the individual row's getToggleRowSelectedProps method
// to the render a checkbox
Cell: ({ row }) => (
<div>
<input type="checkbox" {...row.getToggleRowSelectedProps()} />
</div>
),
},
{
Header: 'Name',
columns: [
{
Header: 'First Name',
accessor: 'firstName',
// Use a two-stage aggregator here to first
// count the total rows being aggregated,
// then sum any of those counts if they are
// aggregated further
aggregate: ['sum', 'count'],
Aggregated: ({ cell: { value } }) => `${value} Names`,
},
{
Header: 'Last Name',
accessor: 'lastName',
// Use our custom `fuzzyText` filter on this column
filter: 'fuzzyText',
// Use another two-stage aggregator here to
// first count the UNIQUE values from the rows
// being aggregated, then sum those counts if
// they are aggregated further
aggregate: ['sum', 'uniqueCount'],
Aggregated: ({ cell: { value } }) => `${value} Unique Names`,
},
],
},
{
Header: 'Info',
columns: [
{
Header: 'Age',
accessor: 'age',
Filter: SliderColumnFilter,
filter: 'equals',
// Aggregate the average age of visitors
aggregate: 'average',
Aggregated: ({ cell: { value } }) => `${value} (avg)`,
},
{
Header: 'Visits',
accessor: 'visits',
Filter: NumberRangeColumnFilter,
filter: 'between',
// Aggregate the sum of all visits
aggregate: 'sum',
Aggregated: ({ cell: { value } }) => `${value} (total)`,
},
{
Header: 'Status',
accessor: 'status',
Filter: SelectColumnFilter,
filter: 'includes',
},
{
Header: 'Profile Progress',
accessor: 'progress',
Filter: SliderColumnFilter,
filter: filterGreaterThan,
// Use our custom roundedMedian aggregator
aggregate: roundedMedian,
Aggregated: ({ cell: { value } }) => `${value} (med)`,
},
],
},
],
[]
)
const [data, setData] = React.useState(() => makeData(10000))
const [originalData] = React.useState(data)
// We need to keep the table from resetting the pageIndex when we
// Update data. So we can keep track of that flag with a ref.
const skipPageResetRef = React.useRef(false)
// When our cell renderer calls updateMyData, we'll use
// the rowIndex, columnID and new value to update the
// original data
const updateMyData = (rowIndex, columnID, value) => {
// We also turn on the flag to not reset the page
skipPageResetRef.current = true
setData(old =>
old.map((row, index) => {
if (index === rowIndex) {
return {
...row,
[columnID]: value,
}
}
return row
})
)
}
// After data chagnes, we turn the flag back off
// so that if data actually changes when we're not
// editing it, the page is reset
React.useEffect(() => {
skipPageResetRef.current = false
}, [data])
// Let's add a data resetter/randomizer to help
// illustrate that flow...
const resetData = () => {
// Don't reset the page when we do this
skipPageResetRef.current = true
setData(originalData)
}
return (
<Styles>
<button onClick={resetData}>Reset Data</button>
<Table
columns={columns}
data={data}
updateMyData={updateMyData}
disablePageResetOnDataChange={skipPageResetRef.current}
/>
</Styles>
)
}
export default App
+9
View File
@@ -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)
})
+13
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;
}
+12
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()
+40
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()
}
+135
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
+95 -3
View File
@@ -1,6 +1,98 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app) and Rescripts.
You can:
# Pagination
- [Open this example in a new CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/pagination)
- `yarn` and `yarn start` to run and edit the example
## Guide
To add automatic client side pagination, use the `usePagination` hook:
```diff
// Import React
import React from 'react'
// Import React Table
import {
useTable,
useGroupBy,
useFilters,
useSortBy,
useExpanded,
+ usePagination,
} from 'react-table'
// Create a component to render your table
function MyTable(props) {
// Use the useTable hook to create your table configuration
const instance = useTable(
props,
useGroupBy,
useFilters,
useSortBy,
useExpanded,
+ usePagination,
)
// Use the state and functions returned from useTable to build your UI
const {
getTableProps,
headerGroups,
rows,
getRowProps,
prepareRow,
+ pageOptions,
+ page,
+ state: [{ pageIndex, pageSize }],
+ gotoPage,
+ previousPage,
+ nextPage,
+ setPageSize,
+ canPreviousPage,
+ canNextPage,
} = instance
// Render the UI for your table
return (
<div>
<table {...getTableProps()}>
...
</table>
+ <div>
+ <button onClick={() => previousPage()} disabled={!canPreviousPage}>
+ Previous Page
+ </button>
+ <button onClick={() => nextPage()} disabled={!canNextPage}>
+ Next Page
+ </button>
+ <div>
+ Page{' '}
+ <em>
+ {pageIndex + 1} of {pageOptions.length}
+ </em>
+ </div>
+ <div>Go to page:</div>
+ <input
+ type="number"
+ defaultValue={pageIndex + 1 || 1}
+ onChange={e => {
+ const page = e.target.value ? Number(e.target.value) - 1 : 0
+ gotoPage(page)
+ }}
+ />
+ <select
+ value={pageSize}
+ onChange={e => {
+ setPageSize(Number(e.target.value))
+ }}
+ >
+ {pageSizeOptions.map(pageSize => (
+ <option key={pageSize} value={pageSize}>
+ Show {pageSize}
+ </option>
+ ))}
+ </select>
+ </div>
</div>
)
}
```
+59 -3
View File
@@ -1,6 +1,62 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app) and Rescripts.
# Sorting
You can:
Automatic sorting can be accomplished by using the `useSortBy` plugin hook.
- [Open this example in a new CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/sorting)
- `yarn` and `yarn start` to run and edit the example
- Or, `yarn` and `yarn start` to run and edit the example
## Guide
Start by importing the hook from `react-table`:
```diff
-import { useTable } from 'react-table'
+import { useTable, useSortBy } from 'react-table'
```
Next, add the `useSortBy` hook to your `useTable` hook and add the necessary UI pieces we need to make sorting work:
```diff
function MyTable() {
const { getTableProps, headerGroups, rows, prepareRow } = useTable(
{
data,
columns,
},
- useSortBy
+ useSortBy
)
return (
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
- <th {...column.getHeaderProps()}>
+ <th {...column.getHeaderProps(column.getSortByToggleProps())}>
{column.render('Header')}
+ <span>
+ {column.isSorted ? (column.isSortedDesc ? ' 🔽' : ' 🔼') : ''}
+ </span>
</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>
)
}
```
+5 -7
View File
@@ -33,17 +33,11 @@ const Styles = styled.div`
}
`
const defaultColumn = {
sort: 'numeric',
}
function Table({ columns, data }) {
const { getTableProps, headerGroups, rows, prepareRow } = useTable(
{
columns,
data,
defaultColumn,
debug: true,
},
useSortBy
)
@@ -65,7 +59,11 @@ function Table({ columns, data }) {
{column.render('Header')}
{/* Add a sort direction indicator */}
<span>
{column.sorted ? (column.sortedDesc ? ' 🔽' : ' 🔼') : ''}
{column.isSorted
? column.isSortedDesc
? ' 🔽'
: ' 🔼'
: ''}
</span>
</th>
))}
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "react-table",
"version": "7.0.0-alpha.22",
"version": "7.0.0-alpha.26",
"description": "A fast, lightweight, opinionated table and datagrid built on React",
"license": "MIT",
"homepage": "https://github.com/tannerlinsley/react-table#readme",
@@ -80,6 +80,7 @@
"jest-watch-select-projects": "^0.1.2",
"jest-watch-typeahead": "^0.3.1",
"lint-staged": "^9.2.1",
"prettier": "^1.18.2",
"prop-types": "^15.5.0",
"react": "^16.9.0",
"react-dom": "^16.9.0",
+130 -143
View File
@@ -10,6 +10,7 @@ import {
makeHeaderGroups,
findMaxDepth,
flattenBy,
determineColumnVisibility,
} from '../utils'
import { useTableState } from './useTableState'
@@ -49,27 +50,24 @@ export const useTable = (props, ...plugins) => {
debug = process.env.NODE_ENV === 'production' ? false : debug
// Always provide a default state
// Always provide a default table state
const defaultState = useTableState()
// But use the users state if provided
// But use the users table state if provided
const state = userState || defaultState
// The initial api
// The table instance ref
let instanceRef = React.useRef({})
Object.assign(instanceRef.current, {
...props,
data,
state,
plugins,
data, // The raw data
state, // The resolved table state
plugins, // All resolved plugins
hooks: {
columnsBeforeHeaderGroups: [],
columnsBeforeHeaderGroupsDeps: [],
useMain: [],
useColumns: [],
useHeaders: [],
useHeaderGroups: [],
useRows: [],
prepareRow: [],
getTableProps: [],
@@ -82,61 +80,54 @@ export const useTable = (props, ...plugins) => {
// Allow plugins to register hooks
if (process.env.NODE_ENV === 'development' && debug) console.time('plugins')
plugins.filter(Boolean).forEach(plugin => {
plugin(instanceRef.current.hooks)
})
if (process.env.NODE_ENV === 'development' && debug)
console.timeEnd('plugins')
if (process.env.NODE_ENV === 'development' && debug)
console.info('buildColumns/headerGroup/headers')
// Decorate All the columns
let columnTree = React.useMemo(
let headers = React.useMemo(
() => decorateColumnTree(userColumns, defaultColumn),
[defaultColumn, userColumns]
)
// Get the flat list of all columns
let columns = React.useMemo(() => flattenBy(columnTree, 'columns'), [
columnTree,
])
let columns = React.useMemo(() => flattenBy(headers, 'columns'), [headers])
// Allow hooks to decorate columns (and trigger this memoization via deps)
columns = React.useMemo(
() => {
if (process.env.NODE_ENV === 'development' && debug)
console.time('hooks.columnsBeforeHeaderGroups')
const newColumns = applyHooks(
instanceRef.current.hooks.columnsBeforeHeaderGroups,
columns,
instanceRef.current
)
if (process.env.NODE_ENV === 'development' && debug)
console.timeEnd('hooks.columnsBeforeHeaderGroups')
return newColumns
},
[
columns = React.useMemo(() => {
if (process.env.NODE_ENV === 'development' && debug)
console.time('hooks.columnsBeforeHeaderGroups')
let newColumns = applyHooks(
instanceRef.current.hooks.columnsBeforeHeaderGroups,
columns,
debug,
// eslint-disable-next-line react-hooks/exhaustive-deps
...applyHooks(
instanceRef.current.hooks.columnsBeforeHeaderGroupsDeps,
[],
instanceRef.current
),
]
)
instanceRef.current
)
if (process.env.NODE_ENV === 'development' && debug)
console.timeEnd('hooks.columnsBeforeHeaderGroups')
return newColumns
}, [
columns,
debug,
// eslint-disable-next-line react-hooks/exhaustive-deps
...applyHooks(
instanceRef.current.hooks.columnsBeforeHeaderGroupsDeps,
[],
instanceRef.current
),
])
// Make the headerGroups
const headerGroups = React.useMemo(
() => makeHeaderGroups(columns, findMaxDepth(columnTree), defaultColumn),
[columnTree, columns, defaultColumn]
() => makeHeaderGroups(columns, findMaxDepth(headers), defaultColumn),
[columns, defaultColumn, headers]
)
const headers = React.useMemo(() => flattenBy(headerGroups, 'headers'), [
headerGroups,
])
Object.assign(instanceRef.current, {
columns,
headerGroups,
@@ -144,84 +135,82 @@ export const useTable = (props, ...plugins) => {
})
// Access the row model
const [rows, rowPaths, flatRows] = React.useMemo(
() => {
if (process.env.NODE_ENV === 'development' && debug)
console.time('getAccessedRows')
const [rows, rowPaths, flatRows] = React.useMemo(() => {
if (process.env.NODE_ENV === 'development' && debug)
console.time('getAccessedRows')
let flatRows = 0
const rowPaths = []
let flatRows = 0
const rowPaths = []
// Access the row's data
const accessRow = (originalRow, i, depth = 0, parentPath = []) => {
// Keep the original reference around
const original = originalRow
// Access the row's data
const accessRow = (originalRow, i, depth = 0, parentPath = []) => {
// Keep the original reference around
const original = originalRow
// Make the new path for the row
const path = [...parentPath, i]
// Make the new path for the row
const path = [...parentPath, i]
flatRows++
rowPaths.push(path.join('.'))
flatRows++
rowPaths.push(path.join('.'))
// Process any subRows
const subRows = originalRow[subRowsKey]
? originalRow[subRowsKey].map((d, i) =>
accessRow(d, i, depth + 1, path)
)
: []
const row = {
original,
index: i,
path, // used to create a key for each row even if not nested
subRows,
depth,
cells: [{}], // This is a dummy cell
}
// Override common array functions (and the dummy cell's getCellProps function)
// to show an error if it is accessed without calling prepareRow
const unpreparedAccessWarning = () => {
throw new Error(
'React-Table: You have not called prepareRow(row) one or more rows you are attempting to render.'
// Process any subRows
const subRows = originalRow[subRowsKey]
? originalRow[subRowsKey].map((d, i) =>
accessRow(d, i, depth + 1, path)
)
}
row.cells.map = unpreparedAccessWarning
row.cells.filter = unpreparedAccessWarning
row.cells.forEach = unpreparedAccessWarning
row.cells[0].getCellProps = unpreparedAccessWarning
: []
// Create the cells and values
row.values = {}
instanceRef.current.columns.forEach(column => {
row.values[column.id] = column.accessor
? column.accessor(originalRow, i, { subRows, depth, data })
: undefined
})
return row
const row = {
original,
index: i,
path, // used to create a key for each row even if not nested
subRows,
depth,
cells: [{}], // This is a dummy cell
}
// Use the resolved data
const accessedData = data.map((d, i) => accessRow(d, i))
if (process.env.NODE_ENV === 'development' && debug)
console.timeEnd('getAccessedRows')
return [accessedData, rowPaths, flatRows]
},
[debug, data, subRowsKey]
)
// Override common array functions (and the dummy cell's getCellProps function)
// to show an error if it is accessed without calling prepareRow
const unpreparedAccessWarning = () => {
throw new Error(
'React-Table: You have not called prepareRow(row) one or more rows you are attempting to render.'
)
}
row.cells.map = unpreparedAccessWarning
row.cells.filter = unpreparedAccessWarning
row.cells.forEach = unpreparedAccessWarning
row.cells[0].getCellProps = unpreparedAccessWarning
// Create the cells and values
row.values = {}
columns.forEach(column => {
row.values[column.id] = column.accessor
? column.accessor(originalRow, i, { subRows, depth, data })
: undefined
})
return row
}
// Use the resolved data
const accessedData = data.map((d, i) => accessRow(d, i))
if (process.env.NODE_ENV === 'development' && debug)
console.timeEnd('getAccessedRows')
return [accessedData, rowPaths, flatRows]
}, [debug, data, columns, subRowsKey])
instanceRef.current.rows = rows
instanceRef.current.rowPaths = rowPaths
instanceRef.current.flatRows = flatRows
// Determine column visibility
instanceRef.current.columns.forEach(column => {
column.visible =
typeof column.show === 'function'
? column.show(instanceRef.current)
: !!column.show
})
determineColumnVisibility(instanceRef.current)
// Provide a flat header list for utilities
instanceRef.current.flatHeaders = headerGroups.reduce(
(all, headerGroup) => [...all, ...headerGroup.headers],
[]
)
if (process.env.NODE_ENV === 'development' && debug)
console.time('hooks.useMain')
@@ -231,43 +220,42 @@ export const useTable = (props, ...plugins) => {
)
if (process.env.NODE_ENV === 'development' && debug)
console.timeEnd('hooks.useMain')
;[...instanceRef.current.columns, ...instanceRef.current.headers].forEach(
column => {
// Give columns/headers rendering power
column.render = (type, userProps = {}) => {
const Comp = typeof type === 'string' ? column[type] : type
if (typeof Comp === 'undefined') {
throw new Error(renderErr)
}
// Each materialized header needs to be assigned a render function and other
// prop getter properties here.
instanceRef.current.flatHeaders.forEach(column => {
// Give columns/headers rendering power
column.render = (type, userProps = {}) => {
const Comp = typeof type === 'string' ? column[type] : type
return flexRender(Comp, {
...instanceRef.current,
column,
...userProps,
})
if (typeof Comp === 'undefined') {
throw new Error(renderErr)
}
// Give columns/headers a default getHeaderProps
column.getHeaderProps = props =>
mergeProps(
{
key: ['header', column.id].join('_'),
colSpan: column.columns
? column.columns.filter(column => column.visible).length
: 1,
},
applyPropHooks(
instanceRef.current.hooks.getHeaderProps,
column,
instanceRef.current
),
props
)
return flexRender(Comp, {
...instanceRef.current,
column,
...userProps,
})
}
)
instanceRef.current.headerGroups.filter((headerGroup, i) => {
// Give columns/headers a default getHeaderProps
column.getHeaderProps = props =>
mergeProps(
{
key: ['header', column.id].join('_'),
colSpan: column.totalHeaderCount,
},
applyPropHooks(
instanceRef.current.hooks.getHeaderProps,
column,
instanceRef.current
),
props
)
})
instanceRef.current.headerGroups.forEach((headerGroup, i) => {
// Filter out any headers and headerGroups that don't have visible columns
headerGroup.headers = headerGroup.headers.filter(header => {
const recurse = columns =>
@@ -275,12 +263,12 @@ export const useTable = (props, ...plugins) => {
if (column.columns) {
return recurse(column.columns)
}
return column.visible
return column.isVisible
}).length
if (header.columns) {
return recurse(header.columns)
}
return header.visible
return header.isVisible
})
// Give headerGroups getRowProps
@@ -297,10 +285,9 @@ export const useTable = (props, ...plugins) => {
),
props
)
return true
}
return false
})
// Run the rows (this could be a dangerous hook with a ton of data)
@@ -330,7 +317,7 @@ export const useTable = (props, ...plugins) => {
)
const visibleColumns = instanceRef.current.columns.filter(
column => column.visible
column => column.isVisible
)
// Build the cells for each row
-2
View File
@@ -9,6 +9,4 @@ 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'
@@ -19,7 +19,7 @@ Snapshot Diff:
</pre>
<table
class=""
@@ -82,10 +84,53 @@
@@ -78,10 +80,53 @@
<td
class=""
>
@@ -73,7 +73,7 @@ Snapshot Diff:
</span>
</td>
<td
@@ -115,10 +160,139 @@
@@ -111,10 +156,139 @@
</td>
<td
class=""
@@ -235,7 +235,7 @@ Snapshot Diff:
</code>
</pre>
<table
@@ -127,10 +129,53 @@
@@ -123,10 +125,53 @@
<td
class=""
>
@@ -289,7 +289,7 @@ Snapshot Diff:
</span>
</td>
<td
@@ -160,10 +205,139 @@
@@ -156,10 +201,139 @@
</td>
<td
class=""
@@ -451,7 +451,7 @@ Snapshot Diff:
}
</code>
</pre>
@@ -172,10 +174,53 @@
@@ -168,10 +170,53 @@
<td
class=""
>
@@ -505,7 +505,7 @@ Snapshot Diff:
</span>
</td>
<td
@@ -205,10 +250,139 @@
@@ -201,10 +246,139 @@
</td>
<td
class=""
@@ -667,7 +667,7 @@ Snapshot Diff:
}
}
</code>
@@ -218,11 +220,11 @@
@@ -214,11 +216,11 @@
class=""
>
<span
@@ -680,7 +680,7 @@ Snapshot Diff:
<td
class=""
>
@@ -250,10 +252,30 @@
@@ -246,10 +248,30 @@
</td>
<td
class=""
@@ -1,11 +1,11 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`renders a table with seletable rows 1`] = `
exports[`renders a table with selectable rows 1`] = `
Snapshot Diff:
- First value
+ Second value
@@ -109,11 +109,11 @@
@@ -101,11 +101,11 @@
</td>
<td
class=""
@@ -18,7 +18,7 @@ Snapshot Diff:
<td
class=""
>
@@ -165,11 +165,11 @@
@@ -157,11 +157,11 @@
</td>
<td
class=""
@@ -31,7 +31,7 @@ Snapshot Diff:
<td
class=""
>
@@ -221,11 +221,11 @@
@@ -213,11 +213,11 @@
</td>
<td
class=""
@@ -44,7 +44,7 @@ Snapshot Diff:
<td
class=""
>
@@ -277,11 +277,11 @@
@@ -269,11 +269,11 @@
</td>
<td
class=""
@@ -57,7 +57,227 @@ Snapshot Diff:
<td
class=""
>
@@ -314,15 +314,20 @@
@@ -325,11 +325,11 @@
</td>
<td
class=""
>
<div>
- Not Selected
+ Selected
</div>
</td>
<td
class=""
>
@@ -381,11 +381,11 @@
</td>
<td
class=""
>
<div>
- Not Selected
+ Selected
</div>
</td>
<td
class=""
>
@@ -418,15 +418,22 @@
</td>
</tr>
</tbody>
</table>
<p>
- Selected Rows: 0
+ Selected Rows: 6
</p>
<pre>
<code>
{
- "selectedRows": []
+ "selectedRows": [
+ "0",
+ "1",
+ "2",
+ "2.0",
+ "2.1",
+ "3"
+ ]
}
</code>
</pre>
</DocumentFragment>
`;
exports[`renders a table with selectable rows 2`] = `
Snapshot Diff:
- First value
+ Second value
@@ -101,11 +101,11 @@
</td>
<td
class=""
>
<div>
- Selected
+ Not Selected
</div>
</td>
<td
class=""
>
@@ -157,11 +157,11 @@
</td>
<td
class=""
>
<div>
- Selected
+ Not Selected
</div>
</td>
<td
class=""
>
@@ -213,11 +213,11 @@
</td>
<td
class=""
>
<div>
- Selected
+ Not Selected
</div>
</td>
<td
class=""
>
@@ -269,11 +269,11 @@
</td>
<td
class=""
>
<div>
- Selected
+ Not Selected
</div>
</td>
<td
class=""
>
@@ -325,11 +325,11 @@
</td>
<td
class=""
>
<div>
- Selected
+ Not Selected
</div>
</td>
<td
class=""
>
@@ -381,11 +381,11 @@
</td>
<td
class=""
>
<div>
- Selected
+ Not Selected
</div>
</td>
<td
class=""
>
@@ -418,22 +418,15 @@
</td>
</tr>
</tbody>
</table>
<p>
- Selected Rows: 6
+ Selected Rows: 0
</p>
<pre>
<code>
{
- "selectedRows": [
- "0",
- "1",
- "2",
- "2.0",
- "2.1",
- "3"
- ]
+ "selectedRows": []
}
</code>
</pre>
</DocumentFragment>
`;
exports[`renders a table with selectable rows 3`] = `
Snapshot Diff:
- First value
+ Second value
@@ -101,11 +101,11 @@
</td>
<td
class=""
>
<div>
- Not Selected
+ Selected
</div>
</td>
<td
class=""
>
@@ -213,11 +213,11 @@
</td>
<td
class=""
>
<div>
- Not Selected
+ Selected
</div>
</td>
<td
class=""
>
@@ -269,11 +269,11 @@
</td>
<td
class=""
>
<div>
- Not Selected
+ Selected
</div>
</td>
<td
class=""
>
@@ -325,11 +325,11 @@
</td>
<td
class=""
>
<div>
- Not Selected
+ Selected
</div>
</td>
<td
class=""
>
@@ -418,15 +418,20 @@
</td>
</tr>
</tbody>
@@ -72,9 +292,9 @@ Snapshot Diff:
- "selectedRows": []
+ "selectedRows": [
+ "0",
+ "1",
+ "2",
+ "3"
+ "2.0",
+ "2.1"
+ ]
}
</code>
@@ -82,12 +302,12 @@ Snapshot Diff:
</DocumentFragment>
`;
exports[`renders a table with seletable rows 2`] = `
exports[`renders a table with selectable rows 4`] = `
Snapshot Diff:
- First value
+ Second value
@@ -109,11 +109,11 @@
@@ -213,11 +213,11 @@
</td>
<td
class=""
@@ -100,7 +320,7 @@ Snapshot Diff:
<td
class=""
>
@@ -165,11 +165,11 @@
@@ -269,11 +269,11 @@
</td>
<td
class=""
@@ -113,7 +333,7 @@ Snapshot Diff:
<td
class=""
>
@@ -221,11 +221,11 @@
@@ -325,11 +325,11 @@
</td>
<td
class=""
@@ -126,50 +346,37 @@ Snapshot Diff:
<td
class=""
>
@@ -277,11 +277,11 @@
</td>
<td
class=""
>
<div>
- Selected
+ Not Selected
</div>
</td>
<td
class=""
>
@@ -314,20 +314,15 @@
@@ -418,20 +418,17 @@
</td>
</tr>
</tbody>
</table>
<p>
- Selected Rows: 4
+ Selected Rows: 0
+ Selected Rows: 1
</p>
<pre>
<code>
{
- "selectedRows": [
"selectedRows": [
- "0",
- "1",
- "2",
- "3"
- ]
+ "selectedRows": []
- "2.0",
- "2.1"
+ "0"
]
}
</code>
</pre>
</DocumentFragment>
`;
exports[`renders a table with seletable rows 3`] = `
exports[`renders a table with selectable rows 5`] = `
Snapshot Diff:
- First value
+ Second value
@@ -109,11 +109,11 @@
@@ -269,11 +269,11 @@
</td>
<td
class=""
@@ -182,36 +389,135 @@ Snapshot Diff:
<td
class=""
>
@@ -221,11 +221,11 @@
</td>
<td
class=""
>
<div>
- Not Selected
+ Selected
</div>
</td>
<td
class=""
>
@@ -314,15 +314,18 @@
@@ -418,17 +418,18 @@
</td>
</tr>
</tbody>
</table>
<p>
- Selected Rows: 0
- Selected Rows: 1
+ Selected Rows: 2
</p>
<pre>
<code>
{
- "selectedRows": []
+ "selectedRows": [
"selectedRows": [
- "0"
+ "0",
+ "2.0"
]
}
</code>
</pre>
</DocumentFragment>
`;
exports[`renders a table with selectable rows 6`] = `
Snapshot Diff:
- First value
+ Second value
@@ -213,11 +213,11 @@
</td>
<td
class=""
>
<div>
- Not Selected
+ Selected
</div>
</td>
<td
class=""
>
@@ -325,11 +325,11 @@
</td>
<td
class=""
>
<div>
- Not Selected
+ Selected
</div>
</td>
<td
class=""
>
@@ -418,18 +418,20 @@
</td>
</tr>
</tbody>
</table>
<p>
- Selected Rows: 2
+ Selected Rows: 4
</p>
<pre>
<code>
{
"selectedRows": [
"0",
- "2.0"
+ "2.0",
+ "2.1",
+ "2"
+ ]
]
}
</code>
</pre>
</DocumentFragment>
`;
exports[`renders a table with selectable rows 7`] = `
Snapshot Diff:
- First value
+ Second value
@@ -213,11 +213,11 @@
</td>
<td
class=""
>
<div>
- Selected
+ Not Selected
</div>
</td>
<td
class=""
>
@@ -325,11 +325,11 @@
</td>
<td
class=""
>
<div>
- Selected
+ Not Selected
</div>
</td>
<td
class=""
>
@@ -418,20 +418,18 @@
</td>
</tr>
</tbody>
</table>
<p>
- Selected Rows: 4
+ Selected Rows: 2
</p>
<pre>
<code>
{
"selectedRows": [
"0",
- "2.0",
- "2.1",
- "2"
+ "2.0"
]
}
</code>
</pre>
+4 -4
View File
@@ -73,7 +73,7 @@ function Table({ columns, data }) {
{column.canGroupBy ? (
// If the column can be grouped, let's add a toggle
<span {...column.getGroupByToggleProps()}>
{column.grouped ? '🛑' : '👊'}
{column.isGrouped ? '🛑' : '👊'}
</span>
) : null}
{column.render('Header')}
@@ -90,7 +90,7 @@ function Table({ columns, data }) {
{row.cells.map(cell => {
return (
<td {...cell.getCellProps()}>
{cell.grouped ? (
{cell.isGrouped ? (
<>
<span
style={{
@@ -102,9 +102,9 @@ function Table({ columns, data }) {
</span>
{cell.render('Cell')} ({row.subRows.length})
</>
) : cell.aggregated ? (
) : cell.isAggregated ? (
cell.render('Aggregated')
) : cell.repeatedValue ? null : (
) : cell.isRepeatedValue ? null : (
cell.render('Cell')
)}
</td>
+44 -3
View File
@@ -2,6 +2,7 @@ import React from 'react'
import { render, fireEvent } from '@testing-library/react'
import { useTable } from '../../hooks/useTable'
import { useRowSelect } from '../useRowSelect'
import { useExpanded } from '../useExpanded'
const data = [
{
@@ -27,6 +28,25 @@ const data = [
visits: 20,
status: 'Complicated',
progress: 10,
expanded: true,
subRows: [
{
firstName: 'bob',
lastName: 'ross',
age: 52,
visits: 40,
status: 'In Relationship',
progress: 30,
},
{
firstName: 'john',
lastName: 'smith',
age: 21,
visits: 30,
status: 'Single',
progress: 60,
},
],
},
{
firstName: 'jaylen',
@@ -51,7 +71,8 @@ function Table({ columns, data }) {
columns,
data,
},
useRowSelect
useRowSelect,
useExpanded
)
// Render the UI for your table
@@ -120,7 +141,7 @@ function App() {
{
id: 'selectedStatus',
Cell: ({ row }) => (
<div>{row.selected ? 'Selected' : 'Not Selected'}</div>
<div>{row.isSelected ? 'Selected' : 'Not Selected'}</div>
),
},
{
@@ -164,7 +185,7 @@ function App() {
return <Table columns={columns} data={data} />
}
test('renders a table with seletable rows', () => {
test('renders a table with selectable rows', () => {
const { getByLabelText, getAllByLabelText, asFragment } = render(<App />)
const fragment1 = asFragment()
@@ -182,7 +203,27 @@ test('renders a table with seletable rows', () => {
const fragment4 = asFragment()
fireEvent.click(getAllByLabelText('Select Row')[2])
const fragment5 = asFragment()
fireEvent.click(getAllByLabelText('Select Row')[3])
const fragment6 = asFragment()
fireEvent.click(getAllByLabelText('Select Row')[4])
const fragment7 = asFragment()
fireEvent.click(getAllByLabelText('Select Row')[4])
const fragment8 = asFragment()
expect(fragment1).toMatchDiffSnapshot(fragment2)
expect(fragment2).toMatchDiffSnapshot(fragment3)
expect(fragment3).toMatchDiffSnapshot(fragment4)
expect(fragment4).toMatchDiffSnapshot(fragment5)
expect(fragment5).toMatchDiffSnapshot(fragment6)
expect(fragment6).toMatchDiffSnapshot(fragment7)
expect(fragment7).toMatchDiffSnapshot(fragment8)
})
+1 -1
View File
@@ -56,7 +56,7 @@ function Table({ columns, data }) {
{column.render('Header')}
{/* Add a sort direction indicator */}
<span>
{column.sorted ? (column.sortedDesc ? ' 🔽' : ' 🔼') : ''}
{column.isSorted ? (column.isSortedDesc ? ' 🔽' : ' 🔼') : ''}
</span>
</th>
))}
+11 -8
View File
@@ -17,7 +17,7 @@ addActions('toggleExpanded', 'useExpanded')
const propTypes = {
manualExpandedKey: PropTypes.string,
nestExpandedRows: PropTypes.bool,
paginateExpandedRows: PropTypes.bool,
}
export const useExpanded = hooks => {
@@ -34,16 +34,16 @@ function useMain(instance) {
debug,
rows,
manualExpandedKey = 'expanded',
paginateExpandedRows = true,
hooks,
state: [{ expanded }, setState],
nestExpandedRows,
} = instance
const toggleExpandedByPath = (path, set) => {
return setState(old => {
const { expanded } = old
const existing = getBy(expanded, path)
set = getFirstDefined(set, !existing)
set = getFirstDefined(set, existing ? undefined : true)
return {
...old,
expanded: setBy(expanded, path, set),
@@ -85,13 +85,16 @@ function useMain(instance) {
(row.original && row.original[manualExpandedKey]) ||
getBy(expanded, row.path)
if (!nestExpandedRows || (nestExpandedRows && row.depth === 0)) {
expandedRows.push(row)
}
expandedRows.push(row)
row.canExpand = row.subRows && !!row.subRows.length
if (row.isExpanded && row.subRows && row.subRows.length) {
if (
paginateExpandedRows &&
row.isExpanded &&
row.subRows &&
row.subRows.length
) {
row.subRows.forEach(handleRow)
}
@@ -101,7 +104,7 @@ function useMain(instance) {
rows.forEach(handleRow)
return expandedRows
}, [debug, rows, manualExpandedKey, expanded, nestExpandedRows])
}, [debug, rows, manualExpandedKey, expanded, paginateExpandedRows])
const expandedDepth = findExpandedDepth(expanded)
+67 -72
View File
@@ -129,92 +129,87 @@ function useMain(instance) {
// cache for each row group (top-level rows, and each row's recursive subrows)
// This would make multi-filtering a lot faster though. Too far?
const filteredRows = React.useMemo(
() => {
if (manualFilters || !Object.keys(filters).length) {
return rows
}
const filteredRows = React.useMemo(() => {
if (manualFilters || !Object.keys(filters).length) {
return rows
}
if (process.env.NODE_ENV === 'development' && debug)
console.info('getFilteredRows')
if (process.env.NODE_ENV === 'development' && debug)
console.info('getFilteredRows')
// Filters top level and nested rows
const filterRows = (rows, depth = 0) => {
let filteredRows = rows
// Filters top level and nested rows
const filterRows = (rows, depth = 0) => {
let filteredRows = rows
filteredRows = Object.entries(filters).reduce(
(filteredSoFar, [columnID, filterValue]) => {
// Find the filters column
const column = columns.find(d => d.id === columnID)
filteredRows = Object.entries(filters).reduce(
(filteredSoFar, [columnID, filterValue]) => {
// Find the filters column
const column = columns.find(d => d.id === columnID)
if (depth === 0) {
column.preFilteredRows = filteredSoFar
}
if (!column) {
return filteredSoFar
}
if (!column) {
return filteredSoFar
}
if (depth === 0) {
column.preFilteredRows = filteredSoFar
}
const filterMethod = getFilterMethod(
column.filter,
userFilterTypes || {},
filterTypes
const filterMethod = getFilterMethod(
column.filter,
userFilterTypes || {},
filterTypes
)
if (!filterMethod) {
console.warn(
`Could not find a valid 'column.filter' for column with the ID: ${column.id}.`
)
if (!filterMethod) {
console.warn(
`Could not find a valid 'column.filter' for column with the ID: ${
column.id
}.`
)
return filteredSoFar
}
// Pass the rows, id, filterValue and column to the filterMethod
// to get the filtered rows back
return filterMethod(filteredSoFar, columnID, filterValue, column)
},
rows
)
// Apply the filter to any subRows
// We technically could do this recursively in the above loop,
// but that would severely hinder the API for the user, since they
// would be required to do that recursion in some scenarios
filteredRows = filteredRows.map(row => {
if (!row.subRows) {
return row
return filteredSoFar
}
return {
...row,
subRows:
row.subRows && row.subRows.length > 0
? filterRows(row.subRows, depth + 1)
: row.subRows,
}
})
return filteredRows
}
const filteredRows = filterRows(rows)
// Now that each filtered column has it's partially filtered rows,
// lets assign the final filtered rows to all of the other columns
const nonFilteredColumns = columns.filter(
column => !Object.keys(filters).includes(column.id)
// Pass the rows, id, filterValue and column to the filterMethod
// to get the filtered rows back
return filterMethod(filteredSoFar, columnID, filterValue, column)
},
rows
)
// This essentially enables faceted filter options to be built easily
// using every column's preFilteredRows value
nonFilteredColumns.forEach(column => {
column.preFilteredRows = filteredRows
// Apply the filter to any subRows
// We technically could do this recursively in the above loop,
// but that would severely hinder the API for the user, since they
// would be required to do that recursion in some scenarios
filteredRows = filteredRows.map(row => {
if (!row.subRows) {
return row
}
return {
...row,
subRows:
row.subRows && row.subRows.length > 0
? filterRows(row.subRows, depth + 1)
: row.subRows,
}
})
return filteredRows
},
[manualFilters, filters, debug, rows, columns, userFilterTypes]
)
}
return filterRows(rows)
}, [manualFilters, filters, debug, rows, columns, userFilterTypes])
React.useMemo(() => {
// Now that each filtered column has it's partially filtered rows,
// lets assign the final filtered rows to all of the other columns
const nonFilteredColumns = columns.filter(
column => !Object.keys(filters).includes(column.id)
)
// This essentially enables faceted filter options to be built easily
// using every column's preFilteredRows value
nonFilteredColumns.forEach(column => {
column.preFilteredRows = filteredRows
})
}, [columns, filteredRows, filters])
return {
...instance,
-144
View File
@@ -1,144 +0,0 @@
import PropTypes from 'prop-types'
import { getFirstDefined, sum } from '../utils'
export const actions = {}
const propTypes = {
defaultFlex: PropTypes.number,
}
export const useFlexLayout = hooks => {
hooks.useMain.push(useMain)
}
function useMain(instance) {
PropTypes.checkPropTypes(propTypes, instance, 'property', 'useFlexLayout')
const {
defaultFlex = 1,
hooks: {
columns: columnsHooks,
getRowProps,
getHeaderGroupProps,
getHeaderProps,
getCellProps,
},
} = instance
columnsHooks.push((columns, api) => {
const visibleColumns = columns.filter(column => column.visible)
const columnMeasurements = {}
let sumWidth = 0
visibleColumns.forEach(column => {
const { width, minWidth } = getSizesForColumn(
column,
defaultFlex,
undefined,
undefined,
api
)
if (width) {
sumWidth += width
} else if (minWidth) {
sumWidth += minWidth
} else {
sumWidth += defaultFlex
}
})
const rowStyles = {
style: {
display: 'flex',
minWidth: `${sumWidth}px`,
},
}
api.rowStyles = rowStyles
getRowProps.push(() => rowStyles)
getHeaderGroupProps.push(() => rowStyles)
getHeaderProps.push(column => ({
style: {
boxSizing: 'border-box',
...getStylesForColumn(column, columnMeasurements, defaultFlex, api),
},
}))
getCellProps.push(cell => {
return {
style: {
...getStylesForColumn(
cell.column,
columnMeasurements,
defaultFlex,
undefined,
api
),
},
}
})
return columns
})
return instance
}
// Utils
function getStylesForColumn(column, columnMeasurements, defaultFlex, api) {
const { flex, width, maxWidth } = getSizesForColumn(
column,
columnMeasurements,
defaultFlex,
api
)
return {
flex: `${flex} 0 auto`,
width: `${width}px`,
maxWidth: `${maxWidth}px`,
}
}
function getSizesForColumn(
{ columns, id, width, minWidth, maxWidth },
columnMeasurements,
defaultFlex,
api
) {
if (columns) {
columns = columns
.filter(col => col.show || col.visible)
.map(column =>
getSizesForColumn(column, columnMeasurements, defaultFlex, api)
)
.filter(Boolean)
if (!columns.length) {
return false
}
const flex = sum(columns.map(col => col.flex))
const width = sum(columns.map(col => col.width))
const maxWidth = sum(columns.map(col => col.maxWidth))
return {
flex,
width,
maxWidth,
}
}
return {
flex: width ? 0 : defaultFlex,
width:
width === 'auto'
? columnMeasurements[id] || defaultFlex
: getFirstDefined(width, minWidth, defaultFlex),
maxWidth,
}
}
+22 -7
View File
@@ -9,6 +9,7 @@ import {
applyPropHooks,
defaultGroupByFn,
getFirstDefined,
ensurePluginOrder,
} from '../utils'
defaultState.groupBy = []
@@ -50,9 +51,18 @@ useGroupBy.pluginName = 'useGroupBy'
function columnsBeforeHeaderGroups(columns, { state: [{ groupBy }] }) {
// Sort grouped columns to the start of the column list
// before the headers are built
const groupByColumns = groupBy.map(g => columns.find(col => col.id === g))
const nonGroupByColumns = columns.filter(col => !groupBy.includes(col.id))
// If a groupByBoundary column is found, place the groupBy's after it
const groupByBoundaryColumnIndex =
columns.findIndex(column => column.groupByBoundary) + 1
return [
...groupBy.map(g => columns.find(col => col.id === g)),
...columns.filter(col => !groupBy.includes(col.id)),
...nonGroupByColumns.slice(0, groupByBoundaryColumnIndex),
...groupByColumns,
...nonGroupByColumns.slice(groupByBoundaryColumnIndex),
]
}
@@ -69,12 +79,15 @@ function useMain(instance) {
disableGrouping,
aggregations: userAggregations = {},
hooks,
plugins,
state: [{ groupBy }, setState],
} = instance
ensurePluginOrder(plugins, [], 'useGroupBy', ['useExpanded'])
columns.forEach(column => {
const { id, accessor, disableGrouping: columnDisableGrouping } = column
column.grouped = groupBy.includes(id)
column.isGrouped = groupBy.includes(id)
column.groupedIndex = groupBy.indexOf(id)
column.canGroupBy = accessor
@@ -137,11 +150,12 @@ function useMain(instance) {
hooks.prepareRow.push(row => {
row.cells.forEach(cell => {
// Grouped cells are in the groupBy and the pivot cell for the row
cell.grouped = cell.column.grouped && cell.column.id === row.groupByID
cell.isGrouped = cell.column.isGrouped && cell.column.id === row.groupByID
// Repeated cells are any columns in the groupBy that are not grouped
cell.repeatedValue = !cell.grouped && cell.column.grouped
cell.isRepeatedValue = !cell.isGrouped && cell.column.isGrouped
// Aggregated cells are not grouped, not repeated, but still have subRows
cell.aggregated = !cell.grouped && !cell.repeatedValue && row.canExpand
cell.isAggregated =
!cell.isGrouped && !cell.isRepeatedValue && row.canExpand
})
return row
})
@@ -218,7 +232,7 @@ function useMain(instance) {
// Recurse to sub rows before aggregation
groupedRows = Object.entries(groupedRows).map(
([groupByVal, subRows], index) => {
const path = [...parentPath, groupByVal]
const path = [...parentPath, `${columnID}:${groupByVal}`]
subRows = groupRecursively(subRows, depth + 1, path)
@@ -228,6 +242,7 @@ function useMain(instance) {
)
const row = {
isAggregated: true,
groupByID: columnID,
groupByVal,
values,
+54 -45
View File
@@ -14,6 +14,7 @@ addActions('pageChange', 'pageSizeChange')
const propTypes = {
// General
manualPagination: PropTypes.bool,
paginateExpandedRows: PropTypes.bool,
}
// SSR has issues with useLayoutEffect still, so use useEffect during SSR
@@ -32,75 +33,84 @@ function useMain(instance) {
PropTypes.checkPropTypes(propTypes, instance, 'property', 'usePagination')
const {
data,
rows,
manualPagination,
disablePageResetOnDataChange,
debug,
plugins,
pageCount: userPageCount,
paginateExpandedRows = true,
state: [{ pageSize, pageIndex, filters, groupBy, sortBy }, setState],
} = instance
ensurePluginOrder(
plugins,
['useFilters', 'useGroupBy', 'useSortBy'],
['useFilters', 'useGroupBy', 'useSortBy', 'useExpanded'],
'usePagination',
[]
)
const rowDep = manualPagination || disablePageResetOnDataChange ? null : rows
const rowDep = manualPagination ? null : data
const isPageIndexMountedRef = React.useRef()
useLayoutEffect(
() => {
if (isPageIndexMountedRef.current) {
setState(
old => ({
...old,
pageIndex: 0,
}),
actions.pageChange
)
}
isPageIndexMountedRef.current = true
},
[setState, rowDep, filters, groupBy, sortBy]
)
useLayoutEffect(() => {
if (isPageIndexMountedRef.current && !disablePageResetOnDataChange) {
setState(
old => ({
...old,
pageIndex: 0,
}),
actions.pageChange
)
}
isPageIndexMountedRef.current = true
}, [setState, rowDep, filters, groupBy, sortBy, disablePageResetOnDataChange])
const pages = React.useMemo(
() => {
if (manualPagination) {
return undefined
}
if (process.env.NODE_ENV === 'development' && debug)
console.info('getPages')
// Create a new pages with the first page ready to go.
const pages = rows.length ? [] : [[]]
// Start the pageIndex and currentPage cursors
let cursor = 0
while (cursor < rows.length) {
const end = cursor + pageSize
pages.push(rows.slice(cursor, end))
cursor = end
}
return pages
},
[debug, manualPagination, pageSize, rows]
)
const pageCount = manualPagination ? userPageCount : pages.length
const pageCount = manualPagination
? userPageCount
: Math.ceil(rows.length / pageSize)
const pageOptions = React.useMemo(
() => (pageCount > 0 ? [...new Array(pageCount)].map((d, i) => i) : []),
[pageCount]
)
const page = manualPagination ? rows : pages[pageIndex]
const page = React.useMemo(() => {
let page
if (manualPagination) {
page = rows
} else {
if (process.env.NODE_ENV === 'development' && debug)
console.info('getPage')
const pageStart = pageSize * pageIndex
const pageEnd = pageStart + pageSize
page = rows.slice(pageStart, pageEnd)
}
if (paginateExpandedRows) {
return page
}
const expandedPage = []
const handleRow = row => {
expandedPage.push(row)
if (row.subRows && row.subRows.length && row.isExpanded) {
row.subRows.forEach(handleRow)
}
}
page.forEach(handleRow)
return expandedPage
}, [debug, manualPagination, pageIndex, pageSize, paginateExpandedRows, rows])
const canPreviousPage = pageIndex > 0
const canNextPage = pageCount === -1 || pageIndex < pageCount - 1
@@ -140,7 +150,6 @@ function useMain(instance) {
return {
...instance,
pages,
pageOptions,
pageCount,
page,
+77 -12
View File
@@ -25,7 +25,7 @@ function useMain(instance) {
const {
hooks,
manualRowSelectedKey = 'selected',
manualRowSelectedKey = 'isSelected',
plugins,
rowPaths,
state: [{ selectedRows }, setState],
@@ -38,11 +38,11 @@ function useMain(instance) {
[]
)
const allRowsSelected = rowPaths.length === selectedRows.length
const isAllRowsSelected = rowPaths.length === selectedRows.length
const toggleRowSelectedAll = set => {
setState(old => {
const selectAll = typeof set !== 'undefined' ? set : !allRowsSelected
const selectAll = typeof set !== 'undefined' ? set : !isAllRowsSelected
return {
...old,
selectedRows: selectAll ? [...rowPaths] : [],
@@ -50,6 +50,24 @@ function useMain(instance) {
}, actions.toggleRowSelectedAll)
}
const updateParentRow = (selectedRows, path) => {
const parentPath = path.slice(0, path.length - 1)
const parentKey = parentPath.join('.')
const selected =
rowPaths.filter(
path =>
path !== parentKey &&
path.startsWith(parentKey) &&
!selectedRows.has(path)
).length === 0
if (selected) {
selectedRows.add(parentKey)
} else {
selectedRows.delete(parentKey)
}
if (parentPath.length > 1) updateParentRow(selectedRows, parentPath)
}
const toggleRowSelected = (path, set) => {
const key = path.join('.')
@@ -59,16 +77,24 @@ function useMain(instance) {
// in a flat object
const exists = old.selectedRows.includes(key)
const shouldExist = typeof set !== 'undefined' ? set : !exists
let newSelectedRows = new Set(selectedRows)
let newSelectedRows = new Set(old.selectedRows)
if (!exists && shouldExist) {
newSelectedRows.add(key)
rowPaths.forEach(rowPath => {
if (rowPath.startsWith(key)) newSelectedRows.add(rowPath)
})
} else if (exists && !shouldExist) {
newSelectedRows.delete(key)
rowPaths.forEach(rowPath => {
if (rowPath.startsWith(key)) newSelectedRows.delete(rowPath)
})
} else {
return old
}
// If the row is a subRow update
// its parent row to reflect changes
if (path.length > 1) updateParentRow(newSelectedRows, path)
return {
...old,
selectedRows: [...newSelectedRows.values()],
@@ -85,7 +111,7 @@ function useMain(instance) {
style: {
cursor: 'pointer',
},
checked: allRowsSelected,
checked: isAllRowsSelected,
title: 'Toggle All Rows Selected',
},
applyPropHooks(instance.hooks.getToggleAllRowsSelectedProps, instance),
@@ -94,10 +120,49 @@ function useMain(instance) {
}
hooks.prepareRow.push(row => {
row.canSelect = !!row.original
// Aggregate rows have entirely different select logic
if (row.isAggregated) {
const subRowPaths = row.subRows.map(row => row.path)
row.isSelected = subRowPaths.every(path =>
selectedRows.includes(path.join('.'))
)
row.toggleRowSelected = set => {
set = typeof set !== 'undefined' ? set : !row.isSelected
console.log(subRowPaths)
subRowPaths.forEach(path => {
toggleRowSelected(path, set)
})
}
row.getToggleRowSelectedProps = props => {
let checked = false
if (row.canSelect) {
row.selected = selectedRows.includes(row.path.join('.'))
if (row.original && row.original[manualRowSelectedKey]) {
checked = true
} else {
checked = row.isSelected
}
return mergeProps(
{
onChange: e => {
row.toggleRowSelected(e.target.checked)
},
style: {
cursor: 'pointer',
},
checked,
title: 'Toggle Row Selected',
},
applyPropHooks(
instance.hooks.getToggleRowSelectedProps,
row,
instance
),
props
)
}
} else {
row.isSelected = selectedRows.includes(row.path.join('.'))
row.toggleRowSelected = set => toggleRowSelected(row.path, set)
row.getToggleRowSelectedProps = props => {
let checked = false
@@ -105,7 +170,7 @@ function useMain(instance) {
if (row.original && row.original[manualRowSelectedKey]) {
checked = true
} else {
checked = selectedRows.includes(row.path.join('.'))
checked = row.isSelected
}
return mergeProps(
@@ -137,6 +202,6 @@ function useMain(instance) {
toggleRowSelected,
toggleRowSelectedAll,
getToggleAllRowsSelectedProps,
allRowsSelected,
isAllRowsSelected,
}
}
+11 -14
View File
@@ -72,21 +72,18 @@ function useMain(instance) {
const rowsMountedRef = React.useRef()
// When data changes, reset row and cell state
React.useEffect(
() => {
if (rowsMountedRef.current) {
setState(old => {
return {
...old,
rowState: {},
}
}, actions.setRowState)
}
React.useEffect(() => {
if (rowsMountedRef.current) {
setState(old => {
return {
...old,
rowState: {},
}
}, actions.setRowState)
}
rowsMountedRef.current = true
},
[rows, setState]
)
rowsMountedRef.current = true
}, [rows, setState])
hooks.prepareRow.push(row => {
const pathKey = row.path.join('.')
+74 -62
View File
@@ -59,12 +59,13 @@ function useMain(instance) {
disableMultiSort,
isMultiSortEvent = e => e.shiftKey,
maxMultiSortColCount = Number.MAX_SAFE_INTEGER,
flatHeaders,
hooks,
state: [{ sortBy }, setState],
plugins,
} = instance
ensurePluginOrder(plugins, [], 'useSortBy', ['useFilters'])
ensurePluginOrder(plugins, ['useFilters'], 'useSortBy', [])
// Add custom hooks
hooks.getSortByToggleProps = []
@@ -157,7 +158,7 @@ function useMain(instance) {
}
// Add the getSortByToggleProps method to columns and headers
;[...instance.columns, ...instance.headers].forEach(column => {
flatHeaders.forEach(column => {
const { accessor, disableSorting: columnDisableSorting, id } = column
const canSort = accessor
@@ -197,77 +198,88 @@ function useMain(instance) {
)
}
column.sorted = sortBy.find(d => d.id === id)
const columnSort = sortBy.find(d => d.id === id)
column.isSorted = !!columnSort
column.sortedIndex = sortBy.findIndex(d => d.id === id)
column.sortedDesc = column.sorted ? column.sorted.desc : undefined
column.isSortedDesc = column.isSorted ? columnSort.desc : undefined
})
const sortedRows = React.useMemo(
() => {
if (manualSorting || !sortBy.length) {
return rows
}
if (process.env.NODE_ENV === 'development' && debug)
console.time('getSortedRows')
const sortedRows = React.useMemo(() => {
if (manualSorting || !sortBy.length) {
return rows
}
if (process.env.NODE_ENV === 'development' && debug)
console.time('getSortedRows')
const sortData = rows => {
// Use the orderByFn to compose multiple sortBy's together.
// This will also perform a stable sorting using the row index
// if needed.
const sortedData = orderByFn(
rows,
sortBy.map(sort => {
// Support custom sorting methods for each column
const { sortType } = columns.find(d => d.id === sort.id)
// Filter out sortBys that correspond to non existing columns
const availableSortBy = sortBy.filter(sort =>
columns.find(col => col.id === sort.id)
)
// Look up sortBy functions in this order:
// column function
// column string lookup on user sortType
// column string lookup on built-in sortType
// default function
// default string lookup on user sortType
// default string lookup on built-in sortType
const sortMethod =
isFunction(sortType) ||
(userSortTypes || {})[sortType] ||
sortTypes[sortType] ||
sortTypes.alphanumeric
const sortData = rows => {
// Use the orderByFn to compose multiple sortBy's together.
// This will also perform a stable sorting using the row index
// if needed.
const sortedData = orderByFn(
rows,
availableSortBy.map(sort => {
// Support custom sorting methods for each column
const column = columns.find(d => d.id === sort.id)
// Return the correct sortFn
return (a, b) =>
sortMethod(a.values[sort.id], b.values[sort.id], sort.desc)
}),
// Map the directions
sortBy.map(sort => {
// Detect and use the sortInverted option
const { sortInverted } = columns.find(d => d.id === sort.id)
if (sortInverted) {
return sort.desc
}
return !sort.desc
})
)
// If there are sub-rows, sort them
sortedData.forEach(row => {
if (!row.subRows || row.subRows.length <= 1) {
return
if (!column) {
throw new Error(
`React-Table: Could not find a column with id: ${sort.id} while sorting`
)
}
row.subRows = sortData(row.subRows)
const { sortType } = column
// Look up sortBy functions in this order:
// column function
// column string lookup on user sortType
// column string lookup on built-in sortType
// default function
// default string lookup on user sortType
// default string lookup on built-in sortType
const sortMethod =
isFunction(sortType) ||
(userSortTypes || {})[sortType] ||
sortTypes[sortType] ||
sortTypes.alphanumeric
// Return the correct sortFn.
// This function should always return in ascending order
return (a, b) => sortMethod(a, b, sort.id)
}),
// Map the directions
availableSortBy.map(sort => {
// Detect and use the sortInverted option
const column = columns.find(d => d.id === sort.id)
if (column && column.sortInverted) {
return sort.desc
}
return !sort.desc
})
)
return sortedData
}
// If there are sub-rows, sort them
sortedData.forEach(row => {
if (!row.subRows || row.subRows.length <= 1) {
return
}
row.subRows = sortData(row.subRows)
})
if (process.env.NODE_ENV === 'development' && debug)
console.timeEnd('getSortedRows')
return sortedData
}
return sortData(rows)
},
[manualSorting, sortBy, debug, columns, rows, orderByFn, userSortTypes]
)
if (process.env.NODE_ENV === 'development' && debug)
console.timeEnd('getSortedRows')
return sortData(rows)
}, [manualSorting, sortBy, debug, columns, rows, orderByFn, userSortTypes])
return {
...instance,
+22 -5
View File
@@ -3,7 +3,9 @@ const reSplitAlphaNumeric = /([0-9]+)/gm
// Mixed sorting is slow, but very inclusive of many edge cases.
// It handles numbers, mixed alphanumeric combinations, and even
// null, undefined, and Infinity
export const alphanumeric = (a, b) => {
export const alphanumeric = (rowA, rowB, columnID) => {
let a = getRowValueByColumnID(rowA, columnID)
let b = getRowValueByColumnID(rowB, columnID)
// Force to strings (or "" for unsupported types)
a = toString(a)
b = toString(b)
@@ -51,18 +53,33 @@ export const alphanumeric = (a, b) => {
return a.length - b.length
}
export function datetime(a, b) {
export function datetime(rowA, rowB, columnID) {
let a = getRowValueByColumnID(rowA, columnID)
let b = getRowValueByColumnID(rowB, columnID)
a = a.getTime()
b = b.getTime()
return numeric(a, b)
return compareBasic(a, b)
}
export function numeric(a, b) {
return a === b ? 0 : a > b ? 1 : -1
export function basic(rowA, rowB, columnID) {
let a = getRowValueByColumnID(rowA, columnID)
let b = getRowValueByColumnID(rowB, columnID)
return compareBasic(a, b)
}
// Utils
function compareBasic(a, b) {
return a === b ? 0 : a > b ? 1 : -1
}
function getRowValueByColumnID(row, columnID) {
return row.values[columnID]
}
function toString(a) {
if (typeof a === 'number') {
if (isNaN(a) || a === Infinity || a === -Infinity) {
+45 -19
View File
@@ -19,8 +19,8 @@ export function decorateColumn(column, defaultColumn, parent, depth, index) {
if (typeof accessor === 'string') {
id = id || accessor
const accessorString = accessor
accessor = row => getBy(row, accessorString)
const accessorPath = accessor.split('.')
accessor = row => getBy(row, accessorPath)
}
if (!id && typeof Header === 'string' && Header) {
@@ -72,14 +72,6 @@ export function decorateColumnTree(columns, defaultColumn, parent, depth = 0) {
export function makeHeaderGroups(columns, maxDepth, defaultColumn) {
const headerGroups = []
const removeChildColumns = column => {
delete column.columns
if (column.parent) {
removeChildColumns(column.parent)
}
}
columns.forEach(removeChildColumns)
const buildGroup = (columns, depth = 0) => {
const headerGroup = {
headers: [],
@@ -124,15 +116,22 @@ export function makeHeaderGroups(columns, maxDepth, defaultColumn) {
}
}
// Establish the new columns[] relationship on the parent
// Establish the new headers[] relationship on the parent
if (column.parent || hasParents) {
latestParentColumn = [...parentColumns].reverse()[0]
latestParentColumn.columns = latestParentColumn.columns || []
if (!latestParentColumn.columns.includes(column)) {
latestParentColumn.columns.push(column)
latestParentColumn.headers = latestParentColumn.headers || []
if (!latestParentColumn.headers.includes(column)) {
latestParentColumn.headers.push(column)
}
}
column.totalHeaderCount = column.headers
? column.headers.reduce(
(sum, header) => sum + header.totalHeaderCount,
0
)
: 1 // Leaf node columns take up at least one count
headerGroup.headers.push(column)
})
@@ -148,6 +147,25 @@ export function makeHeaderGroups(columns, maxDepth, defaultColumn) {
return headerGroups.reverse()
}
export function determineColumnVisibility(instance) {
const { headers } = instance
const handleColumn = (column, parentVisible) => {
column.isVisible = parentVisible
? typeof column.show === 'function'
? column.show(instance)
: !!column.show
: false
if (column.columns && column.columns.length) {
column.columns.forEach(subColumn =>
handleColumn(subColumn, column.isVisible)
)
}
}
headers.forEach(subColumn => handleColumn(subColumn, true))
}
export function getBy(obj, path, def) {
if (!path) {
return obj
@@ -196,6 +214,7 @@ export function defaultGroupByFn(rows, columnID) {
}
export function setBy(obj = {}, path, value) {
path = makePathArray(path)
const recurse = (obj, depth = 0) => {
const key = path[depth]
const target = typeof obj[key] !== 'object' ? {} : obj[key]
@@ -347,11 +366,18 @@ This usually means you need to need to name your plugin hook by setting the 'plu
//
function makePathArray(obj) {
return flattenDeep(obj)
.join('.')
.replace(/\[/g, '.')
.replace(/\]/g, '')
.split('.')
return (
flattenDeep(obj)
// remove all periods in parts
.map(d => String(d).replace('.', '_'))
// join parts using period
.join('.')
// replace brackets with periods
.replace(/\[/g, '.')
.replace(/\]/g, '')
// split it back out on periods
.split('.')
)
}
function flattenDeep(arr, newArr = []) {
+5
View File
@@ -6320,6 +6320,11 @@ prettier-linter-helpers@^1.0.0:
dependencies:
fast-diff "^1.1.2"
prettier@^1.18.2:
version "1.18.2"
resolved "https://registry.yarnpkg.com/prettier/-/prettier-1.18.2.tgz#6823e7c5900017b4bd3acf46fe9ac4b4d7bda9ea"
integrity sha512-OeHeMc0JhFE9idD4ZdtNibzY0+TPHSpSSb9h8FqtP+YnoZZ1sl8Vc9b1sasjfymH3SonAF4QcA2+mzHPhMvIiw==
pretty-format@^23.6.0:
version "23.6.0"
resolved "https://registry.yarnpkg.com/pretty-format/-/pretty-format-23.6.0.tgz#5eaac8eeb6b33b987b7fe6097ea6a8a146ab5760"