Death of the path, fix some hooks, fix selectedRows

- Fixed an issue where dependency hooks were not being reduced properly, thus the table would rerender unnecessarily
- Renamed `toggleRowSelectedAll` to `toggleAllRowsSelected`. Duh...
- Added an `indeterminate` boolean prop to the default props for row selection toggle prop getters
- Renamed `selectedRowPaths` to `selectedRowIds`, which also no longer contains paths, but row IDs
- Grouped or nested row selection actions and state are now derived, instead of tracked in state.
- Rows now have a new property called `id`, which existed before and was derived from the `getRowId` option
- Rows now also have an `isSomeSelected` prop when using the `useRowSelect` hook, which denotes that at least one subRow is selected (if applicable)
- Rows' `path` property has been deprecated in favor of `id`
- Expanded state is now tracked with row IDs instead of paths
- RowState is now tracked with row IDs instead of paths
- `toggleExpandedByPath` has been renamed to `toggleExpandedById`, and thus accepts a row ID now, instead of a row path
This commit is contained in:
Tanner Linsley
2019-12-10 23:04:34 -07:00
parent 42b78d52ca
commit ddfa0fa227
19 changed files with 269 additions and 197 deletions
@@ -485,8 +485,8 @@ Snapshot Diff:
<pre>
<code>
{
- "selectedRowPaths": []
+ "selectedRowPaths": [
- "selectedRowIds": []
+ "selectedRowIds": [
+ "0",
+ "1",
+ "2",
@@ -1015,7 +1015,7 @@ Snapshot Diff:
<pre>
<code>
{
- "selectedRowPaths": [
- "selectedRowIds": [
- "0",
- "1",
- "2",
@@ -1053,7 +1053,7 @@ Snapshot Diff:
- "22.1",
- "23"
- ]
+ "selectedRowPaths": []
+ "selectedRowIds": []
}
</code>
</pre>
@@ -1129,8 +1129,8 @@ Snapshot Diff:
<pre>
<code>
{
- "selectedRowPaths": []
+ "selectedRowPaths": [
- "selectedRowIds": []
+ "selectedRowIds": [
+ "0",
+ "2",
+ "2.0",
@@ -1198,7 +1198,7 @@ Snapshot Diff:
<pre>
<code>
{
"selectedRowPaths": [
"selectedRowIds": [
- "0",
- "2",
- "2.0",
@@ -1241,7 +1241,7 @@ Snapshot Diff:
<pre>
<code>
{
"selectedRowPaths": [
"selectedRowIds": [
- "0"
+ "0",
+ "2.0"
@@ -1257,6 +1257,19 @@ Snapshot Diff:
- First value
+ Second value
@@ -163,11 +163,11 @@
</label>
</div>
</td>
<td>
<div>
- Row 2 Not Selected
+ Row 2 Selected
</div>
</td>
<td>
joe
</td>
@@ -237,11 +237,11 @@
</label>
</div>
@@ -1282,7 +1295,7 @@ Snapshot Diff:
<pre>
<code>
{
"selectedRowPaths": [
"selectedRowIds": [
"0",
- "2.0"
+ "2.0",
@@ -1299,6 +1312,19 @@ Snapshot Diff:
- First value
+ Second value
@@ -163,11 +163,11 @@
</label>
</div>
</td>
<td>
<div>
- Row 2 Selected
+ Row 2 Not Selected
</div>
</td>
<td>
joe
</td>
@@ -237,11 +237,11 @@
</label>
</div>
@@ -1324,7 +1350,7 @@ Snapshot Diff:
<pre>
<code>
{
"selectedRowPaths": [
"selectedRowIds": [
"0",
- "2.0",
- "2.1"
+19 -7
View File
@@ -75,7 +75,7 @@ function Table({ columns, data }) {
headerGroups,
rows,
prepareRow,
state: { selectedRowPaths },
state: { selectedRowIds },
} = useTable(
{
columns,
@@ -113,11 +113,11 @@ function Table({ columns, data }) {
)}
</tbody>
</table>
<p>Selected Rows: {selectedRowPaths.size}</p>
<p>Selected Rows: {selectedRowIds.size}</p>
<pre>
<code>
{JSON.stringify(
{ selectedRowPaths: [...selectedRowPaths.values()] },
{ selectedRowIds: [...selectedRowIds.values()] },
null,
2
)}
@@ -127,6 +127,19 @@ function Table({ columns, data }) {
)
}
const IndeterminateCheckbox = React.forwardRef(
({ indeterminate, ...rest }, ref) => {
const defaultRef = React.useRef()
const resolvedRef = ref || defaultRef
React.useEffect(() => {
resolvedRef.current.indeterminate = indeterminate
}, [resolvedRef, indeterminate])
return <input type="checkbox" ref={resolvedRef} {...rest} />
}
)
function App() {
const columns = React.useMemo(
() => [
@@ -138,7 +151,7 @@ function App() {
Header: ({ getToggleAllRowsSelectedProps }) => (
<div>
<label>
<input type="checkbox" {...getToggleAllRowsSelectedProps()} />{' '}
<IndeterminateCheckbox {...getToggleAllRowsSelectedProps()} />{' '}
Select All
</label>
</div>
@@ -148,7 +161,7 @@ function App() {
Cell: ({ row }) => (
<div>
<label>
<input type="checkbox" {...row.getToggleRowSelectedProps()} />{' '}
<IndeterminateCheckbox {...row.getToggleRowSelectedProps()} />{' '}
Select Row
</label>
</div>
@@ -158,8 +171,7 @@ function App() {
id: 'selectedStatus',
Cell: ({ row }) => (
<div>
Row {row.path.join('.')}{' '}
{row.isSelected ? 'Selected' : 'Not Selected'}
Row {row.id} {row.isSelected ? 'Selected' : 'Not Selected'}
</div>
),
},
+13 -14
View File
@@ -10,7 +10,7 @@ import {
import { useConsumeHookGetter } from '../publicUtils'
// Actions
actions.toggleExpandedByPath = 'toggleExpandedByPath'
actions.toggleExpandedById = 'toggleExpandedById'
actions.resetExpanded = 'resetExpanded'
export const useExpanded = hooks => {
@@ -51,17 +51,16 @@ function reducer(state, action) {
}
}
if (action.type === actions.toggleExpandedByPath) {
const { path, expanded } = action
const key = path.join('.')
const exists = state.expanded.includes(key)
if (action.type === actions.toggleExpandedById) {
const { id, expanded } = action
const exists = state.expanded.includes(id)
const shouldExist = typeof expanded !== 'undefined' ? expanded : !exists
let newExpanded = new Set(state.expanded)
if (!exists && shouldExist) {
newExpanded.add(key)
newExpanded.add(id)
} else if (exists && !shouldExist) {
newExpanded.delete(key)
newExpanded.delete(id)
} else {
return state
}
@@ -95,8 +94,8 @@ function useInstance(instance) {
}
}, [dispatch, data])
const toggleExpandedByPath = (path, expanded) => {
dispatch({ type: actions.toggleExpandedByPath, path, expanded })
const toggleExpandedById = (id, expanded) => {
dispatch({ type: actions.toggleExpandedById, id, expanded })
}
// use reference to avoid memory leak in #1608
@@ -108,7 +107,7 @@ function useInstance(instance) {
)
hooks.prepareRow.push(row => {
row.toggleExpanded = set => instance.toggleExpandedByPath(row.path, set)
row.toggleExpanded = set => instance.toggleExpandedById(row.id, set)
row.getExpandedToggleProps = makePropGetter(
getExpandedTogglePropsHooks(),
@@ -128,7 +127,7 @@ function useInstance(instance) {
const expandedDepth = findExpandedDepth(expanded)
Object.assign(instance, {
toggleExpandedByPath,
toggleExpandedById,
preExpandedRows: rows,
expandedRows,
rows: expandedRows,
@@ -139,9 +138,9 @@ function useInstance(instance) {
function findExpandedDepth(expanded) {
let maxDepth = 0
expanded.forEach(key => {
const path = key.split('.')
maxDepth = Math.max(maxDepth, path.length)
expanded.forEach(id => {
const splitId = id.split('.')
maxDepth = Math.max(maxDepth, splitId.length)
})
return maxDepth
+4 -7
View File
@@ -236,12 +236,9 @@ function useInstance(instance) {
let groupedFlatRows = []
// Recursively group the data
const groupRecursively = (rows, depth = 0, parentPath = []) => {
const groupRecursively = (rows, depth = 0) => {
// This is the last level, just return the rows
if (depth >= groupBy.length) {
rows.forEach(row => {
row.path = [...parentPath, ...row.path]
})
groupedFlatRows = groupedFlatRows.concat(rows)
return rows
}
@@ -254,13 +251,14 @@ function useInstance(instance) {
// Recurse to sub rows before aggregation
groupedRows = Object.entries(groupedRows).map(
([groupByVal, subRows], index) => {
const path = [...parentPath, `${columnId}:${groupByVal}`]
const id = `${columnId}:${groupByVal}`
subRows = groupRecursively(subRows, depth + 1, path)
subRows = groupRecursively(subRows, depth + 1)
const values = aggregateRowsToValues(subRows, depth < groupBy.length)
const row = {
id,
isAggregated: true,
groupByID: columnId,
groupByVal,
@@ -268,7 +266,6 @@ function useInstance(instance) {
subRows,
depth,
index,
path,
}
groupedFlatRows.push(row)
+88 -73
View File
@@ -13,7 +13,7 @@ const pluginName = 'useRowSelect'
// Actions
actions.resetSelectedRows = 'resetSelectedRows'
actions.toggleRowSelectedAll = 'toggleRowSelectedAll'
actions.toggleAllRowsSelected = 'toggleAllRowsSelected'
actions.toggleRowSelected = 'toggleRowSelected'
export const useRowSelect = hooks => {
@@ -47,6 +47,7 @@ const defaultGetToggleRowSelectedProps = (props, instance, row) => {
},
checked,
title: 'Toggle Row Selected',
indeterminate: row.isSomeSelected,
},
]
}
@@ -55,20 +56,23 @@ const defaultGetToggleAllRowsSelectedProps = (props, instance) => [
props,
{
onChange: e => {
instance.toggleRowSelectedAll(e.target.checked)
instance.toggleAllRowsSelected(e.target.checked)
},
style: {
cursor: 'pointer',
},
checked: instance.isAllRowsSelected,
title: 'Toggle All Rows Selected',
indeterminate: Boolean(
!instance.isAllRowsSelected && instance.state.selectedRowIds.size
),
},
]
function reducer(state, action, previousState, instanceRef) {
if (action.type === actions.init) {
return {
selectedRowPaths: new Set(),
selectedRowIds: new Set(),
...state,
}
}
@@ -76,103 +80,85 @@ function reducer(state, action, previousState, instanceRef) {
if (action.type === actions.resetSelectedRows) {
return {
...state,
selectedRowPaths: new Set(),
selectedRowIds: new Set(),
}
}
if (action.type === actions.toggleRowSelectedAll) {
if (action.type === actions.toggleAllRowsSelected) {
const { selected } = action
const { isAllRowsSelected, flatRowPaths } = instanceRef.current
const { isAllRowsSelected, flatRowsById } = instanceRef.current
const selectAll =
typeof selected !== 'undefined' ? selected : !isAllRowsSelected
return {
...state,
selectedRowPaths: selectAll ? new Set(flatRowPaths) : new Set(),
selectedRowIds: selectAll ? new Set(flatRowsById.keys()) : new Set(),
}
}
if (action.type === actions.toggleRowSelected) {
const { path, selected } = action
const { flatRowPaths } = instanceRef.current
const { id, selected } = action
const { flatGroupedRowsById } = instanceRef.current
const key = path.join('.')
const childRowPrefixKey = [key, '.'].join('')
// Join the paths of deep rows
// Join the ids of deep rows
// to make a key, then manage all of the keys
// in a flat object
const exists = state.selectedRowPaths.has(key)
const shouldExist = typeof set !== 'undefined' ? selected : !exists
const row = flatGroupedRowsById.get(id)
const isSelected = row.isSelected
const shouldExist = typeof set !== 'undefined' ? selected : !isSelected
let newSelectedRowPaths = new Set(state.selectedRowPaths)
if (!exists && shouldExist) {
flatRowPaths.forEach(rowPath => {
if (rowPath === key || rowPath.startsWith(childRowPrefixKey)) {
newSelectedRowPaths.add(rowPath)
}
})
} else if (exists && !shouldExist) {
flatRowPaths.forEach(rowPath => {
if (rowPath === key || rowPath.startsWith(childRowPrefixKey)) {
newSelectedRowPaths.delete(rowPath)
}
})
} else {
if (isSelected === shouldExist) {
return state
}
const updateParentRow = (selectedRowPaths, path) => {
const parentPath = path.slice(0, path.length - 1)
const parentKey = parentPath.join('.')
const selected =
flatRowPaths.filter(rowPath => {
const path = rowPath
return (
path !== parentKey &&
path.startsWith(parentKey) &&
!selectedRowPaths.has(path)
)
}).length === 0
if (selected) {
selectedRowPaths.add(parentKey)
} else {
selectedRowPaths.delete(parentKey)
let newSelectedRowPaths = new Set(state.selectedRowIds)
const handleRowById = id => {
const row = flatGroupedRowsById.get(id)
if (!row.isAggregated) {
if (!isSelected && shouldExist) {
newSelectedRowPaths.add(id)
} else if (isSelected && !shouldExist) {
newSelectedRowPaths.delete(id)
}
}
if (row.subRows) {
return row.subRows.forEach(row => handleRowById(row.id))
}
if (parentPath.length > 1) updateParentRow(selectedRowPaths, parentPath)
}
// If the row is a subRow update
// its parent row to reflect changes
if (path.length > 1) updateParentRow(newSelectedRowPaths, path)
handleRowById(id)
return {
...state,
selectedRowPaths: newSelectedRowPaths,
selectedRowIds: newSelectedRowPaths,
}
}
}
function useRows(rows, instance) {
const {
state: { selectedRowPaths },
state: { selectedRowIds },
} = instance
instance.selectedFlatRows = React.useMemo(() => {
const selectedFlatRows = []
rows.forEach(row => {
row.isSelected = getRowIsSelected(row, selectedRowPaths)
const isSelected = getRowIsSelected(row, selectedRowIds)
row.isSelected = !!isSelected
row.isSomeSelected = isSelected === null
if (row.isSelected) {
if (isSelected) {
selectedFlatRows.push(row)
}
})
return selectedFlatRows
}, [rows, selectedRowPaths])
}, [rows, selectedRowIds])
return rows
}
@@ -184,7 +170,7 @@ function useInstance(instance) {
plugins,
flatRows,
autoResetSelectedRows = true,
state: { selectedRowPaths },
state: { selectedRowIds },
dispatch,
} = instance
@@ -195,12 +181,24 @@ function useInstance(instance) {
[]
)
const flatRowPaths = flatRows.map(d => d.path.join('.'))
const [flatRowsById, flatGroupedRowsById] = React.useMemo(() => {
const map = new Map()
const groupedMap = new Map()
let isAllRowsSelected = !!flatRowPaths.length && !!selectedRowPaths.size
flatRows.forEach(row => {
if (!row.isAggregated) {
map.set(row.id, row)
}
groupedMap.set(row.id, row)
})
return [map, groupedMap]
}, [flatRows])
let isAllRowsSelected = Boolean(flatRowsById.size && selectedRowIds.size)
if (isAllRowsSelected) {
if (flatRowPaths.some(d => !selectedRowPaths.has(d))) {
if ([...flatRowsById.keys()].some(d => !selectedRowIds.has(d))) {
isAllRowsSelected = false
}
}
@@ -213,13 +211,12 @@ function useInstance(instance) {
}
}, [dispatch, data])
const toggleRowSelectedAll = selected =>
dispatch({ type: actions.toggleRowSelectedAll, selected })
const toggleAllRowsSelected = selected =>
dispatch({ type: actions.toggleAllRowsSelected, selected })
const toggleRowSelected = (path, selected) =>
dispatch({ type: actions.toggleRowSelected, path, selected })
const toggleRowSelected = (id, selected) =>
dispatch({ type: actions.toggleRowSelected, id, selected })
// use reference to avoid memory leak in #1608
const getInstance = useGetLatest(instance)
const getToggleAllRowsSelectedPropsHooks = useConsumeHookGetter(
@@ -238,7 +235,7 @@ function useInstance(instance) {
)
hooks.prepareRow.push(row => {
row.toggleRowSelected = set => toggleRowSelected(row.path, set)
row.toggleRowSelected = set => toggleRowSelected(row.id, set)
row.getToggleRowSelectedProps = makePropGetter(
getToggleRowSelectedPropsHooks(),
@@ -248,20 +245,38 @@ function useInstance(instance) {
})
Object.assign(instance, {
flatRowPaths,
flatRowsById,
flatGroupedRowsById,
toggleRowSelected,
toggleRowSelectedAll,
toggleAllRowsSelected,
getToggleAllRowsSelectedProps,
isAllRowsSelected,
})
}
function getRowIsSelected(row, selectedRowPaths) {
if (row.isAggregated) {
return row.subRows.every(subRow =>
getRowIsSelected(subRow, selectedRowPaths)
)
function getRowIsSelected(row, selectedRowIds) {
if (selectedRowIds.has(row.id)) {
return true
}
return selectedRowPaths.has(row.path.join('.'))
if (row.isAggregated || (row.subRows && row.subRows.length)) {
let allChildrenSelected = true
let someSelected = false
row.subRows.forEach(subRow => {
// Bail out early if we know both of these
if (someSelected && !allChildrenSelected) {
return
}
if (getRowIsSelected(subRow, selectedRowIds)) {
someSelected = true
} else {
allChildrenSelected = false
}
})
return allChildrenSelected ? true : someSelected ? null : false
}
return false
}
+8 -12
View File
@@ -34,15 +34,13 @@ function reducer(state, action) {
}
if (action.type === actions.setRowState) {
const { path, value } = action
const pathKey = path.join('.')
const { id, value } = action
return {
...state,
rowState: {
...state.rowState,
[pathKey]: functionalUpdate(value, state.rowState[pathKey] || {}),
[id]: functionalUpdate(value, state.rowState[id] || {}),
},
}
}
@@ -59,10 +57,10 @@ function useInstance(instance) {
} = instance
const setRowState = React.useCallback(
(path, value, columnId) =>
(id, value, columnId) =>
dispatch({
type: actions.setRowState,
path,
id,
value,
columnId,
}),
@@ -92,23 +90,21 @@ function useInstance(instance) {
)
hooks.prepareRow.push(row => {
const pathKey = row.path.join('.')
if (row.original) {
row.state =
(typeof rowState[pathKey] !== 'undefined'
? rowState[pathKey]
(typeof rowState[row.id] !== 'undefined'
? rowState[row.id]
: initialRowStateAccessor && initialRowStateAccessor(row)) || {}
row.setState = updater => {
return setRowState(row.path, updater)
return setRowState(row.id, updater)
}
row.cells.forEach(cell => {
cell.state = row.state.cellState || {}
cell.setState = updater => {
return setCellState(row.path, cell.column.id, updater)
return setCellState(row.id, cell.column.id, updater)
}
})
}