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';
25 import _ from 'lodash';
27 export interface CollectionPanelFilesProps {
30 onUploadDataClick: (targetLocation?: string) => void;
31 onSearchChange: (searchValue: string) => void;
32 onItemMenuOpen: (event: React.MouseEvent<HTMLElement>, item: TreeItem<FileTreeData>, isWritable: boolean) => void;
33 onOptionsMenuOpen: (event: React.MouseEvent<HTMLElement>, isWritable: boolean) => void;
34 onSelectionToggle: (event: React.MouseEvent<HTMLElement>, item: TreeItem<FileTreeData>) => void;
35 onCollapseToggle: (id: string, status: TreeItemStatus) => void;
36 onFileClick: (id: string) => void;
39 collectionPanelFiles: any;
43 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";
45 const styles: StyleRulesCallback<CssRules> = (theme: Theme) => ({
49 color: 'rgba(0, 0, 0, 0.87)',
51 fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
54 letterSpacing: '0.01071em'
70 marginBottom: '0.5rem',
73 backgroundColor: 'rgba(0, 0, 0, 0.08)',
90 display: 'inline-flex',
91 flexDirection: 'column',
92 justifyContent: 'center'
95 display: 'inline-block',
99 searchWrapperHidden: {
106 color: `${theme.palette.primary.main} !important`,
109 display: 'inline-flex',
110 flexDirection: 'column',
111 justifyContent: 'center'
119 marginBottom: '1rem',
120 backgroundColor: '#fff',
121 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%)',
123 pathPanelPathWrapper: {
124 display: 'inline-block',
130 whiteSpace: 'nowrap',
131 position: 'relative',
132 backgroundColor: '#fff',
133 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%)',
138 animation: `animateVisible 1000ms ${theme.transitions.easing.easeOut}`
146 "@keyframes animateVisible": {
161 position: 'relative',
162 backgroundColor: '#fff',
163 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%)',
169 transform: 'rotate(180deg)'
176 const pathPromise = {};
179 function difference(object, base) {
180 function changes(object, base) {
181 return _.transform(object, function(result, value, key) {
182 if (!_.isEqual(value, base[key])) {
183 result[key] = (_.isObject(value) && _.isObject(base[key])) ? changes(value, base[key]) : value;
187 return changes(object, base);
189 export const CollectionPanelFiles = withStyles(styles)(connect((state: RootState) => ({
191 collectionPanel: state.collectionPanel,
192 collectionPanelFiles: state.collectionPanelFiles,
193 }))((props: CollectionPanelFilesProps & WithStyles<CssRules> & { auth: AuthState }) => {
194 const diff = difference(props, prevState);
196 console.log('---> render CollectionPanel <------', diff);
197 const { classes, onItemMenuOpen, onUploadDataClick, isWritable, dispatch, collectionPanelFiles, collectionPanel } = props;
198 const { apiToken, config } = props.auth;
200 const webdavClient = new WebDAV();
201 webdavClient.defaults.baseURL = config.keepWebServiceUrl;
202 webdavClient.defaults.headers = {
203 Authorization: `Bearer ${apiToken}`
206 const webDAVRequestConfig: WebDAVRequestConfig = {
212 const parentRef = React.useRef(null);
213 const [path, setPath]: any = React.useState([]);
214 const [pathData, setPathData]: any = React.useState({});
215 const [isLoading, setIsLoading] = React.useState(false);
216 const [leftSearch, setLeftSearch] = React.useState('');
217 const [rightSearch, setRightSearch] = React.useState('');
219 const leftKey = (path.length > 1 ? path.slice(0, path.length - 1) : path).join('/');
220 const rightKey = path.join('/');
222 const leftData = pathData[leftKey] || [];
223 const rightData = pathData[rightKey];
225 React.useEffect(() => {
226 if (props.currentItemUuid) {
227 console.log(' --> useEffect current UUID: ', props.currentItemUuid);
229 setPath([props.currentItemUuid]);
231 }, [props.currentItemUuid]);
233 const fetchData = (keys, ignoreCache = false) => {
234 console.log('---> fetchData', keys);
235 const keyArray = Array.isArray(keys) ? keys : [keys];
237 Promise.all(keyArray.filter(key => !!key)
239 const dataExists = !!pathData[key];
240 const runningRequest = pathPromise[key];
242 if ((!dataExists || ignoreCache) && (!runningRequest || ignoreCache)) {
247 pathPromise[key] = true;
249 console.log('>>> fetching data for key', key);
250 return webdavClient.propfind(`c=${key}`, webDAVRequestConfig);
253 return Promise.resolve(null);
255 .filter((promise) => !!promise)
257 .then((requests) => {
258 const newState = requests.map((request, index) => {
259 if (request && request.responseXML != null) {
260 console.log(">>> got data for key", keyArray[index]);
261 const key = keyArray[index];
262 const result: any = extractFilesData(request.responseXML);
263 const sortedResult = sortBy(result, (n) => n.name).sort((n1, n2) => {
264 if (n1.type === 'directory' && n2.type !== 'directory') {
267 if (n1.type !== 'directory' && n2.type === 'directory') {
273 return { [key]: sortedResult };
276 }).reduce((prev, next) => {
277 return { ...next, ...prev };
280 setPathData({ ...pathData, ...newState });
284 keyArray.forEach(key => delete pathPromise[key]);
288 React.useEffect(() => {
290 console.log('---> useEffect rightKey:', rightKey);
295 }, [rightKey]); // eslint-disable-line react-hooks/exhaustive-deps
297 const currentPDH = (collectionPanel.item || {}).portableDataHash;
298 React.useEffect(() => {
300 console.log('---> useEffect PDH change:', currentPDH);
301 // Avoid fetching the same content level twice
302 if (leftKey !== rightKey) {
303 fetchData([leftKey, rightKey], true);
305 fetchData(rightKey, true);
308 }, [currentPDH]); // eslint-disable-line react-hooks/exhaustive-deps
310 React.useEffect(() => {
312 console.log('---> useEffect rightData:', rightData, 'search:', rightSearch);
313 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
314 setCollectionFiles(filtered, false)(dispatch);
316 }, [rightData, dispatch, rightSearch]);
318 const handleRightClick = React.useCallback(
320 event.preventDefault();
321 let elem = event.target;
323 while (elem && elem.dataset && !elem.dataset.item) {
324 elem = elem.parentNode;
327 if (!elem || !elem.dataset) {
331 const { id } = elem.dataset;
335 data: rightData.find((elem) => elem.id === id),
339 onItemMenuOpen(event, item, isWritable);
342 [onItemMenuOpen, isWritable, rightData] // eslint-disable-line react-hooks/exhaustive-deps
345 React.useEffect(() => {
348 if (parentRef && parentRef.current) {
349 console.log('---> useEffect parentRef:', parentRef);
350 node = parentRef.current;
351 (node as any).addEventListener('contextmenu', handleRightClick);
356 (node as any).removeEventListener('contextmenu', handleRightClick);
359 }, [parentRef, handleRightClick]);
361 const handleClick = React.useCallback(
363 let isCheckbox = false;
364 let elem = event.target;
366 if (elem.type === 'checkbox') {
370 while (elem && elem.dataset && !elem.dataset.item) {
371 elem = elem.parentNode;
374 if (elem && elem.dataset && !isCheckbox) {
375 const { parentPath, subfolderPath, breadcrumbPath, type } = elem.dataset;
377 if (breadcrumbPath) {
378 const index = path.indexOf(breadcrumbPath);
379 setPath([...path.slice(0, index + 1)]);
382 if (parentPath && type === 'directory') {
383 if (path.length > 1) {
387 setPath([...path, parentPath]);
390 if (subfolderPath && type === 'directory') {
391 setPath([...path, subfolderPath]);
394 if (elem.dataset.id && type === 'file') {
395 const item = rightData.find(({id}) => id === elem.dataset.id) || leftData.find(({ id }) => id === elem.dataset.id);
396 const enhancedItem = servicesProvider.getServices().collectionService.extendFileURL(item);
397 const fileUrl = sanitizeToken(getInlineFileUrl(enhancedItem.url, config.keepWebServiceUrl, config.keepWebInlineServiceUrl), true);
398 window.open(fileUrl, '_blank');
403 const { id } = elem.dataset;
404 const item = collectionPanelFiles[id];
405 props.onSelectionToggle(event, item);
408 [path, setPath, collectionPanelFiles] // eslint-disable-line react-hooks/exhaustive-deps
411 const getItemIcon = React.useCallback(
412 (type: string, activeClass: string | null) => {
413 let Icon = DefaultIcon;
417 Icon = DirectoryIcon;
425 <ListItemIcon className={classNames(classes.listItemIcon, activeClass)}>
433 const getActiveClass = React.useCallback(
435 return path[path.length - 1] === name ? classes.rowActive : null;
440 const onOptionsMenuOpen = React.useCallback(
441 (ev, isWritable) => {
442 props.onOptionsMenuOpen(ev, isWritable);
444 [props.onOptionsMenuOpen] // eslint-disable-line react-hooks/exhaustive-deps
447 return <div data-cy="collection-files-panel" onClick={handleClick} ref={parentRef}>
448 <div className={classes.pathPanel}>
449 <div className={classes.pathPanelPathWrapper}>
450 { path.map((p: string, index: number) => <span
451 key={`${index}-${p}`}
453 className={classes.pathPanelItem}
454 data-breadcrumb-path={p}
456 <span className={classes.rowActive}>{index === 0 ? 'Home' : p}</span> <b>/</b>
459 <Tooltip className={classes.pathPanelMenu} title="More options" disableFocusListener>
461 data-cy='collection-files-panel-options-btn'
463 onOptionsMenuOpen(ev, isWritable);
465 <CustomizeTableIcon />
469 <div className={classes.wrapper}>
470 <div className={classNames(classes.leftPanel, path.length > 1 ? classes.leftPanelVisible : classes.leftPanelHidden)} data-cy="collection-files-left-panel">
471 <Tooltip title="Go back" className={path.length > 1 ? classes.backButton : classes.backButtonHidden}>
472 <IconButton onClick={() => setPath([...path.slice(0, path.length -1)])}>
477 <div className={classes.wrapper}>
478 <div className={classNames(classes.leftPanel, path.length > 1 ? classes.leftPanelVisible : classes.leftPanelHidden)} data-cy="collection-files-left-panel">
479 <Tooltip title="Go back" className={path.length > 1 ? classes.backButton : classes.backButtonHidden}>
480 <IconButton onClick={() => setPath([...path.slice(0, path.length -1)])}>
484 <div className={path.length > 1 ? classes.searchWrapper : classes.searchWrapperHidden}>
485 <SearchInput selfClearProp={leftKey} label="Search" value={leftSearch} onSearch={setLeftSearch} />
487 <div className={classes.dataWrapper}>
490 <AutoSizer defaultWidth={0}>
491 {({ height, width }) => {
492 const filtered = leftData.filter(({ name }) => name.indexOf(leftSearch) > -1);
494 return !!filtered.length ? <FixedSizeList
496 itemCount={filtered.length}
501 ({ index, style }) => {
502 const { id, type, name } = filtered[index];
509 data-parent-path={name}
510 className={classNames(classes.row, getActiveClass(name))}
512 {getItemIcon(type, getActiveClass(name))}
513 <div className={classes.rowName}>
517 getActiveClass(name) ? <SidePanelRightArrowIcon
518 style={{ display: 'inline', marginTop: '5px', marginLeft: '5px' }} /> : null
523 </FixedSizeList> : <div className={classes.rowEmpty}>No directories available</div>
525 </AutoSizer> : <div className={classes.row}><CircularProgress className={classes.loader} size={30} /></div>
530 <div className={classes.rightPanel} data-cy="collection-files-right-panel">
531 <div className={classes.searchWrapper}>
532 <SearchInput selfClearProp={rightKey} label="Search" value={rightSearch} onSearch={setRightSearch} />
537 className={classes.uploadButton}
538 data-cy='upload-button'
540 onUploadDataClick(rightKey === leftKey ? undefined : rightKey);
545 <DownloadIcon className={classes.uploadIcon} />
549 <div className={classes.dataWrapper}>
551 rightData && !isLoading ?
552 <AutoSizer defaultHeight={500}>
553 {({ height, width }) => {
554 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
556 return !!filtered.length
557 ? <FixedSizeList height={height} itemCount={filtered.length}
558 itemSize={35} width={width}>{ ({ index, style }) => {
559 console.log("Left Data ROW: ", filtered[index]);
560 const { id, type, name } = filtered[index];
562 return <div data-id={id} style={style} data-item="true"
563 data-type={type} data-parent-path={name} key={id}
564 className={classNames(classes.row, getActiveClass(name))}>
565 { getItemIcon(type, getActiveClass(name)) }
566 <div className={classes.rowName}>
569 { getActiveClass(name)
570 ? <SidePanelRightArrowIcon style={{
573 marginLeft: '5px' }} />
577 : <div className={classes.rowEmpty}>No directories available</div>
579 : <div className={classes.row}>
580 <CircularProgress className={classes.loader} size={30} />
584 <div className={classes.rightPanel}>
585 <div className={classes.searchWrapper}>
586 <SearchInput selfClearProp={rightKey} label="Search" value={rightSearch} onSearch={setRightSearch} />
589 <Button className={classes.uploadButton} data-cy='upload-button'
593 variant='contained' color='primary' size='small'>
594 <DownloadIcon className={classes.uploadIcon} />
597 <div className={classes.dataWrapper}>{ rightData && !isLoading
598 ? <AutoSizer defaultHeight={500}>{({ height, width }) => {
599 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
600 console.log("Right Data: ", filtered);
602 return !!filtered.length
603 ? <FixedSizeList height={height} itemCount={filtered.length}
604 itemSize={35} width={width}>{ ({ index, style }) => {
605 console.log("Right Data ROW: ", filtered[index]);
606 const { id, type, name, size } = filtered[index];
608 return <div style={style} data-id={id} data-item="true"
609 data-type={type} data-subfolder-path={name}
610 className={classes.row} key={id}>
611 <Checkbox color="primary"
612 className={classes.rowSelection}
613 checked={collectionPanelFiles[id] ? collectionPanelFiles[id].value.selected : false}
615 {getItemIcon(type, null)}
616 <div className={classes.rowName}>
619 <span className={classes.rowName} style={{
620 marginLeft: 'auto', marginRight: '1rem' }}>
621 { formatFileSize(size) }
625 : <div className={classes.rowEmpty}>This collection is empty</div>
627 : <div className={classes.row}>
628 <CircularProgress className={classes.loader} size={30} />