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 { 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";
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';
19 type CssRules = 'list'
23 | 'toggableIconContainer'
34 const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
43 transform: 'translate(0px)',
46 toggableIconContainer: {
47 color: theme.palette.grey["700"],
50 marginBottom: '0.4rem',
59 transition: 'all 0.1s ease',
62 transition: 'all 0.1s ease',
63 transform: 'rotate(90deg)',
66 width: theme.spacing.unit * 3,
67 height: theme.spacing.unit * 3,
68 margin: `0 ${theme.spacing.unit}px`,
70 color: theme.palette.grey["500"],
79 backgroundColor: 'rgba(0, 0, 0, 0.08)',
85 color: 'rgba(0, 0, 0, 0.54)',
88 color: theme.palette.primary.main,
92 color: theme.palette.grey["600"],
100 export enum TreeItemStatus {
106 export interface TreeItem<T> {
113 initialState?: boolean;
114 indeterminate?: boolean;
116 status: TreeItemStatus;
117 items?: Array<TreeItem<T>>;
121 export interface TreeProps<T> {
122 disableRipple?: boolean;
123 currentItemUuid?: string;
124 items?: Array<TreeItem<T>>;
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;
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.
142 useRadioButtons?: boolean;
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;
151 while (action === undefined || id === undefined) {
152 currentTarget = currentTarget.parentElement as HTMLElement;
154 if (!currentTarget) {
158 action = action || currentTarget.dataset.action;
159 id = id || currentTarget.dataset.id;
165 const isInFavoritesTree = (item: TreeItem<any>): boolean => {
166 return item.id === SidePanelTreeCategory.FAVORITES || item.id === SidePanelTreeCategory.PUBLIC_FAVORITES;
169 interface FlatTreeProps {
171 levelIndentation: number;
172 onContextMenu: Function;
173 handleToggleItemOpen: Function;
174 toggleItemActive: Function;
175 getToggableIconClassNames: Function;
176 getProperArrowAnimation: Function;
177 itemsMap?: Map<string, TreeItem<any>>;
180 useRadioButtons?: boolean;
181 handleCheckboxChange: Function;
182 selectedRef?: (node: HTMLDivElement | null) => void;
185 const FLAT_TREE_ACTIONS = {
186 toggleOpen: 'TOGGLE_OPEN',
187 contextMenu: 'CONTEXT_MENU',
188 toggleActive: 'TOGGLE_ACTIVE',
191 const ItemIcon = React.memo(({ type, kind, headKind, active, groupClass, classes }: any) => {
192 let Icon = ProjectIcon;
194 if (groupClass === GroupClass.FILTER) {
195 Icon = FilterGroupIcon;
201 Icon = DirectoryIcon;
212 if(kind === ResourceKind.LINK && headKind) kind = headKind;
214 case ResourceKind.COLLECTION:
215 Icon = CollectionIcon;
217 case ResourceKind.CONTAINER_REQUEST:
225 return <Icon className={classnames({ [classes.active]: active }, classes.childItemIcon)} />;
228 const FlatTree = (props: FlatTreeProps) =>
230 onContextMenu={(event) => {
231 const id = getActionAndId(event, FLAT_TREE_ACTIONS.contextMenu)[1];
232 props.onContextMenu(event, { id } as any);
234 onClick={(event) => {
235 const [action, id] = getActionAndId(event);
238 const item = props.itemsMap ? props.itemsMap[id] : { id };
241 case FLAT_TREE_ACTIONS.toggleOpen:
242 props.handleToggleItemOpen(item as any, event);
244 case FLAT_TREE_ACTIONS.toggleActive:
245 props.toggleItemActive(event, item as any);
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} />
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!)}
266 {props.showSelection(item) && !props.useRadioButtons &&
268 checked={item.selected}
269 className={props.classes.checkbox}
271 onClick={props.handleCheckboxChange(item)} />}
272 {props.showSelection(item) && props.useRadioButtons &&
274 checked={item.selected}
275 className={props.classes.checkbox}
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' }}>
284 !!item.data.frozenByUuid ? <FreezeIcon className={props.classes.frozenIcon} /> : null
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;
301 const getProperArrowAnimation = (status: string, items: Array<TreeItem<T>>) => {
302 return isSidePanelIconNotNeeded(status, items) ? <span /> : <SidePanelRightArrowIcon style={{ fontSize: '14px' }} />;
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);
311 const getToggableIconClassNames = (isOpen?: boolean, isActive?: boolean) => {
312 const { iconOpen, iconClose, active, toggableIcon } = props.classes;
313 return classnames(toggableIcon, {
315 [iconClose]: !isOpen,
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);
330 const handleToggleItemOpen = (item: TreeItem<T>, event: React.MouseEvent<HTMLElement>) => {
331 event.stopPropagation();
332 props.toggleItemOpen(event, item);
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" });
342 }, [cachedSelectedRef]);
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) }
350 return <div key={`item/${level}/${it.id}`}>
351 <ListItem button className={listItem}
353 paddingLeft: (level + 1) * levelIndentation,
354 paddingRight: itemRightPadding,
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!)}
368 {showSelection(it) && !useRadioButtons &&
370 checked={it.selected}
371 indeterminate={!it.selected && it.indeterminate}
372 className={classes.checkbox}
374 onClick={handleCheckboxChange(it)} />}
375 {showSelection(it) && useRadioButtons &&
377 checked={it.selected}
378 className={classes.checkbox}
380 <div className={renderContainer} ref={!!it.active ? selectedRef : undefined}>
385 it.open && it.items && it.items.length > 0 &&
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}
402 <Collapse in={it.open} timeout="auto" unmountOnExit>
404 showSelection={props.showSelection}
407 disableRipple={disableRipple}
408 toggleItemOpen={toggleItemOpen}
409 toggleItemActive={toggleItemActive}
411 onContextMenu={props.onContextMenu}
412 toggleItemSelection={props.toggleItemSelection}
413 selectedRef={selectedRef}