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 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;
37 loadFilesFunc: () => void;
40 collectionPanelFiles: any;
44 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";
46 const styles: StyleRulesCallback<CssRules> = (theme: Theme) => ({
50 color: 'rgba(0, 0, 0, 0.87)',
52 fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
55 letterSpacing: '0.01071em'
71 marginBottom: '0.5rem',
74 backgroundColor: 'rgba(0, 0, 0, 0.08)',
91 display: 'inline-flex',
92 flexDirection: 'column',
93 justifyContent: 'center'
96 display: 'inline-block',
100 searchWrapperHidden: {
107 color: `${theme.palette.primary.main} !important`,
110 display: 'inline-flex',
111 flexDirection: 'column',
112 justifyContent: 'center'
120 marginBottom: '1rem',
121 backgroundColor: '#fff',
122 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%)',
124 pathPanelPathWrapper: {
125 display: 'inline-block',
131 whiteSpace: 'nowrap',
132 position: 'relative',
133 backgroundColor: '#fff',
134 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%)',
139 animation: `animateVisible 1000ms ${theme.transitions.easing.easeOut}`
147 "@keyframes animateVisible": {
162 position: 'relative',
163 backgroundColor: '#fff',
164 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%)',
170 transform: 'rotate(180deg)'
177 const pathPromise = {};
179 export const CollectionPanelFiles = withStyles(styles)(connect((state: RootState) => ({
181 collectionPanel: state.collectionPanel,
182 collectionPanelFiles: state.collectionPanelFiles,
183 }))((props: CollectionPanelFilesProps & WithStyles<CssRules> & { auth: AuthState }) => {
184 const { classes, onItemMenuOpen, onUploadDataClick, isWritable, dispatch, collectionPanelFiles, collectionPanel } = props;
185 const { apiToken, config } = props.auth;
187 const webdavClient = new WebDAV();
188 webdavClient.defaults.baseURL = config.keepWebServiceUrl;
189 webdavClient.defaults.headers = {
190 Authorization: `Bearer ${apiToken}`
193 const webDAVRequestConfig: WebDAVRequestConfig = {
199 const parentRef = React.useRef(null);
200 const [path, setPath]: any = React.useState([]);
201 const [pathData, setPathData]: any = React.useState({});
202 const [isLoading, setIsLoading] = React.useState(false);
203 const [leftSearch, setLeftSearch] = React.useState('');
204 const [rightSearch, setRightSearch] = React.useState('');
206 const leftKey = (path.length > 1 ? path.slice(0, path.length - 1) : path).join('/');
207 const rightKey = path.join('/');
209 const leftData = pathData[leftKey] || [];
210 const rightData = pathData[rightKey];
212 React.useEffect(() => {
213 console.log(' --> useEffect current UUID: ', props.currentItemUuid);
214 if (props.currentItemUuid) {
216 setPath([props.currentItemUuid]);
218 }, [props.currentItemUuid]);
220 const fetchData = (keys, ignoreCache = false) => {
221 console.log('---> fetchData', keys);
222 const keyArray = Array.isArray(keys) ? keys : [keys];
224 Promise.all(keyArray.filter(key => !!key)
226 const dataExists = !!pathData[key];
227 const runningRequest = pathPromise[key];
229 if ((!dataExists || ignoreCache) && (!runningRequest || ignoreCache)) {
234 pathPromise[key] = true;
236 console.log('>>> fetching data for key', key);
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 console.log(">>> got data for key", keyArray[index]);
248 const key = keyArray[index];
249 const result: any = extractFilesData(request.responseXML);
250 const sortedResult = sortBy(result, (n) => n.name).sort((n1, n2) => {
251 if (n1.type === 'directory' && n2.type !== 'directory') {
254 if (n1.type !== 'directory' && n2.type === 'directory') {
260 return { [key]: sortedResult };
263 }).reduce((prev, next) => {
264 return { ...next, ...prev };
267 setPathData({ ...pathData, ...newState });
271 keyArray.forEach(key => delete pathPromise[key]);
275 React.useEffect(() => {
276 console.log('---> useEffect rightKey', rightKey);
282 }, [rightKey]); // eslint-disable-line react-hooks/exhaustive-deps
284 const currentPDH = (collectionPanel.item || {}).portableDataHash;
285 React.useEffect(() => {
286 console.log('---> useEffect PDH change:', currentPDH);
288 fetchData([leftKey, rightKey], true);
290 }, [currentPDH]); // eslint-disable-line react-hooks/exhaustive-deps
292 React.useEffect(() => {
293 console.log('---> useEffect rightData:', rightData, dispatch, rightSearch);
295 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
296 setCollectionFiles(filtered, false)(dispatch);
298 }, [rightData, dispatch, rightSearch]);
300 const handleRightClick = React.useCallback(
302 event.preventDefault();
303 let elem = event.target;
305 while (elem && elem.dataset && !elem.dataset.item) {
306 elem = elem.parentNode;
309 if (!elem || !elem.dataset) {
313 const { id } = elem.dataset;
317 data: rightData.find((elem) => elem.id === id),
321 onItemMenuOpen(event, item, isWritable);
324 [onItemMenuOpen, isWritable, rightData] // eslint-disable-line react-hooks/exhaustive-deps
327 React.useEffect(() => {
328 console.log('---> useEffect parentRef:', parentRef, handleRightClick);
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
429 console.log('---> render CollectionPanel <------');
430 return <div data-cy="collection-files-panel" onClick={handleClick} ref={parentRef}>
431 <div className={classes.pathPanel}>
432 <div className={classes.pathPanelPathWrapper}>
433 { path.map((p: string, index: number) => <span
434 key={`${index}-${p}`}
436 className={classes.pathPanelItem}
437 data-breadcrumb-path={p}
439 <span className={classes.rowActive}>{index === 0 ? 'Home' : p}</span> <b>/</b>
442 <Tooltip className={classes.pathPanelMenu} title="More options" disableFocusListener>
444 data-cy='collection-files-panel-options-btn'
446 onOptionsMenuOpen(ev, isWritable);
448 <CustomizeTableIcon />
452 <div className={classes.wrapper}>
453 <div className={classNames(classes.leftPanel, path.length > 1 ? classes.leftPanelVisible : classes.leftPanelHidden)} data-cy="collection-files-left-panel">
454 <Tooltip title="Go back" className={path.length > 1 ? classes.backButton : classes.backButtonHidden}>
455 <IconButton onClick={() => setPath([...path.slice(0, path.length -1)])}>
460 <div className={classes.wrapper}>
461 <div className={classNames(classes.leftPanel, path.length > 1 ? classes.leftPanelVisible : classes.leftPanelHidden)} data-cy="collection-files-left-panel">
462 <Tooltip title="Go back" className={path.length > 1 ? classes.backButton : classes.backButtonHidden}>
463 <IconButton onClick={() => setPath([...path.slice(0, path.length -1)])}>
467 <div className={path.length > 1 ? classes.searchWrapper : classes.searchWrapperHidden}>
468 <SearchInput selfClearProp={leftKey} label="Search" value={leftSearch} onSearch={setLeftSearch} />
470 <div className={classes.dataWrapper}>
473 <AutoSizer defaultWidth={0}>
474 {({ height, width }) => {
475 const filtered = leftData.filter(({ name }) => name.indexOf(leftSearch) > -1);
477 return !!filtered.length ? <FixedSizeList
479 itemCount={filtered.length}
484 ({ index, style }) => {
485 const { id, type, name } = filtered[index];
492 data-parent-path={name}
493 className={classNames(classes.row, getActiveClass(name))}
495 {getItemIcon(type, getActiveClass(name))}
496 <div className={classes.rowName}>
500 getActiveClass(name) ? <SidePanelRightArrowIcon
501 style={{ display: 'inline', marginTop: '5px', marginLeft: '5px' }} /> : null
506 </FixedSizeList> : <div className={classes.rowEmpty}>No directories available</div>
508 </AutoSizer> : <div className={classes.row}><CircularProgress className={classes.loader} size={30} /></div>
513 <div className={classes.rightPanel} data-cy="collection-files-right-panel">
514 <div className={classes.searchWrapper}>
515 <SearchInput selfClearProp={rightKey} label="Search" value={rightSearch} onSearch={setRightSearch} />
520 className={classes.uploadButton}
521 data-cy='upload-button'
523 onUploadDataClick(rightKey === leftKey ? undefined : rightKey);
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
540 ? <FixedSizeList height={height} itemCount={filtered.length}
541 itemSize={35} width={width}>{ ({ index, style }) => {
542 console.log("Left Data ROW: ", filtered[index]);
543 const { id, type, name } = filtered[index];
545 return <div data-id={id} style={style} data-item="true"
546 data-type={type} data-parent-path={name} key={id}
547 className={classNames(classes.row, getActiveClass(name))}>
548 { getItemIcon(type, getActiveClass(name)) }
549 <div className={classes.rowName}>
552 { getActiveClass(name)
553 ? <SidePanelRightArrowIcon style={{
556 marginLeft: '5px' }} />
560 : <div className={classes.rowEmpty}>No directories available</div>
562 : <div className={classes.row}>
563 <CircularProgress className={classes.loader} size={30} />
567 <div className={classes.rightPanel}>
568 <div className={classes.searchWrapper}>
569 <SearchInput selfClearProp={rightKey} label="Search" value={rightSearch} onSearch={setRightSearch} />
572 <Button className={classes.uploadButton} data-cy='upload-button'
576 variant='contained' color='primary' size='small'>
577 <DownloadIcon className={classes.uploadIcon} />
580 <div className={classes.dataWrapper}>{ rightData && !isLoading
581 ? <AutoSizer defaultHeight={500}>{({ height, width }) => {
582 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
583 console.log("Right Data: ", filtered);
585 return !!filtered.length
586 ? <FixedSizeList height={height} itemCount={filtered.length}
587 itemSize={35} width={width}>{ ({ index, style }) => {
588 console.log("Right Data ROW: ", filtered[index]);
589 const { id, type, name, size } = filtered[index];
591 return <div style={style} data-id={id} data-item="true"
592 data-type={type} data-subfolder-path={name}
593 className={classes.row} key={id}>
594 <Checkbox color="primary"
595 className={classes.rowSelection}
596 checked={collectionPanelFiles[id] ? collectionPanelFiles[id].value.selected : false}
598 {getItemIcon(type, null)}
599 <div className={classes.rowName}>
602 <span className={classes.rowName} style={{
603 marginLeft: 'auto', marginRight: '1rem' }}>
604 { formatFileSize(size) }
608 : <div className={classes.rowEmpty}>This collection is empty</div>
610 : <div className={classes.row}>
611 <CircularProgress className={classes.loader} size={30} />