a6bce0f23e724be018dc0f87a3ef11f6d3b0ab8b
[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 { CustomizeTableIcon } from 'components/icon/icon';
9 import { ListItemIcon, StyleRulesCallback, Theme, WithStyles, withStyles, Tooltip, IconButton, Checkbox } from '@material-ui/core';
10 import { FileTreeData } from '../file-tree/file-tree-data';
11 import { TreeItem, TreeItemStatus } from '../tree/tree';
12 import { RootState } from 'store/store';
13 import { WebDAV, WebDAVRequestConfig } from 'common/webdav';
14 import { AuthState } from 'store/auth/auth-reducer';
15 import { extractFilesData } from 'services/collection-service/collection-service-files-response';
16 import { DefaultIcon, DirectoryIcon, FileIcon } from 'components/icon/icon';
17 import { setCollectionFiles } from 'store/collection-panel/collection-panel-files/collection-panel-files-actions';
18
19 export interface CollectionPanelFilesProps {
20     items: any;
21     isWritable: boolean;
22     isLoading: boolean;
23     tooManyFiles: boolean;
24     onUploadDataClick: () => void;
25     onSearchChange: (searchValue: string) => void;
26     onItemMenuOpen: (event: React.MouseEvent<HTMLElement>, item: TreeItem<FileTreeData>, isWritable: boolean) => void;
27     onOptionsMenuOpen: (event: React.MouseEvent<HTMLElement>, isWritable: boolean) => void;
28     onSelectionToggle: (event: React.MouseEvent<HTMLElement>, item: TreeItem<FileTreeData>) => void;
29     onCollapseToggle: (id: string, status: TreeItemStatus) => void;
30     onFileClick: (id: string) => void;
31     loadFilesFunc: () => void;
32     currentItemUuid: any;
33     dispatch: Function;
34     collectionPanelFiles: any;
35     collectionPanel: any;
36 }
37
38 type CssRules = "wrapper" | "row" | "leftPanel" | "rightPanel" | "pathPanel" | "pathPanelItem" | "rowName" | "listItemIcon" | "rowActive" | "pathPanelMenu" | "rowSelection";
39
40 const styles: StyleRulesCallback<CssRules> = (theme: Theme) => ({
41     wrapper: {
42         display: 'flex',
43     },
44     row: {
45         display: 'flex',
46         margin: '0.5rem',
47         cursor: 'pointer',
48         "&:hover": {
49             backgroundColor: 'rgba(0, 0, 0, 0.08)',
50         }
51     },
52     rowName: {
53         paddingTop: '6px',
54         paddingBottom: '6px',
55     },
56     rowSelection: {
57         padding: '0px',
58     },
59     rowActive: {
60         color: `${theme.palette.primary.main} !important`,
61     },
62     listItemIcon: {
63         marginTop: '2px',
64     },
65     pathPanelMenu: {
66         float: 'right',
67         marginTop: '-15px',
68     },
69     pathPanel: {
70         padding: '1rem',
71         marginBottom: '1rem',
72         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%)',
73     },
74     leftPanel: {
75         flex: '30%',
76         padding: '1rem',
77         marginRight: '1rem',
78         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%)',
79     },
80     rightPanel: {
81         flex: '70%',
82         padding: '1rem',
83         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%)',
84     },
85     pathPanelItem: {
86         cursor: 'pointer',
87     }
88
89 });
90
91 export const CollectionPanelFiles = withStyles(styles)(connect((state: RootState) => ({ 
92     auth: state.auth,
93     collectionPanel: state.collectionPanel,
94     collectionPanelFiles: state.collectionPanelFiles,
95  }))((props: CollectionPanelFilesProps & WithStyles<CssRules> & { auth: AuthState }) => {
96     const { classes, onItemMenuOpen, isWritable, dispatch, collectionPanelFiles, collectionPanel } = props;
97     const { apiToken, config } = props.auth;
98
99     const webdavClient = new WebDAV();
100     webdavClient.defaults.baseURL = config.keepWebServiceUrl;
101     webdavClient.defaults.headers = {
102         Authorization: `Bearer ${apiToken}`
103     };
104
105     const webDAVRequestConfig: WebDAVRequestConfig = {
106         headers: {
107             Depth: '1',
108         },
109     };
110
111     const parentRef = React.useRef(null);
112     const [path, setPath]: any = React.useState([]);
113     const [pathData, setPathData]: any = React.useState({});
114     const [isLoading, setIsLoading] = React.useState(false);
115
116     const leftKey = (path.length > 1 ? path.slice(0, path.length - 1) : path).join('/');
117     const rightKey = path.join('/');
118
119     React.useEffect(() => {
120         if (props.currentItemUuid) {
121             setPathData({});
122             setPath([props.currentItemUuid]);
123         }
124     }, [props.currentItemUuid]);
125
126     React.useEffect(() => {
127         if (rightKey && !pathData[rightKey] && !isLoading) {
128             webdavClient.propfind(`c=${rightKey}`, webDAVRequestConfig)
129                 .then((request) => {
130                     if (request.responseXML != null) {
131                         const result: any = extractFilesData(request.responseXML);
132                         const sortedResult = result.sort((n1: any, n2: any) => n1.name > n2.name ? 1 : -1);
133                         const newPathData = { ...pathData, [rightKey]: sortedResult };
134                         setPathData(newPathData);
135                         setIsLoading(false);
136                     }
137                 });
138         } else {
139             setTimeout(() => setIsLoading(false), 100);
140         }
141     }, [path, pathData, webdavClient, webDAVRequestConfig, rightKey, isLoading, collectionPanelFiles]);
142
143     const leftData = pathData[leftKey];
144     const rightData = pathData[rightKey];
145
146     React.useEffect(() => {
147         webdavClient.propfind(`c=${rightKey}`, webDAVRequestConfig)
148             .then((request) => {
149                 if (request.responseXML != null) {
150                     const result: any = extractFilesData(request.responseXML);
151                     const sortedResult = result.sort((n1: any, n2: any) => n1.name > n2.name ? 1 : -1);
152                     const newPathData = { ...pathData, [rightKey]: sortedResult };
153                     setPathData(newPathData);
154                     setIsLoading(false);
155                 }
156             });
157     }, [collectionPanel.item]);
158
159     React.useEffect(() => {
160         if (rightData) {
161             setCollectionFiles(rightData, false)(dispatch);
162         }
163     }, [rightData, dispatch]);
164
165     const handleRightClick = React.useCallback(
166         (event) => {
167             event.preventDefault();
168
169             let elem = event.target;
170
171             while (elem && elem.dataset && !elem.dataset.item) {
172                 elem = elem.parentNode;
173             }
174
175             if (!elem) {
176                 return;
177             }
178
179             const { id } = elem.dataset;
180             const item: any = { id, data: rightData.find((elem) => elem.id === id) };
181
182             if (id) {
183                 onItemMenuOpen(event, item, isWritable);
184             }
185         },
186         [onItemMenuOpen, isWritable, rightData]
187     );
188
189     React.useEffect(() => {
190         let node = null;
191
192         if (parentRef && parentRef.current) {
193             node = parentRef.current;
194             (node as any).addEventListener('contextmenu', handleRightClick);
195         }
196
197         return () => {
198             if (node) {
199                 (node as any).removeEventListener('contextmenu', handleRightClick);
200             }
201         };
202     }, [parentRef, handleRightClick]);
203
204     const handleClick = React.useCallback(
205         (event: any) => {
206             let isCheckbox = false;
207             let elem = event.target;
208
209             if (elem.type === 'checkbox') {
210                 isCheckbox = true;
211             }
212
213             while (elem && elem.dataset && !elem.dataset.item) {
214                 elem = elem.parentNode;
215             }
216
217             if (elem && elem.dataset && !isCheckbox) {
218                 const { parentPath, subfolderPath, breadcrumbPath, type } = elem.dataset;
219
220                 setIsLoading(true);
221
222                 if (breadcrumbPath) {
223                     const index = path.indexOf(breadcrumbPath);
224                     setPath([...path.slice(0, index + 1)]);
225                 }
226
227                 if (parentPath) {
228                     if (path.length > 1) {
229                         path.pop()
230                     }
231
232                     setPath([...path, parentPath]);
233                 }
234
235                 if (subfolderPath && type === 'directory') {
236                     setPath([...path, subfolderPath]);
237                 }
238             }
239
240             if (isCheckbox) {
241                 const { id } = elem.dataset;
242                 const item = collectionPanelFiles[id];
243                 props.onSelectionToggle(event, item);
244             }
245         },
246         [path, setPath, collectionPanelFiles]
247     );
248
249     const getItemIcon = React.useCallback(
250         (type: string, activeClass: string | null) => {
251             let Icon = DefaultIcon;
252
253             switch (type) {
254                 case 'directory':
255                     Icon = DirectoryIcon;
256                     break;
257                 case 'file':
258                     Icon = FileIcon;
259                     break;
260             }
261
262             return (
263                 <ListItemIcon className={classNames(classes.listItemIcon, activeClass)}>
264                     <Icon />
265                 </ListItemIcon>
266             )
267         },
268         [classes]
269     );
270
271     const getActiveClass = React.useCallback(
272         (name) => {
273             const index = path.indexOf(name);
274
275             return index === (path.length - 1) ? classes.rowActive : null
276         },
277         [path, classes]
278     );
279
280     const onOptionsMenuOpen = React.useCallback(
281         (ev, isWritable) => {
282             props.onOptionsMenuOpen(ev, isWritable);
283         },
284         [props.onOptionsMenuOpen]
285     );
286
287     return (
288         <div onClick={handleClick} ref={parentRef}>
289             <div className={classes.pathPanel}>
290                 {
291                     path.map((p: string, index: number) => <span
292                         key={`${index}-${p}`}
293                         data-item="true"
294                         className={classes.pathPanelItem}
295                         data-breadcrumb-path={p}
296                     >
297                         {index === 0 ? 'Home' : p} /&nbsp;
298                     </span>)
299                 }
300                 <Tooltip  className={classes.pathPanelMenu} title="More options" disableFocusListener>
301                     <IconButton
302                         data-cy='collection-files-panel-options-btn'
303                         onClick={(ev) => onOptionsMenuOpen(ev, isWritable)}>
304                         <CustomizeTableIcon />
305                     </IconButton>
306                 </Tooltip>
307             </div>
308             <div className={classes.wrapper}>
309                 <div className={classes.leftPanel}>
310                     {
311                         leftData && !!leftData.length ?
312                             leftData.filter(({ type }) => type === 'directory').map(({ name, id, type }: any) => <div
313                                 data-item="true"
314                                 data-parent-path={name}
315                                 className={classNames(classes.row, getActiveClass(name))}
316                                 key={id}>{getItemIcon(type, getActiveClass(name))} <div className={classes.rowName}>{name}</div>
317                             </div>) : <div className={classes.row}>Loading...</div>
318                     }
319                 </div>
320                 <div className={classes.rightPanel}>
321                     {
322                         rightData && !isLoading ?
323                             rightData.map(({ name, id, type }: any) => <div
324                                 data-id={id}
325                                 data-item="true"
326                                 data-type={type}
327                                 data-subfolder-path={name}
328                                 className={classes.row} key={id}>
329                                     <Checkbox
330                                         color="primary"
331                                         className={classes.rowSelection}
332                                         checked={collectionPanelFiles[id] ? collectionPanelFiles[id].value.selected : false}
333                                     />&nbsp;
334                                     {getItemIcon(type, null)} <div className={classes.rowName}>
335                                     {name}
336                                 </div>
337                             </div>) : <div className={classes.row}>Loading...</div>
338                     }
339                 </div>
340             </div>
341         </div>
342     );
343 }));