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 {
46 onUploadDataClick: (targetLocation?: string) => void;
47 onSearchChange: (searchValue: string) => void;
48 onItemMenuOpen: (event: React.MouseEvent<HTMLElement>, item: TreeItem<FileTreeData>, isWritable: boolean) => void;
49 onOptionsMenuOpen: (event: React.MouseEvent<HTMLElement>, isWritable: boolean) => void;
50 onSelectionToggle: (event: React.MouseEvent<HTMLElement>, item: TreeItem<FileTreeData>) => void;
51 onCollapseToggle: (id: string, status: TreeItemStatus) => void;
52 onFileClick: (id: string) => void;
55 collectionPanelFiles: any;
59 type CssRules = "backButton"
61 | "pathPanelPathWrapper"
81 | "searchWrapperHidden";
83 const styles: StyleRulesCallback<CssRules> = (theme: Theme) => ({
87 color: 'rgba(0, 0, 0, 0.87)',
89 fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
92 letterSpacing: '0.01071em'
108 marginBottom: '0.5rem',
111 backgroundColor: 'rgba(0, 0, 0, 0.08)',
128 display: 'inline-flex',
129 flexDirection: 'column',
130 justifyContent: 'center'
133 display: 'inline-block',
134 marginBottom: '1rem',
137 searchWrapperHidden: {
144 color: `${theme.palette.primary.main} !important`,
147 display: 'inline-flex',
148 flexDirection: 'column',
149 justifyContent: 'center'
157 marginBottom: '1rem',
158 backgroundColor: '#fff',
159 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%)',
161 pathPanelPathWrapper: {
162 display: 'inline-block',
168 whiteSpace: 'nowrap',
169 position: 'relative',
170 backgroundColor: '#fff',
171 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%)',
176 animation: `animateVisible 1000ms ${theme.transitions.easing.easeOut}`
184 "@keyframes animateVisible": {
199 position: 'relative',
200 backgroundColor: '#fff',
201 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%)',
207 transform: 'rotate(180deg)'
214 const pathPromise = {};
217 function difference(object, base) {
218 function changes(object, base) {
219 return _.transform(object, function(result, value, key) {
220 if (!_.isEqual(value, base[key])) {
221 result[key] = (_.isObject(value) && _.isObject(base[key])) ? changes(value, base[key]) : value;
225 return changes(object, base);
227 export const CollectionPanelFiles = withStyles(styles)(connect((state: RootState) => ({
229 collectionPanel: state.collectionPanel,
230 collectionPanelFiles: state.collectionPanelFiles,
231 }))((props: CollectionPanelFilesProps & WithStyles<CssRules> & { auth: AuthState }) => {
232 const diff = difference(props, prevState);
234 console.log('---> render CollectionPanelFiles <------', diff);
235 const { classes, onItemMenuOpen, onUploadDataClick, isWritable, dispatch, collectionPanelFiles, collectionPanel } = props;
236 const { apiToken, config } = props.auth;
238 const webdavClient = new WebDAV();
239 webdavClient.defaults.baseURL = config.keepWebServiceUrl;
240 webdavClient.defaults.headers = {
241 Authorization: `Bearer ${apiToken}`
244 const webDAVRequestConfig: WebDAVRequestConfig = {
250 const parentRef = React.useRef(null);
251 const [path, setPath]: any = React.useState([]);
252 const [pathData, setPathData]: any = React.useState({});
253 const [isLoading, setIsLoading] = React.useState(false);
254 const [leftSearch, setLeftSearch] = React.useState('');
255 const [rightSearch, setRightSearch] = React.useState('');
257 const leftKey = (path.length > 1 ? path.slice(0, path.length - 1) : path).join('/');
258 const rightKey = path.join('/');
260 const leftData = pathData[leftKey] || [];
261 const rightData = pathData[rightKey];
263 React.useEffect(() => {
264 if (props.currentItemUuid) {
265 console.log(' --> useEffect current UUID: ', props.currentItemUuid);
267 setPath([props.currentItemUuid]);
269 }, [props.currentItemUuid]);
271 const fetchData = (keys, ignoreCache = false) => {
272 console.log('---> fetchData', keys);
273 const keyArray = Array.isArray(keys) ? keys : [keys];
275 Promise.all(keyArray.filter(key => !!key)
277 const dataExists = !!pathData[key];
278 const runningRequest = pathPromise[key];
280 if ((!dataExists || ignoreCache) && (!runningRequest || ignoreCache)) {
285 pathPromise[key] = true;
287 console.log('>>> fetching data for key', key);
288 return webdavClient.propfind(`c=${key}`, webDAVRequestConfig);
291 return Promise.resolve(null);
293 .filter((promise) => !!promise)
295 .then((requests) => {
296 const newState = requests.map((request, index) => {
297 if (request && request.responseXML != null) {
298 console.log(">>> got data for key", keyArray[index]);
299 const key = keyArray[index];
300 const result: any = extractFilesData(request.responseXML);
301 const sortedResult = sortBy(result, (n) => n.name).sort((n1, n2) => {
302 if (n1.type === 'directory' && n2.type !== 'directory') {
305 if (n1.type !== 'directory' && n2.type === 'directory') {
311 return { [key]: sortedResult };
314 }).reduce((prev, next) => {
315 return { ...next, ...prev };
318 setPathData({ ...pathData, ...newState });
322 keyArray.forEach(key => delete pathPromise[key]);
326 React.useEffect(() => {
328 console.log('---> useEffect rightKey:', rightKey);
333 }, [rightKey]); // eslint-disable-line react-hooks/exhaustive-deps
335 const currentPDH = (collectionPanel.item || {}).portableDataHash;
336 React.useEffect(() => {
338 console.log('---> useEffect PDH change:', currentPDH);
339 // Avoid fetching the same content level twice
340 if (leftKey !== rightKey) {
341 fetchData([leftKey, rightKey], true);
343 fetchData(rightKey, true);
346 }, [currentPDH]); // eslint-disable-line react-hooks/exhaustive-deps
348 React.useEffect(() => {
350 console.log('---> useEffect rightData:', rightData, 'search:', rightSearch);
351 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
352 setCollectionFiles(filtered, false)(dispatch);
354 }, [rightData, dispatch, rightSearch]);
356 const handleRightClick = React.useCallback(
358 event.preventDefault();
359 let elem = event.target;
361 while (elem && elem.dataset && !elem.dataset.item) {
362 elem = elem.parentNode;
365 if (!elem || !elem.dataset) {
369 const { id } = elem.dataset;
373 data: rightData.find((elem) => elem.id === id),
377 onItemMenuOpen(event, item, isWritable);
380 [onItemMenuOpen, isWritable, rightData] // eslint-disable-line react-hooks/exhaustive-deps
383 React.useEffect(() => {
386 if (parentRef && parentRef.current) {
387 console.log('---> useEffect parentRef:', parentRef);
388 node = parentRef.current;
389 (node as any).addEventListener('contextmenu', handleRightClick);
394 (node as any).removeEventListener('contextmenu', handleRightClick);
397 }, [parentRef, handleRightClick]);
399 const handleClick = React.useCallback(
401 let isCheckbox = false;
402 let elem = event.target;
404 if (elem.type === 'checkbox') {
408 while (elem && elem.dataset && !elem.dataset.item) {
409 elem = elem.parentNode;
412 if (elem && elem.dataset && !isCheckbox) {
413 const { parentPath, subfolderPath, breadcrumbPath, type } = elem.dataset;
415 if (breadcrumbPath) {
416 const index = path.indexOf(breadcrumbPath);
417 setPath([...path.slice(0, index + 1)]);
420 if (parentPath && type === 'directory') {
421 if (path.length > 1) {
425 setPath([...path, parentPath]);
428 if (subfolderPath && type === 'directory') {
429 setPath([...path, subfolderPath]);
432 if (elem.dataset.id && type === 'file') {
433 const item = rightData.find(({id}) => id === elem.dataset.id) || leftData.find(({ id }) => id === elem.dataset.id);
434 const enhancedItem = servicesProvider.getServices().collectionService.extendFileURL(item);
435 const fileUrl = sanitizeToken(getInlineFileUrl(enhancedItem.url, config.keepWebServiceUrl, config.keepWebInlineServiceUrl), true);
436 window.open(fileUrl, '_blank');
441 const { id } = elem.dataset;
442 const item = collectionPanelFiles[id];
443 props.onSelectionToggle(event, item);
446 [path, setPath, collectionPanelFiles] // eslint-disable-line react-hooks/exhaustive-deps
449 const getItemIcon = React.useCallback(
450 (type: string, activeClass: string | null) => {
451 let Icon = DefaultIcon;
455 Icon = DirectoryIcon;
463 <ListItemIcon className={classNames(classes.listItemIcon, activeClass)}>
471 const getActiveClass = React.useCallback(
473 return path[path.length - 1] === name ? classes.rowActive : null;
478 const onOptionsMenuOpen = React.useCallback(
479 (ev, isWritable) => {
480 props.onOptionsMenuOpen(ev, isWritable);
482 [props.onOptionsMenuOpen] // eslint-disable-line react-hooks/exhaustive-deps
485 return <div data-cy="collection-files-panel" onClick={handleClick} ref={parentRef}>
486 <div className={classes.pathPanel}>
487 <div className={classes.pathPanelPathWrapper}>
488 { path.map( (p: string, index: number) =>
489 <span key={`${index}-${p}`} data-item="true"
490 className={classes.pathPanelItem} data-breadcrumb-path={p}>
491 <span className={classes.rowActive}>{index === 0 ? 'Home' : p}</span> <b>/</b>
495 <Tooltip className={classes.pathPanelMenu} title="More options" disableFocusListener>
496 <IconButton data-cy='collection-files-panel-options-btn'
498 onOptionsMenuOpen(ev, isWritable);
500 <CustomizeTableIcon />
504 <div className={classes.wrapper}>
505 <div className={classNames(classes.leftPanel, path.length > 1 ? classes.leftPanelVisible : classes.leftPanelHidden)} data-cy="collection-files-left-panel">
506 <Tooltip title="Go back" className={path.length > 1 ? classes.backButton : classes.backButtonHidden}>
507 <IconButton onClick={() => setPath([...path.slice(0, path.length -1)])}>
511 <div className={path.length > 1 ? classes.searchWrapper : classes.searchWrapperHidden}>
512 <SearchInput selfClearProp={leftKey} label="Search" value={leftSearch} onSearch={setLeftSearch} />
514 <div className={classes.dataWrapper}>{ leftData
515 ? <AutoSizer defaultWidth={0}>{({ height, width }) => {
516 const filtered = leftData.filter(({ name }) => name.indexOf(leftSearch) > -1);
517 return !!filtered.length
518 ? <FixedSizeList height={height} itemCount={filtered.length}
519 itemSize={35} width={width}>{ ({ index, style }) => {
520 console.log("Left Data ROW: ", filtered[index]);
521 const { id, type, name } = filtered[index];
522 return <div data-id={id} style={style} data-item="true"
523 data-type={type} data-parent-path={name}
524 className={classNames(classes.row, getActiveClass(name))}
526 { getItemIcon(type, getActiveClass(name)) }
527 <div className={classes.rowName}>
530 { getActiveClass(name)
531 ? <SidePanelRightArrowIcon
532 style={{ display: 'inline', marginTop: '5px', marginLeft: '5px' }} />
537 : <div className={classes.rowEmpty}>No directories available</div>
540 : <div className={classes.row}><CircularProgress className={classes.loader} size={30} /></div> }
543 <div className={classes.rightPanel}>
544 <div className={classes.searchWrapper}>
545 <SearchInput selfClearProp={rightKey} label="Search" value={rightSearch} onSearch={setRightSearch} />
548 <Button className={classes.uploadButton} data-cy='upload-button'
550 onUploadDataClick(rightKey === leftKey ? undefined : rightKey);
552 variant='contained' color='primary' size='small'>
553 <DownloadIcon className={classes.uploadIcon} />
556 <div className={classes.dataWrapper}>{ rightData && !isLoading
557 ? <AutoSizer defaultHeight={500}>{({ height, width }) => {
558 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
559 console.log("Right Data: ", filtered);
560 return !!filtered.length
561 ? <FixedSizeList height={height} itemCount={filtered.length}
562 itemSize={35} width={width}>{ ({ index, style }) => {
563 console.log("Right Data ROW: ", filtered[index]);
564 const { id, type, name, size } = filtered[index];
566 return <div style={style} data-id={id} data-item="true"
567 data-type={type} data-subfolder-path={name}
568 className={classes.row} key={id}>
569 <Checkbox color="primary"
570 className={classes.rowSelection}
571 checked={collectionPanelFiles[id] ? collectionPanelFiles[id].value.selected : false}
573 {getItemIcon(type, null)}
574 <div className={classes.rowName}>
577 <span className={classes.rowName} style={{
578 marginLeft: 'auto', marginRight: '1rem' }}>
579 { formatFileSize(size) }
583 : <div className={classes.rowEmpty}>This collection is empty</div>
585 : <div className={classes.row}>
586 <CircularProgress className={classes.loader} size={30} />