20318: Merge branch 'main' into 20318-disk-cache
[arvados.git] / services / workbench2 / src / components / data-table / data-table.tsx
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import React from "react";
6 import {
7     Table,
8     TableBody,
9     TableRow,
10     TableCell,
11     TableHead,
12     TableSortLabel,
13     StyleRulesCallback,
14     Theme,
15     WithStyles,
16     withStyles,
17     IconButton,
18     Tooltip,
19 } from "@material-ui/core";
20 import classnames from "classnames";
21 import { DataColumn, SortDirection } from "./data-column";
22 import { DataTableDefaultView } from "../data-table-default-view/data-table-default-view";
23 import { DataTableFilters } from "../data-table-filters/data-table-filters-tree";
24 import { DataTableMultiselectPopover } from "../data-table-multiselect-popover/data-table-multiselect-popover";
25 import { DataTableFiltersPopover } from "../data-table-filters/data-table-filters-popover";
26 import { countNodes, getTreeDirty } from "models/tree";
27 import { IconType, PendingIcon } from "components/icon/icon";
28 import { SvgIconProps } from "@material-ui/core/SvgIcon";
29 import ArrowDownwardIcon from "@material-ui/icons/ArrowDownward";
30 import { createTree } from "models/tree";
31 import { DataTableMultiselectOption } from "../data-table-multiselect-popover/data-table-multiselect-popover";
32
33 export type DataColumns<I, R> = Array<DataColumn<I, R>>;
34
35 export enum DataTableFetchMode {
36     PAGINATED,
37     INFINITE,
38 }
39
40 export interface DataTableDataProps<I> {
41     items: I[];
42     columns: DataColumns<I, any>;
43     onRowClick: (event: React.MouseEvent<HTMLTableRowElement>, item: I) => void;
44     onContextMenu: (event: React.MouseEvent<HTMLElement>, item: I) => void;
45     onRowDoubleClick: (event: React.MouseEvent<HTMLTableRowElement>, item: I) => void;
46     onSortToggle: (column: DataColumn<I, any>) => void;
47     onFiltersChange: (filters: DataTableFilters, column: DataColumn<I, any>) => void;
48     extractKey?: (item: I) => React.Key;
49     working?: boolean;
50     defaultViewIcon?: IconType;
51     defaultViewMessages?: string[];
52     currentItemUuid?: string;
53     currentRoute?: string;
54     toggleMSToolbar: (isVisible: boolean) => void;
55     setCheckedListOnStore: (checkedList: TCheckedList) => void;
56     checkedList: TCheckedList;
57 }
58
59 type CssRules =
60     | "tableBody"
61     | "root"
62     | "content"
63     | "noItemsInfo"
64     | "checkBoxHead"
65     | "checkBoxCell"
66     | "checkBox"
67     | "firstTableCell"
68     | "tableCell"
69     | "arrow"
70     | "arrowButton"
71     | "tableCellWorkflows"
72     | "loader";
73
74 const styles: StyleRulesCallback<CssRules> = (theme: Theme) => ({
75     root: {
76         width: "100%",
77     },
78     content: {
79         display: "inline-block",
80         width: "100%",
81     },
82     tableBody: {
83         background: theme.palette.background.paper,
84     },
85     loader: {
86         left: "50%",
87         marginLeft: "-84px",
88         position: "absolute",
89     },
90     noItemsInfo: {
91         textAlign: "center",
92         padding: theme.spacing.unit,
93     },
94     checkBoxHead: {
95         padding: "0",
96         display: "flex",
97     },
98     checkBoxCell: {
99         padding: "0",
100         paddingLeft: "10px",
101     },
102     checkBox: {
103         cursor: "pointer",
104     },
105     tableCell: {
106         wordWrap: "break-word",
107         paddingRight: "24px",
108         color: "#737373",
109     },
110     firstTableCell: {
111         paddingLeft: "5px",
112     },
113     tableCellWorkflows: {
114         "&:nth-last-child(2)": {
115             padding: "0px",
116             maxWidth: "48px",
117         },
118         "&:last-child": {
119             padding: "0px",
120             paddingRight: "24px",
121             width: "48px",
122         },
123     },
124     arrow: {
125         margin: 0,
126     },
127     arrowButton: {
128         color: theme.palette.text.primary,
129     },
130 });
131
132 export type TCheckedList = Record<string, boolean>;
133
134 type DataTableState = {
135     isSelected: boolean;
136 };
137
138 type DataTableProps<T> = DataTableDataProps<T> & WithStyles<CssRules>;
139
140 export const DataTable = withStyles(styles)(
141     class Component<T> extends React.Component<DataTableProps<T>> {
142         state: DataTableState = {
143             isSelected: false,
144         };
145
146         componentDidMount(): void {
147             this.initializeCheckedList(this.props.items);
148         }
149
150         componentDidUpdate(prevProps: Readonly<DataTableProps<T>>, prevState: DataTableState) {
151             const { items, setCheckedListOnStore } = this.props;
152             const { isSelected } = this.state;
153             if (prevProps.items !== items) {
154                 if (isSelected === true) this.setState({ isSelected: false });
155                 if (items.length) this.initializeCheckedList(items);
156                 else setCheckedListOnStore({});
157             }
158         }
159
160         checkBoxColumn: DataColumn<any, any> = {
161             name: "checkBoxColumn",
162             selected: true,
163             configurable: false,
164             filters: createTree(),
165             render: uuid => {
166                 const { classes, checkedList } = this.props;
167                 return (
168                     <input
169                         type="checkbox"
170                         name={uuid}
171                         className={classes.checkBox}
172                         checked={checkedList && checkedList[uuid] ? checkedList[uuid] : false}
173                         onChange={() => this.handleSelectOne(uuid)}
174                         onDoubleClick={ev => ev.stopPropagation()}></input>
175                 );
176             },
177         };
178
179         multiselectOptions: DataTableMultiselectOption[] = [
180             { name: "All", fn: list => this.handleSelectAll(list) },
181             { name: "None", fn: list => this.handleSelectNone(list) },
182             { name: "Invert", fn: list => this.handleInvertSelect(list) },
183         ];
184
185         initializeCheckedList = (uuids: any[]): void => {
186             const newCheckedList = { ...this.props.checkedList };
187
188             uuids.forEach(uuid => {
189                 if (!newCheckedList.hasOwnProperty(uuid)) {
190                     newCheckedList[uuid] = false;
191                 }
192             });
193             for (const key in newCheckedList) {
194                 if (!uuids.includes(key)) {
195                     delete newCheckedList[key];
196                 }
197             }
198             this.props.setCheckedListOnStore(newCheckedList);
199         };
200
201         isAllSelected = (list: TCheckedList): boolean => {
202             for (const key in list) {
203                 if (list[key] === false) return false;
204             }
205             return true;
206         };
207
208         isAnySelected = (): boolean => {
209             const { checkedList } = this.props;
210             if (!Object.keys(checkedList).length) return false;
211             for (const key in checkedList) {
212                 if (checkedList[key] === true) return true;
213             }
214             return false;
215         };
216
217         handleSelectOne = (uuid: string): void => {
218             const { checkedList } = this.props;
219             const newCheckedList = { ...checkedList };
220             newCheckedList[uuid] = !checkedList[uuid];
221             this.setState({ isSelected: this.isAllSelected(newCheckedList) });
222             this.props.setCheckedListOnStore(newCheckedList);
223         };
224
225         handleSelectorSelect = (): void => {
226             const { checkedList } = this.props;
227             const { isSelected } = this.state;
228             isSelected ? this.handleSelectNone(checkedList) : this.handleSelectAll(checkedList);
229         };
230
231         handleSelectAll = (list: TCheckedList): void => {
232             if (Object.keys(list).length) {
233                 const newCheckedList = { ...list };
234                 for (const key in newCheckedList) {
235                     newCheckedList[key] = true;
236                 }
237                 this.setState({ isSelected: true });
238                 this.props.setCheckedListOnStore(newCheckedList);
239             }
240         };
241
242         handleSelectNone = (list: TCheckedList): void => {
243             const newCheckedList = { ...list };
244             for (const key in newCheckedList) {
245                 newCheckedList[key] = false;
246             }
247             this.setState({ isSelected: false });
248             this.props.setCheckedListOnStore(newCheckedList);
249         };
250
251         handleInvertSelect = (list: TCheckedList): void => {
252             if (Object.keys(list).length) {
253                 const newCheckedList = { ...list };
254                 for (const key in newCheckedList) {
255                     newCheckedList[key] = !list[key];
256                 }
257                 this.setState({ isSelected: this.isAllSelected(newCheckedList) });
258                 this.props.setCheckedListOnStore(newCheckedList);
259             }
260         };
261
262         render() {
263             const { items, classes, working, columns } = this.props;
264             if (columns[0].name === this.checkBoxColumn.name) columns.shift();
265             columns.unshift(this.checkBoxColumn);
266             return (
267                 <div className={classes.root}>
268                     <div className={classes.content}>
269                         <Table>
270                             <TableHead>
271                                 <TableRow>{this.mapVisibleColumns(this.renderHeadCell)}</TableRow>
272                             </TableHead>
273                             <TableBody className={classes.tableBody}>{!working && items.map(this.renderBodyRow)}</TableBody>
274                         </Table>
275                         {!!working && (
276                             <div className={classes.loader}>
277                                 <DataTableDefaultView
278                                     icon={PendingIcon}
279                                     messages={["Loading data, please wait."]}
280                                 />
281                             </div>
282                         )}
283                         {items.length === 0 && !working && this.renderNoItemsPlaceholder(this.props.columns)}
284                     </div>
285                 </div>
286             );
287         }
288
289         renderNoItemsPlaceholder = (columns: DataColumns<T, any>) => {
290             const dirty = columns.some(column => getTreeDirty("")(column.filters));
291             return (
292                 <DataTableDefaultView
293                     icon={this.props.defaultViewIcon}
294                     messages={this.props.defaultViewMessages}
295                     filtersApplied={dirty}
296                 />
297             );
298         };
299
300         renderHeadCell = (column: DataColumn<T, any>, index: number) => {
301             const { name, key, renderHeader, filters, sort } = column;
302             const { onSortToggle, onFiltersChange, classes, checkedList } = this.props;
303             const { isSelected } = this.state;
304             return column.name === "checkBoxColumn" ? (
305                 <TableCell
306                     key={key || index}
307                     className={classes.checkBoxCell}>
308                     <div className={classes.checkBoxHead}>
309                         <Tooltip title={this.state.isSelected ? "Deselect All" : "Select All"}>
310                             <input
311                                 type="checkbox"
312                                 className={classes.checkBox}
313                                 checked={isSelected}
314                                 disabled={!this.props.items.length}
315                                 onChange={this.handleSelectorSelect}></input>
316                         </Tooltip>
317                         <DataTableMultiselectPopover
318                             name={`Options`}
319                             disabled={!this.props.items.length}
320                             options={this.multiselectOptions}
321                             checkedList={checkedList}></DataTableMultiselectPopover>
322                     </div>
323                 </TableCell>
324             ) : (
325                 <TableCell
326                     className={index === 1 ? classes.firstTableCell : classes.tableCell}
327                     key={key || index}>
328                     {renderHeader ? (
329                         renderHeader()
330                     ) : countNodes(filters) > 0 ? (
331                         <DataTableFiltersPopover
332                             name={`${name} filters`}
333                             mutuallyExclusive={column.mutuallyExclusiveFilters}
334                             onChange={filters => onFiltersChange && onFiltersChange(filters, column)}
335                             filters={filters}>
336                             {name}
337                         </DataTableFiltersPopover>
338                     ) : sort ? (
339                         <TableSortLabel
340                             active={sort.direction !== SortDirection.NONE}
341                             direction={sort.direction !== SortDirection.NONE ? sort.direction : undefined}
342                             IconComponent={this.ArrowIcon}
343                             hideSortIcon
344                             onClick={() => onSortToggle && onSortToggle(column)}>
345                             {name}
346                         </TableSortLabel>
347                     ) : (
348                         <span>{name}</span>
349                     )}
350                 </TableCell>
351             );
352         };
353
354         ArrowIcon = ({ className, ...props }: SvgIconProps) => (
355             <IconButton
356                 component="span"
357                 className={this.props.classes.arrowButton}
358                 tabIndex={-1}>
359                 <ArrowDownwardIcon
360                     {...props}
361                     className={classnames(className, this.props.classes.arrow)}
362                 />
363             </IconButton>
364         );
365
366         renderBodyRow = (item: any, index: number) => {
367             const { onRowClick, onRowDoubleClick, extractKey, classes, currentItemUuid, currentRoute } = this.props;
368             return (
369                 <TableRow
370                     hover
371                     key={extractKey ? extractKey(item) : index}
372                     onClick={event => onRowClick && onRowClick(event, item)}
373                     onContextMenu={this.handleRowContextMenu(item)}
374                     onDoubleClick={event => onRowDoubleClick && onRowDoubleClick(event, item)}
375                     selected={item === currentItemUuid}>
376                     {this.mapVisibleColumns((column, index) => (
377                         <TableCell
378                             key={column.key || index}
379                             className={
380                                 currentRoute === "/workflows"
381                                     ? classes.tableCellWorkflows
382                                     : index === 0
383                                     ? classes.checkBoxCell
384                                     : `${classes.tableCell} ${index === 1 ? classes.firstTableCell : ""}`
385                             }>
386                             {column.render(item)}
387                         </TableCell>
388                     ))}
389                 </TableRow>
390             );
391         };
392
393         mapVisibleColumns = (fn: (column: DataColumn<T, any>, index: number) => React.ReactElement<any>) => {
394             return this.props.columns.filter(column => column.selected).map(fn);
395         };
396
397         handleRowContextMenu = (item: T) => (event: React.MouseEvent<HTMLElement>) => this.props.onContextMenu(event, item);
398     }
399 );