UNPKG

@shopify/polaris

Version:

Shopify’s admin product component library

543 lines (486 loc) • 18 kB
import React, { PureComponent, createRef } from 'react'; import isEqual from 'react-fast-compare'; import { debounce } from '../../utilities/debounce.js'; import { classNames } from '../../utilities/css.js'; import { headerCell } from '../shared.js'; import { measureColumn, getPrevAndCurrentColumns } from './utilities.js'; import styles from './DataTable.scss.js'; import { Cell } from './components/Cell/Cell.js'; import { Navigation } from './components/Navigation/Navigation.js'; import { AfterInitialMount } from '../AfterInitialMount/AfterInitialMount.js'; import { Sticky } from '../Sticky/Sticky.js'; import { useI18n } from '../../utilities/i18n/hooks.js'; import { EventListener } from '../EventListener/EventListener.js'; class DataTableInner extends PureComponent { constructor(...args) { super(...args); this.state = { condensed: false, columnVisibilityData: [], isScrolledFarthestLeft: true, isScrolledFarthestRight: false }; this.dataTable = /*#__PURE__*/createRef(); this.scrollContainer = /*#__PURE__*/createRef(); this.table = /*#__PURE__*/createRef(); this.stickyTableHeadingsRow = /*#__PURE__*/createRef(); this.tableHeadings = []; this.stickyHeadings = []; this.tableHeadingWidths = []; this.stickyHeaderActive = false; this.handleResize = debounce(() => { const { table: { current: table }, scrollContainer: { current: scrollContainer } } = this; let condensed = false; if (table && scrollContainer) { condensed = table.scrollWidth > scrollContainer.clientWidth; } this.setState({ condensed, ...this.calculateColumnVisibilityData(condensed) }); }); this.setCellRef = ({ ref, index, inStickyHeader }) => { if (ref == null) { return; } if (inStickyHeader) { this.stickyHeadings[index] = ref; const button = ref.querySelector('button'); if (button == null) { return; } button.addEventListener('focus', this.handleHeaderButtonFocus); } else { this.tableHeadings[index] = ref; this.tableHeadingWidths[index] = ref.getBoundingClientRect().width; } }; this.changeHeadingFocus = () => { const { tableHeadings, stickyHeadings } = this; const stickyFocusedItemIndex = stickyHeadings.findIndex(item => { var _document$activeEleme; return item === ((_document$activeEleme = document.activeElement) === null || _document$activeEleme === void 0 ? void 0 : _document$activeEleme.parentElement); }); const tableFocusedItemIndex = tableHeadings.findIndex(item => { var _document$activeEleme2; return item === ((_document$activeEleme2 = document.activeElement) === null || _document$activeEleme2 === void 0 ? void 0 : _document$activeEleme2.parentElement); }); if (stickyFocusedItemIndex < 0 && tableFocusedItemIndex < 0) { return null; } let button; if (stickyFocusedItemIndex >= 0) { button = tableHeadings[stickyFocusedItemIndex].querySelector('button'); } else if (tableFocusedItemIndex >= 0) { button = stickyHeadings[tableFocusedItemIndex].querySelector('button'); } if (button == null) { return null; } button.style.visibility = 'visible'; button.focus(); button.style.removeProperty('visibility'); }; this.calculateColumnVisibilityData = condensed => { const { table: { current: table }, scrollContainer: { current: scrollContainer }, dataTable: { current: dataTable } } = this; if (condensed && table && scrollContainer && dataTable) { const headerCells = table.querySelectorAll(headerCell.selector); if (headerCells.length > 0) { const firstVisibleColumnIndex = headerCells.length - 1; const tableLeftVisibleEdge = scrollContainer.scrollLeft; const tableRightVisibleEdge = scrollContainer.scrollLeft + dataTable.offsetWidth; const tableData = { firstVisibleColumnIndex, tableLeftVisibleEdge, tableRightVisibleEdge }; const columnVisibilityData = [...headerCells].map(measureColumn(tableData)); const lastColumn = columnVisibilityData[columnVisibilityData.length - 1]; return { columnVisibilityData, ...getPrevAndCurrentColumns(tableData, columnVisibilityData), isScrolledFarthestLeft: tableLeftVisibleEdge === 0, isScrolledFarthestRight: lastColumn.rightEdge <= tableRightVisibleEdge }; } } return { columnVisibilityData: [], previousColumn: undefined, currentColumn: undefined }; }; this.handleHeaderButtonFocus = event => { if (this.scrollContainer.current == null || event.target == null) { return; } const target = event.target; const currentCell = target.parentNode; const tableScrollLeft = this.scrollContainer.current.scrollLeft; const tableViewableWidth = this.scrollContainer.current.offsetWidth; const tableRightEdge = tableScrollLeft + tableViewableWidth; const firstColumnWidth = this.state.columnVisibilityData[0].rightEdge; const currentColumnLeftEdge = currentCell.offsetLeft; const currentColumnRightEdge = currentCell.offsetLeft + currentCell.offsetWidth; if (tableScrollLeft > currentColumnLeftEdge - firstColumnWidth) { this.scrollContainer.current.scrollLeft = currentColumnLeftEdge - firstColumnWidth; } if (currentColumnRightEdge > tableRightEdge) { this.scrollContainer.current.scrollLeft = currentColumnRightEdge - tableViewableWidth; } }; this.stickyHeaderScrolling = () => { const { current: stickyTableHeadingsRow } = this.stickyTableHeadingsRow; const { current: scrollContainer } = this.scrollContainer; if (stickyTableHeadingsRow == null || scrollContainer == null) { return; } stickyTableHeadingsRow.scrollLeft = scrollContainer.scrollLeft; }; this.scrollListener = () => { debounce(() => { this.setState(prevState => ({ ...this.calculateColumnVisibilityData(prevState.condensed) })); }, 500); if (this.props.stickyHeader && this.stickyHeaderActive) { this.stickyHeaderScrolling(); } }; this.navigateTable = direction => { const { currentColumn, previousColumn } = this.state; const { current: scrollContainer } = this.scrollContainer; const handleScroll = () => { if (!currentColumn || !previousColumn) { return; } if (scrollContainer) { scrollContainer.scrollLeft = direction === 'right' ? currentColumn.rightEdge : previousColumn.leftEdge; requestAnimationFrame(() => { this.setState(prevState => ({ ...this.calculateColumnVisibilityData(prevState.condensed) })); }); } }; return handleScroll; }; this.renderHeadings = (heading, headingIndex) => { const { sortable, truncate = false, columnContentTypes, defaultSortDirection, initialSortColumnIndex = 0, verticalAlign } = this.props; const { sortDirection = defaultSortDirection, sortedColumnIndex = initialSortColumnIndex } = this.state; let sortableHeadingProps; const id = `heading-cell-${headingIndex}`; if (sortable) { const isSortable = sortable[headingIndex]; const isSorted = isSortable && sortedColumnIndex === headingIndex; const direction = isSorted ? sortDirection : 'none'; sortableHeadingProps = { defaultSortDirection, sorted: isSorted, sortable: isSortable, sortDirection: direction, onSort: this.defaultOnSort(headingIndex) }; } return /*#__PURE__*/React.createElement(Cell, Object.assign({ setRef: ref => this.setCellRef({ ref, index: headingIndex, inStickyHeader: false }), header: true, key: id, content: heading, contentType: columnContentTypes[headingIndex], firstColumn: headingIndex === 0, truncate: truncate }, sortableHeadingProps, { verticalAlign: verticalAlign })); }; this.totalsRowHeading = () => { const { i18n, totals, totalsName } = this.props; const totalsLabel = totalsName ? totalsName : { singular: i18n.translate('Polaris.DataTable.totalRowHeading'), plural: i18n.translate('Polaris.DataTable.totalsRowHeading') }; return totals && totals.filter(total => total !== '').length > 1 ? totalsLabel.plural : totalsLabel.singular; }; this.renderTotals = (total, index) => { const id = `totals-cell-${index}`; const { truncate = false, verticalAlign } = this.props; let content; let contentType; if (index === 0) { content = this.totalsRowHeading(); } if (total !== '' && index > 0) { contentType = 'numeric'; content = total; } const totalInFooter = this.props.showTotalsInFooter; return /*#__PURE__*/React.createElement(Cell, { total: true, totalInFooter: totalInFooter, firstColumn: index === 0, key: id, content: content, contentType: contentType, truncate: truncate, verticalAlign: verticalAlign }); }; this.getColSpan = (rowLength, headingsLength, contentTypesLength, cellIndex) => { const rowLen = rowLength ? rowLength : 1; const colLen = headingsLength ? headingsLength : contentTypesLength; const colSpan = Math.floor(colLen / rowLen); const remainder = colLen % rowLen; return cellIndex === 0 ? colSpan + remainder : colSpan; }; this.defaultRenderRow = (row, index) => { const { columnContentTypes, truncate = false, verticalAlign, hoverable = true, headings } = this.props; const className = classNames(styles.TableRow, hoverable && styles.hoverable); return /*#__PURE__*/React.createElement("tr", { key: `row-${index}`, className: className }, row.map((content, cellIndex) => { const id = `cell-${cellIndex}-row-${index}`; const colSpan = this.getColSpan(row.length, headings.length, columnContentTypes.length, cellIndex); return /*#__PURE__*/React.createElement(Cell, { key: id, content: content, contentType: columnContentTypes[cellIndex], firstColumn: cellIndex === 0, truncate: truncate, verticalAlign: verticalAlign, colSpan: colSpan }); })); }; this.defaultOnSort = headingIndex => { const { onSort, defaultSortDirection = 'ascending', initialSortColumnIndex } = this.props; const { sortDirection = defaultSortDirection, sortedColumnIndex = initialSortColumnIndex } = this.state; let newSortDirection = defaultSortDirection; if (sortedColumnIndex === headingIndex) { newSortDirection = sortDirection === 'ascending' ? 'descending' : 'ascending'; } const handleSort = () => { this.setState({ sortDirection: newSortDirection, sortedColumnIndex: headingIndex }, () => { if (onSort) { onSort(headingIndex, newSortDirection); } }); }; return handleSort; }; } componentDidMount() { // We need to defer the calculation in development so the styles have time to be injected. if (process.env.NODE_ENV === 'development') { setTimeout(() => { this.handleResize(); }, 10); } else { this.handleResize(); } } componentDidUpdate(prevProps) { if (isEqual(prevProps, this.props)) { return; } this.handleResize(); } componentWillUnmount() { this.handleResize.cancel(); } render() { const { headings, totals, showTotalsInFooter, rows, footerContent, hideScrollIndicator = false, increasedTableDensity = false, hasZebraStripingOnData = false, stickyHeader = false } = this.props; const { condensed, columnVisibilityData, isScrolledFarthestLeft, isScrolledFarthestRight } = this.state; const rowCountIsEven = rows.length % 2 === 0; const className = classNames(styles.DataTable, condensed && styles.condensed, totals && styles.ShowTotals, showTotalsInFooter && styles.ShowTotalsInFooter, hasZebraStripingOnData && styles.ZebraStripingOnData, hasZebraStripingOnData && rowCountIsEven && styles.RowCountIsEven); const wrapperClassName = classNames(styles.TableWrapper, condensed && styles.condensed, increasedTableDensity && styles.IncreasedTableDensity, stickyHeader && styles.StickyHeaderEnabled); const headingMarkup = /*#__PURE__*/React.createElement("tr", null, headings.map(this.renderHeadings)); const totalsMarkup = totals ? /*#__PURE__*/React.createElement("tr", null, totals.map(this.renderTotals)) : null; const bodyMarkup = rows.map(this.defaultRenderRow); const footerMarkup = footerContent ? /*#__PURE__*/React.createElement("div", { className: styles.Footer }, footerContent) : null; const headerTotalsMarkup = !showTotalsInFooter ? totalsMarkup : null; const footerTotalsMarkup = showTotalsInFooter ? /*#__PURE__*/React.createElement("tfoot", null, totalsMarkup) : null; const navigationMarkup = hideScrollIndicator ? null : /*#__PURE__*/React.createElement(Navigation, { columnVisibilityData: columnVisibilityData, isScrolledFarthestLeft: isScrolledFarthestLeft, isScrolledFarthestRight: isScrolledFarthestRight, navigateTableLeft: this.navigateTable('left'), navigateTableRight: this.navigateTable('right') }); const stickyHeaderMarkup = stickyHeader ? /*#__PURE__*/React.createElement(AfterInitialMount, null, /*#__PURE__*/React.createElement("div", { className: styles.StickyTable, role: "presentation" }, /*#__PURE__*/React.createElement(Sticky, { boundingElement: this.dataTable.current, onStickyChange: isSticky => { this.changeHeadingFocus(); this.stickyHeaderActive = isSticky; } }, isSticky => { const stickyHeaderClassNames = classNames(styles.StickyTableHeader, isSticky && styles['StickyTableHeader-isSticky']); return /*#__PURE__*/React.createElement("div", { className: stickyHeaderClassNames }, /*#__PURE__*/React.createElement("div", null, navigationMarkup), /*#__PURE__*/React.createElement("div", { className: styles.StickyTableHeadingsRow, ref: this.stickyTableHeadingsRow }, headings.map((heading, index) => { const { sortable, truncate = false, columnContentTypes, defaultSortDirection, initialSortColumnIndex = 0, verticalAlign } = this.props; const { sortDirection = defaultSortDirection, sortedColumnIndex = initialSortColumnIndex } = this.state; const id = `heading-cell-${index}`; let sortableHeadingProps; if (sortable) { const isSortable = sortable[index]; const isSorted = isSortable && sortedColumnIndex === index; const direction = isSorted ? sortDirection : 'none'; sortableHeadingProps = { defaultSortDirection, sorted: isSorted, sortable: isSortable, sortDirection: direction, onSort: this.defaultOnSort(index) }; } return /*#__PURE__*/React.createElement(Cell, Object.assign({ stickyHeadingCell: true, setRef: ref => this.setCellRef({ ref, index, inStickyHeader: true }), header: true, content: heading, contentType: columnContentTypes[index], firstColumn: index === 0, truncate: truncate }, sortableHeadingProps, { verticalAlign: verticalAlign, stickyCellWidth: this.tableHeadingWidths[index], key: id })); }))); }))) : null; return /*#__PURE__*/React.createElement("div", { className: wrapperClassName }, navigationMarkup, /*#__PURE__*/React.createElement("div", { className: className, ref: this.dataTable }, stickyHeaderMarkup, /*#__PURE__*/React.createElement("div", { className: styles.ScrollContainer, ref: this.scrollContainer }, /*#__PURE__*/React.createElement(EventListener, { event: "resize", handler: this.handleResize }), /*#__PURE__*/React.createElement(EventListener, { capture: true, passive: true, event: "scroll", handler: this.scrollListener }), /*#__PURE__*/React.createElement("table", { className: styles.Table, ref: this.table }, /*#__PURE__*/React.createElement("thead", null, headingMarkup, headerTotalsMarkup), /*#__PURE__*/React.createElement("tbody", null, bodyMarkup), footerTotalsMarkup)), footerMarkup)); } } function DataTable(props) { const i18n = useI18n(); return /*#__PURE__*/React.createElement(DataTableInner, Object.assign({}, props, { i18n: i18n })); } export { DataTable };