Merge branch '20943-trashed-role-groups' refs #20943
[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 } 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 import { isExactlyOneSelected } from "store/multiselect/multiselect-actions";
33 import { PendingIcon } from "components/icon/icon";
34
35 export type DataColumns<I, R> = Array<DataColumn<I, R>>;
36
37 export enum DataTableFetchMode {
38     PAGINATED,
39     INFINITE,
40 }
41
42 export interface DataTableDataProps<I> {
43     items: I[];
44     columns: DataColumns<I, any>;
45     onRowClick: (event: React.MouseEvent<HTMLTableRowElement>, item: I) => void;
46     onContextMenu: (event: React.MouseEvent<HTMLElement>, item: I) => void;
47     onRowDoubleClick: (event: React.MouseEvent<HTMLTableRowElement>, item: I) => void;
48     onSortToggle: (column: DataColumn<I, any>) => void;
49     onFiltersChange: (filters: DataTableFilters, column: DataColumn<I, any>) => void;
50     extractKey?: (item: I) => React.Key;
51     working?: boolean;
52     defaultViewIcon?: IconType;
53     defaultViewMessages?: string[];
54     toggleMSToolbar: (isVisible: boolean) => void;
55     setCheckedListOnStore: (checkedList: TCheckedList) => void;
56     currentRoute?: string;
57     currentRouteUuid: string;
58     checkedList: TCheckedList;
59     selectedResourceUuid: string;
60     setSelectedUuid: (uuid: string | null) => void;
61     isNotFound?: boolean;
62 }
63
64 type CssRules =
65     | "tableBody"
66     | "root"
67     | "content"
68     | "noItemsInfo"
69     | "checkBoxHead"
70     | "checkBoxCell"
71     | "clickBox"
72     | "checkBox"
73     | "firstTableCell"
74     | "tableCell"
75     | "arrow"
76     | "arrowButton"
77     | "tableCellWorkflows";
78
79 const styles: StyleRulesCallback<CssRules> = (theme: Theme) => ({
80     root: {
81         width: "100%",
82     },
83     content: {
84         display: "inline-block",
85         width: "100%",
86     },
87     tableBody: {
88         background: theme.palette.background.paper,
89     },
90     noItemsInfo: {
91         textAlign: "center",
92         padding: theme.spacing.unit,
93     },
94     checkBoxHead: {
95         padding: "0",
96         display: "flex",
97         width: '2rem',
98         height: "1.5rem",
99         paddingLeft: '0.9rem',
100         marginRight: '0.5rem'
101     },
102     checkBoxCell: {
103         padding: "0",
104     },
105     clickBox: {
106         display: 'flex',
107         width: '1.6rem',
108         height: "1.5rem",
109         paddingLeft: '0.35rem',
110         paddingTop: '0.1rem',
111         marginLeft: '0.5rem',
112         cursor: "pointer",
113     },
114     checkBox: {
115         cursor: "pointer",
116     },
117     tableCell: {
118         wordWrap: "break-word",
119         paddingRight: "24px",
120         color: "#737373",
121     },
122     firstTableCell: {
123         paddingLeft: "5px",
124     },
125     tableCellWorkflows: {
126         "&:nth-last-child(2)": {
127             padding: "0px",
128             maxWidth: "48px",
129         },
130         "&:last-child": {
131             padding: "0px",
132             paddingRight: "24px",
133             width: "48px",
134         },
135     },
136     arrow: {
137         margin: 0,
138     },
139     arrowButton: {
140         color: theme.palette.text.primary,
141     },
142 });
143
144 export type TCheckedList = Record<string, boolean>;
145
146 type DataTableState = {
147     isSelected: boolean;
148     isLoaded: boolean;
149 };
150
151 type DataTableProps<T> = DataTableDataProps<T> & WithStyles<CssRules>;
152
153 export const DataTable = withStyles(styles)(
154     class Component<T> extends React.Component<DataTableProps<T>> {
155         state: DataTableState = {
156             isSelected: false,
157             isLoaded: false,
158         };
159
160         componentDidMount(): void {
161             this.initializeCheckedList([]);
162             // If table is initialized loaded but empty
163             // isLoaded won't be set true by componentDidUpdate later
164             // So we set it to true here
165             if (!this.props.working) {
166                 this.setState({ isLoaded: true });
167             }
168         }
169
170         componentDidUpdate(prevProps: Readonly<DataTableProps<T>>, prevState: DataTableState) {
171             const { items, currentRouteUuid, setCheckedListOnStore } = this.props;
172             const { isSelected } = this.state;
173             const singleSelected = isExactlyOneSelected(this.props.checkedList);
174             if (prevProps.items !== items) {
175                 if (isSelected === true) this.setState({ isSelected: false });
176                 if (items.length) this.initializeCheckedList(items);
177                 else setCheckedListOnStore({});
178             }
179             if (prevProps.currentRoute !== this.props.currentRoute) {
180                 this.initializeCheckedList([]);
181             }
182             if (singleSelected && singleSelected !== isExactlyOneSelected(prevProps.checkedList)) {
183                 this.props.setSelectedUuid(singleSelected);
184             }
185             if (!singleSelected && !!currentRouteUuid && !this.isAnySelected()) {
186                 this.props.setSelectedUuid(currentRouteUuid);
187             }
188             if (!singleSelected && this.isAnySelected()) {
189                 this.props.setSelectedUuid(null);
190             }
191             if(prevProps.working === true && this.props.working === false) {
192                 this.setState({ isLoaded: true });
193             }
194             if((this.props.items.length > 0) && !this.state.isLoaded) {
195                 this.setState({ isLoaded: true });
196             }
197         }
198
199         componentWillUnmount(): void {
200             this.initializeCheckedList([]);
201         }
202
203         checkBoxColumn: DataColumn<any, any> = {
204             name: "checkBoxColumn",
205             selected: true,
206             configurable: false,
207             filters: createTree(),
208             render: uuid => {
209                 const { classes, checkedList } = this.props;
210                 return (
211                     <div
212                         className={classes.clickBox}
213                         onClick={(ev) => {
214                             ev.stopPropagation()
215                             this.handleSelectOne(uuid)
216                         }}
217                         onDoubleClick={(ev) => ev.stopPropagation()}
218                     >
219                         <input
220                             data-cy={`multiselect-checkbox-${uuid}`}
221                             type='checkbox'
222                             name={uuid}
223                             className={classes.checkBox}
224                             checked={checkedList && checkedList[uuid] ? checkedList[uuid] : false}
225                             onChange={() => this.handleSelectOne(uuid)}
226                             onDoubleClick={(ev) => ev.stopPropagation()}
227                         ></input>
228                     </div>
229                 );
230             },
231         };
232
233         multiselectOptions: DataTableMultiselectOption[] = [
234             { name: "All", fn: list => this.handleSelectAll(list) },
235             { name: "None", fn: list => this.handleSelectNone(list) },
236             { name: "Invert", fn: list => this.handleInvertSelect(list) },
237         ];
238
239         initializeCheckedList = (uuids: any[]): void => {
240             const newCheckedList = { ...this.props.checkedList };
241
242             if(Object.keys(newCheckedList).length === 0){
243                 for(const uuid of uuids){
244                     newCheckedList[uuid] = false
245                 }
246             }
247
248             for (const key in newCheckedList) {
249                 if (!uuids.includes(key)) {
250                     delete newCheckedList[key];
251                 }
252             }
253             this.props.setCheckedListOnStore(newCheckedList);
254         };
255
256         isAllSelected = (list: TCheckedList): boolean => {
257             for (const key in list) {
258                 if (list[key] === false) return false;
259             }
260             return true;
261         };
262
263         isAnySelected = (): boolean => {
264             const { checkedList } = this.props;
265             if (!Object.keys(checkedList).length) return false;
266             for (const key in checkedList) {
267                 if (checkedList[key] === true) return true;
268             }
269             return false;
270         };
271
272         handleSelectOne = (uuid: string): void => {
273             const { checkedList } = this.props;
274             const newCheckedList = { ...checkedList };
275             newCheckedList[uuid] = !checkedList[uuid];
276             this.setState({ isSelected: this.isAllSelected(newCheckedList) });
277             this.props.setCheckedListOnStore(newCheckedList);
278         };
279
280         handleSelectorSelect = (): void => {
281             const { checkedList } = this.props;
282             const { isSelected } = this.state;
283             isSelected ? this.handleSelectNone(checkedList) : this.handleSelectAll(checkedList);
284         };
285
286         handleSelectAll = (list: TCheckedList): void => {
287             if (Object.keys(list).length) {
288                 const newCheckedList = { ...list };
289                 for (const key in newCheckedList) {
290                     newCheckedList[key] = true;
291                 }
292                 this.setState({ isSelected: true });
293                 this.props.setCheckedListOnStore(newCheckedList);
294             }
295         };
296
297         handleSelectNone = (list: TCheckedList): void => {
298             const newCheckedList = { ...list };
299             for (const key in newCheckedList) {
300                 newCheckedList[key] = false;
301             }
302             this.setState({ isSelected: false });
303             this.props.setCheckedListOnStore(newCheckedList);
304         };
305
306         handleInvertSelect = (list: TCheckedList): void => {
307             if (Object.keys(list).length) {
308                 const newCheckedList = { ...list };
309                 for (const key in newCheckedList) {
310                     newCheckedList[key] = !list[key];
311                 }
312                 this.setState({ isSelected: this.isAllSelected(newCheckedList) });
313                 this.props.setCheckedListOnStore(newCheckedList);
314             }
315         };
316
317         render() {
318             const { items, classes, columns, isNotFound } = this.props;
319             const { isLoaded } = this.state;
320             if (columns.length && columns[0].name === this.checkBoxColumn.name) columns.shift();
321             columns.unshift(this.checkBoxColumn);
322             return (
323                 <div className={classes.root}>
324                     <div className={classes.content}>
325                         <Table>
326                             <TableHead>
327                                 <TableRow>{this.mapVisibleColumns(this.renderHeadCell)}</TableRow>
328                             </TableHead>
329                             <TableBody className={classes.tableBody}>{(isLoaded && !isNotFound) && items.map(this.renderBodyRow)}</TableBody>
330                         </Table>
331                         {(!isLoaded || isNotFound || items.length === 0) && this.renderNoItemsPlaceholder(this.props.columns)}
332                     </div>
333                 </div>
334             );
335         }
336
337         renderNoItemsPlaceholder = (columns: DataColumns<T, any>) => {
338             const { isLoaded } = this.state;
339             const { working, isNotFound } = this.props;
340             const dirty = columns.some(column => getTreeDirty("")(column.filters));
341             if (isNotFound && isLoaded) {
342                 return (
343                     <DataTableDefaultView
344                         icon={this.props.defaultViewIcon}
345                         messages={["No items found"]}
346                     />
347                 );
348             } else
349             if (isLoaded === false || working === true) {
350                 return (
351                     <DataTableDefaultView
352                         icon={PendingIcon}
353                         messages={["Loading data, please wait"]}
354                     />
355                 );
356             } else {
357                 // isLoaded && !working && !isNotFound
358                 return (
359                     <DataTableDefaultView
360                         icon={this.props.defaultViewIcon}
361                         messages={this.props.defaultViewMessages}
362                         filtersApplied={dirty}
363                     />
364                 );
365             }
366         };
367
368         renderHeadCell = (column: DataColumn<T, any>, index: number) => {
369             const { name, key, renderHeader, filters, sort } = column;
370             const { onSortToggle, onFiltersChange, classes, checkedList } = this.props;
371             const { isSelected } = this.state;
372             return column.name === "checkBoxColumn" ? (
373                 <TableCell
374                     key={key || index}
375                     className={classes.checkBoxCell}>
376                     <div className={classes.checkBoxHead}>
377                         <Tooltip title={this.state.isSelected ? "Deselect all" : "Select all"}>
378                             <input
379                                 type="checkbox"
380                                 className={classes.checkBox}
381                                 checked={isSelected}
382                                 disabled={!this.props.items.length}
383                                 onChange={this.handleSelectorSelect}></input>
384                         </Tooltip>
385                         <DataTableMultiselectPopover
386                             name={`Options`}
387                             disabled={!this.props.items.length}
388                             options={this.multiselectOptions}
389                             checkedList={checkedList}></DataTableMultiselectPopover>
390                     </div>
391                 </TableCell>
392             ) : (
393                 <TableCell
394                     className={index === 1 ? classes.firstTableCell : classes.tableCell}
395                     key={key || index}>
396                     {renderHeader ? (
397                         renderHeader()
398                     ) : countNodes(filters) > 0 ? (
399                         <DataTableFiltersPopover
400                             name={`${name} filters`}
401                             mutuallyExclusive={column.mutuallyExclusiveFilters}
402                             onChange={filters => onFiltersChange && onFiltersChange(filters, column)}
403                             filters={filters}>
404                             {name}
405                         </DataTableFiltersPopover>
406                     ) : sort ? (
407                         <TableSortLabel
408                             active={sort.direction !== SortDirection.NONE}
409                             direction={sort.direction !== SortDirection.NONE ? sort.direction : undefined}
410                             IconComponent={this.ArrowIcon}
411                             hideSortIcon
412                             onClick={() => onSortToggle && onSortToggle(column)}>
413                             {name}
414                         </TableSortLabel>
415                     ) : (
416                         <span>{name}</span>
417                     )}
418                 </TableCell>
419             );
420         };
421
422         ArrowIcon = ({ className, ...props }: SvgIconProps) => (
423             <IconButton
424                 component="span"
425                 className={this.props.classes.arrowButton}
426                 tabIndex={-1}>
427                 <ArrowDownwardIcon
428                     {...props}
429                     className={classnames(className, this.props.classes.arrow)}
430                 />
431             </IconButton>
432         );
433
434         renderBodyRow = (item: any, index: number) => {
435             const { onRowClick, onRowDoubleClick, extractKey, classes, selectedResourceUuid, currentRoute } = this.props;
436             return (
437                 <TableRow
438                     data-cy={'data-table-row'}
439                     hover
440                     key={extractKey ? extractKey(item) : index}
441                     onClick={event => onRowClick && onRowClick(event, item)}
442                     onContextMenu={this.handleRowContextMenu(item)}
443                     onDoubleClick={event => onRowDoubleClick && onRowDoubleClick(event, item)}
444                     selected={item === selectedResourceUuid}>
445                     {this.mapVisibleColumns((column, index) => (
446                         <TableCell
447                             key={column.key || index}
448                             className={
449                                 currentRoute === "/workflows"
450                                     ? classes.tableCellWorkflows
451                                     : index === 0
452                                     ? classes.checkBoxCell
453                                     : `${classes.tableCell} ${index === 1 ? classes.firstTableCell : ""}`
454                             }>
455                             {column.render(item)}
456                         </TableCell>
457                     ))}
458                 </TableRow>
459             );
460         };
461
462         mapVisibleColumns = (fn: (column: DataColumn<T, any>, index: number) => React.ReactElement<any>) => {
463             return this.props.columns.filter(column => column.selected).map(fn);
464         };
465
466         handleRowContextMenu = (item: T) => (event: React.MouseEvent<HTMLElement>) => this.props.onContextMenu(event, item);
467     }
468 );