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, SidePanelRightArrowIcon } 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) => ({
51 color: 'rgba(0, 0, 0, 0.87)',
53 fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
56 letterSpacing: '0.01071em'
72 marginBottom: '0.5rem',
75 backgroundColor: 'rgba(0, 0, 0, 0.08)',
92 display: 'inline-flex',
93 flexDirection: 'column',
94 justifyContent: 'center'
97 display: 'inline-block',
101 searchWrapperHidden: {
108 color: `${theme.palette.primary.main} !important`,
111 display: 'inline-flex',
112 flexDirection: 'column',
113 justifyContent: 'center'
121 marginBottom: '1rem',
122 backgroundColor: '#fff',
123 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%)',
125 pathPanelPathWrapper: {
126 display: 'inline-block',
132 whiteSpace: 'nowrap',
133 position: 'relative',
134 backgroundColor: '#fff',
135 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%)',
140 animation: `animateVisible 1000ms ${theme.transitions.easing.easeOut}`
148 "@keyframes animateVisible": {
163 position: 'relative',
164 backgroundColor: '#fff',
165 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%)',
171 transform: 'rotate(180deg)'
178 const pathPromise = {};
180 export const CollectionPanelFiles = withStyles(styles)(connect((state: RootState) => ({
182 collectionPanel: state.collectionPanel,
183 collectionPanelFiles: state.collectionPanelFiles,
184 }))((props: CollectionPanelFilesProps & WithStyles<CssRules> & { auth: AuthState }) => {
185 const { classes, onItemMenuOpen, onUploadDataClick, isWritable, dispatch, collectionPanelFiles, collectionPanel } = props;
186 const { apiToken, config } = props.auth;
188 const webdavClient = new WebDAV();
189 webdavClient.defaults.baseURL = config.keepWebServiceUrl;
190 webdavClient.defaults.headers = {
191 Authorization: `Bearer ${apiToken}`
194 const webDAVRequestConfig: WebDAVRequestConfig = {
200 const parentRef = React.useRef(null);
201 const [path, setPath]: any = React.useState([]);
202 const [pathData, setPathData]: any = React.useState({});
203 const [isLoading, setIsLoading] = React.useState(false);
204 const [collectionAutofetchEnabled, setCollectionAutofetchEnabled] = React.useState(false);
205 const [leftSearch, setLeftSearch] = React.useState('');
206 const [rightSearch, setRightSearch] = React.useState('');
208 const leftKey = (path.length > 1 ? path.slice(0, path.length - 1) : path).join('/');
209 const rightKey = path.join('/');
211 const leftData = pathData[leftKey] || [];
212 const rightData = pathData[rightKey];
214 React.useEffect(() => {
215 if (props.currentItemUuid) {
217 setPath([props.currentItemUuid]);
219 }, [props.currentItemUuid]);
221 const fetchData = (keys, ignoreCache = false) => {
222 const keyArray = Array.isArray(keys) ? keys : [keys];
226 const dataExists = !!pathData[key];
227 const runningRequest = pathPromise[key];
229 if ((!dataExists || ignoreCache) && (!runningRequest || ignoreCache)) {
234 pathPromise[key] = true;
236 return webdavClient.propfind(`c=${key}`, webDAVRequestConfig);
239 return Promise.resolve(null);
241 .filter((promise) => !!promise)
243 .then((requests) => {
244 const newState = requests.map((request, index) => {
245 if (request && request.responseXML != null) {
246 const key = keyArray[index];
247 const result: any = extractFilesData(request.responseXML);
248 const sortedResult = sortBy(result, (n) => n.name).sort((n1, n2) => {
249 if (n1.type === 'directory' && n2.type !== 'directory') {
252 if (n1.type !== 'directory' && n2.type === 'directory') {
258 return { [key]: sortedResult };
261 }).reduce((prev, next) => {
262 return { ...next, ...prev };
265 setPathData({ ...pathData, ...newState });
269 keyArray.forEach(key => delete pathPromise[key]);
273 React.useEffect(() => {
279 }, [rightKey]); // eslint-disable-line react-hooks/exhaustive-deps
281 React.useEffect(() => {
282 const hash = (collectionPanel.item || {}).portableDataHash;
284 if (hash && collectionAutofetchEnabled) {
285 fetchData([leftKey, rightKey], true);
287 }, [(collectionPanel.item || {}).portableDataHash]); // eslint-disable-line react-hooks/exhaustive-deps
289 React.useEffect(() => {
291 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
292 setCollectionFiles(filtered, false)(dispatch);
294 }, [rightData, dispatch, rightSearch]);
296 const handleRightClick = React.useCallback(
298 event.preventDefault();
299 let elem = event.target;
301 while (elem && elem.dataset && !elem.dataset.item) {
302 elem = elem.parentNode;
305 if (!elem || !elem.dataset) {
309 const { id } = elem.dataset;
313 data: rightData.find((elem) => elem.id === id),
317 onItemMenuOpen(event, item, isWritable);
319 if (!collectionAutofetchEnabled) {
320 setCollectionAutofetchEnabled(true);
324 [onItemMenuOpen, isWritable, rightData] // eslint-disable-line react-hooks/exhaustive-deps
327 React.useEffect(() => {
330 if (parentRef && parentRef.current) {
331 node = parentRef.current;
332 (node as any).addEventListener('contextmenu', handleRightClick);
337 (node as any).removeEventListener('contextmenu', handleRightClick);
340 }, [parentRef, handleRightClick]);
342 const handleClick = React.useCallback(
344 let isCheckbox = false;
345 let elem = event.target;
347 if (elem.type === 'checkbox') {
351 while (elem && elem.dataset && !elem.dataset.item) {
352 elem = elem.parentNode;
355 if (elem && elem.dataset && !isCheckbox) {
356 const { parentPath, subfolderPath, breadcrumbPath, type } = elem.dataset;
358 if (breadcrumbPath) {
359 const index = path.indexOf(breadcrumbPath);
360 setPath([...path.slice(0, index + 1)]);
363 if (parentPath && type === 'directory') {
364 if (path.length > 1) {
368 setPath([...path, parentPath]);
371 if (subfolderPath && type === 'directory') {
372 setPath([...path, subfolderPath]);
375 if (elem.dataset.id && type === 'file') {
376 const item = rightData.find(({id}) => id === elem.dataset.id) || leftData.find(({ id }) => id === elem.dataset.id);
377 const enhancedItem = servicesProvider.getServices().collectionService.extendFileURL(item);
378 const fileUrl = sanitizeToken(getInlineFileUrl(enhancedItem.url, config.keepWebServiceUrl, config.keepWebInlineServiceUrl), true);
379 window.open(fileUrl, '_blank');
384 const { id } = elem.dataset;
385 const item = collectionPanelFiles[id];
386 props.onSelectionToggle(event, item);
389 [path, setPath, collectionPanelFiles] // eslint-disable-line react-hooks/exhaustive-deps
392 const getItemIcon = React.useCallback(
393 (type: string, activeClass: string | null) => {
394 let Icon = DefaultIcon;
398 Icon = DirectoryIcon;
406 <ListItemIcon className={classNames(classes.listItemIcon, activeClass)}>
414 const getActiveClass = React.useCallback(
416 return path[path.length - 1] === name ? classes.rowActive : null;
421 const onOptionsMenuOpen = React.useCallback(
422 (ev, isWritable) => {
423 props.onOptionsMenuOpen(ev, isWritable);
425 [props.onOptionsMenuOpen] // eslint-disable-line react-hooks/exhaustive-deps
429 <div data-cy="collection-files-panel" onClick={handleClick} ref={parentRef}>
430 <div className={classes.pathPanel}>
431 <div className={classes.pathPanelPathWrapper}>
434 .map((p: string, index: number) => <span
435 key={`${index}-${p}`}
437 className={classes.pathPanelItem}
438 data-breadcrumb-path={p}
440 <span className={classes.rowActive}>{index === 0 ? 'Home' : p}</span> <b>/</b>
444 <Tooltip className={classes.pathPanelMenu} title="More options" disableFocusListener>
446 data-cy='collection-files-panel-options-btn'
448 if (!collectionAutofetchEnabled) {
449 setCollectionAutofetchEnabled(true);
451 onOptionsMenuOpen(ev, isWritable);
453 <CustomizeTableIcon />
457 <div className={classes.wrapper}>
458 <div className={classNames(classes.leftPanel, path.length > 1 ? classes.leftPanelVisible : classes.leftPanelHidden)}>
459 <Tooltip title="Go back" className={path.length > 1 ? classes.backButton : classes.backButtonHidden}>
460 <IconButton onClick={() => setPath([...path.slice(0, path.length -1)])}>
464 <div className={path.length > 1 ? classes.searchWrapper : classes.searchWrapperHidden}>
465 <SearchInput selfClearProp={leftKey} label="Search" value={leftSearch} onSearch={setLeftSearch} />
467 <div className={classes.dataWrapper}>
470 <AutoSizer defaultWidth={0}>
471 {({ height, width }) => {
472 const filtered = leftData.filter(({ name }) => name.indexOf(leftSearch) > -1);
474 return !!filtered.length ? <FixedSizeList
476 itemCount={filtered.length}
481 ({ index, style }) => {
482 const { id, type, name } = filtered[index];
489 data-parent-path={name}
490 className={classNames(classes.row, getActiveClass(name))}
492 {getItemIcon(type, getActiveClass(name))}
493 <div className={classes.rowName}>
497 getActiveClass(name) ? <SidePanelRightArrowIcon
498 style={{ display: 'inline', marginTop: '5px', marginLeft: '5px' }} /> : null
503 </FixedSizeList> : <div className={classes.rowEmpty}>No directories available</div>
505 </AutoSizer> : <div className={classes.row}><CircularProgress className={classes.loader} size={30} /></div>
510 <div className={classes.rightPanel}>
511 <div className={classes.searchWrapper}>
512 <SearchInput selfClearProp={rightKey} label="Search" value={rightSearch} onSearch={setRightSearch} />
517 className={classes.uploadButton}
518 data-cy='upload-button'
520 if (!collectionAutofetchEnabled) {
521 setCollectionAutofetchEnabled(true);
528 <DownloadIcon className={classes.uploadIcon} />
532 <div className={classes.dataWrapper}>
534 rightData && !isLoading ?
535 <AutoSizer defaultHeight={500}>
536 {({ height, width }) => {
537 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
539 return !!filtered.length ? <FixedSizeList
541 itemCount={filtered.length}
546 ({ index, style }) => {
547 const { id, type, name, size } = filtered[index];
554 data-subfolder-path={name}
555 className={classes.row} key={id}>
558 className={classes.rowSelection}
559 checked={collectionPanelFiles[id] ? collectionPanelFiles[id].value.selected : false}
561 {getItemIcon(type, null)} <div className={classes.rowName}>
564 <span className={classes.rowName} style={{ marginLeft: 'auto', marginRight: '1rem' }}>
565 {formatFileSize(size)}
570 </FixedSizeList> : <div className={classes.rowEmpty}>This collection is empty</div>
572 </AutoSizer> : <div className={classes.row}><CircularProgress className={classes.loader} size={30} /></div>