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 "@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";
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';
21 type CssRules = 'list'
25 | 'toggableIconContainer'
36 const styles: CustomStyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
45 transform: 'translate(0px)',
48 toggableIconContainer: {
49 color: theme.palette.grey["700"],
52 marginBottom: '0.4rem',
62 transition: 'all 0.1s ease',
65 transition: 'all 0.1s ease',
66 transform: 'rotate(90deg)',
69 width: theme.spacing(3),
70 height: theme.spacing(3),
71 margin: `0 ${theme.spacing(1)}`,
73 color: theme.palette.grey["500"],
82 backgroundColor: 'rgba(0, 0, 0, 0.08)',
88 color: 'rgba(0, 0, 0, 0.54)',
91 color: theme.palette.primary.main,
95 color: theme.palette.grey["600"],
103 export enum TreeItemStatus {
109 export interface TreeItem<T> {
116 initialState?: boolean;
117 indeterminate?: boolean;
119 status: TreeItemStatus;
120 items?: Array<TreeItem<T>>;
124 export interface TreeProps<T> {
125 disableRipple?: boolean;
126 currentItemUuid?: string;
127 items?: Array<TreeItem<T>>;
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;
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.
145 useRadioButtons?: boolean;
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;
154 while (action === undefined || id === undefined) {
155 currentTarget = currentTarget.parentElement as HTMLElement;
157 if (!currentTarget) {
161 action = action || currentTarget.dataset.action;
162 id = id || currentTarget.dataset.id;
168 const isInFavoritesTree = (item: TreeItem<any>): boolean => {
169 return item.id === SidePanelTreeCategory.FAVORITES || item.id === SidePanelTreeCategory.PUBLIC_FAVORITES;
172 interface FlatTreeProps {
174 levelIndentation: number;
175 onContextMenu: Function;
176 handleToggleItemOpen: Function;
177 toggleItemActive: Function;
178 getToggableIconClassNames: Function;
179 getProperArrowAnimation: Function;
180 itemsMap?: Map<string, TreeItem<any>>;
183 useRadioButtons?: boolean;
184 handleCheckboxChange: Function;
185 selectedRef?: (node: HTMLDivElement | null) => void;
188 const FLAT_TREE_ACTIONS = {
189 toggleOpen: 'TOGGLE_OPEN',
190 contextMenu: 'CONTEXT_MENU',
191 toggleActive: 'TOGGLE_ACTIVE',
194 const ItemIcon = React.memo(({ type, kind, headKind, active, groupClass, classes }: any) => {
195 let Icon = ProjectIcon;
197 if (groupClass === GroupClass.FILTER) {
198 Icon = FilterGroupIcon;
204 Icon = DirectoryIcon;
215 if(kind === ResourceKind.LINK && headKind) kind = headKind;
217 case ResourceKind.COLLECTION:
218 Icon = CollectionIcon;
220 case ResourceKind.CONTAINER_REQUEST:
228 return <Icon className={classnames({ [classes.active]: active }, classes.childItemIcon)} />;
231 const FlatTree = (props: FlatTreeProps) =>
233 onContextMenu={(event) => {
234 const id = getActionAndId(event, FLAT_TREE_ACTIONS.contextMenu)[1];
235 props.onContextMenu(event, { id } as any);
237 onClick={(event) => {
238 const [action, id] = getActionAndId(event);
241 const item = props.itemsMap ? props.itemsMap[id] : { id };
244 case FLAT_TREE_ACTIONS.toggleOpen:
245 props.handleToggleItemOpen(item as any, event);
247 case FLAT_TREE_ACTIONS.toggleActive:
248 props.toggleItemActive(event, item as any);
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} />
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!)}
269 {props.showSelection(item) && !props.useRadioButtons &&
271 checked={item.selected}
272 className={props.classes.checkbox}
274 onClick={props.handleCheckboxChange(item)} />}
275 {props.showSelection(item) && props.useRadioButtons &&
277 checked={item.selected}
278 className={props.classes.checkbox}
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' }}>
287 !!item.data.frozenByUuid ? <FreezeIcon className={props.classes.frozenIcon} /> : null
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;
304 const getProperArrowAnimation = (status: string, items: Array<TreeItem<T>>) => {
305 return isSidePanelIconNotNeeded(status, items) ? <span /> : <SidePanelRightArrowIcon style={{ fontSize: '14px' }} />;
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);
314 const getToggableIconClassNames = (isOpen?: boolean, isActive?: boolean) => {
315 const { iconOpen, iconClose, active, toggableIcon } = props.classes;
316 return classnames(toggableIcon, {
318 [iconClose]: !isOpen,
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);
333 const handleToggleItemOpen = (item: TreeItem<T>, event: React.MouseEvent<HTMLElement>) => {
334 event.stopPropagation();
335 props.toggleItemOpen(event, item);
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" });
345 }, [cachedSelectedRef]);
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) }
353 return <div key={`item/${level}/${it.id}`}>
354 <ListItem button className={listItem}
357 paddingLeft: (level + 1) * levelIndentation,
358 paddingRight: itemRightPadding,
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!)}
372 {showSelection(it) && !useRadioButtons &&
374 checked={it.selected}
375 indeterminate={!it.selected && it.indeterminate}
376 className={classes.checkbox}
378 onClick={handleCheckboxChange(it)} />}
379 {showSelection(it) && useRadioButtons &&
381 checked={it.selected}
382 className={classes.checkbox}
384 <div className={renderContainer} ref={!!it.active ? selectedRef : undefined}>
389 it.open && it.items && it.items.length > 0 &&
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}
406 <Collapse in={it.open} timeout="auto" unmountOnExit>
408 showSelection={props.showSelection}
411 disableRipple={disableRipple}
412 toggleItemOpen={toggleItemOpen}
413 toggleItemActive={toggleItemActive}
415 onContextMenu={props.onContextMenu}
416 toggleItemSelection={props.toggleItemSelection}
417 selectedRef={selectedRef}