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