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;
282 return webdavClient.propfind(`c=${key}`, webDAVRequestConfig);
285 return Promise.resolve(null);
287 .filter(promise => !!promise)
290 const newState = requests
291 .map((request, index) => {
292 if (request && request.responseXML != null) {
293 const key = keyArray[index];
294 const result: any = extractFilesData(request.responseXML);
295 const sortedResult = sortBy(result, n => n.name).sort((n1, n2) => {
296 if (n1.type === "directory" && n2.type !== "directory") {
299 if (n1.type !== "directory" && n2.type === "directory") {
305 return { [key]: sortedResult };
309 .reduce((prev, next) => {
310 return { ...next, ...prev };
312 setPathData(state => ({ ...state, ...newState }));
316 keyArray.forEach(key => delete pathPromise[key]);
320 React.useEffect(() => {
326 }, [rightKey]); // eslint-disable-line react-hooks/exhaustive-deps
328 const currentPDH = (collectionPanel.item || {}).portableDataHash;
329 React.useEffect(() => {
331 fetchData([leftKey, rightKey], true);
333 }, [currentPDH]); // eslint-disable-line react-hooks/exhaustive-deps
335 React.useEffect(() => {
337 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
338 setCollectionFiles(filtered, false)(dispatch);
340 }, [rightData, dispatch, rightSearch]);
342 const handleRightClick = React.useCallback(
344 event.preventDefault();
345 let elem = event.target;
347 while (elem && elem.dataset && !elem.dataset.item) {
348 elem = elem.parentNode;
351 if (!elem || !elem.dataset) {
355 const { id } = elem.dataset;
359 data: rightData.find(elem => elem.id === id),
363 onItemMenuOpen(event, item, isWritable);
366 [onItemMenuOpen, isWritable, rightData]
369 React.useEffect(() => {
372 if (parentRef?.current) {
373 node = parentRef.current;
374 (node as any).addEventListener("contextmenu", handleRightClick);
379 (node as any).removeEventListener("contextmenu", handleRightClick);
382 }, [parentRef, handleRightClick]);
384 const handleClick = React.useCallback(
386 let isCheckbox = false;
387 let isMoreButton = false;
388 let elem = event.target;
390 if (elem.type === "checkbox") {
393 // The "More options" button click event could be triggered on its
394 // internal graphic element.
396 (elem.dataset && elem.dataset.id === "moreOptions") ||
397 (elem.parentNode && elem.parentNode.dataset && elem.parentNode.dataset.id === "moreOptions")
402 while (elem && elem.dataset && !elem.dataset.item) {
403 elem = elem.parentNode;
406 if (elem && elem.dataset && !isCheckbox && !isMoreButton) {
407 const { parentPath, subfolderPath, breadcrumbPath, type } = elem.dataset;
409 if (breadcrumbPath) {
410 const index = path.indexOf(breadcrumbPath);
411 setPath(state => [...state.slice(0, index + 1)]);
414 if (parentPath && type === "directory") {
415 if (path.length > 1) {
419 setPath(state => [...state, parentPath]);
422 if (subfolderPath && type === "directory") {
423 setPath(state => [...state, subfolderPath]);
426 if (elem.dataset.id && type === "file") {
427 const item = rightData.find(({ id }) => id === elem.dataset.id) || leftData.find(({ id }) => id === elem.dataset.id);
428 const enhancedItem = servicesProvider.getServices().collectionService.extendFileURL(item);
429 const fileUrl = sanitizeToken(
430 getInlineFileUrl(enhancedItem.url, config.keepWebServiceUrl, config.keepWebInlineServiceUrl),
433 window.open(fileUrl, "_blank");
438 const { id } = elem.dataset;
439 const item = collectionPanelFiles[id];
440 props.onSelectionToggle(event, item);
443 const { id } = elem.dataset;
446 data: rightData.find(elem => elem.id === id),
448 onItemMenuOpen(event, item, isWritable);
451 [path, setPath, collectionPanelFiles] // eslint-disable-line react-hooks/exhaustive-deps
454 const getItemIcon = React.useCallback(
455 (type: string, activeClass: string | null) => {
456 let Icon = DefaultIcon;
460 Icon = DirectoryIcon;
468 <ListItemIcon className={classNames(classes.listItemIcon, activeClass)}>
476 const getActiveClass = React.useCallback(
478 return path[path.length - 1] === name ? classes.rowActive : null;
483 const onOptionsMenuOpen = React.useCallback(
484 (ev, isWritable) => {
485 props.onOptionsMenuOpen(ev, isWritable);
487 [props.onOptionsMenuOpen] // eslint-disable-line react-hooks/exhaustive-deps
492 data-cy="collection-files-panel"
493 onClick={handleClick}
495 <div className={classes.pathPanel}>
496 <div className={classes.pathPanelPathWrapper}>
497 {path.map((p: string, index: number) => (
499 key={`${index}-${p}`}
501 className={classes.pathPanelItem}
502 data-breadcrumb-path={p}>
503 <span className={classes.rowActive}>{index === 0 ? "Home" : p}</span> <b>/</b>
508 className={classes.pathPanelMenu}
510 disableFocusListener>
512 data-cy="collection-files-panel-options-btn"
514 onOptionsMenuOpen(ev, isWritable);
516 <CustomizeTableIcon />
520 <div className={classes.wrapper}>
522 className={classNames(classes.leftPanel, path.length > 1 ? classes.leftPanelVisible : classes.leftPanelHidden)}
523 data-cy="collection-files-left-panel">
526 className={path.length > 1 ? classes.backButton : classes.backButtonHidden}>
527 <IconButton onClick={() => setPath(state => [...state.slice(0, state.length - 1)])}>
531 <div className={path.length > 1 ? classes.searchWrapper : classes.searchWrapperHidden}>
533 selfClearProp={leftKey}
536 onSearch={setLeftSearch}
539 <div className={classes.dataWrapper}>
541 <AutoSizer defaultWidth={0}>
542 {({ height, width }) => {
543 const filtered = leftData.filter(({ name }) => name.indexOf(leftSearch) > -1);
544 return !!filtered.length ? (
547 itemCount={filtered.length}
550 {({ index, style }) => {
551 const { id, type, name } = filtered[index];
558 data-parent-path={name}
559 className={classNames(classes.row, getActiveClass(name))}
561 {getItemIcon(type, getActiveClass(name))}
562 <div className={classes.rowName}>{name}</div>
563 {getActiveClass(name) ? (
564 <SidePanelRightArrowIcon
565 style={{ display: "inline", marginTop: "5px", marginLeft: "5px" }}
573 <div className={classes.rowEmpty}>No directories available</div>
579 data-cy="collection-loader"
580 className={classes.row}>
582 className={classes.loader}
590 className={classes.rightPanel}
591 data-cy="collection-files-right-panel">
592 <div className={classes.searchWrapper}>
594 selfClearProp={rightKey}
597 onSearch={setRightSearch}
602 className={classes.uploadButton}
603 data-cy="upload-button"
605 onUploadDataClick(rightKey === leftKey ? undefined : rightKey);
610 <DownloadIcon className={classes.uploadIcon} />
614 <div className={classes.dataWrapper}>
615 {rightData && !isLoading ? (
616 <AutoSizer defaultHeight={500}>
617 {({ height, width }) => {
618 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
619 return !!filtered.length ? (
622 itemCount={filtered.length}
625 {({ index, style }) => {
626 const { id, type, name, size } = filtered[index];
634 data-subfolder-path={name}
635 className={classes.row}
639 className={classes.rowSelection}
640 checked={collectionPanelFiles[id] ? collectionPanelFiles[id].value.selected : false}
643 {getItemIcon(type, null)}
644 <div className={classes.rowName}>{name}</div>
646 className={classes.rowName}
651 {formatFileSize(size)}
655 disableFocusListener>
657 data-id="moreOptions"
658 data-cy="file-item-options-btn"
659 className={classes.moreOptionsButton}>
661 data-id="moreOptions"
662 className={classes.moreOptions}
671 <div className={classes.rowEmpty}>This collection is empty</div>
676 <div className={classes.row}>
678 className={classes.loader}