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 servicesProvider from 'common/service-provider';
11 import { CustomizeTableIcon, DownloadIcon, MoreOptionsIcon } from 'components/icon/icon';
12 import { SearchInput } from 'components/search-input/search-input';
24 } from '@material-ui/core';
25 import { FileTreeData } from '../file-tree/file-tree-data';
26 import { TreeItem, TreeItemStatus } from '../tree/tree';
27 import { RootState } from 'store/store';
28 import { WebDAV, WebDAVRequestConfig } from 'common/webdav';
29 import { AuthState } from 'store/auth/auth-reducer';
30 import { extractFilesData } from 'services/collection-service/collection-service-files-response';
36 SidePanelRightArrowIcon
37 } from 'components/icon/icon';
38 import { setCollectionFiles } from 'store/collection-panel/collection-panel-files/collection-panel-files-actions';
39 import { sortBy } from 'lodash';
40 import { formatFileSize } from 'common/formatters';
41 import { getInlineFileUrl, sanitizeToken } from 'views-components/context-menu/actions/helpers';
43 export interface CollectionPanelFilesProps {
45 onUploadDataClick: (targetLocation?: string) => void;
46 onSearchChange: (searchValue: string) => void;
47 onItemMenuOpen: (event: React.MouseEvent<HTMLElement>, item: TreeItem<FileTreeData>, isWritable: boolean) => void;
48 onOptionsMenuOpen: (event: React.MouseEvent<HTMLElement>, isWritable: boolean) => void;
49 onSelectionToggle: (event: React.MouseEvent<HTMLElement>, item: TreeItem<FileTreeData>) => void;
50 onCollapseToggle: (id: string, status: TreeItemStatus) => void;
51 onFileClick: (id: string) => void;
54 collectionPanelFiles: any;
58 type CssRules = "backButton"
60 | "pathPanelPathWrapper"
82 | "searchWrapperHidden";
84 const styles: StyleRulesCallback<CssRules> = (theme: Theme) => ({
88 color: 'rgba(0,0,0,0.87)',
90 fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
93 letterSpacing: '0.01071em'
109 marginBottom: '0.5rem',
112 backgroundColor: 'rgba(0, 0, 0, 0.08)',
129 display: 'inline-flex',
130 flexDirection: 'column',
131 justifyContent: 'center'
134 display: 'inline-block',
135 marginBottom: '1rem',
138 searchWrapperHidden: {
145 color: `${theme.palette.primary.main} !important`,
148 display: 'inline-flex',
149 flexDirection: 'column',
150 justifyContent: 'center'
158 marginBottom: '0.5rem',
159 backgroundColor: '#fff',
160 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%)',
162 pathPanelPathWrapper: {
163 display: 'inline-block',
167 padding: '0 1rem 1rem',
169 whiteSpace: 'nowrap',
170 position: 'relative',
171 backgroundColor: '#fff',
172 boxShadow: '0px 3px 3px 0px rgb(0 0 0 / 20%), 0px 3px 1px 0px rgb(0 0 0 / 14%), 0px 3px 1px -1px rgb(0 0 0 / 12%)',
177 animation: `animateVisible 1000ms ${theme.transitions.easing.easeOut}`
185 "@keyframes animateVisible": {
198 paddingTop: '0.5rem',
199 marginTop: '-0.5rem',
200 position: 'relative',
201 backgroundColor: '#fff',
202 boxShadow: '0px 3px 3px 0px rgb(0 0 0 / 20%), 0px 3px 1px 0px rgb(0 0 0 / 14%), 0px 3px 1px -1px rgb(0 0 0 / 12%)',
208 transform: 'rotate(180deg)'
214 width: theme.spacing.unit * 3,
215 height: theme.spacing.unit * 3,
216 marginRight: theme.spacing.unit,
218 marginBottom: 'auto',
219 justifyContent: 'center',
226 const pathPromise = {};
228 export const CollectionPanelFiles = withStyles(styles)(connect((state: RootState) => ({
230 collectionPanel: state.collectionPanel,
231 collectionPanelFiles: state.collectionPanelFiles,
232 }))((props: CollectionPanelFilesProps & WithStyles<CssRules> & { auth: AuthState }) => {
233 const { classes, onItemMenuOpen, onUploadDataClick, isWritable, dispatch, collectionPanelFiles, collectionPanel } = props;
234 const { apiToken, config } = props.auth;
236 const webdavClient = new WebDAV({
237 baseURL: config.keepWebServiceUrl,
239 Authorization: `Bearer ${apiToken}`
243 const webDAVRequestConfig: WebDAVRequestConfig = {
249 const parentRef = React.useRef(null);
250 const [path, setPath] = React.useState<string[]>([]);
251 const [pathData, setPathData] = React.useState({});
252 const [isLoading, setIsLoading] = React.useState(false);
253 const [leftSearch, setLeftSearch] = React.useState('');
254 const [rightSearch, setRightSearch] = React.useState('');
256 const leftKey = (path.length > 1 ? path.slice(0, path.length - 1) : path).join('/');
257 const rightKey = path.join('/');
259 const leftData = pathData[leftKey] || [];
260 const rightData = pathData[rightKey];
262 React.useEffect(() => {
263 if (props.currentItemUuid) {
265 setPath([props.currentItemUuid]);
267 }, [props.currentItemUuid]);
269 const fetchData = (keys, ignoreCache = false) => {
270 const keyArray = Array.isArray(keys) ? keys : [keys];
272 Promise.all(keyArray.filter(key => !!key)
274 const dataExists = !!pathData[key];
275 const runningRequest = pathPromise[key];
277 if (ignoreCache || (!dataExists && !runningRequest)) {
282 pathPromise[key] = true;
284 return webdavClient.propfind(`c=${key}`, webDAVRequestConfig);
287 return Promise.resolve(null);
289 .filter((promise) => !!promise)
291 .then((requests) => {
292 const newState = requests.map((request, index) => {
293 if (request && request.responseXML != null) {
294 const key = keyArray[index];
295 const result: any = extractFilesData(request.responseXML);
296 const sortedResult = sortBy(result, (n) => n.name).sort((n1, n2) => {
297 if (n1.type === 'directory' && n2.type !== 'directory') {
300 if (n1.type !== 'directory' && n2.type === 'directory') {
306 return { [key]: sortedResult };
309 }).reduce((prev, next) => {
310 return { ...next, ...prev };
313 setPathData({ ...pathData, ...newState });
317 keyArray.forEach(key => delete pathPromise[key]);
321 React.useEffect(() => {
327 }, [rightKey]); // eslint-disable-line react-hooks/exhaustive-deps
329 const currentPDH = (collectionPanel.item || {}).portableDataHash;
330 React.useEffect(() => {
332 fetchData([leftKey, rightKey], true);
334 }, [currentPDH]); // eslint-disable-line react-hooks/exhaustive-deps
336 React.useEffect(() => {
338 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
339 setCollectionFiles(filtered, false)(dispatch);
341 }, [rightData, dispatch, rightSearch]);
343 const handleRightClick = React.useCallback(
345 event.preventDefault();
346 let elem = event.target;
348 while (elem && elem.dataset && !elem.dataset.item) {
349 elem = elem.parentNode;
352 if (!elem || !elem.dataset) {
356 const { id } = elem.dataset;
360 data: rightData.find((elem) => elem.id === id),
364 onItemMenuOpen(event, item, isWritable);
367 [onItemMenuOpen, isWritable, rightData]);
369 React.useEffect(() => {
372 if (parentRef?.current) {
373 node = parentRef.current;
374 (node as any).addEventListener('contextmenu', handleRightClick);
379 (node as any).removeEventListener('contextmenu', handleRightClick);
382 }, [parentRef, handleRightClick]);
384 const handleClick = React.useCallback(
386 let isCheckbox = false;
387 let isMoreButton = false;
388 let elem = event.target;
390 if (elem.type === 'checkbox') {
393 // The "More options" button click event could be triggered on its
394 // internal graphic element.
395 else if ((elem.dataset && elem.dataset.id === 'moreOptions') || (elem.parentNode && elem.parentNode.dataset && elem.parentNode.dataset.id === 'moreOptions')) {
399 while (elem && elem.dataset && !elem.dataset.item) {
400 elem = elem.parentNode;
403 if (elem && elem.dataset && !isCheckbox && !isMoreButton) {
404 const { parentPath, subfolderPath, breadcrumbPath, type } = elem.dataset;
406 if (breadcrumbPath) {
407 const index = path.indexOf(breadcrumbPath);
408 setPath([...path.slice(0, index + 1)]);
411 if (parentPath && type === 'directory') {
412 if (path.length > 1) {
416 setPath([...path, parentPath]);
419 if (subfolderPath && type === 'directory') {
420 setPath([...path, subfolderPath]);
423 if (elem.dataset.id && type === 'file') {
424 const item = rightData.find(({id}) => id === elem.dataset.id) || leftData.find(({ id }) => id === elem.dataset.id);
425 const enhancedItem = servicesProvider.getServices().collectionService.extendFileURL(item);
426 const fileUrl = sanitizeToken(getInlineFileUrl(enhancedItem.url, config.keepWebServiceUrl, config.keepWebInlineServiceUrl), true);
427 window.open(fileUrl, '_blank');
432 const { id } = elem.dataset;
433 const item = collectionPanelFiles[id];
434 props.onSelectionToggle(event, item);
437 const { id } = elem.dataset;
440 data: rightData.find((elem) => elem.id === id),
442 onItemMenuOpen(event, item, isWritable);
445 [path, setPath, collectionPanelFiles] // eslint-disable-line react-hooks/exhaustive-deps
448 const getItemIcon = React.useCallback(
449 (type: string, activeClass: string | null) => {
450 let Icon = DefaultIcon;
454 Icon = DirectoryIcon;
462 <ListItemIcon className={classNames(classes.listItemIcon, activeClass)}>
470 const getActiveClass = React.useCallback(
472 return path[path.length - 1] === name ? classes.rowActive : null;
477 const onOptionsMenuOpen = React.useCallback(
478 (ev, isWritable) => {
479 props.onOptionsMenuOpen(ev, isWritable);
481 [props.onOptionsMenuOpen] // eslint-disable-line react-hooks/exhaustive-deps
484 return <div data-cy="collection-files-panel" onClick={handleClick} ref={parentRef}>
485 <div className={classes.pathPanel}>
486 <div className={classes.pathPanelPathWrapper}>
487 { path.map( (p: string, index: number) =>
488 <span key={`${index}-${p}`} data-item="true"
489 className={classes.pathPanelItem} data-breadcrumb-path={p}>
490 <span className={classes.rowActive}>{index === 0 ? 'Home' : p}</span> <b>/</b>
494 <Tooltip className={classes.pathPanelMenu} title="More options" disableFocusListener>
495 <IconButton data-cy='collection-files-panel-options-btn'
497 onOptionsMenuOpen(ev, isWritable);
499 <CustomizeTableIcon />
503 <div className={classes.wrapper}>
504 <div className={classNames(classes.leftPanel, path.length > 1 ? classes.leftPanelVisible : classes.leftPanelHidden)} data-cy="collection-files-left-panel">
505 <Tooltip title="Go back" className={path.length > 1 ? classes.backButton : classes.backButtonHidden}>
506 <IconButton onClick={() => setPath([...path.slice(0, path.length -1)])}>
510 <div className={path.length > 1 ? classes.searchWrapper : classes.searchWrapperHidden}>
511 <SearchInput selfClearProp={leftKey} label="Search" value={leftSearch} onSearch={setLeftSearch} />
513 <div className={classes.dataWrapper}>{ leftData
514 ? <AutoSizer defaultWidth={0}>{({ height, width }) => {
515 const filtered = leftData.filter(({ name }) => name.indexOf(leftSearch) > -1);
516 return !!filtered.length
517 ? <FixedSizeList height={height} itemCount={filtered.length}
518 itemSize={35} width={width}>{ ({ index, style }) => {
519 const { id, type, name } = filtered[index];
520 return <div data-id={id} style={style} data-item="true"
521 data-type={type} data-parent-path={name}
522 className={classNames(classes.row, getActiveClass(name))}
524 { getItemIcon(type, getActiveClass(name)) }
525 <div className={classes.rowName}>
528 { getActiveClass(name)
529 ? <SidePanelRightArrowIcon
530 style={{ display: 'inline', marginTop: '5px', marginLeft: '5px' }} />
535 : <div className={classes.rowEmpty}>No directories available</div>
538 : <div data-cy="collection-loader" className={classes.row}><CircularProgress className={classes.loader} size={30} /></div> }
541 <div className={classes.rightPanel} data-cy="collection-files-right-panel">
542 <div className={classes.searchWrapper}>
543 <SearchInput selfClearProp={rightKey} label="Search" value={rightSearch} onSearch={setRightSearch} />
546 <Button className={classes.uploadButton} data-cy='upload-button'
548 onUploadDataClick(rightKey === leftKey ? undefined : rightKey);
550 variant='contained' color='primary' size='small'>
551 <DownloadIcon className={classes.uploadIcon} />
554 <div className={classes.dataWrapper}>{ rightData && !isLoading
555 ? <AutoSizer defaultHeight={500}>{({ height, width }) => {
556 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
557 return !!filtered.length
558 ? <FixedSizeList height={height} itemCount={filtered.length}
559 itemSize={35} width={width}>{ ({ index, style }) => {
560 const { id, type, name, size } = filtered[index];
562 return <div style={style} data-id={id} data-item="true"
563 data-type={type} data-subfolder-path={name}
564 className={classes.row} key={id}>
565 <Checkbox color="primary"
566 className={classes.rowSelection}
567 checked={collectionPanelFiles[id] ? collectionPanelFiles[id].value.selected : false}
569 {getItemIcon(type, null)}
570 <div className={classes.rowName}>
573 <span className={classes.rowName} style={{
574 marginLeft: 'auto', marginRight: '1rem' }}>
575 { formatFileSize(size) }
577 <Tooltip title="More options" disableFocusListener>
578 <IconButton data-id='moreOptions'
579 data-cy='file-item-options-btn'
580 className={classes.moreOptionsButton}>
582 data-id='moreOptions'
583 className={classes.moreOptions} />
588 : <div className={classes.rowEmpty}>This collection is empty</div>
590 : <div className={classes.row}>
591 <CircularProgress className={classes.loader} size={30} />