mirror of
https://github.com/gosticks/react-table.git
synced 2025-10-16 11:55:36 +00:00
feat: added useColumnOrder + examples
This commit is contained in:
parent
9b7264fad4
commit
b0d6169848
24
docs/api.md
24
docs/api.md
@ -1573,9 +1573,29 @@ The following additional properties are available on every `Cell` object returne
|
||||
- Use this function to programmatically update the state of a cell.
|
||||
- `updater` can be a function or value. If a `function` is passed, it will receive the current value and expect a new one to be returned.
|
||||
|
||||
### Example
|
||||
# `useColumnOrder`
|
||||
|
||||
> Have an example of using useRowState? Submit a PR to add it here!
|
||||
- Plugin Hook
|
||||
- Optional
|
||||
|
||||
`useColumnOrder` is a plugin hook that implements **basic column reordering**. As columns are reordered, their header groups are reverse-engineered so as to never have orphaned header groups.
|
||||
|
||||
### Table Options
|
||||
|
||||
The following options are supported via the main options object passed to `useTable(options)`
|
||||
|
||||
- `state[0].columnOrder: Array<ColumnID>`
|
||||
- Optional
|
||||
- Defaults to `[]`
|
||||
- Any column ID's not represented in this array will be naturally ordered based on their position in the original table's `column` structure
|
||||
|
||||
### Instance Properties
|
||||
|
||||
The following values are provided to the table `instance`:
|
||||
|
||||
- `setColumnOrder: Function(updater: Function | Array<ColumnID>) => void`
|
||||
- Use this function to programmatically update the columnOrder.
|
||||
- `updater` can be a function or value. If a `function` is passed, it will receive the current value and expect a new one to be returned.
|
||||
|
||||
# `useTableState`
|
||||
|
||||
|
||||
@ -28,6 +28,9 @@
|
||||
- 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)
|
||||
- Column Ordering
|
||||
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/column-ordering)
|
||||
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/column-ordering)
|
||||
- **Complex**
|
||||
- The "Kitchen Sink"
|
||||
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/kitchen-sink)
|
||||
@ -37,6 +40,9 @@
|
||||
- [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!
|
||||
- Animated (Framer-Motion)
|
||||
- [Source + Guide](https://github.com/tannerlinsley/react-table/tree/master/examples/animated-framer-motion)
|
||||
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/animated-framer-motion)
|
||||
- [ ] Styled-Components
|
||||
- [ ] CSS
|
||||
- [ ] Material-UI
|
||||
|
||||
4
examples/animated-framer-motion/.babelrc
Normal file
4
examples/animated-framer-motion/.babelrc
Normal file
@ -0,0 +1,4 @@
|
||||
{
|
||||
"presets": ["react-app"],
|
||||
"plugins": ["styled-components"]
|
||||
}
|
||||
1
examples/animated-framer-motion/.env
Normal file
1
examples/animated-framer-motion/.env
Normal file
@ -0,0 +1 @@
|
||||
SKIP_PREFLIGHT_CHECK=true
|
||||
7
examples/animated-framer-motion/.eslintrc
Normal file
7
examples/animated-framer-motion/.eslintrc
Normal file
@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": ["react-app", "prettier"],
|
||||
"rules": {
|
||||
// "eqeqeq": 0,
|
||||
// "jsx-a11y/anchor-is-valid": 0
|
||||
}
|
||||
}
|
||||
23
examples/animated-framer-motion/.gitignore
vendored
Normal file
23
examples/animated-framer-motion/.gitignore
vendored
Normal 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
examples/animated-framer-motion/.rescriptsrc.js
Normal file
29
examples/animated-framer-motion/.rescriptsrc.js
Normal 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,
|
||||
]
|
||||
6
examples/animated-framer-motion/README.md
Normal file
6
examples/animated-framer-motion/README.md
Normal file
@ -0,0 +1,6 @@
|
||||
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app) and Rescripts.
|
||||
|
||||
You can:
|
||||
|
||||
- [Open this example in a new CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/basic)
|
||||
- `yarn` and `yarn start` to run and edit the example
|
||||
38
examples/animated-framer-motion/package.json
Normal file
38
examples/animated-framer-motion/package.json
Normal file
@ -0,0 +1,38 @@
|
||||
{
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"start": "rescripts start",
|
||||
"build": "rescripts build",
|
||||
"test": "rescripts test",
|
||||
"eject": "rescripts eject"
|
||||
},
|
||||
"dependencies": {
|
||||
"framer-motion": "^1.6.3",
|
||||
"match-sorter": "^4.0.1",
|
||||
"namor": "^1.1.2",
|
||||
"react": "^16.8.6",
|
||||
"react-dom": "^16.8.6",
|
||||
"react-scripts": "3.0.1",
|
||||
"react-spring": "^8.0.27",
|
||||
"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"
|
||||
]
|
||||
}
|
||||
}
|
||||
BIN
examples/animated-framer-motion/public/favicon.ico
Normal file
BIN
examples/animated-framer-motion/public/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 3.8 KiB |
38
examples/animated-framer-motion/public/index.html
Normal file
38
examples/animated-framer-motion/public/index.html
Normal 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>
|
||||
15
examples/animated-framer-motion/public/manifest.json
Normal file
15
examples/animated-framer-motion/public/manifest.json
Normal file
@ -0,0 +1,15 @@
|
||||
{
|
||||
"short_name": "React App",
|
||||
"name": "Create React App Sample",
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicon.ico",
|
||||
"sizes": "64x64 32x32 24x24 16x16",
|
||||
"type": "image/x-icon"
|
||||
}
|
||||
],
|
||||
"start_url": ".",
|
||||
"display": "standalone",
|
||||
"theme_color": "#000000",
|
||||
"background_color": "#ffffff"
|
||||
}
|
||||
382
examples/animated-framer-motion/src/App.js
Normal file
382
examples/animated-framer-motion/src/App.js
Normal file
@ -0,0 +1,382 @@
|
||||
import React from 'react'
|
||||
import styled from 'styled-components'
|
||||
import { useTable, useSortBy, useFilters, useColumnOrder } from 'react-table'
|
||||
import { motion, AnimatePresence } from 'framer-motion'
|
||||
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;
|
||||
background: white;
|
||||
|
||||
:last-child {
|
||||
border-right: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
// 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
|
||||
|
||||
function shuffle(arr) {
|
||||
arr = [...arr]
|
||||
const shuffled = []
|
||||
while (arr.length) {
|
||||
const rand = Math.floor(Math.random() * arr.length)
|
||||
shuffled.push(arr.splice(rand, 1)[0])
|
||||
}
|
||||
return shuffled
|
||||
}
|
||||
|
||||
function Table({ columns, data }) {
|
||||
const defaultColumn = React.useMemo(
|
||||
() => ({
|
||||
// Let's set up our default Filter UI
|
||||
Filter: DefaultColumnFilter,
|
||||
}),
|
||||
[]
|
||||
)
|
||||
|
||||
const {
|
||||
getTableProps,
|
||||
headerGroups,
|
||||
rows,
|
||||
flatColumns,
|
||||
prepareRow,
|
||||
setColumnOrder,
|
||||
state,
|
||||
} = useTable(
|
||||
{
|
||||
columns,
|
||||
data,
|
||||
defaultColumn,
|
||||
},
|
||||
useColumnOrder,
|
||||
useFilters,
|
||||
useSortBy
|
||||
)
|
||||
|
||||
const spring = React.useMemo(
|
||||
() => ({
|
||||
type: 'spring',
|
||||
damping: 50,
|
||||
stiffness: 100,
|
||||
}),
|
||||
[]
|
||||
)
|
||||
|
||||
const randomizeColumns = () => {
|
||||
setColumnOrder(shuffle(flatColumns.map(d => d.id)))
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<button onClick={() => randomizeColumns({})}>Randomize Columns</button>
|
||||
<table {...getTableProps()}>
|
||||
<thead>
|
||||
{headerGroups.map((headerGroup, i) => (
|
||||
<tr {...headerGroup.getHeaderGroupProps()}>
|
||||
{headerGroup.headers.map(column => (
|
||||
<motion.th
|
||||
{...column.getHeaderProps({
|
||||
layoutTransition: spring,
|
||||
style: {
|
||||
minWidth: column.minWidth,
|
||||
},
|
||||
})}
|
||||
>
|
||||
<div {...column.getSortByToggleProps()}>
|
||||
{column.render('Header')}
|
||||
<span>
|
||||
{column.isSorted
|
||||
? column.isSortedDesc
|
||||
? ' 🔽'
|
||||
: ' 🔼'
|
||||
: ''}
|
||||
</span>
|
||||
</div>
|
||||
<div>{column.canFilter ? column.render('Filter') : null}</div>
|
||||
</motion.th>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
<tbody>
|
||||
<AnimatePresence>
|
||||
{rows.slice(0, 10).map(
|
||||
(row, i) =>
|
||||
prepareRow(row) || (
|
||||
<motion.tr
|
||||
{...row.getRowProps({
|
||||
layoutTransition: spring,
|
||||
exit: { opacity: 0, maxHeight: 0 },
|
||||
})}
|
||||
>
|
||||
{row.cells.map((cell, i) => {
|
||||
return (
|
||||
<motion.td
|
||||
{...cell.getCellProps({
|
||||
layoutTransition: spring,
|
||||
})}
|
||||
>
|
||||
{cell.render('Cell')}
|
||||
</motion.td>
|
||||
)
|
||||
})}
|
||||
</motion.tr>
|
||||
)
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</tbody>
|
||||
</table>
|
||||
<pre>
|
||||
<code>{JSON.stringify(state[0], 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'
|
||||
|
||||
function App() {
|
||||
const columns = React.useMemo(
|
||||
() => [
|
||||
{
|
||||
Header: 'Name',
|
||||
columns: [
|
||||
{
|
||||
Header: 'First Name',
|
||||
accessor: 'firstName',
|
||||
minWidth: 150,
|
||||
},
|
||||
{
|
||||
Header: 'Last Name',
|
||||
accessor: 'lastName',
|
||||
minWidth: 150,
|
||||
// Use our custom `fuzzyText` filter on this column
|
||||
filter: 'fuzzyText',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
Header: 'Info',
|
||||
columns: [
|
||||
{
|
||||
Header: 'Age',
|
||||
accessor: 'age',
|
||||
minWidth: 150,
|
||||
Filter: SliderColumnFilter,
|
||||
filter: 'equals',
|
||||
},
|
||||
{
|
||||
Header: 'Visits',
|
||||
accessor: 'visits',
|
||||
minWidth: 150,
|
||||
Filter: NumberRangeColumnFilter,
|
||||
filter: 'between',
|
||||
},
|
||||
{
|
||||
Header: 'Status',
|
||||
accessor: 'status',
|
||||
minWidth: 150,
|
||||
Filter: SelectColumnFilter,
|
||||
filter: 'includes',
|
||||
},
|
||||
{
|
||||
Header: 'Profile Progress',
|
||||
accessor: 'progress',
|
||||
minWidth: 150,
|
||||
Filter: SliderColumnFilter,
|
||||
filter: filterGreaterThan,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
[]
|
||||
)
|
||||
|
||||
const data = React.useMemo(() => makeData(100), [])
|
||||
|
||||
return (
|
||||
<Styles>
|
||||
<Table columns={columns} data={data} />
|
||||
</Styles>
|
||||
)
|
||||
}
|
||||
|
||||
export default App
|
||||
9
examples/animated-framer-motion/src/App.test.js
Normal file
9
examples/animated-framer-motion/src/App.test.js
Normal 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
examples/animated-framer-motion/src/index.css
Normal file
13
examples/animated-framer-motion/src/index.css
Normal 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
examples/animated-framer-motion/src/index.js
Normal file
12
examples/animated-framer-motion/src/index.js
Normal 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
examples/animated-framer-motion/src/makeData.js
Normal file
40
examples/animated-framer-motion/src/makeData.js
Normal 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
examples/animated-framer-motion/src/serviceWorker.js
Normal file
135
examples/animated-framer-motion/src/serviceWorker.js
Normal 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()
|
||||
})
|
||||
}
|
||||
}
|
||||
10237
examples/animated-framer-motion/yarn.lock
Normal file
10237
examples/animated-framer-motion/yarn.lock
Normal file
File diff suppressed because it is too large
Load Diff
@ -1,6 +1,6 @@
|
||||
import React from 'react'
|
||||
import styled from 'styled-components'
|
||||
import { useTable, useSortBy, useFilters } from 'react-table'
|
||||
import { useTable, useSortBy, useFilters, useColumnOrder } from 'react-table'
|
||||
import { motion, AnimatePresence } from 'framer-motion'
|
||||
import matchSorter from 'match-sorter'
|
||||
|
||||
@ -36,22 +36,6 @@ const Styles = styled.div`
|
||||
}
|
||||
`
|
||||
|
||||
function useRandomColumnOrder(hooks) {
|
||||
const columnsBeforeHeaderGroups = React.useCallback(columns => {
|
||||
columns = [...columns]
|
||||
const newColumns = []
|
||||
while (columns.length) {
|
||||
const rand = Math.floor(Math.random() * columns.length)
|
||||
newColumns.push(columns.splice(rand, 1)[0])
|
||||
}
|
||||
return newColumns
|
||||
}, [])
|
||||
hooks.columnsBeforeHeaderGroupsDeps.push((deps, instance) => {
|
||||
return [instance.randomizeOrder]
|
||||
})
|
||||
hooks.columnsBeforeHeaderGroups.push(columnsBeforeHeaderGroups)
|
||||
}
|
||||
|
||||
// Define a default UI for filtering
|
||||
function DefaultColumnFilter({
|
||||
column: { filterValue, preFilteredRows, setFilter },
|
||||
@ -197,9 +181,17 @@ function fuzzyTextFilterFn(rows, id, filterValue) {
|
||||
// Let the table remove the filter if the string is empty
|
||||
fuzzyTextFilterFn.autoRemove = val => !val
|
||||
|
||||
function Table({ columns, data }) {
|
||||
const [randomizeOrder, setRandomizeOrder] = React.useState({})
|
||||
function shuffle(arr) {
|
||||
arr = [...arr]
|
||||
const shuffled = []
|
||||
while (arr.length) {
|
||||
const rand = Math.floor(Math.random() * arr.length)
|
||||
shuffled.push(arr.splice(rand, 1)[0])
|
||||
}
|
||||
return shuffled
|
||||
}
|
||||
|
||||
function Table({ columns, data }) {
|
||||
const defaultColumn = React.useMemo(
|
||||
() => ({
|
||||
// Let's set up our default Filter UI
|
||||
@ -208,14 +200,21 @@ function Table({ columns, data }) {
|
||||
[]
|
||||
)
|
||||
|
||||
const { getTableProps, headerGroups, rows, prepareRow } = useTable(
|
||||
const {
|
||||
getTableProps,
|
||||
headerGroups,
|
||||
rows,
|
||||
flatColumns,
|
||||
prepareRow,
|
||||
setColumnOrder,
|
||||
state,
|
||||
} = useTable(
|
||||
{
|
||||
columns,
|
||||
data,
|
||||
randomizeOrder,
|
||||
defaultColumn,
|
||||
},
|
||||
useRandomColumnOrder,
|
||||
useColumnOrder,
|
||||
useFilters,
|
||||
useSortBy
|
||||
)
|
||||
@ -229,57 +228,51 @@ function Table({ columns, data }) {
|
||||
[]
|
||||
)
|
||||
|
||||
const randomizeColumns = () => {
|
||||
setColumnOrder(shuffle(flatColumns.map(d => d.id)))
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<button onClick={() => setRandomizeOrder({})}>Randomize Columns</button>
|
||||
<button onClick={() => randomizeColumns({})}>Randomize Columns</button>
|
||||
<table {...getTableProps()}>
|
||||
<thead>
|
||||
{headerGroups.map((headerGroup, i) => (
|
||||
<tr {...headerGroup.getHeaderGroupProps()}>
|
||||
<AnimatePresence>
|
||||
{headerGroup.headers.map(column => (
|
||||
<motion.th
|
||||
{...column.getHeaderProps({
|
||||
initial: false,
|
||||
enter: { opacity: 1, width: 'auto' },
|
||||
exit: { opacity: 0, width: 0 },
|
||||
layoutTransition: spring,
|
||||
style: {
|
||||
minWidth: column.minWidth,
|
||||
},
|
||||
})}
|
||||
>
|
||||
<div {...column.getSortByToggleProps()}>
|
||||
{/* {column.render('Header')} */}
|
||||
{column.id}
|
||||
<span>
|
||||
{column.isSorted
|
||||
? column.isSortedDesc
|
||||
? ' 🔽'
|
||||
: ' 🔼'
|
||||
: ''}
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
{column.canFilter ? column.render('Filter') : null}
|
||||
</div>
|
||||
</motion.th>
|
||||
))}
|
||||
</AnimatePresence>
|
||||
{headerGroup.headers.map(column => (
|
||||
<motion.th
|
||||
{...column.getHeaderProps({
|
||||
layoutTransition: spring,
|
||||
style: {
|
||||
minWidth: column.minWidth,
|
||||
},
|
||||
})}
|
||||
>
|
||||
<div {...column.getSortByToggleProps()}>
|
||||
{column.render('Header')}
|
||||
<span>
|
||||
{column.isSorted
|
||||
? column.isSortedDesc
|
||||
? ' 🔽'
|
||||
: ' 🔼'
|
||||
: ''}
|
||||
</span>
|
||||
</div>
|
||||
<div>{column.canFilter ? column.render('Filter') : null}</div>
|
||||
</motion.th>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
<tbody>
|
||||
<AnimatePresence delayChildren={false}>
|
||||
{rows.map(
|
||||
<AnimatePresence>
|
||||
{rows.slice(0, 10).map(
|
||||
(row, i) =>
|
||||
prepareRow(row) || (
|
||||
<motion.tr
|
||||
{...row.getRowProps({
|
||||
initial: false,
|
||||
enter: { opacity: 1, height: 'auto' },
|
||||
exit: { opacity: 0, height: 0 },
|
||||
layoutTransition: spring,
|
||||
exit: { opacity: 0, maxHeight: 0 },
|
||||
})}
|
||||
>
|
||||
{row.cells.map((cell, i) => {
|
||||
@ -299,6 +292,9 @@ function Table({ columns, data }) {
|
||||
</AnimatePresence>
|
||||
</tbody>
|
||||
</table>
|
||||
<pre>
|
||||
<code>{JSON.stringify(state[0], null, 2)}</code>
|
||||
</pre>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@ -374,7 +370,7 @@ function App() {
|
||||
[]
|
||||
)
|
||||
|
||||
const data = React.useMemo(() => makeData(10), [])
|
||||
const data = React.useMemo(() => makeData(100), [])
|
||||
|
||||
return (
|
||||
<Styles>
|
||||
|
||||
4
examples/column-ordering/.babelrc
Normal file
4
examples/column-ordering/.babelrc
Normal file
@ -0,0 +1,4 @@
|
||||
{
|
||||
"presets": ["react-app"],
|
||||
"plugins": ["styled-components"]
|
||||
}
|
||||
1
examples/column-ordering/.env
Normal file
1
examples/column-ordering/.env
Normal file
@ -0,0 +1 @@
|
||||
SKIP_PREFLIGHT_CHECK=true
|
||||
7
examples/column-ordering/.eslintrc
Normal file
7
examples/column-ordering/.eslintrc
Normal file
@ -0,0 +1,7 @@
|
||||
{
|
||||
"extends": ["react-app", "prettier"],
|
||||
"rules": {
|
||||
// "eqeqeq": 0,
|
||||
// "jsx-a11y/anchor-is-valid": 0
|
||||
}
|
||||
}
|
||||
23
examples/column-ordering/.gitignore
vendored
Normal file
23
examples/column-ordering/.gitignore
vendored
Normal 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
examples/column-ordering/.rescriptsrc.js
Normal file
29
examples/column-ordering/.rescriptsrc.js
Normal 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,
|
||||
]
|
||||
6
examples/column-ordering/README.md
Normal file
6
examples/column-ordering/README.md
Normal file
@ -0,0 +1,6 @@
|
||||
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app) and Rescripts.
|
||||
|
||||
You can:
|
||||
|
||||
- [Open this example in a new CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/basic)
|
||||
- `yarn` and `yarn start` to run and edit the example
|
||||
38
examples/column-ordering/package.json
Normal file
38
examples/column-ordering/package.json
Normal file
@ -0,0 +1,38 @@
|
||||
{
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"start": "rescripts start",
|
||||
"build": "rescripts build",
|
||||
"test": "rescripts test",
|
||||
"eject": "rescripts eject"
|
||||
},
|
||||
"dependencies": {
|
||||
"framer-motion": "^1.6.3",
|
||||
"match-sorter": "^4.0.1",
|
||||
"namor": "^1.1.2",
|
||||
"react": "^16.8.6",
|
||||
"react-dom": "^16.8.6",
|
||||
"react-scripts": "3.0.1",
|
||||
"react-spring": "^8.0.27",
|
||||
"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"
|
||||
]
|
||||
}
|
||||
}
|
||||
BIN
examples/column-ordering/public/favicon.ico
Normal file
BIN
examples/column-ordering/public/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 3.8 KiB |
38
examples/column-ordering/public/index.html
Normal file
38
examples/column-ordering/public/index.html
Normal 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>
|
||||
15
examples/column-ordering/public/manifest.json
Normal file
15
examples/column-ordering/public/manifest.json
Normal file
@ -0,0 +1,15 @@
|
||||
{
|
||||
"short_name": "React App",
|
||||
"name": "Create React App Sample",
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicon.ico",
|
||||
"sizes": "64x64 32x32 24x24 16x16",
|
||||
"type": "image/x-icon"
|
||||
}
|
||||
],
|
||||
"start_url": ".",
|
||||
"display": "standalone",
|
||||
"theme_color": "#000000",
|
||||
"background_color": "#ffffff"
|
||||
}
|
||||
157
examples/column-ordering/src/App.js
Normal file
157
examples/column-ordering/src/App.js
Normal file
@ -0,0 +1,157 @@
|
||||
import React from 'react'
|
||||
import styled from 'styled-components'
|
||||
import { useTable, useSortBy, useFilters, useColumnOrder } from 'react-table'
|
||||
import { motion, AnimatePresence } from 'framer-motion'
|
||||
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;
|
||||
background: white;
|
||||
|
||||
:last-child {
|
||||
border-right: 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
|
||||
function shuffle(arr) {
|
||||
arr = [...arr]
|
||||
const shuffled = []
|
||||
while (arr.length) {
|
||||
const rand = Math.floor(Math.random() * arr.length)
|
||||
shuffled.push(arr.splice(rand, 1)[0])
|
||||
}
|
||||
return shuffled
|
||||
}
|
||||
|
||||
function Table({ columns, data }) {
|
||||
const {
|
||||
getTableProps,
|
||||
headerGroups,
|
||||
rows,
|
||||
flatColumns,
|
||||
prepareRow,
|
||||
setColumnOrder,
|
||||
state,
|
||||
} = useTable(
|
||||
{
|
||||
columns,
|
||||
data,
|
||||
},
|
||||
useColumnOrder
|
||||
)
|
||||
|
||||
const randomizeColumns = () => {
|
||||
setColumnOrder(shuffle(flatColumns.map(d => d.id)))
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<button onClick={() => randomizeColumns({})}>Randomize Columns</button>
|
||||
<table {...getTableProps()}>
|
||||
<thead>
|
||||
{headerGroups.map((headerGroup, i) => (
|
||||
<tr {...headerGroup.getHeaderGroupProps()}>
|
||||
{headerGroup.headers.map(column => (
|
||||
<th {...column.getHeaderProps()}>{column.render('Header')}</th>
|
||||
))}
|
||||
</tr>
|
||||
))}
|
||||
</thead>
|
||||
<tbody>
|
||||
<AnimatePresence>
|
||||
{rows.slice(0, 10).map(
|
||||
(row, i) =>
|
||||
prepareRow(row) || (
|
||||
<tr {...row.getRowProps()}>
|
||||
{row.cells.map((cell, i) => {
|
||||
return (
|
||||
<td {...cell.getCellProps()}>{cell.render('Cell')}</td>
|
||||
)
|
||||
})}
|
||||
</tr>
|
||||
)
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</tbody>
|
||||
</table>
|
||||
<pre>
|
||||
<code>{JSON.stringify(state[0], null, 2)}</code>
|
||||
</pre>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function App() {
|
||||
const columns = React.useMemo(
|
||||
() => [
|
||||
{
|
||||
Header: 'Name',
|
||||
columns: [
|
||||
{
|
||||
Header: 'First Name',
|
||||
accessor: 'firstName',
|
||||
},
|
||||
{
|
||||
Header: 'Last Name',
|
||||
accessor: 'lastName',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
Header: 'Info',
|
||||
columns: [
|
||||
{
|
||||
Header: 'Age',
|
||||
accessor: 'age',
|
||||
},
|
||||
{
|
||||
Header: 'Visits',
|
||||
accessor: 'visits',
|
||||
},
|
||||
{
|
||||
Header: 'Status',
|
||||
accessor: 'status',
|
||||
},
|
||||
{
|
||||
Header: 'Profile Progress',
|
||||
accessor: 'progress',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
[]
|
||||
)
|
||||
|
||||
const data = React.useMemo(() => makeData(10), [])
|
||||
|
||||
return (
|
||||
<Styles>
|
||||
<Table columns={columns} data={data} />
|
||||
</Styles>
|
||||
)
|
||||
}
|
||||
|
||||
export default App
|
||||
9
examples/column-ordering/src/App.test.js
Normal file
9
examples/column-ordering/src/App.test.js
Normal 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
examples/column-ordering/src/index.css
Normal file
13
examples/column-ordering/src/index.css
Normal 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
examples/column-ordering/src/index.js
Normal file
12
examples/column-ordering/src/index.js
Normal 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
examples/column-ordering/src/makeData.js
Normal file
40
examples/column-ordering/src/makeData.js
Normal 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
examples/column-ordering/src/serviceWorker.js
Normal file
135
examples/column-ordering/src/serviceWorker.js
Normal 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()
|
||||
})
|
||||
}
|
||||
}
|
||||
10237
examples/column-ordering/yarn.lock
Normal file
10237
examples/column-ordering/yarn.lock
Normal file
File diff suppressed because it is too large
Load Diff
@ -9,4 +9,5 @@ export { useSortBy } from './plugin-hooks/useSortBy'
|
||||
export { usePagination } from './plugin-hooks/usePagination'
|
||||
export { useRowSelect } from './plugin-hooks/useRowSelect'
|
||||
export { useRowState } from './plugin-hooks/useRowState'
|
||||
export { useColumnOrder } from './plugin-hooks/useColumnOrder'
|
||||
export { actions, addActions } from './actions'
|
||||
|
||||
80
src/plugin-hooks/useColumnOrder.js
Normal file
80
src/plugin-hooks/useColumnOrder.js
Normal file
@ -0,0 +1,80 @@
|
||||
import React from 'react'
|
||||
import PropTypes from 'prop-types'
|
||||
|
||||
import { addActions, actions } from '../actions'
|
||||
import { defaultState } from '../hooks/useTableState'
|
||||
|
||||
defaultState.columnOrder = []
|
||||
|
||||
addActions('setColumnOrder')
|
||||
|
||||
const propTypes = {
|
||||
initialRowStateAccessor: PropTypes.func,
|
||||
}
|
||||
|
||||
export const useColumnOrder = hooks => {
|
||||
hooks.columnsBeforeHeaderGroupsDeps.push((deps, instance) => {
|
||||
return [...deps, instance.state[0].columnOrder]
|
||||
})
|
||||
hooks.columnsBeforeHeaderGroups.push(columnsBeforeHeaderGroups)
|
||||
hooks.useMain.push(useMain)
|
||||
}
|
||||
|
||||
useColumnOrder.pluginName = 'useColumnOrder'
|
||||
|
||||
function columnsBeforeHeaderGroups(columns, instance) {
|
||||
const {
|
||||
state: [{ columnOrder }],
|
||||
} = instance
|
||||
|
||||
// If there is no order, return the normal columns
|
||||
if (!columnOrder || !columnOrder.length) {
|
||||
return columns
|
||||
}
|
||||
|
||||
const columnOrderCopy = [...columnOrder]
|
||||
|
||||
// If there is an order, make a copy of the columns
|
||||
const columnsCopy = [...columns]
|
||||
|
||||
// And make a new ordered array of the columns
|
||||
const columnsInOrder = []
|
||||
|
||||
// Loop over the columns and place them in order into the new array
|
||||
while (columnsCopy.length && columnOrderCopy.length) {
|
||||
const targetColumnID = columnOrderCopy.shift()
|
||||
const foundIndex = columnsCopy.findIndex(d => d.id === targetColumnID)
|
||||
if (foundIndex > -1) {
|
||||
columnsInOrder.push(columnsCopy.splice(foundIndex, 1)[0])
|
||||
}
|
||||
}
|
||||
|
||||
// If there are any columns left, add them to the end
|
||||
return [...columnsInOrder, ...columnsCopy]
|
||||
}
|
||||
|
||||
function useMain(instance) {
|
||||
PropTypes.checkPropTypes(propTypes, instance, 'property', 'useColumnOrder')
|
||||
|
||||
const {
|
||||
state: [, setState],
|
||||
} = instance
|
||||
|
||||
const setColumnOrder = React.useCallback(
|
||||
updater => {
|
||||
return setState(old => {
|
||||
return {
|
||||
...old,
|
||||
columnOrder:
|
||||
typeof updater === 'function' ? updater(old.columnOrder) : updater,
|
||||
}
|
||||
}, actions.setColumnOrder)
|
||||
},
|
||||
[setState]
|
||||
)
|
||||
|
||||
return {
|
||||
...instance,
|
||||
setColumnOrder,
|
||||
}
|
||||
}
|
||||
@ -4,7 +4,7 @@ import PropTypes from 'prop-types'
|
||||
//
|
||||
import { addActions, actions } from '../actions'
|
||||
import { defaultState } from '../hooks/useTableState'
|
||||
import { ensurePluginOrder } from '../utils'
|
||||
import { ensurePluginOrder, safeUseLayoutEffect } from '../utils'
|
||||
|
||||
defaultState.pageSize = 10
|
||||
defaultState.pageIndex = 0
|
||||
@ -17,12 +17,6 @@ const propTypes = {
|
||||
paginateExpandedRows: PropTypes.bool,
|
||||
}
|
||||
|
||||
// SSR has issues with useLayoutEffect still, so use useEffect during SSR
|
||||
let useLayoutEffect =
|
||||
typeof window !== 'undefined' && process.env.NODE_ENV === 'production'
|
||||
? React.useLayoutEffect
|
||||
: React.useEffect
|
||||
|
||||
export const usePagination = hooks => {
|
||||
hooks.useMain.push(useMain)
|
||||
}
|
||||
@ -55,7 +49,7 @@ function useMain(instance) {
|
||||
|
||||
const isPageIndexMountedRef = React.useRef()
|
||||
|
||||
useLayoutEffect(() => {
|
||||
safeUseLayoutEffect(() => {
|
||||
if (isPageIndexMountedRef.current && !disablePageResetOnDataChange) {
|
||||
setState(
|
||||
old => ({
|
||||
|
||||
@ -6,6 +6,12 @@ const columnFallbacks = {
|
||||
show: true,
|
||||
}
|
||||
|
||||
// SSR has issues with useLayoutEffect still, so use useEffect during SSR
|
||||
export const safeUseLayoutEffect =
|
||||
typeof window !== 'undefined' && process.env.NODE_ENV === 'production'
|
||||
? React.useLayoutEffect
|
||||
: React.useEffect
|
||||
|
||||
// Find the depth of the columns
|
||||
export function findMaxDepth(columns, depth = 0) {
|
||||
return columns.reduce((prev, curr) => {
|
||||
|
||||
Loading…
Reference in New Issue
Block a user