import { CSSProperties, KeyboardEvent as ReactKeyboardEvent, MouseEvent, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' import { useGatedContentAccessMap } from '@audius/common/hooks' import { Kind, ID, TrackMetadata } from '@audius/common/models' import { dayjs } from '@audius/common/utils' import { IconCaretDown, IconCaretLeft, IconCaretRight, IconCaretUp, isKeyboardActivationKey, Tooltip } from '@audius/harmony' import cn from 'classnames' import { range } from 'lodash' import { Cell, Row, TableRowProps, useFlexLayout, useSortBy, useTable } from 'react-table' import { AutoSizer, InfiniteLoader, List, WindowScroller } from 'react-virtualized' import { Draggable, Droppable } from 'components/dragndrop' import Skeleton from 'components/skeleton/Skeleton' import styles from './Table.module.css' import { TableLoadingSpinner } from './components/TableLoadingSpinner' import { ResponsiveColumns, getHiddenResponsiveColumns } from './responsiveColumns' const FETCH_THRESHOLD = 40 const FETCH_BATCH_SIZE = 80 const TABLE_COLUMN_HORIZONTAL_CHROME_WIDTH = 24 const getColumnSortLabel = (column: any, headerContent: unknown) => { if (typeof column.sortTitle === 'string') return column.sortTitle if (typeof headerContent === 'string') return headerContent if (typeof column.Header === 'string') return column.Header return column.id ?? column.accessor ?? 'column' } export const numericSorter = (accessor: string) => (rowA: any, rowB: any) => { return rowA[accessor] - rowB[accessor] } export const alphaSorter = (accessor: string) => (rowA: any, rowB: any) => { if ( rowA[accessor].trim().toLowerCase() < rowB[accessor].trim().toLowerCase() ) { return -1 } if ( rowA[accessor].trim().toLowerCase() > rowB[accessor].trim().toLowerCase() ) { return 1 } return 0 } export const dateSorter = (accessor: string) => (rowA: any, rowB: any) => { if (dayjs(rowB[accessor]).isAfter(dayjs(rowA[accessor]))) return 1 if (dayjs(rowA[accessor]).isAfter(dayjs(rowB[accessor]))) return -1 return 0 } const isEmptyRowDefault = (row: any) => { return Boolean(!row?.original?.uid || row?.original?.kind === Kind.EMPTY) } export type TableProps = { activeIndex?: number columns: any[] data: any[] defaultSorter?: (a: any, b: any) => number fetchBatchSize?: number fetchMore?: ( offset: number, limit: number ) => Promise | undefined | void fetchPage?: (page: number) => void fetchThreshold?: number getRowClassName?: (rowIndex: number) => string isPaginated?: boolean isReorderable?: boolean isTracksTable?: boolean isDense?: boolean isVirtualized?: boolean loading?: boolean onClickRow?: ( e: MouseEvent, rowInfo: any, index: number ) => void onReorder?: (source: number, destination: number) => void onShowMoreToggle?: (setting: boolean) => void onSort?: (...props: any[]) => void isEmptyRow?: (row: any) => boolean pageSize?: number scrollRef?: React.MutableRefObject showMoreLimit?: number tableClassName?: string tableHeaderClassName?: string totalRowCount?: number useLocalSort?: boolean wrapperClassName?: string responsiveColumns?: ResponsiveColumns } type TableRowPropsWithKeyDown = TableRowProps & { onKeyDown?: (e: ReactKeyboardEvent) => void } export const Table = ({ activeIndex = -1, columns, data, defaultSorter, fetchBatchSize = FETCH_BATCH_SIZE, fetchMore, fetchPage, fetchThreshold = FETCH_THRESHOLD, getRowClassName, isPaginated = false, isReorderable = false, isTracksTable = false, isDense = false, isVirtualized = false, loading = false, onClickRow, onReorder, onShowMoreToggle, onSort, isEmptyRow = isEmptyRowDefault, pageSize = 50, scrollRef, showMoreLimit, tableClassName, tableHeaderClassName, totalRowCount, useLocalSort = false, wrapperClassName, responsiveColumns, ...other }: TableProps) => { const trackAccessMap = useGatedContentAccessMap(isTracksTable ? data : []) useEffect(() => { if (totalRowCount == null && isPaginated) { console.error( 'Programming error - need to specify the `totalRowCount` if using paginated Table component (i.e .if `isPaginated` is `true`)' ) } }, [isPaginated, totalRowCount]) const defaultColumn = useMemo( () => ({ minWidth: 64, width: 64, maxWidth: 200 }), [] ) const [currentPage, setCurrentPage] = useState(0) const maxPage = useMemo(() => { if (totalRowCount == null) { return 0 } return Math.floor(totalRowCount / pageSize) }, [pageSize, totalRowCount]) const tableResizeObserverRef = useRef(null) const tableResizeHandlerRef = useRef<(() => void) | null>(null) const [tableWidth, setTableWidth] = useState(0) const hiddenResponsiveColumnIds = useMemo(() => { if (!responsiveColumns) return new Set() return getHiddenResponsiveColumns({ columns, containerWidth: tableWidth, responsiveColumns, fallbackColumnWidth: defaultColumn.width, columnChromeWidth: TABLE_COLUMN_HORIZONTAL_CHROME_WIDTH }) }, [columns, defaultColumn.width, responsiveColumns, tableWidth]) const getColumnId = (column: any) => { if (typeof column?.id === 'string' && column.id.length > 0) return column.id if (typeof column?.accessor === 'string' && column.accessor.length > 0) { return column.accessor } return null } const visibleColumns = useMemo(() => { if (!hiddenResponsiveColumnIds.size) return columns return columns.filter((column) => { const id = getColumnId(column) return id == null || !hiddenResponsiveColumnIds.has(id) }) }, [columns, hiddenResponsiveColumnIds]) const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow, state: { sortBy } } = useTable( { columns: visibleColumns, data, defaultColumn, autoResetSortBy: false, manualSortBy: Boolean(onSort) }, useSortBy, useFlexLayout ) const setTableWrapperNode = useCallback((node: HTMLDivElement | null) => { if (tableResizeObserverRef.current) { tableResizeObserverRef.current.disconnect() tableResizeObserverRef.current = null } if (tableResizeHandlerRef.current) { window.removeEventListener('resize', tableResizeHandlerRef.current) tableResizeHandlerRef.current = null } if (!node) return const measure = () => setTableWidth(node.clientWidth) measure() if (typeof ResizeObserver !== 'undefined') { const resizeObserver = new ResizeObserver(() => { measure() }) resizeObserver.observe(node) tableResizeObserverRef.current = resizeObserver } else { window.addEventListener('resize', measure) tableResizeHandlerRef.current = measure } }, []) useEffect(() => { return () => { if (tableResizeObserverRef.current) { tableResizeObserverRef.current.disconnect() } if (tableResizeHandlerRef.current) { window.removeEventListener('resize', tableResizeHandlerRef.current) } } }, []) const isEndColumn = useCallback( (id: string) => id === 'trackActions' || id === 'overflowMenu', [] ) const isColumnVisible = useCallback( (id: string) => !hiddenResponsiveColumnIds.has(id), [hiddenResponsiveColumnIds] ) const [showMore, setShowMore] = useState( !showMoreLimit || pageSize < showMoreLimit ) const prevSortValue = useRef(null) const sortValue = sortBy[0] ? `${sortBy[0].id}${sortBy[0].desc}` : null const handleSortChange = useCallback(() => { if (isVirtualized && !useLocalSort) { if (sortBy.length === 0) return onSort?.('', '') const sortColumn = columns.find((c) => c.id === sortBy[0].id) const column = sortColumn.accessor const order = sortBy[0]?.desc ? 'desc' : 'asc' onSort?.(column, order) } else { let sorter = null let sortColumn let order = 'ascend' if (sortBy.length === 0) { sorter = defaultSorter } else { sortColumn = columns.find((c) => c.id === sortBy[0].id) sorter = sortColumn?.sorter order = sortBy[0]?.desc ? 'descend' : 'ascend' } if (sorter) { onSort?.({ column: { sorter }, order }) } else { onSort?.({ column: null, order }) } } }, [columns, defaultSorter, isVirtualized, onSort, sortBy, useLocalSort]) useEffect(() => { if (sortValue !== prevSortValue.current) { prevSortValue.current = sortValue handleSortChange() } // eslint-disable-next-line react-hooks/exhaustive-deps }, [sortValue]) const renderTableHeader = useCallback((column: any, endHeader?: boolean) => { const { key, colSpan, role, style } = column.getHeaderProps() const hasExplicitNullHeader = column?.Header === null || column?.Header === false const headerContent = hasExplicitNullHeader ? null : column.render('Header') const isSortable = column.disableSortBy !== true const { onClick: onSortClick, onKeyDown: onSortKeyDown, ...sortByToggleProps } = column.getSortByToggleProps() const handleSortKeyDown = (e: ReactKeyboardEvent) => { onSortKeyDown?.(e) if (e.defaultPrevented || !isKeyboardActivationKey(e)) return e.preventDefault() e.stopPropagation() onSortClick?.(e) } return ( {/* Sorting Container */}
{column.sortTitle && headerContent ? ( {headerContent} ) : ( headerContent )}
{!column.disableSortBy ? (
{!column.isSorted || !column.isSortedDesc ? ( ) : null} {!column.isSorted || column.isSortedDesc ? ( ) : null}
) : null}
) }, []) const renderHeaders = useCallback(() => { return headerGroups.map((headerGroup) => { const headers = headerGroup.headers.filter( (header) => isColumnVisible(header.id) && !isEndColumn(header.id) ) const endHeaders = headerGroup.headers.filter( (header) => isColumnVisible(header.id) && isEndColumn(header.id) ) const { key: headerGroupKey, ...headerGroupProps } = headerGroup.getHeaderGroupProps() return ( {headers.map((header) => renderTableHeader(header, false))} {endHeaders.length ? endHeaders.map((endHeader) => renderTableHeader(endHeader, true)) : null} ) }) }, [headerGroups, isColumnVisible, isEndColumn, renderTableHeader]) const renderCell = useCallback( (cell: Cell, isEnd?: boolean) => { const Cell = isVirtualized ? 'div' : 'td' return ( {cell.render('Cell')} ) }, [isVirtualized] ) const renderSkeletonCell = useCallback( (cell: Cell) => ( ), [] ) const renderTableRow = useCallback( (row: Row, key: string, props: TableRowProps, className = '') => { const { onKeyDown: onRowPropsKeyDown, ...rowProps } = props as TableRowPropsWithKeyDown const cells = row.cells.filter( (cell: Cell) => isColumnVisible(cell.column.id) && !isEndColumn(cell.column.id) ) const endCells = row.cells.filter( (cell: Cell) => isColumnVisible(cell.column.id) && isEndColumn(cell.column.id) ) const Row = isVirtualized ? 'div' : 'tr' const { isFetchingNFTAccess, hasStreamAccess } = trackAccessMap[ (row.original as any).track_id ] ?? { isFetchingNFTAccess: false, hasStreamAccess: true } const isLocked = !isFetchingNFTAccess && !hasStreamAccess return ( ) => onClickRow?.(e, row, row.index) } onKeyDown={onRowPropsKeyDown} > {cells.map((cell) => renderCell(cell))} {endCells.length ? endCells.map((endCell) => renderCell(endCell, true)) : null} ) }, [ trackAccessMap, activeIndex, getRowClassName, isColumnVisible, isEndColumn, onClickRow, renderCell, isVirtualized ] ) const renderSkeletonRow = useCallback( (row: Row, key: string, props: TableRowProps) => { const cells = row.cells.filter((cell: Cell) => isColumnVisible(cell.column.id) ) return ( {cells.map((cell) => renderSkeletonCell(cell))} ) }, [activeIndex, getRowClassName, isColumnVisible, renderSkeletonCell] ) const onDragEnd = useCallback( ({ source, destination }: { source: number; destination: number }) => { if (source === destination) return onReorder?.(source, source < destination ? destination - 1 : destination) }, [onReorder] ) const renderDraggableRow = useCallback( (row: any, key: string, props: TableRowProps, className = '') => { return ( {renderTableRow(row, key, props, className)} ) }, [isTracksTable, renderTableRow] ) const renderReorderableRow = useCallback( (row: any, key: string, props: TableRowProps, className = '') => { return ( { onDragEnd({ source: index, destination: row.index }) }} acceptedKinds={['track', 'table-row']} asChild > {renderTableRow( row, key, props, cn(styles.reorderableRow, className) )} ) }, [isTracksTable, onDragEnd, renderTableRow] ) const renderRow = useCallback( ({ index, key, style }: { index: number key: string style: CSSProperties }) => { const row = rows[index] if (!row) return prepareRow(row) const rowProps = { ...row.getRowProps({ style }) } const isStreamGated = (row.original as TrackMetadata).is_stream_gated if (isEmptyRow(row)) { return renderSkeletonRow(row, key, rowProps) } if (isReorderable) { return renderReorderableRow(row, key, rowProps) } if (isTracksTable && !isStreamGated) { return renderDraggableRow(row, key, rowProps) } return renderTableRow(row, key, rowProps) }, [ rows, prepareRow, isEmptyRow, renderSkeletonRow, isReorderable, renderReorderableRow, isTracksTable, renderDraggableRow, renderTableRow ] ) const renderRows = useCallback(() => { const displayRows = !showMore ? rows.slice(0, showMoreLimit) : rows return displayRows.map((row) => { prepareRow(row) const rowProps = { ...row.getRowProps() } const isStreamGated = (row.original as TrackMetadata).is_stream_gated if (isReorderable) { return renderReorderableRow(row, row.id, rowProps) } if (isTracksTable && !isStreamGated) { return renderDraggableRow(row, row.id, rowProps) } return renderTableRow(row, row.id, rowProps) }) }, [ showMore, rows, showMoreLimit, prepareRow, isReorderable, renderReorderableRow, isTracksTable, renderDraggableRow, renderTableRow ]) const loadMoreRows = useCallback( async ({ startIndex }: { startIndex: number }) => { const offset = startIndex const limit = fetchBatchSize await fetchMore?.(offset, limit) }, [fetchMore, fetchBatchSize] ) const isRowLoaded = useCallback( ({ index }: { index: number }) => !isEmptyRow(rows[index]), [rows, isEmptyRow] ) const goToPage = useCallback( (page: number) => { if (page !== currentPage) setCurrentPage(page) }, [currentPage] ) const nextPage = useCallback(() => { if (currentPage < maxPage) goToPage(currentPage + 1) }, [currentPage, goToPage, maxPage]) const prevPage = useCallback(() => { if (currentPage > 0) goToPage(currentPage - 1) }, [currentPage, goToPage]) useEffect(() => { fetchPage?.(currentPage) }, [currentPage, fetchPage]) const renderPaginationControls = useCallback(() => { if (!isPaginated || maxPage === 0 || !showMore) return null return (
{range(maxPage + 1).map((idx) => ( ))}
) }, [ currentPage, goToPage, isPaginated, maxPage, nextPage, prevPage, showMore ]) const renderShowMoreControl = useCallback(() => { if (!showMoreLimit || rows.length <= showMoreLimit) return null const handleShowMoreToggle = () => { onShowMoreToggle?.(!showMore) setShowMore(!showMore) } return ( ) }, [onShowMoreToggle, rows.length, showMore, showMoreLimit]) const renderContent = useCallback(() => { return (
{renderHeaders()} {loading ? : renderRows()}
{renderPaginationControls()} {renderShowMoreControl()}
) }, [ getTableBodyProps, getTableProps, loading, renderHeaders, renderPaginationControls, renderRows, renderShowMoreControl, setTableWrapperNode, tableClassName, tableHeaderClassName, wrapperClassName, isDense ]) const wsRef = useRef(null) useLayoutEffect(() => { wsRef.current?.updatePosition() }, [rows.length]) const renderVirtualizedContent = useCallback(() => { return ( {({ onRowsRendered, registerChild: registerListChild }) => (
{({ height, registerChild, isScrolling, onChildScroll, scrollTop }) => (
{renderHeaders()} {loading ? : null}
void } > {loading ? null : ( {({ width }) => ( onRowsRendered(info)} ref={registerListChild} overscanRowsCount={2} rowCount={ fetchMore && totalRowCount != null ? totalRowCount : rows.length } rowHeight={isDense ? 56 : 64} rowRenderer={renderRow} /> )} )}
)}
)}
) }, [ isRowLoaded, loadMoreRows, totalRowCount, rows.length, setTableWrapperNode, fetchThreshold, fetchBatchSize, scrollRef, wrapperClassName, isDense, tableClassName, getTableProps, tableHeaderClassName, renderHeaders, loading, getTableBodyProps, fetchMore, renderRow ]) return isVirtualized ? renderVirtualizedContent() : renderContent() }