UNPKG

@carbon/react

Version:

React components for the Carbon Design System

730 lines (721 loc) 25.1 kB
/** * Copyright IBM Corp. 2016, 2023 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import { defineProperty as _defineProperty } from '../../_virtual/_rollupPluginBabelHelpers.js'; import PropTypes from 'prop-types'; import { Component } from 'react'; import isEqual from 'react-fast-compare'; import getDerivedStateFromProps from './state/getDerivedStateFromProps.js'; import { getNextSortState } from './state/sorting.js'; import { getCellId } from './tools/cells.js'; import denormalize from './tools/denormalize.js'; import { composeEventHandlers } from '../../tools/events.js'; import { defaultFilterRows } from './tools/filter.js'; import { setupGetInstanceId } from '../../tools/setupGetInstanceId.js'; import { Table } from './Table.js'; import TableActionList from './TableActionList.js'; import TableBatchAction from './TableBatchAction.js'; import TableBatchActions from './TableBatchActions.js'; import TableBody from './TableBody.js'; import TableCell from './TableCell.js'; import TableContainer from './TableContainer.js'; import TableDecoratorRow from './TableDecoratorRow.js'; import TableExpandHeader from './TableExpandHeader.js'; import TableExpandRow from './TableExpandRow.js'; import TableExpandedRow from './TableExpandedRow.js'; import TableHead from './TableHead.js'; import TableHeader from './TableHeader.js'; import TableRow from './TableRow.js'; import TableSelectAll from './TableSelectAll.js'; import TableSelectRow from './TableSelectRow.js'; import TableSlugRow from './TableSlugRow.js'; import TableToolbar from './TableToolbar.js'; import TableToolbarAction from './TableToolbarAction.js'; import TableToolbarContent from './TableToolbarContent.js'; import TableToolbarSearch from './TableToolbarSearch.js'; import TableToolbarMenu from './TableToolbarMenu.js'; const getInstanceId = setupGetInstanceId(); const translationKeys = { expandRow: 'carbon.table.row.expand', collapseRow: 'carbon.table.row.collapse', expandAll: 'carbon.table.all.expand', collapseAll: 'carbon.table.all.collapse', selectAll: 'carbon.table.all.select', unselectAll: 'carbon.table.all.unselect', selectRow: 'carbon.table.row.select', unselectRow: 'carbon.table.row.unselect' }; /** * Message ids that will be passed to translateWithId(). */ const defaultTranslations = { [translationKeys.expandAll]: 'Expand all rows', [translationKeys.collapseAll]: 'Collapse all rows', [translationKeys.expandRow]: 'Expand current row', [translationKeys.collapseRow]: 'Collapse current row', [translationKeys.selectAll]: 'Select all rows', [translationKeys.unselectAll]: 'Unselect all rows', [translationKeys.selectRow]: 'Select row', [translationKeys.unselectRow]: 'Unselect row' }; const translateWithId = id => defaultTranslations[id]; /** * Data Tables are used to represent a collection of resources, displaying a * subset of their fields in columns, or headers. We prioritize direct updates * to the state of what we're rendering, so internally we end up normalizing the * given data and then denormalizing it when rendering. * * As a result, each part of the DataTable is accessible through look-up by id, * and updating the state of the single entity will cascade updates to the * consumer. */ class DataTable extends Component { constructor(_props) { super(_props); _defineProperty(this, "instanceId", void 0); // TODO: Replace with a `type` when this component is converted to a // functional component. _defineProperty(this, "rp", void 0); /** * Get the props associated with the given header. Mostly used for adding in * sorting behavior. */ _defineProperty(this, "getHeaderProps", ({ header, onClick, isSortable = this.props.isSortable, ...rest }) => { const { sortDirection, sortHeaderKey } = this.state; return { ...rest, key: header.key, sortDirection, isSortable, isSortHeader: sortHeaderKey === header.key, slug: header.slug, decorator: header.decorator, onClick: event => { const nextSortState = getNextSortState(this.props, this.state, { key: header.key }); this.setState(nextSortState, () => { onClick && this.handleOnHeaderClick(onClick, { sortHeaderKey: header.key, sortDirection: nextSortState.sortDirection })(event); }); } }; }); /** * Get the props associated with the given expand header. */ _defineProperty(this, "getExpandHeaderProps", ({ onClick, onExpand, ...rest } = {}) => { const { translateWithId: t = translateWithId } = this.props; const { isExpandedAll, rowIds, rowsById } = this.state; const isExpanded = isExpandedAll || rowIds.every(id => rowsById[id].isExpanded); const translationKey = isExpanded ? translationKeys.collapseAll : translationKeys.expandAll; return { ...rest, 'aria-label': t(translationKey), // Provide a string of all the expanded row id's, separated by a space. 'aria-controls': rowIds.map(id => `expanded-row-${id}`).join(' '), isExpanded, // Compose the event handlers so we don't overwrite a consumer's `onClick` // handler onExpand: composeEventHandlers([this.handleOnExpandAll, onExpand, onClick && this.handleOnExpandHeaderClick(onClick, { isExpanded })]) }; }); /** * Decorate consumer's `onClick` event handler with sort parameters */ _defineProperty(this, "handleOnHeaderClick", (onClick, sortParams) => { return event => onClick(event, sortParams); }); /** * Decorate consumer's `onClick` event handler with expand parameters */ _defineProperty(this, "handleOnExpandHeaderClick", (onClick, expandParams) => { return event => onClick(event, expandParams); }); /** * Get the props associated with the given row. Mostly used for expansion. */ _defineProperty(this, "getRowProps", ({ row, onClick, ...rest }) => { const { translateWithId: t = translateWithId } = this.props; const translationKey = row.isExpanded ? translationKeys.collapseRow : translationKeys.expandRow; return { ...rest, key: row.id, onClick, // Compose the event handlers so we don't overwrite a consumer's `onClick` // handler onExpand: composeEventHandlers([this.handleOnExpandRow(row.id), onClick]), isExpanded: row.isExpanded, 'aria-label': t(translationKey), 'aria-controls': `expanded-row-${row.id}`, isSelected: row.isSelected, disabled: row.disabled }; }); /** * Get the props associated with an expanded row */ _defineProperty(this, "getExpandedRowProps", ({ row, ...rest }) => { return { ...rest, id: `expanded-row-${row.id}` }; }); /** * Gets the props associated with selection for a header or a row, where * applicable. Most often used to indicate selection status of the table or * for a specific row. */ _defineProperty(this, "getSelectionProps", ({ onClick, row, ...rest } = {}) => { const { translateWithId: t = translateWithId } = this.props; // If we're given a row, return the selection state values for that row if (row) { const translationKey = row.isSelected ? translationKeys.unselectRow : translationKeys.selectRow; return { ...rest, checked: row.isSelected, onSelect: composeEventHandlers([this.handleOnSelectRow(row.id), onClick]), id: `${this.getTablePrefix()}__select-row-${row.id}`, name: `select-row-${this.instanceId}`, 'aria-label': t(translationKey), disabled: row.disabled, radio: this.props.radio }; } // Otherwise, we're working on `TableSelectAll` which handles toggling the // selection state of all rows. const rowCount = this.state.rowIds.length; const selectedRowCount = this.getSelectedRows().length; const checked = rowCount > 0 && selectedRowCount === rowCount; const indeterminate = rowCount > 0 && selectedRowCount > 0 && selectedRowCount !== rowCount; const translationKey = checked || indeterminate ? translationKeys.unselectAll : translationKeys.selectAll; return { ...rest, 'aria-label': t(translationKey), checked, id: `${this.getTablePrefix()}__select-all`, indeterminate, name: `select-all-${this.instanceId}`, onSelect: composeEventHandlers([this.handleSelectAll, onClick]) }; }); _defineProperty(this, "getToolbarProps", props => { const { size } = this.props; const isSmall = size === 'xs' || size === 'sm'; return { ...props, size: isSmall ? 'sm' : undefined }; }); _defineProperty(this, "getBatchActionProps", props => { const { shouldShowBatchActions } = this.state; const totalSelected = this.getSelectedRows().length; return { onSelectAll: undefined, totalCount: this.state.rowIds.length || 0, ...props, shouldShowBatchActions: shouldShowBatchActions && totalSelected > 0, totalSelected, onCancel: this.handleOnCancel }; }); _defineProperty(this, "getTableProps", () => { const { useZebraStyles, size = 'lg', isSortable, useStaticWidth, stickyHeader, overflowMenuOnHover = false, experimentalAutoAlign } = this.props; return { useZebraStyles, size, isSortable, useStaticWidth, stickyHeader, overflowMenuOnHover, experimentalAutoAlign }; }); _defineProperty(this, "getTableContainerProps", () => { const { stickyHeader, useStaticWidth } = this.props; return { stickyHeader, useStaticWidth }; }); // TODO: `getHeaderProps` and `getRowProps` return `key` props. Would it be // beneficial for this function to also return a `key` prop? /** * Get the props associated with the given table cell. */ _defineProperty(this, "getCellProps", ({ cell: { hasAILabelHeader, hasDecoratorHeader }, ...rest }) => { return { ...rest, hasAILabelHeader, hasDecoratorHeader }; }); /** * Helper utility to get all the currently selected rows * * @returns the array of rowIds that are currently selected */ _defineProperty(this, "getSelectedRows", () => this.state.rowIds.filter(id => { const row = this.state.rowsById[id]; return row.isSelected && !row.disabled; })); /** * Helper utility to get all of the available rows after applying the filter * * @returns the array of rowIds that are currently included through the filter */ _defineProperty(this, "getFilteredRowIds", () => { const { filterRows = defaultFilterRows } = this.props; const filteredRowIds = typeof this.state.filterInputValue === 'string' ? filterRows({ rowIds: this.state.rowIds, headers: this.props.headers, cellsById: this.state.cellsById, inputValue: this.state.filterInputValue, getCellId }) : this.state.rowIds; if (filteredRowIds.length == 0) { return []; } return filteredRowIds; }); /** * Helper for getting the table prefix for elements that require an * `id` attribute that is unique. */ _defineProperty(this, "getTablePrefix", () => `data-table-${this.instanceId}`); /** * Helper for toggling all selected items in a state. Does not call * setState, so use it when setting state. * * @returns object to put into this.setState (use spread operator) */ _defineProperty(this, "setAllSelectedState", (initialState, isSelected, filteredRowIds) => { const { rowIds } = initialState; const isFiltered = rowIds.length != filteredRowIds.length; return { rowsById: rowIds.reduce((acc, id) => { const row = { ...initialState.rowsById[id] }; if (!row.disabled && (!isFiltered || filteredRowIds.includes(id))) { row.isSelected = isSelected; } acc[id] = row; // Local mutation for performance with large tables return acc; }, {}) }; }); /** * Handler for the `onCancel` event to hide the batch action bar and * deselect all selected rows */ _defineProperty(this, "handleOnCancel", () => { this.setState(state => { return { shouldShowBatchActions: false, ...this.setAllSelectedState(state, false, this.getFilteredRowIds()) }; }); }); /** * Handler for toggling the selection state of all rows in the database */ _defineProperty(this, "handleSelectAll", () => { this.setState(state => { const filteredRowIds = this.getFilteredRowIds(); const { rowsById } = state; const isSelected = !(Object.values(rowsById).filter(row => row.isSelected && !row.disabled).length > 0); return { shouldShowBatchActions: isSelected, ...this.setAllSelectedState(state, isSelected, filteredRowIds) }; }); }); /** * Handler for toggling the selection state of a given row. */ _defineProperty(this, "handleOnSelectRow", rowId => () => { this.setState(state => { const row = state.rowsById[rowId]; if (this.props.radio) { // deselect all radio buttons const rowsById = Object.entries(state.rowsById).reduce((p, c) => { const [key, val] = c; val.isSelected = false; p[key] = val; return p; }, {}); return { shouldShowBatchActions: false, rowsById: { ...rowsById, [rowId]: { ...row, isSelected: !row.isSelected } } }; } const selectedRows = state.rowIds.filter(id => state.rowsById[id].isSelected).length; // Predict the length of the selected rows after this change occurs const selectedRowsCount = !row.isSelected ? selectedRows + 1 : selectedRows - 1; return { // Basic assumption here is that we want to show the batch action bar if // the row is being selected. If it's being unselected, then see if we // have a non-zero number of selected rows that batch actions could // still apply to shouldShowBatchActions: !row.isSelected || selectedRowsCount > 0, rowsById: { ...state.rowsById, [rowId]: { ...row, isSelected: !row.isSelected } } }; }); }); /** * Handler for toggling the expansion state of a given row. */ _defineProperty(this, "handleOnExpandRow", rowId => () => { this.setState(state => { const row = state.rowsById[rowId]; const { isExpandedAll } = state; return { isExpandedAll: row.isExpanded ? false : isExpandedAll, rowsById: { ...state.rowsById, [rowId]: { ...row, isExpanded: !row.isExpanded } } }; }); }); /** * Handler for changing the expansion state of all rows. */ _defineProperty(this, "handleOnExpandAll", () => { this.setState(state => { const { rowIds, isExpandedAll } = state; return { isExpandedAll: !isExpandedAll, rowsById: rowIds.reduce((acc, id) => ({ ...acc, [id]: { ...state.rowsById[id], isExpanded: !isExpandedAll } }), {}) }; }); }); /** * Handler for transitioning to the next sort state of the table * * @param headerKey - The field for the header that we are sorting by. */ _defineProperty(this, "handleSortBy", headerKey => () => { this.setState(state => getNextSortState(this.props, state, { key: headerKey })); }); /** * Event handler for transitioning input value state changes for the table * filter component. */ _defineProperty(this, "handleOnInputValueChange", (event, defaultValue) => { if (event.target) { this.setState({ filterInputValue: event.target.value }); } if (defaultValue) { this.setState({ filterInputValue: defaultValue }); } }); this.state = { ...getDerivedStateFromProps(_props, {}), isExpandedAll: false // Start with collapsed state, treat `undefined` as neutral state }; this.instanceId = getInstanceId(); } // If state needs to be updated, defer render until after the update completes. shouldComponentUpdate(nextProps) { if (this.props !== nextProps) { const nextRowIds = nextProps.rows.map(row => row.id); const rowIds = this.props.rows.map(row => row.id); if (!isEqual(nextRowIds, rowIds)) { this.setState(state => getDerivedStateFromProps(this.props, state)); return false; } const nextHeaders = nextProps.headers.map(header => header.key); const headers = this.props.headers.map(header => header.key); if (!isEqual(nextHeaders, headers)) { this.setState(state => getDerivedStateFromProps(this.props, state)); return false; } if (!isEqual(nextProps.rows, this.props.rows)) { this.setState(state => getDerivedStateFromProps(this.props, state)); return false; } } return true; } render() { const { children, filterRows = defaultFilterRows, headers, render } = this.props; const { filterInputValue, rowIds, rowsById, cellsById } = this.state; const filteredRowIds = typeof filterInputValue === 'string' ? filterRows({ rowIds, headers, cellsById, inputValue: filterInputValue, getCellId }) : rowIds; const renderProps = { // Data derived from state rows: denormalize(filteredRowIds, rowsById, cellsById), headers: this.props.headers, selectedRows: denormalize(this.getSelectedRows(), rowsById, cellsById), // Prop accessors/getters getHeaderProps: this.getHeaderProps, getExpandHeaderProps: this.getExpandHeaderProps, getRowProps: this.getRowProps, getExpandedRowProps: this.getExpandedRowProps, getSelectionProps: this.getSelectionProps, getToolbarProps: this.getToolbarProps, getBatchActionProps: this.getBatchActionProps, getTableProps: this.getTableProps, getTableContainerProps: this.getTableContainerProps, getCellProps: this.getCellProps, // Custom event handlers onInputChange: this.handleOnInputValueChange, // Expose internal state change actions sortBy: headerKey => this.handleSortBy(headerKey)(), selectAll: this.handleSelectAll, selectRow: rowId => this.handleOnSelectRow(rowId)(), expandRow: rowId => this.handleOnExpandRow(rowId)(), expandAll: this.handleOnExpandAll, radio: this.props.radio }; if (typeof render !== 'undefined') { return render(renderProps); } if (typeof children !== 'undefined') { return children(renderProps); } return null; } } _defineProperty(DataTable, "translationKeys", Object.values(translationKeys)); // TODO: Delete these static properties when the components are converted to a // functional component. // // Static properties for sub-components _defineProperty(DataTable, "Table", void 0); _defineProperty(DataTable, "TableActionList", void 0); _defineProperty(DataTable, "TableBatchAction", void 0); _defineProperty(DataTable, "TableBatchActions", void 0); _defineProperty(DataTable, "TableBody", void 0); _defineProperty(DataTable, "TableCell", void 0); _defineProperty(DataTable, "TableContainer", void 0); _defineProperty(DataTable, "TableDecoratorRow", void 0); _defineProperty(DataTable, "TableExpandHeader", void 0); _defineProperty(DataTable, "TableExpandRow", void 0); _defineProperty(DataTable, "TableExpandedRow", void 0); _defineProperty(DataTable, "TableHead", void 0); _defineProperty(DataTable, "TableHeader", void 0); _defineProperty(DataTable, "TableRow", void 0); _defineProperty(DataTable, "TableSelectAll", void 0); _defineProperty(DataTable, "TableSelectRow", void 0); _defineProperty(DataTable, "TableSlugRow", void 0); _defineProperty(DataTable, "TableToolbar", void 0); _defineProperty(DataTable, "TableToolbarAction", void 0); _defineProperty(DataTable, "TableToolbarContent", void 0); _defineProperty(DataTable, "TableToolbarSearch", void 0); _defineProperty(DataTable, "TableToolbarMenu", void 0); DataTable.Table = Table; DataTable.TableActionList = TableActionList; DataTable.TableBatchAction = TableBatchAction; DataTable.TableBatchActions = TableBatchActions; DataTable.TableBody = TableBody; DataTable.TableCell = TableCell; DataTable.TableContainer = TableContainer; DataTable.TableDecoratorRow = TableDecoratorRow; DataTable.TableExpandHeader = TableExpandHeader; DataTable.TableExpandRow = TableExpandRow; DataTable.TableExpandedRow = TableExpandedRow; DataTable.TableHead = TableHead; DataTable.TableHeader = TableHeader; DataTable.TableRow = TableRow; DataTable.TableSelectAll = TableSelectAll; DataTable.TableSelectRow = TableSelectRow; DataTable.TableSlugRow = TableSlugRow; DataTable.TableToolbar = TableToolbar; DataTable.TableToolbarAction = TableToolbarAction; DataTable.TableToolbarContent = TableToolbarContent; DataTable.TableToolbarSearch = TableToolbarSearch; DataTable.TableToolbarMenu = TableToolbarMenu; DataTable.propTypes = { /** * Experimental property. Allows table to align cell contents to the top if there is text wrapping in the content. Might have performance issues, intended for smaller tables */ experimentalAutoAlign: PropTypes.bool, /** * Optional hook to manually control filtering of the rows from the * TableToolbarSearch component */ filterRows: PropTypes.func, /** * The `headers` prop represents the order in which the headers should * appear in the table. We expect an array of objects to be passed in, where * `key` is the name of the key in a row object, and `header` is the name of * the header. */ headers: PropTypes.arrayOf(PropTypes.shape({ key: PropTypes.string.isRequired, header: PropTypes.node.isRequired })).isRequired, /** * Specify whether the table should be able to be sorted by its headers */ isSortable: PropTypes.bool, /** * Provide a string for the current locale */ locale: PropTypes.string, /** * Specify whether the overflow menu (if it exists) should be shown always, or only on hover */ overflowMenuOnHover: PropTypes.bool, /** * Specify whether the control should be a radio button or inline checkbox */ radio: PropTypes.bool, /** * The `rows` prop is where you provide us with a list of all the rows that * you want to render in the table. The only hard requirement is that this * is an array of objects, and that each object has a unique `id` field * available on it. */ rows: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.string.isRequired, disabled: PropTypes.bool, isSelected: PropTypes.bool, isExpanded: PropTypes.bool })).isRequired, /** * Change the row height of table. Currently supports `xs`, `sm`, `md`, `lg`, and `xl`. */ size: PropTypes.oneOf(['xs', 'sm', 'md', 'lg', 'xl']), /** * Optional hook to manually control sorting of the rows. */ sortRow: PropTypes.func, /** * Specify whether the header should be sticky. * Still experimental: may not work with every combination of table props */ stickyHeader: PropTypes.bool, /** * Optional method that takes in a message id and returns an * internationalized string. See `DataTable.translationKeys` for all * available message ids. */ translateWithId: PropTypes.func, /** * `false` If true, will use a width of 'auto' instead of 100% */ useStaticWidth: PropTypes.bool, /** * `true` to add useZebraStyles striping. */ useZebraStyles: PropTypes.bool }; export { DataTable as default };