1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import * as React from 'react';
6 import { Table, TableBody, TableRow, TableCell, TableHead, TableSortLabel, StyleRulesCallback, Theme, WithStyles, withStyles, Typography } from '@material-ui/core';
7 import { DataColumn, SortDirection } from './data-column';
8 import { DataTableFilters, DataTableFilterItem } from "../data-table-filters/data-table-filters";
10 export type DataColumns<T, F extends DataTableFilterItem = DataTableFilterItem> = Array<DataColumn<T, F>>;
12 export interface DataTableDataProps<T> {
14 columns: DataColumns<T>;
15 onRowClick: (event: React.MouseEvent<HTMLTableRowElement>, item: T) => void;
16 onContextMenu: (event: React.MouseEvent<HTMLElement>, item: T) => void;
17 onRowDoubleClick: (event: React.MouseEvent<HTMLTableRowElement>, item: T) => void;
18 onSortToggle: (column: DataColumn<T>) => void;
19 onFiltersChange: (filters: DataTableFilterItem[], column: DataColumn<T>) => void;
20 extractKey?: (item: T) => React.Key;
23 type CssRules = "tableBody" | "tableContainer" | "noItemsInfo";
25 const styles: StyleRulesCallback<CssRules> = (theme: Theme) => ({
31 background: theme.palette.background.paper
35 padding: theme.spacing.unit
39 type DataTableProps<T> = DataTableDataProps<T> & WithStyles<CssRules>;
41 export const DataTable = withStyles(styles)(
42 class Component<T> extends React.Component<DataTableProps<T>> {
44 const { items, classes } = this.props;
46 className={classes.tableContainer}>
50 {this.mapVisibleColumns(this.renderHeadCell)}
53 <TableBody className={classes.tableBody}>
54 {items.map(this.renderBodyRow)}
60 renderHeadCell = (column: DataColumn<T>, index: number) => {
61 const { name, key, renderHeader, filters, sortDirection } = column;
62 const { onSortToggle, onFiltersChange } = this.props;
63 return <TableCell key={key || index} style={{ width: column.width, minWidth: column.width }}>
68 name={`${name} filters`}
71 onFiltersChange(filters, column)}
77 active={sortDirection !== SortDirection.NONE}
78 direction={sortDirection !== SortDirection.NONE ? sortDirection : undefined}
81 onSortToggle(column)}>
90 renderBodyRow = (item: T, index: number) => {
91 const { onRowClick, onRowDoubleClick, extractKey } = this.props;
94 key={extractKey ? extractKey(item) : index}
95 onClick={event => onRowClick && onRowClick(event, item)}
96 onContextMenu={this.handleRowContextMenu(item)}
97 onDoubleClick={event => onRowDoubleClick && onRowDoubleClick(event, item) }>
98 {this.mapVisibleColumns((column, index) => (
99 <TableCell key={column.key || index}>
100 {column.render(item)}
106 mapVisibleColumns = (fn: (column: DataColumn<T>, index: number) => React.ReactElement<any>) => {
107 return this.props.columns.filter(column => column.selected).map(fn);
110 handleRowContextMenu = (item: T) =>
111 (event: React.MouseEvent<HTMLElement>) =>
112 this.props.onContextMenu(event, item)