From bcd0da73793bc1bd9b630cff0d2daac1b5d83c38 Mon Sep 17 00:00:00 2001 From: Maximilian Brandau Date: Thu, 15 Aug 2019 16:57:22 +0200 Subject: [PATCH] fix: update colSpan (#1447) Only count visible columns for determining the colSpan fix #1446 --- src/hooks/useTable.js | 158 ++++++++++++------------ src/hooks/useTableState.js | 25 ++-- src/plugin-hooks/useExpanded.js | 51 ++++---- src/plugin-hooks/useFilters.js | 109 ++++++++--------- src/plugin-hooks/useGroupBy.js | 193 +++++++++++++++--------------- src/plugin-hooks/usePagination.js | 58 ++++----- src/plugin-hooks/useRowState.js | 19 ++- src/plugin-hooks/useSortBy.js | 26 ++-- 8 files changed, 314 insertions(+), 325 deletions(-) diff --git a/src/hooks/useTable.js b/src/hooks/useTable.js index 400049b..54a76c2 100755 --- a/src/hooks/useTable.js +++ b/src/hooks/useTable.js @@ -100,30 +100,27 @@ export const useTable = (props, ...plugins) => { ]) // Allow hooks to decorate columns (and trigger this memoization via deps) - columns = React.useMemo( - () => { - if (process.env.NODE_ENV === 'development' && debug) - console.time('hooks.columnsBeforeHeaderGroups') - const newColumns = applyHooks( - instanceRef.current.hooks.columnsBeforeHeaderGroups, - columns, - instanceRef.current - ) - if (process.env.NODE_ENV === 'development' && debug) - console.timeEnd('hooks.columnsBeforeHeaderGroups') - return newColumns - }, - [ + columns = React.useMemo(() => { + if (process.env.NODE_ENV === 'development' && debug) + console.time('hooks.columnsBeforeHeaderGroups') + const newColumns = applyHooks( + instanceRef.current.hooks.columnsBeforeHeaderGroups, columns, - debug, - // eslint-disable-next-line react-hooks/exhaustive-deps - ...applyHooks( - instanceRef.current.hooks.columnsBeforeHeaderGroupsDeps, - [], - instanceRef.current - ), - ] - ) + instanceRef.current + ) + if (process.env.NODE_ENV === 'development' && debug) + console.timeEnd('hooks.columnsBeforeHeaderGroups') + return newColumns + }, [ + columns, + debug, + // eslint-disable-next-line react-hooks/exhaustive-deps + ...applyHooks( + instanceRef.current.hooks.columnsBeforeHeaderGroupsDeps, + [], + instanceRef.current + ), + ]) // Make the headerGroups const headerGroups = React.useMemo( @@ -142,72 +139,69 @@ export const useTable = (props, ...plugins) => { }) // Access the row model - const [rows, rowPaths, flatRows] = React.useMemo( - () => { - if (process.env.NODE_ENV === 'development' && debug) - console.time('getAccessedRows') + const [rows, rowPaths, flatRows] = React.useMemo(() => { + if (process.env.NODE_ENV === 'development' && debug) + console.time('getAccessedRows') - let flatRows = 0 - const rowPaths = [] + let flatRows = 0 + const rowPaths = [] - // Access the row's data - const accessRow = (originalRow, i, depth = 0, parentPath = []) => { - // Keep the original reference around - const original = originalRow + // Access the row's data + const accessRow = (originalRow, i, depth = 0, parentPath = []) => { + // Keep the original reference around + const original = originalRow - // Make the new path for the row - const path = [...parentPath, i] + // Make the new path for the row + const path = [...parentPath, i] - flatRows++ - rowPaths.push(path.join('.')) + flatRows++ + rowPaths.push(path.join('.')) - // Process any subRows - const subRows = originalRow[subRowsKey] - ? originalRow[subRowsKey].map((d, i) => - accessRow(d, i, depth + 1, path) - ) - : [] - - const row = { - original, - index: i, - path, // used to create a key for each row even if not nested - subRows, - depth, - cells: [{}], // This is a dummy cell - } - - // Override common array functions (and the dummy cell's getCellProps function) - // to show an error if it is accessed without calling prepareRow - const unpreparedAccessWarning = () => { - throw new Error( - 'React-Table: You have not called prepareRow(row) one or more rows you are attempting to render.' + // Process any subRows + const subRows = originalRow[subRowsKey] + ? originalRow[subRowsKey].map((d, i) => + accessRow(d, i, depth + 1, path) ) - } - row.cells.map = unpreparedAccessWarning - row.cells.filter = unpreparedAccessWarning - row.cells.forEach = unpreparedAccessWarning - row.cells[0].getCellProps = unpreparedAccessWarning + : [] - // Create the cells and values - row.values = {} - instanceRef.current.columns.forEach(column => { - row.values[column.id] = column.accessor - ? column.accessor(originalRow, i, { subRows, depth, data }) - : undefined - }) - - return row + const row = { + original, + index: i, + path, // used to create a key for each row even if not nested + subRows, + depth, + cells: [{}], // This is a dummy cell } - // Use the resolved data - const accessedData = data.map((d, i) => accessRow(d, i)) - if (process.env.NODE_ENV === 'development' && debug) - console.timeEnd('getAccessedRows') - return [accessedData, rowPaths, flatRows] - }, - [debug, data, subRowsKey] - ) + // Override common array functions (and the dummy cell's getCellProps function) + // to show an error if it is accessed without calling prepareRow + const unpreparedAccessWarning = () => { + throw new Error( + 'React-Table: You have not called prepareRow(row) one or more rows you are attempting to render.' + ) + } + row.cells.map = unpreparedAccessWarning + row.cells.filter = unpreparedAccessWarning + row.cells.forEach = unpreparedAccessWarning + row.cells[0].getCellProps = unpreparedAccessWarning + + // Create the cells and values + row.values = {} + instanceRef.current.columns.forEach(column => { + row.values[column.id] = column.accessor + ? column.accessor(originalRow, i, { subRows, depth, data }) + : undefined + }) + + return row + } + + // Use the resolved data + const accessedData = data.map((d, i) => accessRow(d, i)) + if (process.env.NODE_ENV === 'development' && debug) + console.timeEnd('getAccessedRows') + return [accessedData, rowPaths, flatRows] + }, [debug, data, subRowsKey]) instanceRef.current.rows = rows instanceRef.current.rowPaths = rowPaths @@ -251,7 +245,9 @@ export const useTable = (props, ...plugins) => { mergeProps( { key: ['header', column.id].join('_'), - colSpan: column.columns ? column.columns.length : 1, + colSpan: column.columns + ? column.columns.filter(column => column.visible).length + : 1, }, applyPropHooks( instanceRef.current.hooks.getHeaderProps, diff --git a/src/hooks/useTableState.js b/src/hooks/useTableState.js index 7f60231..fe2f48a 100755 --- a/src/hooks/useTableState.js +++ b/src/hooks/useTableState.js @@ -16,20 +16,17 @@ export const useTableState = ( ...initialState, }) - const overriddenState = React.useMemo( - () => { - const newState = { - ...state, - } - if (overrides) { - Object.keys(overrides).forEach(key => { - newState[key] = overrides[key] - }) - } - return newState - }, - [overrides, state] - ) + const overriddenState = React.useMemo(() => { + const newState = { + ...state, + } + if (overrides) { + Object.keys(overrides).forEach(key => { + newState[key] = overrides[key] + }) + } + return newState + }, [overrides, state]) const overriddenStateRef = React.useRef() overriddenStateRef.current = overriddenState diff --git a/src/plugin-hooks/useExpanded.js b/src/plugin-hooks/useExpanded.js index 84067b3..b71a5ce 100755 --- a/src/plugin-hooks/useExpanded.js +++ b/src/plugin-hooks/useExpanded.js @@ -72,39 +72,36 @@ function useMain(instance) { return row }) - const expandedRows = useMemo( - () => { - if (process.env.NODE_ENV === 'development' && debug) - console.info('getExpandedRows') + const expandedRows = useMemo(() => { + if (process.env.NODE_ENV === 'development' && debug) + console.info('getExpandedRows') - const expandedRows = [] + const expandedRows = [] - // Here we do some mutation, but it's the last stage in the - // immutable process so this is safe - const handleRow = row => { - row.isExpanded = - (row.original && row.original[manualExpandedKey]) || - getBy(expanded, row.path) + // Here we do some mutation, but it's the last stage in the + // immutable process so this is safe + const handleRow = row => { + row.isExpanded = + (row.original && row.original[manualExpandedKey]) || + getBy(expanded, row.path) - if (!nestExpandedRows || (nestExpandedRows && row.depth === 0)) { - expandedRows.push(row) - } - - row.canExpand = row.subRows && !!row.subRows.length - - if (row.isExpanded && row.subRows && row.subRows.length) { - row.subRows.forEach(handleRow) - } - - return row + if (!nestExpandedRows || (nestExpandedRows && row.depth === 0)) { + expandedRows.push(row) } - rows.forEach(handleRow) + row.canExpand = row.subRows && !!row.subRows.length - return expandedRows - }, - [debug, rows, manualExpandedKey, expanded, nestExpandedRows] - ) + if (row.isExpanded && row.subRows && row.subRows.length) { + row.subRows.forEach(handleRow) + } + + return row + } + + rows.forEach(handleRow) + + return expandedRows + }, [debug, rows, manualExpandedKey, expanded, nestExpandedRows]) const expandedDepth = findExpandedDepth(expanded) diff --git a/src/plugin-hooks/useFilters.js b/src/plugin-hooks/useFilters.js index 1a610a8..8aa63f0 100755 --- a/src/plugin-hooks/useFilters.js +++ b/src/plugin-hooks/useFilters.js @@ -124,73 +124,68 @@ function useMain(instance) { // cache for each row group (top-level rows, and each row's recursive subrows) // This would make multi-filtering a lot faster though. Too far? - const filteredRows = React.useMemo( - () => { - if (manualFilters || !Object.keys(filters).length) { - return rows - } + const filteredRows = React.useMemo(() => { + if (manualFilters || !Object.keys(filters).length) { + return rows + } - if (process.env.NODE_ENV === 'development' && debug) - console.info('getFilteredRows') + if (process.env.NODE_ENV === 'development' && debug) + console.info('getFilteredRows') - // Filters top level and nested rows - const filterRows = rows => { - let filteredRows = rows + // Filters top level and nested rows + const filterRows = rows => { + let filteredRows = rows - filteredRows = Object.entries(filters).reduce( - (filteredSoFar, [columnID, filterValue]) => { - // Find the filters column - const column = columns.find(d => d.id === columnID) + filteredRows = Object.entries(filters).reduce( + (filteredSoFar, [columnID, filterValue]) => { + // Find the filters column + const column = columns.find(d => d.id === columnID) - if (!column) { - return filteredSoFar - } + if (!column) { + return filteredSoFar + } - column.preFilteredRows = filteredSoFar + column.preFilteredRows = filteredSoFar - const filterMethod = getFilterMethod( - column.filter, - userFilterTypes || {}, - filterTypes + const filterMethod = getFilterMethod( + column.filter, + userFilterTypes || {}, + filterTypes + ) + + if (!filterMethod) { + console.warn( + `Could not find a valid 'column.filter' for column with the ID: ${column.id}.` ) - - if (!filterMethod) { - console.warn( - `Could not find a valid 'column.filter' for column with the ID: ${ - column.id - }.` - ) - return filteredSoFar - } - - // Pass the rows, id, filterValue and column to the filterMethod - // to get the filtered rows back - return filterMethod(filteredSoFar, columnID, filterValue, column) - }, - rows - ) - - // Apply the filter to any subRows - // We technically could do this recursively in the above loop, - // but that would severely hinder the API for the user, since they - // would be required to do that recursion in some scenarios - filteredRows = filteredRows.map(row => { - if (!row.subRows) { - return row + return filteredSoFar } - return { - ...row, - subRows: filterRows(row.subRows), - } - }) - return filteredRows - } + // Pass the rows, id, filterValue and column to the filterMethod + // to get the filtered rows back + return filterMethod(filteredSoFar, columnID, filterValue, column) + }, + rows + ) - return filterRows(rows) - }, - [manualFilters, filters, debug, rows, columns, userFilterTypes] - ) + // Apply the filter to any subRows + // We technically could do this recursively in the above loop, + // but that would severely hinder the API for the user, since they + // would be required to do that recursion in some scenarios + filteredRows = filteredRows.map(row => { + if (!row.subRows) { + return row + } + return { + ...row, + subRows: filterRows(row.subRows), + } + }) + + return filteredRows + } + + return filterRows(rows) + }, [manualFilters, filters, debug, rows, columns, userFilterTypes]) return { ...instance, diff --git a/src/plugin-hooks/useGroupBy.js b/src/plugin-hooks/useGroupBy.js index 0697a91..cbfd2f2 100755 --- a/src/plugin-hooks/useGroupBy.js +++ b/src/plugin-hooks/useGroupBy.js @@ -146,110 +146,115 @@ function useMain(instance) { return row }) - const groupedRows = useMemo( - () => { - if (manualGroupBy || !groupBy.length) { + const groupedRows = useMemo(() => { + if (manualGroupBy || !groupBy.length) { + return rows + } + + if (process.env.NODE_ENV === 'development' && debug) + console.info('getGroupedRows') + // Find the columns that can or are aggregating + + // Uses each column to aggregate rows into a single value + const aggregateRowsToValues = (rows, isSourceRows) => { + const values = {} + + columns.forEach(column => { + // Don't aggregate columns that are in the groupBy + if (groupBy.includes(column.id)) { + values[column.id] = rows[0] ? rows[0].values[column.id] : null + return + } + + const columnValues = rows.map(d => d.values[column.id]) + + let aggregator = column.aggregate + + if (Array.isArray(aggregator)) { + if (aggregator.length !== 2) { + console.info({ column }) + throw new Error( + `React Table: Complex aggregators must have 2 values, eg. aggregate: ['sum', 'count']. More info above...` + ) + } + if (isSourceRows) { + aggregator = aggregator[1] + } else { + aggregator = aggregator[0] + } + } + + let aggregateFn = + typeof aggregator === 'function' + ? aggregator + : userAggregations[aggregator] || aggregations[aggregator] + + if (aggregateFn) { + values[column.id] = aggregateFn(columnValues, rows) + } else if (aggregator) { + console.info({ column }) + throw new Error( + `React Table: Invalid aggregate option for column listed above` + ) + } else { + values[column.id] = null + } + }) + return values + } + + // Recursively group the data + const groupRecursively = (rows, depth = 0, parentPath = []) => { + // This is the last level, just return the rows + if (depth >= groupBy.length) { return rows } - if (process.env.NODE_ENV === 'development' && debug) - console.info('getGroupedRows') - // Find the columns that can or are aggregating + const columnID = groupBy[depth] - // Uses each column to aggregate rows into a single value - const aggregateRowsToValues = (rows, isSourceRows) => { - const values = {} + // Group the rows together for this level + let groupedRows = groupByFn(rows, columnID) - columns.forEach(column => { - // Don't aggregate columns that are in the groupBy - if (groupBy.includes(column.id)) { - values[column.id] = rows[0] ? rows[0].values[column.id] : null - return + // Recurse to sub rows before aggregation + groupedRows = Object.entries(groupedRows).map( + ([groupByVal, subRows], index) => { + const path = [...parentPath, groupByVal] + + subRows = groupRecursively(subRows, depth + 1, path) + + const values = aggregateRowsToValues( + subRows, + depth + 1 >= groupBy.length + ) + + const row = { + groupByID: columnID, + groupByVal, + values, + subRows, + depth, + index, + path, } - const columnValues = rows.map(d => d.values[column.id]) - - let aggregator = column.aggregate - - if (Array.isArray(aggregator)) { - if (aggregator.length !== 2) { - console.info({ column }) - throw new Error( - `React Table: Complex aggregators must have 2 values, eg. aggregate: ['sum', 'count']. More info above...` - ) - } - if (isSourceRows) { - aggregator = aggregator[1] - } else { - aggregator = aggregator[0] - } - } - - let aggregateFn = - typeof aggregator === 'function' - ? aggregator - : userAggregations[aggregator] || aggregations[aggregator] - - if (aggregateFn) { - values[column.id] = aggregateFn(columnValues, rows) - } else if (aggregator) { - console.info({ column }) - throw new Error( - `React Table: Invalid aggregate option for column listed above` - ) - } else { - values[column.id] = null - } - }) - return values - } - - // Recursively group the data - const groupRecursively = (rows, depth = 0, parentPath = []) => { - // This is the last level, just return the rows - if (depth >= groupBy.length) { - return rows + return row } + ) - const columnID = groupBy[depth] + return groupedRows + } - // Group the rows together for this level - let groupedRows = groupByFn(rows, columnID) - - // Recurse to sub rows before aggregation - groupedRows = Object.entries(groupedRows).map( - ([groupByVal, subRows], index) => { - const path = [...parentPath, groupByVal] - - subRows = groupRecursively(subRows, depth + 1, path) - - const values = aggregateRowsToValues( - subRows, - depth + 1 >= groupBy.length - ) - - const row = { - groupByID: columnID, - groupByVal, - values, - subRows, - depth, - index, - path, - } - - return row - } - ) - - return groupedRows - } - - // Assign the new data - return groupRecursively(rows) - }, - [manualGroupBy, groupBy, debug, rows, columns, userAggregations, groupByFn] - ) + // Assign the new data + return groupRecursively(rows) + }, [ + manualGroupBy, + groupBy, + debug, + rows, + columns, + userAggregations, + groupByFn, + ]) return { ...instance, diff --git a/src/plugin-hooks/usePagination.js b/src/plugin-hooks/usePagination.js index a2ed4cd..2e1127a 100755 --- a/src/plugin-hooks/usePagination.js +++ b/src/plugin-hooks/usePagination.js @@ -50,43 +50,37 @@ function useMain(instance) { const rowDep = manualPagination || disablePageResetOnDataChange ? null : rows - useLayoutEffect( - () => { - setState( - old => ({ - ...old, - pageIndex: 0, - }), - actions.pageChange - ) - }, - [setState, rowDep, filters, groupBy, sortBy] - ) + useLayoutEffect(() => { + setState( + old => ({ + ...old, + pageIndex: 0, + }), + actions.pageChange + ) + }, [setState, rowDep, filters, groupBy, sortBy]) - const pages = React.useMemo( - () => { - if (manualPagination) { - return undefined - } - if (process.env.NODE_ENV === 'development' && debug) - console.info('getPages') + const pages = React.useMemo(() => { + if (manualPagination) { + return undefined + } + if (process.env.NODE_ENV === 'development' && debug) + console.info('getPages') - // Create a new pages with the first page ready to go. - const pages = rows.length ? [] : [[]] + // Create a new pages with the first page ready to go. + const pages = rows.length ? [] : [[]] - // Start the pageIndex and currentPage cursors - let cursor = 0 + // Start the pageIndex and currentPage cursors + let cursor = 0 - while (cursor < rows.length) { - const end = cursor + pageSize - pages.push(rows.slice(cursor, end)) - cursor = end - } + while (cursor < rows.length) { + const end = cursor + pageSize + pages.push(rows.slice(cursor, end)) + cursor = end + } - return pages - }, - [debug, manualPagination, pageSize, rows] - ) + return pages + }, [debug, manualPagination, pageSize, rows]) const pageCount = manualPagination ? userPageCount : pages.length diff --git a/src/plugin-hooks/useRowState.js b/src/plugin-hooks/useRowState.js index 91e26ec..0f91a53 100644 --- a/src/plugin-hooks/useRowState.js +++ b/src/plugin-hooks/useRowState.js @@ -70,17 +70,14 @@ function useMain(instance) { ) // When data changes, reset row and cell state - React.useEffect( - () => { - setState(old => { - return { - ...old, - rowState: {}, - } - }, actions.setRowState) - }, - [rows, setState] - ) + React.useEffect(() => { + setState(old => { + return { + ...old, + rowState: {}, + } + }, actions.setRowState) + }, [rows, setState]) hooks.prepareRow.push(row => { const pathKey = row.path.join('.') diff --git a/src/plugin-hooks/useSortBy.js b/src/plugin-hooks/useSortBy.js index 773d323..8d9e2ba 100755 --- a/src/plugin-hooks/useSortBy.js +++ b/src/plugin-hooks/useSortBy.js @@ -255,19 +255,27 @@ function useMain(instance) { if (!row.subRows || row.subRows.length <= 1) { return } - row.subRows = sortData(row.subRows) + + return !sort.desc }) + ) - return sortedData - } + // If there are sub-rows, sort them + sortedData.forEach(row => { + if (!row.subRows) { + return + } + row.subRows = sortData(row.subRows) + }) - if (process.env.NODE_ENV === 'development' && debug) - console.timeEnd('getSortedRows') + return sortedData + } - return sortData(rows) - }, - [manualSorting, sortBy, debug, columns, rows, orderByFn, userSortTypes] - ) + if (process.env.NODE_ENV === 'development' && debug) + console.timeEnd('getSortedRows') + + return sortData(rows) + }, [manualSorting, sortBy, debug, columns, rows, orderByFn, userSortTypes]) return { ...instance,