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: '1rem',
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',
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": {
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 webdavClient.defaults.baseURL = config.keepWebServiceUrl;
238 webdavClient.defaults.headers = {
239 Authorization: `Bearer ${apiToken}`
242 const webDAVRequestConfig: WebDAVRequestConfig = {
248 const parentRef = React.useRef(null);
249 const [path, setPath] = React.useState<string[]>([]);
250 const [pathData, setPathData] = React.useState({});
251 const [isLoading, setIsLoading] = React.useState(false);
252 const [leftSearch, setLeftSearch] = React.useState('');
253 const [rightSearch, setRightSearch] = React.useState('');
255 const leftKey = (path.length > 1 ? path.slice(0, path.length - 1) : path).join('/');
256 const rightKey = path.join('/');
258 const leftData = pathData[leftKey] || [];
259 const rightData = pathData[rightKey];
261 React.useEffect(() => {
262 if (props.currentItemUuid) {
264 setPath([props.currentItemUuid]);
266 }, [props.currentItemUuid]);
268 const fetchData = (keys, ignoreCache = false) => {
269 const keyArray = Array.isArray(keys) ? keys : [keys];
271 Promise.all(keyArray.filter(key => !!key)
273 const dataExists = !!pathData[key];
274 const runningRequest = pathPromise[key];
276 if (ignoreCache || (!dataExists && !runningRequest)) {
281 pathPromise[key] = true;
283 return webdavClient.propfind(`c=${key}`, webDAVRequestConfig);
286 return Promise.resolve(null);
288 .filter((promise) => !!promise)
290 .then((requests) => {
291 const newState = requests.map((request, index) => {
292 if (request && request.responseXML != null) {
293 const key = keyArray[index];
294 const result: any = extractFilesData(request.responseXML);
295 const sortedResult = sortBy(result, (n) => n.name).sort((n1, n2) => {
296 if (n1.type === 'directory' && n2.type !== 'directory') {
299 if (n1.type !== 'directory' && n2.type === 'directory') {
305 return { [key]: sortedResult };
308 }).reduce((prev, next) => {
309 return { ...next, ...prev };
312 setPathData({ ...pathData, ...newState });
316 keyArray.forEach(key => delete pathPromise[key]);
320 React.useEffect(() => {
326 }, [rightKey]); // eslint-disable-line react-hooks/exhaustive-deps
328 const currentPDH = (collectionPanel.item || {}).portableDataHash;
329 React.useEffect(() => {
331 // Avoid fetching the same content level twice
332 if (leftKey !== rightKey) {
333 fetchData([leftKey, rightKey], true);
335 fetchData(rightKey, true);
338 }, [currentPDH]); // eslint-disable-line react-hooks/exhaustive-deps
340 React.useEffect(() => {
342 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
343 setCollectionFiles(filtered, false)(dispatch);
345 }, [rightData, dispatch, rightSearch]);
347 const handleRightClick = React.useCallback(
349 event.preventDefault();
350 let elem = event.target;
352 while (elem && elem.dataset && !elem.dataset.item) {
353 elem = elem.parentNode;
356 if (!elem || !elem.dataset) {
360 const { id } = elem.dataset;
364 data: rightData.find((elem) => elem.id === id),
368 onItemMenuOpen(event, item, isWritable);
371 [onItemMenuOpen, isWritable, rightData]);
373 React.useEffect(() => {
376 if (parentRef?.current) {
377 node = parentRef.current;
378 (node as any).addEventListener('contextmenu', handleRightClick);
383 (node as any).removeEventListener('contextmenu', handleRightClick);
386 }, [parentRef, handleRightClick]);
388 const handleClick = React.useCallback(
390 let isCheckbox = false;
391 let isMoreButton = false;
392 let elem = event.target;
394 if (elem.type === 'checkbox') {
397 // The "More options" button click event could be triggered on its
398 // internal graphic element.
399 else if ((elem.dataset && elem.dataset.id === 'moreOptions') || (elem.parentNode && elem.parentNode.dataset && elem.parentNode.dataset.id === 'moreOptions')) {
403 while (elem && elem.dataset && !elem.dataset.item) {
404 elem = elem.parentNode;
407 if (elem && elem.dataset && !isCheckbox && !isMoreButton) {
408 const { parentPath, subfolderPath, breadcrumbPath, type } = elem.dataset;
410 if (breadcrumbPath) {
411 const index = path.indexOf(breadcrumbPath);
412 setPath([...path.slice(0, index + 1)]);
415 if (parentPath && type === 'directory') {
416 if (path.length > 1) {
420 setPath([...path, parentPath]);
423 if (subfolderPath && type === 'directory') {
424 setPath([...path, subfolderPath]);
427 if (elem.dataset.id && type === 'file') {
428 const item = rightData.find(({id}) => id === elem.dataset.id) || leftData.find(({ id }) => id === elem.dataset.id);
429 const enhancedItem = servicesProvider.getServices().collectionService.extendFileURL(item);
430 const fileUrl = sanitizeToken(getInlineFileUrl(enhancedItem.url, config.keepWebServiceUrl, config.keepWebInlineServiceUrl), true);
431 window.open(fileUrl, '_blank');
436 const { id } = elem.dataset;
437 const item = collectionPanelFiles[id];
438 props.onSelectionToggle(event, item);
441 const { id } = elem.dataset;
444 data: rightData.find((elem) => elem.id === id),
446 onItemMenuOpen(event, item, isWritable);
449 [path, setPath, collectionPanelFiles] // eslint-disable-line react-hooks/exhaustive-deps
452 const getItemIcon = React.useCallback(
453 (type: string, activeClass: string | null) => {
454 let Icon = DefaultIcon;
458 Icon = DirectoryIcon;
466 <ListItemIcon className={classNames(classes.listItemIcon, activeClass)}>
474 const getActiveClass = React.useCallback(
476 return path[path.length - 1] === name ? classes.rowActive : null;
481 const onOptionsMenuOpen = React.useCallback(
482 (ev, isWritable) => {
483 props.onOptionsMenuOpen(ev, isWritable);
485 [props.onOptionsMenuOpen] // eslint-disable-line react-hooks/exhaustive-deps
488 return <div data-cy="collection-files-panel" onClick={handleClick} ref={parentRef}>
489 <div className={classes.pathPanel}>
490 <div className={classes.pathPanelPathWrapper}>
491 { path.map( (p: string, index: number) =>
492 <span key={`${index}-${p}`} data-item="true"
493 className={classes.pathPanelItem} data-breadcrumb-path={p}>
494 <span className={classes.rowActive}>{index === 0 ? 'Home' : p}</span> <b>/</b>
498 <Tooltip className={classes.pathPanelMenu} title="More options" disableFocusListener>
499 <IconButton data-cy='collection-files-panel-options-btn'
501 onOptionsMenuOpen(ev, isWritable);
503 <CustomizeTableIcon />
507 <div className={classes.wrapper}>
508 <div className={classNames(classes.leftPanel, path.length > 1 ? classes.leftPanelVisible : classes.leftPanelHidden)} data-cy="collection-files-left-panel">
509 <Tooltip title="Go back" className={path.length > 1 ? classes.backButton : classes.backButtonHidden}>
510 <IconButton onClick={() => setPath([...path.slice(0, path.length -1)])}>
514 <div className={path.length > 1 ? classes.searchWrapper : classes.searchWrapperHidden}>
515 <SearchInput selfClearProp={leftKey} label="Search" value={leftSearch} onSearch={setLeftSearch} />
517 <div className={classes.dataWrapper}>{ leftData
518 ? <AutoSizer defaultWidth={0}>{({ height, width }) => {
519 const filtered = leftData.filter(({ name }) => name.indexOf(leftSearch) > -1);
520 return !!filtered.length
521 ? <FixedSizeList height={height} itemCount={filtered.length}
522 itemSize={35} width={width}>{ ({ index, style }) => {
523 const { id, type, name } = filtered[index];
524 return <div data-id={id} style={style} data-item="true"
525 data-type={type} data-parent-path={name}
526 className={classNames(classes.row, getActiveClass(name))}
528 { getItemIcon(type, getActiveClass(name)) }
529 <div className={classes.rowName}>
532 { getActiveClass(name)
533 ? <SidePanelRightArrowIcon
534 style={{ display: 'inline', marginTop: '5px', marginLeft: '5px' }} />
539 : <div className={classes.rowEmpty}>No directories available</div>
542 : <div data-cy="collection-loader" className={classes.row}><CircularProgress className={classes.loader} size={30} /></div> }
545 <div className={classes.rightPanel} data-cy="collection-files-right-panel">
546 <div className={classes.searchWrapper}>
547 <SearchInput selfClearProp={rightKey} label="Search" value={rightSearch} onSearch={setRightSearch} />
550 <Button className={classes.uploadButton} data-cy='upload-button'
552 onUploadDataClick(rightKey === leftKey ? undefined : rightKey);
554 variant='contained' color='primary' size='small'>
555 <DownloadIcon className={classes.uploadIcon} />
558 <div className={classes.dataWrapper}>{ rightData && !isLoading
559 ? <AutoSizer defaultHeight={500}>{({ height, width }) => {
560 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
561 return !!filtered.length
562 ? <FixedSizeList height={height} itemCount={filtered.length}
563 itemSize={35} width={width}>{ ({ index, style }) => {
564 const { id, type, name, size } = filtered[index];
566 return <div style={style} data-id={id} data-item="true"
567 data-type={type} data-subfolder-path={name}
568 className={classes.row} key={id}>
569 <Checkbox color="primary"
570 className={classes.rowSelection}
571 checked={collectionPanelFiles[id] ? collectionPanelFiles[id].value.selected : false}
573 {getItemIcon(type, null)}
574 <div className={classes.rowName}>
577 <span className={classes.rowName} style={{
578 marginLeft: 'auto', marginRight: '1rem' }}>
579 { formatFileSize(size) }
581 <Tooltip title="More options" disableFocusListener>
582 <IconButton data-id='moreOptions'
583 data-cy='file-item-options-btn'
584 className={classes.moreOptionsButton}>
586 data-id='moreOptions'
587 className={classes.moreOptions} />
592 : <div className={classes.rowEmpty}>This collection is empty</div>
594 : <div className={classes.row}>
595 <CircularProgress className={classes.loader} size={30} />