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';
13 import { ListItemIcon, StyleRulesCallback, Theme, WithStyles, withStyles, Tooltip, IconButton, Checkbox, CircularProgress, Button } from '@material-ui/core';
14 import { FileTreeData } from '../file-tree/file-tree-data';
15 import { TreeItem, TreeItemStatus } from '../tree/tree';
16 import { RootState } from 'store/store';
17 import { WebDAV, WebDAVRequestConfig } from 'common/webdav';
18 import { AuthState } from 'store/auth/auth-reducer';
19 import { extractFilesData } from 'services/collection-service/collection-service-files-response';
20 import { DefaultIcon, DirectoryIcon, FileIcon, BackIcon } from 'components/icon/icon';
21 import { setCollectionFiles } from 'store/collection-panel/collection-panel-files/collection-panel-files-actions';
22 import { sortBy } from 'lodash';
23 import { formatFileSize } from 'common/formatters';
24 import { getInlineFileUrl, sanitizeToken } from 'views-components/context-menu/actions/helpers';
26 export interface CollectionPanelFilesProps {
30 tooManyFiles: boolean;
31 onUploadDataClick: () => void;
32 onSearchChange: (searchValue: string) => void;
33 onItemMenuOpen: (event: React.MouseEvent<HTMLElement>, item: TreeItem<FileTreeData>, isWritable: boolean) => void;
34 onOptionsMenuOpen: (event: React.MouseEvent<HTMLElement>, isWritable: boolean) => void;
35 onSelectionToggle: (event: React.MouseEvent<HTMLElement>, item: TreeItem<FileTreeData>) => void;
36 onCollapseToggle: (id: string, status: TreeItemStatus) => void;
37 onFileClick: (id: string) => void;
38 loadFilesFunc: () => void;
41 collectionPanelFiles: any;
45 type CssRules = "backButton" | "backButtonHidden" | "pathPanelPathWrapper" | "uploadButton" | "uploadIcon" | "loader" | "wrapper" | "dataWrapper" | "row" | "rowEmpty" | "leftPanel" | "rightPanel" | "pathPanel" | "pathPanelItem" | "rowName" | "listItemIcon" | "rowActive" | "pathPanelMenu" | "rowSelection" | "leftPanelHidden" | "leftPanelVisible" | "searchWrapper" | "searchWrapperHidden";
47 const styles: StyleRulesCallback<CssRules> = (theme: Theme) => ({
52 color: 'rgba(0, 0, 0, 0.87)',
54 fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
57 letterSpacing: '0.01071em'
73 marginBottom: '0.5rem',
76 backgroundColor: 'rgba(0, 0, 0, 0.08)',
93 display: 'inline-flex',
94 flexDirection: 'column',
95 justifyContent: 'center'
98 display: 'inline-block',
102 searchWrapperHidden: {
109 color: `${theme.palette.primary.main} !important`,
112 display: 'inline-flex',
113 flexDirection: 'column',
114 justifyContent: 'center'
122 marginBottom: '1rem',
123 backgroundColor: '#fff',
124 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%)',
126 pathPanelPathWrapper: {
127 display: 'inline-block',
133 whiteSpace: 'nowrap',
134 position: 'relative',
135 backgroundColor: '#fff',
136 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%)',
141 animation: `animateVisible 1000ms ${theme.transitions.easing.easeOut}`
149 "@keyframes animateVisible": {
164 position: 'relative',
165 backgroundColor: '#fff',
166 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%)',
172 transform: 'rotate(180deg)'
179 const pathPromise = {};
181 export const CollectionPanelFiles = withStyles(styles)(connect((state: RootState) => ({
183 collectionPanel: state.collectionPanel,
184 collectionPanelFiles: state.collectionPanelFiles,
185 }))((props: CollectionPanelFilesProps & WithStyles<CssRules> & { auth: AuthState }) => {
186 const { classes, onItemMenuOpen, onUploadDataClick, isWritable, dispatch, collectionPanelFiles, collectionPanel } = props;
187 const { apiToken, config } = props.auth;
189 const webdavClient = new WebDAV();
190 webdavClient.defaults.baseURL = config.keepWebServiceUrl;
191 webdavClient.defaults.headers = {
192 Authorization: `Bearer ${apiToken}`
195 const webDAVRequestConfig: WebDAVRequestConfig = {
201 const parentRef = React.useRef(null);
202 const [path, setPath]: any = React.useState([]);
203 const [pathData, setPathData]: any = React.useState({});
204 const [isLoading, setIsLoading] = React.useState(false);
205 const [collectionAutofetchEnabled, setCollectionAutofetchEnabled] = React.useState(false);
206 const [leftSearch, setLeftSearch] = React.useState('');
207 const [rightSearch, setRightSearch] = React.useState('');
209 const leftKey = (path.length > 1 ? path.slice(0, path.length - 1) : path).join('/');
210 const rightKey = path.join('/');
212 const leftData = pathData[leftKey] || [];
213 const rightData = pathData[rightKey];
215 React.useEffect(() => {
216 if (props.currentItemUuid) {
218 setPath([props.currentItemUuid]);
220 }, [props.currentItemUuid]);
222 const fetchData = (keys, ignoreCache = false) => {
223 const keyArray = Array.isArray(keys) ? keys : [keys];
227 const dataExists = !!pathData[key];
228 const runningRequest = pathPromise[key];
230 if ((!dataExists || ignoreCache) && (!runningRequest || ignoreCache)) {
235 pathPromise[key] = true;
237 return webdavClient.propfind(`c=${key}`, webDAVRequestConfig);
240 return Promise.resolve(null);
242 .filter((promise) => !!promise)
244 .then((requests) => {
245 const newState = requests.map((request, index) => {
246 if (request && request.responseXML != null) {
247 const key = keyArray[index];
248 const result: any = extractFilesData(request.responseXML);
249 const sortedResult = sortBy(result, (n) => n.name).sort((n1, n2) => {
250 if (n1.type === 'directory' && n2.type !== 'directory') {
253 if (n1.type !== 'directory' && n2.type === 'directory') {
259 return { [key]: sortedResult };
262 }).reduce((prev, next) => {
263 return { ...next, ...prev };
266 setPathData({ ...pathData, ...newState });
270 keyArray.forEach(key => delete pathPromise[key]);
274 React.useEffect(() => {
280 }, [rightKey]); // eslint-disable-line react-hooks/exhaustive-deps
282 React.useEffect(() => {
283 const hash = (collectionPanel.item || {}).portableDataHash;
285 if (hash && collectionAutofetchEnabled) {
286 fetchData([leftKey, rightKey], true);
288 }, [(collectionPanel.item || {}).portableDataHash]); // eslint-disable-line react-hooks/exhaustive-deps
290 React.useEffect(() => {
292 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
293 setCollectionFiles(filtered, false)(dispatch);
295 }, [rightData, dispatch, rightSearch]);
297 const handleRightClick = React.useCallback(
299 event.preventDefault();
300 let elem = event.target;
302 while (elem && elem.dataset && !elem.dataset.item) {
303 elem = elem.parentNode;
306 if (!elem || !elem.dataset) {
310 const { id } = elem.dataset;
314 data: rightData.find((elem) => elem.id === id),
318 onItemMenuOpen(event, item, isWritable);
320 if (!collectionAutofetchEnabled) {
321 setCollectionAutofetchEnabled(true);
325 [onItemMenuOpen, isWritable, rightData] // eslint-disable-line react-hooks/exhaustive-deps
328 React.useEffect(() => {
331 if (parentRef && parentRef.current) {
332 node = parentRef.current;
333 (node as any).addEventListener('contextmenu', handleRightClick);
338 (node as any).removeEventListener('contextmenu', handleRightClick);
341 }, [parentRef, handleRightClick]);
343 const handleClick = React.useCallback(
345 let isCheckbox = false;
346 let elem = event.target;
348 if (elem.type === 'checkbox') {
352 while (elem && elem.dataset && !elem.dataset.item) {
353 elem = elem.parentNode;
356 if (elem && elem.dataset && !isCheckbox) {
357 const { parentPath, subfolderPath, breadcrumbPath, type } = elem.dataset;
359 if (breadcrumbPath) {
360 const index = path.indexOf(breadcrumbPath);
361 setPath([...path.slice(0, index + 1)]);
364 if (parentPath && type === 'directory') {
365 if (path.length > 1) {
369 setPath([...path, parentPath]);
372 if (subfolderPath && type === 'directory') {
373 setPath([...path, subfolderPath]);
376 if (elem.dataset.id && type === 'file') {
377 const item = rightData.find(({id}) => id === elem.dataset.id) || leftData.find(({ id }) => id === elem.dataset.id);
378 const enhancedItem = servicesProvider.getServices().collectionService.extendFileURL(item);
379 const fileUrl = sanitizeToken(getInlineFileUrl(enhancedItem.url, config.keepWebServiceUrl, config.keepWebInlineServiceUrl), true);
380 window.open(fileUrl, '_blank');
385 const { id } = elem.dataset;
386 const item = collectionPanelFiles[id];
387 props.onSelectionToggle(event, item);
390 [path, setPath, collectionPanelFiles] // eslint-disable-line react-hooks/exhaustive-deps
393 const getItemIcon = React.useCallback(
394 (type: string, activeClass: string | null) => {
395 let Icon = DefaultIcon;
399 Icon = DirectoryIcon;
407 <ListItemIcon className={classNames(classes.listItemIcon, activeClass)}>
415 const getActiveClass = React.useCallback(
417 return path[path.length - 1] === name ? classes.rowActive : null;
422 const onOptionsMenuOpen = React.useCallback(
423 (ev, isWritable) => {
424 props.onOptionsMenuOpen(ev, isWritable);
426 [props.onOptionsMenuOpen] // eslint-disable-line react-hooks/exhaustive-deps
430 <div data-cy="collection-files-panel" onClick={handleClick} ref={parentRef}>
431 <div className={classes.pathPanel}>
432 <div className={classes.pathPanelPathWrapper}>
435 .map((p: string, index: number) => <span
436 key={`${index}-${p}`}
438 className={classes.pathPanelItem}
439 data-breadcrumb-path={p}
441 <span className={classes.rowActive}>{index === 0 ? 'Home' : p}</span> <b>/</b>
445 <Tooltip className={classes.pathPanelMenu} title="More options" disableFocusListener>
447 data-cy='collection-files-panel-options-btn'
449 if (!collectionAutofetchEnabled) {
450 setCollectionAutofetchEnabled(true);
452 onOptionsMenuOpen(ev, isWritable);
454 <CustomizeTableIcon />
458 <div className={classes.wrapper}>
459 <div className={classNames(classes.leftPanel, path.length > 1 ? classes.leftPanelVisible : classes.leftPanelHidden)}>
460 <Tooltip title="Go back" className={path.length > 1 ? classes.backButton : classes.backButtonHidden}>
461 <IconButton onClick={() => setPath([...path.slice(0, path.length -1)])}>
465 <div className={path.length > 1 ? classes.searchWrapper : classes.searchWrapperHidden}>
466 <SearchInput label="Search" value={leftSearch} onSearch={setLeftSearch} />
468 <div className={classes.dataWrapper}>
471 <AutoSizer defaultWidth={0}>
472 {({ height, width }) => {
473 const filtered = leftData.filter(({ name }) => name.indexOf(leftSearch) > -1);
475 return !!filtered.length ? <FixedSizeList
477 itemCount={filtered.length}
482 ({ index, style }) => {
483 const { id, type, name } = filtered[index];
490 data-parent-path={name}
491 className={classNames(classes.row, getActiveClass(name))}
492 key={id}>{getItemIcon(type, getActiveClass(name))} <div className={classes.rowName}>{name}</div>
496 </FixedSizeList> : <div className={classes.rowEmpty}>No directories available</div>
498 </AutoSizer> : <div className={classes.row}><CircularProgress className={classes.loader} size={30} /></div>
503 <div className={classes.rightPanel}>
504 <div className={classes.searchWrapper}>
505 <SearchInput label="Search" value={rightSearch} onSearch={setRightSearch} />
510 className={classes.uploadButton}
511 data-cy='upload-button'
512 onClick={onUploadDataClick}
516 <DownloadIcon className={classes.uploadIcon} />
520 <div className={classes.dataWrapper}>
522 rightData && !isLoading ?
523 <AutoSizer defaultHeight={500}>
524 {({ height, width }) => {
525 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
527 return !!filtered.length ? <FixedSizeList
529 itemCount={filtered.length}
534 ({ index, style }) => {
535 const { id, type, name, size } = filtered[index];
542 data-subfolder-path={name}
543 className={classes.row} key={id}>
546 className={classes.rowSelection}
547 checked={collectionPanelFiles[id] ? collectionPanelFiles[id].value.selected : false}
549 {getItemIcon(type, null)} <div className={classes.rowName}>
552 <span className={classes.rowName} style={{ marginLeft: 'auto', marginRight: '1rem' }}>
553 {formatFileSize(size)}
558 </FixedSizeList> : <div className={classes.rowEmpty}>No data available</div>
560 </AutoSizer> : <div className={classes.row}><CircularProgress className={classes.loader} size={30} /></div>