Merge branch '21900-groups-panel-toolbar'
[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 { StyleRulesCallback, withStyles, WithStyles, Toolbar, Tooltip, IconButton } from "@material-ui/core";
8 import { ArvadosTheme } from "common/custom-theme";
9 import { RootState } from "store/store";
10 import { Dispatch } from "redux";
11 import { TCheckedList } from "components/data-table/data-table";
12 import { ContextMenuResource } from "store/context-menu/context-menu-actions";
13 import { Resource, ResourceKind, extractUuidKind } from "models/resource";
14 import { getResource } from "store/resources/resources";
15 import { ResourcesState } from "store/resources/resources";
16 import { MultiSelectMenuAction, MultiSelectMenuActionSet } from "views-components/multiselect-toolbar/ms-menu-actions";
17 import { ContextMenuAction, ContextMenuActionNames } from "views-components/context-menu/context-menu-action-set";
18 import { multiselectActionsFilters, TMultiselectActionsFilters } from "./ms-toolbar-action-filters";
19 import { kindToActionSet, findActionByName } from "./ms-kind-action-differentiator";
20 import { msToggleTrashAction } from "views-components/multiselect-toolbar/ms-project-action-set";
21 import { copyToClipboardAction } from "store/open-in-new-tab/open-in-new-tab.actions";
22 import { ContainerRequestResource } from "models/container-request";
23 import { FavoritesState } from "store/favorites/favorites-reducer";
24 import { resourceIsFrozen } from "common/frozen-resources";
25 import { getResourceWithEditableStatus } from "store/resources/resources";
26 import { GroupResource } from "models/group";
27 import { EditableResource } from "models/resource";
28 import { User } from "models/user";
29 import { GroupClass } from "models/group";
30 import { isProcessCancelable } from "store/processes/process";
31 import { CollectionResource } from "models/collection";
32 import { getProcess } from "store/processes/process";
33 import { Process } from "store/processes/process";
34 import { PublicFavoritesState } from "store/public-favorites/public-favorites-reducer";
35 import { AuthState } from "store/auth/auth-reducer";
36 import { IntersectionObserverWrapper } from "./ms-toolbar-overflow-wrapper";
37 import classNames from "classnames";
38 import { ContextMenuKind, sortMenuItems, menuDirection } from 'views-components/context-menu/menu-item-sort';
39
40 type CssRules = "root" | "button" | "iconContainer" | "icon" | "divider";
41
42 const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
43     root: {
44         display: "flex",
45         flexDirection: "row",
46         width: 0,
47         height: '2.5rem',
48         padding: 0,
49         margin: 0,
50         overflow: 'hidden',
51     },
52     button: {
53         width: "2.5rem",
54         height: "2.5rem ",
55         paddingLeft: 0,
56         border: "1px solid transparent",
57     },
58     iconContainer: {
59         height: '100%',
60     },
61     icon: {
62         marginLeft: '-0.5rem',
63     },
64     divider: {
65         display: "flex",
66         alignItems: "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`}}
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                                 <Tooltip
147                                     className={classes.button}
148                                     data-targetid={name}
149                                     title={currentPathIsTrash || (useAlts && useAlts(selectedResourceUuid, iconProps)) ? altName : name}
150                                     key={i}
151                                     disableFocusListener
152                                 >
153                                     <span className={classes.iconContainer}>
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                                         >
160                                             {currentPathIsTrash || (useAlts && useAlts(selectedResourceUuid, iconProps)) ? altIcon && altIcon({}) : icon({})}
161                                         </IconButton>
162                                     </span>
163                                 </Tooltip>
164                             ) : (
165                                 <Tooltip
166                                     className={classes.button}
167                                     data-targetid={name}
168                                     title={action.name}
169                                     key={i}
170                                     disableFocusListener
171                                 >
172                                     <span className={classes.iconContainer}>
173                                         <IconButton
174                                             data-cy='multiselect-button'
175                                             onClick={() => {
176                                                 props.executeMulti(action, targetResources, iconProps.resources)}}
177                                             className={classes.icon}
178                                         >
179                                             {action.icon({})}
180                                         </IconButton>
181                                     </span>
182                                 </Tooltip>
183                             );
184                             })}
185                         </IntersectionObserverWrapper>
186                     ) : (
187                         <></>
188                     )}
189                 </Toolbar>
190             </React.Fragment>
191         )
192     })
193 );
194
195 export function selectedToArray(checkedList: TCheckedList): Array<string> {
196     const arrayifiedSelectedList: Array<string> = [];
197     for (const [key, value] of Object.entries(checkedList)) {
198         if (value === true) {
199             arrayifiedSelectedList.push(key);
200         }
201     }
202     return arrayifiedSelectedList;
203 }
204
205 export function selectedToKindSet(checkedList: TCheckedList, resources: ResourcesState = {}): Set<string> {
206     const setifiedList = new Set<string>();
207     for (const [key, value] of Object.entries(checkedList)) {
208         if (value === true) {
209             isGroupResource(key, resources) ? setifiedList.add(ContextMenuKind.GROUPS) : setifiedList.add(extractUuidKind(key) as string);
210         }
211     }
212     return setifiedList;
213 }
214
215 export const isGroupResource = (uuid: string, resources: ResourcesState): boolean => {
216     const resource = getResource(uuid)(resources);
217     if(!resource) return false;
218     return resource.kind === ResourceKind.PROJECT && (resource as GroupResource).groupClass === GroupClass.ROLE;
219 };
220
221 function groupByKind(checkedList: TCheckedList, resources: ResourcesState): Record<string, ContextMenuResource[]> {
222     const result = {};
223     selectedToArray(checkedList).forEach(uuid => {
224         const resource = getResource(uuid)(resources) as ContainerRequestResource | Resource;
225         const kind = isGroupResource(uuid, resources) ? ContextMenuKind.GROUPS : resource.kind;
226         if (!result[kind]) result[kind] = [];
227         result[kind].push(resource);
228     });
229     return result;
230 }
231
232 function filterActions(actionArray: MultiSelectMenuActionSet, filters: Set<string>): Array<MultiSelectMenuAction> {
233     return actionArray[0].filter(action => filters.has(action.name as string));
234 }
235
236 const resourceToMsResourceKind = (uuid: string, resources: ResourcesState, user: User | null, readonly = false): (ContextMenuKind | ResourceKind) | undefined => {
237     if (!user) return;
238     const resource = getResourceWithEditableStatus<GroupResource & EditableResource>(uuid, user.uuid)(resources);
239     const { isAdmin } = user;
240     const kind = extractUuidKind(uuid);
241
242     const isFrozen = resource?.kind && resource.kind === ResourceKind.PROJECT ? resourceIsFrozen(resource, resources) : false;
243     const isEditable = (user.isAdmin || (resource || ({} as EditableResource)).isEditable) && !readonly && !isFrozen;
244
245     switch (kind) {
246         case ResourceKind.PROJECT:
247             if (isFrozen) {
248                 return isAdmin ? ContextMenuKind.FROZEN_PROJECT_ADMIN : ContextMenuKind.FROZEN_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             return isEditable
262                 ? resource && resource.groupClass !== GroupClass.FILTER
263                     ? ContextMenuKind.PROJECT
264                     : ContextMenuKind.FILTER_GROUP
265                 : ContextMenuKind.READONLY_PROJECT;
266         case ResourceKind.COLLECTION:
267             const c = getResource<CollectionResource>(uuid)(resources);
268             if (c === undefined) {
269                 return;
270             }
271             const isOldVersion = c.uuid !== c.currentVersionUuid;
272             const isTrashed = c.isTrashed;
273             return isOldVersion
274                 ? ContextMenuKind.OLD_VERSION_COLLECTION
275                 : isTrashed && isEditable
276                 ? ContextMenuKind.TRASHED_COLLECTION
277                 : isAdmin && isEditable
278                 ? ContextMenuKind.COLLECTION_ADMIN
279                 : isEditable
280                 ? ContextMenuKind.COLLECTION
281                 : ContextMenuKind.READONLY_COLLECTION;
282         case ResourceKind.PROCESS:
283             return isAdmin && isEditable
284                 ? resource && isProcessCancelable(getProcess(resource.uuid)(resources) as Process)
285                     ? ContextMenuKind.RUNNING_PROCESS_ADMIN
286                     : ContextMenuKind.PROCESS_ADMIN
287                 : readonly
288                 ? ContextMenuKind.READONLY_PROCESS_RESOURCE
289                 : resource && isProcessCancelable(getProcess(resource.uuid)(resources) as Process)
290                 ? ContextMenuKind.RUNNING_PROCESS_RESOURCE
291                 : ContextMenuKind.PROCESS_RESOURCE;
292         case ResourceKind.USER:
293             return isAdmin ? ContextMenuKind.ROOT_PROJECT_ADMIN : ContextMenuKind.ROOT_PROJECT;
294         case ResourceKind.LINK:
295             return ContextMenuKind.LINK;
296         case ResourceKind.WORKFLOW:
297             return isEditable ? ContextMenuKind.WORKFLOW : ContextMenuKind.READONLY_WORKFLOW;
298         default:
299             return;
300     }
301 };
302
303 function selectActionsByKind(currentResourceKinds: Array<string>, filterSet: TMultiselectActionsFilters): MultiSelectMenuAction[] {
304     const rawResult: Set<MultiSelectMenuAction> = new Set();
305     const resultNames = new Set();
306     const allFiltersArray: MultiSelectMenuAction[][] = []
307     currentResourceKinds.forEach(kind => {
308         if (filterSet[kind]) {
309             const actions = filterActions(...filterSet[kind]);
310             allFiltersArray.push(actions);
311             actions.forEach(action => {
312                 if (!resultNames.has(action.name)) {
313                     rawResult.add(action);
314                     resultNames.add(action.name);
315                 }
316             });
317         }
318     });
319
320     const filteredNameSet = allFiltersArray.map(filterArray => {
321         const resultSet = new Set<string>();
322         filterArray.forEach(action => resultSet.add(action.name as string || ""));
323         return resultSet;
324     });
325
326     const filteredResult = Array.from(rawResult).filter(action => {
327         for (let i = 0; i < filteredNameSet.length; i++) {
328             if (!filteredNameSet[i].has(action.name as string)) return false;
329         }
330         return true;
331     });
332
333     return filteredResult;
334 }
335
336
337 //--------------------------------------------------//
338
339 function mapStateToProps({auth, multiselect, resources, favorites, publicFavorites, selectedResourceUuid}: RootState) {
340     return {
341         checkedList: multiselect.checkedList as TCheckedList,
342         user: auth && auth.user ? auth.user : null,
343         disabledButtons: new Set<string>(multiselect.disabledButtons),
344         auth,
345         selectedResourceUuid,
346         location: window.location.pathname,
347         iconProps: {
348             resources,
349             favorites,
350             publicFavorites
351         }
352     }
353 }
354
355 function mapDispatchToProps(dispatch: Dispatch) {
356     return {
357         executeMulti: (selectedAction: ContextMenuAction, checkedList: TCheckedList, resources: ResourcesState): void => {
358             const kindGroups = groupByKind(checkedList, resources);
359             const currentList = selectedToArray(checkedList)
360             switch (selectedAction.name) {
361                 case ContextMenuActionNames.MOVE_TO:
362                 case ContextMenuActionNames.REMOVE:
363                     const firstResourceKind = isGroupResource(currentList[0], resources) 
364                         ? ContextMenuKind.GROUPS 
365                         : (getResource(currentList[0])(resources) as ContainerRequestResource | Resource).kind;
366                     const action = findActionByName(selectedAction.name as string, kindToActionSet[firstResourceKind]);
367                     if (action) action.execute(dispatch, kindGroups[firstResourceKind]);
368                     break;
369                 case ContextMenuActionNames.COPY_LINK_TO_CLIPBOARD:
370                     const selectedResources = currentList.map(uuid => getResource(uuid)(resources));
371                     dispatch<any>(copyToClipboardAction(selectedResources));
372                     break;
373                 default:
374                     for (const kind in kindGroups) {
375                         const action = findActionByName(selectedAction.name as string, kindToActionSet[kind]);
376                         if (action) action.execute(dispatch, kindGroups[kind]);
377                     }
378                     break;
379             }
380         },
381     };
382 }