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, 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';
18 type CssRules = 'list'
22 | 'toggableIconContainer'
32 const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
41 transform: 'translate(0px)',
44 toggableIconContainer: {
45 color: theme.palette.grey["700"],
56 transition: 'all 0.1s ease',
59 transition: 'all 0.1s ease',
60 transform: 'rotate(90deg)',
63 width: theme.spacing.unit * 3,
64 height: theme.spacing.unit * 3,
65 margin: `0 ${theme.spacing.unit}px`,
67 color: theme.palette.grey["500"],
76 backgroundColor: 'rgba(0, 0, 0, 0.08)',
82 color: 'rgba(0, 0, 0, 0.54)',
85 color: theme.palette.primary.main,
89 color: theme.palette.grey["600"],
94 export enum TreeItemStatus {
100 export interface TreeItem<T> {
106 initialState?: boolean;
107 indeterminate?: boolean;
109 status: TreeItemStatus;
110 items?: Array<TreeItem<T>>;
114 export interface TreeProps<T> {
115 disableRipple?: boolean;
116 currentItemUuid?: string;
117 items?: Array<TreeItem<T>>;
119 itemsMap?: Map<string, TreeItem<T>>;
120 onContextMenu: (event: React.MouseEvent<HTMLElement>, item: TreeItem<T>) => void;
121 render: (item: TreeItem<T>, level?: number) => ReactElement<{}>;
122 showSelection?: boolean | ((item: TreeItem<T>) => boolean);
123 levelIndentation?: number;
124 itemRightPadding?: number;
125 toggleItemActive: (event: React.MouseEvent<HTMLElement>, item: TreeItem<T>) => void;
126 toggleItemOpen: (event: React.MouseEvent<HTMLElement>, item: TreeItem<T>) => void;
127 toggleItemSelection?: (event: React.MouseEvent<HTMLElement>, item: TreeItem<T>) => void;
128 selectedRef?: (node: HTMLDivElement | null) => void;
131 * When set to true use radio buttons instead of checkboxes for item selection.
132 * This does not guarantee radio group behavior (i.e item mutual exclusivity).
133 * Any item selection logic must be done in the toggleItemActive callback prop.
135 useRadioButtons?: boolean;
138 const getActionAndId = (event: any, initAction: string | undefined = undefined) => {
139 const { nativeEvent: { target } } = event;
140 let currentTarget: HTMLElement = target as HTMLElement;
141 let action: string | undefined = initAction || currentTarget.dataset.action;
142 let id: string | undefined = currentTarget.dataset.id;
144 while (action === undefined || id === undefined) {
145 currentTarget = currentTarget.parentElement as HTMLElement;
147 if (!currentTarget) {
151 action = action || currentTarget.dataset.action;
152 id = id || currentTarget.dataset.id;
158 interface FlatTreeProps {
160 levelIndentation: number;
161 onContextMenu: Function;
162 handleToggleItemOpen: Function;
163 toggleItemActive: Function;
164 getToggableIconClassNames: Function;
165 getProperArrowAnimation: Function;
166 itemsMap?: Map<string, TreeItem<any>>;
169 useRadioButtons?: boolean;
170 handleCheckboxChange: Function;
171 selectedRef?: (node: HTMLDivElement | null) => void;
174 const FLAT_TREE_ACTIONS = {
175 toggleOpen: 'TOGGLE_OPEN',
176 contextMenu: 'CONTEXT_MENU',
177 toggleActive: 'TOGGLE_ACTIVE',
180 const ItemIcon = React.memo(({ type, kind, active, groupClass, classes }: any) => {
181 let Icon = ProjectIcon;
183 if (groupClass === GroupClass.FILTER) {
184 Icon = FilterGroupIcon;
190 Icon = DirectoryIcon;
202 case ResourceKind.COLLECTION:
203 Icon = CollectionIcon;
210 return <Icon className={classnames({ [classes.active]: active }, classes.childItemIcon)} />;
213 const FlatTree = (props: FlatTreeProps) =>
215 onContextMenu={(event) => {
216 const id = getActionAndId(event, FLAT_TREE_ACTIONS.contextMenu)[1];
217 props.onContextMenu(event, { id } as any);
219 onClick={(event) => {
220 const [action, id] = getActionAndId(event);
223 const item = props.itemsMap ? props.itemsMap[id] : { id };
226 case FLAT_TREE_ACTIONS.toggleOpen:
227 props.handleToggleItemOpen(item as any, event);
229 case FLAT_TREE_ACTIONS.toggleActive:
230 props.toggleItemActive(event, item as any);
239 (props.it.items || [])
240 .map((item: any) => <div key={item.id} data-id={item.id}
241 className={classnames(props.classes.childItem, { [props.classes.active]: item.active })}
242 style={{ paddingLeft: `${item.depth * props.levelIndentation}px` }}>
243 <i data-action={FLAT_TREE_ACTIONS.toggleOpen} className={props.classes.toggableIconContainer}>
244 <ListItemIcon className={props.getToggableIconClassNames(item.open, item.active)}>
245 {props.getProperArrowAnimation(item.status, item.items!)}
248 {props.showSelection(item) && !props.useRadioButtons &&
250 checked={item.selected}
251 className={props.classes.checkbox}
253 onClick={props.handleCheckboxChange(item)} />}
254 {props.showSelection(item) && props.useRadioButtons &&
256 checked={item.selected}
257 className={props.classes.checkbox}
259 <div data-action={FLAT_TREE_ACTIONS.toggleActive} className={props.classes.renderContainer} ref={item.active ? props.selectedRef : undefined}>
260 <span style={{ display: 'flex', alignItems: 'center' }}>
261 <ItemIcon type={item.data.type} active={item.active} kind={item.data.kind} groupClass={item.data.kind === ResourceKind.GROUP ? item.data.groupClass : ''} classes={props.classes} />
262 <span style={{ fontSize: '0.875rem' }}>
266 !!item.data.frozenByUuid ? <FreezeIcon className={props.classes.frozenIcon} /> : null
274 export const Tree = withStyles(styles)(
275 function<T>(props: TreeProps<T> & WithStyles<CssRules>) {
276 const level = props.level ? props.level : 0;
277 const { classes, render, items, toggleItemActive, toggleItemOpen, disableRipple, currentItemUuid, useRadioButtons, itemsMap } = props;
278 const { list, listItem, loader, toggableIconContainer, renderContainer } = classes;
279 const showSelection = typeof props.showSelection === 'function'
280 ? props.showSelection
281 : () => props.showSelection ? true : false;
283 const getProperArrowAnimation = (status: string, items: Array<TreeItem<T>>) => {
284 return isSidePanelIconNotNeeded(status, items) ? <span /> : <SidePanelRightArrowIcon style={{ fontSize: '14px' }} />;
287 const isSidePanelIconNotNeeded = (status: string, items: Array<TreeItem<T>>) => {
288 return status === TreeItemStatus.PENDING ||
289 (status === TreeItemStatus.LOADED && !items) ||
290 (status === TreeItemStatus.LOADED && items && items.length === 0);
293 const getToggableIconClassNames = (isOpen?: boolean, isActive?: boolean) => {
294 const { iconOpen, iconClose, active, toggableIcon } = props.classes;
295 return classnames(toggableIcon, {
297 [iconClose]: !isOpen,
302 const handleCheckboxChange = (item: TreeItem<T>) => {
303 const { toggleItemSelection } = props;
304 return toggleItemSelection
305 ? (event: React.MouseEvent<HTMLElement>) => {
306 event.stopPropagation();
307 toggleItemSelection(event, item);
312 const handleToggleItemOpen = (item: TreeItem<T>, event: React.MouseEvent<HTMLElement>) => {
313 event.stopPropagation();
314 props.toggleItemOpen(event, item);
317 // Scroll to selected item whenever it changes, accepts selectedRef from props for recursive trees
318 const [cachedSelectedRef, setCachedRef] = useState<HTMLDivElement | null>(null)
319 const selectedRef = props.selectedRef || useCallback((node: HTMLDivElement | null) => {
320 if (node && node.scrollIntoView && node !== cachedSelectedRef) {
321 node.scrollIntoView({ behavior: "smooth", block: "center" });
324 }, [cachedSelectedRef]);
326 const { levelIndentation = 20, itemRightPadding = 20 } = props;
327 return <List className={list}>
328 {items && items.map((it: TreeItem<T>, idx: number) => {
329 return <div key={`item/${level}/${it.id}`}>
330 <ListItem button className={listItem}
332 paddingLeft: (level + 1) * levelIndentation,
333 paddingRight: itemRightPadding,
335 disableRipple={disableRipple}
336 onClick={event => toggleItemActive(event, it)}
337 selected={showSelection(it) && it.id === currentItemUuid}
338 onContextMenu={(event) => props.onContextMenu(event, it)}>
339 {it.status === TreeItemStatus.PENDING ?
340 <CircularProgress size={10} className={loader} /> : null}
341 <i onClick={(e) => handleToggleItemOpen(it, e)}
342 className={toggableIconContainer}>
343 <ListItemIcon className={getToggableIconClassNames(it.open, it.active)}>
344 {getProperArrowAnimation(it.status, it.items!)}
347 {showSelection(it) && !useRadioButtons &&
349 checked={it.selected}
350 indeterminate={!it.selected && it.indeterminate}
351 className={classes.checkbox}
353 onClick={handleCheckboxChange(it)} />}
354 {showSelection(it) && useRadioButtons &&
356 checked={it.selected}
357 className={classes.checkbox}
359 <div className={renderContainer} ref={!!it.active ? selectedRef : undefined}>
364 it.open && it.items && it.items.length > 0 &&
369 showSelection={showSelection}
370 classes={props.classes}
371 useRadioButtons={useRadioButtons}
372 levelIndentation={levelIndentation}
373 handleCheckboxChange={handleCheckboxChange}
374 onContextMenu={props.onContextMenu}
375 handleToggleItemOpen={handleToggleItemOpen}
376 toggleItemActive={props.toggleItemActive}
377 getToggableIconClassNames={getToggableIconClassNames}
378 getProperArrowAnimation={getProperArrowAnimation}
379 selectedRef={selectedRef}
381 <Collapse in={it.open} timeout="auto" unmountOnExit>
383 showSelection={props.showSelection}
386 disableRipple={disableRipple}
387 toggleItemOpen={toggleItemOpen}
388 toggleItemActive={toggleItemActive}
390 onContextMenu={props.onContextMenu}
391 toggleItemSelection={props.toggleItemSelection}
392 selectedRef={selectedRef}