f565fba98a17e0ed33a76a290b0af78b9947286d
[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: '1rem',
158         marginBottom: '1rem',
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: '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: '2rem',
199         marginTop: '-1rem',
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             // Avoid fetching the same content level twice
332             if (leftKey !== rightKey) {
333                 fetchData([leftKey, rightKey], true);
334             } else {
335                 fetchData(rightKey, true);
336             }
337         }
338     }, [currentPDH]); // eslint-disable-line react-hooks/exhaustive-deps
339
340     React.useEffect(() => {
341         if (rightData) {
342             const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
343             setCollectionFiles(filtered, false)(dispatch);
344         }
345     }, [rightData, dispatch, rightSearch]);
346
347     const handleRightClick = React.useCallback(
348         (event) => {
349             event.preventDefault();
350             let elem = event.target;
351
352             while (elem && elem.dataset && !elem.dataset.item) {
353                 elem = elem.parentNode;
354             }
355
356             if (!elem || !elem.dataset) {
357                 return;
358             }
359
360             const { id } = elem.dataset;
361
362             const item: any = {
363                 id,
364                 data: rightData.find((elem) => elem.id === id),
365             };
366
367             if (id) {
368                 onItemMenuOpen(event, item, isWritable);
369             }
370         },
371         [onItemMenuOpen, isWritable, rightData]);
372
373     React.useEffect(() => {
374         let node = null;
375
376         if (parentRef?.current) {
377             node = parentRef.current;
378             (node as any).addEventListener('contextmenu', handleRightClick);
379         }
380
381         return () => {
382             if (node) {
383                 (node as any).removeEventListener('contextmenu', handleRightClick);
384             }
385         };
386     }, [parentRef, handleRightClick]);
387
388     const handleClick = React.useCallback(
389         (event: any) => {
390             let isCheckbox = false;
391             let isMoreButton = false;
392             let elem = event.target;
393
394             if (elem.type === 'checkbox') {
395                 isCheckbox = true;
396             }
397             // The "More options" button click event could be triggered on its
398             // internal graphic element.
399             else if ((elem.dataset && elem.dataset.id === 'moreOptions') || (elem.parentNode && elem.parentNode.dataset && elem.parentNode.dataset.id === 'moreOptions')) {
400                 isMoreButton = true;
401             }
402
403             while (elem && elem.dataset && !elem.dataset.item) {
404                 elem = elem.parentNode;
405             }
406
407             if (elem && elem.dataset && !isCheckbox && !isMoreButton) {
408                 const { parentPath, subfolderPath, breadcrumbPath, type } = elem.dataset;
409
410                 if (breadcrumbPath) {
411                     const index = path.indexOf(breadcrumbPath);
412                     setPath([...path.slice(0, index + 1)]);
413                 }
414
415                 if (parentPath && type === 'directory') {
416                     if (path.length > 1) {
417                         path.pop()
418                     }
419
420                     setPath([...path, parentPath]);
421                 }
422
423                 if (subfolderPath && type === 'directory') {
424                     setPath([...path, subfolderPath]);
425                 }
426
427                 if (elem.dataset.id && type === 'file') {
428                     const item = rightData.find(({id}) => id === elem.dataset.id) || leftData.find(({ id }) => id === elem.dataset.id);
429                     const enhancedItem = servicesProvider.getServices().collectionService.extendFileURL(item);
430                     const fileUrl = sanitizeToken(getInlineFileUrl(enhancedItem.url, config.keepWebServiceUrl, config.keepWebInlineServiceUrl), true);
431                     window.open(fileUrl, '_blank');
432                 }
433             }
434
435             if (isCheckbox) {
436                 const { id } = elem.dataset;
437                 const item = collectionPanelFiles[id];
438                 props.onSelectionToggle(event, item);
439             }
440             if (isMoreButton) {
441                 const { id } = elem.dataset;
442                 const item: any = {
443                     id,
444                     data: rightData.find((elem) => elem.id === id),
445                 };
446                 onItemMenuOpen(event, item, isWritable);
447             }
448         },
449         [path, setPath, collectionPanelFiles] // eslint-disable-line react-hooks/exhaustive-deps
450     );
451
452     const getItemIcon = React.useCallback(
453         (type: string, activeClass: string | null) => {
454             let Icon = DefaultIcon;
455
456             switch (type) {
457                 case 'directory':
458                     Icon = DirectoryIcon;
459                     break;
460                 case 'file':
461                     Icon = FileIcon;
462                     break;
463             }
464
465             return (
466                 <ListItemIcon className={classNames(classes.listItemIcon, activeClass)}>
467                     <Icon />
468                 </ListItemIcon>
469             )
470         },
471         [classes]
472     );
473
474     const getActiveClass = React.useCallback(
475         (name) => {
476             return path[path.length - 1] === name ? classes.rowActive : null;
477         },
478         [path, classes]
479     );
480
481     const onOptionsMenuOpen = React.useCallback(
482         (ev, isWritable) => {
483             props.onOptionsMenuOpen(ev, isWritable);
484         },
485         [props.onOptionsMenuOpen] // eslint-disable-line react-hooks/exhaustive-deps
486     );
487
488     return <div data-cy="collection-files-panel" onClick={handleClick} ref={parentRef}>
489         <div className={classes.pathPanel}>
490             <div className={classes.pathPanelPathWrapper}>
491             { path.map( (p: string, index: number) =>
492                 <span key={`${index}-${p}`} data-item="true"
493                 className={classes.pathPanelItem} data-breadcrumb-path={p}>
494                     <span className={classes.rowActive}>{index === 0 ? 'Home' : p}</span> <b>/</b>&nbsp;
495                 </span>)
496             }
497             </div>
498             <Tooltip className={classes.pathPanelMenu} title="More options" disableFocusListener>
499                 <IconButton data-cy='collection-files-panel-options-btn'
500                     onClick={(ev) => {
501                         onOptionsMenuOpen(ev, isWritable);
502                     }}>
503                     <CustomizeTableIcon />
504                 </IconButton>
505             </Tooltip>
506         </div>
507         <div className={classes.wrapper}>
508             <div className={classNames(classes.leftPanel, path.length > 1 ? classes.leftPanelVisible : classes.leftPanelHidden)} data-cy="collection-files-left-panel">
509                 <Tooltip title="Go back" className={path.length > 1 ? classes.backButton : classes.backButtonHidden}>
510                     <IconButton onClick={() => setPath([...path.slice(0, path.length -1)])}>
511                         <BackIcon />
512                     </IconButton>
513                 </Tooltip>
514                 <div className={path.length > 1 ? classes.searchWrapper : classes.searchWrapperHidden}>
515                     <SearchInput selfClearProp={leftKey} label="Search" value={leftSearch} onSearch={setLeftSearch} />
516                 </div>
517                 <div className={classes.dataWrapper}>{ leftData
518                 ? <AutoSizer defaultWidth={0}>{({ height, width }) => {
519                     const filtered = leftData.filter(({ name }) => name.indexOf(leftSearch) > -1);
520                     return !!filtered.length
521                     ? <FixedSizeList height={height} itemCount={filtered.length}
522                         itemSize={35} width={width}>{ ({ index, style }) => {
523                         const { id, type, name } = filtered[index];
524                         return <div data-id={id} style={style} data-item="true"
525                             data-type={type} data-parent-path={name}
526                             className={classNames(classes.row, getActiveClass(name))}
527                             key={id}>
528                                 { getItemIcon(type, getActiveClass(name)) }
529                                 <div className={classes.rowName}>
530                                     {name}
531                                 </div>
532                                 { getActiveClass(name)
533                                 ? <SidePanelRightArrowIcon
534                                     style={{ display: 'inline', marginTop: '5px', marginLeft: '5px' }} />
535                                 : null
536                                 }
537                         </div>;
538                     }}</FixedSizeList>
539                     : <div className={classes.rowEmpty}>No directories available</div>
540                     }}
541                 </AutoSizer>
542                 : <div className={classes.row}><CircularProgress className={classes.loader} size={30} /></div> }
543                 </div>
544             </div>
545             <div className={classes.rightPanel} data-cy="collection-files-right-panel">
546                 <div className={classes.searchWrapper}>
547                     <SearchInput selfClearProp={rightKey} label="Search" value={rightSearch} onSearch={setRightSearch} />
548                 </div>
549                 { isWritable &&
550                 <Button className={classes.uploadButton} data-cy='upload-button'
551                     onClick={() => {
552                         onUploadDataClick(rightKey === leftKey ? undefined : rightKey);
553                     }}
554                     variant='contained' color='primary' size='small'>
555                     <DownloadIcon className={classes.uploadIcon} />
556                     Upload data
557                 </Button> }
558                 <div className={classes.dataWrapper}>{ rightData && !isLoading
559                     ? <AutoSizer defaultHeight={500}>{({ height, width }) => {
560                         const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
561                         return !!filtered.length
562                         ? <FixedSizeList height={height} itemCount={filtered.length}
563                             itemSize={35} width={width}>{ ({ index, style }) => {
564                                 const { id, type, name, size } = filtered[index];
565
566                                 return <div style={style} data-id={id} data-item="true"
567                                     data-type={type} data-subfolder-path={name}
568                                     className={classes.row} key={id}>
569                                     <Checkbox color="primary"
570                                         className={classes.rowSelection}
571                                         checked={collectionPanelFiles[id] ? collectionPanelFiles[id].value.selected : false}
572                                     />&nbsp;
573                                     {getItemIcon(type, null)}
574                                     <div className={classes.rowName}>
575                                         {name}
576                                     </div>
577                                     <span className={classes.rowName} style={{
578                                         marginLeft: 'auto', marginRight: '1rem' }}>
579                                         { formatFileSize(size) }
580                                     </span>
581                                     <Tooltip title="More options" disableFocusListener>
582                                         <IconButton data-id='moreOptions'
583                                             className={classes.moreOptionsButton}>
584                                             <MoreOptionsIcon data-cy='file-item-options-btn' data-id='moreOptions' 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>}));