c46239e2a1cbe5deeff10fc60b42718181c82817
[arvados-workbench2.git] / src / routes / routes.ts
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import { History, Location } from 'history';
6 import { RootStore } from '../store/store';
7 import { matchPath } from 'react-router';
8 import { ResourceKind, RESOURCE_UUID_PATTERN, extractUuidKind } from '~/models/resource';
9 import { getProjectUrl } from '../models/project';
10 import { getCollectionUrl } from '~/models/collection';
11 import { loadProject, loadFavorites, loadCollection } from '../store/workbench/workbench-actions';
12
13 export const Routes = {
14     ROOT: '/',
15     TOKEN: '/token',
16     PROJECTS: `/projects/:id(${RESOURCE_UUID_PATTERN})`,
17     COLLECTIONS: `/collections/:id(${RESOURCE_UUID_PATTERN})`,
18     PROCESS: `/processes/:id(${RESOURCE_UUID_PATTERN})`,
19     FAVORITES: '/favorites',
20 };
21
22 export const getResourceUrl = (uuid: string) => {
23     const kind = extractUuidKind(uuid);
24     switch (kind) {
25         case ResourceKind.PROJECT:
26             return getProjectUrl(uuid);
27         case ResourceKind.COLLECTION:
28             return getCollectionUrl(uuid);
29         default:
30             return undefined;
31     }
32 };
33
34 export const getProcessUrl = (uuid: string) => `/processes/${uuid}`;
35
36 export const addRouteChangeHandlers = (history: History, store: RootStore) => {
37     const handler = handleLocationChange(store);
38     handler(history.location);
39     history.listen(handler);
40 };
41
42 export const matchRootRoute = (route: string) =>
43     matchPath(route, { path: Routes.ROOT, exact: true });
44
45 export const matchFavoritesRoute = (route: string) =>
46     matchPath(route, { path: Routes.FAVORITES });
47
48 export interface ResourceRouteParams {
49     id: string;
50 }
51
52 export const matchProjectRoute = (route: string) =>
53     matchPath<ResourceRouteParams>(route, { path: Routes.PROJECTS });
54
55 export const matchCollectionRoute = (route: string) =>
56     matchPath<ResourceRouteParams>(route, { path: Routes.COLLECTIONS });
57
58 export const matchProcessRoute = (route: string) =>
59     matchPath<ResourceRouteParams>(route, { path: Routes.COLLECTIONS });
60
61
62 const handleLocationChange = (store: RootStore) => ({ pathname }: Location) => {
63     const projectMatch = matchProjectRoute(pathname);
64     const collectionMatch = matchCollectionRoute(pathname);
65     const favoriteMatch = matchFavoritesRoute(pathname);
66     const processMatch = matchProcessRoute(pathname);
67     if (projectMatch) {
68         store.dispatch(loadProject(projectMatch.params.id));
69     } else if (collectionMatch) {
70         store.dispatch(loadCollection(collectionMatch.params.id));
71     } else if (favoriteMatch) {
72         store.dispatch(loadFavorites());
73     } else if (processMatch) {
74         store.dispatch(processMatch.params.id);
75     }
76 };