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 { DownloadIcon, MoreHorizontalIcon, MoreVerticalIcon } 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";
36 import { extractUuidKind, ResourceKind } from "models/resource";
38 export interface CollectionPanelFilesProps {
40 onUploadDataClick: (targetLocation?: string) => void;
41 onSearchChange: (searchValue: string) => void;
42 onItemMenuOpen: (event: React.MouseEvent<HTMLElement>, item: TreeItem<FileTreeData>, isWritable: boolean) => void;
43 onOptionsMenuOpen: (event: React.MouseEvent<HTMLElement>, isWritable: boolean) => void;
44 onSelectionToggle: (event: React.MouseEvent<HTMLElement>, item: TreeItem<FileTreeData>) => void;
45 onCollapseToggle: (id: string, status: TreeItemStatus) => void;
46 onFileClick: (id: string) => void;
49 collectionPanelFiles: any;
56 | "pathPanelPathWrapper"
78 | "searchWrapperHidden";
80 const styles: StyleRulesCallback<CssRules> = (theme: Theme) => ({
84 color: "rgba(0,0,0,0.87)",
86 fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
89 letterSpacing: "0.01071em",
105 marginBottom: "0.5rem",
108 backgroundColor: "rgba(0, 0, 0, 0.08)",
115 position: "absolute",
122 position: "absolute",
125 display: "inline-flex",
126 flexDirection: "column",
127 justifyContent: "center",
130 display: "inline-block",
131 marginBottom: "1rem",
134 searchWrapperHidden: {
141 color: `${theme.palette.primary.main} !important`,
144 display: "inline-flex",
145 flexDirection: "column",
146 justifyContent: "center",
154 marginBottom: "0.5rem",
155 backgroundColor: "#fff",
156 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%)",
158 pathPanelPathWrapper: {
159 display: "inline-block",
163 padding: "0 1rem 1rem",
165 whiteSpace: "nowrap",
166 position: "relative",
167 backgroundColor: "#fff",
168 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%)",
173 animation: `animateVisible 1000ms ${theme.transitions.easing.easeOut}`,
181 "@keyframes animateVisible": {
194 paddingTop: "0.5rem",
195 marginTop: "-0.5rem",
196 position: "relative",
197 backgroundColor: "#fff",
198 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%)",
204 transform: "rotate(180deg)",
210 width: theme.spacing.unit * 3,
211 height: theme.spacing.unit * 3,
212 marginRight: theme.spacing.unit,
214 marginBottom: "auto",
215 justifyContent: "center",
218 position: "absolute",
222 const pathPromise = {};
224 export const CollectionPanelFiles = withStyles(styles)(
225 connect((state: RootState) => ({
227 collectionPanel: state.collectionPanel,
228 collectionPanelFiles: state.collectionPanelFiles,
229 }))((props: CollectionPanelFilesProps & WithStyles<CssRules> & { auth: AuthState }) => {
230 const { classes, onItemMenuOpen, onUploadDataClick, isWritable, dispatch, collectionPanelFiles, collectionPanel } = props;
231 const { apiToken, config } = props.auth;
233 const webdavClient = new WebDAV({
234 baseURL: config.keepWebServiceUrl,
236 Authorization: `Bearer ${apiToken}`,
240 const webDAVRequestConfig: WebDAVRequestConfig = {
246 const parentRef = React.useRef(null);
247 const [path, setPath] = React.useState<string[]>([]);
248 const [pathData, setPathData] = React.useState({});
249 const [isLoading, setIsLoading] = React.useState(false);
250 const [leftSearch, setLeftSearch] = React.useState("");
251 const [rightSearch, setRightSearch] = React.useState("");
253 const leftKey = (path.length > 1 ? path.slice(0, path.length - 1) : path).join("/");
254 const rightKey = path.join("/");
256 const leftData = pathData[leftKey] || [];
257 const rightData = pathData[rightKey];
259 React.useEffect(() => {
260 if (props.currentItemUuid && extractUuidKind(props.currentItemUuid) === ResourceKind.COLLECTION) {
262 setPath([props.currentItemUuid]);
264 }, [props.currentItemUuid]);
266 const fetchData = (keys, ignoreCache = false) => {
267 const keyArray = Array.isArray(keys) ? keys : [keys];
271 .filter(key => !!key)
273 const dataExists = !!pathData[key];
274 const runningRequest = pathPromise[key];
276 if (ignoreCache || (!dataExists && !runningRequest)) {
281 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 }));
319 keyArray.forEach(key => delete pathPromise[key]);
323 React.useEffect(() => {
329 }, [rightKey, rightData]); // eslint-disable-line react-hooks/exhaustive-deps
331 const currentPDH = (collectionPanel.item || {}).portableDataHash;
332 React.useEffect(() => {
334 fetchData([leftKey, rightKey], true);
336 }, [currentPDH]); // eslint-disable-line react-hooks/exhaustive-deps
338 React.useEffect(() => {
340 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
341 setCollectionFiles(filtered, false)(dispatch);
343 }, [rightData, dispatch, rightSearch]);
345 const handleRightClick = React.useCallback(
347 event.preventDefault();
348 let elem = event.target;
350 while (elem && elem.dataset && !elem.dataset.item) {
351 elem = elem.parentNode;
354 if (!elem || !elem.dataset) {
358 const { id } = elem.dataset;
362 data: rightData.find(elem => elem.id === id),
366 onItemMenuOpen(event, item, isWritable);
369 [onItemMenuOpen, isWritable, rightData]
372 React.useEffect(() => {
375 if (parentRef?.current) {
376 node = parentRef.current;
377 (node as any).addEventListener("contextmenu", handleRightClick);
382 (node as any).removeEventListener("contextmenu", handleRightClick);
385 }, [parentRef, handleRightClick]);
387 const handleClick = React.useCallback(
389 let isCheckbox = false;
390 let isMoreButton = false;
391 let elem = event.target;
393 if (elem.type === "checkbox") {
396 // The "More options" button click event could be triggered on its
397 // internal graphic element.
399 (elem.dataset && elem.dataset.id === "moreOptions") ||
400 (elem.parentNode && elem.parentNode.dataset && elem.parentNode.dataset.id === "moreOptions")
405 while (elem && elem.dataset && !elem.dataset.item) {
406 elem = elem.parentNode;
409 if (elem && elem.dataset && !isCheckbox && !isMoreButton) {
410 const { parentPath, subfolderPath, breadcrumbPath, type } = elem.dataset;
412 if (breadcrumbPath) {
413 const index = path.indexOf(breadcrumbPath);
414 setPath(state => [...state.slice(0, index + 1)]);
417 if (parentPath && type === "directory") {
418 if (path.length > 1) {
422 setPath(state => [...state, parentPath]);
425 if (subfolderPath && type === "directory") {
426 setPath(state => [...state, subfolderPath]);
429 if (elem.dataset.id && type === "file") {
430 const item = rightData.find(({ id }) => id === elem.dataset.id) || leftData.find(({ id }) => id === elem.dataset.id);
431 const enhancedItem = servicesProvider.getServices().collectionService.extendFileURL(item);
432 const fileUrl = sanitizeToken(
433 getInlineFileUrl(enhancedItem.url, config.keepWebServiceUrl, config.keepWebInlineServiceUrl),
436 window.open(fileUrl, "_blank", "noopener");
441 const { id } = elem.dataset;
442 const item = collectionPanelFiles[id];
443 props.onSelectionToggle(event, item);
446 const { id } = elem.dataset;
449 data: rightData.find(elem => elem.id === id),
451 onItemMenuOpen(event, item, isWritable);
454 [path, setPath, collectionPanelFiles] // eslint-disable-line react-hooks/exhaustive-deps
457 const getItemIcon = React.useCallback(
458 (type: string, activeClass: string | null) => {
459 let Icon = DefaultIcon;
463 Icon = DirectoryIcon;
471 <ListItemIcon className={classNames(classes.listItemIcon, activeClass)}>
479 const getActiveClass = React.useCallback(
481 return path[path.length - 1] === name ? classes.rowActive : null;
486 const onOptionsMenuOpen = React.useCallback(
487 (ev, isWritable) => {
488 props.onOptionsMenuOpen(ev, isWritable);
490 [props.onOptionsMenuOpen] // eslint-disable-line react-hooks/exhaustive-deps
495 data-cy="collection-files-panel"
496 onClick={handleClick}
499 <div className={classes.pathPanel}>
500 <div className={classes.pathPanelPathWrapper}>
501 {path.map((p: string, index: number) => (
503 key={`${index}-${p}`}
505 className={classes.pathPanelItem}
506 data-breadcrumb-path={p}
508 <span className={classes.rowActive}>{index === 0 ? "Home" : p}</span> <b>/</b>
513 className={classes.pathPanelMenu}
518 data-cy="collection-files-panel-options-btn"
520 onOptionsMenuOpen(ev, isWritable);
527 <div className={classes.wrapper}>
529 className={classNames(classes.leftPanel, path.length > 1 ? classes.leftPanelVisible : classes.leftPanelHidden)}
530 data-cy="collection-files-left-panel"
534 className={path.length > 1 ? classes.backButton : classes.backButtonHidden}
536 <IconButton onClick={() => setPath(state => [...state.slice(0, state.length - 1)])}>
540 <div className={path.length > 1 ? classes.searchWrapper : classes.searchWrapperHidden}>
542 selfClearProp={leftKey}
545 onSearch={setLeftSearch}
548 <div className={classes.dataWrapper}>
550 <AutoSizer defaultWidth={0}>
551 {({ height, width }) => {
552 const filtered = leftData.filter(({ name }) => name.indexOf(leftSearch) > -1);
553 return !!filtered.length ? (
556 itemCount={filtered.length}
560 {({ index, style }) => {
561 const { id, type, name } = filtered[index];
568 data-parent-path={name}
569 className={classNames(classes.row, getActiveClass(name))}
572 {getItemIcon(type, getActiveClass(name))}
573 <div className={classes.rowName}>{name}</div>
574 {getActiveClass(name) ? (
575 <SidePanelRightArrowIcon
576 style={{ display: "inline", marginTop: "5px", marginLeft: "5px" }}
584 <div className={classes.rowEmpty}>No directories available</div>
590 data-cy="collection-loader"
591 className={classes.row}
594 className={classes.loader}
602 className={classes.rightPanel}
603 data-cy="collection-files-right-panel"
605 <div className={classes.searchWrapper}>
607 selfClearProp={rightKey}
610 onSearch={setRightSearch}
615 className={classes.uploadButton}
616 data-cy="upload-button"
618 onUploadDataClick(rightKey === leftKey ? undefined : rightKey);
624 <DownloadIcon className={classes.uploadIcon} />
628 <div className={classes.dataWrapper}>
629 {rightData && !isLoading ? (
630 <AutoSizer defaultHeight={500}>
631 {({ height, width }) => {
632 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
633 return !!filtered.length ? (
636 itemCount={filtered.length}
640 {({ index, style }) => {
641 const { id, type, name, size } = filtered[index];
649 data-subfolder-path={name}
650 className={classes.row}
655 className={classes.rowSelection}
656 checked={collectionPanelFiles[id] ? collectionPanelFiles[id].value.selected : false}
659 {getItemIcon(type, null)}
660 <div className={classes.rowName}>{name}</div>
662 className={classes.rowName}
668 {formatFileSize(size)}
675 data-id="moreOptions"
676 data-cy="file-item-options-btn"
677 className={classes.moreOptionsButton}
680 data-id="moreOptions"
681 className={classes.moreOptions}
690 <div className={classes.rowEmpty}>This collection is empty</div>
695 <div className={classes.row}>
697 className={classes.loader}