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 memoizedMapStateToProps = () => {
22 let prevTree: Ttree<any>;
23 let mappedProps: Pick<TreeProps<any>, 'items' | 'disableRipple'>;
24 return <T>(state: RootState, props: TreePickerProps<T>): Pick<TreeProps<T>, 'items' | 'disableRipple'> => {
25 const tree = state.treePicker[props.pickerId] || createTree();
26 if (tree !== prevTree) {
30 items: getNodeChildrenIds('')(tree)
31 .map(treePickerToTreeItems(tree))
38 const mapDispatchToProps = (_: Dispatch, props: TreePickerProps<any>): Pick<TreeProps<any>, 'onContextMenu' | 'toggleItemOpen' | 'toggleItemActive' | 'toggleItemSelection'> => ({
39 onContextMenu: (event, item) => props.onContextMenu(event, item, props.pickerId),
40 toggleItemActive: (event, item) => props.toggleItemActive(event, item, props.pickerId),
41 toggleItemOpen: (event, item) => props.toggleItemOpen(event, item, props.pickerId),
42 toggleItemSelection: (event, item) => props.toggleItemSelection(event, item, props.pickerId),
45 export const TreePicker = connect(memoizedMapStateToProps(), mapDispatchToProps)(Tree);
47 const treePickerToTreeItems = (tree: Ttree<any>) =>
48 (id: string): TreeItem<any> => {
49 const node = getNode(id)(tree) || initTreeNode({ id: '', value: 'InvalidNode' });
50 const items = getNodeChildrenIds(node.id)(tree)
51 .map(treePickerToTreeItems(tree));
56 items: items.length > 0 ? items : undefined,
58 selected: node.selected,
59 status: treeNodeStatusToTreeItem(node.status),
63 export const treeNodeStatusToTreeItem = (status: TreeNodeStatus) => {
65 case TreeNodeStatus.INITIAL:
66 return TreeItemStatus.INITIAL;
67 case TreeNodeStatus.PENDING:
68 return TreeItemStatus.PENDING;
69 case TreeNodeStatus.LOADED:
70 return TreeItemStatus.LOADED;