20251: Fix flaky collection file browser by using race-free state update callback
[arvados-workbench2.git] / src / views-components / side-panel-button / side-panel-button.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, DispatchProp } from 'react-redux';
7 import { RootState } from 'store/store';
8 import { ArvadosTheme } from 'common/custom-theme';
9 import { PopoverOrigin } from '@material-ui/core/Popover';
10 import { StyleRulesCallback, WithStyles, withStyles, Toolbar, Grid, Button, MenuItem, Menu } from '@material-ui/core';
11 import { AddIcon, CollectionIcon, ProcessIcon, ProjectIcon } from 'components/icon/icon';
12 import { openProjectCreateDialog } from 'store/projects/project-create-actions';
13 import { openCollectionCreateDialog } from 'store/collections/collection-create-actions';
14 import { navigateToRunProcess } from 'store/navigation/navigation-action';
15 import { runProcessPanelActions } from 'store/run-process-panel/run-process-panel-actions';
16 import { getUserUuid } from 'common/getuser';
17 import { matchProjectRoute } from 'routes/routes';
18 import { GroupClass, GroupResource } from 'models/group';
19 import { ResourcesState, getResource } from 'store/resources/resources';
20 import { extractUuidKind, ResourceKind } from 'models/resource';
21 import { pluginConfig } from 'plugins';
22 import { ElementListReducer } from 'common/plugintypes';
23 import { Location } from 'history';
24 import { ProjectResource } from 'models/project';
25
26 type CssRules = 'button' | 'menuItem' | 'icon';
27
28 const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
29     button: {
30         boxShadow: 'none',
31         padding: '2px 10px 2px 5px',
32         fontSize: '0.75rem'
33     },
34     menuItem: {
35         fontSize: '0.875rem',
36         color: theme.palette.grey["700"]
37     },
38     icon: {
39         marginRight: theme.spacing.unit
40     }
41 });
42
43 interface SidePanelDataProps {
44     location: Location;
45     currentItemId: string;
46     resources: ResourcesState;
47     currentUserUUID: string | undefined;
48 }
49
50 interface SidePanelState {
51     anchorEl: any;
52 }
53
54 type SidePanelProps = SidePanelDataProps & DispatchProp & WithStyles<CssRules>;
55
56 const transformOrigin: PopoverOrigin = {
57     vertical: -50,
58     horizontal: 0
59 };
60
61 export const isProjectTrashed = (proj: GroupResource | undefined, resources: ResourcesState): boolean => {
62     if (proj === undefined) { return false; }
63     if (proj.isTrashed) { return true; }
64     if (extractUuidKind(proj.ownerUuid) === ResourceKind.USER) { return false; }
65     const parentProj = getResource<GroupResource>(proj.ownerUuid)(resources);
66     return isProjectTrashed(parentProj, resources);
67 };
68
69 export const SidePanelButton = withStyles(styles)(
70     connect((state: RootState) => ({
71         currentItemId: state.router.location
72             ? state.router.location.pathname.split('/').slice(-1)[0]
73             : null,
74         location: state.router.location,
75         resources: state.resources,
76         currentUserUUID: getUserUuid(state),
77     }))(
78         class extends React.Component<SidePanelProps> {
79
80             state: SidePanelState = {
81                 anchorEl: undefined
82             };
83
84             render() {
85                 const { classes, location, resources, currentUserUUID, currentItemId } = this.props;
86                 const { anchorEl } = this.state;
87                 let enabled = false;
88                 if (currentItemId === currentUserUUID) {
89                     enabled = true;
90                 } else if (matchProjectRoute(location ? location.pathname : '')) {
91                     const currentProject = getResource<ProjectResource>(currentItemId)(resources);
92                     if (currentProject && currentProject.writableBy &&
93                         currentProject.writableBy.indexOf(currentUserUUID || '') >= 0 &&
94                         !currentProject.frozenByUuid &&
95                         !isProjectTrashed(currentProject, resources) &&
96                         currentProject.groupClass !== GroupClass.FILTER) {
97                         enabled = true;
98                     }
99                 }
100
101                 for (const enableFn of pluginConfig.enableNewButtonMatchers) {
102                     if (enableFn(location, currentItemId, currentUserUUID, resources)) {
103                         enabled = true;
104                     }
105                 }
106
107                 let menuItems = <>
108                     <MenuItem data-cy='side-panel-new-collection' className={classes.menuItem} onClick={this.handleNewCollectionClick}>
109                         <CollectionIcon className={classes.icon} /> New collection
110                     </MenuItem>
111                     <MenuItem data-cy='side-panel-run-process' className={classes.menuItem} onClick={this.handleRunProcessClick}>
112                         <ProcessIcon className={classes.icon} /> Run a workflow
113                     </MenuItem>
114                     <MenuItem data-cy='side-panel-new-project' className={classes.menuItem} onClick={this.handleNewProjectClick}>
115                         <ProjectIcon className={classes.icon} /> New project
116                     </MenuItem>
117                 </>;
118
119                 const reduceItemsFn: (a: React.ReactElement[], b: ElementListReducer) => React.ReactElement[] =
120                     (a, b) => b(a, classes.menuItem);
121
122                 menuItems = React.createElement(React.Fragment, null,
123                     pluginConfig.newButtonMenuList.reduce(reduceItemsFn, React.Children.toArray(menuItems.props.children)));
124
125                 return <Toolbar>
126                     <Grid container>
127                         <Grid container item xs alignItems="center" justify="flex-start">
128                             <Button data-cy="side-panel-button" variant="contained" disabled={!enabled}
129                                 color="primary" size="small" className={classes.button}
130                                 aria-owns={anchorEl ? 'aside-menu-list' : undefined}
131                                 aria-haspopup="true"
132                                 onClick={this.handleOpen}>
133                                 <AddIcon />
134                                 New
135                             </Button>
136                             <Menu
137                                 id='aside-menu-list'
138                                 anchorEl={anchorEl}
139                                 open={Boolean(anchorEl)}
140                                 onClose={this.handleClose}
141                                 onClick={this.handleClose}
142                                 transformOrigin={transformOrigin}>
143                                 {menuItems}
144                             </Menu>
145                         </Grid>
146                     </Grid>
147                 </Toolbar>;
148             }
149
150             handleNewProjectClick = () => {
151                 this.props.dispatch<any>(openProjectCreateDialog(this.props.currentItemId));
152             }
153
154             handleRunProcessClick = () => {
155                 const location = this.props.location;
156                 this.props.dispatch(runProcessPanelActions.RESET_RUN_PROCESS_PANEL());
157                 this.props.dispatch(runProcessPanelActions.SET_PROCESS_PATHNAME(location.pathname));
158                 this.props.dispatch(runProcessPanelActions.SET_PROCESS_OWNER_UUID(this.props.currentItemId));
159
160                 this.props.dispatch<any>(navigateToRunProcess);
161             }
162
163             handleNewCollectionClick = () => {
164                 this.props.dispatch<any>(openCollectionCreateDialog(this.props.currentItemId));
165             }
166
167             handleClose = () => {
168                 this.setState({ anchorEl: undefined });
169             }
170
171             handleOpen = (event: React.MouseEvent<HTMLButtonElement>) => {
172                 this.setState({ anchorEl: event.currentTarget });
173             }
174         }
175     )
176 );