17585: Added data-cy attribute
[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 } from 'components/icon/icon';
11 import { SearchInput } from 'components/search-input/search-input';
12 import { ListItemIcon, StyleRulesCallback, Theme, WithStyles, withStyles, Tooltip, IconButton, Checkbox, CircularProgress } 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 = "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         width: '100%',
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     leftPanel: {
116         flex: 0,
117         padding: '1rem',
118         marginRight: '1rem',
119         whiteSpace: 'nowrap',
120         position: 'relative',
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     leftPanelVisible: {
125         opacity: 1,
126         flex: '30%',
127         animation: `animateVisible 1000ms ${theme.transitions.easing.easeOut}`
128     },
129     leftPanelHidden: {
130         opacity: 0,
131         flex: 'initial',
132         padding: '0',
133         marginRight: '0',
134     },
135     "@keyframes animateVisible": {
136         "0%": {
137             opacity: 0,
138             flex: 'initial',
139         },
140         "100%": {
141             opacity: 1,
142             flex: '30%',
143         }
144     },
145     rightPanel: {
146         flex: '70%',
147         padding: '1rem',
148         position: 'relative',
149         backgroundColor: '#fff',
150         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%)',
151     },
152     pathPanelItem: {
153         cursor: 'pointer',
154     }
155 });
156
157 const pathPromise = {};
158
159 export const CollectionPanelFiles = withStyles(styles)(connect((state: RootState) => ({
160     auth: state.auth,
161     collectionPanel: state.collectionPanel,
162     collectionPanelFiles: state.collectionPanelFiles,
163 }))((props: CollectionPanelFilesProps & WithStyles<CssRules> & { auth: AuthState }) => {
164     const { classes, onItemMenuOpen, isWritable, dispatch, collectionPanelFiles, collectionPanel } = props;
165     const { apiToken, config } = props.auth;
166
167     const webdavClient = new WebDAV();
168     webdavClient.defaults.baseURL = config.keepWebServiceUrl;
169     webdavClient.defaults.headers = {
170         Authorization: `Bearer ${apiToken}`
171     };
172
173     const webDAVRequestConfig: WebDAVRequestConfig = {
174         headers: {
175             Depth: '1',
176         },
177     };
178
179     const parentRef = React.useRef(null);
180     const [path, setPath]: any = React.useState([]);
181     const [pathData, setPathData]: any = React.useState({});
182     const [isLoading, setIsLoading] = React.useState(false);
183     const [rightClickUsed, setRightClickUsed] = React.useState(false);
184     const [leftSearch, setLeftSearch] = React.useState('');
185     const [rightSearch, setRightSearch] = React.useState('');
186
187     const leftKey = (path.length > 1 ? path.slice(0, path.length - 1) : path).join('/');
188     const rightKey = path.join('/');
189
190     const leftData = (pathData[leftKey] || []).filter(({ type }) => type === 'directory');
191     const rightData = pathData[rightKey];
192
193     React.useEffect(() => {
194         if (props.currentItemUuid) {
195             setPathData({});
196             setPath([props.currentItemUuid]);
197         }
198     }, [props.currentItemUuid]);
199
200     const fetchData = (rightKey, ignoreCache = false) => {
201         const dataExists = !!pathData[rightKey];
202         const runningRequest = pathPromise[rightKey];
203
204         if ((!dataExists || ignoreCache) && !runningRequest) {
205             setIsLoading(true);
206
207             webdavClient.propfind(`c=${rightKey}`, webDAVRequestConfig)
208                 .then((request) => {
209                     if (request.responseXML != null) {
210                         const result: any = extractFilesData(request.responseXML);
211                         const sortedResult = sortBy(result, (n) => n.name).sort((n1, n2) => {
212                             if (n1.type === 'directory' && n2.type !== 'directory') {
213                                 return -1;
214                             }
215                             if (n1.type !== 'directory' && n2.type === 'directory') {
216                                 return 1;
217                             }
218                             return 0;
219                         });
220                         const newPathData = { ...pathData, [rightKey]: sortedResult };
221                         setPathData(newPathData);
222                     }
223                 })
224                 .finally(() => {
225                     setIsLoading(false);
226                     delete pathPromise[rightKey];
227                 });
228
229             pathPromise[rightKey] = true;
230         } else {
231             setTimeout(() => setIsLoading(false), 0);
232         }
233     };
234
235     React.useEffect(() => {
236         if (rightKey) {
237             fetchData(rightKey);
238             setLeftSearch('');
239             setRightSearch('');
240         }
241     }, [rightKey]); // eslint-disable-line react-hooks/exhaustive-deps
242
243     React.useEffect(() => {
244         const hash = (collectionPanel.item || {}).portableDataHash;
245
246         if (hash && rightClickUsed) {
247             fetchData(rightKey, true);
248         }
249     }, [(collectionPanel.item || {}).portableDataHash]); // eslint-disable-line react-hooks/exhaustive-deps
250
251     React.useEffect(() => {
252         if (rightData) {
253             const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
254             setCollectionFiles(filtered, false)(dispatch);
255         }
256     }, [rightData, dispatch, rightSearch]);
257
258     const handleRightClick = React.useCallback(
259         (event) => {
260             event.preventDefault();
261
262             if (!rightClickUsed) {
263                 setRightClickUsed(true);
264             }
265
266             let elem = event.target;
267
268             while (elem && elem.dataset && !elem.dataset.item) {
269                 elem = elem.parentNode;
270             }
271
272             if (!elem) {
273                 return;
274             }
275
276             const { id } = elem.dataset;
277             const item: any = { id, data: rightData.find((elem) => elem.id === id) };
278
279             if (id) {
280                 onItemMenuOpen(event, item, isWritable);
281             }
282         },
283         [onItemMenuOpen, isWritable, rightData] // eslint-disable-line react-hooks/exhaustive-deps
284     );
285
286     React.useEffect(() => {
287         let node = null;
288
289         if (parentRef && parentRef.current) {
290             node = parentRef.current;
291             (node as any).addEventListener('contextmenu', handleRightClick);
292         }
293
294         return () => {
295             if (node) {
296                 (node as any).removeEventListener('contextmenu', handleRightClick);
297             }
298         };
299     }, [parentRef, handleRightClick]);
300
301     const handleClick = React.useCallback(
302         (event: any) => {
303             let isCheckbox = false;
304             let elem = event.target;
305
306             if (elem.type === 'checkbox') {
307                 isCheckbox = true;
308             }
309
310             while (elem && elem.dataset && !elem.dataset.item) {
311                 elem = elem.parentNode;
312             }
313
314             if (elem && elem.dataset && !isCheckbox) {
315                 const { parentPath, subfolderPath, breadcrumbPath, type } = elem.dataset;
316
317                 if (breadcrumbPath) {
318                     const index = path.indexOf(breadcrumbPath);
319                     setPath([...path.slice(0, index + 1)]);
320                 }
321
322                 if (parentPath) {
323                     if (path.length > 1) {
324                         path.pop()
325                     }
326
327                     setPath([...path, parentPath]);
328                 }
329
330                 if (subfolderPath && type === 'directory') {
331                     setPath([...path, subfolderPath]);
332                 }
333             }
334
335             if (isCheckbox) {
336                 const { id } = elem.dataset;
337                 const item = collectionPanelFiles[id];
338                 props.onSelectionToggle(event, item);
339             }
340         },
341         [path, setPath, collectionPanelFiles] // eslint-disable-line react-hooks/exhaustive-deps
342     );
343
344     const getItemIcon = React.useCallback(
345         (type: string, activeClass: string | null) => {
346             let Icon = DefaultIcon;
347
348             switch (type) {
349                 case 'directory':
350                     Icon = DirectoryIcon;
351                     break;
352                 case 'file':
353                     Icon = FileIcon;
354                     break;
355             }
356
357             return (
358                 <ListItemIcon className={classNames(classes.listItemIcon, activeClass)}>
359                     <Icon />
360                 </ListItemIcon>
361             )
362         },
363         [classes]
364     );
365
366     const getActiveClass = React.useCallback(
367         (name) => {
368             return path[path.length - 1] === name ? classes.rowActive : null;
369         },
370         [path, classes]
371     );
372
373     const onOptionsMenuOpen = React.useCallback(
374         (ev, isWritable) => {
375             props.onOptionsMenuOpen(ev, isWritable);
376         },
377         [props.onOptionsMenuOpen] // eslint-disable-line react-hooks/exhaustive-deps
378     );
379
380     return (
381         <div data-cy="collection-files-panel" onClick={handleClick} ref={parentRef}>
382             <div className={classes.pathPanel}>
383                 {
384                     path
385                         .map((p: string, index: number) => <span
386                             key={`${index}-${p}`}
387                             data-item="true"
388                             className={classes.pathPanelItem}
389                             data-breadcrumb-path={p}
390                         >
391                             {index === 0 ? 'Home' : p} /&nbsp;
392                         </span>)
393                 }
394                 <Tooltip className={classes.pathPanelMenu} title="More options" disableFocusListener>
395                     <IconButton
396                         data-cy='collection-files-panel-options-btn'
397                         onClick={(ev) => onOptionsMenuOpen(ev, isWritable)}>
398                         <CustomizeTableIcon />
399                     </IconButton>
400                 </Tooltip>
401             </div>
402             <div className={classes.wrapper}>
403                 <div className={classNames(classes.leftPanel, path.length > 1 ? classes.leftPanelVisible : classes.leftPanelHidden)}>
404                     <div className={path.length > 1 ? classes.searchWrapper : classes.searchWrapperHidden}>
405                         <SearchInput label="Search" value={leftSearch} onSearch={setLeftSearch} />
406                     </div>
407                     <div className={classes.dataWrapper}>
408                         {
409                             leftData ?
410                                 <AutoSizer defaultWidth={0}>
411                                     {({ height, width }) => {
412                                         const filtered = leftData.filter(({ name }) => name.indexOf(leftSearch) > -1);
413
414                                         return !!filtered.length ? <FixedSizeList
415                                             height={height}
416                                             itemCount={filtered.length}
417                                             itemSize={35}
418                                             width={width}
419                                         >
420                                             {
421                                                 ({ index, style }) => {
422                                                     const { id, type, name } = filtered[index];
423
424                                                     return <div
425                                                         style={style}
426                                                         data-item="true"
427                                                         data-parent-path={name}
428                                                         className={classNames(classes.row, getActiveClass(name))}
429                                                         key={id}>{getItemIcon(type, getActiveClass(name))} <div className={classes.rowName}>{name}</div>
430                                                     </div>;
431                                                 }
432                                             }
433                                         </FixedSizeList> : <div className={classes.rowEmpty}>No directories available</div>
434                                     }}
435                                 </AutoSizer> : <div className={classes.row}><CircularProgress className={classes.loader} size={30} /></div>
436                         }
437
438                     </div>
439                 </div>
440                 <div className={classes.rightPanel}>
441                     <div className={classes.searchWrapper}>
442                         <SearchInput label="Search" value={rightSearch} onSearch={setRightSearch} />
443                     </div>
444                     <div className={classes.dataWrapper}>
445                         {
446                             rightData && !isLoading ?
447                                 <AutoSizer defaultHeight={500}>
448                                     {({ height, width }) => {
449                                         const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
450
451                                         return !!filtered.length ? <FixedSizeList
452                                             height={height}
453                                             itemCount={filtered.length}
454                                             itemSize={35}
455                                             width={width}
456                                         >
457                                             {
458                                                 ({ index, style }) => {
459                                                     const { id, type, name, size } = filtered[index];
460
461                                                     return <div
462                                                         style={style}
463                                                         data-id={id}
464                                                         data-item="true"
465                                                         data-type={type}
466                                                         data-subfolder-path={name}
467                                                         className={classes.row} key={id}>
468                                                         <Checkbox
469                                                             color="primary"
470                                                             className={classes.rowSelection}
471                                                             checked={collectionPanelFiles[id] ? collectionPanelFiles[id].value.selected : false}
472                                                         />&nbsp;
473                                                     {getItemIcon(type, null)} <div className={classes.rowName}>
474                                                             {name}
475                                                         </div>
476                                                         <span className={classes.rowName} style={{marginLeft: 'auto', marginRight: '1rem'}}>
477                                                             {formatFileSize(size)}
478                                                         </span>
479                                                     </div>
480                                                 }
481                                             }
482                                         </FixedSizeList> : <div className={classes.rowEmpty}>No data available</div>
483                                     }}
484                                 </AutoSizer> : <div className={classes.row}><CircularProgress className={classes.loader} size={30} /></div>
485                         }
486                     </div>
487                 </div>
488             </div>
489         </div>
490     );
491 }));