Merge branch '13858-process-view-information-card'
[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 addRouteChangeHandlers = (history: History, store: RootStore) => {
35     const handler = handleLocationChange(store);
36     handler(history.location);
37     history.listen(handler);
38 };
39
40 export const matchRootRoute = (route: string) =>
41     matchPath(route, { path: Routes.ROOT, exact: true });
42
43 export const matchFavoritesRoute = (route: string) =>
44     matchPath(route, { path: Routes.FAVORITES });
45
46 export interface ProjectRouteParams {
47     id: string;
48 }
49
50 export const matchProjectRoute = (route: string) =>
51     matchPath<ProjectRouteParams>(route, { path: Routes.PROJECTS });
52
53 export interface CollectionRouteParams {
54     id: string;
55 }
56
57 export const matchCollectionRoute = (route: string) =>
58     matchPath<CollectionRouteParams>(route, { path: Routes.COLLECTIONS });
59
60
61 const handleLocationChange = (store: RootStore) => ({ pathname }: Location) => {
62     const projectMatch = matchProjectRoute(pathname);
63     const collectionMatch = matchCollectionRoute(pathname);
64     const favoriteMatch = matchFavoritesRoute(pathname);
65     if (projectMatch) {
66         store.dispatch(loadProject(projectMatch.params.id));
67     } else if (collectionMatch) {
68         store.dispatch(loadCollection(collectionMatch.params.id));
69     } else if (favoriteMatch) {
70         store.dispatch(loadFavorites());
71     }
72 };