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