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