1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import { connect } from "react-redux";
6 import { Tree, TreeProps, TreeItem, TreeItemStatus } from "~/components/tree/tree";
7 import { RootState } from "~/store/store";
8 import { getNodeChildrenIds, Tree as Ttree, createTree, getNode, TreeNodeStatus } from '~/models/tree';
9 import { Dispatch } from "redux";
10 import { initTreeNode } from '../../models/tree';
12 type Callback<T> = (event: React.MouseEvent<HTMLElement>, item: TreeItem<T>, pickerId: string) => void;
13 export interface TreePickerProps<T> {
15 onContextMenu: Callback<T>;
16 toggleItemOpen: Callback<T>;
17 toggleItemActive: Callback<T>;
18 toggleItemSelection: Callback<T>;
21 const flatTree = (depth: number, items?: any): [] => {
22 return items ? items.reduce((prev: any, next: any) => {
23 const { items } = next;
28 ...(next.open ? flatTree(depth + 1, items) : []),
33 const memoizedMapStateToProps = () => {
34 let prevTree: Ttree<any>;
35 let mappedProps: Pick<TreeProps<any>, 'items' | 'disableRipple'>;
36 return <T>(state: RootState, props: TreePickerProps<T>): Pick<TreeProps<T>, 'items' | 'disableRipple'> => {
37 const tree = state.treePicker[props.pickerId] || createTree();
38 if (tree !== prevTree) {
42 items: getNodeChildrenIds('')(tree)
43 .map(treePickerToTreeItems(tree))
47 items: flatTree(2, parentItem.items || []),
55 const mapDispatchToProps = (_: Dispatch, props: TreePickerProps<any>): Pick<TreeProps<any>, 'onContextMenu' | 'toggleItemOpen' | 'toggleItemActive' | 'toggleItemSelection'> => ({
56 onContextMenu: (event, item) => props.onContextMenu(event, item, props.pickerId),
57 toggleItemActive: (event, item) => props.toggleItemActive(event, item, props.pickerId),
58 toggleItemOpen: (event, item) => props.toggleItemOpen(event, item, props.pickerId),
59 toggleItemSelection: (event, item) => props.toggleItemSelection(event, item, props.pickerId),
62 export const TreePicker = connect(memoizedMapStateToProps(), mapDispatchToProps)(Tree);
64 const treePickerToTreeItems = (tree: Ttree<any>) =>
65 (id: string): TreeItem<any> => {
66 const node = getNode(id)(tree) || initTreeNode({ id: '', value: 'InvalidNode' });
67 const items = getNodeChildrenIds(node.id)(tree)
68 .map(treePickerToTreeItems(tree));
73 items: items.length > 0 ? items : undefined,
75 selected: node.selected,
76 status: treeNodeStatusToTreeItem(node.status),
80 export const treeNodeStatusToTreeItem = (status: TreeNodeStatus) => {
82 case TreeNodeStatus.INITIAL:
83 return TreeItemStatus.INITIAL;
84 case TreeNodeStatus.PENDING:
85 return TreeItemStatus.PENDING;
86 case TreeNodeStatus.LOADED:
87 return TreeItemStatus.LOADED;