feat(useresizecolumns): added useResizeColumns

This commit is contained in:
tannerlinsley 2019-10-03 08:25:36 -06:00
parent 727f4157c1
commit de7f5c9385
26 changed files with 10891 additions and 11 deletions

View File

@ -44,6 +44,7 @@ Hooks for building **lightweight, fast and extendable datagrids** for React
- Column Ordering
- Animatable
- Virtualizable
- Resizable
- Server-side/controlled data/state
- Extensible via hook-based plugin system
- <a href="https://medium.com/@tannerlinsley/why-i-wrote-react-table-and-the-problems-it-has-solved-for-nozzle-others-445c4e93d4a8#.axza4ixba" target="\_parent">"Why I wrote React Table and the problems it has solved for Nozzle.io"</a> by Tanner Linsley

View File

@ -19,6 +19,7 @@ React Table is essentially a compatible collection of **custom React hooks**:
- Layout Hooks
- [`useBlockLayout`](#useBlockLayout)
- [`useAbsoluteLayout`](#useAbsoluteLayout)
- [`useResizeColumns`](#useResizeColumns)
- Utility Hooks
- [`useTableState`](#useTableState)
- 3rd Party Plugin Hooks
@ -119,7 +120,7 @@ The following options are supported via the main options object passed to `useTa
- A flag to turn on debug mode.
- Defaults to `false`
### `column` Options
### Column Options
The following options are supported on any column object you can pass to `columns`.
@ -884,7 +885,7 @@ The following additional properties are available on every `Cell` object returne
`useBlocklayout` is a plugin hook that adds support for headers and cells to be rendered as `inline-block` `div`s (or other non-table elements) with explicit `width`. Similar to the `useAbsoluteLayout` hook, this becomes useful if and when you need to virtualize rows and cells for performance.
**NOTE:** Although no additional options are needed, the core column options `width`, `minWidth` and `maxWidth` are used to calculate column and cell widths and must be set. [See Column Options](#column-options) for more information on these options.
**NOTE:** Although no additional options are needed for this plugin to work, the core column options `width`, `minWidth` and `maxWidth` are used to calculate column and cell widths and must be set. [See Column Options](#column-options) for more information on these options.
### Row Properties
@ -916,7 +917,7 @@ The following additional properties are available on every `Cell` object returne
`useAbsoluteLayout` is a plugin hook that adds support for headers and cells to be rendered as absolutely positioned `div`s (or other non-table elements) with explicit `width`. Similar to the `useBlockLayout` hook, this becomes useful if and when you need to virtualize rows and cells for performance.
**NOTE:** Although no additional options are needed, the core column options `width`, `minWidth` and `maxWidth` are used to calculate column and cell widths and must be set. [See Column Options](#column-options) for more information on these options.
**NOTE:** Although no additional options are needed for this plugin to work, the core column options `width`, `minWidth` and `maxWidth` are used to calculate column and cell widths and must be set. [See Column Options](#column-options) for more information on these options.
### Instance Properties
@ -947,6 +948,42 @@ The following additional properties are available on every `Cell` object returne
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/absolute-layout)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/absolute-layout)
# `useResizeColumns`
- Plugin Hook
- Optional
`useResizeColumns` is a plugin hook that adds support for resizing headers and cells when using non-table elements for layout eg. the `useBlockLayout` and `useAbsoluteLayout` hooks. It even supports resizing column groups!
### Table Options
- `disableResizing: Bool`
- Defaults to `false`
- When set to `true`, resizing is disabled across the entire table
### Column Options
The core column options `width`, `minWidth` and `maxWidth` are used to calculate column and cell widths and must be set. [See Column Options](#column-options) for more information on these options.
- `disableResizing: Bool`
- Defaults to `false`
- When set to `true`, resizing is disabled for this column
### Header Properties
- `getResizerProps`
- **Usage Required**
- This core prop getter is required to to enable absolute layout for headers
- `canResize: Bool`
- Will be `true` if this column can be resized
- `isResizing: Bool`
- Will be `true` if this column is currently being resized
### Example
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/column-resizing)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/column-resizing)
# `useColumnOrder`
- Plugin Hook

View File

@ -31,6 +31,9 @@
- Column Ordering
- [Source](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)
- Column Resizing
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/column-resizing)
- [Open in CodeSandbox](https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/column-resizing)
- **Complex**
- The "Kitchen Sink"
- [Source](https://github.com/tannerlinsley/react-table/tree/master/examples/kitchen-sink)

View File

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

View File

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

View File

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

23
examples/column-resizing/.gitignore vendored Normal file
View File

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

View File

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

View File

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

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

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

View File

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

View File

@ -0,0 +1,176 @@
import React from 'react'
import styled from 'styled-components'
import { useTable, useBlockLayout, useResizeColumns } from 'react-table'
import makeData from './makeData'
const Styles = styled.div`
padding: 1rem;
.table {
display: inline-block;
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;
${'' /* In this example we use an absolutely position resizer,
so this is required. */}
position: relative;
:last-child {
border-right: 0;
}
${'' /* The resizer styles! */}
.resizer {
display: inline-block;
background: blue;
width: 5px;
height: 100%;
position: absolute;
right: 0;
top: 0;
transform: translateX(50%);
z-index: 1;
&.isResizing {
background: red;
}
}
}
}
`
function Table({ columns, data }) {
const defaultColumn = React.useMemo(
() => ({
minWidth: 20,
width: 150,
maxWidth: 500,
}),
[]
)
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
} = useTable(
{
columns,
data,
defaultColumn,
},
useBlockLayout,
useResizeColumns
)
return (
<div {...getTableProps()} className="table">
<div>
{headerGroups.map(headerGroup => (
<div {...headerGroup.getHeaderGroupProps()} className="tr">
{headerGroup.headers.map(column => (
<div {...column.getHeaderProps()} className="th">
{column.render('Header')}
{/* Use column.getResizerProps to hook up the events correctly */}
<div
{...column.getResizerProps()}
className={`resizer ${column.isResizing ? 'isResizing' : ''}`}
/>
</div>
))}
</div>
))}
</div>
<div {...getTableBodyProps()}>
{rows.map(
(row, i) =>
prepareRow(row) || (
<div {...row.getRowProps()} className="tr">
{row.cells.map(cell => {
return (
<div {...cell.getCellProps()} className="td">
{cell.render('Cell')}
</div>
)
})}
</div>
)
)}
</div>
</div>
)
}
function App() {
const columns = React.useMemo(
() => [
{
Header: 'Name',
columns: [
{
Header: 'First Name',
accessor: 'firstName',
},
{
Header: 'Last Name',
accessor: 'lastName',
},
],
},
{
Header: 'Info',
columns: [
{
Header: 'Age',
accessor: 'age',
width: 50,
},
{
Header: 'Visits',
accessor: 'visits',
width: 60,
},
{
Header: 'Status',
accessor: 'status',
},
{
Header: 'Profile Progress',
accessor: 'progress',
},
],
},
],
[]
)
const data = React.useMemo(() => makeData(20), [])
return (
<Styles>
<Table columns={columns} data={data} />
</Styles>
)
}
export default App

View File

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

View File

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

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

@ -85,8 +85,6 @@ function Table({ columns, data }) {
[prepareRow, rows]
)
console.log(headerGroups)
// Render the UI for your table
return (
<div {...getTableProps()} className="table">

View File

@ -66,6 +66,7 @@ export const useTable = (props, ...plugins) => {
hooks: {
columnsBeforeHeaderGroups: [],
columnsBeforeHeaderGroupsDeps: [],
useBeforeDimensions: [],
useMain: [],
useRows: [],
prepareRow: [],
@ -215,6 +216,15 @@ export const useTable = (props, ...plugins) => {
[]
)
if (process.env.NODE_ENV === 'development' && debug)
console.time('hooks.useBeforeDimensions')
instanceRef.current = applyHooks(
instanceRef.current.hooks.useBeforeDimensions,
instanceRef.current
)
if (process.env.NODE_ENV === 'development' && debug)
console.timeEnd('hooks.useBeforeDimensions')
calculateDimensions(instanceRef.current)
if (process.env.NODE_ENV === 'development' && debug)

View File

@ -11,6 +11,7 @@ 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 { useResizeColumns } from './plugin-hooks/useResizeColumns'
export { useAbsoluteLayout } from './plugin-hooks/useAbsoluteLayout'
export { useBlockLayout } from './plugin-hooks/useBlockLayout'
export { actions, addActions } from './actions'

View File

@ -8,7 +8,7 @@ exports[`renders a table 1`] = `
<div>
<div
class="row"
style="display: block; width: 1400px;"
style="display: flex; width: 1400px;"
>
<div
class="cell header"
@ -27,7 +27,7 @@ exports[`renders a table 1`] = `
</div>
<div
class="row"
style="display: block; width: 1400px;"
style="display: flex; width: 1400px;"
>
<div
class="cell header"
@ -78,7 +78,7 @@ exports[`renders a table 1`] = `
>
<div
class="row"
style="display: block; width: 1400px;"
style="display: flex; width: 1400px;"
>
<div
class="cell"
@ -119,7 +119,7 @@ exports[`renders a table 1`] = `
</div>
<div
class="row"
style="display: block; width: 1400px;"
style="display: flex; width: 1400px;"
>
<div
class="cell"
@ -160,7 +160,7 @@ exports[`renders a table 1`] = `
</div>
<div
class="row"
style="display: block; width: 1400px;"
style="display: flex; width: 1400px;"
>
<div
class="cell"

View File

@ -18,7 +18,7 @@ const useMain = instance => {
const rowStyles = {
style: {
display: 'block',
display: 'flex',
width: `${totalColumnsWidth}px`,
},
}

View File

@ -0,0 +1,142 @@
import PropTypes from 'prop-types'
//
import { defaultState } from '../hooks/useTableState'
import { defaultColumn, getFirstDefined } from '../utils'
import { mergeProps, applyPropHooks } from '../utils'
defaultState.columnResizing = {
columnWidths: {},
}
defaultColumn.canResize = true
const propTypes = {}
export const useResizeColumns = hooks => {
hooks.useBeforeDimensions.push(useBeforeDimensions)
}
useResizeColumns.pluginName = 'useResizeColumns'
const useBeforeDimensions = instance => {
PropTypes.checkPropTypes(propTypes, instance, 'property', 'useResizeColumns')
instance.hooks.getResizerProps = []
const {
flatHeaders,
disableResizing,
hooks: { getHeaderProps },
state: [{ columnResizing }, setState],
} = instance
getHeaderProps.push(() => {
return {
style: {
position: 'relative',
},
}
})
const onMouseDown = (e, header) => {
const headersToResize = getLeafHeaders(header)
const startWidths = headersToResize.map(header => header.totalWidth)
const startX = e.clientX
const onMouseMove = e => {
const currentX = e.clientX
const deltaX = currentX - startX
const percentageDeltaX = deltaX / headersToResize.length
const newColumnWidths = {}
headersToResize.forEach((header, index) => {
newColumnWidths[header.id] = Math.max(
startWidths[index] + percentageDeltaX,
0
)
})
setState(old => ({
...old,
columnResizing: {
...old.columnResizing,
columnWidths: {
...old.columnResizing.columnWidths,
...newColumnWidths,
},
},
}))
}
const onMouseUp = e => {
document.removeEventListener('mousemove', onMouseMove)
document.removeEventListener('mouseup', onMouseUp)
setState(old => ({
...old,
columnResizing: {
...old.columnResizing,
startX: null,
isResizingColumn: null,
},
}))
}
document.addEventListener('mousemove', onMouseMove)
document.addEventListener('mouseup', onMouseUp)
setState(old => ({
...old,
columnResizing: {
...old.columnResizing,
startX,
isResizingColumn: header.id,
},
}))
}
flatHeaders.forEach(header => {
const canResize = getFirstDefined(
header.disableResizing === true ? false : undefined,
disableResizing === true ? false : undefined,
true
)
header.canResize = canResize
header.width = columnResizing.columnWidths[header.id] || header.width
header.isResizing = columnResizing.isResizingColumn === header.id
if (canResize) {
header.getResizerProps = userProps => {
return mergeProps(
{
onMouseDown: e => e.persist() || onMouseDown(e, header),
style: {
cursor: 'ew-resize',
},
draggable: false,
},
applyPropHooks(instance.hooks.getResizerProps, header, instance),
userProps
)
}
}
})
return instance
}
function getLeafHeaders(header) {
const leafHeaders = []
const recurseHeader = header => {
if (header.columns && header.columns.length) {
header.columns.map(recurseHeader)
}
leafHeaders.push(header)
}
recurseHeader(header)
return leafHeaders
}