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