17585: Fixed color, font size and added file size
[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         }
239     }, [rightKey]);
240
241     React.useEffect(() => {
242         const hash = (collectionPanel.item || {}).portableDataHash;
243
244         if (hash && rightClickUsed) {
245             fetchData(rightKey, true);
246         }
247     }, [(collectionPanel.item || {}).portableDataHash]);
248
249     React.useEffect(() => {
250         if (rightData) {
251             setCollectionFiles(rightData, false)(dispatch);
252         }
253     }, [rightData, dispatch]);
254
255     const handleRightClick = React.useCallback(
256         (event) => {
257             event.preventDefault();
258
259             if (!rightClickUsed) {
260                 setRightClickUsed(true);
261             }
262
263             let elem = event.target;
264
265             while (elem && elem.dataset && !elem.dataset.item) {
266                 elem = elem.parentNode;
267             }
268
269             if (!elem) {
270                 return;
271             }
272
273             const { id } = elem.dataset;
274             const item: any = { id, data: rightData.find((elem) => elem.id === id) };
275
276             if (id) {
277                 onItemMenuOpen(event, item, isWritable);
278             }
279         },
280         [onItemMenuOpen, isWritable, rightData]
281     );
282
283     React.useEffect(() => {
284         let node = null;
285
286         if (parentRef && parentRef.current) {
287             node = parentRef.current;
288             (node as any).addEventListener('contextmenu', handleRightClick);
289         }
290
291         return () => {
292             if (node) {
293                 (node as any).removeEventListener('contextmenu', handleRightClick);
294             }
295         };
296     }, [parentRef, handleRightClick]);
297
298     const handleClick = React.useCallback(
299         (event: any) => {
300             let isCheckbox = false;
301             let elem = event.target;
302
303             if (elem.type === 'checkbox') {
304                 isCheckbox = true;
305             }
306
307             while (elem && elem.dataset && !elem.dataset.item) {
308                 elem = elem.parentNode;
309             }
310
311             if (elem && elem.dataset && !isCheckbox) {
312                 const { parentPath, subfolderPath, breadcrumbPath, type } = elem.dataset;
313
314                 if (breadcrumbPath) {
315                     const index = path.indexOf(breadcrumbPath);
316                     setPath([...path.slice(0, index + 1)]);
317                 }
318
319                 if (parentPath) {
320                     if (path.length > 1) {
321                         path.pop()
322                     }
323
324                     setPath([...path, parentPath]);
325                 }
326
327                 if (subfolderPath && type === 'directory') {
328                     setPath([...path, subfolderPath]);
329                 }
330             }
331
332             if (isCheckbox) {
333                 const { id } = elem.dataset;
334                 const item = collectionPanelFiles[id];
335                 props.onSelectionToggle(event, item);
336             }
337         },
338         [path, setPath, collectionPanelFiles]
339     );
340
341     const getItemIcon = React.useCallback(
342         (type: string, activeClass: string | null) => {
343             let Icon = DefaultIcon;
344
345             switch (type) {
346                 case 'directory':
347                     Icon = DirectoryIcon;
348                     break;
349                 case 'file':
350                     Icon = FileIcon;
351                     break;
352             }
353
354             return (
355                 <ListItemIcon className={classNames(classes.listItemIcon, activeClass)}>
356                     <Icon />
357                 </ListItemIcon>
358             )
359         },
360         [classes]
361     );
362
363     const getActiveClass = React.useCallback(
364         (name) => {
365             return path[path.length - 1] === name ? classes.rowActive : null;
366         },
367         [path, classes]
368     );
369
370     const onOptionsMenuOpen = React.useCallback(
371         (ev, isWritable) => {
372             props.onOptionsMenuOpen(ev, isWritable);
373         },
374         [props.onOptionsMenuOpen]
375     );
376
377     return (
378         <div onClick={handleClick} ref={parentRef}>
379             <div className={classes.pathPanel}>
380                 {
381                     path
382                         .map((p: string, index: number) => <span
383                             key={`${index}-${p}`}
384                             data-item="true"
385                             className={classes.pathPanelItem}
386                             data-breadcrumb-path={p}
387                         >
388                             {index === 0 ? 'Home' : p} /&nbsp;
389                         </span>)
390                 }
391                 <Tooltip className={classes.pathPanelMenu} title="More options" disableFocusListener>
392                     <IconButton
393                         data-cy='collection-files-panel-options-btn'
394                         onClick={(ev) => onOptionsMenuOpen(ev, isWritable)}>
395                         <CustomizeTableIcon />
396                     </IconButton>
397                 </Tooltip>
398             </div>
399             <div className={classes.wrapper}>
400                 <div className={classNames(classes.leftPanel, path.length > 1 ? classes.leftPanelVisible : classes.leftPanelHidden)}>
401                     <div className={path.length > 1 ? classes.searchWrapper : classes.searchWrapperHidden}>
402                         <SearchInput label="Search" value={leftSearch} onSearch={setLeftSearch} />
403                     </div>
404                     <div className={classes.dataWrapper}>
405                         {
406                             leftData ?
407                                 <AutoSizer defaultWidth={0}>
408                                     {({ height, width }) => {
409                                         const filtered = leftData.filter(({ name }) => name.indexOf(leftSearch) > -1);
410
411                                         return !!filtered.length ? <FixedSizeList
412                                             height={height}
413                                             itemCount={filtered.length}
414                                             itemSize={35}
415                                             width={width}
416                                         >
417                                             {
418                                                 ({ index, style }) => {
419                                                     const { id, type, name } = filtered[index];
420
421                                                     return <div
422                                                         style={style}
423                                                         data-item="true"
424                                                         data-parent-path={name}
425                                                         className={classNames(classes.row, getActiveClass(name))}
426                                                         key={id}>{getItemIcon(type, getActiveClass(name))} <div className={classes.rowName}>{name}</div>
427                                                     </div>;
428                                                 }
429                                             }
430                                         </FixedSizeList> : <div className={classes.rowEmpty}>No directories available</div>
431                                     }}
432                                 </AutoSizer> : <div className={classes.row}><CircularProgress className={classes.loader} size={30} /></div>
433                         }
434
435                     </div>
436                 </div>
437                 <div className={classes.rightPanel}>
438                     <div className={classes.searchWrapper}>
439                         <SearchInput label="Search" value={rightSearch} onSearch={setRightSearch} />
440                     </div>
441                     <div className={classes.dataWrapper}>
442                         {
443                             rightData && !isLoading ?
444                                 <AutoSizer defaultHeight={500}>
445                                     {({ height, width }) => {
446                                         const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
447
448                                         return !!filtered.length ? <FixedSizeList
449                                             height={height}
450                                             itemCount={filtered.length}
451                                             itemSize={35}
452                                             width={width}
453                                         >
454                                             {
455                                                 ({ index, style }) => {
456                                                     const { id, type, name, size } = filtered[index];
457
458                                                     return <div
459                                                         style={style}
460                                                         data-id={id}
461                                                         data-item="true"
462                                                         data-type={type}
463                                                         data-subfolder-path={name}
464                                                         className={classes.row} key={id}>
465                                                         <Checkbox
466                                                             color="primary"
467                                                             className={classes.rowSelection}
468                                                             checked={collectionPanelFiles[id] ? collectionPanelFiles[id].value.selected : false}
469                                                         />&nbsp;
470                                                     {getItemIcon(type, null)} <div className={classes.rowName}>
471                                                             {name}
472                                                         </div>
473                                                         <span className={classes.rowName} style={{marginLeft: 'auto', marginRight: '1rem'}}>
474                                                             {formatFileSize(size)}
475                                                         </span>
476                                                     </div>
477                                                 }
478                                             }
479                                         </FixedSizeList> : <div className={classes.rowEmpty}>No data available</div>
480                                     }}
481                                 </AutoSizer> : <div className={classes.row}><CircularProgress className={classes.loader} size={30} /></div>
482                         }
483                     </div>
484                 </div>
485             </div>
486         </div>
487     );
488 }));