18787: Further improves code readability.
[arvados-workbench2.git] / src / components / collection-panel-files / collection-panel-files.tsx
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import React from 'react';
6 import classNames from 'classnames';
7 import { connect } from 'react-redux';
8 import { FixedSizeList } from "react-window";
9 import AutoSizer from "react-virtualized-auto-sizer";
10 import servicesProvider from 'common/service-provider';
11 import { CustomizeTableIcon, DownloadIcon } from 'components/icon/icon';
12 import { SearchInput } from 'components/search-input/search-input';
13 import {
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 _ from 'lodash';
43
44 export interface CollectionPanelFilesProps {
45     items: any;
46     isWritable: boolean;
47     onUploadDataClick: (targetLocation?: string) => void;
48     onSearchChange: (searchValue: string) => void;
49     onItemMenuOpen: (event: React.MouseEvent<HTMLElement>, item: TreeItem<FileTreeData>, isWritable: boolean) => void;
50     onOptionsMenuOpen: (event: React.MouseEvent<HTMLElement>, isWritable: boolean) => void;
51     onSelectionToggle: (event: React.MouseEvent<HTMLElement>, item: TreeItem<FileTreeData>) => void;
52     onCollapseToggle: (id: string, status: TreeItemStatus) => void;
53     onFileClick: (id: string) => void;
54     currentItemUuid: any;
55     dispatch: Function;
56     collectionPanelFiles: any;
57     collectionPanel: any;
58 }
59
60 type CssRules = "backButton"
61     | "backButtonHidden"
62     | "pathPanelPathWrapper"
63     | "uploadButton"
64     | "uploadIcon"
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 });
214
215 const pathPromise = {};
216
217 let prevState = {};
218 function difference(object, base) {
219         function changes(object, base) {
220                 return _.transform(object, function(result, value, key) {
221                         if (!_.isEqual(value, base[key])) {
222                                 result[key] = (_.isObject(value) && _.isObject(base[key])) ? changes(value, base[key]) : value;
223                         }
224                 });
225         }
226         return changes(object, base);
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 diff = difference(props, prevState);
234     prevState = props;
235     console.log('---> render CollectionPanel <------', diff);
236     const { classes, onItemMenuOpen, onUploadDataClick, isWritable, dispatch, collectionPanelFiles, collectionPanel } = props;
237     const { apiToken, config } = props.auth;
238
239     const webdavClient = new WebDAV();
240     webdavClient.defaults.baseURL = config.keepWebServiceUrl;
241     webdavClient.defaults.headers = {
242         Authorization: `Bearer ${apiToken}`
243     };
244
245     const webDAVRequestConfig: WebDAVRequestConfig = {
246         headers: {
247             Depth: '1',
248         },
249     };
250
251     const parentRef = React.useRef(null);
252     const [path, setPath]: any = React.useState([]);
253     const [pathData, setPathData]: any = React.useState({});
254     const [isLoading, setIsLoading] = React.useState(false);
255     const [leftSearch, setLeftSearch] = React.useState('');
256     const [rightSearch, setRightSearch] = React.useState('');
257
258     const leftKey = (path.length > 1 ? path.slice(0, path.length - 1) : path).join('/');
259     const rightKey = path.join('/');
260
261     const leftData = pathData[leftKey] || [];
262     const rightData = pathData[rightKey];
263
264     React.useEffect(() => {
265         if (props.currentItemUuid) {
266             console.log(' --> useEffect current UUID: ', props.currentItemUuid);
267             setPathData({});
268             setPath([props.currentItemUuid]);
269         }
270     }, [props.currentItemUuid]);
271
272     const fetchData = (keys, ignoreCache = false) => {
273         console.log('---> fetchData', keys);
274         const keyArray = Array.isArray(keys) ? keys : [keys];
275
276         Promise.all(keyArray.filter(key => !!key)
277             .map((key) => {
278                 const dataExists = !!pathData[key];
279                 const runningRequest = pathPromise[key];
280
281                 if ((!dataExists || ignoreCache) && (!runningRequest || ignoreCache)) {
282                     if (!isLoading) {
283                         setIsLoading(true);
284                     }
285
286                     pathPromise[key] = true;
287
288                     console.log('>>> fetching data for key', key);
289                     return webdavClient.propfind(`c=${key}`, webDAVRequestConfig);
290                 }
291
292                 return Promise.resolve(null);
293             })
294             .filter((promise) => !!promise)
295         )
296         .then((requests) => {
297             const newState = requests.map((request, index) => {
298                 if (request && request.responseXML != null) {
299                     console.log(">>> got data for key", keyArray[index]);
300                     const key = keyArray[index];
301                     const result: any = extractFilesData(request.responseXML);
302                     const sortedResult = sortBy(result, (n) => n.name).sort((n1, n2) => {
303                         if (n1.type === 'directory' && n2.type !== 'directory') {
304                             return -1;
305                         }
306                         if (n1.type !== 'directory' && n2.type === 'directory') {
307                             return 1;
308                         }
309                         return 0;
310                     });
311
312                     return { [key]: sortedResult };
313                 }
314                 return {};
315             }).reduce((prev, next) => {
316                 return { ...next, ...prev };
317             }, {});
318
319             setPathData({ ...pathData, ...newState });
320         })
321         .finally(() => {
322             setIsLoading(false);
323             keyArray.forEach(key => delete pathPromise[key]);
324         });
325     };
326
327     React.useEffect(() => {
328         if (rightKey) {
329             console.log('---> useEffect rightKey:', rightKey);
330             fetchData(rightKey);
331             setLeftSearch('');
332             setRightSearch('');
333         }
334     }, [rightKey]); // eslint-disable-line react-hooks/exhaustive-deps
335
336     const currentPDH = (collectionPanel.item || {}).portableDataHash;
337     React.useEffect(() => {
338         if (currentPDH) {
339             console.log('---> useEffect PDH change:', currentPDH);
340             // Avoid fetching the same content level twice
341             if (leftKey !== rightKey) {
342                 fetchData([leftKey, rightKey], true);
343             } else {
344                 fetchData(rightKey, true);
345             }
346         }
347     }, [currentPDH]); // eslint-disable-line react-hooks/exhaustive-deps
348
349     React.useEffect(() => {
350         if (rightData) {
351             console.log('---> useEffect rightData:', rightData, 'search:', rightSearch);
352             const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
353             setCollectionFiles(filtered, false)(dispatch);
354         }
355     }, [rightData, dispatch, rightSearch]);
356
357     const handleRightClick = React.useCallback(
358         (event) => {
359             event.preventDefault();
360             let elem = event.target;
361
362             while (elem && elem.dataset && !elem.dataset.item) {
363                 elem = elem.parentNode;
364             }
365
366             if (!elem || !elem.dataset) {
367                 return;
368             }
369
370             const { id } = elem.dataset;
371
372             const item: any = {
373                 id,
374                 data: rightData.find((elem) => elem.id === id),
375             };
376
377             if (id) {
378                 onItemMenuOpen(event, item, isWritable);
379             }
380         },
381         [onItemMenuOpen, isWritable, rightData] // eslint-disable-line react-hooks/exhaustive-deps
382     );
383
384     React.useEffect(() => {
385         let node = null;
386
387         if (parentRef && parentRef.current) {
388             console.log('---> useEffect parentRef:', parentRef);
389             node = parentRef.current;
390             (node as any).addEventListener('contextmenu', handleRightClick);
391         }
392
393         return () => {
394             if (node) {
395                 (node as any).removeEventListener('contextmenu', handleRightClick);
396             }
397         };
398     }, [parentRef, handleRightClick]);
399
400     const handleClick = React.useCallback(
401         (event: any) => {
402             let isCheckbox = false;
403             let elem = event.target;
404
405             if (elem.type === 'checkbox') {
406                 isCheckbox = true;
407             }
408
409             while (elem && elem.dataset && !elem.dataset.item) {
410                 elem = elem.parentNode;
411             }
412
413             if (elem && elem.dataset && !isCheckbox) {
414                 const { parentPath, subfolderPath, breadcrumbPath, type } = elem.dataset;
415
416                 if (breadcrumbPath) {
417                     const index = path.indexOf(breadcrumbPath);
418                     setPath([...path.slice(0, index + 1)]);
419                 }
420
421                 if (parentPath && type === 'directory') {
422                     if (path.length > 1) {
423                         path.pop()
424                     }
425
426                     setPath([...path, parentPath]);
427                 }
428
429                 if (subfolderPath && type === 'directory') {
430                     setPath([...path, subfolderPath]);
431                 }
432
433                 if (elem.dataset.id && type === 'file') {
434                     const item = rightData.find(({id}) => id === elem.dataset.id) || leftData.find(({ id }) => id === elem.dataset.id);
435                     const enhancedItem = servicesProvider.getServices().collectionService.extendFileURL(item);
436                     const fileUrl = sanitizeToken(getInlineFileUrl(enhancedItem.url, config.keepWebServiceUrl, config.keepWebInlineServiceUrl), true);
437                     window.open(fileUrl, '_blank');
438                 }
439             }
440
441             if (isCheckbox) {
442                 const { id } = elem.dataset;
443                 const item = collectionPanelFiles[id];
444                 props.onSelectionToggle(event, item);
445             }
446         },
447         [path, setPath, collectionPanelFiles] // eslint-disable-line react-hooks/exhaustive-deps
448     );
449
450     const getItemIcon = React.useCallback(
451         (type: string, activeClass: string | null) => {
452             let Icon = DefaultIcon;
453
454             switch (type) {
455                 case 'directory':
456                     Icon = DirectoryIcon;
457                     break;
458                 case 'file':
459                     Icon = FileIcon;
460                     break;
461             }
462
463             return (
464                 <ListItemIcon className={classNames(classes.listItemIcon, activeClass)}>
465                     <Icon />
466                 </ListItemIcon>
467             )
468         },
469         [classes]
470     );
471
472     const getActiveClass = React.useCallback(
473         (name) => {
474             return path[path.length - 1] === name ? classes.rowActive : null;
475         },
476         [path, classes]
477     );
478
479     const onOptionsMenuOpen = React.useCallback(
480         (ev, isWritable) => {
481             props.onOptionsMenuOpen(ev, isWritable);
482         },
483         [props.onOptionsMenuOpen] // eslint-disable-line react-hooks/exhaustive-deps
484     );
485
486     return <div data-cy="collection-files-panel" onClick={handleClick} ref={parentRef}>
487         <div className={classes.pathPanel}>
488             <div className={classes.pathPanelPathWrapper}>
489             { path.map( (p: string, index: number) =>
490                 <span key={`${index}-${p}`} data-item="true"
491                 className={classes.pathPanelItem} data-breadcrumb-path={p}>
492                     <span className={classes.rowActive}>{index === 0 ? 'Home' : p}</span> <b>/</b>&nbsp;
493                 </span>)
494             }
495             </div>
496             <Tooltip className={classes.pathPanelMenu} title="More options" disableFocusListener>
497                 <IconButton data-cy='collection-files-panel-options-btn'
498                     onClick={(ev) => {
499                         onOptionsMenuOpen(ev, isWritable);
500                     }}>
501                     <CustomizeTableIcon />
502                 </IconButton>
503             </Tooltip>
504         </div>
505         <div className={classes.wrapper}>
506             <div className={classNames(classes.leftPanel, path.length > 1 ? classes.leftPanelVisible : classes.leftPanelHidden)}  data-cy="collection-files-left-panel">
507                 <Tooltip title="Go back" className={path.length > 1 ? classes.backButton : classes.backButtonHidden}>
508                     <IconButton onClick={() => setPath([...path.slice(0, path.length -1)])}>
509                         <BackIcon />
510                     </IconButton>
511                 </Tooltip>
512                 <div className={path.length > 1 ? classes.searchWrapper : classes.searchWrapperHidden}>
513                     <SearchInput selfClearProp={leftKey} label="Search" value={leftSearch} onSearch={setLeftSearch} />
514                 </div>
515                 <div className={classes.dataWrapper}>{ leftData
516                 ? <AutoSizer defaultWidth={0}>{({ height, width }) => {
517                     const filtered = leftData.filter(({ name }) => name.indexOf(leftSearch) > -1);
518                     return !!filtered.length
519                     ? <FixedSizeList height={height} itemCount={filtered.length}
520                         itemSize={35} width={width}>{ ({ index, style }) => {
521                         console.log("Left Data ROW: ", filtered[index]);
522                         const { id, type, name } = filtered[index];
523                         return <div data-id={id} style={style} data-item="true"
524                             data-type={type} data-parent-path={name}
525                             className={classNames(classes.row, getActiveClass(name))}
526                             key={id}>
527                                 { getItemIcon(type, getActiveClass(name)) }
528                                 <div className={classes.rowName}>
529                                     {name}
530                                 </div>
531                                 { getActiveClass(name)
532                                 ? <SidePanelRightArrowIcon
533                                     style={{ display: 'inline', marginTop: '5px', marginLeft: '5px' }} />
534                                 : null
535                                 }
536                         </div>;
537                     }}</FixedSizeList>
538                     : <div className={classes.rowEmpty}>No directories available</div>
539                     }}
540                 </AutoSizer>
541                 : <div className={classes.row}><CircularProgress className={classes.loader} size={30} /></div> }
542                 </div>
543             </div>
544             <div className={classes.rightPanel}>
545                 <div className={classes.searchWrapper}>
546                     <SearchInput selfClearProp={rightKey} label="Search" value={rightSearch} onSearch={setRightSearch} />
547                 </div>
548                 { isWritable &&
549                 <Button className={classes.uploadButton} data-cy='upload-button'
550                     onClick={() => {
551                         onUploadDataClick(rightKey === leftKey ? undefined : rightKey);
552                     }}
553                     variant='contained' color='primary' size='small'>
554                     <DownloadIcon className={classes.uploadIcon} />
555                     Upload data
556                 </Button> }
557                 <div className={classes.dataWrapper}>{ rightData && !isLoading
558                     ? <AutoSizer defaultHeight={500}>{({ height, width }) => {
559                         const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
560                         console.log("Right Data: ", filtered);
561                         return !!filtered.length
562                         ? <FixedSizeList height={height} itemCount={filtered.length}
563                             itemSize={35} width={width}>{ ({ index, style }) => {
564                                 console.log("Right Data ROW: ", filtered[index]);
565                                 const { id, type, name, size } = filtered[index];
566
567                                 return <div style={style} data-id={id} data-item="true"
568                                     data-type={type} data-subfolder-path={name}
569                                     className={classes.row} key={id}>
570                                     <Checkbox color="primary"
571                                         className={classes.rowSelection}
572                                         checked={collectionPanelFiles[id] ? collectionPanelFiles[id].value.selected : false}
573                                     />&nbsp;
574                                     {getItemIcon(type, null)}
575                                     <div className={classes.rowName}>
576                                         {name}
577                                     </div>
578                                     <span className={classes.rowName} style={{
579                                         marginLeft: 'auto', marginRight: '1rem' }}>
580                                         { formatFileSize(size) }
581                                     </span>
582                                 </div>
583                             } }</FixedSizeList>
584                         : <div className={classes.rowEmpty}>This collection is empty</div>
585                     }}</AutoSizer>
586                     : <div className={classes.row}>
587                         <CircularProgress className={classes.loader} size={30} />
588                     </div> }
589                 </div>
590             </div>
591         </div>
592     </div>}));