22083: Store "failedToLoadOutputCollection" state
[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 { CustomStyleRulesCallback } from 'common/custom-theme';
7 import {
8     Table,
9     TableBody,
10     TableRow,
11     TableCell,
12     TableHead,
13     TableSortLabel,
14     IconButton,
15     Tooltip,
16 } from "@mui/material";
17 import { WithStyles } from '@mui/styles';
18 import withStyles from '@mui/styles/withStyles';
19 import classnames from "classnames";
20 import { DataColumn, DataColumns, SortDirection } from "./data-column";
21 import { DataTableDefaultView } from "../data-table-default-view/data-table-default-view";
22 import { DataTableFilters } from "../data-table-filters/data-table-filters";
23 import { DataTableMultiselectPopover } from "../data-table-multiselect-popover/data-table-multiselect-popover";
24 import { DataTableFiltersPopover } from "../data-table-filters/data-table-filters-popover";
25 import { countNodes, getTreeDirty } from "models/tree";
26 import { IconType } from "components/icon/icon";
27 import { SvgIconProps } from "@mui/material/SvgIcon";
28 import ArrowDownwardIcon from "@mui/icons-material/ArrowDownward";
29 import { createTree } from "models/tree";
30 import { DataTableMultiselectOption } from "../data-table-multiselect-popover/data-table-multiselect-popover";
31 import { isExactlyOneSelected } from "store/multiselect/multiselect-actions";
32 import { PendingIcon } from "components/icon/icon";
33 import { CustomTheme, ArvadosTheme } from "common/custom-theme";
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     toggleMSToolbar: (isVisible: boolean) => void;
53     setCheckedListOnStore: (checkedList: TCheckedList) => void;
54     currentRoute?: string;
55     currentRouteUuid: string;
56     checkedList: TCheckedList;
57     selectedResourceUuid: string;
58     setSelectedUuid: (uuid: string | null) => void;
59     isNotFound?: boolean;
60     detailsPanelResourceUuid?: string;
61     loadDetailsPanel: (uuid: string) => void;
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     | "firstTableHead"
76     | "tableHead"
77     | "selected"
78     | "hovered"
79     | "arrow"
80     | "arrowButton"
81     | "tableCellWorkflows";
82
83 const styles: CustomStyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
84     root: {
85         width: "100%",
86     },
87     content: {
88         display: "inline-block",
89         width: "100%",
90     },
91     tableBody: {
92         background: theme.palette.background.paper,
93         overflow: "auto",
94     },
95     noItemsInfo: {
96         textAlign: "center",
97         padding: theme.spacing(1),
98     },
99     checkBoxHead: {
100         padding: "0",
101         display: "flex",
102         width: '2rem',
103         height: "1.5rem",
104         paddingLeft: '0.9rem',
105         marginRight: '0.5rem',
106         backgroundColor: theme.palette.background.paper,
107     },
108     checkBoxCell: {
109         padding: "0",
110         backgroundColor: theme.palette.background.paper,
111     },
112     clickBox: {
113         display: 'flex',
114         width: '1.6rem',
115         height: "1.5rem",
116         paddingLeft: '0.35rem',
117         paddingTop: '0.1rem',
118         marginLeft: '0.5rem',
119         cursor: "pointer",
120     },
121     checkBox: {
122         cursor: "pointer",
123     },
124     tableCell: {
125         wordWrap: "break-word",
126         paddingRight: "24px",
127     },
128     firstTableCell: {
129         paddingLeft: "5px",
130     },
131     firstTableHead: {
132         paddingLeft: "5px",
133     },
134     tableHead: {
135         wordWrap: "break-word",
136         paddingRight: "24px",
137         color: "#737373",
138         fontSize: "0.8125rem",
139         backgroundColor: theme.palette.background.paper,
140     },
141     selected: {
142         backgroundColor: `${CustomTheme.palette.grey['300']} !important`
143     },
144     hovered: {
145         backgroundColor: `${CustomTheme.palette.grey['100']} !important`
146     },
147     tableCellWorkflows: {
148         "&:nth-last-child(2)": {
149             padding: "0px",
150             maxWidth: "48px",
151         },
152         "&:last-child": {
153             padding: "0px",
154             paddingRight: "24px",
155             width: "48px",
156         },
157     },
158     arrow: {
159         margin: 0,
160     },
161     arrowButton: {
162         color: theme.palette.text.primary,
163     },
164 });
165
166 export type TCheckedList = Record<string, boolean>;
167
168 type DataTableState = {
169     isSelected: boolean;
170     isLoaded: boolean;
171     hoveredIndex: number | null;
172 };
173
174 type DataTableProps<T> = DataTableDataProps<T> & WithStyles<CssRules>;
175
176 export const DataTable = withStyles(styles)(
177     class Component<T> extends React.Component<DataTableProps<T>> {
178         state: DataTableState = {
179             isSelected: false,
180             isLoaded: false,
181             hoveredIndex: null,
182         };
183
184         componentDidMount(): void {
185             this.initializeCheckedList([]);
186             if(((this.props.items.length > 0) && !this.state.isLoaded) || !this.props.working) {
187                 this.setState({ isLoaded: true });
188             }
189             if(this.props.detailsPanelResourceUuid !== this.props.selectedResourceUuid) {
190                 this.props.loadDetailsPanel(this.props.selectedResourceUuid);
191             }
192         }
193
194         componentDidUpdate(prevProps: Readonly<DataTableProps<T>>, prevState: DataTableState) {
195             const { items, currentRouteUuid, setCheckedListOnStore } = this.props;
196             const { isSelected } = this.state;
197             const singleSelected = isExactlyOneSelected(this.props.checkedList);
198             if (prevProps.items !== items) {
199                 if (isSelected === true) this.setState({ isSelected: false });
200                 if (items.length) this.initializeCheckedList(items);
201                 else setCheckedListOnStore({});
202             }
203             if (prevProps.currentRoute !== this.props.currentRoute) {
204                 this.initializeCheckedList([]);
205             }
206             if (singleSelected && singleSelected !== isExactlyOneSelected(prevProps.checkedList)) {
207                 this.props.setSelectedUuid(singleSelected);
208             }
209             if (!singleSelected && !!currentRouteUuid && !this.isAnySelected()) {
210                 this.props.setSelectedUuid(currentRouteUuid);
211             }
212             if (!singleSelected && this.isAnySelected()) {
213                 this.props.setSelectedUuid(null);
214             }
215             if(prevProps.working === false && this.props.working === true) {
216                 this.setState({ isLoaded: false });
217             }
218             if(prevProps.working === true && this.props.working === false) {
219                 this.setState({ isLoaded: true });
220             }
221             if((this.props.items.length > 0) && !this.state.isLoaded) {
222                 this.setState({ isLoaded: true });
223             }
224         }
225
226         componentWillUnmount(): void {
227             this.initializeCheckedList([]);
228         }
229
230         checkBoxColumn: DataColumn<any, any> = {
231             name: "checkBoxColumn",
232             selected: true,
233             configurable: false,
234             filters: createTree(),
235             render: uuid => {
236                 const { classes, checkedList } = this.props;
237                 return (
238                     <div
239                         className={classes.clickBox}
240                         onClick={(ev) => {
241                             ev.stopPropagation()
242                             this.handleSelectOne(uuid)
243                         }}
244                         onDoubleClick={(ev) => ev.stopPropagation()}
245                     >
246                         <input
247                             data-cy={`multiselect-checkbox-${uuid}`}
248                             type='checkbox'
249                             name={uuid}
250                             className={classes.checkBox}
251                             checked={checkedList && checkedList[uuid] ? checkedList[uuid] : false}
252                             onChange={() => this.handleSelectOne(uuid)}
253                             onDoubleClick={(ev) => ev.stopPropagation()}
254                         ></input>
255                     </div>
256                 );
257             },
258         };
259
260         multiselectOptions: DataTableMultiselectOption[] = [
261             { name: "All", fn: list => this.handleSelectAll(list) },
262             { name: "None", fn: list => this.handleSelectNone(list) },
263             { name: "Invert", fn: list => this.handleInvertSelect(list) },
264         ];
265
266         initializeCheckedList = (uuids: any[]): void => {
267             const newCheckedList = { ...this.props.checkedList };
268
269             if(Object.keys(newCheckedList).length === 0){
270                 for(const uuid of uuids){
271                     newCheckedList[uuid] = false
272                 }
273             }
274
275             for (const key in newCheckedList) {
276                 if (!uuids.includes(key)) {
277                     delete newCheckedList[key];
278                 }
279             }
280             this.props.setCheckedListOnStore(newCheckedList);
281         };
282
283         isAllSelected = (list: TCheckedList): boolean => {
284             for (const key in list) {
285                 if (list[key] === false) return false;
286             }
287             return true;
288         };
289
290         isAnySelected = (): boolean => {
291             const { checkedList } = this.props;
292             if (!checkedList) return false;
293             if (!Object.keys(checkedList).length) return false;
294             for (const key in checkedList) {
295                 if (checkedList[key] === true) return true;
296             }
297             return false;
298         };
299
300         handleSelectOne = (uuid: string): void => {
301             const { checkedList } = this.props;
302             const newCheckedList = { ...checkedList };
303             newCheckedList[uuid] = !checkedList[uuid];
304             this.setState({ isSelected: this.isAllSelected(newCheckedList) });
305             this.props.setCheckedListOnStore(newCheckedList);
306         };
307
308         handleSelectorSelect = (): void => {
309             const { checkedList } = this.props;
310             const { isSelected } = this.state;
311             isSelected ? this.handleSelectNone(checkedList) : this.handleSelectAll(checkedList);
312         };
313
314         handleSelectAll = (list: TCheckedList): void => {
315             if (Object.keys(list).length) {
316                 const newCheckedList = { ...list };
317                 for (const key in newCheckedList) {
318                     newCheckedList[key] = true;
319                 }
320                 this.setState({ isSelected: true });
321                 this.props.setCheckedListOnStore(newCheckedList);
322             }
323         };
324
325         handleSelectNone = (list: TCheckedList): void => {
326             const newCheckedList = { ...list };
327             for (const key in newCheckedList) {
328                 newCheckedList[key] = false;
329             }
330             this.setState({ isSelected: false });
331             this.props.setCheckedListOnStore(newCheckedList);
332         };
333
334         handleInvertSelect = (list: TCheckedList): void => {
335             if (Object.keys(list).length) {
336                 const newCheckedList = { ...list };
337                 for (const key in newCheckedList) {
338                     newCheckedList[key] = !list[key];
339                 }
340                 this.setState({ isSelected: this.isAllSelected(newCheckedList) });
341                 this.props.setCheckedListOnStore(newCheckedList);
342             }
343         };
344
345         render() {
346             const { items, classes, columns, isNotFound } = this.props;
347             const { isLoaded } = this.state;
348             if (columns.length && columns[0].name === this.checkBoxColumn.name) columns.shift();
349             columns.unshift(this.checkBoxColumn);
350             return (
351                 <div className={classes.root}>
352                     <div className={classes.content}>
353                         <Table data-cy="data-table" stickyHeader>
354                             <TableHead>
355                                 <TableRow>{this.mapVisibleColumns(this.renderHeadCell)}</TableRow>
356                             </TableHead>
357                             <TableBody className={classes.tableBody}>{(isLoaded && !isNotFound) && items.map(this.renderBodyRow)}</TableBody>
358                         </Table>
359                         {(!isLoaded || isNotFound || items.length === 0) && this.renderNoItemsPlaceholder(this.props.columns)}
360                     </div>
361                 </div>
362             );
363         }
364
365         renderNoItemsPlaceholder = (columns: DataColumns<T, any>) => {
366             const { isLoaded } = this.state;
367             const { working, isNotFound } = this.props;
368             const dirty = columns.some(column => getTreeDirty("")(column.filters));
369             if (isNotFound && isLoaded) {
370                 return (
371                     <DataTableDefaultView
372                         icon={this.props.defaultViewIcon}
373                         messages={["No items found"]}
374                     />
375                 );
376             } else
377             if (isLoaded === false || working === true) {
378                 return (
379                     <DataTableDefaultView
380                         icon={PendingIcon}
381                         messages={["Loading data, please wait"]}
382                     />
383                 );
384             } else {
385                 // isLoaded && !working && !isNotFound
386                 return (
387                     <DataTableDefaultView
388                         data-cy="data-table-default-view"
389                         icon={this.props.defaultViewIcon}
390                         messages={this.props.defaultViewMessages}
391                         filtersApplied={dirty}
392                     />
393                 );
394             }
395         };
396
397         renderHeadCell = (column: DataColumn<T, any>, index: number) => {
398             const { name, key, renderHeader, filters, sort } = column;
399             const { onSortToggle, onFiltersChange, classes, checkedList } = this.props;
400             const { isSelected } = this.state;
401             return column.name === "checkBoxColumn" ? (
402                 <TableCell
403                     key={key || index}
404                     className={classes.checkBoxCell}>
405                     <div className={classes.checkBoxHead}>
406                         <Tooltip title={this.state.isSelected ? "Deselect all" : "Select all"}>
407                             <input
408                                 type="checkbox"
409                                 className={classes.checkBox}
410                                 checked={isSelected}
411                                 disabled={!this.props.items.length}
412                                 onChange={this.handleSelectorSelect}></input>
413                         </Tooltip>
414                         <DataTableMultiselectPopover
415                             name={`Options`}
416                             disabled={!this.props.items.length}
417                             options={this.multiselectOptions}
418                             checkedList={checkedList}></DataTableMultiselectPopover>
419                     </div>
420                 </TableCell>
421             ) : (
422                 <TableCell
423                     className={classnames(classes.tableHead, index === 1 ? classes.firstTableHead : '')}
424                     key={key || index}>
425                     {renderHeader ? (
426                         renderHeader()
427                     ) : countNodes(filters) > 0 ? (
428                         <DataTableFiltersPopover
429                             name={`${name} filters`}
430                             mutuallyExclusive={column.mutuallyExclusiveFilters}
431                             onChange={filters => onFiltersChange && onFiltersChange(filters, column)}
432                             filters={filters}>
433                             {name}
434                         </DataTableFiltersPopover>
435                     ) : sort ? (
436                         <TableSortLabel
437                             active={sort.direction !== SortDirection.NONE}
438                             direction={sort.direction !== SortDirection.NONE ? sort.direction : undefined}
439                             IconComponent={this.ArrowIcon}
440                             hideSortIcon
441                             onClick={() => onSortToggle && onSortToggle(column)}>
442                             {name}
443                         </TableSortLabel>
444                     ) : (
445                         <span>{name}</span>
446                     )}
447                 </TableCell>
448             );
449         };
450
451         ArrowIcon = ({ className, ...props }: SvgIconProps) => (
452             <IconButton
453                 data-cy="sort-button"
454                 component="span"
455                 className={this.props.classes.arrowButton}
456                 tabIndex={-1}
457                 size="large">
458                 <ArrowDownwardIcon
459                     {...props}
460                     className={classnames(className, this.props.classes.arrow)}
461                 />
462             </IconButton>
463         );
464
465         renderBodyRow = (item: any, index: number) => {
466             const { onRowClick, onRowDoubleClick, extractKey, classes, selectedResourceUuid, currentRoute } = this.props;
467             const { hoveredIndex } = this.state;
468             const isRowSelected = item === selectedResourceUuid;
469             const getClassnames = (colIndex: number) => {
470                 if(currentRoute === '/workflows') return classes.tableCellWorkflows;
471                 if(colIndex === 0) return classnames(classes.checkBoxCell, isRowSelected ? classes.selected : index === hoveredIndex ? classes.hovered : "");
472                 if(colIndex === 1) return classnames(classes.tableCell, classes.firstTableCell, isRowSelected ? classes.selected : "");
473                 return classnames(classes.tableCell, isRowSelected ? classes.selected : "");
474             };
475             const handleHover = (index: number | null) => {
476                 this.setState({ hoveredIndex: index });
477             }
478
479             return (
480                 <TableRow
481                     data-cy={'data-table-row'}
482                     hover
483                     key={extractKey ? extractKey(item) : index}
484                     onClick={event => onRowClick && onRowClick(event, item)}
485                     onContextMenu={this.handleRowContextMenu(item)}
486                     onDoubleClick={event => onRowDoubleClick && onRowDoubleClick(event, item)}
487                     selected={isRowSelected}
488                     className={isRowSelected ? classes.selected : ""}
489                     onMouseEnter={()=>handleHover(index)}
490                     onMouseLeave={()=>handleHover(null)}
491                 >
492                     {this.mapVisibleColumns((column, colIndex) => (
493                         <TableCell
494                             key={column.key || colIndex}
495                             data-cy={column.key || colIndex}
496                             className={getClassnames(colIndex)}>
497                             {column.render(item)}
498                         </TableCell>
499                     ))}
500                 </TableRow>
501             );
502         };
503
504         mapVisibleColumns = (fn: (column: DataColumn<T, any>, index: number) => React.ReactElement<any>) => {
505             return this.props.columns.filter(column => column.selected).map(fn);
506         };
507
508         handleRowContextMenu = (item: T) => (event: React.MouseEvent<HTMLElement>) => this.props.onContextMenu(event, item);
509     }
510 );