Merge branch 'main' from workbench2.git
[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, extractUuidKind } from "models/resource";
14 import { getResource } from "store/resources/resources";
15 import { ResourcesState } from "store/resources/resources";
16 import { ContextMenuAction, ContextMenuActionSet } from "views-components/context-menu/context-menu-action-set";
17 import { RestoreFromTrashIcon, TrashIcon } from "components/icon/icon";
18 import { multiselectActionsFilters, TMultiselectActionsFilters, contextMenuActionConsts } 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
24 type CssRules = "root" | "button";
25
26 const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
27     root: {
28         display: "flex",
29         flexDirection: "row",
30         width: 0,
31         padding: 0,
32         margin: "1rem auto auto 0.5rem",
33         overflow: "hidden",
34         transition: "width 150ms",
35     },
36     button: {
37         width: "2.5rem",
38         height: "2.5rem ",
39     },
40 });
41
42 export type MultiselectToolbarProps = {
43     checkedList: TCheckedList;
44     resources: ResourcesState;
45     executeMulti: (action: ContextMenuAction, checkedList: TCheckedList, resources: ResourcesState) => void;
46 };
47
48 export const MultiselectToolbar = connect(
49     mapStateToProps,
50     mapDispatchToProps
51 )(
52     withStyles(styles)((props: MultiselectToolbarProps & WithStyles<CssRules>) => {
53         const { classes, checkedList } = props;
54         const currentResourceKinds = Array.from(selectedToKindSet(checkedList));
55
56         const currentPathIsTrash = window.location.pathname === "/trash";
57         const buttons =
58             currentPathIsTrash && selectedToKindSet(checkedList).size
59                 ? [msToggleTrashAction]
60                 : selectActionsByKind(currentResourceKinds, multiselectActionsFilters);
61
62         return (
63             <React.Fragment>
64                 <Toolbar
65                     className={classes.root}
66                     style={{ width: `${buttons.length * 2.5}rem` }}
67                 >
68                     {buttons.length ? (
69                         buttons.map((btn, i) =>
70                             btn.name === "ToggleTrashAction" ? (
71                                 <Tooltip
72                                     className={classes.button}
73                                     title={currentPathIsTrash ? "Restore selected" : "Move to trash"}
74                                     key={i}
75                                     disableFocusListener
76                                 >
77                                     <IconButton onClick={() => props.executeMulti(btn, checkedList, props.resources)}>
78                                         {currentPathIsTrash ? <RestoreFromTrashIcon /> : <TrashIcon />}
79                                     </IconButton>
80                                 </Tooltip>
81                             ) : (
82                                 <Tooltip
83                                     className={classes.button}
84                                     title={btn.name}
85                                     key={i}
86                                     disableFocusListener
87                                 >
88                                     <IconButton onClick={() => props.executeMulti(btn, checkedList, props.resources)}>
89                                         {btn.icon ? btn.icon({}) : <></>}
90                                     </IconButton>
91                                 </Tooltip>
92                             )
93                         )
94                     ) : (
95                         <></>
96                     )}
97                 </Toolbar>
98             </React.Fragment>
99         );
100     })
101 );
102
103 export function selectedToArray(checkedList: TCheckedList): Array<string> {
104     const arrayifiedSelectedList: Array<string> = [];
105     for (const [key, value] of Object.entries(checkedList)) {
106         if (value === true) {
107             arrayifiedSelectedList.push(key);
108         }
109     }
110     return arrayifiedSelectedList;
111 }
112
113 export function selectedToKindSet(checkedList: TCheckedList): Set<string> {
114     const setifiedList = new Set<string>();
115     for (const [key, value] of Object.entries(checkedList)) {
116         if (value === true) {
117             setifiedList.add(extractUuidKind(key) as string);
118         }
119     }
120     return setifiedList;
121 }
122
123 function groupByKind(checkedList: TCheckedList, resources: ResourcesState): Record<string, ContextMenuResource[]> {
124     const result = {};
125     selectedToArray(checkedList).forEach(uuid => {
126         const resource = getResource(uuid)(resources) as ContainerRequestResource | Resource;
127         if (!result[resource.kind]) result[resource.kind] = [];
128         result[resource.kind].push(resource);
129     });
130     return result;
131 }
132
133 function filterActions(actionArray: ContextMenuActionSet, filters: Set<string>): Array<ContextMenuAction> {
134     return actionArray[0].filter(action => filters.has(action.name as string));
135 }
136
137 function selectActionsByKind(currentResourceKinds: Array<string>, filterSet: TMultiselectActionsFilters) {
138     const rawResult: Set<ContextMenuAction> = new Set();
139     const resultNames = new Set();
140     const allFiltersArray: ContextMenuAction[][] = [];
141     currentResourceKinds.forEach(kind => {
142         if (filterSet[kind]) {
143             const actions = filterActions(...filterSet[kind]);
144             allFiltersArray.push(actions);
145             actions.forEach(action => {
146                 if (!resultNames.has(action.name)) {
147                     rawResult.add(action);
148                     resultNames.add(action.name);
149                 }
150             });
151         }
152     });
153
154     const filteredNameSet = allFiltersArray.map(filterArray => {
155         const resultSet = new Set();
156         filterArray.forEach(action => resultSet.add(action.name || ""));
157         return resultSet;
158     });
159
160     const filteredResult = Array.from(rawResult).filter(action => {
161         for (let i = 0; i < filteredNameSet.length; i++) {
162             if (!filteredNameSet[i].has(action.name)) return false;
163         }
164         return true;
165     });
166
167     return filteredResult.sort((a, b) => {
168         const nameA = a.name || "";
169         const nameB = b.name || "";
170         if (nameA < nameB) {
171             return -1;
172         }
173         if (nameA > nameB) {
174             return 1;
175         }
176         return 0;
177     });
178 }
179
180 //--------------------------------------------------//
181
182 function mapStateToProps(state: RootState) {
183     return {
184         checkedList: state.multiselect.checkedList as TCheckedList,
185         resources: state.resources,
186     };
187 }
188
189 function mapDispatchToProps(dispatch: Dispatch) {
190     return {
191         executeMulti: (selectedAction: ContextMenuAction, checkedList: TCheckedList, resources: ResourcesState): void => {
192             const kindGroups = groupByKind(checkedList, resources);
193             switch (selectedAction.name) {
194                 case contextMenuActionConsts.MOVE_TO:
195                 case contextMenuActionConsts.REMOVE:
196                     const firstResource = getResource(selectedToArray(checkedList)[0])(resources) as ContainerRequestResource | Resource;
197                     const action = findActionByName(selectedAction.name as string, kindToActionSet[firstResource.kind]);
198                     if (action) action.execute(dispatch, kindGroups[firstResource.kind]);
199                     break;
200                 case contextMenuActionConsts.COPY_TO_CLIPBOARD:
201                     const selectedResources = selectedToArray(checkedList).map(uuid => getResource(uuid)(resources));
202                     dispatch<any>(copyToClipboardAction(selectedResources));
203                     break;
204                 default:
205                     for (const kind in kindGroups) {
206                         const action = findActionByName(selectedAction.name as string, kindToActionSet[kind]);
207                         if (action) action.execute(dispatch, kindGroups[kind]);
208                     }
209                     break;
210             }
211         },
212     };
213 }