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