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