From 9156534443098b8dbb6076f1fc7c40ba4e0c4e42 Mon Sep 17 00:00:00 2001 From: Patrick Riley Date: Tue, 16 Apr 2019 16:30:09 -0400 Subject: [PATCH] feat(virtualized): add virtualized table extensions --- jest.config.js | 55 +- .../patternfly-4/react-docs/gatsby-config.js | 3 +- .../patternfly-4/react-docs/gatsby-node.js | 1 + packages/patternfly-4/react-docs/package.json | 1 + .../patternfly-4/react-table/package.json | 7 +- .../react-table/src/components/Table/Body.js | 10 +- .../src/components/Table/BodyWrapper.js | 26 +- .../src/components/Table/Header.js | 2 +- .../react-table/src/components/Table/Table.js | 17 +- .../Table/__snapshots__/Table.test.js.snap | 152 ++ .../src/components/Table/base/body-row.js | 85 + .../src/components/Table/base/body.js | 67 + .../Table/base/columns-are-equal.js | 19 + .../Table/base/evaluate-formatters.js | 18 + .../Table/base/evaluate-transforms.js | 24 + .../src/components/Table/base/header-row.js | 45 + .../src/components/Table/base/header.js | 38 + .../src/components/Table/base/index.js | 9 + .../src/components/Table/base/merge-props.js | 36 + .../src/components/Table/base/provider.js | 56 + .../components/Table/base/resolve-row-key.js | 31 + .../src/components/Table/base/types.js | 107 ++ .../react-table/src/components/Table/index.js | 1 + .../react-virtualized-extension/.babelrc | 6 + .../react-virtualized-extension/.npmignore | 1 + .../react-virtualized-extension/README.md | 5 + .../build/copyStyles.js | 42 + .../build/snapshot-serializer.js | 8 + .../react-virtualized-extension/package.json | 65 + .../scripts/copyTS.js | 15 + .../Virtualized/VirtualGrid.example.css | 326 ++++ .../src/components/Virtualized/VirtualGrid.js | 1472 +++++++++++++++++ .../Virtualized/VirtualTableBody.js | 287 ++++ .../src/components/Virtualized/Virtualized.md | 590 +++++++ .../Virtualized/WindowScroller.example.css | 7 + .../components/Virtualized/WindowScroller.md | 181 ++ .../accessibilityOverscanIndicesGetter.js | 38 + .../Virtualized/defaultCellRangeRenderer.js | 155 ++ .../defaultOverscanIndicesGetter.js | 33 + .../src/components/Virtualized/index.js | 3 + .../src/components/Virtualized/types.js | 115 ++ .../utils/CellSizeAndPositionManager.js | 255 +++ .../ScalingCellSizeAndPositionManager.js | 190 +++ .../Virtualized/utils/animationFrame.js | 41 + ...izeAndPositionDataAndUpdateScrollOffset.js | 61 + .../utils/createCallbackMemoizer.js | 32 + .../Virtualized/utils/maxElementSize.js | 17 + .../utils/requestAnimationTimeout.js | 39 + .../utils/updateScrollIndexHelper.js | 92 ++ .../src/components/index.js | 1 + .../react-virtualized-extension/src/index.js | 1 + yarn.lock | 20 +- 52 files changed, 4854 insertions(+), 54 deletions(-) create mode 100644 packages/patternfly-4/react-table/src/components/Table/base/body-row.js create mode 100644 packages/patternfly-4/react-table/src/components/Table/base/body.js create mode 100644 packages/patternfly-4/react-table/src/components/Table/base/columns-are-equal.js create mode 100644 packages/patternfly-4/react-table/src/components/Table/base/evaluate-formatters.js create mode 100644 packages/patternfly-4/react-table/src/components/Table/base/evaluate-transforms.js create mode 100644 packages/patternfly-4/react-table/src/components/Table/base/header-row.js create mode 100644 packages/patternfly-4/react-table/src/components/Table/base/header.js create mode 100644 packages/patternfly-4/react-table/src/components/Table/base/index.js create mode 100644 packages/patternfly-4/react-table/src/components/Table/base/merge-props.js create mode 100644 packages/patternfly-4/react-table/src/components/Table/base/provider.js create mode 100644 packages/patternfly-4/react-table/src/components/Table/base/resolve-row-key.js create mode 100644 packages/patternfly-4/react-table/src/components/Table/base/types.js create mode 100644 packages/patternfly-4/react-virtualized-extension/.babelrc create mode 100644 packages/patternfly-4/react-virtualized-extension/.npmignore create mode 100644 packages/patternfly-4/react-virtualized-extension/README.md create mode 100644 packages/patternfly-4/react-virtualized-extension/build/copyStyles.js create mode 100644 packages/patternfly-4/react-virtualized-extension/build/snapshot-serializer.js create mode 100644 packages/patternfly-4/react-virtualized-extension/package.json create mode 100644 packages/patternfly-4/react-virtualized-extension/scripts/copyTS.js create mode 100644 packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/VirtualGrid.example.css create mode 100644 packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/VirtualGrid.js create mode 100644 packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/VirtualTableBody.js create mode 100644 packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/Virtualized.md create mode 100644 packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/WindowScroller.example.css create mode 100644 packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/WindowScroller.md create mode 100644 packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/accessibilityOverscanIndicesGetter.js create mode 100644 packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/defaultCellRangeRenderer.js create mode 100644 packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/defaultOverscanIndicesGetter.js create mode 100644 packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/index.js create mode 100644 packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/types.js create mode 100644 packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/CellSizeAndPositionManager.js create mode 100644 packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/ScalingCellSizeAndPositionManager.js create mode 100644 packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/animationFrame.js create mode 100644 packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/calculateSizeAndPositionDataAndUpdateScrollOffset.js create mode 100644 packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/createCallbackMemoizer.js create mode 100644 packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/maxElementSize.js create mode 100644 packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/requestAnimationTimeout.js create mode 100644 packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/updateScrollIndexHelper.js create mode 100644 packages/patternfly-4/react-virtualized-extension/src/components/index.js create mode 100644 packages/patternfly-4/react-virtualized-extension/src/index.js diff --git a/jest.config.js b/jest.config.js index cd352076dda..a5d66cd9119 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,53 +1,46 @@ module.exports = { collectCoverage: true, clearMocks: true, - coverageReporters: [ - "lcov" - ], + coverageReporters: ['lcov'], modulePathIgnorePatterns: [ - "/packages/*.*/dist/*.*", - "/packages/*.*/public/*.*", - "/packages/*.*/.cache/*.*" + '/packages/*.*/dist/*.*', + '/packages/*.*/public/*.*', + '/packages/*.*/.cache/*.*' ], coveragePathIgnorePatterns: [ - "/packages/*.*/dist/*.*", - "/packages/*.*/examples/*.*", - "/packages/*.docs.*", - "/packages/react-docs/*.*" + '/packages/*.*/dist/*.*', + '/packages/*.*/examples/*.*', + '/packages/*.docs.*', + '/packages/react-docs/*.*' ], modulePaths: [ - "/**/node_modules/", - "/packages/", - "/packages/patternfly-3/", - "/packages/patternfly-4/" - ], - roots: [ - "/packages" - ], - setupFiles: [ - "./test.env.js" + '/**/node_modules/', + '/packages/', + '/packages/patternfly-3/', + '/packages/patternfly-4/' ], + roots: ['/packages'], + setupFiles: ['./test.env.js'], snapshotSerializers: [ "enzyme-to-json/serializer", "/packages/patternfly-4/react-core/scripts/snapshot-serializer" ], transform: { - "^.+\\.(ts|tsx)?$": "ts-jest", - "^.+\\.jsx?$": "babel-jest", - "\\.(css)$": "/packages/patternfly-4/react-styles/jest-transform.js" + '^.+\\.(ts|tsx)?$': 'ts-jest', + '^.+\\.jsx?$': 'babel-jest', + '\\.(css)$': '/packages/patternfly-4/react-styles/jest-transform.js' }, testPathIgnorePatterns: [ - "/scripts/generators/", - "/packages/patternfly-4/react-integration/" - ], - transformIgnorePatterns: [ - "node_modules/(?!@patternfly|@novnc|tippy.js)" + '/scripts/generators/', + '/packages/patternfly-4/react-integration/', + '/node_modules/(?!lodash-es/.*)' ], + transformIgnorePatterns: ['node_modules/(?!@patternfly|@novnc|tippy.js|lodash-es)'], // https://github.com/kulshekhar/ts-jest/blob/master/docs/user/config/index.md - preset: "ts-jest/presets/js-with-babel", + preset: 'ts-jest/presets/js-with-babel', globals: { - "ts-jest": { - tsConfig: "packages/patternfly-4/react-core/tsconfig.jest.json" + 'ts-jest': { + tsConfig: 'packages/patternfly-4/react-core/tsconfig.jest.json' } } }; diff --git a/packages/patternfly-4/react-docs/gatsby-config.js b/packages/patternfly-4/react-docs/gatsby-config.js index cfefa3f8afb..c5c65b1d2d9 100644 --- a/packages/patternfly-4/react-docs/gatsby-config.js +++ b/packages/patternfly-4/react-docs/gatsby-config.js @@ -63,6 +63,7 @@ module.exports = { } }, // The plugin for package.json files (to get version numbers) - `gatsby-transformer-json` + `gatsby-transformer-json`, + `gatsby-plugin-flow` ] }; diff --git a/packages/patternfly-4/react-docs/gatsby-node.js b/packages/patternfly-4/react-docs/gatsby-node.js index 047a7043085..68c746a33d7 100644 --- a/packages/patternfly-4/react-docs/gatsby-node.js +++ b/packages/patternfly-4/react-docs/gatsby-node.js @@ -91,6 +91,7 @@ exports.onCreateWebpackConfig = ({ actions }) => { '@patternfly/react-core': path.resolve(__dirname, '../react-core'), '@patternfly/react-icons': path.resolve(__dirname, '../../react-icons'), '@patternfly/react-inline-edit-extension': path.resolve(__dirname, '../react-inline-edit-extension'), + '@patternfly/react-virtualized-extension': path.resolve(__dirname, '../react-virtualized-extension'), '@patternfly/react-styled-system': path.resolve(__dirname, '../react-styled-system'), '@patternfly/react-styles': path.resolve(__dirname, '../react-styles'), '@patternfly/react-table': path.resolve(__dirname, '../react-table'), diff --git a/packages/patternfly-4/react-docs/package.json b/packages/patternfly-4/react-docs/package.json index 513227422b6..287e5403912 100644 --- a/packages/patternfly-4/react-docs/package.json +++ b/packages/patternfly-4/react-docs/package.json @@ -21,6 +21,7 @@ "@patternfly/react-icons": "^3.9.3", "gatsby": "2.3.14", "gatsby-mdx": "0.6.3", + "gatsby-plugin-flow": "^1.0.5", "gatsby-plugin-react-helmet": "^3.0.11", "gatsby-plugin-sass": "^2.0.11", "gatsby-source-filesystem": "^2.0.28", diff --git a/packages/patternfly-4/react-table/package.json b/packages/patternfly-4/react-table/package.json index 3e35ccff605..3cfba139f3f 100644 --- a/packages/patternfly-4/react-table/package.json +++ b/packages/patternfly-4/react-table/package.json @@ -31,13 +31,14 @@ "@patternfly/react-core": "^3.36.0", "@patternfly/react-icons": "^3.9.3", "@patternfly/react-styles": "^3.3.0", - "exenv": "^1.2.2", - "reactabular-table": "^8.14.0" + "classnames": "^2.2.5", + "exenv": "^1.2.2" }, "peerDependencies": { "prop-types": "^15.6.1", "react": "^16.4.0", - "react-dom": "^15.6.2 || ^16.4.0" + "react-dom": "^15.6.2 || ^16.4.0", + "lodash-es": "4.x" }, "scripts": { "build": "yarn build:babel && node ./scripts/copyTS.js && node ./build/copyStyles.js", diff --git a/packages/patternfly-4/react-table/src/components/Table/Body.js b/packages/patternfly-4/react-table/src/components/Table/Body.js index 0d80e7d1725..f242b41824a 100644 --- a/packages/patternfly-4/react-table/src/components/Table/Body.js +++ b/packages/patternfly-4/react-table/src/components/Table/Body.js @@ -1,5 +1,5 @@ import React from 'react'; -import { Body } from 'reactabular-table'; +import { Body } from './base'; import PropTypes from 'prop-types'; import { TableContext } from './Table'; import { isRowExpanded } from './utils'; @@ -29,10 +29,14 @@ const flagVisibility = rows => { class ContextBody extends React.Component { onRow = (row, rowProps) => { - const { onRowClick } = this.props; + const { onRowClick, onRow } = this.props; + const extendedRowProps = { + ...rowProps, + ...(onRow ? onRow(row, rowProps) : {}) + }; return { row, - rowProps, + rowProps: extendedRowProps, onMouseDown: event => { const computedData = { isInput: event.target.tagName !== 'INPUT', diff --git a/packages/patternfly-4/react-table/src/components/Table/BodyWrapper.js b/packages/patternfly-4/react-table/src/components/Table/BodyWrapper.js index 4cff7139326..9b3c17cc0db 100644 --- a/packages/patternfly-4/react-table/src/components/Table/BodyWrapper.js +++ b/packages/patternfly-4/react-table/src/components/Table/BodyWrapper.js @@ -7,30 +7,42 @@ import { mapOpenedRows } from './utils/headerUtils'; // eslint-disable-next-line react/prefer-stateless-function class BodyWrapper extends React.Component { render() { - const { children, mappedRows, ...props } = this.props; - if (mappedRows.some(row => row.hasOwnProperty('parent'))) { + const { mappedRows, tbodyRef, ...props } = this.props; + if (mappedRows && mappedRows.some(row => row.hasOwnProperty('parent'))) { return ( - {mapOpenedRows(mappedRows, children).map((oneRow, key) => ( - + {mapOpenedRows(mappedRows, this.props.children).map((oneRow, key) => ( + {oneRow.rows} ))} ); } - return {children}; + + return ; } } BodyWrapper.propTypes = { children: PropTypes.node, - mappedRows: PropTypes.array + mappedRows: PropTypes.array, + rows: PropTypes.array, + onCollapse: PropTypes.func, + tbodyRef: PropTypes.func }; BodyWrapper.defaultProps = { children: null, - mappedRows: undefined + mappedRows: undefined, + rows: [], + onCollapse: null, + tbodyRef: null }; export default BodyWrapper; diff --git a/packages/patternfly-4/react-table/src/components/Table/Header.js b/packages/patternfly-4/react-table/src/components/Table/Header.js index d12c831f646..5da0f03b89f 100644 --- a/packages/patternfly-4/react-table/src/components/Table/Header.js +++ b/packages/patternfly-4/react-table/src/components/Table/Header.js @@ -1,5 +1,5 @@ import React from 'react'; -import { Header } from 'reactabular-table'; +import { Header } from './base'; import PropTypes from 'prop-types'; import { TableContext } from './Table'; diff --git a/packages/patternfly-4/react-table/src/components/Table/Table.js b/packages/patternfly-4/react-table/src/components/Table/Table.js index b6e98285180..302bd677e9f 100644 --- a/packages/patternfly-4/react-table/src/components/Table/Table.js +++ b/packages/patternfly-4/react-table/src/components/Table/Table.js @@ -1,7 +1,7 @@ import React from 'react'; import styles from '@patternfly/react-styles/css/components/Table/table'; import stylesGrid from '@patternfly/react-styles/css/components/Table/table-grid'; -import { Provider } from 'reactabular-table'; +import { Provider } from './base'; import { DropdownPosition, DropdownDirection } from '@patternfly/react-core'; import { css, getModifier } from '@patternfly/react-styles'; import PropTypes from 'prop-types'; @@ -125,25 +125,26 @@ const propTypes = { dropdownDirection: PropTypes.oneOf(Object.values(DropdownDirection)), /** Header to display above table for accessibility reasons. */ header: props => { - if (!props['aria-label'] && !props.caption && !props.header) { + if (!props['aria-label'] && !props.caption && !props.header && !props.role === 'presentation') { throw new Error('Specify at least one of: header, caption, aria-label'); } return null; }, /** Caption to display in table for accessibility reasons. */ caption: props => { - if (!props['aria-label'] && !props.caption && !props.header) { + if (!props['aria-label'] && !props.caption && !props.header && !props.role === 'presentation') { throw new Error('Specify at least one of: header, caption, aria-label'); } return null; }, /** aria-label in table for accessibility reasons. */ 'aria-label': props => { - if (!props['aria-label'] && !props.caption && !props.header) { + if (!props['aria-label'] && !props.caption && !props.header && !props.role === 'presentation') { throw new Error('Specify at least one of: header, caption, aria-label'); } return null; - } + }, + role: PropTypes.string }; const defaultProps = { @@ -169,7 +170,8 @@ const defaultProps = { header: undefined, caption: undefined, 'aria-label': undefined, - gridBreakPoint: TableGridBreakpoint.gridMd + gridBreakPoint: TableGridBreakpoint.gridMd, + role: 'grid' }; export const TableContext = React.createContext(); @@ -206,6 +208,7 @@ class Table extends React.Component { bodyWrapper, rowWrapper, borders, + role, ...props } = this.props; @@ -248,7 +251,7 @@ class Table extends React.Component { } }} columns={headerData} - role="grid" + role={role} className={css( styles.table, gridBreakPoint && getModifier(stylesGrid, gridBreakPoint), diff --git a/packages/patternfly-4/react-table/src/components/Table/__snapshots__/Table.test.js.snap b/packages/patternfly-4/react-table/src/components/Table/__snapshots__/Table.test.js.snap index 31f123e8efb..d7d431c25c4 100644 --- a/packages/patternfly-4/react-table/src/components/Table/__snapshots__/Table.test.js.snap +++ b/packages/patternfly-4/react-table/src/components/Table/__snapshots__/Table.test.js.snap @@ -32,6 +32,7 @@ exports[`Actions table 1`] = ` gridBreakPoint="grid-md" onCollapse={null} onExpand={null} + role="grid" rowLabeledBy="simple-node" rows={ Array [ @@ -2398,9 +2399,14 @@ exports[`Actions table 1`] = ` }, ] } + onCollapse={null} + rows={Array []} + tbodyRef={null} > { + const { property, cell, props } = column; + const evaluatedProperty = property || (cell && cell.property); + const { + transforms = [], + formatters = [] + } = cell || {}; // TODO: test against this case + const extraParameters = { + columnIndex, + property: evaluatedProperty, + column, + rowData, + rowIndex, + rowKey + }; + const transformed = evaluateTransforms(transforms, rowData[evaluatedProperty], extraParameters); + + if (!transformed) { + console.warn('Table.Body - Failed to receive a transformed result'); // eslint-disable-line max-len, no-console + } + + return React.createElement( + renderers.cell, + { + key: `${columnIndex}-cell`, + ...mergeProps( + props, + cell && cell.props, + transformed + ) + }, + transformed.children || evaluateFormatters(formatters)(rowData[`_${evaluatedProperty}`] || + rowData[evaluatedProperty], extraParameters) + ); + }) + ); + } +} +BodyRow.defaultProps = tableBodyRowDefaults; +BodyRow.propTypes = tableBodyRowTypes; + +export default BodyRow; \ No newline at end of file diff --git a/packages/patternfly-4/react-table/src/components/Table/base/body.js b/packages/patternfly-4/react-table/src/components/Table/base/body.js new file mode 100644 index 00000000000..7c3b2e8e373 --- /dev/null +++ b/packages/patternfly-4/react-table/src/components/Table/base/body.js @@ -0,0 +1,67 @@ +/** + * body.js + * + * Forked from reactabular-table version 8.14.0 + * https://github.com/reactabular/reactabular/tree/v8.14.0/packages/reactabular-table/src + * */ +import { isEqual, isFunction } from 'lodash-es'; +import React from 'react'; +import { tableBodyTypes, tableBodyDefaults, tableBodyContextTypes } from './types'; +import BodyRow from './body-row'; +import resolveRowKey from './resolve-row-key'; + +class Body extends React.Component { + shouldComponentUpdate(nextProps, nextState, nextContext) { + // eslint-disable-line no-unused-vars + // Skip checking props against `onRow` since that can be bound at render(). + // That's not particularly good practice but you never know how the users + // prefer to define the handler. + + // Check for wrapper based override. + const { renderers } = nextContext; + + if (renderers && renderers.body && renderers.body.wrapper.shouldComponentUpdate) { + if (isFunction(renderers.body.wrapper.shouldComponentUpdate)) { + return renderers.body.wrapper.shouldComponentUpdate.call(this, nextProps, nextState, nextContext); + } + + return true; + } + + return !(isEqual(omitOnRow(this.props), omitOnRow(nextProps)) && isEqual(this.context, nextContext)); + } + render() { + const { onRow, rows, rowKey, ...props } = this.props; + const { columns, renderers } = this.context; + + return React.createElement( + renderers.body.wrapper, + props, + rows.map((rowData, index) => { + const rowIndex = rowData._index || index; + const key = resolveRowKey({ rowData, rowIndex, rowKey }); + + return React.createElement(BodyRow, { + key, + renderers: renderers.body, + onRow, + rowKey: key, + rowIndex, + rowData, + columns + }); + }) + ); + } +} +Body.propTypes = tableBodyTypes; +Body.defaultProps = tableBodyDefaults; +Body.contextTypes = tableBodyContextTypes; + +function omitOnRow(props) { + const { onRow, ...ret } = props; // eslint-disable-line no-unused-vars + + return ret; +} + +export default Body; diff --git a/packages/patternfly-4/react-table/src/components/Table/base/columns-are-equal.js b/packages/patternfly-4/react-table/src/components/Table/base/columns-are-equal.js new file mode 100644 index 00000000000..9541dad5bea --- /dev/null +++ b/packages/patternfly-4/react-table/src/components/Table/base/columns-are-equal.js @@ -0,0 +1,19 @@ +/** + * columns-are-equal.js + * + * Forked from reactabular-table version 8.14.0 + * https://github.com/reactabular/reactabular/tree/v8.14.0/packages/reactabular-table/src + * */ +import { isFunction, isEqualWith } from 'lodash-es'; + +function columnsAreEqual(oldColumns, newColumns) { + return isEqualWith(oldColumns, newColumns, (a, b) => { + if (isFunction(a) && isFunction(b)) { + return true; + } + + return undefined; + }); +} + +export default columnsAreEqual; diff --git a/packages/patternfly-4/react-table/src/components/Table/base/evaluate-formatters.js b/packages/patternfly-4/react-table/src/components/Table/base/evaluate-formatters.js new file mode 100644 index 00000000000..cf0cfe47be1 --- /dev/null +++ b/packages/patternfly-4/react-table/src/components/Table/base/evaluate-formatters.js @@ -0,0 +1,18 @@ +/** + * evaluate-formatters.js + * + * Forked from reactabular-table version 8.14.0 + * https://github.com/reactabular/reactabular/tree/v8.14.0/packages/reactabular-table/src + * */ +function evaluateFormatters(formatters) { + return (value, extra) => + formatters.reduce( + (parameters, formatter) => ({ + value: formatter(parameters.value, parameters.extra), + extra + }), + { value, extra } + ).value; +} + +export default evaluateFormatters; diff --git a/packages/patternfly-4/react-table/src/components/Table/base/evaluate-transforms.js b/packages/patternfly-4/react-table/src/components/Table/base/evaluate-transforms.js new file mode 100644 index 00000000000..b0e7deed564 --- /dev/null +++ b/packages/patternfly-4/react-table/src/components/Table/base/evaluate-transforms.js @@ -0,0 +1,24 @@ +/** + * evaluate-transforms.js + * + * Forked from reactabular-table version 8.14.0 + * https://github.com/reactabular/reactabular/tree/v8.14.0/packages/reactabular-table/src + * */ +import { isFunction } from 'lodash-es'; +import mergeProps from './merge-props'; + +function evaluateTransforms(transforms = [], value, extraParameters = {}) { + if (process.env.NODE_ENV !== 'production') { + if (!transforms.every(isFunction)) { + throw new Error("All transforms weren't functions!", transforms); + } + } + + if (transforms.length === 0) { + return {}; + } + + return mergeProps(...transforms.map(transform => transform(value, extraParameters))); +} + +export default evaluateTransforms; diff --git a/packages/patternfly-4/react-table/src/components/Table/base/header-row.js b/packages/patternfly-4/react-table/src/components/Table/base/header-row.js new file mode 100644 index 00000000000..f4925b14477 --- /dev/null +++ b/packages/patternfly-4/react-table/src/components/Table/base/header-row.js @@ -0,0 +1,45 @@ +/** + * header-row.js + * + * Forked from reactabular-table version 8.14.0 + * https://github.com/reactabular/reactabular/tree/v8.14.0/packages/reactabular-table/src + * */ +import React from 'react'; +import evaluateFormatters from './evaluate-formatters'; +import evaluateTransforms from './evaluate-transforms'; +import mergeProps from './merge-props'; +import { tableHeaderRowTypes, tableHeaderRowDefaults } from './types'; + +const HeaderRow = ({ rowData, rowIndex, renderers, onRow }) => + React.createElement( + renderers.row, + onRow(rowData, { rowIndex }), + rowData.map((column, columnIndex) => { + const { property, header = {}, props = {} } = column; + const evaluatedProperty = property || (header && header.property); + const { label, transforms = [], formatters = [] } = header; + const extraParameters = { + columnIndex, + property: evaluatedProperty, + column + }; + const transformedProps = evaluateTransforms(transforms, label, extraParameters); + + if (!transformedProps) { + console.warn('Table.Header - Failed to receive a transformed result'); // eslint-disable-line max-len, no-console + } + + return React.createElement( + renderers.cell, + { + key: `${columnIndex}-header`, + ...mergeProps(props, header && header.props, transformedProps) + }, + transformedProps.children || evaluateFormatters(formatters)(label, extraParameters) + ); + }) + ); +HeaderRow.defaultProps = tableHeaderRowDefaults; +HeaderRow.propTypes = tableHeaderRowTypes; + +export default HeaderRow; diff --git a/packages/patternfly-4/react-table/src/components/Table/base/header.js b/packages/patternfly-4/react-table/src/components/Table/base/header.js new file mode 100644 index 00000000000..49f5c06d01b --- /dev/null +++ b/packages/patternfly-4/react-table/src/components/Table/base/header.js @@ -0,0 +1,38 @@ +/** + * header.js + * + * Forked from reactabular-table version 8.14.0 + * https://github.com/reactabular/reactabular/tree/v8.14.0/packages/reactabular-table/src + * */ +import React from 'react'; +import { tableHeaderTypes, tableHeaderContextTypes } from './types'; +import HeaderRow from './header-row'; + +// eslint-disable-next-line react/prefer-stateless-function +class Header extends React.Component { + render() { + const { children, headerRows, onRow, ...props } = this.props; + const { renderers, columns } = this.context; + + // If headerRows aren't passed, default to bodyColumns as header rows + return React.createElement( + renderers.header.wrapper, + props, + [ + (headerRows || [columns]).map((rowData, rowIndex) => + React.createElement(HeaderRow, { + key: `${rowIndex}-header-row`, + renderers: renderers.header, + onRow, + rowData, + rowIndex + }) + ) + ].concat(children) + ); + } +} +Header.propTypes = tableHeaderTypes; +Header.contextTypes = tableHeaderContextTypes; + +export default Header; diff --git a/packages/patternfly-4/react-table/src/components/Table/base/index.js b/packages/patternfly-4/react-table/src/components/Table/base/index.js new file mode 100644 index 00000000000..31f9e2760e6 --- /dev/null +++ b/packages/patternfly-4/react-table/src/components/Table/base/index.js @@ -0,0 +1,9 @@ +export { default as Provider } from './provider'; +export { default as Header } from './header'; +export { default as Body } from './body'; +export { default as BodyRow } from './body-row'; +export { default as evaluateFormatters } from './evaluate-formatters'; +export { default as evaluateTransforms } from './evaluate-transforms'; +export { default as mergeProps } from './merge-props'; +export { default as columnsAreEqual } from './columns-are-equal'; +export { default as resolveRowKey } from './resolve-row-key'; diff --git a/packages/patternfly-4/react-table/src/components/Table/base/merge-props.js b/packages/patternfly-4/react-table/src/components/Table/base/merge-props.js new file mode 100644 index 00000000000..e7a58581138 --- /dev/null +++ b/packages/patternfly-4/react-table/src/components/Table/base/merge-props.js @@ -0,0 +1,36 @@ +/** + * merge-props.js + * + * Forked from reactabular-table version 8.14.0 + * https://github.com/reactabular/reactabular/tree/v8.14.0/packages/reactabular-table/src + * */ +import { mergeWith } from 'lodash-es'; +import classNames from 'classnames'; + +function mergePropPair(...props) { + const firstProps = props[0]; + const restProps = props.slice(1); + + if (!restProps.length) { + return mergeWith({}, firstProps); + } + + // Avoid mutating the first prop collection + return mergeWith(mergeWith({}, firstProps), ...restProps, (a, b, key) => { + if (key === 'children') { + // Children have to be merged in reverse order for Reactabular + // logic to work. + return { ...b, ...a }; + } + + if (key === 'className') { + // Process class names through classNames to merge properly + // as a string. + return classNames(a, b); + } + + return undefined; + }); +} + +export default mergePropPair; diff --git a/packages/patternfly-4/react-table/src/components/Table/base/provider.js b/packages/patternfly-4/react-table/src/components/Table/base/provider.js new file mode 100644 index 00000000000..499bba82518 --- /dev/null +++ b/packages/patternfly-4/react-table/src/components/Table/base/provider.js @@ -0,0 +1,56 @@ +/** + * provider.js + * + * Forked from reactabular-table version 8.14.0 + * https://github.com/reactabular/reactabular/tree/v8.14.0/packages/reactabular-table/src + * */ +import React from 'react'; +import PropTypes from 'prop-types'; +import { tableTypes, tableDefaults, tableContextTypes } from './types'; + +const componentDefaults = tableDefaults.renderers; + +export default class Provider extends React.Component { + getChildContext() { + const { columns, components, renderers } = this.props; + let finalRenderers = renderers; + + // XXXXX: Drop in the next major version + if (components) { + // eslint-disable-next-line no-console + console.warn( + '`components` have been deprecated in favor of `renderers` and will be removed in the next major version, please rename!' + ); + + finalRenderers = components; + } + + return { + columns, + renderers: { + table: finalRenderers.table || componentDefaults.table, + header: { ...componentDefaults.header, ...finalRenderers.header }, + body: { ...componentDefaults.body, ...finalRenderers.body } + } + }; + } + render() { + const { + columns, // eslint-disable-line no-unused-vars + renderers, + components, // XXXXX: Drop in the next major version + children, + ...props + } = this.props; + + return React.createElement(renderers.table || tableDefaults.renderers.table, props, children); + } +} +Provider.propTypes = { + ...tableTypes, + children: PropTypes.any +}; +Provider.defaultProps = { + ...tableDefaults +}; +Provider.childContextTypes = tableContextTypes; diff --git a/packages/patternfly-4/react-table/src/components/Table/base/resolve-row-key.js b/packages/patternfly-4/react-table/src/components/Table/base/resolve-row-key.js new file mode 100644 index 00000000000..ad2d9d74c4a --- /dev/null +++ b/packages/patternfly-4/react-table/src/components/Table/base/resolve-row-key.js @@ -0,0 +1,31 @@ +/** + * resolve-row-key.js + * + * Forked from reactabular-table version 8.14.0 + * https://github.com/reactabular/reactabular/tree/v8.14.0/packages/reactabular-table/src + * */ +import { isArray } from 'lodash-es'; + +function resolveRowKey({ rowData, rowIndex, rowKey }) { + if (typeof rowKey === 'function') { + return `${rowKey({ rowData, rowIndex })}-row`; + } else if (process.env.NODE_ENV !== 'production') { + // Arrays cannot have rowKeys by definition so we have to go by index there. + if (!isArray(rowData) && rowData[rowKey] === undefined) { + console.warn( + // eslint-disable-line no-console + 'Table.Body - Missing valid rowKey!', + rowData, + rowKey + ); + } + } + + if (rowData[rowKey] === 0) { + return `${rowData[rowKey]}-row`; + } + + return `${rowData[rowKey] || rowIndex}-row`; +} + +export default resolveRowKey; diff --git a/packages/patternfly-4/react-table/src/components/Table/base/types.js b/packages/patternfly-4/react-table/src/components/Table/base/types.js new file mode 100644 index 00000000000..20293559f6c --- /dev/null +++ b/packages/patternfly-4/react-table/src/components/Table/base/types.js @@ -0,0 +1,107 @@ +/** + * types.js + * + * Forked from reactabular-table version 8.14.0 + * https://github.com/reactabular/reactabular/tree/v8.14.0/packages/reactabular-table/src + * */ +import PropTypes from 'prop-types'; + +const arrayOfObjectColumns = PropTypes.arrayOf( + PropTypes.shape({ + header: PropTypes.shape({ + label: PropTypes.string, + transforms: PropTypes.arrayOf(PropTypes.func), + formatters: PropTypes.arrayOf(PropTypes.func), + props: PropTypes.object + }), + cell: PropTypes.shape({ + property: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), + transforms: PropTypes.arrayOf(PropTypes.func), + formatters: PropTypes.arrayOf(PropTypes.func), + props: PropTypes.object + }) + }) +); +const arrayOfArrayColumns = PropTypes.arrayOf(PropTypes.array); +const rowsType = PropTypes.oneOfType([arrayOfObjectColumns, arrayOfArrayColumns]); +const rowKeyType = PropTypes.oneOfType([PropTypes.func, PropTypes.string]); +const rowDataType = PropTypes.oneOfType([PropTypes.array, PropTypes.object]); +const tableTypes = { + columns: PropTypes.array.isRequired, + renderers: PropTypes.object, + components: PropTypes.object // XXXXX: Deprecated in favor of renderers, remove in the next major! +}; +const tableContextTypes = { + columns: PropTypes.array.isRequired, + renderers: PropTypes.object +}; +const tableBodyDefaults = { + onRow: () => {} +}; +const tableBodyTypes = { + onRow: PropTypes.func, + rows: rowsType.isRequired, + rowKey: rowKeyType +}; +const tableBodyContextTypes = { + columns: PropTypes.array.isRequired, + renderers: PropTypes.object +}; +const tableBodyRowDefaults = { + onRow: () => ({}) +}; +const tableBodyRowTypes = { + columns: PropTypes.array.isRequired, + renderers: PropTypes.object, + onRow: PropTypes.func, + rowIndex: PropTypes.number.isRequired, + rowData: rowDataType.isRequired, + rowKey: PropTypes.string.isRequired +}; +const tableHeaderTypes = { + headerRows: PropTypes.arrayOf(arrayOfObjectColumns), + children: PropTypes.any +}; +const tableHeaderContextTypes = { + columns: PropTypes.array.isRequired, + renderers: PropTypes.object +}; +const tableHeaderRowDefaults = { + onRow: () => ({}) +}; +const tableHeaderRowTypes = { + renderers: PropTypes.object, + onRow: PropTypes.func, + rowIndex: PropTypes.number.isRequired, + rowData: rowDataType.isRequired +}; +const tableDefaults = { + renderers: { + table: 'table', + header: { + wrapper: 'thead', + row: 'tr', + cell: 'th' + }, + body: { + wrapper: 'tbody', + row: 'tr', + cell: 'td' + } + } +}; + +export { + tableTypes, + tableContextTypes, + tableBodyTypes, + tableBodyDefaults, + tableBodyContextTypes, + tableBodyRowTypes, + tableBodyRowDefaults, + tableHeaderTypes, + tableHeaderContextTypes, + tableHeaderRowTypes, + tableHeaderRowDefaults, + tableDefaults +}; diff --git a/packages/patternfly-4/react-table/src/components/Table/index.js b/packages/patternfly-4/react-table/src/components/Table/index.js index 884b75e3211..c65bab9f987 100644 --- a/packages/patternfly-4/react-table/src/components/Table/index.js +++ b/packages/patternfly-4/react-table/src/components/Table/index.js @@ -1,3 +1,4 @@ +export { default as ActionsColumn } from './ActionsColumn'; export { default as Table, TableContext, TableGridBreakpoint, TableVariant } from './Table'; export { default as TableHeader } from './Header'; export { default as TableBody } from './Body'; diff --git a/packages/patternfly-4/react-virtualized-extension/.babelrc b/packages/patternfly-4/react-virtualized-extension/.babelrc new file mode 100644 index 00000000000..40b9ca6c624 --- /dev/null +++ b/packages/patternfly-4/react-virtualized-extension/.babelrc @@ -0,0 +1,6 @@ +{ + "presets": [ + "../.babelrc.js", + "flow" + ] +} \ No newline at end of file diff --git a/packages/patternfly-4/react-virtualized-extension/.npmignore b/packages/patternfly-4/react-virtualized-extension/.npmignore new file mode 100644 index 00000000000..378eac25d31 --- /dev/null +++ b/packages/patternfly-4/react-virtualized-extension/.npmignore @@ -0,0 +1 @@ +build diff --git a/packages/patternfly-4/react-virtualized-extension/README.md b/packages/patternfly-4/react-virtualized-extension/README.md new file mode 100644 index 00000000000..ba01cc213be --- /dev/null +++ b/packages/patternfly-4/react-virtualized-extension/README.md @@ -0,0 +1,5 @@ +# react-virtualized-extension + +This package contains virtualization extensions for tables and lists. + +This package is currently an extension. Extension components do not undergo the same rigorous design or coding review process as core PatternFly components. If enough members of the community find them useful, we will work to move them into our core PatternFly system by starting the design process for the idea. diff --git a/packages/patternfly-4/react-virtualized-extension/build/copyStyles.js b/packages/patternfly-4/react-virtualized-extension/build/copyStyles.js new file mode 100644 index 00000000000..3c501ed0ad6 --- /dev/null +++ b/packages/patternfly-4/react-virtualized-extension/build/copyStyles.js @@ -0,0 +1,42 @@ +/* eslint-disable no-case-declarations */ +const { copySync, readFileSync, writeFileSync } = require('fs-extra'); +const { resolve, dirname, join } = require('path'); +const { parse: parseCSS, stringify: stringifyCSS } = require('css'); + +const baseCSSFilename = 'patternfly-base.css'; +const stylesDir = resolve(__dirname, '../dist/styles'); +const pfDir = dirname(require.resolve(`@patternfly/patternfly/${baseCSSFilename}`)); + +const css = readFileSync(join(pfDir, baseCSSFilename), 'utf8'); +const ast = parseCSS(css); + +const unusedSelectorRegEx = /(\.fas?|\.sr-only)/; +const unusedKeyFramesRegEx = /fa-/; +const unusedFontFamilyRegEx = /Font Awesome 5 Free/; +const ununsedFontFilesRegExt = /(fa-|\.html$|\.css$)/; + +// Core provides font awesome fonts and utlities. React does not use these +ast.stylesheet.rules = ast.stylesheet.rules.filter(rule => { + switch (rule.type) { + case 'rule': + return !rule.selectors.some(sel => unusedSelectorRegEx.test(sel)); + case 'keyframes': + return !unusedKeyFramesRegEx.test(rule.name); + case 'charset': + case 'comment': + return false; + case 'font-face': + const fontFamilyDecl = rule.declarations.find(decl => decl.property === 'font-family'); + return !unusedFontFamilyRegEx.test(fontFamilyDecl.value); + default: + return true; + } +}); + +copySync(join(pfDir, 'assets/images'), join(stylesDir, 'assets/images')); +copySync(join(pfDir, 'assets/fonts'), join(stylesDir, 'assets/fonts'), { + filter(src) { + return !ununsedFontFilesRegExt.test(src); + } +}); +writeFileSync(join(stylesDir, 'base.css'), stringifyCSS(ast)); diff --git a/packages/patternfly-4/react-virtualized-extension/build/snapshot-serializer.js b/packages/patternfly-4/react-virtualized-extension/build/snapshot-serializer.js new file mode 100644 index 00000000000..0edb3cb5b4c --- /dev/null +++ b/packages/patternfly-4/react-virtualized-extension/build/snapshot-serializer.js @@ -0,0 +1,8 @@ +const fs = require('fs'); +const { createSerializer } = require('@patternfly/react-styles/snapshot-serializer'); + +const pf4CSS = fs.readFileSync(require.resolve('@patternfly/patternfly/patternfly-base.css'), 'utf8'); + +module.exports = createSerializer({ + globalCSS: pf4CSS.match(/:root\W?\{(.|\n)*?\}/)[0] +}); diff --git a/packages/patternfly-4/react-virtualized-extension/package.json b/packages/patternfly-4/react-virtualized-extension/package.json new file mode 100644 index 00000000000..30b4902329e --- /dev/null +++ b/packages/patternfly-4/react-virtualized-extension/package.json @@ -0,0 +1,65 @@ +{ + "name": "@patternfly/react-virtualized-extension", + "version": "1.0.0", + "description": "This library provides efficient rendering extensions for PatternFly 4 React tables and lists.", + "main": "dist/js/index.js", + "module": "dist/esm/index.js", + "types": "dist/js/index.d.ts", + "sideEffects": false, + "publishConfig": { + "access": "public", + "tag": "prerelease" + }, + "repository": { + "type": "git", + "url": "https://github.com/patternfly/patternfly-react.git" + }, + "keywords": [ + "react", + "patternfly", + "table", + "reacttabular" + ], + "author": "Red Hat", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/patternfly/patternfly-react/issues" + }, + "homepage": "https://github.com/patternfly/patternfly-react/tree/master/packages/patternfly-4/", + "dependencies": { + "@patternfly/patternfly": "2.8.2", + "@patternfly/react-core": "^3.36.0", + "@patternfly/react-icons": "^3.9.3", + "@patternfly/react-styles": "^3.3.0", + "exenv": "^1.2.2", + "react-virtualized": "9.21.1", + "clsx": "^1.0.1", + "dom-helpers": "^2.4.0 || ^3.0.0", + "react-lifecycles-compat": "^3.0.4", + "linear-layout-vector": "0.0.1" + }, + "peerDependencies": { + "@patternfly/react-table": "^2.10.0", + "lodash-es": "4.x", + "prop-types": "^15.6.1", + "react": "^16.4.0", + "react-dom": "^15.6.2 || ^16.4.0" + }, + "scripts": { + "build": "yarn build:babel && node ./scripts/copyTS.js && node ./build/copyStyles.js", + "build:babel": "concurrently 'yarn build:babel:esm && yarn build:babel:umd' 'yarn build:babel:cjs'", + "build:babel:cjs": "babel src --out-dir dist/js -q", + "build:babel:esm": "babel src --out-dir dist/esm -q", + "build:babel:umd": "babel dist/esm --out-dir dist/umd --plugins transform-es2015-modules-umd --extensions '.js,.ts,.tsx' -q", + "clean": "rimraf dist", + "develop": "yarn build:babel:esm --skip-initial-build --watch --verbose" + }, + "devDependencies": { + "babel-preset-flow": "^6.23.0", + "css": "^2.2.3", + "fs-extra": "^6.0.1", + "glob": "^7.1.2", + "uuid": "^3.3.2", + "rimraf": "^2.6.2" + } +} diff --git a/packages/patternfly-4/react-virtualized-extension/scripts/copyTS.js b/packages/patternfly-4/react-virtualized-extension/scripts/copyTS.js new file mode 100644 index 00000000000..569890d173f --- /dev/null +++ b/packages/patternfly-4/react-virtualized-extension/scripts/copyTS.js @@ -0,0 +1,15 @@ +const path = require('path'); +const glob = require('glob'); +const fse = require('fs-extra'); + +const srcDir = path.join('./src'); +const distDir = path.join('./dist/js'); + +const files = glob.sync('**/*.d.ts', { + cwd: srcDir +}); +files.forEach(file => { + const from = path.join(srcDir, file); + const to = path.join(distDir, file); + fse.copySync(from, to); +}); diff --git a/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/VirtualGrid.example.css b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/VirtualGrid.example.css new file mode 100644 index 00000000000..12d45ab06eb --- /dev/null +++ b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/VirtualGrid.example.css @@ -0,0 +1,326 @@ +.pf-c-scrollablegrid .pf-c-table { + table-layout: fixed; +} + +.pf-c-table.pf-c-virtualized tr { + display: table; + table-layout: fixed; + width: 100%; +} + +.pf-c-scrollablegrid .pf-c-table tr > * { + height: auto; +} + +.pf-c-scrollablegrid .pf-c-table tbody > tr > :first-child::before { + content: none; + width: 0 !important; +} + +.pf-c-scrollablegrid .pf-c-table .pf-c-table__check { + width: 8.333% !important; +} + +@media screen and (max-width: 768px) { + .pf-c-scrollablegrid .pf-c-table .pf-c-table__check { + width: 16.66% !important; + } +} + +.pf-c-scrollablegrid .pf-c-table .pf-c-table__action { + width: 5% !important; + padding-left: 0px !important; +} +@media screen and (max-width: 992px) { + .pf-c-scrollablegrid .pf-c-table .pf-c-table__action { + width: 10% !important; + } +} + +@media screen and (min-width: 576px) and (max-width: 768px) { + .pf-m-1-col-on-sm { + width: 8.333% !important; + } +} + +@media screen and (min-width: 768px) and (max-width: 992px) { + .pf-m-1-col-on-md { + width: 8.33% !important; + } +} + +@media screen and (min-width: 992px) and (max-width: 1200px) { + .pf-m-1-col-on-lg { + width: 8.33% !important; + } +} + +@media screen and (min-width: 1200px) { + .pf-m-1-col-on-xl { + width: 8.33% !important; + } +} + +@media screen and (min-width: 576px) and (max-width: 768px) { + .pf-m-2-col-on-sm { + width: 16.66% !important; + } +} + +@media screen and (min-width: 768px) and (max-width: 992px) { + .pf-m-2-col-on-md { + width: 16.66% !important; + } +} + +@media screen and (min-width: 992px) and (max-width: 1200px) { + .pf-m-2-col-on-lg { + width: 16.66% !important; + } +} + +@media screen and (min-width: 1200px) { + .pf-m-2-col-on-xl { + width: 16.66% !important; + } +} + +@media screen and (min-width: 576px) and (max-width: 768px) { + .pf-m-3-col-on-sm { + width: 25% !important; + } +} + +@media screen and (min-width: 768px) and (max-width: 992px) { + .pf-m-3-col-on-md { + width: 25% !important; + } +} + +@media screen and (min-width: 992px) and (max-width: 1200px) { + .pf-m-3-col-on-lg { + width: 25% !important; + } +} + +@media screen and (min-width: 1200px) { + .pf-m-3-col-on-xl { + width: 25% !important; + } +} + +@media screen and (min-width: 576px) and (max-width: 768px) { + .pf-m-4-col-on-xl { + width: 33.333% !important; + } +} + +@media screen and (min-width: 768px) and (max-width: 992px) { + .pf-m-4-col-on-md { + width: 33.333% !important; + } +} + +@media screen and (min-width: 992px) and (max-width: 1200px) { + .pf-m-4-col-on-lg { + width: 33.333% !important; + } +} + +@media screen and (min-width: 1200px) { + .pf-m-4-col-on-xl { + width: 33.333% !important; + } +} + +@media screen and (min-width: 576px) and (max-width: 768px) { + .pf-m-5-col-on-sm { + width: 41.67% !important; + } +} + +@media screen and (min-width: 768px) and (max-width: 992px) { + .pf-m-5-col-on-md { + width: 41.67% !important; + } +} + +@media screen and (min-width: 992px) and (max-width: 1200px) { + .pf-m-5-col-on-lg { + width: 41.67% !important; + } +} + +@media screen and (min-width: 1200px) { + .pf-m-5-col-on-xl { + width: 41.67% !important; + } +} + +@media screen and (max-width: 768px) { + .pf-m-6-col-on-sm { + width: 50% !important; + } +} + +@media screen and (min-width: 768px) and (max-width: 992px) { + .pf-m-6-col-on-md { + width: 50% !important; + } +} + +@media screen and (min-width: 992px) and (max-width: 1200px) { + .pf-m-6-col-on-lg { + width: 50% !important; + } +} + +@media screen and (min-width: 1200px) { + .pf-m-6-col-on-xl { + width: 50% !important; + } +} + +@media screen and (min-width: 576px) and (max-width: 768px) { + .pf-m-7-col-on-sm { + width: 58.333% !important; + } +} + +@media screen and (min-width: 768px) and (max-width: 992px) { + .pf-m-7-col-on-md { + width: 58.333% !important; + } +} + +@media screen and (min-width: 992px) and (max-width: 1200px) { + .pf-m-7-col-on-lg { + width: 58.333% !important; + } +} + +@media screen and (min-width: 1200px) { + .pf-m-7-col-on-xl { + width: 58.333% !important; + } +} + +@media screen and (min-width: 576px) and (max-width: 768px) { + .pf-m-8-col-on-sm { + width: 66.66% !important; + } +} + +@media screen and (min-width: 768px) and (max-width: 992px) { + .pf-m-8-col-on-md { + width: 66.66% !important; + } +} + +@media screen and (min-width: 992px) and (max-width: 1200px) { + .pf-m-8-col-on-lg { + width: 66.66% !important; + } +} + +@media screen and (min-width: 1200px) { + .pf-m-8-col-on-xl { + width: 66.66% !important; + } +} + +@media screen and (min-width: 576px) and (max-width: 768px) { + .pf-m-9-col-on-sm { + width: 75% !important; + } +} + +@media screen and (min-width: 768px) and (max-width: 992px) { + .pf-m-9-col-on-md { + width: 75% !important; + } +} + +@media screen and (min-width: 992px) and (max-width: 1200px) { + .pf-m-9-col-on-lg { + width: 75% !important; + } +} + +@media screen and (min-width: 1200px) { + .pf-m-9-col-on-xl { + width: 75% !important; + } +} + +@media screen and (min-width: 576px) and (max-width: 768px) { + .pf-m-10-col-on-sm { + width: 83.333% !important; + } +} + +@media screen and (min-width: 768px) and (max-width: 992px) { + .pf-m-10-col-on-md { + width: 83.333% !important; + } +} + +@media screen and (min-width: 992px) and (max-width: 1200px) { + .pf-m-10-col-on-lg { + width: 83.333% !important; + } +} + +@media screen and (min-width: 1200px) { + .pf-m-10-col-on-xl { + width: 83.333% !important; + } +} + +@media screen and (min-width: 576px) and (max-width: 768px) { + .pf-m-11-col-on-sm { + width: 91.67% !important; + } +} + +@media screen and (min-width: 768px) and (max-width: 992px) { + .pf-m-11-col-on-md { + width: 91.67% !important; + } +} + +@media screen and (min-width: 992px) and (max-width: 1200px) { + .pf-m-11-col-on-lg { + width: 91.67% !important; + } +} + +@media screen and (min-width: 1200px) { + .pf-m-11-col-on-xl { + width: 91.67% !important; + } +} + +@media screen and (min-width: 576px) and (max-width: 768px) { + .pf-m-12-col-on-sm { + width: 100% !important; + } +} + +@media screen and (min-width: 768px) and (max-width: 992px) { + .pf-m-12-col-on-md { + width: 100% !important; + } +} + +@media screen and (min-width: 992px) and (max-width: 1200px) { + .pf-m-12-col-on-lg { + width: 100% !important; + } +} + +@media screen and (min-width: 1200px) { + .pf-m-12-col-on-xl { + width: 100% !important; + } +} \ No newline at end of file diff --git a/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/VirtualGrid.js b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/VirtualGrid.js new file mode 100644 index 00000000000..34ad6d9d32e --- /dev/null +++ b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/VirtualGrid.js @@ -0,0 +1,1472 @@ +/** @flow */ + +import type { + CellRenderer, + CellRangeRenderer, + CellPosition, + CellSize, + CellSizeGetter, + NoContentRenderer, + Scroll, + ScrollbarPresenceChange, + RenderedSection, + OverscanIndicesGetter, + Alignment, + CellCache, + StyleCache +} from './types'; +import type { AnimationTimeoutId } from './utils/requestAnimationTimeout'; + +import * as React from 'react'; +import clsx from 'clsx'; +import calculateSizeAndPositionDataAndUpdateScrollOffset from './utils/calculateSizeAndPositionDataAndUpdateScrollOffset'; +import ScalingCellSizeAndPositionManager from './utils/ScalingCellSizeAndPositionManager'; +import createCallbackMemoizer from './utils/createCallbackMemoizer'; +import defaultOverscanIndicesGetter, { + SCROLL_DIRECTION_BACKWARD, + SCROLL_DIRECTION_FORWARD +} from './defaultOverscanIndicesGetter'; +import updateScrollIndexHelper from './utils/updateScrollIndexHelper'; +import defaultCellRangeRenderer from './defaultCellRangeRenderer'; +import scrollbarSize from 'dom-helpers/util/scrollbarSize'; +import { polyfill } from 'react-lifecycles-compat'; +import { requestAnimationTimeout, cancelAnimationTimeout } from './utils/requestAnimationTimeout'; + +/** + * Specifies the number of milliseconds during which to disable pointer events while a scroll is in progress. + * This improves performance and makes scrolling smoother. + */ +export const DEFAULT_SCROLLING_RESET_TIME_INTERVAL = 150; + +/** + * Controls whether the VirtualGrid updates the DOM element's scrollLeft/scrollTop based on the current state or just observes it. + * This prevents VirtualGrid from interrupting mouse-wheel animations (see issue #2). + */ +const SCROLL_POSITION_CHANGE_REASONS = { + OBSERVED: 'observed', + REQUESTED: 'requested' +}; + +const renderNull: NoContentRenderer = () => null; + +type ScrollPosition = { + scrollTop?: number, + scrollLeft?: number +}; + +type Props = { + 'aria-label': string, + 'aria-readonly'?: boolean, + + /** + * Set the width of the inner scrollable container to 'auto'. + * This is useful for single-column VirtualGrids to ensure that the column doesn't extend below a vertical scrollbar. + */ + autoContainerWidth: boolean, + + /** + * Removes fixed height from the scrollingContainer so that the total height of rows can stretch the window. + * Intended for use with WindowScroller + */ + autoHeight: boolean, + + /** + * Removes fixed width from the scrollingContainer so that the total width of rows can stretch the window. + * Intended for use with WindowScroller + */ + autoWidth: boolean, + + /** Responsible for rendering a cell given an row and column index. */ + cellRenderer: CellRenderer, + + /** Responsible for rendering a group of cells given their index ranges. */ + cellRangeRenderer: CellRangeRenderer, + + /** Optional custom CSS class name to attach to root VirtualGrid element. */ + className?: string, + + /** Number of columns in grid. */ + columnCount: number, + + /** Either a fixed column width (number) or a function that returns the width of a column given its index. */ + columnWidth: CellSize, + + /** Unfiltered props for the VirtualGrid container. */ + containerProps?: Object, + + /** ARIA role for the cell-container. */ + containerRole: string, + + /** Optional inline style applied to inner cell-container */ + containerStyle: Object, + + /** + * If CellMeasurer is used to measure this VirtualGrid's children, this should be a pointer to its CellMeasurerCache. + * A shared CellMeasurerCache reference enables VirtualGrid and CellMeasurer to share measurement data. + */ + deferredMeasurementCache?: Object, + + /** + * Used to estimate the total width of a VirtualGrid before all of its columns have actually been measured. + * The estimated total width is adjusted as columns are rendered. + */ + estimatedColumnSize: number, + + /** + * Used to estimate the total height of a VirtualGrid before all of its rows have actually been measured. + * The estimated total height is adjusted as rows are rendered. + */ + estimatedRowSize: number, + + /** Exposed for testing purposes only. */ + getScrollbarSize: () => number, + + /** Height of VirtualGrid; this property determines the number of visible (vs virtualized) rows. */ + height: number, + + /** Optional custom id to attach to root VirtualGrid element. */ + id?: string, + + /** + * Override internal is-scrolling state tracking. + * This property is primarily intended for use with the WindowScroller component. + */ + isScrolling?: boolean, + + /** + * Opt-out of isScrolling param passed to cellRangeRenderer. + * To avoid the extra render when scroll stops. + */ + isScrollingOptOut: boolean, + + /** Optional renderer to be used in place of rows when either :rowCount or :columnCount is 0. */ + noContentRenderer: NoContentRenderer, + + /** + * Callback invoked whenever the scroll offset changes within the inner scrollable region. + * This callback can be used to sync scrolling between lists, tables, or grids. + */ + onScroll: (params: Scroll) => void, + + /** + * Called whenever a horizontal or vertical scrollbar is added or removed. + * This prop is not intended for end-user use; + * It is used by MultiVirtualGrid to support fixed-row/fixed-column scroll syncing. + */ + onScrollbarPresenceChange: (params: ScrollbarPresenceChange) => void, + + /** Callback invoked with information about the section of the VirtualGrid that was just rendered. */ + onSectionRendered: (params: RenderedSection) => void, + + /** + * Number of columns to render before/after the visible section of the grid. + * These columns can help for smoother scrolling on touch devices or browsers that send scroll events infrequently. + */ + overscanColumnCount: number, + + /** + * Calculates the number of cells to overscan before and after a specified range. + * This function ensures that overscanning doesn't exceed the available cells. + */ + overscanIndicesGetter: OverscanIndicesGetter, + + /** + * Number of rows to render above/below the visible section of the grid. + * These rows can help for smoother scrolling on touch devices or browsers that send scroll events infrequently. + */ + overscanRowCount: number, + + /** ARIA role for the grid element. */ + role: string, + + /** + * Either a fixed row height (number) or a function that returns the height of a row given its index. + * Should implement the following interface: ({ index: number }): number + */ + rowHeight: CellSize, + + /** Number of rows in grid. */ + rowCount: number, + + /** Wait this amount of time after the last scroll event before resetting VirtualGrid `pointer-events`. */ + scrollingResetTimeInterval: number, + + /** Horizontal offset. */ + scrollLeft?: number, + + /** + * Controls scroll-to-cell behavior of the VirtualGrid. + * The default ("auto") scrolls the least amount possible to ensure that the specified cell is fully visible. + * Use "start" to align cells to the top/left of the VirtualGrid and "end" to align bottom/right. + */ + scrollToAlignment: Alignment, + + /** Column index to ensure visible (by forcefully scrolling if necessary) */ + scrollToColumn: number, + + /** Vertical offset. */ + scrollTop?: number, + + /** Row index to ensure visible (by forcefully scrolling if necessary) */ + scrollToRow: number, + + /** Optional inline style */ + style: Object, + + /** Tab index for focus */ + tabIndex: ?number, + + /** Width of VirtualGrid; this property determines the number of visible (vs virtualized) columns. */ + width: number, + + /** Scroll Container element to render */ + scrollContainerComponent: string | React.ComponentType, + + /** Inner Scroll Container element to render */ + innerScrollContainerComponent: string | React.ComponentType +}; + +type InstanceProps = { + prevColumnWidth: CellSize, + prevRowHeight: CellSize, + + prevColumnCount: number, + prevRowCount: number, + prevIsScrolling: boolean, + prevScrollToColumn: number, + prevScrollToRow: number, + prevScrollLeft: ?number, + prevScrollTop: ?number, + + columnSizeAndPositionManager: ScalingCellSizeAndPositionManager, + rowSizeAndPositionManager: ScalingCellSizeAndPositionManager, + + scrollbarSize: number, + scrollbarSizeMeasured: boolean +}; + +type State = { + instanceProps: InstanceProps, + isScrolling: boolean, + scrollDirectionHorizontal: -1 | 1, + scrollDirectionVertical: -1 | 1, + scrollLeft: number, + scrollTop: number, + scrollPositionChangeReason: 'observed' | 'requested' | null, + needToResetStyleCache: boolean +}; + +/** + * Renders tabular data with virtualization along the vertical and horizontal axes. + * Row heights and column widths must be known ahead of time and specified as properties. + */ +class VirtualGrid extends React.PureComponent { + static defaultProps = { + 'aria-label': 'grid', + 'aria-readonly': true, + autoContainerWidth: false, + autoHeight: false, + autoWidth: false, + cellRangeRenderer: defaultCellRangeRenderer, + containerRole: 'rowgroup', + containerStyle: {}, + estimatedColumnSize: 100, + estimatedRowSize: 30, + getScrollbarSize: scrollbarSize, + noContentRenderer: renderNull, + onScroll: () => {}, + onScrollbarPresenceChange: () => {}, + onSectionRendered: () => {}, + overscanColumnCount: 0, + overscanIndicesGetter: defaultOverscanIndicesGetter, + overscanRowCount: 10, + role: 'grid', + scrollingResetTimeInterval: DEFAULT_SCROLLING_RESET_TIME_INTERVAL, + scrollToAlignment: 'auto', + scrollToColumn: -1, + scrollToRow: -1, + style: {}, + tabIndex: 0, + isScrollingOptOut: false, + scrollContainerComponent: 'div', + innerScrollContainerComponent: 'div' + }; + + // Invokes onSectionRendered callback only when start/stop row or column indices change + _onVirtualGridRenderedMemoizer = createCallbackMemoizer(); + _onScrollMemoizer = createCallbackMemoizer(false); + + _deferredInvalidateColumnIndex = null; + _deferredInvalidateRowIndex = null; + _recomputeScrollLeftFlag = false; + _recomputeScrollTopFlag = false; + + _horizontalScrollBarSize = 0; + _verticalScrollBarSize = 0; + _scrollbarPresenceChanged = false; + _scrollingContainer: Element; + + _childrenToDisplay: React.Element<*>[]; + + _columnStartIndex: number; + _columnStopIndex: number; + _rowStartIndex: number; + _rowStopIndex: number; + _renderedColumnStartIndex = 0; + _renderedColumnStopIndex = 0; + _renderedRowStartIndex = 0; + _renderedRowStopIndex = 0; + + _initialScrollTop: number; + _initialScrollLeft: number; + + _disablePointerEventsTimeoutId: ?AnimationTimeoutId; + + _styleCache: StyleCache = {}; + _cellCache: CellCache = {}; + + constructor(props: Props) { + super(props); + const columnSizeAndPositionManager = new ScalingCellSizeAndPositionManager({ + cellCount: props.columnCount, + cellSizeGetter: params => VirtualGrid._wrapSizeGetter(props.columnWidth)(params), + estimatedCellSize: VirtualGrid._getEstimatedColumnSize(props) + }); + const rowSizeAndPositionManager = new ScalingCellSizeAndPositionManager({ + cellCount: props.rowCount, + cellSizeGetter: params => VirtualGrid._wrapSizeGetter(props.rowHeight)(params), + estimatedCellSize: VirtualGrid._getEstimatedRowSize(props) + }); + + this.state = { + instanceProps: { + columnSizeAndPositionManager, + rowSizeAndPositionManager, + + prevColumnWidth: props.columnWidth, + prevRowHeight: props.rowHeight, + prevColumnCount: props.columnCount, + prevRowCount: props.rowCount, + prevIsScrolling: props.isScrolling === true, + prevScrollToColumn: props.scrollToColumn, + prevScrollToRow: props.scrollToRow, + prevScrollLeft: props.scrollLeft, + prevScrollTop: props.scrollTop, + + scrollbarSize: 0, + scrollbarSizeMeasured: false + }, + isScrolling: false, + scrollDirectionHorizontal: SCROLL_DIRECTION_FORWARD, + scrollDirectionVertical: SCROLL_DIRECTION_FORWARD, + scrollLeft: props.scrollLeft || 0, + scrollTop: props.scrollTop || 0, + scrollPositionChangeReason: null, + + needToResetStyleCache: false + }; + + if (props.scrollToRow > 0) { + this._initialScrollTop = this._getCalculatedScrollTop(props, this.state); + } + if (props.scrollToColumn > 0) { + this._initialScrollLeft = this._getCalculatedScrollLeft(props, this.state); + } + } + + /** + * Gets offsets for a given cell and alignment. + */ + getOffsetForCell({ + alignment = this.props.scrollToAlignment, + columnIndex = this.props.scrollToColumn, + rowIndex = this.props.scrollToRow + }: { + alignment?: Alignment, + columnIndex?: number, + rowIndex?: number + } = {}) { + const offsetProps = { + ...this.props, + scrollToAlignment: alignment, + scrollToColumn: columnIndex, + scrollToRow: rowIndex + }; + + return { + scrollLeft: this._getCalculatedScrollLeft(offsetProps), + scrollTop: this._getCalculatedScrollTop(offsetProps) + }; + } + + /** + * Gets estimated total rows' height. + */ + getTotalRowsHeight() { + return this.state.instanceProps.rowSizeAndPositionManager.getTotalSize(); + } + + /** + * Gets estimated total columns' width. + */ + getTotalColumnsWidth() { + return this.state.instanceProps.columnSizeAndPositionManager.getTotalSize(); + } + + /** + * This method handles a scroll event originating from an external scroll control. + * It's an advanced method and should probably not be used unless you're implementing a custom scroll-bar solution. + */ + handleScrollEvent({ scrollLeft: scrollLeftParam = 0, scrollTop: scrollTopParam = 0 }: ScrollPosition) { + // On iOS, we can arrive at negative offsets by swiping past the start. + // To prevent flicker here, we make playing in the negative offset zone cause nothing to happen. + if (scrollTopParam < 0) { + return; + } + + // Prevent pointer events from interrupting a smooth scroll + this._debounceScrollEnded(); + + const { autoHeight, autoWidth, height, width } = this.props; + const { instanceProps } = this.state; + + // When this component is shrunk drastically, React dispatches a series of back-to-back scroll events, + // Gradually converging on a scrollTop that is within the bounds of the new, smaller height. + // This causes a series of rapid renders that is slow for long lists. + // We can avoid that by doing some simple bounds checking to ensure that scroll offsets never exceed their bounds. + const { scrollbarSize } = instanceProps; + const totalRowsHeight = instanceProps.rowSizeAndPositionManager.getTotalSize(); + const totalColumnsWidth = instanceProps.columnSizeAndPositionManager.getTotalSize(); + const scrollLeft = Math.min(Math.max(0, totalColumnsWidth - width + scrollbarSize), scrollLeftParam); + const scrollTop = Math.min(Math.max(0, totalRowsHeight - height + scrollbarSize), scrollTopParam); + + // Certain devices (like Apple touchpad) rapid-fire duplicate events. + // Don't force a re-render if this is the case. + // The mouse may move faster then the animation frame does. + // Use requestAnimationFrame to avoid over-updating. + if (this.state.scrollLeft !== scrollLeft || this.state.scrollTop !== scrollTop) { + // Track scrolling direction so we can more efficiently overscan rows to reduce empty space around the edges while scrolling. + // Don't change direction for an axis unless scroll offset has changed. + const scrollDirectionHorizontal = + scrollLeft !== this.state.scrollLeft + ? scrollLeft > this.state.scrollLeft + ? SCROLL_DIRECTION_FORWARD + : SCROLL_DIRECTION_BACKWARD + : this.state.scrollDirectionHorizontal; + const scrollDirectionVertical = + scrollTop !== this.state.scrollTop + ? scrollTop > this.state.scrollTop + ? SCROLL_DIRECTION_FORWARD + : SCROLL_DIRECTION_BACKWARD + : this.state.scrollDirectionVertical; + + const newState: $Shape = { + isScrolling: true, + scrollDirectionHorizontal, + scrollDirectionVertical, + scrollPositionChangeReason: SCROLL_POSITION_CHANGE_REASONS.OBSERVED + }; + + if (!autoHeight) { + newState.scrollTop = scrollTop; + } + + if (!autoWidth) { + newState.scrollLeft = scrollLeft; + } + + newState.needToResetStyleCache = false; + this.setState(newState); + } + + this._invokeOnScrollMemoizer({ + scrollLeft, + scrollTop, + totalColumnsWidth, + totalRowsHeight + }); + } + + /** + * Invalidate VirtualGrid size and recompute visible cells. + * This is a deferred wrapper for recomputeVirtualGridSize(). + * It sets a flag to be evaluated on cDM/cDU to avoid unnecessary renders. + * This method is intended for advanced use-cases like CellMeasurer. + */ + // @TODO (bvaughn) Add automated test coverage for this. + invalidateCellSizeAfterRender({ columnIndex, rowIndex }: CellPosition) { + this._deferredInvalidateColumnIndex = + typeof this._deferredInvalidateColumnIndex === 'number' + ? Math.min(this._deferredInvalidateColumnIndex, columnIndex) + : columnIndex; + this._deferredInvalidateRowIndex = + typeof this._deferredInvalidateRowIndex === 'number' + ? Math.min(this._deferredInvalidateRowIndex, rowIndex) + : rowIndex; + } + + /** + * Pre-measure all columns and rows in a VirtualGrid. + * Typically cells are only measured as needed and estimated sizes are used for cells that have not yet been measured. + * This method ensures that the next call to getTotalSize() returns an exact size (as opposed to just an estimated one). + */ + measureAllCells() { + const { columnCount, rowCount } = this.props; + const { instanceProps } = this.state; + instanceProps.columnSizeAndPositionManager.getSizeAndPositionOfCell(columnCount - 1); + instanceProps.rowSizeAndPositionManager.getSizeAndPositionOfCell(rowCount - 1); + } + + /** + * Forced recompute of row heights and column widths. + * This function should be called if dynamic column or row sizes have changed but nothing else has. + * Since VirtualGrid only receives :columnCount and :rowCount it has no way of detecting when the underlying data changes. + */ + recomputeVirtualGridSize({ columnIndex = 0, rowIndex = 0 }: CellPosition = {}) { + const { scrollToColumn, scrollToRow } = this.props; + const { instanceProps } = this.state; + + instanceProps.columnSizeAndPositionManager.resetCell(columnIndex); + instanceProps.rowSizeAndPositionManager.resetCell(rowIndex); + + // Cell sizes may be determined by a function property. + // In this case the cDU handler can't know if they changed. + // Store this flag to let the next cDU pass know it needs to recompute the scroll offset. + this._recomputeScrollLeftFlag = + scrollToColumn >= 0 && + (this.state.scrollDirectionHorizontal === SCROLL_DIRECTION_FORWARD + ? columnIndex <= scrollToColumn + : columnIndex >= scrollToColumn); + this._recomputeScrollTopFlag = + scrollToRow >= 0 && + (this.state.scrollDirectionVertical === SCROLL_DIRECTION_FORWARD + ? rowIndex <= scrollToRow + : rowIndex >= scrollToRow); + + // Clear cell cache in case we are scrolling; + // Invalid row heights likely mean invalid cached content as well. + this._styleCache = {}; + this._cellCache = {}; + + this.forceUpdate(); + } + + /** + * Ensure column and row are visible. + */ + scrollToCell({ columnIndex, rowIndex }: CellPosition) { + const { columnCount } = this.props; + + const { props } = this; + + // Don't adjust scroll offset for single-column grids (eg List, Table). + // This can cause a funky scroll offset because of the vertical scrollbar width. + if (columnCount > 1 && columnIndex !== undefined) { + this._updateScrollLeftForScrollToColumn({ + ...props, + scrollToColumn: columnIndex + }); + } + + if (rowIndex !== undefined) { + this._updateScrollTopForScrollToRow({ + ...props, + scrollToRow: rowIndex + }); + } + } + + componentDidMount() { + const { getScrollbarSize, height, scrollLeft, scrollToColumn, scrollTop, scrollToRow, width } = this.props; + + const { instanceProps } = this.state; + + // Reset initial offsets to be ignored in browser + this._initialScrollTop = 0; + this._initialScrollLeft = 0; + + // If cell sizes have been invalidated (eg we are using CellMeasurer) then reset cached positions. + // We must do this at the start of the method as we may calculate and update scroll position below. + this._handleInvalidatedVirtualGridSize(); + + // If this component was first rendered server-side, scrollbar size will be undefined. + // In that event we need to remeasure. + if (!instanceProps.scrollbarSizeMeasured) { + this.setState(prevState => { + const stateUpdate = { ...prevState, needToResetStyleCache: false }; + stateUpdate.instanceProps.scrollbarSize = getScrollbarSize(); + stateUpdate.instanceProps.scrollbarSizeMeasured = true; + return stateUpdate; + }); + } + + if ((typeof scrollLeft === 'number' && scrollLeft >= 0) || (typeof scrollTop === 'number' && scrollTop >= 0)) { + const stateUpdate = VirtualGrid._getScrollToPositionStateUpdate({ + prevState: this.state, + scrollLeft, + scrollTop + }); + if (stateUpdate) { + stateUpdate.needToResetStyleCache = false; + this.setState(stateUpdate); + } + } + + // refs don't work in `react-test-renderer` + if (this._scrollingContainer) { + // setting the ref's scrollLeft and scrollTop. + // Somehow in MultiVirtualGrid the main grid doesn't trigger a update on mount. + if (this._scrollingContainer.scrollLeft !== this.state.scrollLeft) { + this._scrollingContainer.scrollLeft = this.state.scrollLeft; + } + if (this._scrollingContainer.scrollTop !== this.state.scrollTop) { + this._scrollingContainer.scrollTop = this.state.scrollTop; + } + } + + // Don't update scroll offset if the size is 0; we don't render any cells in this case. + // Setting a state may cause us to later thing we've updated the offce when we haven't. + const sizeIsBiggerThanZero = height > 0 && width > 0; + if (scrollToColumn >= 0 && sizeIsBiggerThanZero) { + this._updateScrollLeftForScrollToColumn(); + } + if (scrollToRow >= 0 && sizeIsBiggerThanZero) { + this._updateScrollTopForScrollToRow(); + } + + // Update onRowsRendered callback + this._invokeOnVirtualGridRenderedHelper(); + + // Initialize onScroll callback + this._invokeOnScrollMemoizer({ + scrollLeft: scrollLeft || 0, + scrollTop: scrollTop || 0, + totalColumnsWidth: instanceProps.columnSizeAndPositionManager.getTotalSize(), + totalRowsHeight: instanceProps.rowSizeAndPositionManager.getTotalSize() + }); + + this._maybeCallOnScrollbarPresenceChange(); + } + + /** + * @private + * This method updates scrollLeft/scrollTop in state for the following conditions: + * 1) New scroll-to-cell props have been set + */ + componentDidUpdate(prevProps: Props, prevState: State) { + const { + autoHeight, + autoWidth, + columnCount, + height, + rowCount, + scrollToAlignment, + scrollToColumn, + scrollToRow, + width + } = this.props; + const { scrollLeft, scrollPositionChangeReason, scrollTop, instanceProps } = this.state; + // If cell sizes have been invalidated (eg we are using CellMeasurer) then reset cached positions. + // We must do this at the start of the method as we may calculate and update scroll position below. + this._handleInvalidatedVirtualGridSize(); + + // Handle edge case where column or row count has only just increased over 0. + // In this case we may have to restore a previously-specified scroll offset. + // For more info see bvaughn/react-virtualized/issues/218 + const columnOrRowCountJustIncreasedFromZero = + (columnCount > 0 && prevProps.columnCount === 0) || (rowCount > 0 && prevProps.rowCount === 0); + + // Make sure requested changes to :scrollLeft or :scrollTop get applied. + // Assigning to scrollLeft/scrollTop tells the browser to interrupt any running scroll animations, + // And to discard any pending async changes to the scroll position that may have happened in the meantime (e.g. on a separate scrolling thread). + // So we only set these when we require an adjustment of the scroll position. + // See issue #2 for more information. + if (scrollPositionChangeReason === SCROLL_POSITION_CHANGE_REASONS.REQUESTED) { + // @TRICKY :autoHeight and :autoWidth properties instructs VirtualGrid to leave :scrollTop and :scrollLeft management to an external HOC (eg WindowScroller). + // In this case we should avoid checking scrollingContainer.scrollTop and scrollingContainer.scrollLeft since it forces layout/flow. + if ( + !autoWidth && + scrollLeft >= 0 && + (scrollLeft !== this._scrollingContainer.scrollLeft || columnOrRowCountJustIncreasedFromZero) + ) { + this._scrollingContainer.scrollLeft = scrollLeft; + } + if ( + !autoHeight && + scrollTop >= 0 && + (scrollTop !== this._scrollingContainer.scrollTop || columnOrRowCountJustIncreasedFromZero) + ) { + this._scrollingContainer.scrollTop = scrollTop; + } + } + + // Special case where the previous size was 0: + // In this case we don't show any windowed cells at all. + // So we should always recalculate offset afterwards. + const sizeJustIncreasedFromZero = (prevProps.width === 0 || prevProps.height === 0) && (height > 0 && width > 0); + + // Update scroll offsets if the current :scrollToColumn or :scrollToRow values requires it + // @TODO Do we also need this check or can the one in componentWillUpdate() suffice? + if (this._recomputeScrollLeftFlag) { + this._recomputeScrollLeftFlag = false; + this._updateScrollLeftForScrollToColumn(this.props); + } else { + updateScrollIndexHelper({ + cellSizeAndPositionManager: instanceProps.columnSizeAndPositionManager, + previousCellsCount: prevProps.columnCount, + previousCellSize: prevProps.columnWidth, + previousScrollToAlignment: prevProps.scrollToAlignment, + previousScrollToIndex: prevProps.scrollToColumn, + previousSize: prevProps.width, + scrollOffset: scrollLeft, + scrollToAlignment, + scrollToIndex: scrollToColumn, + size: width, + sizeJustIncreasedFromZero, + updateScrollIndexCallback: () => this._updateScrollLeftForScrollToColumn(this.props) + }); + } + + if (this._recomputeScrollTopFlag) { + this._recomputeScrollTopFlag = false; + this._updateScrollTopForScrollToRow(this.props); + } else { + updateScrollIndexHelper({ + cellSizeAndPositionManager: instanceProps.rowSizeAndPositionManager, + previousCellsCount: prevProps.rowCount, + previousCellSize: prevProps.rowHeight, + previousScrollToAlignment: prevProps.scrollToAlignment, + previousScrollToIndex: prevProps.scrollToRow, + previousSize: prevProps.height, + scrollOffset: scrollTop, + scrollToAlignment, + scrollToIndex: scrollToRow, + size: height, + sizeJustIncreasedFromZero, + updateScrollIndexCallback: () => this._updateScrollTopForScrollToRow(this.props) + }); + } + + // Update onRowsRendered callback if start/stop indices have changed + this._invokeOnVirtualGridRenderedHelper(); + + // Changes to :scrollLeft or :scrollTop should also notify :onScroll listeners + if (scrollLeft !== prevState.scrollLeft || scrollTop !== prevState.scrollTop) { + const totalRowsHeight = instanceProps.rowSizeAndPositionManager.getTotalSize(); + const totalColumnsWidth = instanceProps.columnSizeAndPositionManager.getTotalSize(); + + this._invokeOnScrollMemoizer({ + scrollLeft, + scrollTop, + totalColumnsWidth, + totalRowsHeight + }); + } + + this._maybeCallOnScrollbarPresenceChange(); + } + + componentWillUnmount() { + if (this._disablePointerEventsTimeoutId) { + cancelAnimationTimeout(this._disablePointerEventsTimeoutId); + } + } + + /** + * This method updates scrollLeft/scrollTop in state for the following conditions: + * 1) Empty content (0 rows or columns) + * 2) New scroll props overriding the current state + * 3) Cells-count or cells-size has changed, making previous scroll offsets invalid + */ + static getDerivedStateFromProps(nextProps: Props, prevState: State): $Shape { + const newState = {}; + const { instanceProps } = prevState; + + if ( + (nextProps.columnCount === 0 && prevState.scrollLeft !== 0) || + (nextProps.rowCount === 0 && prevState.scrollTop !== 0) + ) { + newState.scrollLeft = 0; + newState.scrollTop = 0; + + // only use scroll{Left,Top} from props if scrollTo{Column,Row} isn't specified + // scrollTo{Column,Row} should override scroll{Left,Top} + } else if ( + (nextProps.scrollLeft !== instanceProps.prevScrollLeft && nextProps.scrollToColumn < 0) || + (nextProps.scrollTop !== instanceProps.prevScrollTop && nextProps.scrollToRow < 0) + ) { + Object.assign( + newState, + VirtualGrid._getScrollToPositionStateUpdate({ + prevState, + scrollLeft: nextProps.scrollLeft, + scrollTop: nextProps.scrollTop + }) + ); + } + + // Initially we should not clearStyleCache + newState.needToResetStyleCache = false; + if ( + nextProps.columnWidth !== instanceProps.prevColumnWidth || + nextProps.rowHeight !== instanceProps.prevRowHeight + ) { + // Reset cache. set it to {} in render + newState.needToResetStyleCache = true; + } + + instanceProps.columnSizeAndPositionManager.configure({ + cellCount: nextProps.columnCount, + estimatedCellSize: VirtualGrid._getEstimatedColumnSize(nextProps), + cellSizeGetter: VirtualGrid._wrapSizeGetter(nextProps.columnWidth) + }); + + instanceProps.rowSizeAndPositionManager.configure({ + cellCount: nextProps.rowCount, + estimatedCellSize: VirtualGrid._getEstimatedRowSize(nextProps), + cellSizeGetter: VirtualGrid._wrapSizeGetter(nextProps.rowHeight) + }); + + if (instanceProps.prevColumnCount === 0 || instanceProps.prevRowCount === 0) { + instanceProps.prevColumnCount = 0; + instanceProps.prevRowCount = 0; + } + + // If scrolling is controlled outside this component, clear cache when scrolling stops + if (nextProps.autoHeight && nextProps.isScrolling === false && instanceProps.prevIsScrolling === true) { + Object.assign(newState, { + isScrolling: false + }); + } + + let maybeStateA; + let maybeStateB; + + calculateSizeAndPositionDataAndUpdateScrollOffset({ + cellCount: instanceProps.prevColumnCount, + cellSize: typeof instanceProps.prevColumnWidth === 'number' ? instanceProps.prevColumnWidth : null, + computeMetadataCallback: () => instanceProps.columnSizeAndPositionManager.resetCell(0), + computeMetadataCallbackProps: nextProps, + nextCellsCount: nextProps.columnCount, + nextCellSize: typeof nextProps.columnWidth === 'number' ? nextProps.columnWidth : null, + nextScrollToIndex: nextProps.scrollToColumn, + scrollToIndex: instanceProps.prevScrollToColumn, + updateScrollOffsetForScrollToIndex: () => { + maybeStateA = VirtualGrid._getScrollLeftForScrollToColumnStateUpdate(nextProps, prevState); + } + }); + calculateSizeAndPositionDataAndUpdateScrollOffset({ + cellCount: instanceProps.prevRowCount, + cellSize: typeof instanceProps.prevRowHeight === 'number' ? instanceProps.prevRowHeight : null, + computeMetadataCallback: () => instanceProps.rowSizeAndPositionManager.resetCell(0), + computeMetadataCallbackProps: nextProps, + nextCellsCount: nextProps.rowCount, + nextCellSize: typeof nextProps.rowHeight === 'number' ? nextProps.rowHeight : null, + nextScrollToIndex: nextProps.scrollToRow, + scrollToIndex: instanceProps.prevScrollToRow, + updateScrollOffsetForScrollToIndex: () => { + maybeStateB = VirtualGrid._getScrollTopForScrollToRowStateUpdate(nextProps, prevState); + } + }); + + instanceProps.prevColumnCount = nextProps.columnCount; + instanceProps.prevColumnWidth = nextProps.columnWidth; + instanceProps.prevIsScrolling = nextProps.isScrolling === true; + instanceProps.prevRowCount = nextProps.rowCount; + instanceProps.prevRowHeight = nextProps.rowHeight; + instanceProps.prevScrollToColumn = nextProps.scrollToColumn; + instanceProps.prevScrollToRow = nextProps.scrollToRow; + instanceProps.prevScrollLeft = nextProps.scrollLeft; + instanceProps.prevScrollTop = nextProps.scrollTop; + + // getting scrollBarSize (moved from componentWillMount) + instanceProps.scrollbarSize = nextProps.getScrollbarSize(); + if (instanceProps.scrollbarSize === undefined) { + instanceProps.scrollbarSizeMeasured = false; + instanceProps.scrollbarSize = 0; + } else { + instanceProps.scrollbarSizeMeasured = true; + } + + newState.instanceProps = instanceProps; + + return { ...newState, ...maybeStateA, ...maybeStateB }; + } + + render() { + const { + autoContainerWidth, + autoHeight, + autoWidth, + className, + containerProps, + containerRole, + containerStyle, + height, + id, + noContentRenderer, + role, + style, + tabIndex, + width, + scrollContainerComponent, + innerScrollContainerComponent + } = this.props; + const { instanceProps, needToResetStyleCache } = this.state; + + const isScrolling = this._isScrolling(); + + const gridStyle: Object = { + boxSizing: 'border-box', + direction: 'ltr', + height: autoHeight ? 'auto' : height, + position: 'relative', + width: autoWidth ? 'auto' : width, + WebkitOverflowScrolling: 'touch', + willChange: 'transform' + }; + + if (needToResetStyleCache) { + this._styleCache = {}; + } + + // calculate _styleCache here + // if state.isScrolling (not from _isScrolling) then reset + if (!this.state.isScrolling) { + this._resetStyleCache(); + } + + // calculate children to render here + this._calculateChildrenToRender(this.props, this.state); + + const totalColumnsWidth = instanceProps.columnSizeAndPositionManager.getTotalSize(); + const totalRowsHeight = instanceProps.rowSizeAndPositionManager.getTotalSize(); + + // Force browser to hide scrollbars when we know they aren't necessary. + // Otherwise once scrollbars appear they may not disappear again. + // For more info see issue #116 + const verticalScrollBarSize = totalRowsHeight > height ? instanceProps.scrollbarSize : 0; + const horizontalScrollBarSize = totalColumnsWidth > width ? instanceProps.scrollbarSize : 0; + + if ( + horizontalScrollBarSize !== this._horizontalScrollBarSize || + verticalScrollBarSize !== this._verticalScrollBarSize + ) { + this._horizontalScrollBarSize = horizontalScrollBarSize; + this._verticalScrollBarSize = verticalScrollBarSize; + this._scrollbarPresenceChanged = true; + } + + // Also explicitly init styles to 'auto' if scrollbars are required. + // This works around an obscure edge case where external CSS styles have not yet been loaded, + // But an initial scroll index of offset is set as an external prop. + // Without this style, VirtualGrid would render the correct range of cells but would NOT update its internal offset. + // This was originally reported via clauderic/react-infinite-calendar/issues/23 + gridStyle.overflowX = totalColumnsWidth + verticalScrollBarSize <= width ? 'hidden' : 'auto'; + gridStyle.overflowY = totalRowsHeight + horizontalScrollBarSize <= height ? 'hidden' : 'auto'; + + const childrenToDisplay = this._childrenToDisplay; + + const showNoContentRenderer = childrenToDisplay.length === 0 && height > 0 && width > 0; + + const scrollContainerProps = { + ...containerProps, + ref: this._setScrollingContainerRef, + 'aria-label': this.props['aria-label'], + 'aria-readonly': this.props['aria-readonly'], + className: clsx('ReactVirtualized__VirtualGrid', className), + id, + onScroll: this._onScroll, + role, + style: { + ...gridStyle, + ...style + }, + tabIndex + }; + + let innerScrollContainer = null; + if (childrenToDisplay.length > 0) { + const innerScrollContainerProps = { + className: 'ReactVirtualized__VirtualGrid__innerScrollContainer', + key: 'ReactVirtualized__VirtualGrid__innerScrollContainer', + role: containerRole, + style: { + width: autoContainerWidth ? 'auto' : totalColumnsWidth, + height: totalRowsHeight, + maxWidth: totalColumnsWidth, + maxHeight: totalRowsHeight, + overflow: 'hidden', + pointerEvents: isScrolling ? 'none' : '', + position: 'relative', + ...containerStyle + } + }; + innerScrollContainer = React.createElement( + innerScrollContainerComponent, + innerScrollContainerProps, + childrenToDisplay + ); + } + return React.createElement(scrollContainerComponent, scrollContainerProps, [ + innerScrollContainer, + showNoContentRenderer && noContentRenderer() + ]); + } + + /* ---------------------------- Helper methods ---------------------------- */ + + _calculateChildrenToRender(props: Props = this.props, state: State = this.state) { + const { + cellRenderer, + cellRangeRenderer, + columnCount, + deferredMeasurementCache, + height, + overscanColumnCount, + overscanIndicesGetter, + overscanRowCount, + rowCount, + width, + isScrollingOptOut + } = props; + + const { scrollDirectionHorizontal, scrollDirectionVertical, instanceProps } = state; + + const scrollTop = this._initialScrollTop > 0 ? this._initialScrollTop : state.scrollTop; + const scrollLeft = this._initialScrollLeft > 0 ? this._initialScrollLeft : state.scrollLeft; + + const isScrolling = this._isScrolling(props, state); + + this._childrenToDisplay = []; + + // Render only enough columns and rows to cover the visible area of the grid. + if (height > 0 && width > 0) { + const visibleColumnIndices = instanceProps.columnSizeAndPositionManager.getVisibleCellRange({ + containerSize: width, + offset: scrollLeft + }); + const visibleRowIndices = instanceProps.rowSizeAndPositionManager.getVisibleCellRange({ + containerSize: height, + offset: scrollTop + }); + + const horizontalOffsetAdjustment = instanceProps.columnSizeAndPositionManager.getOffsetAdjustment({ + containerSize: width, + offset: scrollLeft + }); + const verticalOffsetAdjustment = instanceProps.rowSizeAndPositionManager.getOffsetAdjustment({ + containerSize: height, + offset: scrollTop + }); + + // Store for _invokeOnVirtualGridRenderedHelper() + this._renderedColumnStartIndex = visibleColumnIndices.start; + this._renderedColumnStopIndex = visibleColumnIndices.stop; + this._renderedRowStartIndex = visibleRowIndices.start; + this._renderedRowStopIndex = visibleRowIndices.stop; + + const overscanColumnIndices = overscanIndicesGetter({ + direction: 'horizontal', + cellCount: columnCount, + overscanCellsCount: overscanColumnCount, + scrollDirection: scrollDirectionHorizontal, + startIndex: typeof visibleColumnIndices.start === 'number' ? visibleColumnIndices.start : 0, + stopIndex: typeof visibleColumnIndices.stop === 'number' ? visibleColumnIndices.stop : -1 + }); + + const overscanRowIndices = overscanIndicesGetter({ + direction: 'vertical', + cellCount: rowCount, + overscanCellsCount: overscanRowCount, + scrollDirection: scrollDirectionVertical, + startIndex: typeof visibleRowIndices.start === 'number' ? visibleRowIndices.start : 0, + stopIndex: typeof visibleRowIndices.stop === 'number' ? visibleRowIndices.stop : -1 + }); + + // Store for _invokeOnVirtualGridRenderedHelper() + let columnStartIndex = overscanColumnIndices.overscanStartIndex; + let columnStopIndex = overscanColumnIndices.overscanStopIndex; + let rowStartIndex = overscanRowIndices.overscanStartIndex; + let rowStopIndex = overscanRowIndices.overscanStopIndex; + + // Advanced use-cases (eg CellMeasurer) require batched measurements to determine accurate sizes. + if (deferredMeasurementCache) { + // If rows have a dynamic height, scan the rows we are about to render. + // If any have not yet been measured, then we need to render all columns initially, + // Because the height of the row is equal to the tallest cell within that row, + // (And so we can't know the height without measuring all column-cells first). + if (!deferredMeasurementCache.hasFixedHeight()) { + for (let rowIndex = rowStartIndex; rowIndex <= rowStopIndex; rowIndex++) { + if (!deferredMeasurementCache.has(rowIndex, 0)) { + columnStartIndex = 0; + columnStopIndex = columnCount - 1; + break; + } + } + } + + // If columns have a dynamic width, scan the columns we are about to render. + // If any have not yet been measured, then we need to render all rows initially, + // Because the width of the column is equal to the widest cell within that column, + // (And so we can't know the width without measuring all row-cells first). + if (!deferredMeasurementCache.hasFixedWidth()) { + for (let columnIndex = columnStartIndex; columnIndex <= columnStopIndex; columnIndex++) { + if (!deferredMeasurementCache.has(0, columnIndex)) { + rowStartIndex = 0; + rowStopIndex = rowCount - 1; + break; + } + } + } + } + + this._childrenToDisplay = cellRangeRenderer({ + cellCache: this._cellCache, + cellRenderer, + columnSizeAndPositionManager: instanceProps.columnSizeAndPositionManager, + columnStartIndex, + columnStopIndex, + deferredMeasurementCache, + horizontalOffsetAdjustment, + isScrolling, + isScrollingOptOut, + parent: this, + rowSizeAndPositionManager: instanceProps.rowSizeAndPositionManager, + rowStartIndex, + rowStopIndex, + scrollLeft, + scrollTop, + styleCache: this._styleCache, + verticalOffsetAdjustment, + visibleColumnIndices, + visibleRowIndices + }); + + // update the indices + this._columnStartIndex = columnStartIndex; + this._columnStopIndex = columnStopIndex; + this._rowStartIndex = rowStartIndex; + this._rowStopIndex = rowStopIndex; + } + } + + /** + * Sets an :isScrolling flag for a small window of time. + * This flag is used to disable pointer events on the scrollable portion of the VirtualGrid. + * This prevents jerky/stuttery mouse-wheel scrolling. + */ + _debounceScrollEnded() { + const { scrollingResetTimeInterval } = this.props; + + if (this._disablePointerEventsTimeoutId) { + cancelAnimationTimeout(this._disablePointerEventsTimeoutId); + } + + this._disablePointerEventsTimeoutId = requestAnimationTimeout( + this._debounceScrollEndedCallback, + scrollingResetTimeInterval + ); + } + + _debounceScrollEndedCallback = () => { + this._disablePointerEventsTimeoutId = null; + // isScrolling is used to determine if we reset styleCache + this.setState({ + isScrolling: false, + needToResetStyleCache: false + }); + }; + + static _getEstimatedColumnSize(props: Props) { + return typeof props.columnWidth === 'number' ? props.columnWidth : props.estimatedColumnSize; + } + + static _getEstimatedRowSize(props: Props) { + return typeof props.rowHeight === 'number' ? props.rowHeight : props.estimatedRowSize; + } + + /** + * Check for batched CellMeasurer size invalidations. + * This will occur the first time one or more previously unmeasured cells are rendered. + */ + _handleInvalidatedVirtualGridSize() { + if ( + typeof this._deferredInvalidateColumnIndex === 'number' && + typeof this._deferredInvalidateRowIndex === 'number' + ) { + const columnIndex = this._deferredInvalidateColumnIndex; + const rowIndex = this._deferredInvalidateRowIndex; + + this._deferredInvalidateColumnIndex = null; + this._deferredInvalidateRowIndex = null; + + this.recomputeVirtualGridSize({ columnIndex, rowIndex }); + } + } + + _invokeOnVirtualGridRenderedHelper = () => { + const { onSectionRendered } = this.props; + + this._onVirtualGridRenderedMemoizer({ + callback: onSectionRendered, + indices: { + columnOverscanStartIndex: this._columnStartIndex, + columnOverscanStopIndex: this._columnStopIndex, + columnStartIndex: this._renderedColumnStartIndex, + columnStopIndex: this._renderedColumnStopIndex, + rowOverscanStartIndex: this._rowStartIndex, + rowOverscanStopIndex: this._rowStopIndex, + rowStartIndex: this._renderedRowStartIndex, + rowStopIndex: this._renderedRowStopIndex + } + }); + }; + + _invokeOnScrollMemoizer({ + scrollLeft, + scrollTop, + totalColumnsWidth, + totalRowsHeight + }: { + scrollLeft: number, + scrollTop: number, + totalColumnsWidth: number, + totalRowsHeight: number + }) { + this._onScrollMemoizer({ + callback: ({ scrollLeft, scrollTop }) => { + const { height, onScroll, width } = this.props; + + onScroll({ + clientHeight: height, + clientWidth: width, + scrollHeight: totalRowsHeight, + scrollLeft, + scrollTop, + scrollWidth: totalColumnsWidth + }); + }, + indices: { + scrollLeft, + scrollTop + } + }); + } + + _isScrolling(props: Props = this.props, state: State = this.state): boolean { + // If isScrolling is defined in props, use it to override the value in state + // This is a performance optimization for WindowScroller + VirtualGrid + return Object.hasOwnProperty.call(props, 'isScrolling') ? Boolean(props.isScrolling) : Boolean(state.isScrolling); + } + + _maybeCallOnScrollbarPresenceChange() { + if (this._scrollbarPresenceChanged) { + const { onScrollbarPresenceChange } = this.props; + + this._scrollbarPresenceChanged = false; + + onScrollbarPresenceChange({ + horizontal: this._horizontalScrollBarSize > 0, + size: this.state.instanceProps.scrollbarSize, + vertical: this._verticalScrollBarSize > 0 + }); + } + } + + _setScrollingContainerRef = (ref: Element) => { + this._scrollingContainer = ref; + }; + + /** + * Get the updated state after scrolling to + * scrollLeft and scrollTop + */ + static _getScrollToPositionStateUpdate({ + prevState, + scrollLeft, + scrollTop + }: { + prevState: State, + scrollLeft?: number, + scrollTop?: number + }): $Shape { + const newState: Object = { + scrollPositionChangeReason: SCROLL_POSITION_CHANGE_REASONS.REQUESTED + }; + + if (typeof scrollLeft === 'number' && scrollLeft >= 0) { + newState.scrollDirectionHorizontal = + scrollLeft > prevState.scrollLeft ? SCROLL_DIRECTION_FORWARD : SCROLL_DIRECTION_BACKWARD; + newState.scrollLeft = scrollLeft; + } + + if (typeof scrollTop === 'number' && scrollTop >= 0) { + newState.scrollDirectionVertical = + scrollTop > prevState.scrollTop ? SCROLL_DIRECTION_FORWARD : SCROLL_DIRECTION_BACKWARD; + newState.scrollTop = scrollTop; + } + + if ( + (typeof scrollLeft === 'number' && scrollLeft >= 0 && scrollLeft !== prevState.scrollLeft) || + (typeof scrollTop === 'number' && scrollTop >= 0 && scrollTop !== prevState.scrollTop) + ) { + return newState; + } + return null; + } + + /** + * Scroll to the specified offset(s). + * Useful for animating position changes. + */ + scrollToPosition({ scrollLeft, scrollTop }: ScrollPosition) { + const stateUpdate = VirtualGrid._getScrollToPositionStateUpdate({ + prevState: this.state, + scrollLeft, + scrollTop + }); + + if (stateUpdate) { + stateUpdate.needToResetStyleCache = false; + this.setState(stateUpdate); + } + } + + static _wrapSizeGetter(value: CellSize): CellSizeGetter { + return typeof value === 'function' ? value : () => (value: any); + } + + static _getCalculatedScrollLeft(nextProps: Props, prevState: State) { + const { columnCount, height, scrollToAlignment, scrollToColumn, width } = nextProps; + const { scrollLeft, instanceProps } = prevState; + + if (columnCount > 0) { + const finalColumn = columnCount - 1; + const targetIndex = scrollToColumn < 0 ? finalColumn : Math.min(finalColumn, scrollToColumn); + const totalRowsHeight = instanceProps.rowSizeAndPositionManager.getTotalSize(); + const scrollBarSize = + instanceProps.scrollbarSizeMeasured && totalRowsHeight > height ? instanceProps.scrollbarSize : 0; + + return instanceProps.columnSizeAndPositionManager.getUpdatedOffsetForIndex({ + align: scrollToAlignment, + containerSize: width - scrollBarSize, + currentOffset: scrollLeft, + targetIndex + }); + } + return 0; + } + + _getCalculatedScrollLeft(props: Props = this.props, state: State = this.state) { + return VirtualGrid._getCalculatedScrollLeft(props, state); + } + + static _getScrollLeftForScrollToColumnStateUpdate(nextProps: Props, prevState: State): $Shape { + const { scrollLeft } = prevState; + const calculatedScrollLeft = VirtualGrid._getCalculatedScrollLeft(nextProps, prevState); + + if (typeof calculatedScrollLeft === 'number' && calculatedScrollLeft >= 0 && scrollLeft !== calculatedScrollLeft) { + return VirtualGrid._getScrollToPositionStateUpdate({ + prevState, + scrollLeft: calculatedScrollLeft, + scrollTop: -1 + }); + } + return null; + } + + _updateScrollLeftForScrollToColumn(props: Props = this.props, state: State = this.state) { + const stateUpdate = VirtualGrid._getScrollLeftForScrollToColumnStateUpdate(props, state); + if (stateUpdate) { + stateUpdate.needToResetStyleCache = false; + this.setState(stateUpdate); + } + } + + static _getCalculatedScrollTop(nextProps: Props, prevState: State) { + const { height, rowCount, scrollToAlignment, scrollToRow, width } = nextProps; + const { scrollTop, instanceProps } = prevState; + + if (rowCount > 0) { + const finalRow = rowCount - 1; + const targetIndex = scrollToRow < 0 ? finalRow : Math.min(finalRow, scrollToRow); + const totalColumnsWidth = instanceProps.columnSizeAndPositionManager.getTotalSize(); + const scrollBarSize = + instanceProps.scrollbarSizeMeasured && totalColumnsWidth > width ? instanceProps.scrollbarSize : 0; + + return instanceProps.rowSizeAndPositionManager.getUpdatedOffsetForIndex({ + align: scrollToAlignment, + containerSize: height - scrollBarSize, + currentOffset: scrollTop, + targetIndex + }); + } + return 0; + } + + _getCalculatedScrollTop(props: Props = this.props, state: State = this.state) { + return VirtualGrid._getCalculatedScrollTop(props, state); + } + + _resetStyleCache() { + const styleCache = this._styleCache; + const cellCache = this._cellCache; + const { isScrollingOptOut } = this.props; + + // Reset cell and style caches once scrolling stops. + // This makes VirtualGrid simpler to use (since cells commonly change). + // And it keeps the caches from growing too large. + // Performance is most sensitive when a user is scrolling. + // Don't clear visible cells from cellCache if isScrollingOptOut is specified. + // This keeps the cellCache to a resonable size. + this._cellCache = {}; + this._styleCache = {}; + + // Copy over the visible cell styles so avoid unnecessary re-render. + for (let rowIndex = this._rowStartIndex; rowIndex <= this._rowStopIndex; rowIndex++) { + for (let columnIndex = this._columnStartIndex; columnIndex <= this._columnStopIndex; columnIndex++) { + const key = `${rowIndex}-${columnIndex}`; + this._styleCache[key] = styleCache[key]; + + if (isScrollingOptOut) { + this._cellCache[key] = cellCache[key]; + } + } + } + } + + static _getScrollTopForScrollToRowStateUpdate(nextProps: Props, prevState: State): $Shape { + const { scrollTop } = prevState; + const calculatedScrollTop = VirtualGrid._getCalculatedScrollTop(nextProps, prevState); + + if (typeof calculatedScrollTop === 'number' && calculatedScrollTop >= 0 && scrollTop !== calculatedScrollTop) { + return VirtualGrid._getScrollToPositionStateUpdate({ + prevState, + scrollLeft: -1, + scrollTop: calculatedScrollTop + }); + } + return null; + } + + _updateScrollTopForScrollToRow(props: Props = this.props, state: State = this.state) { + const stateUpdate = VirtualGrid._getScrollTopForScrollToRowStateUpdate(props, state); + if (stateUpdate) { + stateUpdate.needToResetStyleCache = false; + this.setState(stateUpdate); + } + } + + _onScroll = (event: Event) => { + // In certain edge-cases React dispatches an onScroll event with an invalid target.scrollLeft / target.scrollTop. + // This invalid event can be detected by comparing event.target to this component's scrollable DOM element. + // See issue #404 for more information. + if (event.target === this._scrollingContainer) { + this.handleScrollEvent((event.target: any)); + } + }; +} + +polyfill(VirtualGrid); +export default VirtualGrid; diff --git a/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/VirtualTableBody.js b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/VirtualTableBody.js new file mode 100644 index 00000000000..f54dd8f4628 --- /dev/null +++ b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/VirtualTableBody.js @@ -0,0 +1,287 @@ +/** @flow */ + +import * as React from 'react'; +import type { + NoContentRenderer, + Alignment, + CellSize, + CellPosition, + OverscanIndicesGetter, + RenderedSection, + CellRendererParams, + Scroll as VirtualGridScroll, + RowRenderer, + RenderedRows, + Scroll +} from './types'; + +import accessibilityOverscanIndicesGetter from './accessibilityOverscanIndicesGetter'; +import VirtualGrid from './VirtualGrid'; +import clsx from 'clsx'; + +/** + * It is inefficient to create and manage a large list of DOM elements within a scrolling container + * if only a few of those elements are visible. The primary purpose of this component is to improve + * performance by only rendering the DOM nodes that a user is able to see based on their current + * scroll position. + * + * This component renders a virtualized list of elements with either fixed or dynamic heights. + */ + +type Props = { + 'aria-label'?: string, + + /** + * Removes fixed height from the scrollingContainer so that the total height + * of rows can stretch the window. Intended for use with WindowScroller + */ + autoHeight: boolean, + + /** Optional CSS class name */ + className?: string, + + /** + * Used to estimate the total height of a List before all of its rows have actually been measured. + * The estimated total height is adjusted as rows are rendered. + */ + estimatedRowSize: number, + + /** Height constraint for list (determines how many actual rows are rendered) */ + height: number, + + /** Optional renderer to be used in place of rows when rowCount is 0 */ + noRowsRenderer: NoContentRenderer, + + /** Callback invoked with information about the slice of rows that were just rendered. */ + + onRowsRendered: (params: RenderedRows) => void, + + /** + * Callback invoked whenever the scroll offset changes within the inner scrollable region. + * This callback can be used to sync scrolling between lists, tables, or grids. + */ + onScroll: (params: Scroll) => void, + + /** See VirtualGrid#overscanIndicesGetter */ + overscanIndicesGetter: OverscanIndicesGetter, + + /** + * Number of rows to render above/below the visible bounds of the list. + * These rows can help for smoother scrolling on touch devices. + */ + overscanRowCount: number, + + /** Either a fixed row height (number) or a function that returns the height of a row given its index. */ + rowHeight: CellSize, + + /** Responsible for rendering a row given an index; ({ index: number }): node */ + rowRenderer: RowRenderer, + + /** Number of rows in list. */ + rowCount: number, + + /** See VirtualGrid#scrollToAlignment */ + scrollToAlignment: Alignment, + + /** Row index to ensure visible (by forcefully scrolling if necessary) */ + scrollToIndex: number, + + /** Vertical offset. */ + scrollTop?: number, + + /** Optional inline style */ + style: Object, + + /** Tab index for focus */ + tabIndex?: number, + + /** Width of list */ + width: number, + + columns: Array, + + rows: Array +}; + +export default class VirtualTableBody extends React.PureComponent { + static defaultProps = { + autoHeight: false, + estimatedRowSize: 30, + onScroll: () => {}, + noRowsRenderer: () => null, + onRowsRendered: () => {}, + overscanIndicesGetter: accessibilityOverscanIndicesGetter, + overscanRowCount: 10, + scrollToAlignment: 'auto', + scrollToIndex: -1, + style: {} + }; + + VirtualGrid: ?React.ElementRef; + + forceUpdateVirtualGrid() { + if (this.VirtualGrid) { + this.VirtualGrid.forceUpdate(); + } + } + + /** See VirtualGrid#getOffsetForCell */ + getOffsetForRow({ alignment, index }: { alignment: Alignment, index: number }) { + if (this.VirtualGrid) { + const { scrollTop } = this.VirtualGrid.getOffsetForCell({ + alignment, + rowIndex: index, + columnIndex: 0 + }); + + return scrollTop; + } + return 0; + } + + /** CellMeasurer compatibility */ + invalidateCellSizeAfterRender({ columnIndex, rowIndex }: CellPosition) { + if (this.VirtualGrid) { + this.VirtualGrid.invalidateCellSizeAfterRender({ + rowIndex, + columnIndex + }); + } + } + + /** See VirtualGrid#measureAllCells */ + measureAllRows() { + if (this.VirtualGrid) { + this.VirtualGrid.measureAllCells(); + } + } + + /** CellMeasurer compatibility */ + recomputeVirtualGridSize({ columnIndex = 0, rowIndex = 0 }: CellPosition = {}) { + if (this.VirtualGrid) { + this.VirtualGrid.recomputeVirtualGridSize({ + rowIndex, + columnIndex + }); + } + } + + /** See VirtualGrid#recomputeVirtualGridSize */ + recomputeRowHeights(index: number = 0) { + if (this.VirtualGrid) { + this.VirtualGrid.recomputeVirtualGridSize({ + rowIndex: index, + columnIndex: 0 + }); + } + } + + /** See VirtualGrid#scrollToPosition */ + scrollToPosition(scrollTop: number = 0) { + if (this.VirtualGrid) { + this.VirtualGrid.scrollToPosition({ scrollTop }); + } + } + + /** See VirtualGrid#scrollToCell */ + scrollToRow(index: number = 0) { + if (this.VirtualGrid) { + this.VirtualGrid.scrollToCell({ + columnIndex: 0, + rowIndex: index + }); + } + } + + render() { + const { className, noRowsRenderer, scrollToIndex, width, columns, rows, tabIndex, style } = this.props; + + const classNames = clsx('ReactVirtualized__List', className); + + return ( + // note: these aria props if rendered will break a11y for role="presentation" + // this approach attempts to fix non standard table grids + // see: https://www.html5accessibility.com/tests/aria-table-fix.html + + ); + } + + _cellRenderer = ({ parent, rowIndex, style, isScrolling, isVisible, key }: CellRendererParams) => { + const { rowRenderer } = this.props; + + // TRICKY The style object is sometimes cached by VirtualGrid. + // This prevents new style objects from bypassing shallowCompare(). + // However as of React 16, style props are auto-frozen (at least in dev mode) + // Check to make sure we can still modify the style before proceeding. + // https://github.com/facebook/react/commit/977357765b44af8ff0cfea327866861073095c12#commitcomment-20648713 + const { writable } = Object.getOwnPropertyDescriptor(style, 'width'); + if (writable) { + // By default, List cells should be 100% width. + // This prevents them from flowing under a scrollbar (if present). + style.width = '100%'; + } + + return rowRenderer({ + index: rowIndex, + style, + isScrolling, + isVisible, + key, + parent + }); + }; + + _setRef = (ref: ?React.ElementRef) => { + this.VirtualGrid = ref; + }; + + _onScroll = ({ clientHeight, scrollHeight, scrollTop }: VirtualGridScroll) => { + const { onScroll } = this.props; + + onScroll({ clientHeight, scrollHeight, scrollTop }); + }; + + _onSectionRendered = ({ + rowOverscanStartIndex, + rowOverscanStopIndex, + rowStartIndex, + rowStopIndex + }: RenderedSection) => { + const { onRowsRendered } = this.props; + + onRowsRendered({ + overscanStartIndex: rowOverscanStartIndex, + overscanStopIndex: rowOverscanStopIndex, + startIndex: rowStartIndex, + stopIndex: rowStopIndex + }); + }; +} diff --git a/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/Virtualized.md b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/Virtualized.md new file mode 100644 index 00000000000..73ced06a489 --- /dev/null +++ b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/Virtualized.md @@ -0,0 +1,590 @@ +--- +title: 'Table' +section: 'Virtual Scroll' +--- + +import clsx from 'clsx'; +import PropTypes from 'prop-types'; +import * as React from 'react'; +import { ActionsColumn, Table, TableHeader, TableGridBreakpoint, headerCol, sortable, SortByDirection } from '@patternfly/react-table'; +import { CellMeasurerCache, CellMeasurer} from 'react-virtualized'; +import { AutoSizer, VirtualTableBody } from '@patternfly/react-virtualized-extension'; +import UUID from 'uuid/v1'; +import virtualGridStyles from './VirtualGrid.example.css'; + + +## Simple Example + +```js +import clsx from 'clsx'; +import PropTypes from 'prop-types'; +import * as React from 'react'; +import { Table, TableHeader, TableGridBreakpoint } from '@patternfly/react-table'; +import { CellMeasurerCache, CellMeasurer} from 'react-virtualized'; +import { AutoSizer, VirtualTableBody } from '@patternfly/react-virtualized-extension'; +import virtualGridStyles from './VirtualGrid.example.css'; + +class VirtualizedExample extends React.Component { + constructor(){ + const rows = []; + for (let i = 0; i < 100; i++) { + rows.push({ + id: UUID(), + cells: [`one-${i}`, `two-${i}`, `three-${i}`, `four-${i}`, `five-${i}`] + }); + } + + this.state = { + columns: [ + { title: 'Repositories', props: { className: 'pf-m-6-col-on-sm pf-m-4-col-on-md pf-m-3-col-on-lg pf-m-2-col-on-xl'} }, + { title: 'Branches', props: { className: 'pf-m-6-col-on-sm pf-m-4-col-on-md pf-m-3-col-on-lg pf-m-2-col-on-xl'} }, + { title: 'Pull requests', props: { className: 'pf-m-4-col-on-md pf-m-4-col-on-lg pf-m-3-col-on-xl pf-m-hidden pf-m-visible-on-md'} }, + { title: 'Workspaces', props: { className: 'pf-m-2-col-on-lg pf-m-2-col-on-xl pf-m-hidden pf-m-visible-on-lg'} }, + { title: 'Last Commit', props: { className: 'pf-m-3-col-on-xl pf-m-hidden pf-m-visible-on-xl'} } + ], + rows + }; + this._handleResize = this._handleResize.bind(this); + } + + componentDidMount(){ + // re-render after resize + window.addEventListener('resize', this._handleResize); + } + + componentWillUnmount(){ + window.removeEventListener('resize', this._handleResize); + } + + _handleResize() { + this.forceUpdate(); + } + + render() { + const {columns, rows} = this.state; + + const measurementCache = new CellMeasurerCache({ + fixedWidth: true, + minHeight: 44, + keyMapper: rowIndex => rowIndex + }); + + const rowRenderer = ({index, isScrolling, isVisible, key, style, parent}) => { + const {rows, columns} = this.state; + const text = rows[index].cells[0]; + + const className = clsx({ + isVisible: isVisible + }); + + // do not render non visible elements (this excludes overscan) + if(!isVisible){ + return null; + } + return + + {text} + {text} + {text} + {text} + {text} + + ; + } + + return ( +
+ + +
+ + {({width}) => ( + + )} + +
+ ); + } +} + +export default VirtualizedExample; +``` + +## Sortable Example + +```js +import clsx from 'clsx'; +import PropTypes from 'prop-types'; +import * as React from 'react'; +import { Table, TableHeader, sortable, SortByDirection, TableGridBreakpoint } from '@patternfly/react-table'; +import { CellMeasurerCache, CellMeasurer} from 'react-virtualized'; +import { AutoSizer, VirtualTableBody } from '@patternfly/react-virtualized-extension'; +import virtualGridStyles from './VirtualGrid.example.css'; + +class SortableExample extends React.Component { + constructor(){ + const rows = []; + for (let i = 0; i < 100; i++) { + rows.push({ + id: UUID(), + cells: [`one-${i}`, `two-${i}`, `three-${i}`, `four-${i}`, `five-${i}`] + }); + } + + this.sortableVirtualBody = null; + + this.state = { + columns: [ + { title: 'Repositories', transforms: [sortable], props: { className: 'pf-m-6-col-on-sm pf-m-4-col-on-md pf-m-3-col-on-lg pf-m-2-col-on-xl'} }, + { title: 'Branches', props: { className: 'pf-m-6-col-on-sm pf-m-4-col-on-md pf-m-3-col-on-lg pf-m-2-col-on-xl'} }, + { title: 'Pull requests', transforms: [sortable], props: { className: 'pf-m-4-col-on-md pf-m-4-col-on-lg pf-m-3-col-on-xl pf-m-hidden pf-m-visible-on-md'} }, + { title: 'Workspaces', props: { className: 'pf-m-2-col-on-lg pf-m-2-col-on-xl pf-m-hidden pf-m-visible-on-lg'} }, + { title: 'Last Commit', props: { className: 'pf-m-3-col-on-xl pf-m-hidden pf-m-visible-on-xl'} } + ], + rows, + sortBy: {} + }; + + this.onSort = this.onSort.bind(this); + this._handleResize = this._handleResize.bind(this); + } + + componentDidMount(){ + // re-render after resize + window.addEventListener('resize', this._handleResize); + } + + componentWillUnmount(){ + window.removeEventListener('resize', this._handleResize); + } + + _handleResize() { + this.forceUpdate(); + } + + onSort(_event, index, direction) { + const sortedRows = this.state.rows.sort((a, b) => + a.cells[index] < b.cells[index] ? -1 : a.cells[index] > b.cells[index] ? 1 : 0 + ); + this.setState({ + sortBy: { + index, + direction + }, + rows: direction === SortByDirection.asc ? sortedRows : sortedRows.reverse() + }); + + this.sortableVirtualBody.forceUpdateVirtualGrid(); + } + + render() { + const {sortBy, columns, rows} = this.state; + + const measurementCache = new CellMeasurerCache({ + fixedWidth: true, + minHeight: 44, + keyMapper: rowIndex => rowIndex + }); + + const rowRenderer = ({index, isScrolling, isVisible, key, style, parent}) => { + const {rows, columns} = this.state; + const text = rows[index].cells[0]; + + const className = clsx({ + isVisible: isVisible + }); + + // do not render non visible elements (this excludes overscan) + if(!isVisible){ + return null; + } + return + + {text} + {text} + {text} + {text} + {text} + + ; + } + + return ( +
+ + +
+ + {({width}) => ( + this.sortableVirtualBody = ref} + className={'pf-c-table pf-c-virtualized pf-c-window-scroller'} + deferredMeasurementCache={measurementCache} + rowHeight={measurementCache.rowHeight} + height={400} + overscanRowCount={2} + columns={columns} + rows={rows} + rowCount={rows.length} + rowRenderer={rowRenderer} + width={width} + /> + )} + +
+ ); + } +} + +export default SortableExample; +``` + +## Selectable Example + +```js +import clsx from 'clsx'; +import PropTypes from 'prop-types'; +import * as React from 'react'; +import { Table, TableHeader, headerCol, TableGridBreakpoint } from '@patternfly/react-table'; +import { CellMeasurerCache, CellMeasurer} from 'react-virtualized'; +import { AutoSizer, VirtualTableBody } from '@patternfly/react-virtualized-extension'; +import virtualGridStyles from './VirtualGrid.example.css'; + +class SelectableExample extends React.Component { + constructor(){ + const rows = []; + for (let i = 0; i < 100; i++) { + rows.push({ + selected: false, + id: UUID(), + cells: [`one-${i}`, `two-${i}`, `three-${i}`, `four-${i}`, `five-${i}`] + }); + } + + this.selectableVirtualBody = null; + + this.state = { + columns: [ + //headerCol transform adds checkbox column with pf-m-2-sm, pf-m-1-md+ column space + { title: 'Repositories', cellTransforms: [headerCol()], props: { className: 'pf-m-5-col-on-sm pf-m-4-col-on-md pf-m-3-col-on-lg pf-m-2-col-on-xl'} }, + { title: 'Pull requests', props: { className: 'pf-m-5-col-on-sm pf-m-4-col-on-md pf-m-4-col-on-lg pf-m-3-col-on-xl'} }, + { title: 'Workspaces', props: { className: 'pf-m-2-col-on-lg pf-m-2-col-on-xl pf-m-hidden pf-m-visible-on-lg'} }, + { title: 'Last Commit', props: { className: 'pf-m-3-col-on-xl pf-m-hidden pf-m-visible-on-xl'} } + ], + rows + }; + + this.onSelect = this.onSelect.bind(this); + this._handleResize = this._handleResize.bind(this); + } + + componentDidMount(){ + // re-render after resize + window.addEventListener('resize', this._handleResize); + } + + componentWillUnmount(){ + window.removeEventListener('resize', this._handleResize); + } + + _handleResize() { + this.forceUpdate(); + } + + onSelect(event, isSelected, virtualRowIndex, rowData) { + let rows; + if (virtualRowIndex === -1) { + rows = this.state.rows.map(oneRow => { + oneRow.selected = isSelected; + return oneRow; + }); + } else { + rows = [...this.state.rows]; + const rowIndex = rows.findIndex(r => r.id === rowData.id); + rows[rowIndex].selected = isSelected; + } + this.setState({ + rows + }); + this.selectableVirtualBody.forceUpdateVirtualGrid(); + } + + render() { + const {columns, rows} = this.state; + + const measurementCache = new CellMeasurerCache({ + fixedWidth: true, + minHeight: 44, + keyMapper: rowIndex => rowIndex + }); + + const rowRenderer = ({index, isScrolling, isVisible, key, style, parent}) => { + const {rows, columns} = this.state; + const text = rows[index].cells[0]; + + const className = clsx({ + isVisible: isVisible + }); + + // do not render non visible elements (this excludes overscan) + if(!isVisible){ + return null; + } + return + + + + { this.onSelect(e, e.target.checked, 0, {id: rows[index].id})}} + /> + + {text} + {text} + {text} + {text} + + ; + } + + return ( +
+ + +
+ + {({width}) => ( + this.selectableVirtualBody = ref} + className={'pf-c-table pf-c-virtualized pf-c-window-scroller'} + deferredMeasurementCache={measurementCache} + rowHeight={measurementCache.rowHeight} + height={400} + overscanRowCount={2} + columns={columns} + rows={rows} + rowCount={rows.length} + rowRenderer={rowRenderer} + width={width} + /> + )} + +
+ ); + } +} + +export default SelectableExample; +``` + +## Actions Example + +```js +import clsx from 'clsx'; +import PropTypes from 'prop-types'; +import * as React from 'react'; +import { ActionsColumn, Table, TableHeader, TableGridBreakpoint } from '@patternfly/react-table'; +import { CellMeasurerCache, CellMeasurer} from 'react-virtualized'; +import { AutoSizer, VirtualTableBody } from '@patternfly/react-virtualized-extension'; +import virtualGridStyles from './VirtualGrid.example.css'; + +class ActionsExample extends React.Component { + constructor(){ + const rows = []; + for (let i = 0; i < 100; i++) { + rows.push({ + disableActions: i % 3 === 2, + id: UUID(), + cells: [`one-${i}`, `two-${i}`, `three-${i}`, `four-${i}`, `five-${i}`] + }); + } + + this.actionsVirtualBody = null; + + this.state = { + columns: [ + { title: 'Name', props: { className: 'pf-m-6-col-on-sm pf-m-4-col-on-md pf-m-3-col-on-lg pf-m-2-col-on-xl'} }, + { title: 'Namespace', props: { className: 'pf-m-6-col-on-sm pf-m-4-col-on-md pf-m-3-col-on-lg pf-m-2-col-on-xl'} }, + { title: 'Labels', props: { className: 'pf-m-4-col-on-md pf-m-4-col-on-lg pf-m-3-col-on-xl pf-m-hidden pf-m-visible-on-md'} }, + { title: 'Status', props: { className: 'pf-m-2-col-on-lg pf-m-2-col-on-xl pf-m-hidden pf-m-visible-on-lg'} }, + { title: 'Pod Selector', props: { className: 'pf-m-2-col-on-xl pf-m-hidden pf-m-visible-on-xl'} }, + { title: '', props: { className: 'pf-c-table__action'}}, + ], + rows, + actions: [ + { + title: 'Some action', + onClick: (event, rowId, rowData, extra) => console.log('clicked on Some action, on row: ', rowId) + }, + { + title:
Another action
, + onClick: (event, rowId, rowData, extra) => console.log('clicked on Another action, on row: ', rowId) + }, + { + isSeparator: true + }, + { + title: 'Third action', + onClick: (event, rowId, rowData, extra) => console.log('clicked on Third action, on row: ', rowId) + } + ] + }; + + this._handleResize = this._handleResize.bind(this); + } + + componentDidMount(){ + // re-render after resize + window.addEventListener('resize', this._handleResize); + } + + componentWillUnmount(){ + window.removeEventListener('resize', this._handleResize); + } + + _handleResize() { + this.forceUpdate(); + } + + render() { + const {columns, rows} = this.state; + + const measurementCache = new CellMeasurerCache({ + fixedWidth: true, + minHeight: 44, + keyMapper: rowIndex => rowIndex + }); + + const rowRenderer = ({index, isScrolling, isVisible, key, style, parent}) => { + const {rows, columns, actions} = this.state; + const text = rows[index].cells[0]; + + const className = clsx({ + isVisible: isVisible + }); + + // do not render non visible elements (this excludes overscan) + if(!isVisible){ + return null; + } + return + + {text} + {text} + {text} + {text} + {text} + + + + + ; + } + + return ( +
+ + +
+ + {({width}) => ( + this.actionsVirtualBody = ref} + className={'pf-c-table pf-c-virtualized pf-c-window-scroller'} + deferredMeasurementCache={measurementCache} + rowHeight={measurementCache.rowHeight} + height={400} + overscanRowCount={2} + columns={columns} + rows={rows} + rowCount={rows.length} + rowRenderer={rowRenderer} + width={width} + /> + )} + +
+ ); + } +} + +export default ActionsExample; +``` \ No newline at end of file diff --git a/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/WindowScroller.example.css b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/WindowScroller.example.css new file mode 100644 index 00000000000..70b69c40208 --- /dev/null +++ b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/WindowScroller.example.css @@ -0,0 +1,7 @@ +.pf-c-window-scroller .ReactVirtualized__VirtualGrid { + overflow: visible !important; +} + +.pf-c-window-scroller .ReactVirtualized__VirtualGrid__innerScrollContainer { + overflow: visible !important; +} \ No newline at end of file diff --git a/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/WindowScroller.md b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/WindowScroller.md new file mode 100644 index 00000000000..36c4d5003ef --- /dev/null +++ b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/WindowScroller.md @@ -0,0 +1,181 @@ +--- +title: 'Window Scroller' +section: 'Virtual Scroll' +--- + +import clsx from 'clsx'; +import PropTypes from 'prop-types'; +import * as React from 'react'; +import { Table, TableHeader, TableGridBreakpoint } from '@patternfly/react-table'; +import { CellMeasurerCache, CellMeasurer } from 'react-virtualized'; +import { AutoSizer, VirtualTableBody, WindowScroller } from '@patternfly/react-virtualized-extension'; +import UUID from 'uuid/v1'; +import virtualGridStyles from './VirtualGrid.example.css'; +import windowScrollerStyles from './WindowScroller.example.css'; + +## Window Scroller Example + +```js +import clsx from 'clsx'; +import PropTypes from 'prop-types'; +import * as React from 'react'; +import { Table, TableHeader, TableGridBreakpoint } from '@patternfly/react-table'; +import { CellMeasurerCache, CellMeasurer } from 'react-virtualized'; +import { AutoSizer, VirtualTable, WindowScroller } from '@patternfly/react-virtualized-extension'; +import virtualGridStyles from './VirtualGrid.example.css'; +import windowScrollerStyles from './WindowScroller.example.css'; + +class WindowScrollerExample extends React.Component { + constructor(){ + const rows = []; + for (let i = 0; i < 100000; i++) { + const cells = []; + const num = Math.floor(Math.random() * Math.floor(2)) + 1; + for (let j = 0; j < 5; j++) { + const cellValue = i.toString() + ' Arma virumque cano Troiae qui primus ab oris. '.repeat(num); + cells.push(cellValue); + } + rows.push({ + id: UUID(), + cells + }); + } + + this.scrollableElement = React.createRef(); + + this.state = { + scrollToIndex: -1, //can be used to programmatically set current index + scrollableElement: null, + columns: [ + { title: 'Repositories', props: { className: 'pf-m-6-col-on-sm pf-m-4-col-on-md pf-m-3-col-on-lg pf-m-2-col-on-xl'} }, + { title: 'Branches', props: { className: 'pf-m-6-col-on-sm pf-m-4-col-on-md pf-m-3-col-on-lg pf-m-2-col-on-xl'} }, + { title: 'Pull requests', props: { className: 'pf-m-4-col-on-md pf-m-4-col-on-lg pf-m-3-col-on-xl pf-m-hidden pf-m-visible-on-md'} }, + { title: 'Workspaces', props: { className: 'pf-m-2-col-on-lg pf-m-2-col-on-xl pf-m-hidden pf-m-visible-on-lg'} }, + { title: 'Last Commit', props: { className: 'pf-m-3-col-on-xl pf-m-hidden pf-m-visible-on-xl'} } + ], + rows + }; + + this._handleResize = this._handleResize.bind(this); + } + + componentDidMount(){ + // re-render after resize + window.addEventListener('resize', this._handleResize); + } + + componentDidMount(){ + setTimeout(() => { + const scollableElement = document.getElementById('content-scrollable-1'); + this.setState({ scollableElement }); + }); + + // re-render after resize + window.addEventListener('resize', this._handleResize); + } + + componentWillUnmount(){ + window.removeEventListener('resize', this._handleResize); + } + + _handleResize() { + this.forceUpdate(); + } + + render() { + const {scrollToIndex, columns, rows, scollableElement} = this.state; + + const measurementCache = new CellMeasurerCache({ + fixedWidth: true, + minHeight: 44, + keyMapper: rowIndex => rowIndex + }); + + const rowRenderer = ({index, isScrolling, isVisible, key, style, parent}) => { + const {rows, columns} = this.state; + const text = rows[index].cells[0]; + + const className = clsx({ + isVisible: isVisible + }); + + // do not render non visible elements (this excludes overscan) + if(!isVisible){ + return null; + } + return + + {text} + {text} + {text} + {text} + {text} + + ; + } + + return ( +
+ + +
+ + {({height, isScrolling, registerChild, onChildScroll, scrollTop}) => ( + + {({width}) => ( +
+ +
+ )} +
+ )} +
+
+ ); + } +} + +export default WindowScrollerExample; +``` diff --git a/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/accessibilityOverscanIndicesGetter.js b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/accessibilityOverscanIndicesGetter.js new file mode 100644 index 00000000000..24cb2384f7a --- /dev/null +++ b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/accessibilityOverscanIndicesGetter.js @@ -0,0 +1,38 @@ +// @flow + +import type { OverscanIndicesGetterParams, OverscanIndices } from './types'; + +export const SCROLL_DIRECTION_BACKWARD = -1; +export const SCROLL_DIRECTION_FORWARD = 1; + +export const SCROLL_DIRECTION_HORIZONTAL = 'horizontal'; +export const SCROLL_DIRECTION_VERTICAL = 'vertical'; + +/** + * Calculates the number of cells to overscan before and after a specified range. + * This function ensures that overscanning doesn't exceed the available cells. + */ + +export default function defaultOverscanIndicesGetter({ + cellCount, + overscanCellsCount, + scrollDirection, + startIndex, + stopIndex +}: OverscanIndicesGetterParams): OverscanIndices { + // Make sure we render at least 1 cell extra before and after (except near boundaries) + // This is necessary in order to support keyboard navigation (TAB/SHIFT+TAB) in some cases + // For more info see issues #625 + overscanCellsCount = Math.max(1, overscanCellsCount); + + if (scrollDirection === SCROLL_DIRECTION_FORWARD) { + return { + overscanStartIndex: Math.max(0, startIndex - 1), + overscanStopIndex: Math.min(cellCount - 1, stopIndex + overscanCellsCount) + }; + } + return { + overscanStartIndex: Math.max(0, startIndex - overscanCellsCount), + overscanStopIndex: Math.min(cellCount - 1, stopIndex + 1) + }; +} diff --git a/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/defaultCellRangeRenderer.js b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/defaultCellRangeRenderer.js new file mode 100644 index 00000000000..9422ee75e4c --- /dev/null +++ b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/defaultCellRangeRenderer.js @@ -0,0 +1,155 @@ +/** @flow */ + +import type { CellRangeRendererParams } from './types'; + +/** + * Default implementation of cellRangeRenderer used by Grid. + * This renderer supports cell-caching while the user is scrolling. + */ + +export default function defaultCellRangeRenderer({ + cellCache, + cellRenderer, + columnSizeAndPositionManager, + columnStartIndex, + columnStopIndex, + deferredMeasurementCache, + horizontalOffsetAdjustment, + isScrolling, + isScrollingOptOut, + parent, // Grid (or List or Table) + rowSizeAndPositionManager, + rowStartIndex, + rowStopIndex, + styleCache, + verticalOffsetAdjustment, + visibleColumnIndices, + visibleRowIndices +}: CellRangeRendererParams) { + const renderedCells = []; + + // Browsers have native size limits for elements (eg Chrome 33M pixels, IE 1.5M pixes). + // User cannot scroll beyond these size limitations. + // In order to work around this, ScalingCellSizeAndPositionManager compresses offsets. + // We should never cache styles for compressed offsets though as this can lead to bugs. + // See issue #576 for more. + const areOffsetsAdjusted = + columnSizeAndPositionManager.areOffsetsAdjusted() || rowSizeAndPositionManager.areOffsetsAdjusted(); + + const canCacheStyle = !isScrolling && !areOffsetsAdjusted; + + for (let rowIndex = rowStartIndex; rowIndex <= rowStopIndex; rowIndex++) { + const rowDatum = rowSizeAndPositionManager.getSizeAndPositionOfCell(rowIndex); + + for (let columnIndex = columnStartIndex; columnIndex <= columnStopIndex; columnIndex++) { + const columnDatum = columnSizeAndPositionManager.getSizeAndPositionOfCell(columnIndex); + const isVisible = + columnIndex >= visibleColumnIndices.start && + columnIndex <= visibleColumnIndices.stop && + rowIndex >= visibleRowIndices.start && + rowIndex <= visibleRowIndices.stop; + const key = `${rowIndex}-${columnIndex}`; + let style; + + // Cache style objects so shallow-compare doesn't re-render unnecessarily. + if (canCacheStyle && styleCache[key]) { + style = styleCache[key]; + } else { + // In deferred mode, cells will be initially rendered before we know their size. + // Don't interfere with CellMeasurer's measurements by setting an invalid size. + if (deferredMeasurementCache && !deferredMeasurementCache.has(rowIndex, columnIndex)) { + // Position not-yet-measured cells at top/left 0,0, + // And give them width/height of 'auto' so they can grow larger than the parent Grid if necessary. + // Positioning them further to the right/bottom influences their measured size. + style = { + height: 'auto', + left: 0, + position: 'absolute', + top: 0, + width: 'auto' + }; + } else { + style = { + height: rowDatum.size, + left: columnDatum.offset + horizontalOffsetAdjustment, + position: 'absolute', + top: rowDatum.offset + verticalOffsetAdjustment, + width: columnDatum.size + }; + + styleCache[key] = style; + } + } + + const cellRendererParams = { + columnIndex, + isScrolling, + isVisible, + key, + parent, + rowIndex, + style + }; + + let renderedCell; + + // Avoid re-creating cells while scrolling. + // This can lead to the same cell being created many times and can cause performance issues for "heavy" cells. + // If a scroll is in progress- cache and reuse cells. + // This cache will be thrown away once scrolling completes. + // However if we are scaling scroll positions and sizes, we should also avoid caching. + // This is because the offset changes slightly as scroll position changes and caching leads to stale values. + // For more info refer to issue #395 + // + // If isScrollingOptOut is specified, we always cache cells. + // For more info refer to issue #1028 + if ((isScrollingOptOut || isScrolling) && !horizontalOffsetAdjustment && !verticalOffsetAdjustment) { + if (!cellCache[key]) { + cellCache[key] = cellRenderer(cellRendererParams); + } + + renderedCell = cellCache[key]; + + // If the user is no longer scrolling, don't cache cells. + // This makes dynamic cell content difficult for users and would also lead to a heavier memory footprint. + } else { + renderedCell = cellRenderer(cellRendererParams); + } + + if (renderedCell == null || renderedCell === false) { + continue; + } + + if (process.env.NODE_ENV !== 'production') { + warnAboutMissingStyle(parent, renderedCell); + } + + renderedCells.push(renderedCell); + } + } + + return renderedCells; +} + +function warnAboutMissingStyle(parent, renderedCell) { + if (process.env.NODE_ENV !== 'production') { + if (renderedCell) { + // If the direct child is a CellMeasurer, then we should check its child + // See issue #611 + if (renderedCell.type && renderedCell.type.__internalCellMeasurerFlag) { + renderedCell = renderedCell.props.children; + } + + if ( + renderedCell && + renderedCell.props && + renderedCell.props.style === undefined && + parent.__warnedAboutMissingStyle !== true + ) { + parent.__warnedAboutMissingStyle = true; + + console.warn('Rendered cell should include style property for positioning.'); + } + } + } +} diff --git a/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/defaultOverscanIndicesGetter.js b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/defaultOverscanIndicesGetter.js new file mode 100644 index 00000000000..4e2ed49204f --- /dev/null +++ b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/defaultOverscanIndicesGetter.js @@ -0,0 +1,33 @@ +// @flow + +import type { OverscanIndicesGetterParams, OverscanIndices } from './types'; + +export const SCROLL_DIRECTION_BACKWARD = -1; +export const SCROLL_DIRECTION_FORWARD = 1; + +export const SCROLL_DIRECTION_HORIZONTAL = 'horizontal'; +export const SCROLL_DIRECTION_VERTICAL = 'vertical'; + +/** + * Calculates the number of cells to overscan before and after a specified range. + * This function ensures that overscanning doesn't exceed the available cells. + */ + +export default function defaultOverscanIndicesGetter({ + cellCount, + overscanCellsCount, + scrollDirection, + startIndex, + stopIndex +}: OverscanIndicesGetterParams): OverscanIndices { + if (scrollDirection === SCROLL_DIRECTION_FORWARD) { + return { + overscanStartIndex: Math.max(0, startIndex), + overscanStopIndex: Math.min(cellCount - 1, stopIndex + overscanCellsCount) + }; + } + return { + overscanStartIndex: Math.max(0, startIndex - overscanCellsCount), + overscanStopIndex: Math.min(cellCount - 1, stopIndex) + }; +} diff --git a/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/index.js b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/index.js new file mode 100644 index 00000000000..2497d4618e3 --- /dev/null +++ b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/index.js @@ -0,0 +1,3 @@ +export { AutoSizer, WindowScroller } from 'react-virtualized'; +export { default as VirtualGrid } from './VirtualGrid'; +export { default as VirtualTableBody } from './VirtualTableBody'; diff --git a/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/types.js b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/types.js new file mode 100644 index 00000000000..190d48e5997 --- /dev/null +++ b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/types.js @@ -0,0 +1,115 @@ +// @flow + +import * as React from 'react'; +import ScalingCellSizeAndPositionManager from './utils/ScalingCellSizeAndPositionManager'; + +export type CellPosition = {columnIndex: number, rowIndex: number}; + +export type CellRendererParams = { + columnIndex: number, + isScrolling: boolean, + isVisible: boolean, + key: string, + parent: Object, + rowIndex: number, + style: Object, +}; + +export type CellRenderer = (props: CellRendererParams) => React.Element<*>; + +export type CellCache = {[key: string]: React.Element<*>}; +export type StyleCache = {[key: string]: Object}; + +export type CellRangeRendererParams = { + cellCache: CellCache, + cellRenderer: CellRenderer, + columnSizeAndPositionManager: ScalingCellSizeAndPositionManager, + columnStartIndex: number, + columnStopIndex: number, + deferredMeasurementCache?: Object, + horizontalOffsetAdjustment: number, + isScrolling: boolean, + isScrollingOptOut: boolean, + parent: Object, + rowSizeAndPositionManager: ScalingCellSizeAndPositionManager, + rowStartIndex: number, + rowStopIndex: number, + scrollLeft: number, + scrollTop: number, + styleCache: StyleCache, + verticalOffsetAdjustment: number, + visibleColumnIndices: Object, + visibleRowIndices: Object, +}; + +export type CellRangeRenderer = ( + params: CellRangeRendererParams, +) => React.Element<*>[]; + +export type CellSizeGetter = (params: {index: number}) => number; + +export type CellSize = CellSizeGetter | number; + +export type NoContentRenderer = () => React.Element<*> | null; + +export type Scroll = { + clientHeight: number, + clientWidth: number, + scrollHeight: number, + scrollLeft: number, + scrollTop: number, + scrollWidth: number, +}; + +export type ScrollbarPresenceChange = { + horizontal: boolean, + vertical: boolean, + size: number, +}; + +export type RenderedSection = { + columnOverscanStartIndex: number, + columnOverscanStopIndex: number, + columnStartIndex: number, + columnStopIndex: number, + rowOverscanStartIndex: number, + rowOverscanStopIndex: number, + rowStartIndex: number, + rowStopIndex: number, +}; + +export type OverscanIndicesGetterParams = { + // One of SCROLL_DIRECTION_HORIZONTAL or SCROLL_DIRECTION_VERTICAL + direction: 'horizontal' | 'vertical', + + // One of SCROLL_DIRECTION_BACKWARD or SCROLL_DIRECTION_FORWARD + scrollDirection: -1 | 1, + + // Number of rows or columns in the current axis + cellCount: number, + + // Maximum number of cells to over-render in either direction + overscanCellsCount: number, + + // Begin of range of visible cells + startIndex: number, + + // End of range of visible cells + stopIndex: number, +}; + +export type OverscanIndices = { + overscanStartIndex: number, + overscanStopIndex: number, +}; + +export type OverscanIndicesGetter = ( + params: OverscanIndicesGetterParams, +) => OverscanIndices; + +export type Alignment = 'auto' | 'end' | 'start' | 'center'; + +export type VisibleCellRange = { + start?: number, + stop?: number, +}; diff --git a/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/CellSizeAndPositionManager.js b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/CellSizeAndPositionManager.js new file mode 100644 index 00000000000..69d9f87547e --- /dev/null +++ b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/CellSizeAndPositionManager.js @@ -0,0 +1,255 @@ +/** @flow */ + +import LinearLayoutVector from 'linear-layout-vector'; +import type { Alignment, CellSizeGetter, VisibleCellRange } from '../types'; + +type CellSizeAndPositionManagerParams = { + cellCount: number, + cellSizeGetter: CellSizeGetter, + estimatedCellSize: number +}; + +type ConfigureParams = { + cellCount: number, + estimatedCellSize: number, + cellSizeGetter: CellSizeGetter +}; + +type GetUpdatedOffsetForIndex = { + align: Alignment, + containerSize: number, + currentOffset: number, + targetIndex: number +}; + +type GetVisibleCellRangeParams = { + containerSize: number, + offset: number +}; + +type SizeAndPositionData = { + offset: number, + size: number +}; + +/** + * Just-in-time calculates and caches size and position information for a collection of cells. + */ + +export default class CellSizeAndPositionManager { + // Cache of size and position data for cells, mapped by cell index. + // Note that invalid values may exist in this map so only rely on cells up to this._lastMeasuredIndex + _layoutVector: LinearLayoutVector; + + // Measurements for cells up to this index can be trusted; cells afterward should be estimated. + _lastMeasuredIndex = -1; + + _cellCount: number; + _cellSizeGetter: CellSizeGetter; + _estimatedCellSize: number; + + constructor({ cellCount, cellSizeGetter, estimatedCellSize }: CellSizeAndPositionManagerParams) { + this._cellSizeGetter = cellSizeGetter; + this._cellCount = cellCount; + this._estimatedCellSize = estimatedCellSize; + this._layoutVector = new LinearLayoutVector(); + this._layoutVector.setLength(cellCount); + this._layoutVector.setDefaultSize(estimatedCellSize); + } + + areOffsetsAdjusted() { + return false; + } + + configure({ cellCount, estimatedCellSize, cellSizeGetter }: ConfigureParams) { + this._cellCount = cellCount; + this._estimatedCellSize = estimatedCellSize; + this._cellSizeGetter = cellSizeGetter; + this._layoutVector.setLength(cellCount); + this._layoutVector.setDefaultSize(estimatedCellSize); + } + + getCellCount(): number { + return this._cellCount; + } + + getEstimatedCellSize(): number { + return this._estimatedCellSize; + } + + getLastMeasuredIndex(): number { + return this._lastMeasuredIndex; + } + + getOffsetAdjustment() { + return 0; + } + + /** + * This method returns the size and position for the cell at the specified index. + * It just-in-time calculates (or used cached values) for cells leading up to the index. + */ + getSizeAndPositionOfCell(index: number): SizeAndPositionData { + if (index < 0 || index >= this._cellCount) { + throw Error(`Requested index ${index} is outside of range 0..${this._cellCount}`); + } + const vector = this._layoutVector; + if (index > this._lastMeasuredIndex) { + const token = { index: this._lastMeasuredIndex + 1 }; + + for (let i = token.index; i <= index; token.index = ++i) { + const size = this._cellSizeGetter(token); + // undefined or NaN probably means a logic error in the size getter. + // null means we're using CellMeasurer and haven't yet measured a given index. + if (size === undefined || size !== size) { + throw Error(`Invalid size returned for cell ${i} of value ${size}`); + } else if (size !== null) { + vector.setItemSize(i, size); + } + } + this._lastMeasuredIndex = Math.min(index, this._cellCount - 1); + } + + return { + offset: vector.start(index), + size: vector.getItemSize(index) + }; + } + + getSizeAndPositionOfLastMeasuredCell(): SizeAndPositionData { + const index = this._lastMeasuredIndex; + if (index <= 0) { + return { + offset: 0, + size: 0 + }; + } + const vector = this._layoutVector; + return { + offset: vector.start(index), + size: vector.getItemSize(index) + }; + } + + /** + * Total size of all cells being measured. + * This value will be completely estimated initially. + * As cells are measured, the estimate will be updated. + */ + getTotalSize(): number { + const lastIndex = this._cellCount - 1; + return lastIndex >= 0 ? this._layoutVector.end(lastIndex) : 0; + } + + /** + * Determines a new offset that ensures a certain cell is visible, given the current offset. + * If the cell is already visible then the current offset will be returned. + * If the current offset is too great or small, it will be adjusted just enough to ensure the specified index is visible. + * + * @param align Desired alignment within container; one of "auto" (default), "start", or "end" + * @param containerSize Size (width or height) of the container viewport + * @param currentOffset Container's current (x or y) offset + * @param totalSize Total size (width or height) of all cells + * @return Offset to use to ensure the specified cell is visible + */ + getUpdatedOffsetForIndex({ + align = 'auto', + containerSize, + currentOffset, + targetIndex + }: GetUpdatedOffsetForIndex): number { + if (containerSize <= 0) { + return 0; + } + + const datum = this.getSizeAndPositionOfCell(targetIndex); + const maxOffset = datum.offset; + const minOffset = maxOffset - containerSize + datum.size; + + let idealOffset; + + switch (align) { + case 'start': + idealOffset = maxOffset; + break; + case 'end': + idealOffset = minOffset; + break; + case 'center': + idealOffset = maxOffset - (containerSize - datum.size) / 2; + break; + default: + idealOffset = Math.max(minOffset, Math.min(maxOffset, currentOffset)); + break; + } + + const totalSize = this.getTotalSize(); + + return Math.max(0, Math.min(totalSize - containerSize, idealOffset)); + } + + getVisibleCellRange(params: GetVisibleCellRangeParams): VisibleCellRange { + if (this.getTotalSize() === 0) { + return {}; + } + + const { containerSize, offset } = params; + const maxOffset = offset + containerSize - 1; + return { + start: this._findNearestCell(offset), + stop: this._findNearestCell(maxOffset) + }; + } + + /** + * Clear all cached values for cells after the specified index. + * This method should be called for any cell that has changed its size. + * It will not immediately perform any calculations; they'll be performed the next time getSizeAndPositionOfCell() is called. + */ + resetCell(index: number): void { + this._lastMeasuredIndex = Math.min(this._lastMeasuredIndex, index - 1); + } + + /** + * Searches for the cell (index) nearest the specified offset. + * + * If no exact match is found the next lowest cell index will be returned. + * This allows partially visible cells (with offsets just before/above the fold) to be visible. + */ + _findNearestCell(offset: number): number { + if (isNaN(offset)) { + throw Error(`Invalid offset ${offset} specified`); + } + + const vector = this._layoutVector; + const lastIndex = this._cellCount - 1; + // Our search algorithms find the nearest match at or below the specified offset. + // So make sure the offset is at least 0 or no match will be found. + let targetOffset = Math.max(0, Math.min(offset, vector.start(lastIndex))); + // First interrogate the constant-time lookup table + let nearestCellIndex = vector.indexOf(targetOffset); + + // If we haven't yet measured this high, compute sizes for each cell up to the desired offset. + while (nearestCellIndex > this._lastMeasuredIndex) { + // Measure all the cells up to the one we want to find presently. + // Do this before the last-index check to ensure the sparse array + // is fully populated. + this.getSizeAndPositionOfCell(nearestCellIndex); + // No need to search and compare again if we're at the end. + if (nearestCellIndex === lastIndex) { + return nearestCellIndex; + } + nearestCellIndex = vector.indexOf(targetOffset); + // Guard in case `getSizeAndPositionOfCell` didn't fully measure to + // the nearestCellIndex. This might happen scrolling quickly down + // and back up on large lists -- possible race with React or DOM? + if (nearestCellIndex === -1) { + nearestCellIndex = this._lastMeasuredIndex; + this._lastMeasuredIndex = nearestCellIndex - 1; + targetOffset = Math.max(0, Math.min(offset, vector.start(lastIndex))); + } + } + + return nearestCellIndex; + } +} diff --git a/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/ScalingCellSizeAndPositionManager.js b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/ScalingCellSizeAndPositionManager.js new file mode 100644 index 00000000000..d1b28b80007 --- /dev/null +++ b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/ScalingCellSizeAndPositionManager.js @@ -0,0 +1,190 @@ +/** @flow */ + +import type { Alignment, CellSizeGetter, VisibleCellRange } from '../types'; + +import CellSizeAndPositionManager from './CellSizeAndPositionManager'; +import { getMaxElementSize } from './maxElementSize.js'; + +type ContainerSizeAndOffset = { + containerSize: number, + offset: number +}; + +/** + * Browsers have scroll offset limitations (eg Chrome stops scrolling at ~33.5M pixels where as Edge tops out at ~1.5M pixels). + * After a certain position, the browser won't allow the user to scroll further (even via JavaScript scroll offset adjustments). + * This util picks a lower ceiling for max size and artificially adjusts positions within to make it transparent for users. + */ + +type Params = { + maxScrollSize?: number, + cellCount: number, + cellSizeGetter: CellSizeGetter, + estimatedCellSize: number +}; + +/** + * Extends CellSizeAndPositionManager and adds scaling behavior for lists that are too large to fit within a browser's native limits. + */ +export default class ScalingCellSizeAndPositionManager { + _cellSizeAndPositionManager: CellSizeAndPositionManager; + _maxScrollSize: number; + + constructor({ maxScrollSize = getMaxElementSize(), ...params }: Params) { + // Favor composition over inheritance to simplify IE10 support + this._cellSizeAndPositionManager = new CellSizeAndPositionManager(params); + this._maxScrollSize = maxScrollSize; + } + + areOffsetsAdjusted(): boolean { + return this._cellSizeAndPositionManager.getTotalSize() > this._maxScrollSize; + } + + configure(params: { cellCount: number, estimatedCellSize: number, cellSizeGetter: CellSizeGetter }) { + this._cellSizeAndPositionManager.configure(params); + } + + getCellCount(): number { + return this._cellSizeAndPositionManager.getCellCount(); + } + + getEstimatedCellSize(): number { + return this._cellSizeAndPositionManager.getEstimatedCellSize(); + } + + getLastMeasuredIndex(): number { + return this._cellSizeAndPositionManager.getLastMeasuredIndex(); + } + + /** + * Number of pixels a cell at the given position (offset) should be shifted in order to fit within the scaled container. + * The offset passed to this function is scaled (safe) as well. + */ + getOffsetAdjustment({ + containerSize, + offset // safe + }: ContainerSizeAndOffset): number { + const totalSize = this._cellSizeAndPositionManager.getTotalSize(); + const safeTotalSize = this.getTotalSize(); + const offsetPercentage = this._getOffsetPercentage({ + containerSize, + offset, + totalSize: safeTotalSize + }); + + return Math.round(offsetPercentage * (safeTotalSize - totalSize)); + } + + getSizeAndPositionOfCell(index: number) { + return this._cellSizeAndPositionManager.getSizeAndPositionOfCell(index); + } + + getSizeAndPositionOfLastMeasuredCell() { + return this._cellSizeAndPositionManager.getSizeAndPositionOfLastMeasuredCell(); + } + + /** See CellSizeAndPositionManager#getTotalSize */ + getTotalSize(): number { + return Math.min(this._maxScrollSize, this._cellSizeAndPositionManager.getTotalSize()); + } + + /** See CellSizeAndPositionManager#getUpdatedOffsetForIndex */ + getUpdatedOffsetForIndex({ + align = 'auto', + containerSize, + currentOffset, // safe + targetIndex + }: { + align: Alignment, + containerSize: number, + currentOffset: number, + targetIndex: number + }) { + currentOffset = this._safeOffsetToOffset({ + containerSize, + offset: currentOffset + }); + + const offset = this._cellSizeAndPositionManager.getUpdatedOffsetForIndex({ + align, + containerSize, + currentOffset, + targetIndex + }); + + return this._offsetToSafeOffset({ + containerSize, + offset + }); + } + + /** See CellSizeAndPositionManager#getVisibleCellRange */ + getVisibleCellRange({ + containerSize, + offset // safe + }: ContainerSizeAndOffset): VisibleCellRange { + offset = this._safeOffsetToOffset({ + containerSize, + offset + }); + + return this._cellSizeAndPositionManager.getVisibleCellRange({ + containerSize, + offset + }); + } + + resetCell(index: number): void { + this._cellSizeAndPositionManager.resetCell(index); + } + + _getOffsetPercentage({ + containerSize, + offset, // safe + totalSize + }: { + containerSize: number, + offset: number, + totalSize: number + }) { + return totalSize <= containerSize ? 0 : offset / (totalSize - containerSize); + } + + _offsetToSafeOffset({ + containerSize, + offset // unsafe + }: ContainerSizeAndOffset): number { + const totalSize = this._cellSizeAndPositionManager.getTotalSize(); + const safeTotalSize = this.getTotalSize(); + + if (totalSize === safeTotalSize) { + return offset; + } + const offsetPercentage = this._getOffsetPercentage({ + containerSize, + offset, + totalSize + }); + + return Math.round(offsetPercentage * (safeTotalSize - containerSize)); + } + + _safeOffsetToOffset({ + containerSize, + offset // safe + }: ContainerSizeAndOffset): number { + const totalSize = this._cellSizeAndPositionManager.getTotalSize(); + const safeTotalSize = this.getTotalSize(); + + if (totalSize === safeTotalSize) { + return offset; + } + const offsetPercentage = this._getOffsetPercentage({ + containerSize, + offset, + totalSize: safeTotalSize + }); + + return Math.round(offsetPercentage * (totalSize - containerSize)); + } +} diff --git a/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/animationFrame.js b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/animationFrame.js new file mode 100644 index 00000000000..3282efb3120 --- /dev/null +++ b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/animationFrame.js @@ -0,0 +1,41 @@ +/** + * animationFrame.js + * https://github.com/bvaughn/react-virtualized/blob/9.21.0/source/utils/animationFrame.js + * Brian Vaughn + * + * Forked from version 9.21.0 + * */ + +// Properly handle server-side rendering. +let win; +if (typeof window !== 'undefined') { + win = window; + // eslint-disable-next-line no-restricted-globals +} else if (typeof self !== 'undefined') { + // eslint-disable-next-line no-restricted-globals + win = self; +} else { + win = {}; +} + +// requestAnimationFrame() shim by Paul Irish +// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ +export const raf = + win.requestAnimationFrame || + win.webkitRequestAnimationFrame || + win.mozRequestAnimationFrame || + win.oRequestAnimationFrame || + win.msRequestAnimationFrame || + function raf(callback) { + return win.setTimeout(callback, 1000 / 60); + }; + +export const caf = + win.cancelAnimationFrame || + win.webkitCancelAnimationFrame || + win.mozCancelAnimationFrame || + win.oCancelAnimationFrame || + win.msCancelAnimationFrame || + function cT(id) { + win.clearTimeout(id); + }; diff --git a/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/calculateSizeAndPositionDataAndUpdateScrollOffset.js b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/calculateSizeAndPositionDataAndUpdateScrollOffset.js new file mode 100644 index 00000000000..f5c5eb2909f --- /dev/null +++ b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/calculateSizeAndPositionDataAndUpdateScrollOffset.js @@ -0,0 +1,61 @@ +// @flow + +/** + * Helper method that determines when to recalculate row or column metadata. + */ + +type Params = { + // Number of rows or columns in the current axis + cellCount: number, + + // Width or height of cells for the current axis + cellSize: ?number, + + // Method to invoke if cell metadata should be recalculated + computeMetadataCallback: (props: T) => void, + + // Parameters to pass to :computeMetadataCallback + computeMetadataCallbackProps: T, + + // Newly updated number of rows or columns in the current axis + nextCellsCount: number, + + // Newly updated width or height of cells for the current axis + nextCellSize: ?number, + + // Newly updated scroll-to-index + nextScrollToIndex: number, + + // Scroll-to-index + scrollToIndex: number, + + // Callback to invoke if the scroll position should be recalculated + updateScrollOffsetForScrollToIndex: () => void +}; + +export default function calculateSizeAndPositionDataAndUpdateScrollOffset({ + cellCount, + cellSize, + computeMetadataCallback, + computeMetadataCallbackProps, + nextCellsCount, + nextCellSize, + nextScrollToIndex, + scrollToIndex, + updateScrollOffsetForScrollToIndex +}: Params<*>) { + // Don't compare cell sizes if they are functions because inline functions would cause infinite loops. + // In that event users should use the manual recompute methods to inform of changes. + if ( + cellCount !== nextCellsCount || + ((typeof cellSize === 'number' || typeof nextCellSize === 'number') && cellSize !== nextCellSize) + ) { + computeMetadataCallback(computeMetadataCallbackProps); + + // Updated cell metadata may have hidden the previous scrolled-to item. + // In this case we should also update the scrollTop to ensure it stays visible. + if (scrollToIndex >= 0 && scrollToIndex === nextScrollToIndex) { + updateScrollOffsetForScrollToIndex(); + } + } +} diff --git a/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/createCallbackMemoizer.js b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/createCallbackMemoizer.js new file mode 100644 index 00000000000..38178cf0e0f --- /dev/null +++ b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/createCallbackMemoizer.js @@ -0,0 +1,32 @@ +/** + * Helper utility that updates the specified callback whenever any of the specified indices have changed. + */ +export default function createCallbackMemoizer(requireAllKeys = true) { + let cachedIndices = {}; + + return ({callback, indices}) => { + const keys = Object.keys(indices); + const allInitialized = + !requireAllKeys || + keys.every(key => { + const value = indices[key]; + return Array.isArray(value) ? value.length > 0 : value >= 0; + }); + const indexChanged = + keys.length !== Object.keys(cachedIndices).length || + keys.some(key => { + const cachedValue = cachedIndices[key]; + const value = indices[key]; + + return Array.isArray(value) + ? cachedValue.join(',') !== value.join(',') + : cachedValue !== value; + }); + + cachedIndices = indices; + + if (allInitialized && indexChanged) { + callback(indices); + } + }; +} \ No newline at end of file diff --git a/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/maxElementSize.js b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/maxElementSize.js new file mode 100644 index 00000000000..506c0c5b62a --- /dev/null +++ b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/maxElementSize.js @@ -0,0 +1,17 @@ +// @flow + +const DEFAULT_MAX_ELEMENT_SIZE = 1500000; +const CHROME_MAX_ELEMENT_SIZE = 1.67771e7; + +const isBrowser = () => typeof window !== 'undefined'; + +const isChrome = () => !!window.chrome && !!window.chrome.webstore; + +export const getMaxElementSize = (): number => { + if (isBrowser()) { + if (isChrome()) { + return CHROME_MAX_ELEMENT_SIZE; + } + } + return DEFAULT_MAX_ELEMENT_SIZE; +}; diff --git a/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/requestAnimationTimeout.js b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/requestAnimationTimeout.js new file mode 100644 index 00000000000..79a44fecd44 --- /dev/null +++ b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/requestAnimationTimeout.js @@ -0,0 +1,39 @@ +/** + * requestAnimationTimeout.js + * https://github.com/bvaughn/react-virtualized/blob/9.21.0/source/utils/requestAnimationTimeout.js + * Brian Vaughn + * + * Forked from version 9.21.0 + * */ + +import { caf, raf } from './animationFrame'; + +export const cancelAnimationTimeout = frame => caf(frame.id); + +/** + * Recursively calls requestAnimationFrame until a specified delay has been met or exceeded. + * When the delay time has been reached the function you're timing out will be called. + * + * Credit: Joe Lambert (https://gist.github.com/joelambert/1002116#file-requesttimeout-js) + */ +export const requestAnimationTimeout = (callback, delay) => { + let start; + // wait for end of processing current event handler, because event handler may be long + Promise.resolve().then(() => { + start = Date.now(); + }); + + const timeout = () => { + if (Date.now() - start >= delay) { + callback.call(); + } else { + frame.id = raf(timeout); + } + }; + + const frame = { + id: raf(timeout) + }; + + return frame; +}; diff --git a/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/updateScrollIndexHelper.js b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/updateScrollIndexHelper.js new file mode 100644 index 00000000000..c0cb6347b9f --- /dev/null +++ b/packages/patternfly-4/react-virtualized-extension/src/components/Virtualized/utils/updateScrollIndexHelper.js @@ -0,0 +1,92 @@ +// @flow + +import type { Alignment, CellSize } from '../types'; + +import ScalingCellSizeAndPositionManager from './ScalingCellSizeAndPositionManager.js'; + +/** + * Helper function that determines when to update scroll offsets to ensure that a scroll-to-index remains visible. + * This function also ensures that the scroll ofset isn't past the last column/row of cells. + */ + +type Params = { + // Width or height of cells for the current axis + cellSize?: CellSize, + + // Manages size and position metadata of cells + cellSizeAndPositionManager: ScalingCellSizeAndPositionManager, + + // Previous number of rows or columns + previousCellsCount: number, + + // Previous width or height of cells + previousCellSize: CellSize, + + previousScrollToAlignment: Alignment, + + // Previous scroll-to-index + previousScrollToIndex: number, + + // Previous width or height of the virtualized container + previousSize: number, + + // Current scrollLeft or scrollTop + scrollOffset: number, + + scrollToAlignment: Alignment, + + // Scroll-to-index + scrollToIndex: number, + + // Width or height of the virtualized container + size: number, + + sizeJustIncreasedFromZero: boolean, + + // Callback to invoke with an scroll-to-index value + updateScrollIndexCallback: (index: number) => void +}; + +export default function updateScrollIndexHelper({ + cellSize, + cellSizeAndPositionManager, + previousCellsCount, + previousCellSize, + previousScrollToAlignment, + previousScrollToIndex, + previousSize, + scrollOffset, + scrollToAlignment, + scrollToIndex, + size, + sizeJustIncreasedFromZero, + updateScrollIndexCallback +}: Params) { + const cellCount = cellSizeAndPositionManager.getCellCount(); + const hasScrollToIndex = scrollToIndex >= 0 && scrollToIndex < cellCount; + const sizeHasChanged = + size !== previousSize || + sizeJustIncreasedFromZero || + !previousCellSize || + (typeof cellSize === 'number' && cellSize !== previousCellSize); + + // If we have a new scroll target OR if height/row-height has changed, + // We should ensure that the scroll target is visible. + if ( + hasScrollToIndex && + (sizeHasChanged || scrollToAlignment !== previousScrollToAlignment || scrollToIndex !== previousScrollToIndex) + ) { + updateScrollIndexCallback(scrollToIndex); + + // If we don't have a selected item but list size or number of children have decreased, + // Make sure we aren't scrolled too far past the current content. + } else if (!hasScrollToIndex && cellCount > 0 && (size < previousSize || cellCount < previousCellsCount)) { + // We need to ensure that the current scroll offset is still within the collection's range. + // To do this, we don't need to measure everything; CellMeasurer would perform poorly. + // Just check to make sure we're still okay. + // Only adjust the scroll position if we've scrolled below the last set of rows. + if (scrollOffset > cellSizeAndPositionManager.getTotalSize() - size) { + updateScrollIndexCallback(cellCount - 1); + } + } +} diff --git a/packages/patternfly-4/react-virtualized-extension/src/components/index.js b/packages/patternfly-4/react-virtualized-extension/src/components/index.js new file mode 100644 index 00000000000..1dfee408f4a --- /dev/null +++ b/packages/patternfly-4/react-virtualized-extension/src/components/index.js @@ -0,0 +1 @@ +export * from './Virtualized'; diff --git a/packages/patternfly-4/react-virtualized-extension/src/index.js b/packages/patternfly-4/react-virtualized-extension/src/index.js new file mode 100644 index 00000000000..07635cbbc8e --- /dev/null +++ b/packages/patternfly-4/react-virtualized-extension/src/index.js @@ -0,0 +1 @@ +export * from './components'; diff --git a/yarn.lock b/yarn.lock index 9d71619dece..0b0c1375c7c 100644 --- a/yarn.lock +++ b/yarn.lock @@ -836,6 +836,14 @@ js-levenshtein "^1.1.3" semver "^5.5.0" +"@babel/preset-flow@^7.0.0-rc.1": + version "7.0.0" + resolved "https://registry.yarnpkg.com/@babel/preset-flow/-/preset-flow-7.0.0.tgz#afd764835d9535ec63d8c7d4caf1c06457263da2" + integrity sha512-bJOHrYOPqJZCkPVbG1Lot2r5OSsB+iUOaxiHdlOeB1yPWS6evswVHwvkDLZ54WTaTRIk89ds0iHmGZSnxlPejQ== + dependencies: + "@babel/helper-plugin-utils" "^7.0.0" + "@babel/plugin-transform-flow-strip-types" "^7.0.0" + "@babel/preset-react@7.0.0", "@babel/preset-react@^7.0.0": version "7.0.0" resolved "https://registry.yarnpkg.com/@babel/preset-react/-/preset-react-7.0.0.tgz#e86b4b3d99433c7b3e9e91747e2653958bc6b3c0" @@ -5913,6 +5921,7 @@ clone@^1.0.2: clsx@^1.0.1: version "1.0.4" resolved "https://registry.yarnpkg.com/clsx/-/clsx-1.0.4.tgz#0c0171f6d5cb2fe83848463c15fcc26b4df8c2ec" + integrity sha512-1mQ557MIZTrL/140j+JVdRM6e31/OA4vTYxXgqIIZlndyfjHpyawKZia1Im05Vp9BWmImkcNrNtFYQMyFcgJDg== cmd-shim@^2.0.2: version "2.0.2" @@ -9418,6 +9427,14 @@ gatsby-mdx@0.6.3: unist-util-remove "^1.0.1" unist-util-visit "^1.4.0" +gatsby-plugin-flow@^1.0.5: + version "1.0.5" + resolved "https://registry.yarnpkg.com/gatsby-plugin-flow/-/gatsby-plugin-flow-1.0.5.tgz#1078160648cce0d91610fe37721fd78cae904705" + integrity sha512-LAyvG7+UJpiNyvDFXXVz2/HHHO3fe44d9HcUi0uh1s8rwkD9FfjlGN98rL26fOFtVl2GDtl9EfhCkmuM02PlyA== + dependencies: + "@babel/preset-flow" "^7.0.0-rc.1" + "@babel/runtime" "^7.0.0" + gatsby-plugin-page-creator@^2.0.12: version "2.0.13" resolved "https://registry.yarnpkg.com/gatsby-plugin-page-creator/-/gatsby-plugin-page-creator-2.0.13.tgz#ba5d1af97b6fce9e41ae3e617699eed9c3682bde" @@ -12558,6 +12575,7 @@ liftoff@^2.5.0: linear-layout-vector@0.0.1: version "0.0.1" resolved "https://registry.yarnpkg.com/linear-layout-vector/-/linear-layout-vector-0.0.1.tgz#398114d7303b6ecc7fd6b273af7b8401d8ba9c70" + integrity sha1-OYEU1zA7bsx/1rJzr3uEAdi6nHA= listr-silent-renderer@^1.1.1: version "1.1.1" @@ -16992,7 +17010,7 @@ react-treebeard@^2.1.0: shallowequal "^0.2.2" velocity-react "^1.3.1" -react-virtualized@9.x: +react-virtualized@9.21.1, react-virtualized@9.x: version "9.21.1" resolved "https://registry.yarnpkg.com/react-virtualized/-/react-virtualized-9.21.1.tgz#4dbbf8f0a1420e2de3abf28fbb77120815277b3a" dependencies: