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';
23 export interface CollectionPanelFilesProps {
27 tooManyFiles: boolean;
28 onUploadDataClick: () => void;
29 onSearchChange: (searchValue: string) => void;
30 onItemMenuOpen: (event: React.MouseEvent<HTMLElement>, item: TreeItem<FileTreeData>, isWritable: boolean) => void;
31 onOptionsMenuOpen: (event: React.MouseEvent<HTMLElement>, isWritable: boolean) => void;
32 onSelectionToggle: (event: React.MouseEvent<HTMLElement>, item: TreeItem<FileTreeData>) => void;
33 onCollapseToggle: (id: string, status: TreeItemStatus) => void;
34 onFileClick: (id: string) => void;
35 loadFilesFunc: () => void;
38 collectionPanelFiles: any;
42 type CssRules = "loader" | "wrapper" | "dataWrapper" | "row" | "rowEmpty" | "leftPanel" | "rightPanel" | "pathPanel" | "pathPanelItem" | "rowName" | "listItemIcon" | "rowActive" | "pathPanelMenu" | "rowSelection" | "leftPanelHidden" | "leftPanelVisible" | "searchWrapper" | "searchWrapperHidden";
44 const styles: StyleRulesCallback<CssRules> = (theme: Theme) => ({
56 marginBottom: '0.5rem',
59 backgroundColor: 'rgba(0, 0, 0, 0.08)',
76 display: 'inline-flex',
77 flexDirection: 'column',
78 justifyContent: 'center'
84 searchWrapperHidden: {
91 color: `${theme.palette.primary.main} !important`,
94 display: 'inline-flex',
95 flexDirection: 'column',
96 justifyContent: 'center'
104 marginBottom: '1rem',
105 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%)',
111 whiteSpace: 'nowrap',
112 position: 'relative',
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%)',
118 animation: `animateVisible 1000ms ${theme.transitions.easing.easeOut}`
126 "@keyframes animateVisible": {
139 position: 'relative',
140 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%)',
147 const pathPromise = {};
149 export const CollectionPanelFiles = withStyles(styles)(connect((state: RootState) => ({
151 collectionPanel: state.collectionPanel,
152 collectionPanelFiles: state.collectionPanelFiles,
153 }))((props: CollectionPanelFilesProps & WithStyles<CssRules> & { auth: AuthState }) => {
154 const { classes, onItemMenuOpen, isWritable, dispatch, collectionPanelFiles, collectionPanel } = props;
155 const { apiToken, config } = props.auth;
157 const webdavClient = new WebDAV();
158 webdavClient.defaults.baseURL = config.keepWebServiceUrl;
159 webdavClient.defaults.headers = {
160 Authorization: `Bearer ${apiToken}`
163 const webDAVRequestConfig: WebDAVRequestConfig = {
169 const parentRef = React.useRef(null);
170 const [path, setPath]: any = React.useState([]);
171 const [pathData, setPathData]: any = React.useState({});
172 const [isLoading, setIsLoading] = React.useState(false);
173 const [rightClickUsed, setRightClickUsed] = React.useState(false);
174 const [leftSearch, setLeftSearch] = React.useState('');
175 const [rightSearch, setRightSearch] = React.useState('');
177 const leftKey = (path.length > 1 ? path.slice(0, path.length - 1) : path).join('/');
178 const rightKey = path.join('/');
180 const leftData = (pathData[leftKey] || []).filter(({ type }) => type === 'directory');
181 const rightData = pathData[rightKey];
183 React.useEffect(() => {
184 if (props.currentItemUuid) {
186 setPath([props.currentItemUuid]);
188 }, [props.currentItemUuid]);
190 const fetchData = (rightKey, ignoreCache = false) => {
191 const dataExists = !!pathData[rightKey];
192 const runningRequest = pathPromise[rightKey];
194 if ((!dataExists || ignoreCache) && !runningRequest) {
197 webdavClient.propfind(`c=${rightKey}`, webDAVRequestConfig)
199 if (request.responseXML != null) {
200 const result: any = extractFilesData(request.responseXML);
201 const sortedResult = sortBy(result, (n) => n.name).sort((n1, n2) => {
202 if (n1.type === 'directory' && n2.type !== 'directory') {
205 if (n1.type !== 'directory' && n2.type === 'directory') {
210 const newPathData = { ...pathData, [rightKey]: sortedResult };
211 setPathData(newPathData);
216 delete pathPromise[rightKey];
219 pathPromise[rightKey] = true;
221 setTimeout(() => setIsLoading(false), 0);
225 React.useEffect(() => {
231 React.useEffect(() => {
232 const hash = (collectionPanel.item || {}).portableDataHash;
234 if (hash && rightClickUsed) {
235 fetchData(rightKey, true);
237 }, [(collectionPanel.item || {}).portableDataHash]);
239 React.useEffect(() => {
241 setCollectionFiles(rightData, false)(dispatch);
243 }, [rightData, dispatch]);
245 const handleRightClick = React.useCallback(
247 event.preventDefault();
249 if (!rightClickUsed) {
250 setRightClickUsed(true);
253 let elem = event.target;
255 while (elem && elem.dataset && !elem.dataset.item) {
256 elem = elem.parentNode;
263 const { id } = elem.dataset;
264 const item: any = { id, data: rightData.find((elem) => elem.id === id) };
267 onItemMenuOpen(event, item, isWritable);
270 [onItemMenuOpen, isWritable, rightData]
273 React.useEffect(() => {
276 if (parentRef && parentRef.current) {
277 node = parentRef.current;
278 (node as any).addEventListener('contextmenu', handleRightClick);
283 (node as any).removeEventListener('contextmenu', handleRightClick);
286 }, [parentRef, handleRightClick]);
288 const handleClick = React.useCallback(
290 let isCheckbox = false;
291 let elem = event.target;
293 if (elem.type === 'checkbox') {
297 while (elem && elem.dataset && !elem.dataset.item) {
298 elem = elem.parentNode;
301 if (elem && elem.dataset && !isCheckbox) {
302 const { parentPath, subfolderPath, breadcrumbPath, type } = elem.dataset;
304 if (breadcrumbPath) {
305 const index = path.indexOf(breadcrumbPath);
306 setPath([...path.slice(0, index + 1)]);
310 if (path.length > 1) {
314 setPath([...path, parentPath]);
317 if (subfolderPath && type === 'directory') {
318 setPath([...path, subfolderPath]);
323 const { id } = elem.dataset;
324 const item = collectionPanelFiles[id];
325 props.onSelectionToggle(event, item);
328 [path, setPath, collectionPanelFiles]
331 const getItemIcon = React.useCallback(
332 (type: string, activeClass: string | null) => {
333 let Icon = DefaultIcon;
337 Icon = DirectoryIcon;
345 <ListItemIcon className={classNames(classes.listItemIcon, activeClass)}>
353 const getActiveClass = React.useCallback(
355 return path[path.length - 1] === name ? classes.rowActive : null;
360 const onOptionsMenuOpen = React.useCallback(
361 (ev, isWritable) => {
362 props.onOptionsMenuOpen(ev, isWritable);
364 [props.onOptionsMenuOpen]
368 <div onClick={handleClick} ref={parentRef}>
369 <div className={classes.pathPanel}>
372 .map((p: string, index: number) => <span
373 key={`${index}-${p}`}
375 className={classes.pathPanelItem}
376 data-breadcrumb-path={p}
378 {index === 0 ? 'Home' : p} /
381 <Tooltip className={classes.pathPanelMenu} title="More options" disableFocusListener>
383 data-cy='collection-files-panel-options-btn'
384 onClick={(ev) => onOptionsMenuOpen(ev, isWritable)}>
385 <CustomizeTableIcon />
389 <div className={classes.wrapper}>
390 <div className={classNames(classes.leftPanel, path.length > 1 ? classes.leftPanelVisible : classes.leftPanelHidden)}>
391 <div className={path.length > 1 ? classes.searchWrapper : classes.searchWrapperHidden}>
392 <SearchInput label="Search" value={leftSearch} onSearch={setLeftSearch} />
394 <div className={classes.dataWrapper}>
397 <AutoSizer defaultWidth={0}>
398 {({ height, width }) => {
399 const filtered = leftData.filter(({ name }) => name.indexOf(leftSearch) > -1);
401 return !!filtered.length ? <FixedSizeList
403 itemCount={filtered.length}
408 ({ index, style }) => {
409 const { id, type, name } = filtered[index];
414 data-parent-path={name}
415 className={classNames(classes.row, getActiveClass(name))}
416 key={id}>{getItemIcon(type, getActiveClass(name))} <div className={classes.rowName}>{name}</div>
420 </FixedSizeList> : <div className={classes.rowEmpty}>No directories available</div>
422 </AutoSizer> : <div className={classes.row}><CircularProgress className={classes.loader} size={30} /></div>
427 <div className={classes.rightPanel}>
428 <div className={classes.searchWrapper}>
429 <SearchInput label="Search" value={rightSearch} onSearch={setRightSearch} />
431 <div className={classes.dataWrapper}>
433 rightData && !isLoading ?
434 <AutoSizer defaultHeight={500}>
435 {({ height, width }) => {
436 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
438 return !!filtered.length ? <FixedSizeList
440 itemCount={filtered.length}
445 ({ index, style }) => {
446 const { id, type, name } = filtered[index];
453 data-subfolder-path={name}
454 className={classes.row} key={id}>
457 className={classes.rowSelection}
458 checked={collectionPanelFiles[id] ? collectionPanelFiles[id].value.selected : false}
460 {getItemIcon(type, null)} <div className={classes.rowName}>
466 </FixedSizeList> : <div className={classes.rowEmpty}>No data available</div>
468 </AutoSizer> : <div className={classes.row}><CircularProgress className={classes.loader} size={30} /></div>