15768: button filtering algo works badly Arvados-DCO-1.1-Signed-off-by: Lisa Knox...
[arvados.git] / src / components / multiselectToolbar / 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 { openRemoveProcessDialog, openRemoveManyProcessesDialog } from 'store/processes/processes-actions';
13 import { processResourceActionSet } from '../../views-components/context-menu/action-sets/process-resource-action-set';
14 import { ContextMenuResource } from 'store/context-menu/context-menu-actions';
15 import { Resource, extractUuidKind } from 'models/resource';
16 import { openMoveProcessDialog } from 'store/processes/process-move-actions';
17 import { openCopyProcessDialog, openCopyManyProcessesDialog } from 'store/processes/process-copy-actions';
18 import { getResource } from 'store/resources/resources';
19 import { ResourcesState } from 'store/resources/resources';
20 import { getProcess } from 'store/processes/process';
21 import { CopyProcessDialog, CopyManyProcessesDialog } from 'views-components/dialog-forms/copy-process-dialog';
22 import { collectionActionSet } from 'views-components/context-menu/action-sets/collection-action-set';
23 import { ContextMenuAction, ContextMenuActionSet } from 'views-components/context-menu/context-menu-action-set';
24 import { TrashIcon } from 'components/icon/icon';
25 import {
26     multiselectActionsFilters,
27     TMultiselectActionsFilters,
28     contextMenuActionConsts,
29 } from './ms-toolbar-action-filters';
30 import { kindToActionSet, findActionByName } from './ms-kind-action-differentiator';
31
32 type CssRules = 'root' | 'button';
33
34 const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
35     root: {
36         display: 'flex',
37         flexDirection: 'row',
38         width: 0,
39         padding: 0,
40         margin: '1rem auto auto 0.5rem',
41         overflow: 'hidden',
42         transition: 'width 150ms',
43         borderBottom: '1px solid gray',
44     },
45     button: {
46         width: '1rem',
47         margin: 'auto 5px',
48     },
49 });
50
51 export type MultiselectToolbarProps = {
52     isVisible: boolean;
53     checkedList: TCheckedList;
54     resources: ResourcesState;
55     executeMulti: (action: ContextMenuAction, checkedList: TCheckedList, resources: ResourcesState) => void;
56 };
57
58 export const MultiselectToolbar = connect(
59     mapStateToProps,
60     mapDispatchToProps
61 )(
62     withStyles(styles)((props: MultiselectToolbarProps & WithStyles<CssRules>) => {
63         const { classes, checkedList } = props;
64         const currentResourceKinds = Array.from(selectedToKindSet(checkedList));
65
66         const buttons = selectActionsByKind(currentResourceKinds, multiselectActionsFilters);
67
68         return (
69             <Toolbar className={classes.root} style={{ width: `${buttons.length * 2.12}rem` }}>
70                 {buttons.length ? (
71                     buttons.map((btn, i) =>
72                         btn.name === 'ToggleTrashAction' ? (
73                             <Tooltip className={classes.button} title={'Move to trash'} key={i} disableFocusListener>
74                                 <IconButton onClick={() => props.executeMulti(btn, checkedList, props.resources)}>
75                                     <TrashIcon />
76                                 </IconButton>
77                             </Tooltip>
78                         ) : (
79                             <Tooltip className={classes.button} title={btn.name} key={i} disableFocusListener>
80                                 <IconButton onClick={() => props.executeMulti(btn, checkedList, props.resources)}>
81                                     {btn.icon ? btn.icon({}) : <></>}
82                                 </IconButton>
83                             </Tooltip>
84                         )
85                     )
86                 ) : (
87                     <></>
88                 )}
89             </Toolbar>
90         );
91     })
92 );
93
94 //todo: put these all in a /utils
95 function selectedToArray(checkedList: TCheckedList): Array<string> {
96     const arrayifiedSelectedList: Array<string> = [];
97     for (const [key, value] of Object.entries(checkedList)) {
98         if (value === true) {
99             arrayifiedSelectedList.push(key);
100         }
101     }
102     return arrayifiedSelectedList;
103 }
104
105 function selectedToKindSet(checkedList: TCheckedList): Set<string> {
106     const setifiedList = new Set<string>();
107     for (const [key, value] of Object.entries(checkedList)) {
108         if (value === true) {
109             setifiedList.add(extractUuidKind(key) as string);
110         }
111     }
112     return setifiedList;
113 }
114
115 //num of currentResourceKinds * num of actions (in ContextMenuActionSet) * num of filters
116 //worst case: 14 * n * n -oof
117 function filterActions(actionArray: ContextMenuActionSet, filters: Array<string>): Array<ContextMenuAction> {
118     return actionArray[0].filter((action) => filters.includes(action.name as string));
119 }
120
121 //this might be the least efficient algorithm I've ever written
122 function selectActionsByKind(currentResourceKinds: Array<string>, filterSet: TMultiselectActionsFilters) {
123     let result: Array<ContextMenuAction> = [];
124     const fullFilterArray: ContextMenuAction[][] = [];
125     //start at currentResourceKinds
126     currentResourceKinds.forEach((kind) => {
127         //if there is a matching filter set
128         if (filterSet[kind]) {
129             //filter actions that apply to current kind
130             const actions = filterActions(...filterSet[kind]);
131             fullFilterArray.push(actions);
132             //if action name isn't in result, push name
133             actions.forEach((action) => {
134                 if (!result.some((item) => item.name === action.name)) {
135                     result.push(action);
136                 }
137             });
138         }
139     });
140     // console.log(result, fullFilterArray);
141     ///take fullFilterSet, make it into an array of string sets
142     const filteredNameSet = fullFilterArray.map((filterArray) => {
143         const resultSet = new Set();
144         filterArray.forEach((action) => resultSet.add(action.name || ''));
145         return resultSet;
146     });
147     console.log('filteredNameSet', filteredNameSet);
148     //filter results so that the name of each action is present in all of this string arrays
149     const filteredResult = result.filter((action) => {
150         for (let i = 0; i < filteredNameSet.length; i++) {
151             if (!filteredNameSet[i].has(action.name)) return false;
152         }
153         return true;
154     });
155
156     console.log('filteredResult', filteredResult);
157
158     //return sorted array of actions
159     return filteredResult.sort((a, b) => {
160         a.name = a.name || '';
161         b.name = b.name || '';
162         if (a.name < b.name) {
163             return -1;
164         }
165         if (a.name > b.name) {
166             return 1;
167         }
168         return 0;
169     });
170 }
171
172 //--------------------------------------------------//
173
174 function mapStateToProps(state: RootState) {
175     const { isVisible, checkedList } = state.multiselect;
176     return {
177         isVisible: isVisible,
178         checkedList: checkedList as TCheckedList,
179         resources: state.resources,
180     };
181 }
182
183 function mapDispatchToProps(dispatch: Dispatch) {
184     return {
185         executeMulti: (action: ContextMenuAction, checkedList: TCheckedList, resources: ResourcesState) => {
186             selectedToArray(checkedList).forEach((uuid) => {
187                 const resource = getResource(uuid)(resources);
188                 executeSpecific(dispatch, action.name, resource);
189             });
190         },
191     };
192 }
193
194 function executeSpecific(dispatch: Dispatch, actionName, resource) {
195     const actionSet = kindToActionSet[resource.kind];
196     const action = findActionByName(actionName, actionSet);
197     if (action) action.execute(dispatch, resource);
198 }