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