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