Merge remote-tracking branch 'origin/main' into 17579-Clear-table-filter-when-changin...
[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     React.useEffect(() => {
282         const hash = (collectionPanel.item || {}).portableDataHash;
283
284         if (hash && collectionAutofetchEnabled) {
285             fetchData([leftKey, rightKey], true);
286         }
287     }, [(collectionPanel.item || {}).portableDataHash]); // eslint-disable-line react-hooks/exhaustive-deps
288
289     React.useEffect(() => {
290         if (rightData) {
291             const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
292             setCollectionFiles(filtered, false)(dispatch);
293         }
294     }, [rightData, dispatch, rightSearch]);
295
296     const handleRightClick = React.useCallback(
297         (event) => {
298             event.preventDefault();
299             let elem = event.target;
300
301             while (elem && elem.dataset && !elem.dataset.item) {
302                 elem = elem.parentNode;
303             }
304
305             if (!elem || !elem.dataset) {
306                 return;
307             }
308
309             const { id } = elem.dataset;
310
311             const item: any = {
312                 id,
313                 data: rightData.find((elem) => elem.id === id),
314             };
315
316             if (id) {
317                 onItemMenuOpen(event, item, isWritable);
318
319                 if (!collectionAutofetchEnabled) {
320                     setCollectionAutofetchEnabled(true);
321                 }
322             }
323         },
324         [onItemMenuOpen, isWritable, rightData] // eslint-disable-line react-hooks/exhaustive-deps
325     );
326
327     React.useEffect(() => {
328         let node = null;
329
330         if (parentRef && parentRef.current) {
331             node = parentRef.current;
332             (node as any).addEventListener('contextmenu', handleRightClick);
333         }
334
335         return () => {
336             if (node) {
337                 (node as any).removeEventListener('contextmenu', handleRightClick);
338             }
339         };
340     }, [parentRef, handleRightClick]);
341
342     const handleClick = React.useCallback(
343         (event: any) => {
344             let isCheckbox = false;
345             let elem = event.target;
346
347             if (elem.type === 'checkbox') {
348                 isCheckbox = true;
349             }
350
351             while (elem && elem.dataset && !elem.dataset.item) {
352                 elem = elem.parentNode;
353             }
354
355             if (elem && elem.dataset && !isCheckbox) {
356                 const { parentPath, subfolderPath, breadcrumbPath, type } = elem.dataset;
357
358                 if (breadcrumbPath) {
359                     const index = path.indexOf(breadcrumbPath);
360                     setPath([...path.slice(0, index + 1)]);
361                 }
362
363                 if (parentPath && type === 'directory') {
364                     if (path.length > 1) {
365                         path.pop()
366                     }
367
368                     setPath([...path, parentPath]);
369                 }
370
371                 if (subfolderPath && type === 'directory') {
372                     setPath([...path, subfolderPath]);
373                 }
374
375                 if (elem.dataset.id && type === 'file') {
376                     const item = rightData.find(({id}) => id === elem.dataset.id) || leftData.find(({ id }) => id === elem.dataset.id);
377                     const enhancedItem = servicesProvider.getServices().collectionService.extendFileURL(item);
378                     const fileUrl = sanitizeToken(getInlineFileUrl(enhancedItem.url, config.keepWebServiceUrl, config.keepWebInlineServiceUrl), true);
379                     window.open(fileUrl, '_blank');
380                 }
381             }
382
383             if (isCheckbox) {
384                 const { id } = elem.dataset;
385                 const item = collectionPanelFiles[id];
386                 props.onSelectionToggle(event, item);
387             }
388         },
389         [path, setPath, collectionPanelFiles] // eslint-disable-line react-hooks/exhaustive-deps
390     );
391
392     const getItemIcon = React.useCallback(
393         (type: string, activeClass: string | null) => {
394             let Icon = DefaultIcon;
395
396             switch (type) {
397                 case 'directory':
398                     Icon = DirectoryIcon;
399                     break;
400                 case 'file':
401                     Icon = FileIcon;
402                     break;
403             }
404
405             return (
406                 <ListItemIcon className={classNames(classes.listItemIcon, activeClass)}>
407                     <Icon />
408                 </ListItemIcon>
409             )
410         },
411         [classes]
412     );
413
414     const getActiveClass = React.useCallback(
415         (name) => {
416             return path[path.length - 1] === name ? classes.rowActive : null;
417         },
418         [path, classes]
419     );
420
421     const onOptionsMenuOpen = React.useCallback(
422         (ev, isWritable) => {
423             props.onOptionsMenuOpen(ev, isWritable);
424         },
425         [props.onOptionsMenuOpen] // eslint-disable-line react-hooks/exhaustive-deps
426     );
427
428     return (
429         <div data-cy="collection-files-panel" onClick={handleClick} ref={parentRef}>
430             <div className={classes.pathPanel}>
431                 <div className={classes.pathPanelPathWrapper}>
432                     {
433                         path
434                             .map((p: string, index: number) => <span
435                                 key={`${index}-${p}`}
436                                 data-item="true"
437                                 className={classes.pathPanelItem}
438                                 data-breadcrumb-path={p}
439                             >
440                                 <span className={classes.rowActive}>{index === 0 ? 'Home' : p}</span> <b>/</b>&nbsp;
441                             </span>)
442                     }
443                 </div>
444                 <Tooltip className={classes.pathPanelMenu} title="More options" disableFocusListener>
445                     <IconButton
446                         data-cy='collection-files-panel-options-btn'
447                         onClick={(ev) => {
448                             if (!collectionAutofetchEnabled) {
449                                 setCollectionAutofetchEnabled(true);
450                             }
451                             onOptionsMenuOpen(ev, isWritable);
452                         }}>
453                         <CustomizeTableIcon />
454                     </IconButton>
455                 </Tooltip>
456             </div>
457             <div className={classes.wrapper}>
458                 <div className={classNames(classes.leftPanel, path.length > 1 ? classes.leftPanelVisible : classes.leftPanelHidden)}>
459                     <Tooltip title="Go back" className={path.length > 1 ? classes.backButton : classes.backButtonHidden}>
460                         <IconButton onClick={() => setPath([...path.slice(0, path.length -1)])}>
461                             <BackIcon />
462                         </IconButton>
463                     </Tooltip>
464                     <div className={path.length > 1 ? classes.searchWrapper : classes.searchWrapperHidden}>
465                         <SearchInput selfClearProp={leftKey} label="Search" value={leftSearch} onSearch={setLeftSearch} />
466                     </div>
467                     <div className={classes.dataWrapper}>
468                         {
469                             leftData ?
470                                 <AutoSizer defaultWidth={0}>
471                                     {({ height, width }) => {
472                                         const filtered = leftData.filter(({ name }) => name.indexOf(leftSearch) > -1);
473
474                                         return !!filtered.length ? <FixedSizeList
475                                             height={height}
476                                             itemCount={filtered.length}
477                                             itemSize={35}
478                                             width={width}
479                                         >
480                                             {
481                                                 ({ index, style }) => {
482                                                     const { id, type, name } = filtered[index];
483
484                                                     return <div
485                                                         data-id={id}
486                                                         style={style}
487                                                         data-item="true"
488                                                         data-type={type}
489                                                         data-parent-path={name}
490                                                         className={classNames(classes.row, getActiveClass(name))}
491                                                         key={id}>
492                                                             {getItemIcon(type, getActiveClass(name))}
493                                                             <div className={classes.rowName}>
494                                                                 {name}
495                                                             </div>
496                                                             {
497                                                                 getActiveClass(name) ? <SidePanelRightArrowIcon
498                                                                     style={{ display: 'inline', marginTop: '5px', marginLeft: '5px' }} /> : null
499                                                             }
500                                                     </div>;
501                                                 }
502                                             }
503                                         </FixedSizeList> : <div className={classes.rowEmpty}>No directories available</div>
504                                     }}
505                                 </AutoSizer> : <div className={classes.row}><CircularProgress className={classes.loader} size={30} /></div>
506                         }
507
508                     </div>
509                 </div>
510                 <div className={classes.rightPanel}>
511                     <div className={classes.searchWrapper}>
512                         <SearchInput selfClearProp={rightKey} label="Search" value={rightSearch} onSearch={setRightSearch} />
513                     </div>
514                     {
515                         isWritable &&
516                         <Button
517                             className={classes.uploadButton}
518                             data-cy='upload-button'
519                             onClick={() => {
520                                 if (!collectionAutofetchEnabled) {
521                                     setCollectionAutofetchEnabled(true);
522                                 }
523                                 onUploadDataClick();
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 ? <FixedSizeList
540                                             height={height}
541                                             itemCount={filtered.length}
542                                             itemSize={35}
543                                             width={width}
544                                         >
545                                             {
546                                                 ({ index, style }) => {
547                                                     const { id, type, name, size } = filtered[index];
548
549                                                     return <div
550                                                         style={style}
551                                                         data-id={id}
552                                                         data-item="true"
553                                                         data-type={type}
554                                                         data-subfolder-path={name}
555                                                         className={classes.row} key={id}>
556                                                         <Checkbox
557                                                             color="primary"
558                                                             className={classes.rowSelection}
559                                                             checked={collectionPanelFiles[id] ? collectionPanelFiles[id].value.selected : false}
560                                                         />&nbsp;
561                                                     {getItemIcon(type, null)} <div className={classes.rowName}>
562                                                             {name}
563                                                         </div>
564                                                         <span className={classes.rowName} style={{ marginLeft: 'auto', marginRight: '1rem' }}>
565                                                             {formatFileSize(size)}
566                                                         </span>
567                                                     </div>
568                                                 }
569                                             }
570                                         </FixedSizeList> : <div className={classes.rowEmpty}>No data available</div>
571                                     }}
572                                 </AutoSizer> : <div className={classes.row}><CircularProgress className={classes.loader} size={30} /></div>
573                         }
574                     </div>
575                 </div>
576             </div>
577         </div>
578     );
579 }));