22235: added manageableProject set and unfreezeRequiresAdmin condition
[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, { useMemo } 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     unfreezeRequiresAdmin?: boolean;
81     executeMulti: (action: ContextMenuAction | MultiSelectMenuAction, checkedList: TCheckedList, resources: ResourcesState) => void;
82 };
83
84 type IconProps = {
85     resources: ResourcesState;
86     favorites: FavoritesState;
87     publicFavorites: PublicFavoritesState;
88 }
89
90 const detailsCardPaths = [
91     '/projects',
92 ]
93
94 export const usesDetailsCard = (location: string): boolean => {
95     return detailsCardPaths.some(path => location.includes(path))
96 }
97
98 export const MultiselectToolbar = connect(
99     mapStateToProps,
100     mapDispatchToProps
101 )(
102     withStyles(styles)((props: MultiselectToolbarProps & WithStyles<CssRules>) => {
103         const { classes, checkedList, iconProps, user, disabledButtons, location, forceMultiSelectMode, injectedStyles, unfreezeRequiresAdmin } = props;
104         const selectedResourceArray = selectedToArray(checkedList);
105         const selectedResourceUuid = usesDetailsCard(location) ? props.selectedResourceUuid : selectedResourceArray.length === 1 ? selectedResourceArray[0] : null;
106         const singleResourceKind = selectedResourceUuid && !forceMultiSelectMode ? [resourceToMsResourceKind(selectedResourceUuid, iconProps.resources, user, !!unfreezeRequiresAdmin)] : null
107         const currentResourceKinds = singleResourceKind ? singleResourceKind : Array.from(selectedToKindSet(checkedList, iconProps.resources));
108         const currentPathIsTrash = window.location.pathname === "/trash";
109
110         const rawActions =
111             currentPathIsTrash && selectedToKindSet(checkedList).size
112                 ? [msToggleTrashAction]
113                 : selectActionsByKind(currentResourceKinds as string[], multiselectActionsFilters).filter((action) =>
114                         selectedResourceUuid === null ? action.isForMulti : true
115                     );
116
117         const actions: ContextMenuAction[] | MultiSelectMenuAction[] = sortMenuItems(
118             singleResourceKind && singleResourceKind.length ? (singleResourceKind[0] as ContextMenuKind) : ContextMenuKind.MULTI,
119             rawActions,
120             menuDirection.HORIZONTAL
121         );
122
123         // eslint-disable-next-line
124         const memoizedActions = useMemo(() => actions, [currentResourceKinds, currentPathIsTrash, selectedResourceUuid]);
125
126         const targetResources = selectedResourceUuid ? {[selectedResourceUuid]: true} as TCheckedList : checkedList
127
128         return (
129             <React.Fragment>
130                 <Toolbar
131                     className={classNames(classes.root, injectedStyles)}
132                     style={{ width: `${(memoizedActions.length * 2.5) + 2}rem`, height: '2.5rem'}}
133                     data-cy='multiselect-toolbar'
134                     >
135                     {memoizedActions.length ? (
136                         <IntersectionObserverWrapper 
137                             menuLength={memoizedActions.length}
138                             key={actions.map(a => a.name).join(',')}
139                             >
140                             {memoizedActions.map((action, i) =>{
141                                 const { hasAlts, useAlts, name, altName, icon, altIcon } = action;
142                             return action.name === ContextMenuActionNames.DIVIDER ? (
143                                 action.component && (
144                                     <div
145                                         className={classes.divider}
146                                         data-targetid={`${name}${i}`}
147                                         key={i}
148                                     >
149                                         <action.component />
150                                     </div>
151                                 )
152                             ) : hasAlts ? (
153                                 <span className={classes.iconContainer} data-targetid={name} data-title={(useAlts && useAlts(selectedResourceUuid, iconProps)) ? altName : name}>
154                                     <IconButton
155                                         data-cy='multiselect-button'
156                                         disabled={disabledButtons.has(name)}
157                                         onClick={() => props.executeMulti(action, targetResources, iconProps.resources)}
158                                         className={classes.icon}
159                                         size="large">
160                                         {currentPathIsTrash || (useAlts && useAlts(selectedResourceUuid, iconProps)) ? altIcon && altIcon({}) : icon({})}
161                                     </IconButton>
162                                 </span>
163                             ) : (
164                                 //data-targetid is used to determine what goes to the overflow menu
165                                 //data-title is used to display the tooltip text
166                                 <span className={classes.iconContainer} data-targetid={name} data-title={name}>
167                                     <IconButton
168                                         data-cy='multiselect-button'
169                                         onClick={() => {
170                                             props.executeMulti(action, targetResources, iconProps.resources)}}
171                                         className={classes.icon}
172                                         size="large">
173                                         {action.icon({})}
174                                     </IconButton>
175                                 </span>
176                             );
177                             })}
178                         </IntersectionObserverWrapper>
179                     ) : (
180                         <></>
181                     )}
182                 </Toolbar>
183             </React.Fragment>
184         );
185     })
186 );
187
188 export function selectedToArray(checkedList: TCheckedList): Array<string> {
189     const arrayifiedSelectedList: Array<string> = [];
190     for (const [key, value] of Object.entries(checkedList)) {
191         if (value === true) {
192             arrayifiedSelectedList.push(key);
193         }
194     }
195     return arrayifiedSelectedList;
196 }
197
198 export function selectedToKindSet(checkedList: TCheckedList, resources: ResourcesState = {}): Set<string> {
199     const setifiedList = new Set<string>();
200     for (const [key, value] of Object.entries(checkedList)) {
201         if (value === true) {
202             isGroupResource(key, resources) ? setifiedList.add(ContextMenuKind.GROUPS) : setifiedList.add(extractUuidKind(key) as string);
203         }
204     }
205     return setifiedList;
206 }
207
208 export const isGroupResource = (uuid: string, resources: ResourcesState): boolean => {
209     const resource = getResource(uuid)(resources);
210     if(!resource) return false;
211     return resource.kind === ResourceKind.PROJECT && (resource as GroupResource).groupClass === GroupClass.ROLE;
212 };
213
214 function groupByKind(checkedList: TCheckedList, resources: ResourcesState): Record<string, ContextMenuResource[]> {
215     const result = {};
216     selectedToArray(checkedList).forEach(uuid => {
217         const resource = getResource(uuid)(resources) as ContainerRequestResource | Resource;
218         const kind = isGroupResource(uuid, resources) ? ContextMenuKind.GROUPS : resource.kind;
219         if (!result[kind]) result[kind] = [];
220         result[kind].push(resource);
221     });
222     return result;
223 }
224
225 function filterActions(actionArray: MultiSelectMenuActionSet, filters: Set<string>): Array<MultiSelectMenuAction> {
226     return actionArray[0].filter(action => filters.has(action.name as string));
227 }
228
229 const resourceToMsResourceKind = (uuid: string, resources: ResourcesState, user: User | null, unfreezeRequiresAdmin: boolean, readonly = false ): (ContextMenuKind | ResourceKind) | undefined => {
230     if (!user) return;
231     const resource = getResourceWithEditableStatus<GroupResource & EditableResource>(uuid, user.uuid)(resources);
232     const { isAdmin } = user;
233     const kind = extractUuidKind(uuid);
234
235     const isFrozen = resource?.kind && resource.kind === ResourceKind.PROJECT ? resourceIsFrozen(resource, resources) : false;
236     const isEditable = (user.isAdmin || (resource || ({} as EditableResource)).isEditable) && !readonly && !isFrozen;
237     const { canManage, canWrite } = resource || {};
238
239     switch (kind) {
240         case ResourceKind.PROJECT:
241             if (isFrozen) {
242                 return isAdmin 
243                 ? ContextMenuKind.FROZEN_PROJECT_ADMIN 
244                 : canManage && !unfreezeRequiresAdmin
245                     ? ContextMenuKind.MANAGEABLE_PROJECT
246                     : isEditable 
247                         ? ContextMenuKind.FROZEN_PROJECT
248                         : ContextMenuKind.READONLY_PROJECT;
249             }
250
251             if (isAdmin && !readonly) {
252                 if (resource?.groupClass === GroupClass.FILTER) {
253                     return ContextMenuKind.FILTER_GROUP_ADMIN;
254                 }
255                 if (resource?.groupClass === GroupClass.ROLE) {
256                     return ContextMenuKind.GROUPS;
257                 }
258                 return ContextMenuKind.PROJECT_ADMIN;
259             }
260
261             if(canManage === false && canWrite === true) return ContextMenuKind.WRITEABLE_PROJECT;
262
263             return isEditable
264                 ? resource && resource.groupClass !== GroupClass.FILTER
265                     ? ContextMenuKind.PROJECT
266                     : ContextMenuKind.FILTER_GROUP
267                 : ContextMenuKind.READONLY_PROJECT;
268         case ResourceKind.COLLECTION:
269             const c = getResource<CollectionResource>(uuid)(resources);
270             if (c === undefined) {
271                 return;
272             }
273             const parent = getResource<GroupResource>(c.ownerUuid)(resources);
274             const isWriteable = parent?.canWrite === true && parent.canManage === false;
275             const isOldVersion = c.uuid !== c.currentVersionUuid;
276             const isTrashed = c.isTrashed;
277             return isOldVersion
278                 ? ContextMenuKind.OLD_VERSION_COLLECTION
279                 : isTrashed && isEditable
280                     ? ContextMenuKind.TRASHED_COLLECTION
281                     : isAdmin && isEditable
282                         ? ContextMenuKind.COLLECTION_ADMIN
283                         : isEditable 
284                             ? isWriteable
285                                 ? ContextMenuKind.WRITEABLE_COLLECTION 
286                                 : ContextMenuKind.COLLECTION
287                             : ContextMenuKind.READONLY_COLLECTION;
288         case ResourceKind.PROCESS:
289             return !isEditable
290                 ? ContextMenuKind.READONLY_PROCESS_RESOURCE
291                 : isAdmin
292                     ? resource && isProcessCancelable(getProcess(resource.uuid)(resources) as Process)
293                         ? ContextMenuKind.RUNNING_PROCESS_ADMIN
294                         : ContextMenuKind.PROCESS_ADMIN
295                     : resource && isProcessCancelable(getProcess(resource.uuid)(resources) as Process)
296                         ? ContextMenuKind.RUNNING_PROCESS_RESOURCE
297                         : ContextMenuKind.PROCESS_RESOURCE;
298         case ResourceKind.USER:
299             return isAdmin ? ContextMenuKind.ROOT_PROJECT_ADMIN : ContextMenuKind.ROOT_PROJECT;
300         case ResourceKind.LINK:
301             return ContextMenuKind.LINK;
302         case ResourceKind.WORKFLOW:
303             return isEditable ? ContextMenuKind.WORKFLOW : ContextMenuKind.READONLY_WORKFLOW;
304         default:
305             return;
306     }
307 };
308
309 function selectActionsByKind(currentResourceKinds: Array<string>, filterSet: TMultiselectActionsFilters): MultiSelectMenuAction[] {
310     const rawResult: Set<MultiSelectMenuAction> = new Set();
311     const resultNames = new Set();
312     const allFiltersArray: MultiSelectMenuAction[][] = []
313     currentResourceKinds.forEach(kind => {
314         if (filterSet[kind]) {
315             const actions = filterActions(...filterSet[kind]);
316             allFiltersArray.push(actions);
317             actions.forEach(action => {
318                 if (!resultNames.has(action.name)) {
319                     rawResult.add(action);
320                     resultNames.add(action.name);
321                 }
322             });
323         }
324     });
325
326     const filteredNameSet = allFiltersArray.map(filterArray => {
327         const resultSet = new Set<string>();
328         filterArray.forEach(action => resultSet.add(action.name as string || ""));
329         return resultSet;
330     });
331
332     const filteredResult = Array.from(rawResult).filter(action => {
333         for (let i = 0; i < filteredNameSet.length; i++) {
334             if (!filteredNameSet[i].has(action.name as string)) return false;
335         }
336         return true;
337     });
338
339     return filteredResult;
340 }
341
342
343 //--------------------------------------------------//
344
345 function mapStateToProps({auth, multiselect, resources, favorites, publicFavorites, selectedResourceUuid}: RootState) {
346     return {
347         checkedList: multiselect.checkedList as TCheckedList,
348         user: auth && auth.user ? auth.user : null,
349         disabledButtons: new Set<string>(multiselect.disabledButtons),
350         auth,
351         selectedResourceUuid,
352         location: window.location.pathname,
353         unfreezeRequiresAdmin: auth.remoteHostsConfig[auth.homeCluster]?.clusterConfig?.API?.UnfreezeProjectRequiresAdmin,
354         iconProps: {
355             resources,
356             favorites,
357             publicFavorites
358         }
359     }
360 }
361
362 function mapDispatchToProps(dispatch: Dispatch) {
363     return {
364         executeMulti: (selectedAction: ContextMenuAction, checkedList: TCheckedList, resources: ResourcesState): void => {
365             const kindGroups = groupByKind(checkedList, resources);
366             const currentList = selectedToArray(checkedList)
367             switch (selectedAction.name) {
368                 case ContextMenuActionNames.MOVE_TO:
369                 case ContextMenuActionNames.REMOVE:
370                     const firstResourceKind = isGroupResource(currentList[0], resources) 
371                         ? ContextMenuKind.GROUPS 
372                         : (getResource(currentList[0])(resources) as ContainerRequestResource | Resource).kind;
373                     const action = findActionByName(selectedAction.name as string, kindToActionSet[firstResourceKind]);
374                     if (action) action.execute(dispatch, kindGroups[firstResourceKind]);
375                     break;
376                 case ContextMenuActionNames.COPY_LINK_TO_CLIPBOARD:
377                     const selectedResources = currentList.map(uuid => getResource(uuid)(resources));
378                     dispatch<any>(copyToClipboardAction(selectedResources));
379                     break;
380                 default:
381                     for (const kind in kindGroups) {
382                         const action = findActionByName(selectedAction.name as string, kindToActionSet[kind]);
383                         if (action) action.execute(dispatch, kindGroups[kind]);
384                     }
385                     break;
386             }
387         },
388     };
389 }