Merge branch 'main' of git.arvados.org:arvados into 22202-delete-process-navigation
[arvados.git] / services / workbench2 / src / components / multiselect-toolbar / MultiselectToolbar.tsx
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import React from "react";
6 import { connect } from "react-redux";
7 import { CustomStyleRulesCallback, ArvadosTheme } from 'common/custom-theme';
8 import { Toolbar, IconButton } from "@mui/material";
9 import { WithStyles } from '@mui/styles';
10 import withStyles from '@mui/styles/withStyles';
11 import { RootState } from "store/store";
12 import { Dispatch } from "redux";
13 import { TCheckedList } from "components/data-table/data-table";
14 import { ContextMenuResource } from "store/context-menu/context-menu-actions";
15 import { Resource, ResourceKind, extractUuidKind, EditableResource } from "models/resource";
16 import { getResource, getResourceWithEditableStatus, ResourcesState } from "store/resources/resources";
17 import { MultiSelectMenuAction, MultiSelectMenuActionSet } from "views-components/multiselect-toolbar/ms-menu-actions";
18 import { ContextMenuAction, ContextMenuActionNames } from "views-components/context-menu/context-menu-action-set";
19 import { multiselectActionsFilters, TMultiselectActionsFilters } from "./ms-toolbar-action-filters";
20 import { kindToActionSet, findActionByName } from "./ms-kind-action-differentiator";
21 import { msToggleTrashAction } from "views-components/multiselect-toolbar/ms-project-action-set";
22 import { copyToClipboardAction } from "store/open-in-new-tab/open-in-new-tab.actions";
23 import { ContainerRequestResource } from "models/container-request";
24 import { FavoritesState } from "store/favorites/favorites-reducer";
25 import { resourceIsFrozen } from "common/frozen-resources";
26 import { GroupResource, GroupClass } from "models/group";
27 import { User } from "models/user";
28 import { Process, isProcessCancelable, getProcess } from "store/processes/process";
29 import { CollectionResource } from "models/collection";
30 import { PublicFavoritesState } from "store/public-favorites/public-favorites-reducer";
31 import { AuthState } from "store/auth/auth-reducer";
32 import { IntersectionObserverWrapper } from "./ms-toolbar-overflow-wrapper";
33 import classNames from "classnames";
34 import { ContextMenuKind, sortMenuItems, menuDirection } from 'views-components/context-menu/menu-item-sort';
35
36 type CssRules = "root" | "iconContainer" | "icon" | "divider";
37
38 const styles: CustomStyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
39     root: {
40         display: "flex",
41         flexDirection: "row",
42         height: '2.5rem',
43         width: 0,
44         padding: 0,
45         margin: 0,
46         overflow: 'hidden',
47     },
48     iconContainer: {
49         height: '100%',
50     },
51     icon: {
52         marginLeft: '-5px',
53     },
54     divider: {
55         marginTop: '5px',
56         width: '2rem',
57         display: "flex",
58         alignItems: "center",
59         justifyContent: "center",
60     },
61 });
62
63 export type MultiselectToolbarProps = {
64     checkedList: TCheckedList;
65     selectedResourceUuid: string | null;
66     iconProps: IconProps
67     user: User | null
68     disabledButtons: Set<string>
69     auth: AuthState;
70     location: string;
71     forceMultiSelectMode?: boolean;
72     injectedStyles?: string;
73     executeMulti: (action: ContextMenuAction | MultiSelectMenuAction, checkedList: TCheckedList, resources: ResourcesState) => void;
74 };
75
76 type IconProps = {
77     resources: ResourcesState;
78     favorites: FavoritesState;
79     publicFavorites: PublicFavoritesState;
80 }
81
82 const detailsCardPaths = [
83     '/projects',
84 ]
85
86 export const usesDetailsCard = (location: string): boolean => {
87     return detailsCardPaths.some(path => location.includes(path))
88 }
89
90 export const MultiselectToolbar = connect(
91     mapStateToProps,
92     mapDispatchToProps
93 )(
94     withStyles(styles)((props: MultiselectToolbarProps & WithStyles<CssRules>) => {
95         const { classes, checkedList, iconProps, user, disabledButtons, location, forceMultiSelectMode, injectedStyles } = props;
96         const selectedResourceArray = selectedToArray(checkedList);
97         const selectedResourceUuid = usesDetailsCard(location) ? props.selectedResourceUuid : selectedResourceArray.length === 1 ? selectedResourceArray[0] : null;
98         const singleResourceKind = selectedResourceUuid && !forceMultiSelectMode ? [resourceToMsResourceKind(selectedResourceUuid, iconProps.resources, user)] : null
99         const currentResourceKinds = singleResourceKind ? singleResourceKind : Array.from(selectedToKindSet(checkedList, iconProps.resources));
100         const currentPathIsTrash = window.location.pathname === "/trash";
101
102         const rawActions =
103             currentPathIsTrash && selectedToKindSet(checkedList).size
104                 ? [msToggleTrashAction]
105                 : selectActionsByKind(currentResourceKinds as string[], multiselectActionsFilters).filter((action) =>
106                         selectedResourceUuid === null ? action.isForMulti : true
107                     );
108
109         const actions: ContextMenuAction[] | MultiSelectMenuAction[] = sortMenuItems(
110             singleResourceKind && singleResourceKind.length ? (singleResourceKind[0] as ContextMenuKind) : ContextMenuKind.MULTI,
111             rawActions,
112             menuDirection.HORIZONTAL
113         );
114
115         const targetResources = selectedResourceUuid ? {[selectedResourceUuid]: true} as TCheckedList : checkedList
116
117         return (
118             <React.Fragment>
119                 <Toolbar
120                     className={classNames(classes.root, injectedStyles)}
121                     style={{ width: `${(actions.length * 2.5) + 2}rem`, height: '2.5rem'}}
122                     data-cy='multiselect-toolbar'
123                     >
124                     {actions.length ? (
125                         <IntersectionObserverWrapper menuLength={actions.length}>
126                             {actions.map((action, i) =>{
127                                 const { hasAlts, useAlts, name, altName, icon, altIcon } = action;
128                             return action.name === ContextMenuActionNames.DIVIDER ? (
129                                 action.component && (
130                                     <div
131                                         className={classes.divider}
132                                         data-targetid={`${name}${i}`}
133                                         key={i}
134                                     >
135                                         <action.component />
136                                     </div>
137                                 )
138                             ) : hasAlts ? (
139                                 <span className={classes.iconContainer} data-targetid={name} data-title={(useAlts && useAlts(selectedResourceUuid, iconProps)) ? altName : name}>
140                                     <IconButton
141                                         data-cy='multiselect-button'
142                                         disabled={disabledButtons.has(name)}
143                                         onClick={() => props.executeMulti(action, targetResources, iconProps.resources)}
144                                         className={classes.icon}
145                                         size="large">
146                                         {currentPathIsTrash || (useAlts && useAlts(selectedResourceUuid, iconProps)) ? altIcon && altIcon({}) : icon({})}
147                                     </IconButton>
148                                 </span>
149                             ) : (
150                                 //data-targetid is used to determine what goes to the overflow menu
151                                 //data-title is used to display the tooltip text
152                                 <span className={classes.iconContainer} data-targetid={name} data-title={name}>
153                                     <IconButton
154                                         data-cy='multiselect-button'
155                                         onClick={() => {
156                                             props.executeMulti(action, targetResources, iconProps.resources)}}
157                                         className={classes.icon}
158                                         size="large">
159                                         {action.icon({})}
160                                     </IconButton>
161                                 </span>
162                             );
163                             })}
164                         </IntersectionObserverWrapper>
165                     ) : (
166                         <></>
167                     )}
168                 </Toolbar>
169             </React.Fragment>
170         );
171     })
172 );
173
174 export function selectedToArray(checkedList: TCheckedList): Array<string> {
175     const arrayifiedSelectedList: Array<string> = [];
176     for (const [key, value] of Object.entries(checkedList)) {
177         if (value === true) {
178             arrayifiedSelectedList.push(key);
179         }
180     }
181     return arrayifiedSelectedList;
182 }
183
184 export function selectedToKindSet(checkedList: TCheckedList, resources: ResourcesState = {}): Set<string> {
185     const setifiedList = new Set<string>();
186     for (const [key, value] of Object.entries(checkedList)) {
187         if (value === true) {
188             isGroupResource(key, resources) ? setifiedList.add(ContextMenuKind.GROUPS) : setifiedList.add(extractUuidKind(key) as string);
189         }
190     }
191     return setifiedList;
192 }
193
194 export const isGroupResource = (uuid: string, resources: ResourcesState): boolean => {
195     const resource = getResource(uuid)(resources);
196     if(!resource) return false;
197     return resource.kind === ResourceKind.PROJECT && (resource as GroupResource).groupClass === GroupClass.ROLE;
198 };
199
200 function groupByKind(checkedList: TCheckedList, resources: ResourcesState): Record<string, ContextMenuResource[]> {
201     const result = {};
202     selectedToArray(checkedList).forEach(uuid => {
203         const resource = getResource(uuid)(resources) as ContainerRequestResource | Resource;
204         const kind = isGroupResource(uuid, resources) ? ContextMenuKind.GROUPS : resource.kind;
205         if (!result[kind]) result[kind] = [];
206         result[kind].push(resource);
207     });
208     return result;
209 }
210
211 function filterActions(actionArray: MultiSelectMenuActionSet, filters: Set<string>): Array<MultiSelectMenuAction> {
212     return actionArray[0].filter(action => filters.has(action.name as string));
213 }
214
215 const resourceToMsResourceKind = (uuid: string, resources: ResourcesState, user: User | null, readonly = false): (ContextMenuKind | ResourceKind) | undefined => {
216     if (!user) return;
217     const resource = getResourceWithEditableStatus<GroupResource & EditableResource>(uuid, user.uuid)(resources);
218     const { isAdmin } = user;
219     const kind = extractUuidKind(uuid);
220
221     const isFrozen = resource?.kind && resource.kind === ResourceKind.PROJECT ? resourceIsFrozen(resource, resources) : false;
222     const isEditable = (user.isAdmin || (resource || ({} as EditableResource)).isEditable) && !readonly && !isFrozen;
223
224     switch (kind) {
225         case ResourceKind.PROJECT:
226             if (isFrozen) {
227                 return isAdmin ? ContextMenuKind.FROZEN_PROJECT_ADMIN : ContextMenuKind.FROZEN_PROJECT;
228             }
229
230             if (isAdmin && !readonly) {
231                 if (resource?.groupClass === GroupClass.FILTER) {
232                     return ContextMenuKind.FILTER_GROUP_ADMIN;
233                 }
234                 if (resource?.groupClass === GroupClass.ROLE) {
235                     return ContextMenuKind.GROUPS;
236                 }
237                 return ContextMenuKind.PROJECT_ADMIN;
238             }
239
240             return isEditable
241                 ? resource && resource.groupClass !== GroupClass.FILTER
242                     ? ContextMenuKind.PROJECT
243                     : ContextMenuKind.FILTER_GROUP
244                 : ContextMenuKind.READONLY_PROJECT;
245         case ResourceKind.COLLECTION:
246             const c = getResource<CollectionResource>(uuid)(resources);
247             if (c === undefined) {
248                 return;
249             }
250             const isOldVersion = c.uuid !== c.currentVersionUuid;
251             const isTrashed = c.isTrashed;
252             return isOldVersion
253                 ? ContextMenuKind.OLD_VERSION_COLLECTION
254                 : isTrashed && isEditable
255                 ? ContextMenuKind.TRASHED_COLLECTION
256                 : isAdmin && isEditable
257                 ? ContextMenuKind.COLLECTION_ADMIN
258                 : isEditable
259                 ? ContextMenuKind.COLLECTION
260                 : ContextMenuKind.READONLY_COLLECTION;
261         case ResourceKind.PROCESS:
262             return isAdmin && isEditable
263                 ? resource && isProcessCancelable(getProcess(resource.uuid)(resources) as Process)
264                     ? ContextMenuKind.RUNNING_PROCESS_ADMIN
265                     : ContextMenuKind.PROCESS_ADMIN
266                 : readonly
267                 ? ContextMenuKind.READONLY_PROCESS_RESOURCE
268                 : resource && isProcessCancelable(getProcess(resource.uuid)(resources) as Process)
269                 ? ContextMenuKind.RUNNING_PROCESS_RESOURCE
270                 : ContextMenuKind.PROCESS_RESOURCE;
271         case ResourceKind.USER:
272             return isAdmin ? ContextMenuKind.ROOT_PROJECT_ADMIN : ContextMenuKind.ROOT_PROJECT;
273         case ResourceKind.LINK:
274             return ContextMenuKind.LINK;
275         case ResourceKind.WORKFLOW:
276             return isEditable ? ContextMenuKind.WORKFLOW : ContextMenuKind.READONLY_WORKFLOW;
277         default:
278             return;
279     }
280 };
281
282 function selectActionsByKind(currentResourceKinds: Array<string>, filterSet: TMultiselectActionsFilters): MultiSelectMenuAction[] {
283     const rawResult: Set<MultiSelectMenuAction> = new Set();
284     const resultNames = new Set();
285     const allFiltersArray: MultiSelectMenuAction[][] = []
286     currentResourceKinds.forEach(kind => {
287         if (filterSet[kind]) {
288             const actions = filterActions(...filterSet[kind]);
289             allFiltersArray.push(actions);
290             actions.forEach(action => {
291                 if (!resultNames.has(action.name)) {
292                     rawResult.add(action);
293                     resultNames.add(action.name);
294                 }
295             });
296         }
297     });
298
299     const filteredNameSet = allFiltersArray.map(filterArray => {
300         const resultSet = new Set<string>();
301         filterArray.forEach(action => resultSet.add(action.name as string || ""));
302         return resultSet;
303     });
304
305     const filteredResult = Array.from(rawResult).filter(action => {
306         for (let i = 0; i < filteredNameSet.length; i++) {
307             if (!filteredNameSet[i].has(action.name as string)) return false;
308         }
309         return true;
310     });
311
312     return filteredResult;
313 }
314
315
316 //--------------------------------------------------//
317
318 function mapStateToProps({auth, multiselect, resources, favorites, publicFavorites, selectedResourceUuid}: RootState) {
319     return {
320         checkedList: multiselect.checkedList as TCheckedList,
321         user: auth && auth.user ? auth.user : null,
322         disabledButtons: new Set<string>(multiselect.disabledButtons),
323         auth,
324         selectedResourceUuid,
325         location: window.location.pathname,
326         iconProps: {
327             resources,
328             favorites,
329             publicFavorites
330         }
331     }
332 }
333
334 function mapDispatchToProps(dispatch: Dispatch) {
335     return {
336         executeMulti: (selectedAction: ContextMenuAction, checkedList: TCheckedList, resources: ResourcesState): void => {
337             const kindGroups = groupByKind(checkedList, resources);
338             const currentList = selectedToArray(checkedList)
339             switch (selectedAction.name) {
340                 case ContextMenuActionNames.MOVE_TO:
341                 case ContextMenuActionNames.REMOVE:
342                     const firstResourceKind = isGroupResource(currentList[0], resources)
343                         ? ContextMenuKind.GROUPS
344                         : (getResource(currentList[0])(resources) as ContainerRequestResource | Resource).kind;
345                     const action = findActionByName(selectedAction.name as string, kindToActionSet[firstResourceKind]);
346                     if (action) action.execute(dispatch, kindGroups[firstResourceKind]);
347                     break;
348                 case ContextMenuActionNames.COPY_LINK_TO_CLIPBOARD:
349                     const selectedResources = currentList.map(uuid => getResource(uuid)(resources));
350                     dispatch<any>(copyToClipboardAction(selectedResources));
351                     break;
352                 default:
353                     for (const kind in kindGroups) {
354                         const action = findActionByName(selectedAction.name as string, kindToActionSet[kind]);
355                         if (action) action.execute(dispatch, kindGroups[kind]);
356                     }
357                     break;
358             }
359         },
360     };
361 }