restoring-correct-tree-state-and-panel-item-highlighting-on-page-refresh-with-given-url
[arvados-workbench2.git] / src / views / workbench / workbench.tsx
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import * as React from 'react';
6 import { StyleRulesCallback, WithStyles, withStyles } from '@material-ui/core/styles';
7 import Drawer from '@material-ui/core/Drawer';
8 import { connect, DispatchProp } from "react-redux";
9 import { Route, Switch, RouteComponentProps } from "react-router";
10 import { login, logout } from "../../store/auth/auth-action";
11 import { User } from "../../models/user";
12 import { RootState } from "../../store/store";
13 import { MainAppBar, MainAppBarActionProps, MainAppBarMenuItem } from '../../views-components/main-app-bar/main-app-bar';
14 import { Breadcrumb } from '../../components/breadcrumbs/breadcrumbs';
15 import { push } from 'react-router-redux';
16 import { ProjectTree } from '../../views-components/project-tree/project-tree';
17 import { TreeItem } from "../../components/tree/tree";
18 import { getTreePath } from '../../store/project/project-reducer';
19 import { sidePanelActions } from '../../store/side-panel/side-panel-action';
20 import { SidePanel, SidePanelItem } from '../../components/side-panel/side-panel';
21 import { ItemMode, setProjectItem, restoreBranch } from "../../store/navigation/navigation-action";
22 import { projectActions } from "../../store/project/project-action";
23 import { collectionCreateActions } from '../../store/collections/creator/collection-creator-action';
24 import { ProjectPanel } from "../project-panel/project-panel";
25 import { DetailsPanel } from '../../views-components/details-panel/details-panel';
26 import { ArvadosTheme } from '../../common/custom-theme';
27 import { CreateProjectDialog } from "../../views-components/create-project-dialog/create-project-dialog";
28
29 import { detailsPanelActions, loadDetails } from "../../store/details-panel/details-panel-action";
30 import { contextMenuActions } from "../../store/context-menu/context-menu-actions";
31 import { SidePanelIdentifiers } from '../../store/side-panel/side-panel-reducer';
32 import { ProjectResource } from '../../models/project';
33 import { ResourceKind } from '../../models/resource';
34 import { ContextMenu, ContextMenuKind } from "../../views-components/context-menu/context-menu";
35 import { FavoritePanel } from "../favorite-panel/favorite-panel";
36 import { CurrentTokenDialog } from '../../views-components/current-token-dialog/current-token-dialog';
37 import { dataExplorerActions } from '../../store/data-explorer/data-explorer-action';
38 import { Snackbar } from '../../views-components/snackbar/snackbar';
39 import { favoritePanelActions } from '../../store/favorite-panel/favorite-panel-action';
40 import { CreateCollectionDialog } from '../../views-components/create-collection-dialog/create-collection-dialog';
41 import { CollectionPanel } from '../collection-panel/collection-panel';
42 import { loadCollection } from '../../store/collection-panel/collection-panel-action';
43 import { getCollectionUrl } from '../../models/collection';
44 import { UpdateCollectionDialog } from '../../views-components/update-collection-dialog/update-collection-dialog.';
45 import { AuthService } from "../../services/auth-service/auth-service";
46
47 const DRAWER_WITDH = 240;
48 const APP_BAR_HEIGHT = 100;
49
50 type CssRules = 'root' | 'appBar' | 'drawerPaper' | 'content' | 'contentWrapper' | 'toolbar';
51
52 const styles: StyleRulesCallback<CssRules> = (theme: ArvadosTheme) => ({
53     root: {
54         flexGrow: 1,
55         zIndex: 1,
56         overflow: 'hidden',
57         position: 'relative',
58         display: 'flex',
59         width: '100vw',
60         height: '100vh'
61     },
62     appBar: {
63         zIndex: theme.zIndex.drawer + 1,
64         position: "absolute",
65         width: "100%"
66     },
67     drawerPaper: {
68         position: 'relative',
69         width: DRAWER_WITDH,
70         display: 'flex',
71         flexDirection: 'column',
72     },
73     contentWrapper: {
74         backgroundColor: theme.palette.background.default,
75         display: "flex",
76         flexGrow: 1,
77         minWidth: 0,
78         paddingTop: APP_BAR_HEIGHT
79     },
80     content: {
81         padding: `${theme.spacing.unit}px ${theme.spacing.unit * 3}px`,
82         overflowY: "auto",
83         flexGrow: 1
84     },
85     toolbar: theme.mixins.toolbar
86 });
87
88 interface WorkbenchDataProps {
89     projects: Array<TreeItem<ProjectResource>>;
90     currentProjectId: string;
91     user?: User;
92     currentToken?: string;
93     sidePanelItems: SidePanelItem[];
94     router?: any;
95 }
96
97 interface WorkbenchServiceProps {
98     authService: AuthService;
99 }
100
101 interface WorkbenchActionProps {
102 }
103
104 type WorkbenchProps = WorkbenchDataProps & WorkbenchServiceProps & WorkbenchActionProps & DispatchProp<any> & WithStyles<CssRules>;
105
106 interface NavBreadcrumb extends Breadcrumb {
107     itemId: string;
108 }
109
110 interface NavMenuItem extends MainAppBarMenuItem {
111     action: () => void;
112 }
113
114 interface WorkbenchState {
115     isCurrentTokenDialogOpen: boolean;
116     anchorEl: any;
117     searchText: string;
118     menuItems: {
119         accountMenu: NavMenuItem[],
120         helpMenu: NavMenuItem[],
121         anonymousMenu: NavMenuItem[]
122     };
123 }
124
125 export const Workbench = withStyles(styles)(
126     connect<WorkbenchDataProps>(
127         (state: RootState) => ({
128             projects: state.projects.items,
129             currentProjectId: state.projects.currentItemId,
130             user: state.auth.user,
131             currentToken: state.auth.apiToken,
132             sidePanelItems: state.sidePanel,
133             router: state.router.location
134         })
135     )(
136         class extends React.Component<WorkbenchProps, WorkbenchState> {
137             state = {
138                 isCreationDialogOpen: false,
139                 isCurrentTokenDialogOpen: false,
140                 anchorEl: null,
141                 searchText: "",
142                 breadcrumbs: [],
143                 menuItems: {
144                     accountMenu: [
145                         {
146                             label: 'Current token',
147                             action: () => this.toggleCurrentTokenModal()
148                         },
149                         {
150                             label: "Logout",
151                             action: () => this.props.dispatch(logout())
152                         },
153                         {
154                             label: "My account",
155                             action: () => this.props.dispatch(push("/my-account"))
156                         }
157                     ],
158                     helpMenu: [
159                         {
160                             label: "Help",
161                             action: () => this.props.dispatch(push("/help"))
162                         }
163                     ],
164                     anonymousMenu: [
165                         {
166                             label: "Sign in",
167                             action: () => this.props.dispatch(login())
168                         }
169                     ]
170                 }
171             };
172
173             componentDidMount() {
174                 const PROJECT_URL_REGEX = /\/projects\/(.*)/;
175                 const getProjectIdFromUrl = (url: string) => {
176                     const match = PROJECT_URL_REGEX.exec(url);
177                     return match ? match[1] : match;
178                 };
179
180                 const id = getProjectIdFromUrl(this.props.router.pathname);
181                 if (id) {
182                     this.props.dispatch<any>(sidePanelActions.TOGGLE_SIDE_PANEL_ITEM_ACTIVE(SidePanelIdentifiers.PROJECTS));
183                     this.props.dispatch<any>(restoreBranch(id));
184                 }
185             }
186
187             render() {
188                 const path = getTreePath(this.props.projects, this.props.currentProjectId);
189                 const breadcrumbs = path.map(item => ({
190                     label: item.data.name,
191                     itemId: item.data.uuid,
192                     status: item.status
193                 }));
194
195                 const { classes, user } = this.props;
196                 return (
197                     <div className={classes.root}>
198                         <div className={classes.appBar}>
199                             <MainAppBar
200                                 breadcrumbs={breadcrumbs}
201                                 searchText={this.state.searchText}
202                                 user={this.props.user}
203                                 menuItems={this.state.menuItems}
204                                 {...this.mainAppBarActions} />
205                         </div>
206                         {user &&
207                             <Drawer
208                                 variant="permanent"
209                                 classes={{
210                                     paper: classes.drawerPaper,
211                                 }}>
212                                 <div className={classes.toolbar} />
213                                 <SidePanel
214                                     toggleOpen={this.toggleSidePanelOpen}
215                                     toggleActive={this.toggleSidePanelActive}
216                                     sidePanelItems={this.props.sidePanelItems}
217                                     onContextMenu={(event) => this.openContextMenu(event, {
218                                         uuid: this.props.authService.getUuid() || "",
219                                         name: "",
220                                         kind: ContextMenuKind.ROOT_PROJECT
221                                     })}>
222                                     <ProjectTree
223                                         projects={this.props.projects}
224                                         toggleOpen={itemId => this.props.dispatch(setProjectItem(itemId, ItemMode.OPEN))}
225                                         onContextMenu={(event, item) => this.openContextMenu(event, {
226                                             uuid: item.data.uuid,
227                                             name: item.data.name,
228                                             kind: ContextMenuKind.PROJECT
229                                         })}
230                                         toggleActive={itemId => {
231                                             this.props.dispatch(setProjectItem(itemId, ItemMode.ACTIVE));
232                                             this.props.dispatch(loadDetails(itemId, ResourceKind.PROJECT));
233                                             this.props.dispatch(sidePanelActions.TOGGLE_SIDE_PANEL_ITEM_ACTIVE(SidePanelIdentifiers.PROJECTS));
234                                         }} />
235                                 </SidePanel>
236                             </Drawer>}
237                         <main className={classes.contentWrapper}>
238                             <div className={classes.content}>
239                                 <Switch>
240                                     <Route path="/projects/:id" render={this.renderProjectPanel} />
241                                     <Route path="/favorites" render={this.renderFavoritePanel} />
242                                     <Route path="/collections/:id" render={this.renderCollectionPanel} />
243                                 </Switch>
244                             </div>
245                             {user && <DetailsPanel />}
246                         </main>
247                         <ContextMenu />
248                         <Snackbar />
249                         <CreateProjectDialog />
250                         <CreateCollectionDialog />
251                         <UpdateCollectionDialog />
252                         <CurrentTokenDialog
253                             currentToken={this.props.currentToken}
254                             open={this.state.isCurrentTokenDialogOpen}
255                             handleClose={this.toggleCurrentTokenModal} />
256                     </div>
257                 );
258             }
259
260             renderCollectionPanel = (props: RouteComponentProps<{ id: string }>) => <CollectionPanel
261                 onItemRouteChange={(collectionId) => this.props.dispatch<any>(loadCollection(collectionId, ResourceKind.COLLECTION))}
262                 onContextMenu={(event, item) => {
263                     this.openContextMenu(event, {
264                         uuid: item.uuid,
265                         name: item.name,
266                         kind: ContextMenuKind.COLLECTION
267                     });
268                 }}
269                 {...props} />
270
271             renderProjectPanel = (props: RouteComponentProps<{ id: string }>) => <ProjectPanel
272                 onItemRouteChange={itemId => this.props.dispatch(setProjectItem(itemId, ItemMode.ACTIVE))}
273                 onContextMenu={(event, item) => {
274
275                     const kind = item.kind === ResourceKind.PROJECT ? ContextMenuKind.PROJECT : ContextMenuKind.RESOURCE;
276                     this.openContextMenu(event, {
277                         uuid: item.uuid,
278                         name: item.name,
279                         kind
280                     });
281                 }}
282                 onProjectCreationDialogOpen={this.handleProjectCreationDialogOpen}
283                 onCollectionCreationDialogOpen={this.handleCollectionCreationDialogOpen}
284                 onItemClick={item => {
285                     this.props.dispatch(loadDetails(item.uuid, item.kind as ResourceKind));
286                 }}
287                 onItemDoubleClick={item => {
288                     switch (item.kind) {
289                         case ResourceKind.COLLECTION:
290                             this.props.dispatch(loadCollection(item.uuid, item.kind as ResourceKind));
291                             this.props.dispatch(push(getCollectionUrl(item.uuid)));
292                         default:
293                             this.props.dispatch(setProjectItem(item.uuid, ItemMode.ACTIVE));
294                             this.props.dispatch(loadDetails(item.uuid, item.kind as ResourceKind));
295                     }
296
297                 }}
298                 {...props} />
299
300             renderFavoritePanel = (props: RouteComponentProps<{ id: string }>) => <FavoritePanel
301                 onItemRouteChange={() => this.props.dispatch(favoritePanelActions.REQUEST_ITEMS())}
302                 onContextMenu={(event, item) => {
303                     const kind = item.kind === ResourceKind.PROJECT ? ContextMenuKind.PROJECT : ContextMenuKind.RESOURCE;
304                     this.openContextMenu(event, {
305                         uuid: item.uuid,
306                         name: item.name,
307                         kind,
308                     });
309                 }}
310                 onDialogOpen={this.handleProjectCreationDialogOpen}
311                 onItemClick={item => {
312                     this.props.dispatch(loadDetails(item.uuid, item.kind as ResourceKind));
313                 }}
314                 onItemDoubleClick={item => {
315                     switch (item.kind) {
316                         case ResourceKind.COLLECTION:
317                             this.props.dispatch(loadCollection(item.uuid, item.kind as ResourceKind));
318                             this.props.dispatch(push(getCollectionUrl(item.uuid)));
319                         default:
320                             this.props.dispatch(loadDetails(item.uuid, ResourceKind.PROJECT));
321                             this.props.dispatch(setProjectItem(item.uuid, ItemMode.ACTIVE));
322                             this.props.dispatch(sidePanelActions.TOGGLE_SIDE_PANEL_ITEM_ACTIVE(SidePanelIdentifiers.PROJECTS));
323                     }
324
325                 }}
326                 {...props} />
327
328             mainAppBarActions: MainAppBarActionProps = {
329                 onBreadcrumbClick: ({ itemId }: NavBreadcrumb) => {
330                     this.props.dispatch(setProjectItem(itemId, ItemMode.BOTH));
331                     this.props.dispatch(loadDetails(itemId, ResourceKind.PROJECT));
332                 },
333                 onSearch: searchText => {
334                     this.setState({ searchText });
335                     this.props.dispatch(push(`/search?q=${searchText}`));
336                 },
337                 onMenuItemClick: (menuItem: NavMenuItem) => menuItem.action(),
338                 onDetailsPanelToggle: () => {
339                     this.props.dispatch(detailsPanelActions.TOGGLE_DETAILS_PANEL());
340                 },
341                 onContextMenu: (event: React.MouseEvent<HTMLElement>, breadcrumb: NavBreadcrumb) => {
342                     this.openContextMenu(event, {
343                         uuid: breadcrumb.itemId,
344                         name: breadcrumb.label,
345                         kind: ContextMenuKind.PROJECT
346                     });
347                 }
348             };
349
350             toggleSidePanelOpen = (itemId: string) => {
351                 this.props.dispatch(sidePanelActions.TOGGLE_SIDE_PANEL_ITEM_OPEN(itemId));
352             }
353
354             toggleSidePanelActive = (itemId: string) => {
355                 this.props.dispatch(sidePanelActions.TOGGLE_SIDE_PANEL_ITEM_ACTIVE(itemId));
356                 this.props.dispatch(projectActions.RESET_PROJECT_TREE_ACTIVITY(itemId));
357                 const panelItem = this.props.sidePanelItems.find(it => it.id === itemId);
358                 if (panelItem && panelItem.activeAction) {
359                     panelItem.activeAction(this.props.dispatch);
360                 }
361             }
362
363             handleProjectCreationDialogOpen = (itemUuid: string) => {
364                 this.props.dispatch(projectActions.OPEN_PROJECT_CREATOR({ ownerUuid: itemUuid }));
365             }
366
367             handleCollectionCreationDialogOpen = (itemUuid: string) => {
368                 this.props.dispatch(collectionCreateActions.OPEN_COLLECTION_CREATOR({ ownerUuid: itemUuid }));
369             }
370
371             openContextMenu = (event: React.MouseEvent<HTMLElement>, resource: { name: string; uuid: string; kind: ContextMenuKind; }) => {
372                 event.preventDefault();
373                 this.props.dispatch(
374                     contextMenuActions.OPEN_CONTEXT_MENU({
375                         position: { x: event.clientX, y: event.clientY },
376                         resource
377                     })
378                 );
379             }
380
381             toggleCurrentTokenModal = () => {
382                 this.setState({ isCurrentTokenDialogOpen: !this.state.isCurrentTokenDialogOpen });
383             }
384         }
385     )
386 );