15610: Adds behaviors like the original Tree, and max height on VirtualTree.
[arvados-workbench2.git] / src / components / tree / virtual-tree.tsx
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import * as React from 'react';
6 import * as classnames from "classnames";
7 import { StyleRulesCallback, withStyles, WithStyles } from '@material-ui/core/styles';
8 import { ReactElement } from "react";
9 import { FixedSizeList, ListChildComponentProps } from "react-window";
10 import AutoSizer from "react-virtualized-auto-sizer";
11
12 import { ArvadosTheme } from '~/common/custom-theme';
13 import { TreeItem, TreeProps, TreeItemStatus } from './tree';
14 import { ListItem, Radio, Checkbox, CircularProgress, ListItemIcon } from '@material-ui/core';
15 import { SidePanelRightArrowIcon } from '../icon/icon';
16 import { min } from 'lodash';
17
18 type CssRules = 'list'
19     | 'listItem'
20     | 'active'
21     | 'loader'
22     | 'toggableIconContainer'
23     | 'iconClose'
24     | 'renderContainer'
25     | 'iconOpen'
26     | 'toggableIcon'
27     | 'checkbox'
28     | 'virtualizedList';
29
30 const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
31     list: {
32         padding: '3px 0px',
33     },
34     virtualizedList: {
35         height: '200px',
36     },
37     listItem: {
38         padding: '3px 0px',
39     },
40     loader: {
41         position: 'absolute',
42         transform: 'translate(0px)',
43         top: '3px'
44     },
45     toggableIconContainer: {
46         color: theme.palette.grey["700"],
47         height: '14px',
48         width: '14px',
49     },
50     toggableIcon: {
51         fontSize: '14px'
52     },
53     renderContainer: {
54         flex: 1
55     },
56     active: {
57         color: theme.palette.primary.main,
58     },
59     iconClose: {
60         transition: 'all 0.1s ease',
61     },
62     iconOpen: {
63         transition: 'all 0.1s ease',
64         transform: 'rotate(90deg)',
65     },
66     checkbox: {
67         width: theme.spacing.unit * 3,
68         height: theme.spacing.unit * 3,
69         margin: `0 ${theme.spacing.unit}px`,
70         padding: 0,
71         color: theme.palette.grey["500"],
72     }
73 });
74
75 export interface VirtualTreeItem<T> extends TreeItem<T> {
76     itemCount?: number;
77     level?: number;
78 }
79
80 // For some reason, on TSX files it isn't accepted just one generic param, so
81 // I'm using <T, _> as a workaround.
82 export const Row =  <T, _>(itemList: VirtualTreeItem<T>[], render: any, treeProps: TreeProps<T>) => withStyles(styles)(
83     (props: React.PropsWithChildren<ListChildComponentProps> & WithStyles<CssRules>) => {
84         const { index, style, classes } = props;
85         const it = itemList[index];
86         const level = it.level || 0;
87         const { toggleItemActive, disableRipple, currentItemUuid, useRadioButtons } = treeProps;
88         const { listItem, loader, toggableIconContainer, renderContainer } = classes;
89         const { levelIndentation = 20, itemRightPadding = 20 } = treeProps;
90
91         const showSelection = typeof treeProps.showSelection === 'function'
92             ? treeProps.showSelection
93             : () => treeProps.showSelection ? true : false;
94
95         const handleRowContextMenu = (item: VirtualTreeItem<T>) =>
96             (event: React.MouseEvent<HTMLElement>) => {
97                 treeProps.onContextMenu(event, item);
98             };
99
100         const handleToggleItemOpen = (item: VirtualTreeItem<T>) =>
101             (event: React.MouseEvent<HTMLElement>) => {
102                 event.stopPropagation();
103                 treeProps.toggleItemOpen(event, item);
104             };
105
106         const getToggableIconClassNames = (isOpen?: boolean, isActive?: boolean) => {
107             const { iconOpen, iconClose, active, toggableIcon } = props.classes;
108             return classnames(toggableIcon, {
109                 [iconOpen]: isOpen,
110                 [iconClose]: !isOpen,
111                 [active]: isActive
112             });
113         };
114
115         const isSidePanelIconNotNeeded = (status: string, itemCount: number) => {
116             return status === TreeItemStatus.PENDING ||
117                 (status === TreeItemStatus.LOADED && itemCount === 0);
118         };
119
120         const getProperArrowAnimation = (status: string, itemCount: number) => {
121             return isSidePanelIconNotNeeded(status, itemCount) ? <span /> : <SidePanelRightArrowIcon style={{ fontSize: '14px' }} />;
122         };
123
124         const handleCheckboxChange = (item: VirtualTreeItem<T>) => {
125             const { toggleItemSelection } = treeProps;
126             return toggleItemSelection
127                 ? (event: React.MouseEvent<HTMLElement>) => {
128                     event.stopPropagation();
129                     toggleItemSelection(event, item);
130                 }
131                 : undefined;
132         };
133
134         return <div style={style}>
135             <ListItem button className={listItem}
136                 style={{
137                     paddingLeft: (level + 1) * levelIndentation,
138                     paddingRight: itemRightPadding,
139                 }}
140                 disableRipple={disableRipple}
141                 onClick={event => toggleItemActive(event, it)}
142                 selected={showSelection(it) && it.id === currentItemUuid}
143                 onContextMenu={handleRowContextMenu(it)}>
144                 {it.status === TreeItemStatus.PENDING ?
145                     <CircularProgress size={10} className={loader} /> : null}
146                 <i onClick={handleToggleItemOpen(it)}
147                     className={toggableIconContainer}>
148                     <ListItemIcon className={getToggableIconClassNames(it.open, it.active)}>
149                         {getProperArrowAnimation(it.status, it.itemCount!)}
150                     </ListItemIcon>
151                 </i>
152                 {showSelection(it) && !useRadioButtons &&
153                     <Checkbox
154                         checked={it.selected}
155                         className={classes.checkbox}
156                         color="primary"
157                         onClick={handleCheckboxChange(it)} />}
158                 {showSelection(it) && useRadioButtons &&
159                     <Radio
160                         checked={it.selected}
161                         className={classes.checkbox}
162                         color="primary" />}
163                 <div className={renderContainer}>
164                     {render(it, level)}
165                 </div>
166             </ListItem>
167         </div>;
168     });
169
170 const itemSize = 30;
171
172 export const VirtualList = <T, _>(height: number, width: number, items: VirtualTreeItem<T>[], render: any, treeProps: TreeProps<T>) =>
173     <FixedSizeList
174         height={height}
175         itemCount={items.length}
176         itemSize={itemSize}
177         width={width}
178     >
179         {Row(items, render, treeProps)}
180     </FixedSizeList>;
181
182 export const VirtualTree = (maxElements: number) => withStyles(styles)(
183     class Component<T> extends React.Component<TreeProps<T> & WithStyles<CssRules>, {}> {
184         render(): ReactElement<any> {
185             const { items, render } = this.props;
186
187             // Virtual list viewport's maximum height
188             const itemsQty = items && items.length || 0;
189             const viewportHeight = min([itemsQty, maxElements])! * itemSize;
190
191             return <div style={{height: viewportHeight}}><AutoSizer>
192                 {({ height, width }) => {
193                     return VirtualList(height, width, items || [], render, this.props);
194                 }}
195             </AutoSizer></div>;
196         }
197     }
198 );