Merge branch '21128-toolbar-context-menu'
[arvados-workbench2.git] / src / components / tree / tree.tsx
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import React, { useCallback, useState } from 'react';
6 import { List, ListItem, ListItemIcon, Checkbox, Radio, Collapse } from "@material-ui/core";
7 import { StyleRulesCallback, withStyles, WithStyles } from '@material-ui/core/styles';
8 import { CollectionIcon, DefaultIcon, DirectoryIcon, FileIcon, ProjectIcon, ProcessIcon, FilterGroupIcon, FreezeIcon } from 'components/icon/icon';
9 import { ReactElement } from "react";
10 import CircularProgress from '@material-ui/core/CircularProgress';
11 import classnames from "classnames";
12
13 import { ArvadosTheme } from 'common/custom-theme';
14 import { SidePanelRightArrowIcon } from '../icon/icon';
15 import { ResourceKind } from 'models/resource';
16 import { GroupClass } from 'models/group';
17 import { SidePanelTreeCategory } from 'store/side-panel-tree/side-panel-tree-actions';
18
19 type CssRules = 'list'
20     | 'listItem'
21     | 'active'
22     | 'loader'
23     | 'toggableIconContainer'
24     | 'iconClose'
25     | 'renderContainer'
26     | 'iconOpen'
27     | 'toggableIcon'
28     | 'checkbox'
29     | 'childItem'
30     | 'childItemIcon'
31     | 'frozenIcon'
32     | 'indentSpacer';
33
34 const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
35     list: {
36         padding: '3px 0px'
37     },
38     listItem: {
39         padding: '3px 0px',
40     },
41     loader: {
42         position: 'absolute',
43         transform: 'translate(0px)',
44         top: '3px'
45     },
46     toggableIconContainer: {
47         color: theme.palette.grey["700"],
48         height: '14px',
49         width: '14px',
50         marginBottom: '0.4rem',
51     },
52     toggableIcon: {
53         fontSize: '14px',
54     },
55     renderContainer: {
56         flex: 1
57     },
58     iconClose: {
59         transition: 'all 0.1s ease',
60     },
61     iconOpen: {
62         transition: 'all 0.1s ease',
63         transform: 'rotate(90deg)',
64     },
65     checkbox: {
66         width: theme.spacing.unit * 3,
67         height: theme.spacing.unit * 3,
68         margin: `0 ${theme.spacing.unit}px`,
69         padding: 0,
70         color: theme.palette.grey["500"],
71     },
72     childItem: {
73         cursor: 'pointer',
74         display: 'flex',
75         padding: '3px 20px',
76         fontSize: '0.875rem',
77         alignItems: 'center',
78         '&:hover': {
79             backgroundColor: 'rgba(0, 0, 0, 0.08)',
80         }
81     },
82     childItemIcon: {
83         marginLeft: '8px',
84         marginRight: '16px',
85         color: 'rgba(0, 0, 0, 0.54)',
86     },
87     active: {
88         color: theme.palette.primary.main,
89     },
90     frozenIcon: {
91         fontSize: 20,
92         color: theme.palette.grey["600"],
93         marginLeft: '10px',
94     },
95     indentSpacer: {
96         width: '0.25rem'
97     }
98 });
99
100 export enum TreeItemStatus {
101     INITIAL = 'initial',
102     PENDING = 'pending',
103     LOADED = 'loaded'
104 }
105
106 export interface TreeItem<T> {
107     data: T;
108     depth?: number;
109     id: string;
110     open: boolean;
111     active: boolean;
112     selected?: boolean;
113     initialState?: boolean;
114     indeterminate?: boolean;
115     flatTree?: boolean;
116     status: TreeItemStatus;
117     items?: Array<TreeItem<T>>;
118     isFrozen?: boolean;
119 }
120
121 export interface TreeProps<T> {
122     disableRipple?: boolean;
123     currentItemUuid?: string;
124     items?: Array<TreeItem<T>>;
125     level?: number;
126     itemsMap?: Map<string, TreeItem<T>>;
127     onContextMenu: (event: React.MouseEvent<HTMLElement>, item: TreeItem<T>) => void;
128     render: (item: TreeItem<T>, level?: number) => ReactElement<{}>;
129     showSelection?: boolean | ((item: TreeItem<T>) => boolean);
130     levelIndentation?: number;
131     itemRightPadding?: number;
132     toggleItemActive: (event: React.MouseEvent<HTMLElement>, item: TreeItem<T>) => void;
133     toggleItemOpen: (event: React.MouseEvent<HTMLElement>, item: TreeItem<T>) => void;
134     toggleItemSelection?: (event: React.MouseEvent<HTMLElement>, item: TreeItem<T>) => void;
135     selectedRef?: (node: HTMLDivElement | null) => void;
136
137     /**
138      * When set to true use radio buttons instead of checkboxes for item selection.
139      * This does not guarantee radio group behavior (i.e item mutual exclusivity).
140      * Any item selection logic must be done in the toggleItemActive callback prop.
141      */
142     useRadioButtons?: boolean;
143 }
144
145 const getActionAndId = (event: any, initAction: string | undefined = undefined) => {
146     const { nativeEvent: { target } } = event;
147     let currentTarget: HTMLElement = target as HTMLElement;
148     let action: string | undefined = initAction || currentTarget.dataset.action;
149     let id: string | undefined = currentTarget.dataset.id;
150
151     while (action === undefined || id === undefined) {
152         currentTarget = currentTarget.parentElement as HTMLElement;
153
154         if (!currentTarget) {
155             break;
156         }
157
158         action = action || currentTarget.dataset.action;
159         id = id || currentTarget.dataset.id;
160     }
161
162     return [action, id];
163 };
164
165 const isInFavoritesTree = (item: TreeItem<any>): boolean => {
166     return item.id === SidePanelTreeCategory.FAVORITES || item.id === SidePanelTreeCategory.PUBLIC_FAVORITES;
167 }
168
169 interface FlatTreeProps {
170     it: TreeItem<any>;
171     levelIndentation: number;
172     onContextMenu: Function;
173     handleToggleItemOpen: Function;
174     toggleItemActive: Function;
175     getToggableIconClassNames: Function;
176     getProperArrowAnimation: Function;
177     itemsMap?: Map<string, TreeItem<any>>;
178     classes: any;
179     showSelection: any;
180     useRadioButtons?: boolean;
181     handleCheckboxChange: Function;
182     selectedRef?: (node: HTMLDivElement | null) => void;
183 }
184
185 const FLAT_TREE_ACTIONS = {
186     toggleOpen: 'TOGGLE_OPEN',
187     contextMenu: 'CONTEXT_MENU',
188     toggleActive: 'TOGGLE_ACTIVE',
189 };
190
191 const ItemIcon = React.memo(({ type, kind, headKind, active, groupClass, classes }: any) => {
192     let Icon = ProjectIcon;
193
194     if (groupClass === GroupClass.FILTER) {
195         Icon = FilterGroupIcon;
196     }
197
198     if (type) {
199         switch (type) {
200             case 'directory':
201                 Icon = DirectoryIcon;
202                 break;
203             case 'file':
204                 Icon = FileIcon;
205                 break;
206             default:
207                 Icon = DefaultIcon;
208         }
209     }
210
211     if (kind) {
212         if(kind === ResourceKind.LINK && headKind) kind = headKind;
213         switch (kind) {
214             case ResourceKind.COLLECTION:
215                 Icon = CollectionIcon;
216                 break;
217             case ResourceKind.CONTAINER_REQUEST:
218                 Icon = ProcessIcon;
219                 break;
220             default:
221                 break;
222         }
223     }
224
225     return <Icon className={classnames({ [classes.active]: active }, classes.childItemIcon)} />;
226 });
227
228 const FlatTree = (props: FlatTreeProps) =>
229     <div
230         onContextMenu={(event) => {
231             const id = getActionAndId(event, FLAT_TREE_ACTIONS.contextMenu)[1];
232             props.onContextMenu(event, { id } as any);
233         }}
234         onClick={(event) => {
235             const [action, id] = getActionAndId(event);
236
237             if (action && id) {
238                 const item = props.itemsMap ? props.itemsMap[id] : { id };
239
240                 switch (action) {
241                     case FLAT_TREE_ACTIONS.toggleOpen:
242                         props.handleToggleItemOpen(item as any, event);
243                         break;
244                     case FLAT_TREE_ACTIONS.toggleActive:
245                         props.toggleItemActive(event, item as any);
246                         break;
247                     default:
248                         break;
249                 }
250             }
251         }}
252     >
253         {
254             (props.it.items || [])
255                 .map((item: any) => <div key={item.id} data-id={item.id}
256                     className={classnames(props.classes.childItem, { [props.classes.active]: item.active })}
257                     style={{ paddingLeft: `${item.depth * props.levelIndentation}px` }}>
258                     {isInFavoritesTree(props.it) ? 
259                         <div className={props.classes.indentSpacer} />
260                         :
261                         <i data-action={FLAT_TREE_ACTIONS.toggleOpen} className={props.classes.toggableIconContainer}>
262                             <ListItemIcon className={props.getToggableIconClassNames(item.open, item.active)}>
263                                 {props.getProperArrowAnimation(item.status, item.items!)}
264                             </ListItemIcon> 
265                         </i>}
266                     {props.showSelection(item) && !props.useRadioButtons &&
267                         <Checkbox
268                             checked={item.selected}
269                             className={props.classes.checkbox}
270                             color="primary"
271                             onClick={props.handleCheckboxChange(item)} />}
272                     {props.showSelection(item) && props.useRadioButtons &&
273                         <Radio
274                             checked={item.selected}
275                             className={props.classes.checkbox}
276                             color="primary" />}
277                     <div data-action={FLAT_TREE_ACTIONS.toggleActive} className={props.classes.renderContainer} ref={item.active ? props.selectedRef : undefined}>
278                         <span style={{ display: 'flex', alignItems: 'center' }}>
279                             <ItemIcon type={item.data.type} active={item.active} kind={item.data.kind} headKind={item.data.headKind || null} groupClass={item.data.kind === ResourceKind.GROUP ? item.data.groupClass : ''} classes={props.classes} />
280                             <span style={{ fontSize: '0.875rem' }}>
281                                 {item.data.name}
282                             </span>
283                             {
284                                 !!item.data.frozenByUuid ? <FreezeIcon className={props.classes.frozenIcon} /> : null
285                             }
286                         </span>
287                     </div>
288                 </div>)
289         }
290     </div>;
291
292 export const Tree = withStyles(styles)(
293     function<T>(props: TreeProps<T> & WithStyles<CssRules>) {
294         const level = props.level ? props.level : 0;
295         const { classes, render, items, toggleItemActive, toggleItemOpen, disableRipple, currentItemUuid, useRadioButtons, itemsMap } = props;
296         const { list, listItem, loader, toggableIconContainer, renderContainer } = classes;
297         const showSelection = typeof props.showSelection === 'function'
298             ? props.showSelection
299             : () => props.showSelection ? true : false;
300
301         const getProperArrowAnimation = (status: string, items: Array<TreeItem<T>>) => {
302             return isSidePanelIconNotNeeded(status, items) ? <span /> : <SidePanelRightArrowIcon style={{ fontSize: '14px' }} />;
303         }
304
305         const isSidePanelIconNotNeeded = (status: string, items: Array<TreeItem<T>>) => {
306             return status === TreeItemStatus.PENDING ||
307                 (status === TreeItemStatus.LOADED && !items) ||
308                 (status === TreeItemStatus.LOADED && items && items.length === 0);
309         }
310
311         const getToggableIconClassNames = (isOpen?: boolean, isActive?: boolean) => {
312             const { iconOpen, iconClose, active, toggableIcon } = props.classes;
313             return classnames(toggableIcon, {
314                 [iconOpen]: isOpen,
315                 [iconClose]: !isOpen,
316                 [active]: isActive
317             });
318         }
319
320         const handleCheckboxChange = (item: TreeItem<T>) => {
321             const { toggleItemSelection } = props;
322             return toggleItemSelection
323                 ? (event: React.MouseEvent<HTMLElement>) => {
324                     event.stopPropagation();
325                     toggleItemSelection(event, item);
326                 }
327                 : undefined;
328         }
329
330         const handleToggleItemOpen = (item: TreeItem<T>, event: React.MouseEvent<HTMLElement>) => {
331             event.stopPropagation();
332             props.toggleItemOpen(event, item);
333         }
334
335         // Scroll to selected item whenever it changes, accepts selectedRef from props for recursive trees
336         const [cachedSelectedRef, setCachedRef] = useState<HTMLDivElement | null>(null)
337         const selectedRef = props.selectedRef || useCallback((node: HTMLDivElement | null) => {
338             if (node && node.scrollIntoView && node !== cachedSelectedRef) {
339                 node.scrollIntoView({ behavior: "smooth", block: "center" });
340             }
341             setCachedRef(node);
342         }, [cachedSelectedRef]);
343
344         const { levelIndentation = 20, itemRightPadding = 20 } = props;
345         return <List className={list}>
346             {items && items.map((it: TreeItem<T>, idx: number) => {
347                 if (isInFavoritesTree(it) && it.open === true && it.items && it.items.length) {
348                     it = { ...it, items: it.items.filter(item => item.depth && item.depth < 3) }
349                 }
350                 return <div key={`item/${level}/${it.id}`}>
351                     <ListItem button className={listItem}
352                         style={{
353                             paddingLeft: (level + 1) * levelIndentation,
354                             paddingRight: itemRightPadding,
355                         }}
356                         disableRipple={disableRipple}
357                         onClick={event => toggleItemActive(event, it)}
358                         selected={showSelection(it) && it.id === currentItemUuid}
359                         onContextMenu={(event) => props.onContextMenu(event, it)}>
360                         {it.status === TreeItemStatus.PENDING ?
361                             <CircularProgress size={10} className={loader} /> : null}
362                         <i onClick={(e) => handleToggleItemOpen(it, e)}
363                             className={toggableIconContainer}>
364                             <ListItemIcon className={getToggableIconClassNames(it.open, it.active)}>
365                                 {getProperArrowAnimation(it.status, it.items!)}
366                             </ListItemIcon>
367                         </i>
368                         {showSelection(it) && !useRadioButtons &&
369                             <Checkbox
370                                 checked={it.selected}
371                                 indeterminate={!it.selected && it.indeterminate}
372                                 className={classes.checkbox}
373                                 color="primary"
374                                 onClick={handleCheckboxChange(it)} />}
375                         {showSelection(it) && useRadioButtons &&
376                             <Radio
377                                 checked={it.selected}
378                                 className={classes.checkbox}
379                                 color="primary" />}
380                         <div className={renderContainer} ref={!!it.active ? selectedRef : undefined}>
381                             {render(it, level)}
382                         </div>
383                     </ListItem>
384                     {
385                         it.open && it.items && it.items.length > 0 &&
386                             it.flatTree ?
387                             <FlatTree
388                                 it={it}
389                                 itemsMap={itemsMap}
390                                 showSelection={showSelection}
391                                 classes={props.classes}
392                                 useRadioButtons={useRadioButtons}
393                                 levelIndentation={levelIndentation}
394                                 handleCheckboxChange={handleCheckboxChange}
395                                 onContextMenu={props.onContextMenu}
396                                 handleToggleItemOpen={handleToggleItemOpen}
397                                 toggleItemActive={props.toggleItemActive}
398                                 getToggableIconClassNames={getToggableIconClassNames}
399                                 getProperArrowAnimation={getProperArrowAnimation}
400                                 selectedRef={selectedRef}
401                             /> :
402                             <Collapse in={it.open} timeout="auto" unmountOnExit>
403                                 <Tree
404                                     showSelection={props.showSelection}
405                                     items={it.items}
406                                     render={render}
407                                     disableRipple={disableRipple}
408                                     toggleItemOpen={toggleItemOpen}
409                                     toggleItemActive={toggleItemActive}
410                                     level={level + 1}
411                                     onContextMenu={props.onContextMenu}
412                                     toggleItemSelection={props.toggleItemSelection}
413                                     selectedRef={selectedRef}
414                                 />
415                             </Collapse>
416                     }
417                 </div>;
418             })}
419         </List>;
420     }
421 );