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, MoreOptionsIcon } 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";
31 import { DefaultIcon, DirectoryIcon, FileIcon, BackIcon, SidePanelRightArrowIcon } from "components/icon/icon";
32 import { setCollectionFiles } from "store/collection-panel/collection-panel-files/collection-panel-files-actions";
33 import { sortBy } from "lodash";
34 import { formatFileSize } from "common/formatters";
35 import { getInlineFileUrl, sanitizeToken } from "views-components/context-menu/actions/helpers";
37 export interface CollectionPanelFilesProps {
39 onUploadDataClick: (targetLocation?: string) => void;
40 onSearchChange: (searchValue: string) => void;
41 onItemMenuOpen: (event: React.MouseEvent<HTMLElement>, item: TreeItem<FileTreeData>, isWritable: boolean) => void;
42 onOptionsMenuOpen: (event: React.MouseEvent<HTMLElement>, isWritable: boolean) => void;
43 onSelectionToggle: (event: React.MouseEvent<HTMLElement>, item: TreeItem<FileTreeData>) => void;
44 onCollapseToggle: (id: string, status: TreeItemStatus) => void;
45 onFileClick: (id: string) => void;
48 collectionPanelFiles: any;
55 | "pathPanelPathWrapper"
77 | "searchWrapperHidden";
79 const styles: StyleRulesCallback<CssRules> = (theme: Theme) => ({
83 color: "rgba(0,0,0,0.87)",
85 fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
88 letterSpacing: "0.01071em",
104 marginBottom: "0.5rem",
107 backgroundColor: "rgba(0, 0, 0, 0.08)",
114 position: "absolute",
121 position: "absolute",
124 display: "inline-flex",
125 flexDirection: "column",
126 justifyContent: "center",
129 display: "inline-block",
130 marginBottom: "1rem",
133 searchWrapperHidden: {
140 color: `${theme.palette.primary.main} !important`,
143 display: "inline-flex",
144 flexDirection: "column",
145 justifyContent: "center",
153 marginBottom: "0.5rem",
154 backgroundColor: "#fff",
155 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 pathPanelPathWrapper: {
158 display: "inline-block",
162 padding: "0 1rem 1rem",
164 whiteSpace: "nowrap",
165 position: "relative",
166 backgroundColor: "#fff",
167 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%)",
172 animation: `animateVisible 1000ms ${theme.transitions.easing.easeOut}`,
180 "@keyframes animateVisible": {
193 paddingTop: "0.5rem",
194 marginTop: "-0.5rem",
195 position: "relative",
196 backgroundColor: "#fff",
197 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%)",
203 transform: "rotate(180deg)",
209 width: theme.spacing.unit * 3,
210 height: theme.spacing.unit * 3,
211 marginRight: theme.spacing.unit,
213 marginBottom: "auto",
214 justifyContent: "center",
217 position: "absolute",
221 const pathPromise = {};
223 export const CollectionPanelFiles = withStyles(styles)(
224 connect((state: RootState) => ({
226 collectionPanel: state.collectionPanel,
227 collectionPanelFiles: state.collectionPanelFiles,
228 }))((props: CollectionPanelFilesProps & WithStyles<CssRules> & { auth: AuthState }) => {
229 const { classes, onItemMenuOpen, onUploadDataClick, isWritable, dispatch, collectionPanelFiles, collectionPanel } = props;
230 const { apiToken, config } = props.auth;
232 const webdavClient = new WebDAV({
233 baseURL: config.keepWebServiceUrl,
235 Authorization: `Bearer ${apiToken}`,
239 const webDAVRequestConfig: WebDAVRequestConfig = {
245 const parentRef = React.useRef(null);
246 const [path, setPath] = React.useState<string[]>([]);
247 const [pathData, setPathData] = React.useState({});
248 const [isLoading, setIsLoading] = React.useState(false);
249 const [leftSearch, setLeftSearch] = React.useState("");
250 const [rightSearch, setRightSearch] = React.useState("");
252 const leftKey = (path.length > 1 ? path.slice(0, path.length - 1) : path).join("/");
253 const rightKey = path.join("/");
255 const leftData = pathData[leftKey] || [];
256 const rightData = pathData[rightKey];
258 React.useEffect(() => {
259 if (props.currentItemUuid) {
261 setPath([props.currentItemUuid]);
263 }, [props.currentItemUuid]);
265 const fetchData = (keys, ignoreCache = false) => {
266 const keyArray = Array.isArray(keys) ? keys : [keys];
270 .filter(key => !!key)
272 const dataExists = !!pathData[key];
273 const runningRequest = pathPromise[key];
275 if (ignoreCache || (!dataExists && !runningRequest)) {
280 pathPromise[key] = true;
283 return webdavClient.propfind(`c=${key}`, webDAVRequestConfig);
286 return Promise.resolve(null);
288 .filter(promise => !!promise)
291 const newState = requests
292 .map((request, index) => {
293 if (request && request.responseXML != null) {
294 const key = keyArray[index];
295 const result: any = extractFilesData(request.responseXML);
296 const sortedResult = sortBy(result, n => n.name).sort((n1, n2) => {
297 if (n1.type === "directory" && n2.type !== "directory") {
300 if (n1.type !== "directory" && n2.type === "directory") {
306 return { [key]: sortedResult };
310 .reduce((prev, next) => {
311 return { ...next, ...prev };
313 setPathData(state => ({ ...state, ...newState }));
317 keyArray.forEach(key => delete pathPromise[key]);
321 React.useEffect(() => {
327 }, [rightKey]); // eslint-disable-line react-hooks/exhaustive-deps
329 const currentPDH = (collectionPanel.item || {}).portableDataHash;
330 React.useEffect(() => {
332 fetchData([leftKey, rightKey], true);
334 }, [currentPDH]); // eslint-disable-line react-hooks/exhaustive-deps
336 React.useEffect(() => {
338 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
339 setCollectionFiles(filtered, false)(dispatch);
341 }, [rightData, dispatch, rightSearch]);
343 const handleRightClick = React.useCallback(
345 event.preventDefault();
346 let elem = event.target;
348 while (elem && elem.dataset && !elem.dataset.item) {
349 elem = elem.parentNode;
352 if (!elem || !elem.dataset) {
356 const { id } = elem.dataset;
360 data: rightData.find(elem => elem.id === id),
364 onItemMenuOpen(event, item, isWritable);
367 [onItemMenuOpen, isWritable, rightData]
370 React.useEffect(() => {
373 if (parentRef?.current) {
374 node = parentRef.current;
375 (node as any).addEventListener("contextmenu", handleRightClick);
380 (node as any).removeEventListener("contextmenu", handleRightClick);
383 }, [parentRef, handleRightClick]);
385 const handleClick = React.useCallback(
387 let isCheckbox = false;
388 let isMoreButton = false;
389 let elem = event.target;
391 if (elem.type === "checkbox") {
394 // The "More options" button click event could be triggered on its
395 // internal graphic element.
397 (elem.dataset && elem.dataset.id === "moreOptions") ||
398 (elem.parentNode && elem.parentNode.dataset && elem.parentNode.dataset.id === "moreOptions")
403 while (elem && elem.dataset && !elem.dataset.item) {
404 elem = elem.parentNode;
407 if (elem && elem.dataset && !isCheckbox && !isMoreButton) {
408 const { parentPath, subfolderPath, breadcrumbPath, type } = elem.dataset;
410 if (breadcrumbPath) {
411 const index = path.indexOf(breadcrumbPath);
412 setPath(state => [...state.slice(0, index + 1)]);
415 if (parentPath && type === "directory") {
416 if (path.length > 1) {
420 setPath(state => [...state, parentPath]);
423 if (subfolderPath && type === "directory") {
424 setPath(state => [...state, subfolderPath]);
427 if (elem.dataset.id && type === "file") {
428 const item = rightData.find(({ id }) => id === elem.dataset.id) || leftData.find(({ id }) => id === elem.dataset.id);
429 const enhancedItem = servicesProvider.getServices().collectionService.extendFileURL(item);
430 const fileUrl = sanitizeToken(
431 getInlineFileUrl(enhancedItem.url, config.keepWebServiceUrl, config.keepWebInlineServiceUrl),
434 window.open(fileUrl, "_blank");
439 const { id } = elem.dataset;
440 const item = collectionPanelFiles[id];
441 props.onSelectionToggle(event, item);
444 const { id } = elem.dataset;
447 data: rightData.find(elem => elem.id === id),
449 onItemMenuOpen(event, item, isWritable);
452 [path, setPath, collectionPanelFiles] // eslint-disable-line react-hooks/exhaustive-deps
455 const getItemIcon = React.useCallback(
456 (type: string, activeClass: string | null) => {
457 let Icon = DefaultIcon;
461 Icon = DirectoryIcon;
469 <ListItemIcon className={classNames(classes.listItemIcon, activeClass)}>
477 const getActiveClass = React.useCallback(
479 return path[path.length - 1] === name ? classes.rowActive : null;
484 const onOptionsMenuOpen = React.useCallback(
485 (ev, isWritable) => {
486 props.onOptionsMenuOpen(ev, isWritable);
488 [props.onOptionsMenuOpen] // eslint-disable-line react-hooks/exhaustive-deps
493 data-cy="collection-files-panel"
494 onClick={handleClick}
496 <div className={classes.pathPanel}>
497 <div className={classes.pathPanelPathWrapper}>
498 {path.map((p: string, index: number) => (
500 key={`${index}-${p}`}
502 className={classes.pathPanelItem}
503 data-breadcrumb-path={p}>
504 <span className={classes.rowActive}>{index === 0 ? "Home" : p}</span> <b>/</b>
509 className={classes.pathPanelMenu}
511 disableFocusListener>
513 data-cy="collection-files-panel-options-btn"
515 onOptionsMenuOpen(ev, isWritable);
517 <CustomizeTableIcon />
521 <div className={classes.wrapper}>
523 className={classNames(classes.leftPanel, path.length > 1 ? classes.leftPanelVisible : classes.leftPanelHidden)}
524 data-cy="collection-files-left-panel">
527 className={path.length > 1 ? classes.backButton : classes.backButtonHidden}>
528 <IconButton onClick={() => setPath(state => [...state.slice(0, state.length - 1)])}>
532 <div className={path.length > 1 ? classes.searchWrapper : classes.searchWrapperHidden}>
534 selfClearProp={leftKey}
537 onSearch={setLeftSearch}
540 <div className={classes.dataWrapper}>
542 <AutoSizer defaultWidth={0}>
543 {({ height, width }) => {
544 const filtered = leftData.filter(({ name }) => name.indexOf(leftSearch) > -1);
545 return !!filtered.length ? (
548 itemCount={filtered.length}
551 {({ index, style }) => {
552 const { id, type, name } = filtered[index];
559 data-parent-path={name}
560 className={classNames(classes.row, getActiveClass(name))}
562 {getItemIcon(type, getActiveClass(name))}
563 <div className={classes.rowName}>{name}</div>
564 {getActiveClass(name) ? (
565 <SidePanelRightArrowIcon
566 style={{ display: "inline", marginTop: "5px", marginLeft: "5px" }}
574 <div className={classes.rowEmpty}>No directories available</div>
580 data-cy="collection-loader"
581 className={classes.row}>
583 className={classes.loader}
591 className={classes.rightPanel}
592 data-cy="collection-files-right-panel">
593 <div className={classes.searchWrapper}>
595 selfClearProp={rightKey}
598 onSearch={setRightSearch}
603 className={classes.uploadButton}
604 data-cy="upload-button"
606 onUploadDataClick(rightKey === leftKey ? undefined : rightKey);
611 <DownloadIcon className={classes.uploadIcon} />
615 <div className={classes.dataWrapper}>
616 {rightData && !isLoading ? (
617 <AutoSizer defaultHeight={500}>
618 {({ height, width }) => {
619 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
620 return !!filtered.length ? (
623 itemCount={filtered.length}
626 {({ index, style }) => {
627 const { id, type, name, size } = filtered[index];
635 data-subfolder-path={name}
636 className={classes.row}
640 className={classes.rowSelection}
641 checked={collectionPanelFiles[id] ? collectionPanelFiles[id].value.selected : false}
644 {getItemIcon(type, null)}
645 <div className={classes.rowName}>{name}</div>
647 className={classes.rowName}
652 {formatFileSize(size)}
656 disableFocusListener>
658 data-id="moreOptions"
659 data-cy="file-item-options-btn"
660 className={classes.moreOptionsButton}>
662 data-id="moreOptions"
663 className={classes.moreOptions}
672 <div className={classes.rowEmpty}>This collection is empty</div>
677 <div className={classes.row}>
679 className={classes.loader}