Move Resource interface to models, unify ResourceKind enum
[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 { ResourceKind } from "../../models/kinds";
14 import { Resource } from "../../models/resource";
15
16 export const getResourceUrl = <T extends Resource>(resource: T): string => {
17     switch (resource.kind) {
18         case ResourceKind.Project: return `/projects/${resource.uuid}`;
19         case ResourceKind.Collection: return `/collections/${resource.uuid}`;
20         default: return resource.href;
21     }
22 };
23
24 export enum ItemMode {
25     BOTH,
26     OPEN,
27     ACTIVE
28 }
29
30 export const setProjectItem = (itemId: string, itemMode: ItemMode) =>
31     (dispatch: Dispatch, getState: () => RootState) => {
32         const { projects, router } = getState();
33         const treeItem = findTreeItem(projects.items, itemId);
34
35         if (treeItem) {
36
37             if (itemMode === ItemMode.OPEN || itemMode === ItemMode.BOTH) {
38                 dispatch(projectActions.TOGGLE_PROJECT_TREE_ITEM_OPEN(treeItem.data.uuid));
39             }
40
41             const resourceUrl = getResourceUrl(treeItem.data);
42
43             if (itemMode === ItemMode.ACTIVE || itemMode === ItemMode.BOTH) {
44                 if (router.location && !router.location.pathname.includes(resourceUrl)) {
45                     dispatch(push(resourceUrl));
46                 }
47                 dispatch(projectActions.TOGGLE_PROJECT_TREE_ITEM_ACTIVE(treeItem.data.uuid));
48             }
49
50             const promise = treeItem.status === TreeItemStatus.Loaded
51                 ? Promise.resolve()
52                 : dispatch<any>(getProjectList(itemId));
53
54             promise
55                 .then(() => dispatch<any>(() => {
56                     dispatch(dataExplorerActions.RESET_PAGINATION({id: PROJECT_PANEL_ID}));
57                     dispatch(dataExplorerActions.REQUEST_ITEMS({id: PROJECT_PANEL_ID}));
58                 }));
59
60         }
61     };