15768: cleanup Arvados-DCO-1.1-Signed-off-by: Lisa Knox <lisa.knox@curii.com>
[arvados.git] / src / components / multiselectToolbar / MultiselectToolbar.tsx
index d141afd99931bf4a8f595d6d7922593a5b533624..22a9c7139c7abffde2d051c5140c4485573f1db1 100644 (file)
@@ -2,89 +2,47 @@
 //
 // SPDX-License-Identifier: AGPL-3.0
 
-import React, { ReactElement } from 'react';
-import { connect } from 'react-redux';
-import { StyleRulesCallback, withStyles, WithStyles, Toolbar, Button } from '@material-ui/core';
-import { ArvadosTheme } from 'common/custom-theme';
-import { RootState } from 'store/store';
-import { Dispatch } from 'redux';
-import { CopyToClipboardSnackbar } from 'components/copy-to-clipboard-snackbar/copy-to-clipboard-snackbar';
-import { TCheckedList } from 'components/data-table/data-table';
-import { openRemoveProcessDialog, openRemoveManyProcessesDialog } from 'store/processes/processes-actions';
-import { processResourceActionSet } from '../../views-components/context-menu/action-sets/process-resource-action-set';
-import { ContextMenuResource } from 'store/context-menu/context-menu-actions';
-import { ResourceKind, extractUuidKind } from 'models/resource';
-import { openMoveProcessDialog } from 'store/processes/process-move-actions';
-import { openCopyProcessDialog, openCopyManyProcessesDialog } from 'store/processes/process-copy-actions';
-import { getResource } from 'store/resources/resources';
-import { ResourceName } from 'views-components/data-explorer/renderers';
-import { ProcessResource } from 'models/process';
-import { ResourcesState } from 'store/resources/resources';
-import { Resource } from 'models/resource';
-import { getProcess } from 'store/processes/process';
-import { CopyProcessDialog, CopyManyProcessesDialog } from 'views-components/dialog-forms/copy-process-dialog';
-
-type CssRules = 'root' | 'button';
+import React from "react";
+import { connect } from "react-redux";
+import { StyleRulesCallback, withStyles, WithStyles, Toolbar, Tooltip, IconButton } from "@material-ui/core";
+import { ArvadosTheme } from "common/custom-theme";
+import { RootState } from "store/store";
+import { Dispatch } from "redux";
+import { TCheckedList } from "components/data-table/data-table";
+import { ContextMenuResource } from "store/context-menu/context-menu-actions";
+import { Resource, extractUuidKind } from "models/resource";
+import { getResource } from "store/resources/resources";
+import { ResourcesState } from "store/resources/resources";
+import { ContextMenuAction, ContextMenuActionSet } from "views-components/context-menu/context-menu-action-set";
+import { RestoreFromTrashIcon, TrashIcon } from "components/icon/icon";
+import { multiselectActionsFilters, TMultiselectActionsFilters, contextMenuActionConsts } from "./ms-toolbar-action-filters";
+import { kindToActionSet, findActionByName } from "./ms-kind-action-differentiator";
+import { toggleTrashAction } from "views-components/context-menu/action-sets/project-action-set";
+import { copyToClipboardAction } from "store/open-in-new-tab/open-in-new-tab.actions";
+
+type CssRules = "root" | "button";
 
 const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
     root: {
-        display: 'flex',
-        flexDirection: 'row',
+        display: "flex",
+        flexDirection: "row",
         width: 0,
         padding: 0,
-        margin: '1rem auto auto 0.5rem',
-        overflow: 'hidden',
-        transition: 'width 150ms',
+        margin: "1rem auto auto 0.5rem",
+        overflow: "hidden",
+        transition: "width 150ms",
     },
     button: {
-        backgroundColor: '#017ead',
-        color: 'white',
-        fontSize: '0.75rem',
-        width: 'auto',
-        margin: 'auto',
-        padding: '1px',
+        width: "1rem",
+        margin: "auto 5px",
     },
 });
 
-type MultiselectToolbarAction = {
-    name: string;
-    funcName: string;
-    relevantKinds: Set<ResourceKind>;
-};
-
-//gleaned from src/views-components/context-menu/action-sets
-export const defaultActions: Array<MultiselectToolbarAction> = [
-    {
-        name: 'copy and re-run',
-        funcName: 'copySelected',
-        relevantKinds: new Set([ResourceKind.PROCESS]),
-    },
-    {
-        name: 'move',
-        funcName: 'moveSelected',
-        relevantKinds: new Set([ResourceKind.PROCESS, ResourceKind.PROJECT]),
-    },
-    {
-        name: 'remove',
-        funcName: 'removeSelected',
-        relevantKinds: new Set([ResourceKind.PROCESS, ResourceKind.COLLECTION]),
-    },
-    {
-        name: 'favorite',
-        funcName: 'favoriteSelected',
-        relevantKinds: new Set([ResourceKind.PROCESS, ResourceKind.PROJECT, ResourceKind.COLLECTION]),
-    },
-];
-
 export type MultiselectToolbarProps = {
-    actions: Array<MultiselectToolbarAction>;
     isVisible: boolean;
     checkedList: TCheckedList;
     resources: ResourcesState;
-    copySelected: (checkedList: TCheckedList, resources: ResourcesState) => void;
-    moveSelected: (resource) => void;
-    barSelected: () => void;
-    removeSelected: (checkedList: TCheckedList) => void;
+    executeMulti: (action: ContextMenuAction, checkedList: TCheckedList, resources: ResourcesState) => void;
 };
 
 export const MultiselectToolbar = connect(
@@ -92,21 +50,43 @@ export const MultiselectToolbar = connect(
     mapDispatchToProps
 )(
     withStyles(styles)((props: MultiselectToolbarProps & WithStyles<CssRules>) => {
-        // console.log(props);
-        const { classes, actions, isVisible, checkedList, resources } = props;
-
+        const { classes, checkedList } = props;
         const currentResourceKinds = Array.from(selectedToKindSet(checkedList));
-        const buttons = actions.filter((action) => currentResourceKinds.length && currentResourceKinds.every((kind) => action.relevantKinds.has(kind as ResourceKind)));
+
+        const currentPathIsTrash = window.location.pathname === "/trash";
+        const buttons =
+            currentPathIsTrash && selectedToKindSet(checkedList).size
+                ? [toggleTrashAction]
+                : selectActionsByKind(currentResourceKinds, multiselectActionsFilters);
 
         return (
-            <Toolbar className={classes.root} style={{ width: `${buttons.length * 5.5}rem` }}>
+            <Toolbar
+                className={classes.root}
+                style={{ width: `${buttons.length * 2.12}rem` }}>
                 {buttons.length ? (
-                    buttons.map((btn) => (
-                        <Button key={btn.name} className={classes.button} onClick={() => props[btn.funcName](checkedList)}>
-                            {/* {<CopyProcessDialog>{btn.name}</CopyProcessDialog>} */}
-                            {btn.name}
-                        </Button>
-                    ))
+                    buttons.map((btn, i) =>
+                        btn.name === "ToggleTrashAction" ? (
+                            <Tooltip
+                                className={classes.button}
+                                title={currentPathIsTrash ? "Restore selected" : "Move to trash"}
+                                key={i}
+                                disableFocusListener>
+                                <IconButton onClick={() => props.executeMulti(btn, checkedList, props.resources)}>
+                                    {currentPathIsTrash ? <RestoreFromTrashIcon /> : <TrashIcon />}
+                                </IconButton>
+                            </Tooltip>
+                        ) : (
+                            <Tooltip
+                                className={classes.button}
+                                title={btn.name}
+                                key={i}
+                                disableFocusListener>
+                                <IconButton onClick={() => props.executeMulti(btn, checkedList, props.resources)}>
+                                    {btn.icon ? btn.icon({}) : <></>}
+                                </IconButton>
+                            </Tooltip>
+                        )
+                    )
                 ) : (
                     <></>
                 )}
@@ -115,7 +95,7 @@ export const MultiselectToolbar = connect(
     })
 );
 
-function selectedToArray(checkedList: TCheckedList): Array<string> {
+export function selectedToArray(checkedList: TCheckedList): Array<string> {
     const arrayifiedSelectedList: Array<string> = [];
     for (const [key, value] of Object.entries(checkedList)) {
         if (value === true) {
@@ -125,7 +105,7 @@ function selectedToArray(checkedList: TCheckedList): Array<string> {
     return arrayifiedSelectedList;
 }
 
-function selectedToKindSet(checkedList: TCheckedList): Set<string> {
+export function selectedToKindSet(checkedList: TCheckedList): Set<string> {
     const setifiedList = new Set<string>();
     for (const [key, value] of Object.entries(checkedList)) {
         if (value === true) {
@@ -135,6 +115,65 @@ function selectedToKindSet(checkedList: TCheckedList): Set<string> {
     return setifiedList;
 }
 
+function groupByKind(checkedList: TCheckedList, resources: ResourcesState): Record<string, ContextMenuResource[]> {
+    const result = {};
+    selectedToArray(checkedList).forEach(uuid => {
+        const resource = getResource(uuid)(resources) as Resource;
+        if (!result[resource.kind]) result[resource.kind] = [];
+        result[resource.kind].push(resource);
+    });
+    return result;
+}
+
+function filterActions(actionArray: ContextMenuActionSet, filters: Set<string>): Array<ContextMenuAction> {
+    return actionArray[0].filter(action => filters.has(action.name as string));
+}
+
+function selectActionsByKind(currentResourceKinds: Array<string>, filterSet: TMultiselectActionsFilters) {
+    const rawResult: Set<ContextMenuAction> = new Set();
+    const resultNames = new Set();
+    const allFiltersArray: ContextMenuAction[][] = [];
+    currentResourceKinds.forEach(kind => {
+        if (filterSet[kind]) {
+            const actions = filterActions(...filterSet[kind]);
+            allFiltersArray.push(actions);
+            actions.forEach(action => {
+                if (!resultNames.has(action.name)) {
+                    rawResult.add(action);
+                    resultNames.add(action.name);
+                }
+            });
+        }
+    });
+
+    const filteredNameSet = allFiltersArray.map(filterArray => {
+        const resultSet = new Set();
+        filterArray.forEach(action => resultSet.add(action.name || ""));
+        return resultSet;
+    });
+
+    const filteredResult = Array.from(rawResult).filter(action => {
+        for (let i = 0; i < filteredNameSet.length; i++) {
+            if (!filteredNameSet[i].has(action.name)) return false;
+        }
+        return true;
+    });
+
+    return filteredResult.sort((a, b) => {
+        const nameA = a.name || "";
+        const nameB = b.name || "";
+        if (nameA < nameB) {
+            return -1;
+        }
+        if (nameA > nameB) {
+            return 1;
+        }
+        return 0;
+    });
+}
+
+//--------------------------------------------------//
+
 function mapStateToProps(state: RootState) {
     const { isVisible, checkedList } = state.multiselect;
     return {
@@ -146,35 +185,25 @@ function mapStateToProps(state: RootState) {
 
 function mapDispatchToProps(dispatch: Dispatch) {
     return {
-        copySelected: (checkedList: TCheckedList, resources: ResourcesState) => copyMoveMany(dispatch, checkedList),
-        moveSelected: (checkedList: TCheckedList) => {},
-        barSelected: () => {},
-        removeSelected: (checkedList: TCheckedList) => removeMultiProcesses(dispatch, checkedList),
+        executeMulti: (selectedAction: ContextMenuAction, checkedList: TCheckedList, resources: ResourcesState): void => {
+            const kindGroups = groupByKind(checkedList, resources);
+            switch (selectedAction.name) {
+                case contextMenuActionConsts.MOVE_TO:
+                    const firstResource = getResource(selectedToArray(checkedList)[0])(resources) as Resource;
+                    const action = findActionByName(selectedAction.name as string, kindToActionSet[firstResource.kind]);
+                    if (action) action.execute(dispatch, kindGroups[firstResource.kind]);
+                    break;
+                case contextMenuActionConsts.COPY_TO_CLIPBOARD:
+                    const selectedResources = selectedToArray(checkedList).map(uuid => getResource(uuid)(resources));
+                    dispatch<any>(copyToClipboardAction(selectedResources));
+                    break;
+                default:
+                    for (const kind in kindGroups) {
+                        const action = findActionByName(selectedAction.name as string, kindToActionSet[kind]);
+                        if (action) action.execute(dispatch, kindGroups[kind]);
+                    }
+                    break;
+            }
+        },
     };
 }
-
-function copyMoveMany(dispatch: Dispatch, checkedList: TCheckedList) {
-    const selectedList: Array<string> = selectedToArray(checkedList);
-    const uuid = selectedList[0];
-    // dispatch<any>(openCopyManyProcessesDialog(uuid));
-    dispatch<any>(openCopyManyProcessesDialog(selectedList));
-}
-
-function moveMultiProcesses(dispatch: Dispatch, checkedList: TCheckedList): void {
-    const selectedList: Array<string> = selectedToArray(checkedList);
-    // if (selectedList.length === 1) dispatch<any>(openMoveProcessDialog(selectedList[0]));
-}
-
-const RemoveFunctions = {
-    ONE_PROCESS: (uuid: string) => openRemoveProcessDialog(uuid),
-    MANY_PROCESSES: (list: Array<string>) => openRemoveManyProcessesDialog(list),
-};
-
-function removeMultiProcesses(dispatch: Dispatch, checkedList: TCheckedList): void {
-    const selectedList: Array<string> = selectedToArray(checkedList);
-    dispatch<any>(selectedList.length === 1 ? RemoveFunctions.ONE_PROCESS(selectedList[0]) : RemoveFunctions.MANY_PROCESSES(selectedList));
-}
-
-//onRemove
-//go through the array of selected and choose the appropriate removal function
-//have a constant with [ResourceKind]: different removal methods