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 // eslint-disable-next-line react-hooks/exhaustive-deps
330 }, [rightKey, rightData]);
332 const currentPDH = (collectionPanel.item || {}).portableDataHash;
333 React.useEffect(() => {
335 fetchData([leftKey, rightKey], true);
337 // eslint-disable-next-line react-hooks/exhaustive-deps
340 React.useEffect(() => {
342 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
343 setCollectionFiles(filtered, false)(dispatch);
345 }, [rightData, dispatch, rightSearch]);
347 const handleRightClick = React.useCallback(
349 event.preventDefault();
350 let elem = event.target;
352 while (elem && elem.dataset && !elem.dataset.item) {
353 elem = elem.parentNode;
356 if (!elem || !elem.dataset) {
360 const { id } = elem.dataset;
364 data: rightData.find(elem => elem.id === id),
368 onItemMenuOpen(event, item, isWritable);
371 [onItemMenuOpen, isWritable, rightData]
374 React.useEffect(() => {
377 if (parentRef?.current) {
378 node = parentRef.current;
379 (node as any).addEventListener("contextmenu", handleRightClick);
384 (node as any).removeEventListener("contextmenu", handleRightClick);
387 }, [parentRef, handleRightClick]);
389 const handleClick = React.useCallback(
391 let isCheckbox = false;
392 let isMoreButton = false;
393 let elem = event.target;
395 if (elem.type === "checkbox") {
398 // The "More options" button click event could be triggered on its
399 // internal graphic element.
401 (elem.dataset && elem.dataset.id === "moreOptions") ||
402 (elem.parentNode && elem.parentNode.dataset && elem.parentNode.dataset.id === "moreOptions")
407 while (elem && elem.dataset && !elem.dataset.item) {
408 elem = elem.parentNode;
411 if (elem && elem.dataset && !isCheckbox && !isMoreButton) {
412 const { parentPath, subfolderPath, breadcrumbPath, type } = elem.dataset;
414 if (breadcrumbPath) {
415 const index = path.indexOf(breadcrumbPath);
416 setPath(state => [...state.slice(0, index + 1)]);
419 if (parentPath && type === "directory") {
420 if (path.length > 1) {
424 setPath(state => [...state, parentPath]);
427 if (subfolderPath && type === "directory") {
428 setPath(state => [...state, subfolderPath]);
431 if (elem.dataset.id && type === "file") {
432 const item = rightData.find(({ id }) => id === elem.dataset.id) || leftData.find(({ id }) => id === elem.dataset.id);
433 const enhancedItem = servicesProvider.getServices().collectionService.extendFileURL(item);
434 const fileUrl = sanitizeToken(
435 getInlineFileUrl(enhancedItem.url, config.keepWebServiceUrl, config.keepWebInlineServiceUrl),
438 window.open(fileUrl, "_blank", "noopener");
443 const { id } = elem.dataset;
444 const item = collectionPanelFiles[id];
445 props.onSelectionToggle(event, item);
448 const { id } = elem.dataset;
451 data: rightData.find(elem => elem.id === id),
453 onItemMenuOpen(event, item, isWritable);
456 // eslint-disable-next-line react-hooks/exhaustive-deps
457 [path, setPath, collectionPanelFiles]
460 const getItemIcon = React.useCallback(
461 (type: string, activeClass: string | null) => {
462 let Icon = DefaultIcon;
466 Icon = DirectoryIcon;
474 <ListItemIcon className={classNames(classes.listItemIcon, activeClass)}>
482 const getActiveClass = React.useCallback(
484 return path[path.length - 1] === name ? classes.rowActive : null;
489 const onOptionsMenuOpen = React.useCallback(
490 (ev, isWritable) => {
491 props.onOptionsMenuOpen(ev, isWritable);
493 // eslint-disable-next-line react-hooks/exhaustive-deps
494 [props.onOptionsMenuOpen]
499 data-cy="collection-files-panel"
500 onClick={handleClick}
503 <div className={classes.pathPanel}>
504 <div className={classes.pathPanelPathWrapper}>
505 {path.map((p: string, index: number) => (
507 key={`${index}-${p}`}
509 className={classes.pathPanelItem}
510 data-breadcrumb-path={p}
512 <span className={classes.rowActive}>{index === 0 ? "Home" : p}</span> <b>/</b>
517 className={classes.pathPanelMenu}
522 data-cy="collection-files-panel-options-btn"
524 onOptionsMenuOpen(ev, isWritable);
531 <div className={classes.wrapper}>
533 className={classNames(classes.leftPanel, path.length > 1 ? classes.leftPanelVisible : classes.leftPanelHidden)}
534 data-cy="collection-files-left-panel"
538 className={path.length > 1 ? classes.backButton : classes.backButtonHidden}
540 <IconButton onClick={() => setPath(state => [...state.slice(0, state.length - 1)])}>
544 <div className={path.length > 1 ? classes.searchWrapper : classes.searchWrapperHidden}>
546 selfClearProp={leftKey}
549 onSearch={setLeftSearch}
552 <div className={classes.dataWrapper}>
554 <AutoSizer defaultWidth={0}>
555 {({ height, width }) => {
556 const filtered = leftData.filter(({ name }) => name.indexOf(leftSearch) > -1);
557 return !!filtered.length ? (
560 itemCount={filtered.length}
564 {({ index, style }) => {
565 const { id, type, name } = filtered[index];
572 data-parent-path={name}
573 className={classNames(classes.row, getActiveClass(name))}
576 {getItemIcon(type, getActiveClass(name))}
577 <div className={classes.rowName}>{name}</div>
578 {getActiveClass(name) ? (
579 <SidePanelRightArrowIcon
580 style={{ display: "inline", marginTop: "5px", marginLeft: "5px" }}
588 <div className={classes.rowEmpty}>No directories available</div>
594 data-cy="collection-loader"
595 className={classes.row}
598 className={classes.loader}
606 className={classes.rightPanel}
607 data-cy="collection-files-right-panel"
609 <div className={classes.searchWrapper}>
611 selfClearProp={rightKey}
614 onSearch={setRightSearch}
619 className={classes.uploadButton}
620 data-cy="upload-button"
622 onUploadDataClick(rightKey === leftKey ? undefined : rightKey);
628 <DownloadIcon className={classes.uploadIcon} />
632 <div className={classes.dataWrapper}>
633 {rightData && !isLoading ? (
634 <AutoSizer defaultHeight={500}>
635 {({ height, width }) => {
636 const filtered = rightData.filter(({ name }) => name.indexOf(rightSearch) > -1);
637 return !!filtered.length ? (
640 itemCount={filtered.length}
644 {({ index, style }) => {
645 const { id, type, name, size } = filtered[index];
653 data-subfolder-path={name}
654 className={classes.row}
659 className={classes.rowSelection}
660 checked={collectionPanelFiles[id] ? collectionPanelFiles[id].value.selected : false}
663 {getItemIcon(type, null)}
664 <div className={classes.rowName}>{name}</div>
666 className={classes.rowName}
672 {formatFileSize(size)}
679 data-id="moreOptions"
680 data-cy="file-item-options-btn"
681 className={classes.moreOptionsButton}
684 data-id="moreOptions"
685 className={classes.moreOptions}
694 <div className={classes.rowEmpty}>This collection is empty</div>
699 <div className={classes.row}>
701 className={classes.loader}