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))
46 items: flatTree(2, parentItem.items || []),
54 const mapDispatchToProps = (_: Dispatch, props: TreePickerProps<any>): Pick<TreeProps<any>, 'onContextMenu' | 'toggleItemOpen' | 'toggleItemActive' | 'toggleItemSelection'> => ({
55 onContextMenu: (event, item) => props.onContextMenu(event, item, props.pickerId),
56 toggleItemActive: (event, item) => props.toggleItemActive(event, item, props.pickerId),
57 toggleItemOpen: (event, item) => props.toggleItemOpen(event, item, props.pickerId),
58 toggleItemSelection: (event, item) => props.toggleItemSelection(event, item, props.pickerId),
61 export const TreePicker = connect(memoizedMapStateToProps(), mapDispatchToProps)(Tree);
63 const treePickerToTreeItems = (tree: Ttree<any>) =>
64 (id: string): TreeItem<any> => {
65 const node = getNode(id)(tree) || initTreeNode({ id: '', value: 'InvalidNode' });
66 const items = getNodeChildrenIds(node.id)(tree)
67 .map(treePickerToTreeItems(tree));
72 items: items.length > 0 ? items : undefined,
74 selected: node.selected,
75 status: treeNodeStatusToTreeItem(node.status),
79 export const treeNodeStatusToTreeItem = (status: TreeNodeStatus) => {
81 case TreeNodeStatus.INITIAL:
82 return TreeItemStatus.INITIAL;
83 case TreeNodeStatus.PENDING:
84 return TreeItemStatus.PENDING;
85 case TreeNodeStatus.LOADED:
86 return TreeItemStatus.LOADED;