21846: applied select to context menu open
[arvados.git] / services / workbench2 / src / store / breadcrumbs / breadcrumbs-actions.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 { RootState } from 'store/store';
7 import { getUserUuid } from "common/getuser";
8 import { getResource } from 'store/resources/resources';
9 import { propertiesActions } from '../properties/properties-actions';
10 import { getProcess } from 'store/processes/process';
11 import { ServiceRepository } from 'services/services';
12 import { SidePanelTreeCategory, activateSidePanelTreeItem } from 'store/side-panel-tree/side-panel-tree-actions';
13 import { updateResources } from '../resources/resources-actions';
14 import { ResourceKind } from 'models/resource';
15 import { GroupResource } from 'models/group';
16 import { extractUuidKind } from 'models/resource';
17 import { UserResource } from 'models/user';
18 import { FilterBuilder } from 'services/api/filter-builder';
19 import { ProcessResource } from 'models/process';
20 import { OrderBuilder } from 'services/api/order-builder';
21 import { Breadcrumb } from 'components/breadcrumbs/breadcrumbs';
22 import { ContainerRequestResource, containerRequestFieldsNoMounts } from 'models/container-request';
23 import { AdminMenuIcon, CollectionIcon, IconType, ProcessIcon, ProjectIcon, ResourceIcon, TerminalIcon, WorkflowIcon } from 'components/icon/icon';
24 import { CollectionResource } from 'models/collection';
25 import { getSidePanelIcon } from 'views-components/side-panel-tree/side-panel-tree';
26 import { WorkflowResource } from 'models/workflow';
27 import { progressIndicatorActions } from "store/progress-indicator/progress-indicator-actions";
28
29 export const BREADCRUMBS = 'breadcrumbs';
30
31 export const setBreadcrumbs = (breadcrumbs: any, currentItem?: CollectionResource | ContainerRequestResource | GroupResource | WorkflowResource) => {
32     if (currentItem) {
33         const currentCrumb = resourceToBreadcrumb(currentItem)
34         if (currentCrumb.label.length) breadcrumbs.push(currentCrumb);
35     }
36     return propertiesActions.SET_PROPERTY({ key: BREADCRUMBS, value: breadcrumbs });
37 };
38
39 const resourceToBreadcrumbIcon = (resource: CollectionResource | ContainerRequestResource | GroupResource | WorkflowResource): IconType | undefined => {
40     switch (resource.kind) {
41         case ResourceKind.PROJECT:
42             return ProjectIcon;
43         case ResourceKind.PROCESS:
44             return ProcessIcon;
45         case ResourceKind.COLLECTION:
46             return CollectionIcon;
47         case ResourceKind.WORKFLOW:
48             return WorkflowIcon;
49         default:
50             return undefined;
51     }
52 }
53
54 const resourceToBreadcrumb = (resource: (CollectionResource | ContainerRequestResource | GroupResource | WorkflowResource) & {fullName?: string}  ): Breadcrumb => ({
55     label: resource.name || resource.fullName || '',
56     uuid: resource.uuid,
57     icon: resourceToBreadcrumbIcon(resource),
58 })
59
60 export const setSidePanelBreadcrumbs = (uuid: string) =>
61     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
62         try {
63             dispatch(progressIndicatorActions.START_WORKING(uuid + "-breadcrumbs"));
64             const ancestors = await services.ancestorsService.ancestors(uuid, '');
65             dispatch(updateResources(ancestors));
66
67             let breadcrumbs: Breadcrumb[] = [];
68             const { collectionPanel: { item } } = getState();
69
70             const path = getState().router.location!.pathname;
71             const currentUuid = path.split('/')[2];
72             const uuidKind = extractUuidKind(currentUuid);
73             const rootUuid = getUserUuid(getState());
74
75             if (ancestors.find(ancestor => ancestor.uuid === rootUuid)) {
76                 // Handle home project uuid root
77                 breadcrumbs.push({
78                     label: SidePanelTreeCategory.PROJECTS,
79                     uuid: SidePanelTreeCategory.PROJECTS,
80                     icon: getSidePanelIcon(SidePanelTreeCategory.PROJECTS)
81                 });
82             } else if (uuidKind === ResourceKind.USER) {
83                 // Handle another user root project
84                 const user = getResource<UserResource>(uuid)(getState().resources);
85                 breadcrumbs.push({
86                     label: (user as any)?.fullName || user?.username || uuid,
87                     uuid: user?.uuid || uuid,
88                     icon: getSidePanelIcon(SidePanelTreeCategory.PROJECTS)
89                 });
90             } else if (Object.values(SidePanelTreeCategory).includes(uuid as SidePanelTreeCategory)) {
91                 // Handle SidePanelTreeCategory root
92                 breadcrumbs.push({
93                     label: uuid,
94                     uuid: uuid,
95                     icon: getSidePanelIcon(uuid)
96                 });
97             }
98
99             breadcrumbs = ancestors.reduce((breadcrumbs, ancestor) =>
100                 ancestor.kind === ResourceKind.GROUP
101                     ? [...breadcrumbs, resourceToBreadcrumb(ancestor)]
102                     : breadcrumbs,
103                 breadcrumbs);
104
105             if (uuidKind === ResourceKind.COLLECTION) {
106                 const collectionItem = item ? item : await services.collectionService.get(currentUuid);
107                 const parentProcessItem = await getCollectionParent(collectionItem)(services);
108                 if (parentProcessItem) {
109                     const mainProcessItem = await getProcessParent(parentProcessItem)(services);
110                     mainProcessItem && breadcrumbs.push(resourceToBreadcrumb(mainProcessItem));
111                     breadcrumbs.push(resourceToBreadcrumb(parentProcessItem));
112                 }
113                 dispatch(setBreadcrumbs(breadcrumbs, collectionItem));
114             } else if (uuidKind === ResourceKind.PROCESS) {
115                 const processItem = await services.containerRequestService.get(currentUuid);
116                 const parentProcessItem = await getProcessParent(processItem)(services);
117                 if (parentProcessItem) {
118                     breadcrumbs.push(resourceToBreadcrumb(parentProcessItem));
119                 }
120                 dispatch(setBreadcrumbs(breadcrumbs, processItem));
121             } else if (uuidKind === ResourceKind.WORKFLOW) {
122                 const workflowItem = await services.workflowService.get(currentUuid);
123                 dispatch(setBreadcrumbs(breadcrumbs, workflowItem));
124             }
125             dispatch(setBreadcrumbs(breadcrumbs));
126         } finally {
127             dispatch(progressIndicatorActions.STOP_WORKING(uuid + "-breadcrumbs"));
128         }
129     };
130
131 export const setSharedWithMeBreadcrumbs = (uuid: string) =>
132     setCategoryBreadcrumbs(uuid, SidePanelTreeCategory.SHARED_WITH_ME);
133
134 export const setTrashBreadcrumbs = (uuid: string) =>
135     setCategoryBreadcrumbs(uuid, SidePanelTreeCategory.TRASH);
136
137 export const setCategoryBreadcrumbs = (uuid: string, category: string) =>
138     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
139         try {
140             dispatch(progressIndicatorActions.START_WORKING(uuid + "-breadcrumbs"));
141             const ancestors = await services.ancestorsService.ancestors(uuid, '');
142             dispatch(updateResources(ancestors));
143             const initialBreadcrumbs: Breadcrumb[] = [
144                 {
145                     label: category,
146                     uuid: category,
147                     icon: getSidePanelIcon(category)
148                 }
149             ];
150             const { collectionPanel: { item } } = getState();
151             const path = getState().router.location!.pathname;
152             const currentUuid = path.split('/')[2];
153             const uuidKind = extractUuidKind(currentUuid);
154             let breadcrumbs = ancestors.reduce((breadcrumbs, ancestor) =>
155                 ancestor.kind === ResourceKind.GROUP
156                     ? [...breadcrumbs, resourceToBreadcrumb(ancestor)]
157                     : breadcrumbs,
158                 initialBreadcrumbs);
159             if (uuidKind === ResourceKind.COLLECTION) {
160                 const collectionItem = item ? item : await services.collectionService.get(currentUuid);
161                 const parentProcessItem = await getCollectionParent(collectionItem)(services);
162                 if (parentProcessItem) {
163                     const mainProcessItem = await getProcessParent(parentProcessItem)(services);
164                     mainProcessItem && breadcrumbs.push(resourceToBreadcrumb(mainProcessItem));
165                     breadcrumbs.push(resourceToBreadcrumb(parentProcessItem));
166                 }
167                 dispatch(setBreadcrumbs(breadcrumbs, collectionItem));
168             } else if (uuidKind === ResourceKind.PROCESS) {
169                 const processItem = await services.containerRequestService.get(currentUuid);
170                 const parentProcessItem = await getProcessParent(processItem)(services);
171                 if (parentProcessItem) {
172                     breadcrumbs.push(resourceToBreadcrumb(parentProcessItem));
173                 }
174                 dispatch(setBreadcrumbs(breadcrumbs, processItem));
175             } else if (uuidKind === ResourceKind.WORKFLOW) {
176                 const workflowItem = await services.workflowService.get(currentUuid);
177                 dispatch(setBreadcrumbs(breadcrumbs, workflowItem));
178             }
179             dispatch(setBreadcrumbs(breadcrumbs));
180         } finally {
181             dispatch(progressIndicatorActions.STOP_WORKING(uuid + "-breadcrumbs"));
182         }
183     };
184
185 const getProcessParent = (childProcess: ContainerRequestResource) =>
186     async (services: ServiceRepository): Promise<ContainerRequestResource | undefined> => {
187         if (childProcess.requestingContainerUuid) {
188             const parentProcesses = await services.containerRequestService.list({
189                 order: new OrderBuilder<ProcessResource>().addAsc('createdAt').getOrder(),
190                 filters: new FilterBuilder().addEqual('container_uuid', childProcess.requestingContainerUuid).getFilters(),
191                 select: containerRequestFieldsNoMounts,
192             });
193             if (parentProcesses.items.length > 0) {
194                 return parentProcesses.items[0];
195             } else {
196                 return undefined;
197             }
198         } else {
199             return undefined;
200         }
201     }
202
203 const getCollectionParent = (collection: CollectionResource) =>
204     async (services: ServiceRepository): Promise<ContainerRequestResource | undefined> => {
205         const parentOutputPromise = services.containerRequestService.list({
206             order: new OrderBuilder<ProcessResource>().addAsc('createdAt').getOrder(),
207             filters: new FilterBuilder().addEqual('output_uuid', collection.uuid).getFilters(),
208             select: containerRequestFieldsNoMounts,
209         });
210         const parentLogPromise = services.containerRequestService.list({
211             order: new OrderBuilder<ProcessResource>().addAsc('createdAt').getOrder(),
212             filters: new FilterBuilder().addEqual('log_uuid', collection.uuid).getFilters(),
213             select: containerRequestFieldsNoMounts,
214         });
215         const [parentOutput, parentLog] = await Promise.all([parentOutputPromise, parentLogPromise]);
216         return parentOutput.items.length > 0 ?
217             parentOutput.items[0] :
218             parentLog.items.length > 0 ?
219                 parentLog.items[0] :
220                 undefined;
221     }
222
223
224 export const setProjectBreadcrumbs = (uuid: string) =>
225     async (dispatch: Dispatch<any>, getState: () => RootState, services: ServiceRepository) => {
226         const ancestors = await services.ancestorsService.ancestors(uuid, '');
227         const rootUuid = getUserUuid(getState());
228         if (uuid === rootUuid || ancestors.find(ancestor => ancestor.uuid === rootUuid)) {
229             dispatch(setSidePanelBreadcrumbs(uuid));
230         } else {
231             dispatch(setSharedWithMeBreadcrumbs(uuid));
232             dispatch(activateSidePanelTreeItem(SidePanelTreeCategory.SHARED_WITH_ME));
233         }
234     };
235
236 export const setProcessBreadcrumbs = (processUuid: string) =>
237     (dispatch: Dispatch, getState: () => RootState) => {
238         const { resources } = getState();
239         const process = getProcess(processUuid)(resources);
240         if (process) {
241             dispatch<any>(setProjectBreadcrumbs(process.containerRequest.ownerUuid));
242         }
243     };
244
245 export const setGroupsBreadcrumbs = () =>
246     setBreadcrumbs([{
247         label: SidePanelTreeCategory.GROUPS,
248         uuid: SidePanelTreeCategory.GROUPS,
249         icon: getSidePanelIcon(SidePanelTreeCategory.GROUPS)
250     }]);
251
252 export const setGroupDetailsBreadcrumbs = (groupUuid: string) =>
253     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
254
255         const group = getResource<GroupResource>(groupUuid)(getState().resources);
256
257         const breadcrumbs: Breadcrumb[] = [
258             {
259                 label: SidePanelTreeCategory.GROUPS,
260                 uuid: SidePanelTreeCategory.GROUPS,
261                 icon: getSidePanelIcon(SidePanelTreeCategory.GROUPS)
262             },
263             { label: group ? group.name : (await services.groupsService.get(groupUuid)).name, uuid: groupUuid },
264         ];
265
266         dispatch(setBreadcrumbs(breadcrumbs));
267
268     };
269
270 export const USERS_PANEL_LABEL = 'Users';
271
272 export const setUsersBreadcrumbs = () =>
273     setBreadcrumbs([{ label: USERS_PANEL_LABEL, uuid: USERS_PANEL_LABEL }]);
274
275 export const setUserProfileBreadcrumbs = (userUuid: string) =>
276     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
277         try {
278             const user = getResource<UserResource>(userUuid)(getState().resources)
279                 || await services.userService.get(userUuid, false);
280             const userProfileBreadcrumbs: Breadcrumb[] = [
281                 { label: USERS_PANEL_LABEL, uuid: USERS_PANEL_LABEL },
282                 { label: user ? `${user.firstName} ${user.lastName}` : userUuid, uuid: userUuid },
283             ];    
284             dispatch(setBreadcrumbs(userProfileBreadcrumbs));
285         } catch (e) {
286             const breadcrumbs: Breadcrumb[] = [
287                 { label: USERS_PANEL_LABEL, uuid: USERS_PANEL_LABEL },
288                 { label: userUuid, uuid: userUuid },
289             ];
290             dispatch(setBreadcrumbs(breadcrumbs));
291         }
292     };
293
294 export const MY_ACCOUNT_PANEL_LABEL = 'My Account';
295
296 export const setMyAccountBreadcrumbs = () =>
297     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
298         dispatch(setBreadcrumbs([
299             { label: MY_ACCOUNT_PANEL_LABEL, uuid: MY_ACCOUNT_PANEL_LABEL },
300         ]));
301     };
302
303 export const INSTANCE_TYPES_PANEL_LABEL = 'Instance Types';
304
305 export const setInstanceTypesBreadcrumbs = () =>
306     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
307         dispatch(setBreadcrumbs([
308             { label: INSTANCE_TYPES_PANEL_LABEL, uuid: INSTANCE_TYPES_PANEL_LABEL, icon: ResourceIcon },
309         ]));
310     };
311
312 export const setVirtualMachinesBreadcrumbs = () =>
313     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
314         dispatch(setBreadcrumbs([
315             { label: SidePanelTreeCategory.SHELL_ACCESS, uuid: SidePanelTreeCategory.SHELL_ACCESS, icon: TerminalIcon },
316         ]));
317     };
318
319 export const VIRTUAL_MACHINES_ADMIN_PANEL_LABEL = 'Shell Access Admin';
320
321 export const setVirtualMachinesAdminBreadcrumbs = () =>
322     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
323         dispatch(setBreadcrumbs([
324             { label: VIRTUAL_MACHINES_ADMIN_PANEL_LABEL, uuid: VIRTUAL_MACHINES_ADMIN_PANEL_LABEL, icon: AdminMenuIcon },
325         ]));
326     };
327
328 export const REPOSITORIES_PANEL_LABEL = 'Repositories';
329
330 export const setRepositoriesBreadcrumbs = () =>
331     async (dispatch: Dispatch, getState: () => RootState, services: ServiceRepository) => {
332         dispatch(setBreadcrumbs([
333             { label: REPOSITORIES_PANEL_LABEL, uuid: REPOSITORIES_PANEL_LABEL, icon: AdminMenuIcon },
334         ]));
335     };