Merge branch '18169-cancel-button-not-working' into main
[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         marginBottom: '1rem',
52         color: 'rgba(0, 0, 0, 0.87)',
53         fontSize: '0.875rem',
54         fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
55         fontWeight: 400,
56         lineHeight: '1.5',
57         letterSpacing: '0.01071em'
58     },
59     backButton: {
60         color: '#00bfa5',
61         cursor: 'pointer',
62         float: 'left',
63     },
64     backButtonHidden: {
65         display: 'none',
66     },
67     dataWrapper: {
68         minHeight: '500px'
69     },
70     row: {
71         display: 'flex',
72         marginTop: '0.5rem',
73         marginBottom: '0.5rem',
74         cursor: 'pointer',
75         "&:hover": {
76             backgroundColor: 'rgba(0, 0, 0, 0.08)',
77         }
78     },
79     rowEmpty: {
80         top: '40%',
81         width: '100%',
82         textAlign: 'center',
83         position: 'absolute'
84     },
85     loader: {
86         top: '50%',
87         left: '50%',
88         marginTop: '-15px',
89         marginLeft: '-15px',
90         position: 'absolute'
91     },
92     rowName: {
93         display: 'inline-flex',
94         flexDirection: 'column',
95         justifyContent: 'center'
96     },
97     searchWrapper: {
98         display: 'inline-block',
99         marginBottom: '1rem',
100         marginLeft: '1rem',
101     },
102     searchWrapperHidden: {
103         width: '0px'
104     },
105     rowSelection: {
106         padding: '0px',
107     },
108     rowActive: {
109         color: `${theme.palette.primary.main} !important`,
110     },
111     listItemIcon: {
112         display: 'inline-flex',
113         flexDirection: 'column',
114         justifyContent: 'center'
115     },
116     pathPanelMenu: {
117         float: 'right',
118         marginTop: '-15px',
119     },
120     pathPanel: {
121         padding: '1rem',
122         marginBottom: '1rem',
123         backgroundColor: '#fff',
124         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%)',
125     },
126     pathPanelPathWrapper: {
127         display: 'inline-block',
128     },
129     leftPanel: {
130         flex: 0,
131         padding: '1rem',
132         marginRight: '1rem',
133         whiteSpace: 'nowrap',
134         position: 'relative',
135         backgroundColor: '#fff',
136         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%)',
137     },
138     leftPanelVisible: {
139         opacity: 1,
140         flex: '50%',
141         animation: `animateVisible 1000ms ${theme.transitions.easing.easeOut}`
142     },
143     leftPanelHidden: {
144         opacity: 0,
145         flex: 'initial',
146         padding: '0',
147         marginRight: '0',
148     },
149     "@keyframes animateVisible": {
150         "0%": {
151             opacity: 0,
152             flex: 'initial',
153         },
154         "100%": {
155             opacity: 1,
156             flex: '50%',
157         }
158     },
159     rightPanel: {
160         flex: '50%',
161         padding: '1rem',
162         paddingTop: '2rem',
163         marginTop: '-1rem',
164         position: 'relative',
165         backgroundColor: '#fff',
166         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%)',
167     },
168     pathPanelItem: {
169         cursor: 'pointer',
170     },
171     uploadIcon: {
172         transform: 'rotate(180deg)'
173     },
174     uploadButton: {
175         float: 'right',
176     }
177 });
178
179 const pathPromise = {};
180
181 export const CollectionPanelFiles = withStyles(styles)(connect((state: RootState) => ({
182     auth: state.auth,
183     collectionPanel: state.collectionPanel,
184     collectionPanelFiles: state.collectionPanelFiles,
185 }))((props: CollectionPanelFilesProps & WithStyles<CssRules> & { auth: AuthState }) => {
186     const { classes, onItemMenuOpen, onUploadDataClick, isWritable, dispatch, collectionPanelFiles, collectionPanel } = props;
187     const { apiToken, config } = props.auth;
188
189     const webdavClient = new WebDAV();
190     webdavClient.defaults.baseURL = config.keepWebServiceUrl;
191     webdavClient.defaults.headers = {
192         Authorization: `Bearer ${apiToken}`
193     };
194
195     const webDAVRequestConfig: WebDAVRequestConfig = {
196         headers: {
197             Depth: '1',
198         },
199     };
200
201     const parentRef = React.useRef(null);
202     const [path, setPath]: any = React.useState([]);
203     const [pathData, setPathData]: any = React.useState({});
204     const [isLoading, setIsLoading] = React.useState(false);
205     const [collectionAutofetchEnabled, setCollectionAutofetchEnabled] = React.useState(false);
206     const [leftSearch, setLeftSearch] = React.useState('');
207     const [rightSearch, setRightSearch] = React.useState('');
208
209     const leftKey = (path.length > 1 ? path.slice(0, path.length - 1) : path).join('/');
210     const rightKey = path.join('/');
211
212     const leftData = pathData[leftKey] || [];
213     const rightData = pathData[rightKey];
214
215     React.useEffect(() => {
216         if (props.currentItemUuid) {
217             setPathData({});
218             setPath([props.currentItemUuid]);
219         }
220     }, [props.currentItemUuid]);
221
222     const fetchData = (keys, ignoreCache = false) => {
223         const keyArray = Array.isArray(keys) ? keys : [keys];
224
225         Promise.all(keyArray
226             .map((key) => {
227                 const dataExists = !!pathData[key];
228                 const runningRequest = pathPromise[key];
229
230                 if ((!dataExists || ignoreCache) && (!runningRequest || ignoreCache)) {
231                     if (!isLoading) {
232                         setIsLoading(true);
233                     }
234
235                     pathPromise[key] = true;
236
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                         const key = keyArray[index];
248                         const result: any = extractFilesData(request.responseXML);
249                         const sortedResult = sortBy(result, (n) => n.name).sort((n1, n2) => {
250                             if (n1.type === 'directory' && n2.type !== 'directory') {
251                                 return -1;
252                             }
253                             if (n1.type !== 'directory' && n2.type === 'directory') {
254                                 return 1;
255                             }
256                             return 0;
257                         });
258
259                         return { [key]: sortedResult };
260                     }
261                     return {};
262                 }).reduce((prev, next) => {
263                     return { ...next, ...prev };
264                 }, {});
265
266                 setPathData({ ...pathData, ...newState });
267             })
268             .finally(() => {
269                 setIsLoading(false);
270                 keyArray.forEach(key => delete pathPromise[key]);
271             });
272     };
273
274     React.useEffect(() => {
275         if (rightKey) {
276             fetchData(rightKey);
277             setLeftSearch('');
278             setRightSearch('');
279         }
280     }, [rightKey]); // eslint-disable-line react-hooks/exhaustive-deps
281
282     React.useEffect(() => {
283         const hash = (collectionPanel.item || {}).portableDataHash;
284
285         if (hash && collectionAutofetchEnabled) {
286             fetchData([leftKey, rightKey], true);
287         }
288     }, [(collectionPanel.item || {}).portableDataHash]); // eslint-disable-line react-hooks/exhaustive-deps
289
290     React.useEffect(() => {
291         if (rightData) {
292             const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
293             setCollectionFiles(filtered, false)(dispatch);
294         }
295     }, [rightData, dispatch, rightSearch]);
296
297     const handleRightClick = React.useCallback(
298         (event) => {
299             event.preventDefault();
300             let elem = event.target;
301
302             while (elem && elem.dataset && !elem.dataset.item) {
303                 elem = elem.parentNode;
304             }
305
306             if (!elem || !elem.dataset) {
307                 return;
308             }
309
310             const { id } = elem.dataset;
311
312             const item: any = {
313                 id,
314                 data: rightData.find((elem) => elem.id === id),
315             };
316
317             if (id) {
318                 onItemMenuOpen(event, item, isWritable);
319
320                 if (!collectionAutofetchEnabled) {
321                     setCollectionAutofetchEnabled(true);
322                 }
323             }
324         },
325         [onItemMenuOpen, isWritable, rightData] // eslint-disable-line react-hooks/exhaustive-deps
326     );
327
328     React.useEffect(() => {
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     return (
430         <div data-cy="collection-files-panel" onClick={handleClick} ref={parentRef}>
431             <div className={classes.pathPanel}>
432                 <div className={classes.pathPanelPathWrapper}>
433                     {
434                         path
435                             .map((p: string, index: number) => <span
436                                 key={`${index}-${p}`}
437                                 data-item="true"
438                                 className={classes.pathPanelItem}
439                                 data-breadcrumb-path={p}
440                             >
441                                 <span className={classes.rowActive}>{index === 0 ? 'Home' : p}</span> <b>/</b>&nbsp;
442                             </span>)
443                     }
444                 </div>
445                 <Tooltip className={classes.pathPanelMenu} title="More options" disableFocusListener>
446                     <IconButton
447                         data-cy='collection-files-panel-options-btn'
448                         onClick={(ev) => {
449                             if (!collectionAutofetchEnabled) {
450                                 setCollectionAutofetchEnabled(true);
451                             }
452                             onOptionsMenuOpen(ev, isWritable);
453                         }}>
454                         <CustomizeTableIcon />
455                     </IconButton>
456                 </Tooltip>
457             </div>
458             <div className={classes.wrapper}>
459                 <div className={classNames(classes.leftPanel, path.length > 1 ? classes.leftPanelVisible : classes.leftPanelHidden)}>
460                     <Tooltip title="Go back" className={path.length > 1 ? classes.backButton : classes.backButtonHidden}>
461                         <IconButton onClick={() => setPath([...path.slice(0, path.length -1)])}>
462                             <BackIcon />
463                         </IconButton>
464                     </Tooltip>
465                     <div className={path.length > 1 ? classes.searchWrapper : classes.searchWrapperHidden}>
466                         <SearchInput label="Search" value={leftSearch} onSearch={setLeftSearch} />
467                     </div>
468                     <div className={classes.dataWrapper}>
469                         {
470                             leftData ?
471                                 <AutoSizer defaultWidth={0}>
472                                     {({ height, width }) => {
473                                         const filtered = leftData.filter(({ name }) => name.indexOf(leftSearch) > -1);
474
475                                         return !!filtered.length ? <FixedSizeList
476                                             height={height}
477                                             itemCount={filtered.length}
478                                             itemSize={35}
479                                             width={width}
480                                         >
481                                             {
482                                                 ({ index, style }) => {
483                                                     const { id, type, name } = filtered[index];
484
485                                                     return <div
486                                                         data-id={id}
487                                                         style={style}
488                                                         data-item="true"
489                                                         data-type={type}
490                                                         data-parent-path={name}
491                                                         className={classNames(classes.row, getActiveClass(name))}
492                                                         key={id}>
493                                                             {getItemIcon(type, getActiveClass(name))} 
494                                                             <div className={classes.rowName}>
495                                                                 {name}
496                                                             </div>
497                                                             {
498                                                                 getActiveClass(name) ? <SidePanelRightArrowIcon
499                                                                     style={{ display: 'inline', marginTop: '5px', marginLeft: '5px' }} /> : null
500                                                             }
501                                                     </div>;
502                                                 }
503                                             }
504                                         </FixedSizeList> : <div className={classes.rowEmpty}>No directories available</div>
505                                     }}
506                                 </AutoSizer> : <div className={classes.row}><CircularProgress className={classes.loader} size={30} /></div>
507                         }
508
509                     </div>
510                 </div>
511                 <div className={classes.rightPanel}>
512                     <div className={classes.searchWrapper}>
513                         <SearchInput label="Search" value={rightSearch} onSearch={setRightSearch} />
514                     </div>
515                     {
516                         isWritable &&
517                         <Button
518                             className={classes.uploadButton}
519                             data-cy='upload-button'
520                             onClick={() => {
521                                 if (!collectionAutofetchEnabled) {
522                                     setCollectionAutofetchEnabled(true);
523                                 }
524                                 onUploadDataClick();
525                             }}
526                             variant='contained'
527                             color='primary'
528                             size='small'>
529                             <DownloadIcon className={classes.uploadIcon} />
530                             Upload data
531                         </Button>
532                     }
533                     <div className={classes.dataWrapper}>
534                         {
535                             rightData && !isLoading ?
536                                 <AutoSizer defaultHeight={500}>
537                                     {({ height, width }) => {
538                                         const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
539
540                                         return !!filtered.length ? <FixedSizeList
541                                             height={height}
542                                             itemCount={filtered.length}
543                                             itemSize={35}
544                                             width={width}
545                                         >
546                                             {
547                                                 ({ index, style }) => {
548                                                     const { id, type, name, size } = filtered[index];
549
550                                                     return <div
551                                                         style={style}
552                                                         data-id={id}
553                                                         data-item="true"
554                                                         data-type={type}
555                                                         data-subfolder-path={name}
556                                                         className={classes.row} key={id}>
557                                                         <Checkbox
558                                                             color="primary"
559                                                             className={classes.rowSelection}
560                                                             checked={collectionPanelFiles[id] ? collectionPanelFiles[id].value.selected : false}
561                                                         />&nbsp;
562                                                     {getItemIcon(type, null)} <div className={classes.rowName}>
563                                                             {name}
564                                                         </div>
565                                                         <span className={classes.rowName} style={{ marginLeft: 'auto', marginRight: '1rem' }}>
566                                                             {formatFileSize(size)}
567                                                         </span>
568                                                     </div>
569                                                 }
570                                             }
571                                         </FixedSizeList> : <div className={classes.rowEmpty}>No data available</div>
572                                     }}
573                                 </AutoSizer> : <div className={classes.row}><CircularProgress className={classes.loader} size={30} /></div>
574                         }
575                     </div>
576                 </div>
577             </div>
578         </div>
579     );
580 }));