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 { CustomizeTableIcon } from 'components/icon/icon';
11 import { SearchInput } from 'components/search-input/search-input';
12 import { ListItemIcon, StyleRulesCallback, Theme, WithStyles, withStyles, Tooltip, IconButton, Checkbox, CircularProgress } from '@material-ui/core';
13 import { FileTreeData } from '../file-tree/file-tree-data';
14 import { TreeItem, TreeItemStatus } from '../tree/tree';
15 import { RootState } from 'store/store';
16 import { WebDAV, WebDAVRequestConfig } from 'common/webdav';
17 import { AuthState } from 'store/auth/auth-reducer';
18 import { extractFilesData } from 'services/collection-service/collection-service-files-response';
19 import { DefaultIcon, DirectoryIcon, FileIcon } from 'components/icon/icon';
20 import { setCollectionFiles } from 'store/collection-panel/collection-panel-files/collection-panel-files-actions';
21 import { sortBy } from 'lodash';
22 import { formatFileSize } from 'common/formatters';
24 export interface CollectionPanelFilesProps {
28 tooManyFiles: boolean;
29 onUploadDataClick: () => void;
30 onSearchChange: (searchValue: string) => void;
31 onItemMenuOpen: (event: React.MouseEvent<HTMLElement>, item: TreeItem<FileTreeData>, isWritable: boolean) => void;
32 onOptionsMenuOpen: (event: React.MouseEvent<HTMLElement>, isWritable: boolean) => void;
33 onSelectionToggle: (event: React.MouseEvent<HTMLElement>, item: TreeItem<FileTreeData>) => void;
34 onCollapseToggle: (id: string, status: TreeItemStatus) => void;
35 onFileClick: (id: string) => void;
36 loadFilesFunc: () => void;
39 collectionPanelFiles: any;
43 type CssRules = "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) => ({
50 color: 'rgba(0, 0, 0, 0.87)',
52 fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
55 letterSpacing: '0.01071em'
63 marginBottom: '0.5rem',
66 backgroundColor: 'rgba(0, 0, 0, 0.08)',
83 display: 'inline-flex',
84 flexDirection: 'column',
85 justifyContent: 'center'
91 searchWrapperHidden: {
98 color: `${theme.palette.primary.main} !important`,
101 display: 'inline-flex',
102 flexDirection: 'column',
103 justifyContent: 'center'
111 marginBottom: '1rem',
112 backgroundColor: '#fff',
113 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%)',
119 whiteSpace: 'nowrap',
120 position: 'relative',
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%)',
127 animation: `animateVisible 1000ms ${theme.transitions.easing.easeOut}`
135 "@keyframes animateVisible": {
148 position: 'relative',
149 backgroundColor: '#fff',
150 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%)',
157 const pathPromise = {};
159 export const CollectionPanelFiles = withStyles(styles)(connect((state: RootState) => ({
161 collectionPanel: state.collectionPanel,
162 collectionPanelFiles: state.collectionPanelFiles,
163 }))((props: CollectionPanelFilesProps & WithStyles<CssRules> & { auth: AuthState }) => {
164 const { classes, onItemMenuOpen, isWritable, dispatch, collectionPanelFiles, collectionPanel } = props;
165 const { apiToken, config } = props.auth;
167 const webdavClient = new WebDAV();
168 webdavClient.defaults.baseURL = config.keepWebServiceUrl;
169 webdavClient.defaults.headers = {
170 Authorization: `Bearer ${apiToken}`
173 const webDAVRequestConfig: WebDAVRequestConfig = {
179 const parentRef = React.useRef(null);
180 const [path, setPath]: any = React.useState([]);
181 const [pathData, setPathData]: any = React.useState({});
182 const [isLoading, setIsLoading] = React.useState(false);
183 const [rightClickUsed, setRightClickUsed] = React.useState(false);
184 const [leftSearch, setLeftSearch] = React.useState('');
185 const [rightSearch, setRightSearch] = React.useState('');
187 const leftKey = (path.length > 1 ? path.slice(0, path.length - 1) : path).join('/');
188 const rightKey = path.join('/');
190 const leftData = (pathData[leftKey] || []).filter(({ type }) => type === 'directory');
191 const rightData = pathData[rightKey];
193 React.useEffect(() => {
194 if (props.currentItemUuid) {
196 setPath([props.currentItemUuid]);
198 }, [props.currentItemUuid]);
200 const fetchData = (rightKey, ignoreCache = false) => {
201 const dataExists = !!pathData[rightKey];
202 const runningRequest = pathPromise[rightKey];
204 if ((!dataExists || ignoreCache) && !runningRequest) {
207 webdavClient.propfind(`c=${rightKey}`, webDAVRequestConfig)
209 if (request.responseXML != null) {
210 const result: any = extractFilesData(request.responseXML);
211 const sortedResult = sortBy(result, (n) => n.name).sort((n1, n2) => {
212 if (n1.type === 'directory' && n2.type !== 'directory') {
215 if (n1.type !== 'directory' && n2.type === 'directory') {
220 const newPathData = { ...pathData, [rightKey]: sortedResult };
221 setPathData(newPathData);
226 delete pathPromise[rightKey];
229 pathPromise[rightKey] = true;
231 setTimeout(() => setIsLoading(false), 0);
235 React.useEffect(() => {
241 React.useEffect(() => {
242 const hash = (collectionPanel.item || {}).portableDataHash;
244 if (hash && rightClickUsed) {
245 fetchData(rightKey, true);
247 }, [(collectionPanel.item || {}).portableDataHash]);
249 React.useEffect(() => {
251 setCollectionFiles(rightData, false)(dispatch);
253 }, [rightData, dispatch]);
255 const handleRightClick = React.useCallback(
257 event.preventDefault();
259 if (!rightClickUsed) {
260 setRightClickUsed(true);
263 let elem = event.target;
265 while (elem && elem.dataset && !elem.dataset.item) {
266 elem = elem.parentNode;
273 const { id } = elem.dataset;
274 const item: any = { id, data: rightData.find((elem) => elem.id === id) };
277 onItemMenuOpen(event, item, isWritable);
280 [onItemMenuOpen, isWritable, rightData]
283 React.useEffect(() => {
286 if (parentRef && parentRef.current) {
287 node = parentRef.current;
288 (node as any).addEventListener('contextmenu', handleRightClick);
293 (node as any).removeEventListener('contextmenu', handleRightClick);
296 }, [parentRef, handleRightClick]);
298 const handleClick = React.useCallback(
300 let isCheckbox = false;
301 let elem = event.target;
303 if (elem.type === 'checkbox') {
307 while (elem && elem.dataset && !elem.dataset.item) {
308 elem = elem.parentNode;
311 if (elem && elem.dataset && !isCheckbox) {
312 const { parentPath, subfolderPath, breadcrumbPath, type } = elem.dataset;
314 if (breadcrumbPath) {
315 const index = path.indexOf(breadcrumbPath);
316 setPath([...path.slice(0, index + 1)]);
320 if (path.length > 1) {
324 setPath([...path, parentPath]);
327 if (subfolderPath && type === 'directory') {
328 setPath([...path, subfolderPath]);
333 const { id } = elem.dataset;
334 const item = collectionPanelFiles[id];
335 props.onSelectionToggle(event, item);
338 [path, setPath, collectionPanelFiles]
341 const getItemIcon = React.useCallback(
342 (type: string, activeClass: string | null) => {
343 let Icon = DefaultIcon;
347 Icon = DirectoryIcon;
355 <ListItemIcon className={classNames(classes.listItemIcon, activeClass)}>
363 const getActiveClass = React.useCallback(
365 return path[path.length - 1] === name ? classes.rowActive : null;
370 const onOptionsMenuOpen = React.useCallback(
371 (ev, isWritable) => {
372 props.onOptionsMenuOpen(ev, isWritable);
374 [props.onOptionsMenuOpen]
378 <div onClick={handleClick} ref={parentRef}>
379 <div className={classes.pathPanel}>
382 .map((p: string, index: number) => <span
383 key={`${index}-${p}`}
385 className={classes.pathPanelItem}
386 data-breadcrumb-path={p}
388 {index === 0 ? 'Home' : p} /
391 <Tooltip className={classes.pathPanelMenu} title="More options" disableFocusListener>
393 data-cy='collection-files-panel-options-btn'
394 onClick={(ev) => onOptionsMenuOpen(ev, isWritable)}>
395 <CustomizeTableIcon />
399 <div className={classes.wrapper}>
400 <div className={classNames(classes.leftPanel, path.length > 1 ? classes.leftPanelVisible : classes.leftPanelHidden)}>
401 <div className={path.length > 1 ? classes.searchWrapper : classes.searchWrapperHidden}>
402 <SearchInput label="Search" value={leftSearch} onSearch={setLeftSearch} />
404 <div className={classes.dataWrapper}>
407 <AutoSizer defaultWidth={0}>
408 {({ height, width }) => {
409 const filtered = leftData.filter(({ name }) => name.indexOf(leftSearch) > -1);
411 return !!filtered.length ? <FixedSizeList
413 itemCount={filtered.length}
418 ({ index, style }) => {
419 const { id, type, name } = filtered[index];
424 data-parent-path={name}
425 className={classNames(classes.row, getActiveClass(name))}
426 key={id}>{getItemIcon(type, getActiveClass(name))} <div className={classes.rowName}>{name}</div>
430 </FixedSizeList> : <div className={classes.rowEmpty}>No directories available</div>
432 </AutoSizer> : <div className={classes.row}><CircularProgress className={classes.loader} size={30} /></div>
437 <div className={classes.rightPanel}>
438 <div className={classes.searchWrapper}>
439 <SearchInput label="Search" value={rightSearch} onSearch={setRightSearch} />
441 <div className={classes.dataWrapper}>
443 rightData && !isLoading ?
444 <AutoSizer defaultHeight={500}>
445 {({ height, width }) => {
446 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
448 return !!filtered.length ? <FixedSizeList
450 itemCount={filtered.length}
455 ({ index, style }) => {
456 const { id, type, name, size } = filtered[index];
463 data-subfolder-path={name}
464 className={classes.row} key={id}>
467 className={classes.rowSelection}
468 checked={collectionPanelFiles[id] ? collectionPanelFiles[id].value.selected : false}
470 {getItemIcon(type, null)} <div className={classes.rowName}>
473 <span className={classes.rowName} style={{marginLeft: 'auto', marginRight: '1rem'}}>
474 {formatFileSize(size)}
479 </FixedSizeList> : <div className={classes.rowEmpty}>No data available</div>
481 </AutoSizer> : <div className={classes.row}><CircularProgress className={classes.loader} size={30} /></div>