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