2bdd17a5a2eec12f06bce983aa336d6904d9d89d
[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/navigation/navigation-action';
12
13 export const Routes = {
14     ROOT: '/',
15     PROJECTS: `/projects/:id(${RESOURCE_UUID_PATTERN})`,
16     COLLECTIONS: `/collections/:id(${RESOURCE_UUID_PATTERN})`,
17     FAVORITES: '/favorites',
18 };
19
20 export const getResourceUrl = (uuid: string) => {
21     const kind = extractUuidKind(uuid);
22     switch (kind) {
23         case ResourceKind.PROJECT:
24             return getProjectUrl(uuid);
25         case ResourceKind.COLLECTION:
26             return getCollectionUrl(uuid);
27         default:
28             return undefined;
29     }
30 };
31
32 export const addRouteChangeHandlers = (history: History, store: RootStore) => {
33     const handler = handleLocationChange(store);
34     handler(history.location);
35     history.listen(handler);
36 };
37
38 export const matchRootRoute = (route: string) =>
39     matchPath(route, { path: Routes.ROOT, exact: true });
40
41 export const matchFavoritesRoute = (route: string) =>
42     matchPath(route, { path: Routes.FAVORITES });
43
44 export interface ProjectRouteParams {
45     id: string;
46 }
47
48 export const matchProjectRoute = (route: string) =>
49     matchPath<ProjectRouteParams>(route, { path: Routes.PROJECTS });
50
51 export interface CollectionRouteParams {
52     id: string;
53 }
54
55 export const matchCollectionRoute = (route: string) =>
56     matchPath<ProjectRouteParams>(route, { path: Routes.COLLECTIONS });
57
58
59 const handleLocationChange = (store: RootStore) => ({ pathname }: Location) => {
60     const projectMatch = matchProjectRoute(pathname);
61     const collectionMatch = matchCollectionRoute(pathname);
62     const favoriteMatch = matchFavoritesRoute(pathname);
63     if (projectMatch) {
64         store.dispatch(loadProject(projectMatch.params.id));
65     } else if (collectionMatch) {
66         store.dispatch(loadCollection(collectionMatch.params.id));
67     } else if (favoriteMatch) {
68         store.dispatch(loadFavorites());
69     }
70 };