18787: Attempts to diminish the indentation madness, improving readability.
[arvados-workbench2.git] / src / components / collection-panel-files / collection-panel-files.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 classNames from 'classnames';
7 import { connect } from 'react-redux';
8 import { FixedSizeList } from "react-window";
9 import AutoSizer from "react-virtualized-auto-sizer";
10 import servicesProvider from 'common/service-provider';
11 import { CustomizeTableIcon, DownloadIcon } from 'components/icon/icon';
12 import { SearchInput } from 'components/search-input/search-input';
13 import { ListItemIcon, StyleRulesCallback, Theme, WithStyles, withStyles, Tooltip, IconButton, Checkbox, CircularProgress, Button } from '@material-ui/core';
14 import { FileTreeData } from '../file-tree/file-tree-data';
15 import { TreeItem, TreeItemStatus } from '../tree/tree';
16 import { RootState } from 'store/store';
17 import { WebDAV, WebDAVRequestConfig } from 'common/webdav';
18 import { AuthState } from 'store/auth/auth-reducer';
19 import { extractFilesData } from 'services/collection-service/collection-service-files-response';
20 import { DefaultIcon, DirectoryIcon, FileIcon, BackIcon, SidePanelRightArrowIcon } from 'components/icon/icon';
21 import { setCollectionFiles } from 'store/collection-panel/collection-panel-files/collection-panel-files-actions';
22 import { sortBy } from 'lodash';
23 import { formatFileSize } from 'common/formatters';
24 import { getInlineFileUrl, sanitizeToken } from 'views-components/context-menu/actions/helpers';
25
26 export interface CollectionPanelFilesProps {
27     items: any;
28     isWritable: boolean;
29     isLoading: boolean;
30     tooManyFiles: boolean;
31     onUploadDataClick: (targetLocation?: string) => void;
32     onSearchChange: (searchValue: string) => void;
33     onItemMenuOpen: (event: React.MouseEvent<HTMLElement>, item: TreeItem<FileTreeData>, isWritable: boolean) => void;
34     onOptionsMenuOpen: (event: React.MouseEvent<HTMLElement>, isWritable: boolean) => void;
35     onSelectionToggle: (event: React.MouseEvent<HTMLElement>, item: TreeItem<FileTreeData>) => void;
36     onCollapseToggle: (id: string, status: TreeItemStatus) => void;
37     onFileClick: (id: string) => void;
38     loadFilesFunc: () => void;
39     currentItemUuid: any;
40     dispatch: Function;
41     collectionPanelFiles: any;
42     collectionPanel: any;
43 }
44
45 type CssRules = "backButton" | "backButtonHidden" | "pathPanelPathWrapper" | "uploadButton" | "uploadIcon" | "loader" | "wrapper" | "dataWrapper" | "row" | "rowEmpty" | "leftPanel" | "rightPanel" | "pathPanel" | "pathPanelItem" | "rowName" | "listItemIcon" | "rowActive" | "pathPanelMenu" | "rowSelection" | "leftPanelHidden" | "leftPanelVisible" | "searchWrapper" | "searchWrapperHidden";
46
47 const styles: StyleRulesCallback<CssRules> = (theme: Theme) => ({
48     wrapper: {
49         display: 'flex',
50         minHeight: '600px',
51         color: 'rgba(0, 0, 0, 0.87)',
52         fontSize: '0.875rem',
53         fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
54         fontWeight: 400,
55         lineHeight: '1.5',
56         letterSpacing: '0.01071em'
57     },
58     backButton: {
59         color: '#00bfa5',
60         cursor: 'pointer',
61         float: 'left',
62     },
63     backButtonHidden: {
64         display: 'none',
65     },
66     dataWrapper: {
67         minHeight: '500px'
68     },
69     row: {
70         display: 'flex',
71         marginTop: '0.5rem',
72         marginBottom: '0.5rem',
73         cursor: 'pointer',
74         "&:hover": {
75             backgroundColor: 'rgba(0, 0, 0, 0.08)',
76         }
77     },
78     rowEmpty: {
79         top: '40%',
80         width: '100%',
81         textAlign: 'center',
82         position: 'absolute'
83     },
84     loader: {
85         top: '50%',
86         left: '50%',
87         marginTop: '-15px',
88         marginLeft: '-15px',
89         position: 'absolute'
90     },
91     rowName: {
92         display: 'inline-flex',
93         flexDirection: 'column',
94         justifyContent: 'center'
95     },
96     searchWrapper: {
97         display: 'inline-block',
98         marginBottom: '1rem',
99         marginLeft: '1rem',
100     },
101     searchWrapperHidden: {
102         width: '0px'
103     },
104     rowSelection: {
105         padding: '0px',
106     },
107     rowActive: {
108         color: `${theme.palette.primary.main} !important`,
109     },
110     listItemIcon: {
111         display: 'inline-flex',
112         flexDirection: 'column',
113         justifyContent: 'center'
114     },
115     pathPanelMenu: {
116         float: 'right',
117         marginTop: '-15px',
118     },
119     pathPanel: {
120         padding: '1rem',
121         marginBottom: '1rem',
122         backgroundColor: '#fff',
123         boxShadow: '0px 1px 3px 0px rgb(0 0 0 / 20%), 0px 1px 1px 0px rgb(0 0 0 / 14%), 0px 2px 1px -1px rgb(0 0 0 / 12%)',
124     },
125     pathPanelPathWrapper: {
126         display: 'inline-block',
127     },
128     leftPanel: {
129         flex: 0,
130         padding: '1rem',
131         marginRight: '1rem',
132         whiteSpace: 'nowrap',
133         position: 'relative',
134         backgroundColor: '#fff',
135         boxShadow: '0px 3px 3px 0px rgb(0 0 0 / 20%), 0px 3px 1px 0px rgb(0 0 0 / 14%), 0px 3px 1px -1px rgb(0 0 0 / 12%)',
136     },
137     leftPanelVisible: {
138         opacity: 1,
139         flex: '50%',
140         animation: `animateVisible 1000ms ${theme.transitions.easing.easeOut}`
141     },
142     leftPanelHidden: {
143         opacity: 0,
144         flex: 'initial',
145         padding: '0',
146         marginRight: '0',
147     },
148     "@keyframes animateVisible": {
149         "0%": {
150             opacity: 0,
151             flex: 'initial',
152         },
153         "100%": {
154             opacity: 1,
155             flex: '50%',
156         }
157     },
158     rightPanel: {
159         flex: '50%',
160         padding: '1rem',
161         paddingTop: '2rem',
162         marginTop: '-1rem',
163         position: 'relative',
164         backgroundColor: '#fff',
165         boxShadow: '0px 3px 3px 0px rgb(0 0 0 / 20%), 0px 3px 1px 0px rgb(0 0 0 / 14%), 0px 3px 1px -1px rgb(0 0 0 / 12%)',
166     },
167     pathPanelItem: {
168         cursor: 'pointer',
169     },
170     uploadIcon: {
171         transform: 'rotate(180deg)'
172     },
173     uploadButton: {
174         float: 'right',
175     }
176 });
177
178 const pathPromise = {};
179
180 export const CollectionPanelFiles = withStyles(styles)(connect((state: RootState) => ({
181     auth: state.auth,
182     collectionPanel: state.collectionPanel,
183     collectionPanelFiles: state.collectionPanelFiles,
184 }))((props: CollectionPanelFilesProps & WithStyles<CssRules> & { auth: AuthState }) => {
185     const { classes, onItemMenuOpen, onUploadDataClick, isWritable, dispatch, collectionPanelFiles, collectionPanel } = props;
186     const { apiToken, config } = props.auth;
187
188     const webdavClient = new WebDAV();
189     webdavClient.defaults.baseURL = config.keepWebServiceUrl;
190     webdavClient.defaults.headers = {
191         Authorization: `Bearer ${apiToken}`
192     };
193
194     const webDAVRequestConfig: WebDAVRequestConfig = {
195         headers: {
196             Depth: '1',
197         },
198     };
199
200     const parentRef = React.useRef(null);
201     const [path, setPath]: any = React.useState([]);
202     const [pathData, setPathData]: any = React.useState({});
203     const [isLoading, setIsLoading] = React.useState(false);
204     const [leftSearch, setLeftSearch] = React.useState('');
205     const [rightSearch, setRightSearch] = React.useState('');
206
207     const leftKey = (path.length > 1 ? path.slice(0, path.length - 1) : path).join('/');
208     const rightKey = path.join('/');
209
210     const leftData = pathData[leftKey] || [];
211     const rightData = pathData[rightKey];
212
213     React.useEffect(() => {
214         if (props.currentItemUuid) {
215             setPathData({});
216             setPath([props.currentItemUuid]);
217         }
218     }, [props.currentItemUuid]);
219
220     const fetchData = (keys, ignoreCache = false) => {
221         const keyArray = Array.isArray(keys) ? keys : [keys];
222
223         Promise.all(keyArray
224             .map((key) => {
225                 const dataExists = !!pathData[key];
226                 const runningRequest = pathPromise[key];
227
228                 if ((!dataExists || ignoreCache) && (!runningRequest || ignoreCache)) {
229                     if (!isLoading) {
230                         setIsLoading(true);
231                     }
232
233                     pathPromise[key] = true;
234
235                     return webdavClient.propfind(`c=${key}`, webDAVRequestConfig);
236                 }
237
238                 return Promise.resolve(null);
239             })
240             .filter((promise) => !!promise)
241         )
242             .then((requests) => {
243                 const newState = requests.map((request, index) => {
244                     if (request && request.responseXML != null) {
245                         const key = keyArray[index];
246                         const result: any = extractFilesData(request.responseXML);
247                         const sortedResult = sortBy(result, (n) => n.name).sort((n1, n2) => {
248                             if (n1.type === 'directory' && n2.type !== 'directory') {
249                                 return -1;
250                             }
251                             if (n1.type !== 'directory' && n2.type === 'directory') {
252                                 return 1;
253                             }
254                             return 0;
255                         });
256
257                         return { [key]: sortedResult };
258                     }
259                     return {};
260                 }).reduce((prev, next) => {
261                     return { ...next, ...prev };
262                 }, {});
263
264                 setPathData({ ...pathData, ...newState });
265             })
266             .finally(() => {
267                 setIsLoading(false);
268                 keyArray.forEach(key => delete pathPromise[key]);
269             });
270     };
271
272     React.useEffect(() => {
273         if (rightKey) {
274             fetchData(rightKey);
275             setLeftSearch('');
276             setRightSearch('');
277         }
278     }, [rightKey]); // eslint-disable-line react-hooks/exhaustive-deps
279
280     const currentPDH = (collectionPanel.item || {}).portableDataHash;
281     React.useEffect(() => {
282         if (currentPDH) {
283             fetchData([leftKey, rightKey], true);
284         }
285     }, [currentPDH]); // eslint-disable-line react-hooks/exhaustive-deps
286
287     React.useEffect(() => {
288         if (rightData) {
289             const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
290             setCollectionFiles(filtered, false)(dispatch);
291         }
292     }, [rightData, dispatch, rightSearch]);
293
294     const handleRightClick = React.useCallback(
295         (event) => {
296             event.preventDefault();
297             let elem = event.target;
298
299             while (elem && elem.dataset && !elem.dataset.item) {
300                 elem = elem.parentNode;
301             }
302
303             if (!elem || !elem.dataset) {
304                 return;
305             }
306
307             const { id } = elem.dataset;
308
309             const item: any = {
310                 id,
311                 data: rightData.find((elem) => elem.id === id),
312             };
313
314             if (id) {
315                 onItemMenuOpen(event, item, isWritable);
316             }
317         },
318         [onItemMenuOpen, isWritable, rightData] // eslint-disable-line react-hooks/exhaustive-deps
319     );
320
321     React.useEffect(() => {
322         let node = null;
323
324         if (parentRef && parentRef.current) {
325             node = parentRef.current;
326             (node as any).addEventListener('contextmenu', handleRightClick);
327         }
328
329         return () => {
330             if (node) {
331                 (node as any).removeEventListener('contextmenu', handleRightClick);
332             }
333         };
334     }, [parentRef, handleRightClick]);
335
336     const handleClick = React.useCallback(
337         (event: any) => {
338             let isCheckbox = false;
339             let elem = event.target;
340
341             if (elem.type === 'checkbox') {
342                 isCheckbox = true;
343             }
344
345             while (elem && elem.dataset && !elem.dataset.item) {
346                 elem = elem.parentNode;
347             }
348
349             if (elem && elem.dataset && !isCheckbox) {
350                 const { parentPath, subfolderPath, breadcrumbPath, type } = elem.dataset;
351
352                 if (breadcrumbPath) {
353                     const index = path.indexOf(breadcrumbPath);
354                     setPath([...path.slice(0, index + 1)]);
355                 }
356
357                 if (parentPath && type === 'directory') {
358                     if (path.length > 1) {
359                         path.pop()
360                     }
361
362                     setPath([...path, parentPath]);
363                 }
364
365                 if (subfolderPath && type === 'directory') {
366                     setPath([...path, subfolderPath]);
367                 }
368
369                 if (elem.dataset.id && type === 'file') {
370                     const item = rightData.find(({id}) => id === elem.dataset.id) || leftData.find(({ id }) => id === elem.dataset.id);
371                     const enhancedItem = servicesProvider.getServices().collectionService.extendFileURL(item);
372                     const fileUrl = sanitizeToken(getInlineFileUrl(enhancedItem.url, config.keepWebServiceUrl, config.keepWebInlineServiceUrl), true);
373                     window.open(fileUrl, '_blank');
374                 }
375             }
376
377             if (isCheckbox) {
378                 const { id } = elem.dataset;
379                 const item = collectionPanelFiles[id];
380                 props.onSelectionToggle(event, item);
381             }
382         },
383         [path, setPath, collectionPanelFiles] // eslint-disable-line react-hooks/exhaustive-deps
384     );
385
386     const getItemIcon = React.useCallback(
387         (type: string, activeClass: string | null) => {
388             let Icon = DefaultIcon;
389
390             switch (type) {
391                 case 'directory':
392                     Icon = DirectoryIcon;
393                     break;
394                 case 'file':
395                     Icon = FileIcon;
396                     break;
397             }
398
399             return (
400                 <ListItemIcon className={classNames(classes.listItemIcon, activeClass)}>
401                     <Icon />
402                 </ListItemIcon>
403             )
404         },
405         [classes]
406     );
407
408     const getActiveClass = React.useCallback(
409         (name) => {
410             return path[path.length - 1] === name ? classes.rowActive : null;
411         },
412         [path, classes]
413     );
414
415     const onOptionsMenuOpen = React.useCallback(
416         (ev, isWritable) => {
417             props.onOptionsMenuOpen(ev, isWritable);
418         },
419         [props.onOptionsMenuOpen] // eslint-disable-line react-hooks/exhaustive-deps
420     );
421
422     return <div data-cy="collection-files-panel" onClick={handleClick} ref={parentRef}>
423         <div className={classes.pathPanel}>
424             <div className={classes.pathPanelPathWrapper}>
425                 { path.map((p: string, index: number) => <span
426                     key={`${index}-${p}`}
427                     data-item="true"
428                     className={classes.pathPanelItem}
429                     data-breadcrumb-path={p}
430                 >
431                     <span className={classes.rowActive}>{index === 0 ? 'Home' : p}</span> <b>/</b>&nbsp;
432                 </span>) }
433             </div>
434             <Tooltip className={classes.pathPanelMenu} title="More options" disableFocusListener>
435                 <IconButton
436                     data-cy='collection-files-panel-options-btn'
437                     onClick={(ev) => {
438                         onOptionsMenuOpen(ev, isWritable);
439                     }}>
440                     <CustomizeTableIcon />
441                 </IconButton>
442             </Tooltip>
443         </div>
444         <div className={classes.wrapper}>
445             <div className={classNames(classes.leftPanel, path.length > 1 ? classes.leftPanelVisible : classes.leftPanelHidden)}  data-cy="collection-files-left-panel">
446                 <Tooltip title="Go back" className={path.length > 1 ? classes.backButton : classes.backButtonHidden}>
447                     <IconButton onClick={() => setPath([...path.slice(0, path.length -1)])}>
448                         <BackIcon />
449                     </IconButton>
450                 </Tooltip>
451             </div>
452             <div className={classes.wrapper}>
453                 <div className={classNames(classes.leftPanel, path.length > 1 ? classes.leftPanelVisible : classes.leftPanelHidden)}  data-cy="collection-files-left-panel">
454                     <Tooltip title="Go back" className={path.length > 1 ? classes.backButton : classes.backButtonHidden}>
455                         <IconButton onClick={() => setPath([...path.slice(0, path.length -1)])}>
456                             <BackIcon />
457                         </IconButton>
458                     </Tooltip>
459                     <div className={path.length > 1 ? classes.searchWrapper : classes.searchWrapperHidden}>
460                         <SearchInput selfClearProp={leftKey} label="Search" value={leftSearch} onSearch={setLeftSearch} />
461                     </div>
462                     <div className={classes.dataWrapper}>
463                         {
464                             leftData ?
465                                 <AutoSizer defaultWidth={0}>
466                                     {({ height, width }) => {
467                                         const filtered = leftData.filter(({ name }) => name.indexOf(leftSearch) > -1);
468
469                                         return !!filtered.length ? <FixedSizeList
470                                             height={height}
471                                             itemCount={filtered.length}
472                                             itemSize={35}
473                                             width={width}
474                                         >
475                                             {
476                                                 ({ index, style }) => {
477                                                     const { id, type, name } = filtered[index];
478
479                                                     return <div
480                                                         data-id={id}
481                                                         style={style}
482                                                         data-item="true"
483                                                         data-type={type}
484                                                         data-parent-path={name}
485                                                         className={classNames(classes.row, getActiveClass(name))}
486                                                         key={id}>
487                                                             {getItemIcon(type, getActiveClass(name))}
488                                                             <div className={classes.rowName}>
489                                                                 {name}
490                                                             </div>
491                                                             {
492                                                                 getActiveClass(name) ? <SidePanelRightArrowIcon
493                                                                     style={{ display: 'inline', marginTop: '5px', marginLeft: '5px' }} /> : null
494                                                             }
495                                                     </div>;
496                                                 }
497                                             }
498                                         </FixedSizeList> : <div className={classes.rowEmpty}>No directories available</div>
499                                     }}
500                                 </AutoSizer> : <div className={classes.row}><CircularProgress className={classes.loader} size={30} /></div>
501                         }
502
503                     </div>
504                 </div>
505                 <div className={classes.rightPanel} data-cy="collection-files-right-panel">
506                     <div className={classes.searchWrapper}>
507                         <SearchInput selfClearProp={rightKey} label="Search" value={rightSearch} onSearch={setRightSearch} />
508                     </div>
509                     {
510                         isWritable &&
511                         <Button
512                             className={classes.uploadButton}
513                             data-cy='upload-button'
514                             onClick={() => {
515                                 onUploadDataClick(rightKey === leftKey ? undefined : rightKey);
516                             }}
517                             variant='contained'
518                             color='primary'
519                             size='small'>
520                             <DownloadIcon className={classes.uploadIcon} />
521                             Upload data
522                         </Button>
523                     }
524                     <div className={classes.dataWrapper}>
525                         {
526                             rightData && !isLoading ?
527                                 <AutoSizer defaultHeight={500}>
528                                     {({ height, width }) => {
529                                         const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
530
531                         return !!filtered.length
532                         ? <FixedSizeList height={height} itemCount={filtered.length}
533                             itemSize={35} width={width}>{ ({ index, style }) => {
534                             const { id, type, name } = filtered[index];
535
536                             return <div data-id={id} style={style} data-item="true"
537                                 data-type={type} data-parent-path={name} key={id}
538                                 className={classNames(classes.row, getActiveClass(name))}>
539                                     { getItemIcon(type, getActiveClass(name)) }
540                                     <div className={classes.rowName}>
541                                         {name}
542                                     </div>
543                                     { getActiveClass(name)
544                                     ? <SidePanelRightArrowIcon style={{
545                                         display: 'inline',
546                                         marginTop: '5px',
547                                         marginLeft: '5px' }} />
548                                     : null }
549                             </div>;
550                         } }</FixedSizeList>
551                         : <div className={classes.rowEmpty}>No directories available</div>
552                     } }</AutoSizer>
553                     : <div className={classes.row}>
554                         <CircularProgress className={classes.loader} size={30} />
555                     </div> }
556                 </div>
557             </div>
558             <div className={classes.rightPanel}>
559                 <div className={classes.searchWrapper}>
560                     <SearchInput selfClearProp={rightKey} label="Search" value={rightSearch} onSearch={setRightSearch} />
561                 </div>
562                 { isWritable &&
563                 <Button className={classes.uploadButton} data-cy='upload-button'
564                     onClick={() => {
565                         onUploadDataClick();
566                     }}
567                     variant='contained' color='primary' size='small'>
568                     <DownloadIcon className={classes.uploadIcon} />
569                     Upload data
570                 </Button> }
571                 <div className={classes.dataWrapper}>{ rightData && !isLoading
572                     ? <AutoSizer defaultHeight={500}>{({ height, width }) => {
573                         const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
574
575                         return !!filtered.length
576                         ? <FixedSizeList height={height} itemCount={filtered.length}
577                             itemSize={35} width={width}>{ ({ index, style }) => {
578                                 const { id, type, name, size } = filtered[index];
579
580                                 return <div style={style} data-id={id} data-item="true"
581                                     data-type={type} data-subfolder-path={name}
582                                     className={classes.row} key={id}>
583                                     <Checkbox color="primary"
584                                         className={classes.rowSelection}
585                                         checked={collectionPanelFiles[id] ? collectionPanelFiles[id].value.selected : false}
586                                     />&nbsp;
587                                     {getItemIcon(type, null)}
588                                     <div className={classes.rowName}>
589                                         {name}
590                                     </div>
591                                     <span className={classes.rowName} style={{
592                                         marginLeft: 'auto', marginRight: '1rem' }}>
593                                         { formatFileSize(size) }
594                                     </span>
595                                 </div>
596                             } }</FixedSizeList>
597                         : <div className={classes.rowEmpty}>This collection is empty</div>
598                     }}</AutoSizer>
599                     : <div className={classes.row}>
600                         <CircularProgress className={classes.loader} size={30} />
601                     </div> }
602                 </div>
603             </div>
604         </div>
605     </div>}));