1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import { Project } from "../../models/project";
6 import actions, { ProjectAction } from "./project-action";
7 import { TreeItem, TreeItemStatus } from "../../components/tree/tree";
8 import * as _ from "lodash";
10 export type ProjectState = Array<TreeItem<Project>>;
12 export function findTreeItem<T>(tree: Array<TreeItem<T>>, itemId: string): TreeItem<T> | undefined {
14 for (const t of tree) {
15 item = t.id === itemId
17 : findTreeItem(t.items ? t.items : [], itemId);
25 export function getTreePath<T>(tree: Array<TreeItem<T>>, itemId: string): Array<TreeItem<T>> {
26 for(const item of tree){
27 if(item.id === itemId){
30 const branch = getTreePath(item.items || [], itemId);
31 if(branch.length > 0){
32 return [item, ...branch];
39 function resetTreeActivity<T>(tree: Array<TreeItem<T>>) {
40 for (const t of tree) {
42 resetTreeActivity(t.items ? t.items : []);
46 function updateProjectTree(tree: Array<TreeItem<Project>>, projects: Project[], parentItemId?: string): Array<TreeItem<Project>> {
49 treeItem = findTreeItem(tree, parentItemId);
51 treeItem.status = TreeItemStatus.Loaded;
54 const items = projects.map((p, idx) => ({
58 status: TreeItemStatus.Initial,
61 } as TreeItem<Project>));
64 treeItem.items = items;
71 const projectsReducer = (state: ProjectState = [], action: ProjectAction) => {
72 return actions.match(action, {
73 CREATE_PROJECT: project => [...state, project],
74 REMOVE_PROJECT: () => state,
75 PROJECTS_REQUEST: itemId => {
76 const tree = _.cloneDeep(state);
77 const item = findTreeItem(tree, itemId);
79 item.status = TreeItemStatus.Pending;
83 PROJECTS_SUCCESS: ({ projects, parentItemId }) => {
84 return updateProjectTree(state, projects, parentItemId);
86 TOGGLE_PROJECT_TREE_ITEM: itemId => {
87 const tree = _.cloneDeep(state);
88 resetTreeActivity(tree);
89 const item = findTreeItem(tree, itemId);
91 item.open = !item.open;
101 export default projectsReducer;