import {useState} from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import {LoadingOverlay, Spinner} from '@givewp/components'; import styles from './style.module.scss'; import {__} from '@wordpress/i18n'; const Table = ({title = null, columns = [], data = [], columnFilters = {}, stripped = false, isLoading = false, isSorting, ...rest}) => { const [state, setState] = useState({}); const [cachedData, setCachedData] = useState([]); Table.resetSortState = () => { setState({}); }; // Clear cache if data is empty if (!isLoading && !data.length && cachedData.length) { setCachedData([]); } else if (data.length && data !== cachedData) { // Cache data so we can show that under overlay while new data is fetching setCachedData(data); } const visibleColumns = columns.filter((column) => column.visible || column.visible === undefined); const allowedColumns = visibleColumns.map((column) => column.key); // Get additional row columns added manually const additionalColumns = visibleColumns .filter((column) => 'append' in column && column.append) .map((column) => { return { [column.key]: column.defaultValue ?? '', }; }); // Used when additional columns are added, but they not exist in the result row. // So we have to sort result row to match columns order const sortResults = (order, object) => { const newObject = {}; order.forEach((key) => { newObject[key] = object[key]; }); return newObject; }; const handleItemSort = (item) => { const direction = state[item.label] === 'desc' ? 'asc' : 'desc'; setState({[item.label]: direction}); return item.sortCallback(direction); }; const getItemSortDirectionIcon = (item) => { if (!state[item.label]) { return ( ); } const iconClasses = classNames( 'dashicons', styles.sortIcons, {'dashicons-arrow-down': state[item.label] === 'desc'}, {'dashicons-arrow-up': state[item.label] === 'asc'} ); return ; }; const getHeaderRow = () => { return visibleColumns.map((item, index) => { const columnStyles = item.styles ? {style: item.styles} : null; return (