Merge branch 'master' into 13853-collection-view-info-card
[arvados-workbench2.git] / src / store / navigation / navigation-action.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { Dispatch } from "redux";
6 import { projectActions, getProjectList } from "../project/project-action";
7 import { push } from "react-router-redux";
8 import { TreeItemStatus } from "../../components/tree/tree";
9 import { findTreeItem } from "../project/project-reducer";
10 import { dataExplorerActions } from "../data-explorer/data-explorer-action";
11 import { PROJECT_PANEL_ID } from "../../views/project-panel/project-panel";
12 import { RootState } from "../store";
13 import { Resource, ResourceKind } from "../../models/resource";
14 import { getCollectionUrl } from "../../models/collection";
15 import { getProjectUrl } from "../../models/project";
16
17 export const getResourceUrl = <T extends Resource>(resource: T): string => {
18     switch (resource.kind) {
19         case ResourceKind.PROJECT: return getProjectUrl(resource.uuid);
20         case ResourceKind.COLLECTION: return getCollectionUrl(resource.uuid);
21         default: return resource.href;
22     }
23 };
24
25 export enum ItemMode {
26     BOTH,
27     OPEN,
28     ACTIVE
29 }
30
31 export const setProjectItem = (itemId: string, itemMode: ItemMode) =>
32     (dispatch: Dispatch, getState: () => RootState) => {
33         const { projects, router } = getState();
34         const treeItem = findTreeItem(projects.items, itemId);
35
36         if (treeItem) {
37
38             const resourceUrl = getResourceUrl(treeItem.data);
39
40             if (itemMode === ItemMode.ACTIVE || itemMode === ItemMode.BOTH) {
41                 if (router.location && !router.location.pathname.includes(resourceUrl)) {
42                     dispatch(push(resourceUrl));
43                 }
44                 dispatch(projectActions.TOGGLE_PROJECT_TREE_ITEM_ACTIVE(treeItem.data.uuid));
45             }
46
47             const promise = treeItem.status === TreeItemStatus.LOADED
48                 ? Promise.resolve()
49                 : dispatch<any>(getProjectList(itemId));
50
51             promise
52                 .then(() => dispatch<any>(() => {
53                     if (itemMode === ItemMode.OPEN || itemMode === ItemMode.BOTH) {
54                         dispatch(projectActions.TOGGLE_PROJECT_TREE_ITEM_OPEN(treeItem.data.uuid));
55                     }
56                     dispatch(dataExplorerActions.RESET_PAGINATION({id: PROJECT_PANEL_ID}));
57                     dispatch(dataExplorerActions.REQUEST_ITEMS({id: PROJECT_PANEL_ID}));
58                 }));
59
60         }
61     };
62