22235: differentiated frozen manageable projects
[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 
245                     ? unfreezeRequiresAdmin
246                         ? ContextMenuKind.MANAGEABLE_PROJECT
247                         : ContextMenuKind.FROZEN_MANAGEABLE_PROJECT
248                     : isEditable 
249                         ? ContextMenuKind.FROZEN_PROJECT
250                         : ContextMenuKind.READONLY_PROJECT;
251             }
252
253             if (isAdmin && !readonly) {
254                 if (resource?.groupClass === GroupClass.FILTER) {
255                     return ContextMenuKind.FILTER_GROUP_ADMIN;
256                 }
257                 if (resource?.groupClass === GroupClass.ROLE) {
258                     return ContextMenuKind.GROUPS;
259                 }
260                 return ContextMenuKind.PROJECT_ADMIN;
261             }
262
263             if(canManage === false && canWrite === true) return ContextMenuKind.WRITEABLE_PROJECT;
264
265             return isEditable
266                 ? resource && resource.groupClass !== GroupClass.FILTER
267                     ? ContextMenuKind.PROJECT
268                     : ContextMenuKind.FILTER_GROUP
269                 : ContextMenuKind.READONLY_PROJECT;
270         case ResourceKind.COLLECTION:
271             const c = getResource<CollectionResource>(uuid)(resources);
272             if (c === undefined) {
273                 return;
274             }
275             const parent = getResource<GroupResource>(c.ownerUuid)(resources);
276             const isWriteable = parent?.canWrite === true && parent.canManage === false;
277             const isOldVersion = c.uuid !== c.currentVersionUuid;
278             const isTrashed = c.isTrashed;
279             return isOldVersion
280                 ? ContextMenuKind.OLD_VERSION_COLLECTION
281                 : isTrashed && isEditable
282                     ? ContextMenuKind.TRASHED_COLLECTION
283                     : isAdmin && isEditable
284                         ? ContextMenuKind.COLLECTION_ADMIN
285                         : isEditable 
286                             ? isWriteable
287                                 ? ContextMenuKind.WRITEABLE_COLLECTION 
288                                 : ContextMenuKind.COLLECTION
289                             : ContextMenuKind.READONLY_COLLECTION;
290         case ResourceKind.PROCESS:
291             return !isEditable
292                 ? ContextMenuKind.READONLY_PROCESS_RESOURCE
293                 : isAdmin
294                     ? resource && isProcessCancelable(getProcess(resource.uuid)(resources) as Process)
295                         ? ContextMenuKind.RUNNING_PROCESS_ADMIN
296                         : ContextMenuKind.PROCESS_ADMIN
297                     : resource && isProcessCancelable(getProcess(resource.uuid)(resources) as Process)
298                         ? ContextMenuKind.RUNNING_PROCESS_RESOURCE
299                         : ContextMenuKind.PROCESS_RESOURCE;
300         case ResourceKind.USER:
301             return isAdmin ? ContextMenuKind.ROOT_PROJECT_ADMIN : ContextMenuKind.ROOT_PROJECT;
302         case ResourceKind.LINK:
303             return ContextMenuKind.LINK;
304         case ResourceKind.WORKFLOW:
305             return isEditable ? ContextMenuKind.WORKFLOW : ContextMenuKind.READONLY_WORKFLOW;
306         default:
307             return;
308     }
309 };
310
311 function selectActionsByKind(currentResourceKinds: Array<string>, filterSet: TMultiselectActionsFilters): MultiSelectMenuAction[] {
312     const rawResult: Set<MultiSelectMenuAction> = new Set();
313     const resultNames = new Set();
314     const allFiltersArray: MultiSelectMenuAction[][] = []
315     currentResourceKinds.forEach(kind => {
316         if (filterSet[kind]) {
317             const actions = filterActions(...filterSet[kind]);
318             allFiltersArray.push(actions);
319             actions.forEach(action => {
320                 if (!resultNames.has(action.name)) {
321                     rawResult.add(action);
322                     resultNames.add(action.name);
323                 }
324             });
325         }
326     });
327
328     const filteredNameSet = allFiltersArray.map(filterArray => {
329         const resultSet = new Set<string>();
330         filterArray.forEach(action => resultSet.add(action.name as string || ""));
331         return resultSet;
332     });
333
334     const filteredResult = Array.from(rawResult).filter(action => {
335         for (let i = 0; i < filteredNameSet.length; i++) {
336             if (!filteredNameSet[i].has(action.name as string)) return false;
337         }
338         return true;
339     });
340
341     return filteredResult;
342 }
343
344
345 //--------------------------------------------------//
346
347 function mapStateToProps({auth, multiselect, resources, favorites, publicFavorites, selectedResourceUuid}: RootState) {
348     return {
349         checkedList: multiselect.checkedList as TCheckedList,
350         user: auth && auth.user ? auth.user : null,
351         disabledButtons: new Set<string>(multiselect.disabledButtons),
352         auth,
353         selectedResourceUuid,
354         location: window.location.pathname,
355         unfreezeRequiresAdmin: auth.remoteHostsConfig[auth.homeCluster]?.clusterConfig?.API?.UnfreezeProjectRequiresAdmin,
356         iconProps: {
357             resources,
358             favorites,
359             publicFavorites
360         }
361     }
362 }
363
364 function mapDispatchToProps(dispatch: Dispatch) {
365     return {
366         executeMulti: (selectedAction: ContextMenuAction, checkedList: TCheckedList, resources: ResourcesState): void => {
367             const kindGroups = groupByKind(checkedList, resources);
368             const currentList = selectedToArray(checkedList)
369             switch (selectedAction.name) {
370                 case ContextMenuActionNames.MOVE_TO:
371                 case ContextMenuActionNames.REMOVE:
372                     const firstResourceKind = isGroupResource(currentList[0], resources) 
373                         ? ContextMenuKind.GROUPS 
374                         : (getResource(currentList[0])(resources) as ContainerRequestResource | Resource).kind;
375                     const action = findActionByName(selectedAction.name as string, kindToActionSet[firstResourceKind]);
376                     if (action) action.execute(dispatch, kindGroups[firstResourceKind]);
377                     break;
378                 case ContextMenuActionNames.COPY_LINK_TO_CLIPBOARD:
379                     const selectedResources = currentList.map(uuid => getResource(uuid)(resources));
380                     dispatch<any>(copyToClipboardAction(selectedResources));
381                     break;
382                 default:
383                     for (const kind in kindGroups) {
384                         const action = findActionByName(selectedAction.name as string, kindToActionSet[kind]);
385                         if (action) action.execute(dispatch, kindGroups[kind]);
386                     }
387                     break;
388             }
389         },
390     };
391 }