1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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';
24 export interface CollectionPanelFilesProps {
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;
39 collectionPanelFiles: any;
43 type CssRules = "pathPanelPathWrapper" | "uploadButton" | "uploadIcon" | "loader" | "wrapper" | "dataWrapper" | "row" | "rowEmpty" | "leftPanel" | "rightPanel" | "pathPanel" | "pathPanelItem" | "rowName" | "listItemIcon" | "rowActive" | "pathPanelMenu" | "rowSelection" | "leftPanelHidden" | "leftPanelVisible" | "searchWrapper" | "searchWrapperHidden";
45 const styles: StyleRulesCallback<CssRules> = (theme: Theme) => ({
50 color: 'rgba(0, 0, 0, 0.87)',
52 fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
55 letterSpacing: '0.01071em'
63 marginBottom: '0.5rem',
66 backgroundColor: 'rgba(0, 0, 0, 0.08)',
83 display: 'inline-flex',
84 flexDirection: 'column',
85 justifyContent: 'center'
88 display: 'inline-block',
91 searchWrapperHidden: {
98 color: `${theme.palette.primary.main} !important`,
101 display: 'inline-flex',
102 flexDirection: 'column',
103 justifyContent: 'center'
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%)',
115 pathPanelPathWrapper: {
116 display: 'inline-block',
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%)',
130 animation: `animateVisible 1000ms ${theme.transitions.easing.easeOut}`
138 "@keyframes animateVisible": {
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%)',
159 transform: 'rotate(180deg)'
166 const pathPromise = {};
168 export const CollectionPanelFiles = withStyles(styles)(connect((state: RootState) => ({
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;
176 const webdavClient = new WebDAV();
177 webdavClient.defaults.baseURL = config.keepWebServiceUrl;
178 webdavClient.defaults.headers = {
179 Authorization: `Bearer ${apiToken}`
182 const webDAVRequestConfig: WebDAVRequestConfig = {
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 [rightClickUsed, setRightClickUsed] = React.useState(false);
193 const [leftSearch, setLeftSearch] = React.useState('');
194 const [rightSearch, setRightSearch] = React.useState('');
196 const leftKey = (path.length > 1 ? path.slice(0, path.length - 1) : path).join('/');
197 const rightKey = path.join('/');
199 const leftData = (pathData[leftKey] || []).filter(({ type }) => type === 'directory');
200 const rightData = pathData[rightKey];
202 React.useEffect(() => {
203 if (props.currentItemUuid) {
205 setPath([props.currentItemUuid]);
207 }, [props.currentItemUuid]);
209 const fetchData = (keys, ignoreCache = false) => {
210 const keyArray = Array.isArray(keys) ? keys : [keys];
214 const dataExists = !!pathData[key];
215 const runningRequest = pathPromise[key];
217 if ((!dataExists || ignoreCache) && (!runningRequest || ignoreCache)) {
222 pathPromise[key] = true;
224 return webdavClient.propfind(`c=${key}`, webDAVRequestConfig);
227 return Promise.resolve(null);
229 .filter((promise) => !!promise)
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') {
240 if (n1.type !== 'directory' && n2.type === 'directory') {
246 return { [key]: sortedResult };
249 }).reduce((prev, next) => {
250 return { ...next, ...prev };
253 setPathData({ ...pathData, ...newState });
257 keyArray.forEach(key => delete pathPromise[key]);
261 React.useEffect(() => {
267 }, [rightKey]); // eslint-disable-line react-hooks/exhaustive-deps
269 React.useEffect(() => {
270 const hash = (collectionPanel.item || {}).portableDataHash;
272 if (hash && rightClickUsed) {
273 fetchData([leftKey, rightKey], true);
275 }, [(collectionPanel.item || {}).portableDataHash]); // eslint-disable-line react-hooks/exhaustive-deps
277 React.useEffect(() => {
279 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
280 setCollectionFiles(filtered, false)(dispatch);
282 }, [rightData, dispatch, rightSearch]);
284 const handleRightClick = React.useCallback(
286 event.preventDefault();
287 let elem = event.target;
289 while (elem && elem.dataset && !elem.dataset.item) {
290 elem = elem.parentNode;
297 const { id } = elem.dataset;
298 const item: any = { id, data: rightData.find((elem) => elem.id === id) };
301 onItemMenuOpen(event, item, isWritable);
303 if (!rightClickUsed) {
304 setRightClickUsed(true);
308 [onItemMenuOpen, isWritable, rightData] // eslint-disable-line react-hooks/exhaustive-deps
311 React.useEffect(() => {
314 if (parentRef && parentRef.current) {
315 node = parentRef.current;
316 (node as any).addEventListener('contextmenu', handleRightClick);
321 (node as any).removeEventListener('contextmenu', handleRightClick);
324 }, [parentRef, handleRightClick]);
326 const handleClick = React.useCallback(
328 let isCheckbox = false;
329 let elem = event.target;
331 if (elem.type === 'checkbox') {
335 while (elem && elem.dataset && !elem.dataset.item) {
336 elem = elem.parentNode;
339 if (elem && elem.dataset && !isCheckbox) {
340 const { parentPath, subfolderPath, breadcrumbPath, type } = elem.dataset;
342 if (breadcrumbPath) {
343 const index = path.indexOf(breadcrumbPath);
344 setPath([...path.slice(0, index + 1)]);
348 if (path.length > 1) {
352 setPath([...path, parentPath]);
355 if (subfolderPath && type === 'directory') {
356 setPath([...path, subfolderPath]);
361 const { id } = elem.dataset;
362 const item = collectionPanelFiles[id];
363 props.onSelectionToggle(event, item);
366 [path, setPath, collectionPanelFiles] // eslint-disable-line react-hooks/exhaustive-deps
369 const getItemIcon = React.useCallback(
370 (type: string, activeClass: string | null) => {
371 let Icon = DefaultIcon;
375 Icon = DirectoryIcon;
383 <ListItemIcon className={classNames(classes.listItemIcon, activeClass)}>
391 const getActiveClass = React.useCallback(
393 return path[path.length - 1] === name ? classes.rowActive : null;
398 const onOptionsMenuOpen = React.useCallback(
399 (ev, isWritable) => {
400 props.onOptionsMenuOpen(ev, isWritable);
402 [props.onOptionsMenuOpen] // eslint-disable-line react-hooks/exhaustive-deps
406 <div data-cy="collection-files-panel" onClick={handleClick} ref={parentRef}>
407 <div className={classes.pathPanel}>
408 <div className={classes.pathPanelPathWrapper}>
411 .map((p: string, index: number) => <span
412 key={`${index}-${p}`}
414 className={classes.pathPanelItem}
415 data-breadcrumb-path={p}
417 {index === 0 ? 'Home' : p} /
421 <Tooltip className={classes.pathPanelMenu} title="More options" disableFocusListener>
423 data-cy='collection-files-panel-options-btn'
424 onClick={(ev) => onOptionsMenuOpen(ev, isWritable)}>
425 <CustomizeTableIcon />
429 <div className={classes.wrapper}>
430 <div className={classNames(classes.leftPanel, path.length > 1 ? classes.leftPanelVisible : classes.leftPanelHidden)}>
431 <div className={path.length > 1 ? classes.searchWrapper : classes.searchWrapperHidden}>
432 <SearchInput label="Search" value={leftSearch} onSearch={setLeftSearch} />
434 <div className={classes.dataWrapper}>
437 <AutoSizer defaultWidth={0}>
438 {({ height, width }) => {
439 const filtered = leftData.filter(({ name }) => name.indexOf(leftSearch) > -1);
441 return !!filtered.length ? <FixedSizeList
443 itemCount={filtered.length}
448 ({ index, style }) => {
449 const { id, type, name } = filtered[index];
454 data-parent-path={name}
455 className={classNames(classes.row, getActiveClass(name))}
456 key={id}>{getItemIcon(type, getActiveClass(name))} <div className={classes.rowName}>{name}</div>
460 </FixedSizeList> : <div className={classes.rowEmpty}>No directories available</div>
462 </AutoSizer> : <div className={classes.row}><CircularProgress className={classes.loader} size={30} /></div>
467 <div className={classes.rightPanel}>
468 <div className={classes.searchWrapper}>
469 <SearchInput label="Search" value={rightSearch} onSearch={setRightSearch} />
474 className={classes.uploadButton}
475 data-cy='upload-button'
476 onClick={onUploadDataClick}
480 <DownloadIcon className={classes.uploadIcon} />
484 <div className={classes.dataWrapper}>
486 rightData && !isLoading ?
487 <AutoSizer defaultHeight={500}>
488 {({ height, width }) => {
489 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
491 return !!filtered.length ? <FixedSizeList
493 itemCount={filtered.length}
498 ({ index, style }) => {
499 const { id, type, name, size } = filtered[index];
506 data-subfolder-path={name}
507 className={classes.row} key={id}>
510 className={classes.rowSelection}
511 checked={collectionPanelFiles[id] ? collectionPanelFiles[id].value.selected : false}
513 {getItemIcon(type, null)} <div className={classes.rowName}>
516 <span className={classes.rowName} style={{ marginLeft: 'auto', marginRight: '1rem' }}>
517 {formatFileSize(size)}
522 </FixedSizeList> : <div className={classes.rowEmpty}>No data available</div>
524 </AutoSizer> : <div className={classes.row}><CircularProgress className={classes.loader} size={30} /></div>