Merge branch '21846-rightclick-context-menu'
[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 disallowedPaths = [
90     "/favorites",
91     "/public-favorites",
92     "/trash",
93     "/group",
94 ]
95
96 const isPathDisallowed = (location: string): boolean => {
97     return disallowedPaths.some(path => location.includes(path))
98 }
99
100 export const MultiselectToolbar = connect(
101     mapStateToProps,
102     mapDispatchToProps
103 )(
104     withStyles(styles)((props: MultiselectToolbarProps & WithStyles<CssRules>) => {
105         const { classes, checkedList, iconProps, user, disabledButtons, location, forceMultiSelectMode, injectedStyles } = props;
106         const selectedResourceUuid = isPathDisallowed(location) ? null : props.selectedResourceUuid;
107         const singleResourceKind = selectedResourceUuid && !forceMultiSelectMode ? [resourceToMsResourceKind(selectedResourceUuid, iconProps.resources, user)] : null
108         const currentResourceKinds = singleResourceKind ? singleResourceKind : Array.from(selectedToKindSet(checkedList));
109         const currentPathIsTrash = window.location.pathname === "/trash";
110
111         const rawActions =
112             currentPathIsTrash && selectedToKindSet(checkedList).size
113                 ? [msToggleTrashAction]
114                 : selectActionsByKind(currentResourceKinds as string[], multiselectActionsFilters).filter((action) =>
115                         selectedResourceUuid === null ? action.isForMulti : true
116                     );
117
118         const actions: ContextMenuAction[] | MultiSelectMenuAction[] = sortMenuItems(
119             singleResourceKind && singleResourceKind.length ? (singleResourceKind[0] as ContextMenuKind) : ContextMenuKind.MULTI,
120             rawActions,
121             menuDirection.HORIZONTAL
122         );
123
124         const targetResources = selectedResourceUuid ? {[selectedResourceUuid]: true} as TCheckedList : checkedList
125
126         return (
127             <React.Fragment>
128                 <Toolbar
129                     className={classNames(classes.root, injectedStyles)}
130                     style={{ width: `${(actions.length * 2.5) + 2}rem`}}
131                     data-cy='multiselect-toolbar'
132                     >
133                     {actions.length ? (
134                         <IntersectionObserverWrapper menuLength={actions.length}>
135                             {actions.map((action, i) =>{
136                                 const { hasAlts, useAlts, name, altName, icon, altIcon } = action;
137                             return action.name === ContextMenuActionNames.DIVIDER ? (
138                                 action.component && (
139                                     <div
140                                         className={classes.divider}
141                                         data-targetid={`${name}${i}`}
142                                         key={i}
143                                     >
144                                         <action.component />
145                                     </div>
146                                 )
147                             ) : hasAlts ? (
148                                 <Tooltip
149                                     className={classes.button}
150                                     data-targetid={name}
151                                     title={currentPathIsTrash || (useAlts && useAlts(selectedResourceUuid, iconProps)) ? altName : name}
152                                     key={i}
153                                     disableFocusListener
154                                 >
155                                     <span className={classes.iconContainer}>
156                                         <IconButton
157                                             data-cy='multiselect-button'
158                                             disabled={disabledButtons.has(name)}
159                                             onClick={() => props.executeMulti(action, targetResources, iconProps.resources)}
160                                             className={classes.icon}
161                                         >
162                                             {currentPathIsTrash || (useAlts && useAlts(selectedResourceUuid, iconProps)) ? altIcon && altIcon({}) : icon({})}
163                                         </IconButton>
164                                     </span>
165                                 </Tooltip>
166                             ) : (
167                                 <Tooltip
168                                     className={classes.button}
169                                     data-targetid={name}
170                                     title={action.name}
171                                     key={i}
172                                     disableFocusListener
173                                 >
174                                     <span className={classes.iconContainer}>
175                                         <IconButton
176                                             data-cy='multiselect-button'
177                                             onClick={() => {
178                                                 props.executeMulti(action, targetResources, iconProps.resources)}}
179                                             className={classes.icon}
180                                         >
181                                             {action.icon({})}
182                                         </IconButton>
183                                     </span>
184                                 </Tooltip>
185                             );
186                             })}
187                         </IntersectionObserverWrapper>
188                     ) : (
189                         <></>
190                     )}
191                 </Toolbar>
192             </React.Fragment>
193         )
194     })
195 );
196
197 export function selectedToArray(checkedList: TCheckedList): Array<string> {
198     const arrayifiedSelectedList: Array<string> = [];
199     for (const [key, value] of Object.entries(checkedList)) {
200         if (value === true) {
201             arrayifiedSelectedList.push(key);
202         }
203     }
204     return arrayifiedSelectedList;
205 }
206
207 export function selectedToKindSet(checkedList: TCheckedList): Set<string> {
208     const setifiedList = new Set<string>();
209     for (const [key, value] of Object.entries(checkedList)) {
210         if (value === true) {
211             setifiedList.add(extractUuidKind(key) as string);
212         }
213     }
214     return setifiedList;
215 }
216
217 function groupByKind(checkedList: TCheckedList, resources: ResourcesState): Record<string, ContextMenuResource[]> {
218     const result = {};
219     selectedToArray(checkedList).forEach(uuid => {
220         const resource = getResource(uuid)(resources) as ContainerRequestResource | Resource;
221         if (!result[resource.kind]) result[resource.kind] = [];
222         result[resource.kind].push(resource);
223     });
224     return result;
225 }
226
227 function filterActions(actionArray: MultiSelectMenuActionSet, filters: Set<string>): Array<MultiSelectMenuAction> {
228     return actionArray[0].filter(action => filters.has(action.name as string));
229 }
230
231 const resourceToMsResourceKind = (uuid: string, resources: ResourcesState, user: User | null, readonly = false): (ContextMenuKind | ResourceKind) | undefined => {
232     if (!user) return;
233     const resource = getResourceWithEditableStatus<GroupResource & EditableResource>(uuid, user.uuid)(resources);
234     const { isAdmin } = user;
235     const kind = extractUuidKind(uuid);
236
237     const isFrozen = resource?.kind && resource.kind === ResourceKind.PROJECT ? resourceIsFrozen(resource, resources) : false;
238     const isEditable = (user.isAdmin || (resource || ({} as EditableResource)).isEditable) && !readonly && !isFrozen;
239
240     switch (kind) {
241         case ResourceKind.PROJECT:
242             if (isFrozen) {
243                 return isAdmin ? ContextMenuKind.FROZEN_PROJECT_ADMIN : ContextMenuKind.FROZEN_PROJECT;
244             }
245
246             return isAdmin && !readonly
247                 ? resource && resource.groupClass !== GroupClass.FILTER
248                     ? ContextMenuKind.PROJECT_ADMIN
249                     : ContextMenuKind.FILTER_GROUP_ADMIN
250                 : 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 isAdmin && isEditable
273                 ? resource && isProcessCancelable(getProcess(resource.uuid)(resources) as Process)
274                     ? ContextMenuKind.RUNNING_PROCESS_ADMIN
275                     : ContextMenuKind.PROCESS_ADMIN
276                 : readonly
277                 ? ContextMenuKind.READONLY_PROCESS_RESOURCE
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 firstResource = getResource(currentList[0])(resources) as ContainerRequestResource | Resource;
353                     const action = findActionByName(selectedAction.name as string, kindToActionSet[firstResource.kind]);
354                     if (action) action.execute(dispatch, kindGroups[firstResource.kind]);
355                     break;
356                 case ContextMenuActionNames.COPY_LINK_TO_CLIPBOARD:
357                     const selectedResources = currentList.map(uuid => getResource(uuid)(resources));
358                     dispatch<any>(copyToClipboardAction(selectedResources));
359                     break;
360                 default:
361                     for (const kind in kindGroups) {
362                         const action = findActionByName(selectedAction.name as string, kindToActionSet[kind]);
363                         if (action) action.execute(dispatch, kindGroups[kind]);
364                     }
365                     break;
366             }
367         },
368     };
369 }