1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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";
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';
20 type CssRules = 'list'
24 | 'toggableIconContainer'
35 const styles: CustomStyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
44 transform: 'translate(0px)',
47 toggableIconContainer: {
48 color: theme.palette.grey["700"],
51 marginBottom: '0.4rem',
61 transition: 'all 0.1s ease',
64 transition: 'all 0.1s ease',
65 transform: 'rotate(90deg)',
68 width: theme.spacing(3),
69 height: theme.spacing(3),
70 margin: `0 ${theme.spacing(1)}px`,
72 color: theme.palette.grey["500"],
81 backgroundColor: 'rgba(0, 0, 0, 0.08)',
87 color: 'rgba(0, 0, 0, 0.54)',
90 color: theme.palette.primary.main,
94 color: theme.palette.grey["600"],
102 export enum TreeItemStatus {
108 export interface TreeItem<T> {
115 initialState?: boolean;
116 indeterminate?: boolean;
118 status: TreeItemStatus;
119 items?: Array<TreeItem<T>>;
123 export interface TreeProps<T> {
124 disableRipple?: boolean;
125 currentItemUuid?: string;
126 items?: Array<TreeItem<T>>;
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;
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.
144 useRadioButtons?: boolean;
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;
153 while (action === undefined || id === undefined) {
154 currentTarget = currentTarget.parentElement as HTMLElement;
156 if (!currentTarget) {
160 action = action || currentTarget.dataset.action;
161 id = id || currentTarget.dataset.id;
167 const isInFavoritesTree = (item: TreeItem<any>): boolean => {
168 return item.id === SidePanelTreeCategory.FAVORITES || item.id === SidePanelTreeCategory.PUBLIC_FAVORITES;
171 interface FlatTreeProps {
173 levelIndentation: number;
174 onContextMenu: Function;
175 handleToggleItemOpen: Function;
176 toggleItemActive: Function;
177 getToggableIconClassNames: Function;
178 getProperArrowAnimation: Function;
179 itemsMap?: Map<string, TreeItem<any>>;
182 useRadioButtons?: boolean;
183 handleCheckboxChange: Function;
184 selectedRef?: (node: HTMLDivElement | null) => void;
187 const FLAT_TREE_ACTIONS = {
188 toggleOpen: 'TOGGLE_OPEN',
189 contextMenu: 'CONTEXT_MENU',
190 toggleActive: 'TOGGLE_ACTIVE',
193 const ItemIcon = React.memo(({ type, kind, headKind, active, groupClass, classes }: any) => {
194 let Icon = ProjectIcon;
196 if (groupClass === GroupClass.FILTER) {
197 Icon = FilterGroupIcon;
203 Icon = DirectoryIcon;
214 if(kind === ResourceKind.LINK && headKind) kind = headKind;
216 case ResourceKind.COLLECTION:
217 Icon = CollectionIcon;
219 case ResourceKind.CONTAINER_REQUEST:
227 return <Icon className={classnames({ [classes.active]: active }, classes.childItemIcon)} />;
230 const FlatTree = (props: FlatTreeProps) =>
232 onContextMenu={(event) => {
233 const id = getActionAndId(event, FLAT_TREE_ACTIONS.contextMenu)[1];
234 props.onContextMenu(event, { id } as any);
236 onClick={(event) => {
237 const [action, id] = getActionAndId(event);
240 const item = props.itemsMap ? props.itemsMap[id] : { id };
243 case FLAT_TREE_ACTIONS.toggleOpen:
244 props.handleToggleItemOpen(item as any, event);
246 case FLAT_TREE_ACTIONS.toggleActive:
247 props.toggleItemActive(event, item as any);
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} />
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!)}
268 {props.showSelection(item) && !props.useRadioButtons &&
270 checked={item.selected}
271 className={props.classes.checkbox}
273 onClick={props.handleCheckboxChange(item)} />}
274 {props.showSelection(item) && props.useRadioButtons &&
276 checked={item.selected}
277 className={props.classes.checkbox}
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' }}>
286 !!item.data.frozenByUuid ? <FreezeIcon className={props.classes.frozenIcon} /> : null
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;
303 const getProperArrowAnimation = (status: string, items: Array<TreeItem<T>>) => {
304 return isSidePanelIconNotNeeded(status, items) ? <span /> : <SidePanelRightArrowIcon style={{ fontSize: '14px' }} />;
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);
313 const getToggableIconClassNames = (isOpen?: boolean, isActive?: boolean) => {
314 const { iconOpen, iconClose, active, toggableIcon } = props.classes;
315 return classnames(toggableIcon, {
317 [iconClose]: !isOpen,
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);
332 const handleToggleItemOpen = (item: TreeItem<T>, event: React.MouseEvent<HTMLElement>) => {
333 event.stopPropagation();
334 props.toggleItemOpen(event, item);
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" });
344 }, [cachedSelectedRef]);
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) }
352 return <div key={`item/${level}/${it.id}`}>
353 <ListItem button className={listItem}
355 paddingLeft: (level + 1) * levelIndentation,
356 paddingRight: itemRightPadding,
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!)}
370 {showSelection(it) && !useRadioButtons &&
372 checked={it.selected}
373 indeterminate={!it.selected && it.indeterminate}
374 className={classes.checkbox}
376 onClick={handleCheckboxChange(it)} />}
377 {showSelection(it) && useRadioButtons &&
379 checked={it.selected}
380 className={classes.checkbox}
382 <div className={renderContainer} ref={!!it.active ? selectedRef : undefined}>
387 it.open && it.items && it.items.length > 0 &&
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}
404 <Collapse in={it.open} timeout="auto" unmountOnExit>
406 showSelection={props.showSelection}
409 disableRipple={disableRipple}
410 toggleItemOpen={toggleItemOpen}
411 toggleItemActive={toggleItemActive}
413 onContextMenu={props.onContextMenu}
414 toggleItemSelection={props.toggleItemSelection}
415 selectedRef={selectedRef}