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';
42 import _ from 'lodash';
44 export interface CollectionPanelFilesProps {
47 onUploadDataClick: (targetLocation?: string) => void;
48 onSearchChange: (searchValue: string) => void;
49 onItemMenuOpen: (event: React.MouseEvent<HTMLElement>, item: TreeItem<FileTreeData>, isWritable: boolean) => void;
50 onOptionsMenuOpen: (event: React.MouseEvent<HTMLElement>, isWritable: boolean) => void;
51 onSelectionToggle: (event: React.MouseEvent<HTMLElement>, item: TreeItem<FileTreeData>) => void;
52 onCollapseToggle: (id: string, status: TreeItemStatus) => void;
53 onFileClick: (id: string) => void;
56 collectionPanelFiles: any;
60 type CssRules = "backButton"
62 | "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)'
215 const pathPromise = {};
218 function difference(object, base) {
219 function changes(object, base) {
220 return _.transform(object, function(result, value, key) {
221 if (!_.isEqual(value, base[key])) {
222 result[key] = (_.isObject(value) && _.isObject(base[key])) ? changes(value, base[key]) : value;
226 return changes(object, base);
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 diff = difference(props, prevState);
235 console.log('---> render CollectionPanel <------', diff);
236 const { classes, onItemMenuOpen, onUploadDataClick, isWritable, dispatch, collectionPanelFiles, collectionPanel } = props;
237 const { apiToken, config } = props.auth;
239 const webdavClient = new WebDAV();
240 webdavClient.defaults.baseURL = config.keepWebServiceUrl;
241 webdavClient.defaults.headers = {
242 Authorization: `Bearer ${apiToken}`
245 const webDAVRequestConfig: WebDAVRequestConfig = {
251 const parentRef = React.useRef(null);
252 const [path, setPath]: any = React.useState([]);
253 const [pathData, setPathData]: any = React.useState({});
254 const [isLoading, setIsLoading] = React.useState(false);
255 const [leftSearch, setLeftSearch] = React.useState('');
256 const [rightSearch, setRightSearch] = React.useState('');
258 const leftKey = (path.length > 1 ? path.slice(0, path.length - 1) : path).join('/');
259 const rightKey = path.join('/');
261 const leftData = pathData[leftKey] || [];
262 const rightData = pathData[rightKey];
264 React.useEffect(() => {
265 if (props.currentItemUuid) {
266 console.log(' --> useEffect current UUID: ', props.currentItemUuid);
268 setPath([props.currentItemUuid]);
270 }, [props.currentItemUuid]);
272 const fetchData = (keys, ignoreCache = false) => {
273 console.log('---> fetchData', keys);
274 const keyArray = Array.isArray(keys) ? keys : [keys];
276 Promise.all(keyArray.filter(key => !!key)
278 const dataExists = !!pathData[key];
279 const runningRequest = pathPromise[key];
281 if ((!dataExists || ignoreCache) && (!runningRequest || ignoreCache)) {
286 pathPromise[key] = true;
288 console.log('>>> fetching data for key', key);
289 return webdavClient.propfind(`c=${key}`, webDAVRequestConfig);
292 return Promise.resolve(null);
294 .filter((promise) => !!promise)
296 .then((requests) => {
297 const newState = requests.map((request, index) => {
298 if (request && request.responseXML != null) {
299 console.log(">>> got data for key", keyArray[index]);
300 const key = keyArray[index];
301 const result: any = extractFilesData(request.responseXML);
302 const sortedResult = sortBy(result, (n) => n.name).sort((n1, n2) => {
303 if (n1.type === 'directory' && n2.type !== 'directory') {
306 if (n1.type !== 'directory' && n2.type === 'directory') {
312 return { [key]: sortedResult };
315 }).reduce((prev, next) => {
316 return { ...next, ...prev };
319 setPathData({ ...pathData, ...newState });
323 keyArray.forEach(key => delete pathPromise[key]);
327 React.useEffect(() => {
329 console.log('---> useEffect rightKey:', rightKey);
334 }, [rightKey]); // eslint-disable-line react-hooks/exhaustive-deps
336 const currentPDH = (collectionPanel.item || {}).portableDataHash;
337 React.useEffect(() => {
339 console.log('---> useEffect PDH change:', currentPDH);
340 // Avoid fetching the same content level twice
341 if (leftKey !== rightKey) {
342 fetchData([leftKey, rightKey], true);
344 fetchData(rightKey, true);
347 }, [currentPDH]); // eslint-disable-line react-hooks/exhaustive-deps
349 React.useEffect(() => {
351 console.log('---> useEffect rightData:', rightData, 'search:', rightSearch);
352 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
353 setCollectionFiles(filtered, false)(dispatch);
355 }, [rightData, dispatch, rightSearch]);
357 const handleRightClick = React.useCallback(
359 event.preventDefault();
360 let elem = event.target;
362 while (elem && elem.dataset && !elem.dataset.item) {
363 elem = elem.parentNode;
366 if (!elem || !elem.dataset) {
370 const { id } = elem.dataset;
374 data: rightData.find((elem) => elem.id === id),
378 onItemMenuOpen(event, item, isWritable);
381 [onItemMenuOpen, isWritable, rightData] // eslint-disable-line react-hooks/exhaustive-deps
384 React.useEffect(() => {
387 if (parentRef && parentRef.current) {
388 console.log('---> useEffect parentRef:', parentRef);
389 node = parentRef.current;
390 (node as any).addEventListener('contextmenu', handleRightClick);
395 (node as any).removeEventListener('contextmenu', handleRightClick);
398 }, [parentRef, handleRightClick]);
400 const handleClick = React.useCallback(
402 let isCheckbox = false;
403 let elem = event.target;
405 if (elem.type === 'checkbox') {
409 while (elem && elem.dataset && !elem.dataset.item) {
410 elem = elem.parentNode;
413 if (elem && elem.dataset && !isCheckbox) {
414 const { parentPath, subfolderPath, breadcrumbPath, type } = elem.dataset;
416 if (breadcrumbPath) {
417 const index = path.indexOf(breadcrumbPath);
418 setPath([...path.slice(0, index + 1)]);
421 if (parentPath && type === 'directory') {
422 if (path.length > 1) {
426 setPath([...path, parentPath]);
429 if (subfolderPath && type === 'directory') {
430 setPath([...path, subfolderPath]);
433 if (elem.dataset.id && type === 'file') {
434 const item = rightData.find(({id}) => id === elem.dataset.id) || leftData.find(({ id }) => id === elem.dataset.id);
435 const enhancedItem = servicesProvider.getServices().collectionService.extendFileURL(item);
436 const fileUrl = sanitizeToken(getInlineFileUrl(enhancedItem.url, config.keepWebServiceUrl, config.keepWebInlineServiceUrl), true);
437 window.open(fileUrl, '_blank');
442 const { id } = elem.dataset;
443 const item = collectionPanelFiles[id];
444 props.onSelectionToggle(event, item);
447 [path, setPath, collectionPanelFiles] // eslint-disable-line react-hooks/exhaustive-deps
450 const getItemIcon = React.useCallback(
451 (type: string, activeClass: string | null) => {
452 let Icon = DefaultIcon;
456 Icon = DirectoryIcon;
464 <ListItemIcon className={classNames(classes.listItemIcon, activeClass)}>
472 const getActiveClass = React.useCallback(
474 return path[path.length - 1] === name ? classes.rowActive : null;
479 const onOptionsMenuOpen = React.useCallback(
480 (ev, isWritable) => {
481 props.onOptionsMenuOpen(ev, isWritable);
483 [props.onOptionsMenuOpen] // eslint-disable-line react-hooks/exhaustive-deps
486 return <div data-cy="collection-files-panel" onClick={handleClick} ref={parentRef}>
487 <div className={classes.pathPanel}>
488 <div className={classes.pathPanelPathWrapper}>
489 { path.map( (p: string, index: number) =>
490 <span key={`${index}-${p}`} data-item="true"
491 className={classes.pathPanelItem} data-breadcrumb-path={p}>
492 <span className={classes.rowActive}>{index === 0 ? 'Home' : p}</span> <b>/</b>
496 <Tooltip className={classes.pathPanelMenu} title="More options" disableFocusListener>
497 <IconButton data-cy='collection-files-panel-options-btn'
499 onOptionsMenuOpen(ev, isWritable);
501 <CustomizeTableIcon />
505 <div className={classes.wrapper}>
506 <div className={classNames(classes.leftPanel, path.length > 1 ? classes.leftPanelVisible : classes.leftPanelHidden)} data-cy="collection-files-left-panel">
507 <Tooltip title="Go back" className={path.length > 1 ? classes.backButton : classes.backButtonHidden}>
508 <IconButton onClick={() => setPath([...path.slice(0, path.length -1)])}>
512 <div className={path.length > 1 ? classes.searchWrapper : classes.searchWrapperHidden}>
513 <SearchInput selfClearProp={leftKey} label="Search" value={leftSearch} onSearch={setLeftSearch} />
515 <div className={classes.dataWrapper}>{ leftData
516 ? <AutoSizer defaultWidth={0}>{({ height, width }) => {
517 const filtered = leftData.filter(({ name }) => name.indexOf(leftSearch) > -1);
518 return !!filtered.length
519 ? <FixedSizeList height={height} itemCount={filtered.length}
520 itemSize={35} width={width}>{ ({ index, style }) => {
521 console.log("Left Data ROW: ", filtered[index]);
522 const { id, type, name } = filtered[index];
523 return <div data-id={id} style={style} data-item="true"
524 data-type={type} data-parent-path={name}
525 className={classNames(classes.row, getActiveClass(name))}
527 { getItemIcon(type, getActiveClass(name)) }
528 <div className={classes.rowName}>
531 { getActiveClass(name)
532 ? <SidePanelRightArrowIcon
533 style={{ display: 'inline', marginTop: '5px', marginLeft: '5px' }} />
538 : <div className={classes.rowEmpty}>No directories available</div>
541 : <div className={classes.row}><CircularProgress className={classes.loader} size={30} /></div> }
544 <div className={classes.rightPanel}>
545 <div className={classes.searchWrapper}>
546 <SearchInput selfClearProp={rightKey} label="Search" value={rightSearch} onSearch={setRightSearch} />
549 <Button className={classes.uploadButton} data-cy='upload-button'
551 onUploadDataClick(rightKey === leftKey ? undefined : rightKey);
553 variant='contained' color='primary' size='small'>
554 <DownloadIcon className={classes.uploadIcon} />
557 <div className={classes.dataWrapper}>{ rightData && !isLoading
558 ? <AutoSizer defaultHeight={500}>{({ height, width }) => {
559 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
560 console.log("Right Data: ", filtered);
561 return !!filtered.length
562 ? <FixedSizeList height={height} itemCount={filtered.length}
563 itemSize={35} width={width}>{ ({ index, style }) => {
564 console.log("Right Data ROW: ", filtered[index]);
565 const { id, type, name, size } = filtered[index];
567 return <div style={style} data-id={id} data-item="true"
568 data-type={type} data-subfolder-path={name}
569 className={classes.row} key={id}>
570 <Checkbox color="primary"
571 className={classes.rowSelection}
572 checked={collectionPanelFiles[id] ? collectionPanelFiles[id].value.selected : false}
574 {getItemIcon(type, null)}
575 <div className={classes.rowName}>
578 <span className={classes.rowName} style={{
579 marginLeft: 'auto', marginRight: '1rem' }}>
580 { formatFileSize(size) }
584 : <div className={classes.rowEmpty}>This collection is empty</div>
586 : <div className={classes.row}>
587 <CircularProgress className={classes.loader} size={30} />