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 } 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"
80 | "searchWrapperHidden";
82 const styles: StyleRulesCallback<CssRules> = (theme: Theme) => ({
86 color: 'rgba(0, 0, 0, 0.87)',
88 fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
91 letterSpacing: '0.01071em'
107 marginBottom: '0.5rem',
110 backgroundColor: 'rgba(0, 0, 0, 0.08)',
127 display: 'inline-flex',
128 flexDirection: 'column',
129 justifyContent: 'center'
132 display: 'inline-block',
133 marginBottom: '1rem',
136 searchWrapperHidden: {
143 color: `${theme.palette.primary.main} !important`,
146 display: 'inline-flex',
147 flexDirection: 'column',
148 justifyContent: 'center'
156 marginBottom: '1rem',
157 backgroundColor: '#fff',
158 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%)',
160 pathPanelPathWrapper: {
161 display: 'inline-block',
167 whiteSpace: 'nowrap',
168 position: 'relative',
169 backgroundColor: '#fff',
170 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%)',
175 animation: `animateVisible 1000ms ${theme.transitions.easing.easeOut}`
183 "@keyframes animateVisible": {
198 position: 'relative',
199 backgroundColor: '#fff',
200 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%)',
206 transform: 'rotate(180deg)'
213 const pathPromise = {};
215 export const CollectionPanelFiles = withStyles(styles)(connect((state: RootState) => ({
217 collectionPanel: state.collectionPanel,
218 collectionPanelFiles: state.collectionPanelFiles,
219 }))((props: CollectionPanelFilesProps & WithStyles<CssRules> & { auth: AuthState }) => {
220 const { classes, onItemMenuOpen, onUploadDataClick, isWritable, dispatch, collectionPanelFiles, collectionPanel } = props;
221 const { apiToken, config } = props.auth;
223 const webdavClient = new WebDAV();
224 webdavClient.defaults.baseURL = config.keepWebServiceUrl;
225 webdavClient.defaults.headers = {
226 Authorization: `Bearer ${apiToken}`
229 const webDAVRequestConfig: WebDAVRequestConfig = {
235 const parentRef = React.useRef(null);
236 const [path, setPath] = React.useState<string[]>([]);
237 const [pathData, setPathData] = React.useState({});
238 const [isLoading, setIsLoading] = React.useState(false);
239 const [leftSearch, setLeftSearch] = React.useState('');
240 const [rightSearch, setRightSearch] = React.useState('');
242 const leftKey = (path.length > 1 ? path.slice(0, path.length - 1) : path).join('/');
243 const rightKey = path.join('/');
245 const leftData = pathData[leftKey] || [];
246 const rightData = pathData[rightKey];
248 React.useEffect(() => {
249 if (props.currentItemUuid) {
251 setPath([props.currentItemUuid]);
253 }, [props.currentItemUuid]);
255 const fetchData = (keys, ignoreCache = false) => {
256 const keyArray = Array.isArray(keys) ? keys : [keys];
258 Promise.all(keyArray.filter(key => !!key)
260 const dataExists = !!pathData[key];
261 const runningRequest = pathPromise[key];
263 if (ignoreCache || (!dataExists && !runningRequest)) {
268 pathPromise[key] = true;
270 return webdavClient.propfind(`c=${key}`, webDAVRequestConfig);
273 return Promise.resolve(null);
275 .filter((promise) => !!promise)
277 .then((requests) => {
278 const newState = requests.map((request, index) => {
279 if (request && request.responseXML != null) {
280 const key = keyArray[index];
281 const result: any = extractFilesData(request.responseXML);
282 const sortedResult = sortBy(result, (n) => n.name).sort((n1, n2) => {
283 if (n1.type === 'directory' && n2.type !== 'directory') {
286 if (n1.type !== 'directory' && n2.type === 'directory') {
292 return { [key]: sortedResult };
295 }).reduce((prev, next) => {
296 return { ...next, ...prev };
299 setPathData({ ...pathData, ...newState });
303 keyArray.forEach(key => delete pathPromise[key]);
307 React.useEffect(() => {
313 }, [rightKey]); // eslint-disable-line react-hooks/exhaustive-deps
315 const currentPDH = (collectionPanel.item || {}).portableDataHash;
316 React.useEffect(() => {
318 // Avoid fetching the same content level twice
319 if (leftKey !== rightKey) {
320 fetchData([leftKey, rightKey], true);
322 fetchData(rightKey, true);
325 }, [currentPDH]); // eslint-disable-line react-hooks/exhaustive-deps
327 React.useEffect(() => {
329 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
330 setCollectionFiles(filtered, false)(dispatch);
332 }, [rightData, dispatch, rightSearch]);
334 const handleRightClick = React.useCallback(
336 event.preventDefault();
337 let elem = event.target;
339 while (elem && elem.dataset && !elem.dataset.item) {
340 elem = elem.parentNode;
343 if (!elem || !elem.dataset) {
347 const { id } = elem.dataset;
351 data: rightData.find((elem) => elem.id === id),
355 onItemMenuOpen(event, item, isWritable);
358 [onItemMenuOpen, isWritable, rightData]);
360 React.useEffect(() => {
363 if (parentRef?.current) {
364 node = parentRef.current;
365 (node as any).addEventListener('contextmenu', handleRightClick);
370 (node as any).removeEventListener('contextmenu', handleRightClick);
373 }, [parentRef, handleRightClick]);
375 const handleClick = React.useCallback(
377 let isCheckbox = false;
378 let elem = event.target;
380 if (elem.type === 'checkbox') {
384 while (elem && elem.dataset && !elem.dataset.item) {
385 elem = elem.parentNode;
388 if (elem && elem.dataset && !isCheckbox) {
389 const { parentPath, subfolderPath, breadcrumbPath, type } = elem.dataset;
391 if (breadcrumbPath) {
392 const index = path.indexOf(breadcrumbPath);
393 setPath([...path.slice(0, index + 1)]);
396 if (parentPath && type === 'directory') {
397 if (path.length > 1) {
401 setPath([...path, parentPath]);
404 if (subfolderPath && type === 'directory') {
405 setPath([...path, subfolderPath]);
408 if (elem.dataset.id && type === 'file') {
409 const item = rightData.find(({id}) => id === elem.dataset.id) || leftData.find(({ id }) => id === elem.dataset.id);
410 const enhancedItem = servicesProvider.getServices().collectionService.extendFileURL(item);
411 const fileUrl = sanitizeToken(getInlineFileUrl(enhancedItem.url, config.keepWebServiceUrl, config.keepWebInlineServiceUrl), true);
412 window.open(fileUrl, '_blank');
417 const { id } = elem.dataset;
418 const item = collectionPanelFiles[id];
419 props.onSelectionToggle(event, item);
422 [path, setPath, collectionPanelFiles] // eslint-disable-line react-hooks/exhaustive-deps
425 const getItemIcon = React.useCallback(
426 (type: string, activeClass: string | null) => {
427 let Icon = DefaultIcon;
431 Icon = DirectoryIcon;
439 <ListItemIcon className={classNames(classes.listItemIcon, activeClass)}>
447 const getActiveClass = React.useCallback(
449 return path[path.length - 1] === name ? classes.rowActive : null;
454 const onOptionsMenuOpen = React.useCallback(
455 (ev, isWritable) => {
456 props.onOptionsMenuOpen(ev, isWritable);
458 [props.onOptionsMenuOpen] // eslint-disable-line react-hooks/exhaustive-deps
461 return <div data-cy="collection-files-panel" onClick={handleClick} ref={parentRef}>
462 <div className={classes.pathPanel}>
463 <div className={classes.pathPanelPathWrapper}>
464 { path.map( (p: string, index: number) =>
465 <span key={`${index}-${p}`} data-item="true"
466 className={classes.pathPanelItem} data-breadcrumb-path={p}>
467 <span className={classes.rowActive}>{index === 0 ? 'Home' : p}</span> <b>/</b>
471 <Tooltip className={classes.pathPanelMenu} title="More options" disableFocusListener>
472 <IconButton data-cy='collection-files-panel-options-btn'
474 onOptionsMenuOpen(ev, isWritable);
476 <CustomizeTableIcon />
480 <div className={classes.wrapper}>
481 <div className={classNames(classes.leftPanel, path.length > 1 ? classes.leftPanelVisible : classes.leftPanelHidden)} data-cy="collection-files-left-panel">
482 <Tooltip title="Go back" className={path.length > 1 ? classes.backButton : classes.backButtonHidden}>
483 <IconButton onClick={() => setPath([...path.slice(0, path.length -1)])}>
487 <div className={path.length > 1 ? classes.searchWrapper : classes.searchWrapperHidden}>
488 <SearchInput selfClearProp={leftKey} label="Search" value={leftSearch} onSearch={setLeftSearch} />
490 <div className={classes.dataWrapper}>{ leftData
491 ? <AutoSizer defaultWidth={0}>{({ height, width }) => {
492 const filtered = leftData.filter(({ name }) => name.indexOf(leftSearch) > -1);
493 return !!filtered.length
494 ? <FixedSizeList height={height} itemCount={filtered.length}
495 itemSize={35} width={width}>{ ({ index, style }) => {
496 const { id, type, name } = filtered[index];
497 return <div data-id={id} style={style} data-item="true"
498 data-type={type} data-parent-path={name}
499 className={classNames(classes.row, getActiveClass(name))}
501 { getItemIcon(type, getActiveClass(name)) }
502 <div className={classes.rowName}>
505 { getActiveClass(name)
506 ? <SidePanelRightArrowIcon
507 style={{ display: 'inline', marginTop: '5px', marginLeft: '5px' }} />
512 : <div className={classes.rowEmpty}>No directories available</div>
515 : <div className={classes.row}><CircularProgress className={classes.loader} size={30} /></div> }
518 <div className={classes.rightPanel} data-cy="collection-files-right-panel">
519 <div className={classes.searchWrapper}>
520 <SearchInput selfClearProp={rightKey} label="Search" value={rightSearch} onSearch={setRightSearch} />
523 <Button className={classes.uploadButton} data-cy='upload-button'
525 onUploadDataClick(rightKey === leftKey ? undefined : rightKey);
527 variant='contained' color='primary' size='small'>
528 <DownloadIcon className={classes.uploadIcon} />
531 <div className={classes.dataWrapper}>{ rightData && !isLoading
532 ? <AutoSizer defaultHeight={500}>{({ height, width }) => {
533 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
534 return !!filtered.length
535 ? <FixedSizeList height={height} itemCount={filtered.length}
536 itemSize={35} width={width}>{ ({ index, style }) => {
537 const { id, type, name, size } = filtered[index];
539 return <div style={style} data-id={id} data-item="true"
540 data-type={type} data-subfolder-path={name}
541 className={classes.row} key={id}>
542 <Checkbox color="primary"
543 className={classes.rowSelection}
544 checked={collectionPanelFiles[id] ? collectionPanelFiles[id].value.selected : false}
546 {getItemIcon(type, null)}
547 <div className={classes.rowName}>
550 <span className={classes.rowName} style={{
551 marginLeft: 'auto', marginRight: '1rem' }}>
552 { formatFileSize(size) }
556 : <div className={classes.rowEmpty}>This collection is empty</div>
558 : <div className={classes.row}>
559 <CircularProgress className={classes.loader} size={30} />