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