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