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