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