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