Skip to content

TagSpaces is an offline, open source, document manager with tagging support

Tsn420 - refactor location manager (#1287)

Stanimirc1c04730059e
diff --git a/app/components/DirectoryTreeView.tsx b/app/components/DirectoryTreeView.tsx
index d8d992e7a..2fee3c697 100644
--- a/app/components/DirectoryTreeView.tsx
+++ b/app/components/DirectoryTreeView.tsx
@@ -16,7 +16,7 @@
*
*/
-import React, { useState, forwardRef, useImperativeHandle } from 'react';
+import React, { useState, forwardRef, useImperativeHandle, Ref } from 'react';
import Table from 'rc-table';
import FolderIcon from '@material-ui/icons/FolderOpen';
import { Location, locationType } from '-/reducers/locations';
@@ -40,53 +40,57 @@ interface Props {
handleFileMoveDrop: (item, monitor) => void;
}
-const DirectoryTreeView = forwardRef((props: Props, ref) => {
- const [data, setData] = useState(undefined);
- const [isExpanded, setExpanded] = useState(false);
+export interface DirectoryTreeViewRef {
+ changeLocation: (location: Location) => void;
+ closeLocation: () => void;
+ // removeLocation: () => void;
+}
- useImperativeHandle(ref, () => ({
- changeLocation(location: Location) {
- if (isExpanded && data[location.uuid] !== undefined) {
- /*const dirsTree = data;
- dirsTree[location.uuid] = undefined;
- setData(dirsTree);*/
- //setData(undefined);
- setExpanded(false);
- } else {
- if (location.type === locationType.TYPE_CLOUD) {
- PlatformIO.enableObjectStoreSupport(location)
- .then(() => {
- loadSubDirectories(location, 1);
- props.loadDirectoryContent(location.path || location.paths[0]);
- })
- .catch(error => {
- console.log('enableObjectStoreSupport', error);
- });
- } else if (location.type === locationType.TYPE_LOCAL) {
- PlatformIO.disableObjectStoreSupport();
- loadSubDirectories(location, 1);
- props.loadDirectoryContent(location.path || location.paths[0]);
+const DirectoryTreeView = forwardRef(
+ (props: Props, ref: Ref<DirectoryTreeViewRef>) => {
+ const [data, setData] = useState(undefined);
+ const [isExpanded, setExpanded] = useState(false);
+
+ useImperativeHandle(ref, () => ({
+ changeLocation(location: Location) {
+ if (isExpanded && data[location.uuid] !== undefined) {
+ setData(undefined); // comment this to use cached data after expand
+ setExpanded(false);
+ } else {
+ if (location.type === locationType.TYPE_CLOUD) {
+ PlatformIO.enableObjectStoreSupport(location)
+ .then(() => {
+ loadSubDirectories(location, 1);
+ props.loadDirectoryContent(location.path || location.paths[0]);
+ })
+ .catch(error => {
+ console.log('enableObjectStoreSupport', error);
+ });
+ } else if (location.type === locationType.TYPE_LOCAL) {
+ PlatformIO.disableObjectStoreSupport();
+ loadSubDirectories(location, 1);
+ props.loadDirectoryContent(location.path || location.paths[0]);
+ }
+ }
+ },
+ closeLocation() {
+ setData(undefined);
+ if (isExpanded) {
+ setExpanded(false);
}
}
- },
- closeLocation() {
- // setData(undefined);
- if (isExpanded) {
- setExpanded(false);
- }
- },
- removeLocation() {
- setData(undefined);
- }
- }));
+ /*removeLocation() {
+ setData(undefined);
+ }*/
+ }));
- /*const changeLocation = (location: Location) => {
+ /*const changeLocation = (location: Location) => {
const dirsTree = data;
dirsTree[location.uuid] = undefined;
setData(dirsTree);
};*/
- /*const renderBodyCell = props => (
+ /*const renderBodyCell = props => (
<td {...props}>
<TargetMoveFileBox
// @ts-ignore
@@ -98,302 +102,307 @@ const DirectoryTreeView = forwardRef((props: Props, ref) => {
</td>
);*/
- const renderBodyRow = props => {
- if (
- AppConfig.isElectron ||
- props.location.type !== locationType.TYPE_CLOUD
- ) {
- // DnD to S3 location is not permitted in web browser without <input> element
- return (
- <TargetTableMoveFileBox
- // @ts-ignore
- accepts={[DragItemTypes.FILE]}
- onDrop={props.handleFileMoveDrop}
- location={props.location}
- {...props}
- />
- );
- } else {
- return <tr {...props} />;
- }
- };
+ const renderBodyRow = props => {
+ if (
+ AppConfig.isElectron ||
+ props.location.type !== locationType.TYPE_CLOUD
+ ) {
+ // DnD to S3 location is not permitted in web browser without <input> element
+ return (
+ <TargetTableMoveFileBox
+ accepts={[DragItemTypes.FILE]}
+ onDrop={props.handleFileMoveDrop}
+ location={props.location}
+ {...props}
+ />
+ );
+ } else {
+ return <tr {...props} />;
+ }
+ };
- const renderNameColumnAction = field => {
- const children = (
- <span style={{ fontSize: 15, marginLeft: 5 }} title={field}>
- <FolderIcon
- style={{ marginTop: 0, marginBottom: -8 }}
- className={props.classes.icon}
- />
- {field && field.length > 25 ? field.substr(0, 25) + '...' : field}
- </span>
- );
- return {
- children,
- props: {}
+ const renderNameColumnAction = field => {
+ const children = (
+ <span style={{ fontSize: 15, marginLeft: 5 }} title={field}>
+ <FolderIcon
+ style={{ marginTop: 0, marginBottom: -8 }}
+ className={props.classes.icon}
+ />
+ {field && field.length > 25 ? field.substr(0, 25) + '...' : field}
+ </span>
+ );
+ return {
+ children,
+ props: {}
+ };
};
- };
- const handleCellClick = (record, index) => ({
- /* onContextMenu: (e) => {
+ const handleCellClick = (record, index) => ({
+ /* onContextMenu: (e) => {
this.handleFileContextMenu(e, record.path);
}, */
- onClick: () => {
- onRowClick(record);
- }
- /* onDoubleClick: (e) => {
+ onClick: () => {
+ onRowClick(record);
+ }
+ /* onDoubleClick: (e) => {
this.onRowClick(record, index, e);
} */
- });
+ });
- const onExpand = (expanded, record) => {
- // console.log('onExpand', expanded + JSON.stringify(record));
- if (expanded) {
- // this.onRowClick(record);
- loadSubDirectories(record, 1);
- }
- };
+ const onExpand = (expanded, record) => {
+ // console.log('onExpand', expanded + JSON.stringify(record));
+ if (expanded) {
+ // this.onRowClick(record);
+ loadSubDirectories(record, 1);
+ }
+ };
- const onRowClick = subDir => {
- if (subDir.type === locationType.TYPE_CLOUD) {
- PlatformIO.enableObjectStoreSupport(subDir)
- .then(() => {
- loadSubDirectories(subDir, 1);
- props.loadDirectoryContent(subDir.path);
- })
- .catch(error => {
- console.log('enableObjectStoreSupport', error);
- });
- } else if (subDir.type === locationType.TYPE_LOCAL) {
- PlatformIO.disableObjectStoreSupport();
- loadSubDirectories(subDir, 1);
- props.loadDirectoryContent(subDir.path);
- }
- };
+ const onRowClick = subDir => {
+ if (subDir.type === locationType.TYPE_CLOUD) {
+ PlatformIO.enableObjectStoreSupport(subDir)
+ .then(() => {
+ loadSubDirectories(subDir, 1);
+ props.loadDirectoryContent(subDir.path);
+ })
+ .catch(error => {
+ console.log('enableObjectStoreSupport', error);
+ });
+ } else if (subDir.type === locationType.TYPE_LOCAL) {
+ PlatformIO.disableObjectStoreSupport();
+ loadSubDirectories(subDir, 1);
+ props.loadDirectoryContent(subDir.path);
+ }
+ };
- const columns = [
- {
- title: undefined,
- dataIndex: 'name',
- key: 'name',
- width: '80%',
- render: renderNameColumnAction,
- onCell: handleCellClick
- }
- ];
+ const columns = [
+ {
+ title: undefined,
+ dataIndex: 'name',
+ key: 'name',
+ width: '80%',
+ render: renderNameColumnAction,
+ onCell: handleCellClick
+ }
+ ];
- const loadSubDirectories = (location: Location, deepLevel: number) => {
- const subFolder = {
- ...(location.accessKeyId && { accessKeyId: location.accessKeyId }),
- ...(location.bucketName && { bucketName: location.bucketName }),
- ...(location.region && { region: location.region }),
- ...(location.secretAccessKey && {
- secretAccessKey: location.secretAccessKey
- }),
- uuid: location.uuid,
- name: location.name,
- type: location.type,
- path: location.path || location.paths[0]
- };
- getDirectoriesTree(subFolder, deepLevel)
- .then(children => {
- if (children instanceof Array) {
- if (location.uuid) {
- const dirsTree = {}; // this.state.dirs; (uncomment to allow open multiple Locations folders) //TODO set settings for this
- if (location.path === undefined) {
- // location
- dirsTree[location.uuid] = children;
- } else {
- const dirsCopy = getMergedDirsCopy(location.path, children);
- if (dirsCopy) {
- dirsTree[location.uuid] = dirsCopy;
+ const loadSubDirectories = (location: Location, deepLevel: number) => {
+ const subFolder = {
+ ...(location.accessKeyId && { accessKeyId: location.accessKeyId }),
+ ...(location.bucketName && { bucketName: location.bucketName }),
+ ...(location.region && { region: location.region }),
+ ...(location.secretAccessKey && {
+ secretAccessKey: location.secretAccessKey
+ }),
+ uuid: location.uuid,
+ name: location.name,
+ type: location.type,
+ path: location.path || location.paths[0]
+ };
+ getDirectoriesTree(subFolder, deepLevel)
+ .then(children => {
+ if (children instanceof Array) {
+ if (location.uuid) {
+ const dirsTree = {}; // this.state.dirs; (uncomment to allow open multiple Locations folders) //TODO set settings for this
+ if (location.path === undefined) {
+ // location
+ dirsTree[location.uuid] = children;
} else {
- // eslint-disable-next-line no-param-reassign
- location.children = children;
- dirsTree[location.uuid] = [location];
+ const dirsCopy = getMergedDirsCopy(location.path, children);
+ if (dirsCopy) {
+ dirsTree[location.uuid] = dirsCopy;
+ } else {
+ // eslint-disable-next-line no-param-reassign
+ location.children = children;
+ dirsTree[location.uuid] = [location];
+ }
}
+ setData(dirsTree);
+ setExpanded(true);
}
- setData(dirsTree);
- setExpanded(true);
+ } else if (location.path === undefined) {
+ // if is Location
+ //setData({});
}
- } else if (location.path === undefined) {
- // if is Location
- //setData({});
- }
- return true;
- })
- .catch(error => {
- console.log('loadSubDirectories', error);
- });
- };
+ return true;
+ })
+ .catch(error => {
+ console.log('loadSubDirectories', error);
+ });
+ };
- type SubFolder = {
- accessKeyId?: string;
- bucketName?: string;
- region?: string;
- secretAccessKey?: string;
- uuid: string;
- name: string;
- type: string;
- path: string;
- children?: Array<SubFolder>;
- };
+ type SubFolder = {
+ accessKeyId?: string;
+ bucketName?: string;
+ region?: string;
+ secretAccessKey?: string;
+ uuid: string;
+ name: string;
+ type: string;
+ path: string;
+ children?: Array<SubFolder>;
+ };
- const getDirectoriesTree = (subFolder: SubFolder, deepLevel: number) =>
- // const { settings } = getState();
- PlatformIO.listDirectoryPromise(subFolder.path, false)
- // @ts-ignore
- .then(dirEntries => {
- const directoryContent = [];
- dirEntries.map(entry => {
- if (
- entry.name === AppConfig.metaFolder ||
- entry.name.endsWith('/' + AppConfig.metaFolder) ||
- (!props.showUnixHiddenEntries && entry.name.startsWith('.'))
- ) {
- return true;
- }
- // const enhancedEntry = enhanceEntry(entry);
- if (!entry.isFile) {
- // eslint-disable-next-line no-param-reassign
- if (subFolder.accessKeyId) {
- entry.accessKeyId = subFolder.accessKeyId;
- }
- if (subFolder.bucketName) {
- entry.bucketName = subFolder.bucketName;
+ const getDirectoriesTree = (subFolder: SubFolder, deepLevel: number) =>
+ // const { settings } = getState();
+ PlatformIO.listDirectoryPromise(subFolder.path, false)
+ // @ts-ignore
+ .then(dirEntries => {
+ const directoryContent = [];
+ dirEntries.map(entry => {
+ if (
+ entry.name === AppConfig.metaFolder ||
+ entry.name.endsWith('/' + AppConfig.metaFolder) ||
+ (!props.showUnixHiddenEntries && entry.name.startsWith('.'))
+ ) {
+ return true;
}
- if (subFolder.region) {
- entry.region = subFolder.region;
+ // const enhancedEntry = enhanceEntry(entry);
+ if (!entry.isFile) {
+ // eslint-disable-next-line no-param-reassign
+ if (subFolder.accessKeyId) {
+ entry.accessKeyId = subFolder.accessKeyId;
+ }
+ if (subFolder.bucketName) {
+ entry.bucketName = subFolder.bucketName;
+ }
+ if (subFolder.region) {
+ entry.region = subFolder.region;
+ }
+ if (subFolder.secretAccessKey) {
+ entry.secretAccessKey = subFolder.secretAccessKey;
+ }
+ entry.uuid = subFolder.uuid;
+ entry.type = subFolder.type;
+ directoryContent.push(entry);
}
- if (subFolder.secretAccessKey) {
- entry.secretAccessKey = subFolder.secretAccessKey;
+ return true;
+ });
+ if (directoryContent.length > 0) {
+ // eslint-disable-next-line no-param-reassign
+ subFolder.children = directoryContent;
+ if (deepLevel > 0) {
+ const promisesArr = [];
+ directoryContent.map(directory =>
+ promisesArr.push(getDirectoriesTree(directory, deepLevel - 1))
+ );
+ return Promise.all(promisesArr);
}
- entry.uuid = subFolder.uuid;
- entry.type = subFolder.type;
- directoryContent.push(entry);
}
- return true;
+ return subFolder;
+ })
+ .catch(error => {
+ console.log('getDirectoriesTree', error);
});
- if (directoryContent.length > 0) {
- // eslint-disable-next-line no-param-reassign
- subFolder.children = directoryContent;
- if (deepLevel > 0) {
- const promisesArr = [];
- directoryContent.map(directory =>
- promisesArr.push(getDirectoriesTree(directory, deepLevel - 1))
- );
- return Promise.all(promisesArr);
- }
- }
- return subFolder;
- })
- .catch(error => {
- console.log('getDirectoriesTree', error);
- });
- /**
- * https://codereview.stackexchange.com/questions/47932/recursion-vs-iteration-of-tree-structure
- * Dynamically set property of nested object
- * */
- const getMergedDirsCopy = (path: string, arrChildren: Array<SubFolder>) => {
- const entries = Object.entries(data);
- for (const [uuid, arrSubDirs] of entries) {
- const arr: number = (arrSubDirs as Array<any>).length;
- let a;
- for (a = 0; a < arr; a += 1) {
- if (path === arrSubDirs[a].path) {
- const copyObj = [...data[uuid]];
- copyObj[a].children = arrChildren;
- return copyObj;
- }
- if (arrSubDirs[a].children !== undefined) {
- const stack = [
- {
- depth: 0,
- element: arrSubDirs[a],
- propPath: ''
- }
- ];
- let stackItem = 0;
- let current;
- let children;
- let depth;
- let stackPath;
- let propPath = a + '.children';
+ /**
+ * https://codereview.stackexchange.com/questions/47932/recursion-vs-iteration-of-tree-structure
+ * Dynamically set property of nested object
+ * */
+ const getMergedDirsCopy = (path: string, arrChildren: Array<SubFolder>) => {
+ if (!data) {
+ return arrChildren;
+ }
+ const entries = Object.entries(data);
+ for (const [uuid, arrSubDirs] of entries) {
+ const arr: number = (arrSubDirs as Array<any>).length;
+ let a;
+ for (a = 0; a < arr; a += 1) {
+ if (path === arrSubDirs[a].path) {
+ const copyObj = [...data[uuid]];
+ copyObj[a].children = arrChildren;
+ return copyObj;
+ }
+ if (arrSubDirs[a].children !== undefined) {
+ const stack = [
+ {
+ depth: 0,
+ element: arrSubDirs[a],
+ propPath: ''
+ }
+ ];
+ let stackItem = 0;
+ let current;
+ let children;
+ let depth;
+ let stackPath;
+ let propPath = a + '.children';
- while ((current = stack[stackItem++])) {
- // get the arguments
- stackPath = current.propPath;
- depth = current.depth;
- current = current.element;
- children = current.children;
- if (children !== undefined) {
- const len = children.length;
- for (let i = 0; i < len; i++) {
- if (path === children[i].path) {
- propPath =
- propPath +
- '.' +
- (stackPath ? stackPath + '.' : '') +
- i +
- '.children';
- const copyObj = [...data[uuid]];
+ while ((current = stack[stackItem++])) {
+ // get the arguments
+ stackPath = current.propPath;
+ depth = current.depth;
+ current = current.element;
+ children = current.children;
+ if (children !== undefined) {
+ const len = children.length;
+ for (let i = 0; i < len; i++) {
+ if (path === children[i].path) {
+ propPath =
+ propPath +
+ '.' +
+ (stackPath ? stackPath + '.' : '') +
+ i +
+ '.children';
+ const copyObj = [...data[uuid]];
- let schema = copyObj; // a moving reference to internal objects within obj
- const pList = propPath.split('.');
- const leng = pList.length;
- for (let c = 0; c < leng - 1; c++) {
- const elem = pList[c];
- if (!schema[elem]) schema[elem] = {};
- schema = schema[elem];
+ let schema = copyObj; // a moving reference to internal objects within obj
+ const pList = propPath.split('.');
+ const leng = pList.length;
+ for (let c = 0; c < leng - 1; c++) {
+ const elem = pList[c];
+ if (!schema[elem]) schema[elem] = {};
+ schema = schema[elem];
+ }
+ schema[pList[leng - 1]] = arrChildren;
+ return copyObj;
}
- schema[pList[leng - 1]] = arrChildren;
- return copyObj;
- }
- stack.push({
- // pass args via object or array
- element: children[i],
- depth: depth + 1,
- propPath: (stackPath ? stackPath + '.' : '') + i + '.children'
- });
+ stack.push({
+ // pass args via object or array
+ element: children[i],
+ depth: depth + 1,
+ propPath:
+ (stackPath ? stackPath + '.' : '') + i + '.children'
+ });
+ }
}
}
}
}
}
- }
- };
+ };
- if (isExpanded && data != undefined) {
- // @ts-ignore
- return (
- <Table
- // defaultExpandAllRows
- // className={classes.locationListArea}
- components={{
- // header: { cell: this.renderHeaderRow },
- body: { row: renderBodyRow }
- }}
- showHeader={false}
- // className="table"
- rowKey="path"
- data={data[props.location.uuid]}
- columns={columns}
- indentSize={20}
- expandable={{ onExpand: onExpand }}
- // expandIcon={this.CustomExpandIcon}
- // expandIconAsCell
- // @ts-ignore
- onRow={(record, index) => ({
- index,
- location: record,
- handleFileMoveDrop: props.handleFileMoveDrop
- })}
- />
- );
+ if (isExpanded && data != undefined) {
+ // @ts-ignore
+ return (
+ <Table
+ key={props.location.uuid}
+ // defaultExpandAllRows
+ // className={classes.locationListArea}
+ components={{
+ // header: { cell: this.renderHeaderRow },
+ body: { row: renderBodyRow }
+ }}
+ showHeader={false}
+ // className="table"
+ rowKey="path"
+ data={data[props.location.uuid]}
+ columns={columns}
+ indentSize={20}
+ expandable={{ onExpand: onExpand }}
+ // expandIcon={this.CustomExpandIcon}
+ // expandIconAsCell
+ // @ts-ignore
+ onRow={(record, index) => ({
+ index,
+ location: record,
+ handleFileMoveDrop: props.handleFileMoveDrop
+ })}
+ />
+ );
+ }
+ return null;
}
- return null;
-});
+);
export default DirectoryTreeView;
diff --git a/app/components/LocationManager.tsx b/app/components/LocationManager.tsx
index 91fd65f6b..274ba90f6 100644
--- a/app/components/LocationManager.tsx
+++ b/app/components/LocationManager.tsx
@@ -1,4 +1,3 @@
-// @ts-nocheck @ts-ignore
/**
* TagSpaces - universal file and folder organizer
* Copyright (C) 2017-present TagSpaces UG (haftungsbeschraenkt)
@@ -17,36 +16,14 @@
*
*/
-import React from 'react';
+import React, { useEffect, useState } from 'react';
import { bindActionCreators } from 'redux';
import uuidv1 from 'uuid';
-import classNames from 'classnames';
import { connect } from 'react-redux';
import { withStyles } from '@material-ui/core/styles';
import List from '@material-ui/core/List';
-import ListItem from '@material-ui/core/ListItem';
-import ListItemIcon from '@material-ui/core/ListItemIcon';
-import ListItemText from '@material-ui/core/ListItemText';
-import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction';
-import MoreVertIcon from '@material-ui/icons/MoreVert';
-import Menu from '@material-ui/core/Menu';
-import MenuItem from '@material-ui/core/MenuItem';
-import Typography from '@material-ui/core/Typography';
-import IconButton from '@material-ui/core/IconButton';
import Button from '@material-ui/core/Button';
-import LocationIcon from '@material-ui/icons/WorkOutline';
-import CloudLocationIcon from '@material-ui/icons/CloudQueue';
-import EditIcon from '@material-ui/icons/Edit';
-import RefreshIcon from '@material-ui/icons/Refresh';
-import DeleteIcon from '@material-ui/icons/DeleteForever';
-import CloseIcon from '@material-ui/icons/Close';
-import DefaultLocationIcon from '@material-ui/icons/Highlight';
-import ArrowDownwardIcon from '@material-ui/icons/ArrowDownward';
-import ArrowUpwardIcon from '@material-ui/icons/ArrowUpward';
-import OpenFolderNativelyIcon from '@material-ui/icons/Launch';
-import { Progress } from 'aws-sdk/clients/s3';
import styles from './SidePanels.css';
-import DirectoryMenu from './menus/DirectoryMenu';
import LocationManagerMenu from './menus/LocationManagerMenu';
import ConfirmDialog from './dialogs/ConfirmDialog';
import SelectDirectoryDialog from './dialogs/SelectDirectoryDialog';
@@ -58,22 +35,13 @@ import {
locationType,
Location
} from '../reducers/locations';
-import {
- actions as AppActions,
- getCurrentLocationId,
- isReadOnlyMode
-} from '../reducers/app';
-import { actions as LocationIndexActions } from '../reducers/location-index';
-import { getPerspectives, getShowUnixHiddenEntries } from '-/reducers/settings';
+import { actions as AppActions } from '../reducers/app';
+import { getPerspectives } from '-/reducers/settings';
import i18n from '../services/i18n';
import AppConfig from '../config';
import PlatformIO from '../services/platform-io';
-import TargetMoveFileBox from './TargetMoveFileBox';
-import DragItemTypes from './DragItemTypes';
-import IOActions from '../reducers/io-actions';
-import DirectoryTreeView from '-/components/DirectoryTreeView';
import LoadingLazy from '-/components/LoadingLazy';
-import { FileSystemEntry } from '-/services/utils-io';
+import LocationView from '-/components/LocationView';
const CreateLocationDialog = React.lazy(() =>
import(
@@ -99,64 +67,16 @@ const EditLocationDialogAsync = props => (
interface Props {
classes: any;
+ style: any;
locations: Array<Location>;
perspectives: Array<Object>;
- currentLocationId: string;
- isReadOnlyMode: boolean;
hideDrawer: () => void;
- openFsEntry: (fsEntry: FileSystemEntry) => void;
- reflectCreateEntries: (fsEntries: Array<FileSystemEntry>) => void;
openURLExternally: (path: string) => void;
- loadDirectoryContent: (path: string) => void;
- openLocation: (location: Location) => void;
openFileNatively: (path: string) => void;
- openDirectory: (path: string) => void;
toggleOpenLinkDialog: () => void;
- showInFileManager: (path: string) => void;
- createDirectoryIndex: (
- path: string,
- fullTextIndex: boolean,
- isCurrentLocation: boolean
- ) => void;
addLocation: (location: Location, openAfterCreate?: boolean) => void;
editLocation: () => void;
- moveLocationUp: (locationId: string) => void;
- moveLocationDown: (locationId: string) => void;
- closeLocation: (locationId: string) => void;
removeLocation: (location: Location) => void;
- reflectCreateEntry: (path: string, isFile: boolean) => void;
- deleteDirectory: (directoryPath: string) => void;
- showUnixHiddenEntries: boolean;
- showNotification: (
- text: string,
- notificationType: string,
- autohide: boolean
- ) => void;
- moveFiles: (files: Array<string>, destination: string) => void;
- uploadFiles: (
- files: Array<string>,
- destination: string,
- onUploadProgress?: (progress: Progress, response: any) => void
- ) => Promise<Array<FileSystemEntry>>;
- toggleUploadDialog: () => void;
- resetProgress: () => void;
-}
-
-interface State {
- locationDirectoryContextMenuAnchorEl?: Object | null;
- locationContextMenuOpened?: boolean;
- directoryContextMenuAnchorEl?: Object | null;
- directoryContextMenuOpened?: boolean;
- selectedLocation: Location | null;
- selectedDirectoryPath?: string | null;
- isCreateLocationDialogOpened?: boolean;
- isEditLocationDialogOpened?: boolean;
- isDeleteLocationDialogOpened?: boolean;
- isSelectDirectoryDialogOpened?: boolean;
- createLocationDialogKey: string;
- isCreateDirectoryDialogOpened?: boolean;
- locationManagerMenuOpened: boolean;
- locationManagerMenuAnchorEl: Object | null;
}
type SubFolder = {
@@ -166,36 +86,38 @@ type SubFolder = {
children?: Array<SubFolder>;
};
-class LocationManager extends React.Component<Props, State> {
- constructor(props) {
- super(props);
- this.directoryTreeRef = [];
- }
-
- state = {
- locationDirectoryContextMenuAnchorEl: null,
- locationContextMenuOpened: false,
- directoryContextMenuAnchorEl: null,
- directoryContextMenuOpened: false,
- selectedLocation: null,
- selectedDirectoryPath: null,
- isCreateLocationDialogOpened: false,
- isEditLocationDialogOpened: false,
- isDeleteLocationDialogOpened: false,
- isCreateDirectoryDialogOpened: false,
- isSelectDirectoryDialogOpened: false,
- locationManagerMenuOpened: false,
- locationManagerMenuAnchorEl: null,
- createLocationDialogKey: uuidv1(),
- editLocationDialogKey: uuidv1()
- };
-
- componentDidMount() {
- if (this.props.locations.length < 1) {
+const LocationManager = (props: Props) => {
+ const [selectedLocation, setSelectedLocation] = useState<Location>(null);
+ const [selectedDirectoryPath, setSelectedDirectoryPath] = useState<string>(
+ null
+ );
+ const [
+ isCreateLocationDialogOpened,
+ setCreateLocationDialogOpened
+ ] = useState<boolean>(false);
+ const [isEditLocationDialogOpened, setEditLocationDialogOpened] = useState<
+ boolean
+ >(false);
+ const [
+ isDeleteLocationDialogOpened,
+ setDeleteLocationDialogOpened
+ ] = useState<boolean>(false);
+ const [
+ isCreateDirectoryDialogOpened,
+ setCreateDirectoryDialogOpened
+ ] = useState<boolean>(false);
+ const [
+ isSelectDirectoryDialogOpened,
+ setSelectDirectoryDialogOpened
+ ] = useState<boolean>(false);
+
+ useEffect(() => {
+ if (props.locations.length < 1) {
+ // init locations
const devicePaths = PlatformIO.getDevicePaths();
Object.keys(devicePaths).forEach(key => {
- this.props.addLocation(
+ props.addLocation(
{
uuid: uuidv1(),
type: locationType.TYPE_LOCAL,
@@ -209,642 +131,153 @@ class LocationManager extends React.Component<Props, State> {
);
});
}
- }
-
- handleCloseDialogs = () => {
- this.setState({
- isCreateLocationDialogOpened: false,
- isEditLocationDialogOpened: false,
- isDeleteLocationDialogOpened: false,
- selectedDirectoryPath: undefined
- });
- };
-
- showCreateLocationDialog = () => {
- this.handleRequestCloseContextMenus();
- this.setState({ isCreateLocationDialogOpened: true });
- };
-
- closeChromeExtDialog = () => {
- this.handleRequestCloseContextMenus();
- this.setState({
- isCreateLocationDialogOpened: false,
- isEditLocationDialogOpened: false,
- selectedDirectoryPath: undefined
- });
- };
-
- indexLocation = () => {
- this.handleRequestCloseContextMenus();
- const { selectedLocation } = this.state;
- const { currentLocationId, createDirectoryIndex } = this.props;
- const isCurrentLocation =
- selectedLocation &&
- selectedLocation.uuid &&
- selectedLocation.uuid === currentLocationId;
-
- if (selectedLocation.type === locationType.TYPE_CLOUD) {
- PlatformIO.enableObjectStoreSupport(selectedLocation)
- .then(() => {
- createDirectoryIndex(
- selectedLocation.path || selectedLocation.paths[0],
- selectedLocation.fullTextIndex,
- isCurrentLocation
- );
- return true;
- })
- .catch(() => {
- PlatformIO.disableObjectStoreSupport();
- });
- } else if (selectedLocation.type === locationType.TYPE_LOCAL) {
- PlatformIO.disableObjectStoreSupport();
- createDirectoryIndex(
- selectedLocation.path || selectedLocation.paths[0],
- selectedLocation.fullTextIndex,
- isCurrentLocation
- );
- }
- };
-
- moveLocationUp = () => {
- this.handleRequestCloseContextMenus();
- if (this.state.selectedLocation && this.state.selectedLocation.uuid) {
- this.props.moveLocationUp(this.state.selectedLocation.uuid);
- }
- };
-
- moveLocationDown = () => {
- this.handleRequestCloseContextMenus();
- if (this.state.selectedLocation && this.state.selectedLocation.uuid) {
- this.props.moveLocationDown(this.state.selectedLocation.uuid);
- }
- };
+ }, []); // props.locations]);
- showInFileManager = () => {
- this.handleRequestCloseContextMenus();
- this.props.openDirectory(
- this.state.selectedLocation.path || this.state.selectedLocation.pathS[0]
- );
+ const createNewDirectoryExt = (path: string) => {
+ setCreateDirectoryDialogOpened(true);
+ setSelectedDirectoryPath(path);
};
- closeLocation = () => {
- this.handleRequestCloseContextMenus();
- if (this.state.selectedLocation && this.state.selectedLocation.uuid) {
- this.props.closeLocation(this.state.selectedLocation.uuid);
- this.directoryTreeRef[this.state.selectedLocation.uuid].closeLocation();
- // this.directoryTreeRef[this.state.selectedLocation.uuid] = undefined;
- // this.directoryTreeRef[this.state.selectedLocation.uuid].closeLocation();
- /* this.setState({
- dirs: {}
- }); */
- }
+ const showSelectDirectoryDialog = () => {
+ setSelectDirectoryDialogOpened(true);
+ setSelectedDirectoryPath('');
};
- showEditLocationDialog = () => {
- this.handleRequestCloseContextMenus();
- this.setState({ isEditLocationDialogOpened: true });
+ const chooseDirectoryPath = (currentPath: string) => {
+ setSelectDirectoryDialogOpened(true);
+ setSelectedDirectoryPath(currentPath);
};
- showDeleteLocationDialog = () => {
- this.handleRequestCloseContextMenus();
- this.setState({ isDeleteLocationDialogOpened: true });
- };
-
- handleDirectoryContextMenu = (
- event: React.ChangeEvent<HTMLInputElement>,
- directoryPath: string
- ) => {
- this.setState({
- directoryContextMenuOpened: true,
- directoryContextMenuAnchorEl: event.currentTarget,
- selectedDirectoryPath: directoryPath
- });
- };
-
- toggleDirectoryMenuClose = (event: React.ChangeEvent<HTMLInputElement>) => {
- const opened = this.state.directoryContextMenuOpened;
- this.setState({
- directoryContextMenuOpened: !opened,
- directoryContextMenuAnchorEl: event ? event.currentTarget : null
- });
- };
-
- createNewDirectoryExt = (path: string) => {
- this.setState({
- isCreateDirectoryDialogOpened: true,
- selectedDirectoryPath: path
- });
- };
-
- closeNewDirectoryDialog = () => {
- this.setState({ isCreateDirectoryDialogOpened: false });
- };
-
- showSelectDirectoryDialog = () => {
- this.setState({
- isSelectDirectoryDialogOpened: true,
- selectedDirectoryPath: ''
- });
- };
-
- chooseDirectoryPath = (currentPath: string) => {
- this.setState({
- isSelectDirectoryDialogOpened: false,
- selectedDirectoryPath: currentPath
- });
- };
-
- closeSelectDirectoryExtDialog = () => {
- this.setState({ isSelectDirectoryDialogOpened: false });
- };
-
- handleRequestCloseContextMenus = () => {
- this.setState({
- directoryContextMenuOpened: false,
- directoryContextMenuAnchorEl: null,
- locationContextMenuOpened: false,
- locationDirectoryContextMenuAnchorEl: null
- // selectedLocation: null,
- // selectedDirectoryPath: null,
- });
- };
-
- handleLocationContextMenuClick = (event: any, location: Location) => {
- event.preventDefault();
- event.stopPropagation();
- this.setState({
- locationContextMenuOpened: true,
- locationDirectoryContextMenuAnchorEl: event.currentTarget,
- selectedLocation: location
- });
- };
-
- // todo https://stackoverflow.com/questions/37949981/call-child-method-from-parent
- // const directoryTreeRef = useRef();
-
- handleLocationClick = (location: Location) => {
- this.directoryTreeRef[location.uuid].changeLocation(location);
- if (location.uuid === this.props.currentLocationId) {
- this.props.loadDirectoryContent(location.path || location.paths[0]);
- } else {
- // this.directoryTreeRef[location.uuid].loadSubDir(location, 1);
- this.props.setSelectedEntries([]);
- this.props.openLocation(location);
- if (this.props.hideDrawer) {
- this.props.hideDrawer();
- }
- }
-
- // const grid = document.querySelector('[data-tid="perspectiveGridFileTable"]');
- // const firstGridItem = grid.querySelector('div');
- // if (isObj(firstGridItem)) {
- // firstGridItem.parentNode.scrollTop = target.offsetTop;
- // }
- };
-
- reloadDirectory = () => {
- this.handleRequestCloseContextMenus();
- if (this.state.selectedDirectoryPath) {
- this.props.loadDirectoryContent(this.state.selectedDirectoryPath);
- }
- };
-
- resetState = dialogKey => {
- // @ts-ignore
- this.setState({
- [dialogKey]: uuidv1()
- });
- };
-
- /**
- * https://github.com/react-component/table/blob/master/examples/react-dnd.js
- * @param item
- * @param monitor
- */
- handleFileMoveDrop = (item, monitor) => {
- if (monitor) {
- const { path, selectedEntries } = monitor.getItem();
- const arrPath = [];
- if (selectedEntries && selectedEntries.length > 0) {
- selectedEntries.map(entry => {
- arrPath.push(entry.path);
- return true;
- });
- } else {
- arrPath.push(path);
- }
- if (this.props.isReadOnlyMode) {
- this.props.showNotification(
- i18n.t('core:dndDisabledReadOnlyMode'),
- 'error',
- true
- );
- return;
- }
- if (!AppConfig.isWin && !path.startsWith('/')) {
- this.props.showNotification(
- i18n.t('Moving file not possible'),
- 'error',
- true
- );
- return;
- }
- if (AppConfig.isWin && !path.substr(1).startsWith(':')) {
- this.props.showNotification(
- i18n.t('Moving file not possible'),
- 'error',
- true
- );
- return;
- }
- let targetPath = item.path;
- const targetLocation = item.location;
- if (targetPath === undefined) {
- targetPath = targetLocation.path;
- }
- /* if (item.children && item.children.props && item.children.props.path) {
- targetPath = item.children.props.path;
- } else {
- targetPath = item.children[1].props.record.path;
- } */
- if (monitor && targetPath !== undefined && targetLocation !== undefined) {
- // TODO handle monitor -> isOver and change folder icon
- console.log('Dropped files: ' + path);
- if (targetLocation.type === locationType.TYPE_CLOUD) {
- PlatformIO.enableObjectStoreSupport(targetLocation)
- .then(() => {
- this.props.resetProgress();
- this.props
- .uploadFiles(arrPath, targetPath, this.props.onUploadProgress)
- .then((fsEntries: Array<FileSystemEntry>) => {
- this.props.reflectCreateEntries(fsEntries);
- return true;
- })
- .catch(error => {
- console.log('uploadFiles', error);
- });
- this.props.toggleUploadDialog();
- return true;
- })
- .catch(error => {
- console.log('enableObjectStoreSupport', error);
- });
- } else if (targetLocation.type === locationType.TYPE_LOCAL) {
- PlatformIO.disableObjectStoreSupport();
- this.props.moveFiles(arrPath, targetPath);
- }
- this.props.setSelectedEntries([]);
- }
- }
- };
-
- // <Tooltip id="tooltip-icon" title={i18n.t('core:moreOperations')} placement="bottom"></Tooltip>
- renderLocation = (location: Location) => {
- const isCloudLocation = location.type === locationType.TYPE_CLOUD;
-
- return (
- <div key={location.uuid}>
- <ListItem
- data-tid={'location_' + location.name.replace(/ /g, '_')}
- className={
- this.props.currentLocationId === location.uuid
- ? this.props.classes.listItemSelected
- : this.props.classes.listItem
- }
- title={
- location.isDefault
- ? i18n.t('core: thisIsStartupLocation') + ' : ' + location.path ||
- location.paths[0]
- : location.path || location.paths[0]
- }
- button
- onClick={() => this.handleLocationClick(location)}
- onContextMenu={event =>
- this.handleLocationContextMenuClick(event, location)
- }
- >
- <ListItemIcon
- // onClick={(e) => {
- // e.preventDefault();
- // this.loadSubDirectories(location, 1);
- // }}
- style={{ minWidth: 'auto' }}
- >
- {isCloudLocation ? (
- <CloudLocationIcon className={this.props.classes.icon} />
- ) : (
- <LocationIcon className={this.props.classes.icon} />
- )}
- </ListItemIcon>
-
- {isCloudLocation && !AppConfig.isElectron ? (
- <div style={{ maxWidth: 250 }}>
- <Typography
- variant="inherit"
- style={{ paddingLeft: 5, paddingRight: 5 }}
- className={this.props.classes.header}
- data-tid="locationTitleElement"
- noWrap
- >
- {location.name}
- </Typography>
- </div>
- ) : (
- <TargetMoveFileBox
- accepts={[DragItemTypes.FILE]}
- onDrop={this.handleFileMoveDrop}
- path={location.path || location.paths[0]}
- location={location}
- >
- <div style={{ maxWidth: 250 }}>
- <Typography
- variant="inherit"
- style={{ paddingLeft: 5, paddingRight: 5 }}
- className={this.props.classes.header}
- data-tid="locationTitleElement"
- noWrap
- >
- {location.name}
- </Typography>
- </div>
- </TargetMoveFileBox>
- )}
- {!AppConfig.locationsReadOnly && (
- <ListItemSecondaryAction>
- <IconButton
- aria-label={i18n.t('core:options')}
- aria-haspopup="true"
- edge="end"
- data-tid={'locationMoreButton_' + location.name}
- onClick={event =>
- this.handleLocationContextMenuClick(event, location)
- }
- onContextMenu={event =>
- this.handleLocationContextMenuClick(event, location)
- }
- >
- {location.isDefault && (
- <DefaultLocationIcon data-tid="startupIndication" />
- )}
- <MoreVertIcon />
- </IconButton>
- </ListItemSecondaryAction>
- )}
- </ListItem>
- <DirectoryTreeView
- ref={dirTree => {
- this.directoryTreeRef[location.uuid] = dirTree;
+ const { classes } = props;
+ return (
+ <div className={classes.panel} style={props.style}>
+ <CustomLogo />
+
+ <LocationManagerMenu
+ classes={classes}
+ openURLExternally={props.openURLExternally}
+ showCreateLocationDialog={() => {
+ setCreateLocationDialogOpened(true);
+ }}
+ toggleOpenLinkDialog={props.toggleOpenLinkDialog}
+ />
+ {!AppConfig.locationsReadOnly && (
+ <div
+ style={{
+ width: '100%',
+ textAlign: 'center',
+ marginBottom: 10
}}
- classes={this.props.classes}
- loadDirectoryContent={this.props.loadDirectoryContent}
- location={location}
- showUnixHiddenEntries={this.props.showUnixHiddenEntries}
- moveFiles={this.props.moveFiles}
- handleFileMoveDrop={this.handleFileMoveDrop}
- />
- </div>
- );
- };
-
- handleLocationManagerMenu = (event: any) => {
- this.setState({
- locationManagerMenuOpened: true,
- locationManagerMenuAnchorEl: event.currentTarget
- });
- };
-
- handleCloseLocationManagerMenu = () => {
- this.setState({ locationManagerMenuOpened: false });
- };
-
- render() {
- const { classes } = this.props;
- return (
- <div className={classes.panel} style={this.props.style}>
- <CustomLogo />
- <div className={classes.toolbar}>
- <Typography
- className={classNames(classes.panelTitle, classes.header)}
- variant="subtitle1"
- >
- {i18n.t('core:locationManager')}
- </Typography>
- <IconButton
- data-tid="locationManagerMenu"
- onClick={this.handleLocationManagerMenu}
+ >
+ <Button
+ data-tid="createNewLocation"
+ onClick={() => setCreateLocationDialogOpened(true)}
+ title={i18n.t('core:createLocationTitle')}
+ className={classes.mainActionButton}
+ size="small"
+ variant="outlined"
+ color="primary"
+ style={{ width: '95%' }}
>
- <MoreVertIcon />
- </IconButton>
+ {/* <CreateLocationIcon className={classNames(classes.leftIcon)} /> */}
+ {i18n.t('core:createLocationTitle')}
+ </Button>
</div>
- <LocationManagerMenu
- anchorEl={this.state.locationManagerMenuAnchorEl}
- open={this.state.locationManagerMenuOpened}
- onClose={this.handleCloseLocationManagerMenu}
- openURLExternally={this.props.openURLExternally}
- showCreateLocationDialog={this.showCreateLocationDialog}
- toggleOpenLinkDialog={this.props.toggleOpenLinkDialog}
- />
- {!AppConfig.locationsReadOnly && (
- <div style={{ width: '100%', textAlign: 'center', marginBottom: 10 }}>
- <Button
- data-tid="createNewLocation"
- onClick={this.showCreateLocationDialog}
- title={i18n.t('core:createLocationTitle')}
- className={classes.mainActionButton}
- size="small"
- variant="outlined"
- color="primary"
- style={{ width: '95%' }}
- >
- {/* <CreateLocationIcon className={classNames(classes.leftIcon)} /> */}
- {i18n.t('core:createLocationTitle')}
- </Button>
- </div>
+ )}
+ <div>
+ {isCreateLocationDialogOpened && (
+ <CreateLocationDialogAsync
+ open={isCreateLocationDialogOpened}
+ onClose={() => setCreateLocationDialogOpened(false)}
+ addLocation={props.addLocation}
+ showSelectDirectoryDialog={showSelectDirectoryDialog}
+ />
)}
- <div>
- {this.state.isCreateLocationDialogOpened && (
- <CreateLocationDialogAsync
- key={this.state.createLocationDialogKey}
- resetState={this.resetState}
- open={this.state.isCreateLocationDialogOpened}
- onClose={this.handleCloseDialogs}
- addLocation={this.props.addLocation}
- showSelectDirectoryDialog={this.showSelectDirectoryDialog}
- />
- )}
- {this.state.isEditLocationDialogOpened && (
- <EditLocationDialogAsync
- key={this.state.editLocationDialogKey}
- resetState={this.resetState}
- open={this.state.isEditLocationDialogOpened}
- onClose={this.handleCloseDialogs}
- location={this.state.selectedLocation}
- editLocation={this.props.editLocation}
- showSelectDirectoryDialog={this.showSelectDirectoryDialog}
- selectedDirectoryPath={this.state.selectedDirectoryPath}
- />
- )}
- {this.state.isDeleteLocationDialogOpened && (
- <ConfirmDialog
- open={this.state.isDeleteLocationDialogOpened}
- onClose={this.handleCloseDialogs}
- title={i18n.t('core:deleteLocationTitleAlert')}
- content={i18n.t('core:deleteLocationContentAlert', {
- locationName: this.state.selectedLocation
- ? this.state.selectedLocation.name
- : ''
- })}
- confirmCallback={result => {
- if (result && this.state.selectedLocation) {
- this.props.removeLocation(this.state.selectedLocation);
- this.directoryTreeRef[
- this.state.selectedLocation.uuid
- ].removeLocation();
- }
- }}
- cancelDialogTID="cancelDeleteLocationDialog"
- confirmDialogTID="confirmDeleteLocationDialog"
- />
- )}
- {this.state.isSelectDirectoryDialogOpened && (
- <SelectDirectoryDialog
- open={this.state.isSelectDirectoryDialogOpened}
- onClose={this.closeSelectDirectoryExtDialog}
- createNewDirectoryExt={this.createNewDirectoryExt}
- chooseDirectoryPath={this.chooseDirectoryPath}
- selectedDirectoryPath={this.state.selectedDirectoryPath}
- />
- )}
- {this.state.isCreateDirectoryDialogOpened && (
- <CreateDirectoryDialog
- open={this.state.isCreateDirectoryDialogOpened}
- onClose={this.closeNewDirectoryDialog}
- selectedDirectoryPath={this.state.selectedDirectoryPath}
- />
- )}
- <Menu
- anchorEl={this.state.locationDirectoryContextMenuAnchorEl}
- open={this.state.locationContextMenuOpened}
- onClose={this.handleRequestCloseContextMenus}
- >
- <MenuItem
- data-tid="editLocation"
- onClick={this.showEditLocationDialog}
- >
- <ListItemIcon>
- <EditIcon />
- </ListItemIcon>
- <ListItemText primary={i18n.t('core:editLocationTitle')} />
- </MenuItem>
- <MenuItem data-tid="indexLocation" onClick={this.indexLocation}>
- <ListItemIcon>
- <RefreshIcon />
- </ListItemIcon>
- <ListItemText primary={i18n.t('core:indexLocation')} />
- </MenuItem>
- <MenuItem data-tid="moveLocationUp" onClick={this.moveLocationUp}>
- <ListItemIcon>
- <ArrowUpwardIcon />
- </ListItemIcon>
- <ListItemText primary={i18n.t('core:moveUp')} />
- </MenuItem>
- <MenuItem
- data-tid="moveLocationDown"
- onClick={this.moveLocationDown}
- >
- <ListItemIcon>
- <ArrowDownwardIcon />
- </ListItemIcon>
- <ListItemText primary={i18n.t('core:moveDown')} />
- </MenuItem>
- <MenuItem
- data-tid="removeLocation"
- onClick={this.showDeleteLocationDialog}
- >
- <ListItemIcon>
- <DeleteIcon />
- </ListItemIcon>
- <ListItemText primary={i18n.t('core:removeLocation')} />
- </MenuItem>
- <MenuItem
- data-tid="showInFileManager"
- onClick={this.showInFileManager}
- >
- <ListItemIcon>
- <OpenFolderNativelyIcon />
- </ListItemIcon>
- <ListItemText primary={i18n.t('core:showInFileManager')} />
- </MenuItem>
- <MenuItem data-tid="removeLocation" onClick={this.closeLocation}>
- <ListItemIcon>
- <CloseIcon />
- </ListItemIcon>
- <ListItemText primary={i18n.t('core:closeLocation')} />
- </MenuItem>
- </Menu>
- <List
- className={classes.locationListArea}
- data-tid="locationList"
- style={{
- maxHeight: 'calc(100vh - 175px)',
- // @ts-ignore
- overflowY: AppConfig.isFirefox ? 'auto' : 'overlay'
+ {isEditLocationDialogOpened && (
+ <EditLocationDialogAsync
+ open={isEditLocationDialogOpened}
+ onClose={() => setEditLocationDialogOpened(false)}
+ location={selectedLocation}
+ editLocation={props.editLocation}
+ showSelectDirectoryDialog={showSelectDirectoryDialog}
+ selectedDirectoryPath={selectedDirectoryPath}
+ />
+ )}
+ {isDeleteLocationDialogOpened && (
+ <ConfirmDialog
+ open={isDeleteLocationDialogOpened}
+ onClose={() => setDeleteLocationDialogOpened(false)}
+ title={i18n.t('core:deleteLocationTitleAlert')}
+ content={i18n.t('core:deleteLocationContentAlert', {
+ locationName: selectedLocation ? selectedLocation.name : ''
+ })}
+ confirmCallback={result => {
+ if (result && selectedLocation) {
+ props.removeLocation(selectedLocation);
+ }
}}
- >
- {this.props.locations.map(this.renderLocation)}
- </List>
- </div>
- <DirectoryMenu
- open={this.state.directoryContextMenuOpened}
- onClose={this.toggleDirectoryMenuClose}
- anchorEl={this.state.directoryContextMenuAnchorEl}
- directoryPath={this.state.selectedDirectoryPath}
- loadDirectoryContent={this.props.loadDirectoryContent}
- openDirectory={this.props.openDirectory}
- openFsEntry={this.props.openFsEntry}
- reflectCreateEntry={this.props.reflectCreateEntry}
- deleteDirectory={this.props.deleteDirectory}
- classes={this.props.classes}
- />
+ cancelDialogTID="cancelDeleteLocationDialog"
+ confirmDialogTID="confirmDeleteLocationDialog"
+ />
+ )}
+ {isSelectDirectoryDialogOpened && (
+ <SelectDirectoryDialog
+ open={isSelectDirectoryDialogOpened}
+ onClose={() => setSelectDirectoryDialogOpened(false)}
+ createNewDirectoryExt={createNewDirectoryExt}
+ chooseDirectoryPath={chooseDirectoryPath}
+ />
+ )}
+ {isCreateDirectoryDialogOpened && (
+ <CreateDirectoryDialog
+ open={isCreateDirectoryDialogOpened}
+ onClose={() => setCreateDirectoryDialogOpened(false)}
+ selectedDirectoryPath={selectedDirectoryPath}
+ />
+ )}
+ <List
+ className={classes.locationListArea}
+ data-tid="locationList"
+ style={{
+ maxHeight: 'calc(100vh - 175px)',
+ // @ts-ignore
+ overflowY: AppConfig.isFirefox ? 'auto' : 'overlay'
+ }}
+ >
+ {props.locations.map(location => (
+ <LocationView
+ key={location.uuid}
+ classes={props.classes}
+ location={location}
+ hideDrawer={props.hideDrawer}
+ setEditLocationDialogOpened={setEditLocationDialogOpened}
+ setDeleteLocationDialogOpened={setDeleteLocationDialogOpened}
+ selectedLocation={selectedLocation}
+ setSelectedLocation={setSelectedLocation}
+ />
+ ))}
+ </List>
</div>
- );
- }
-}
+ </div>
+ );
+};
function mapStateToProps(state) {
return {
locations: getLocations(state),
- currentLocationId: getCurrentLocationId(state),
- perspectives: getPerspectives(state),
- isReadOnlyMode: isReadOnlyMode(state),
- showUnixHiddenEntries: getShowUnixHiddenEntries(state)
+ perspectives: getPerspectives(state)
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(
{
- ...LocationActions,
- openLocation: AppActions.openLocation,
- onUploadProgress: AppActions.onUploadProgress,
- toggleUploadDialog: AppActions.toggleUploadDialog,
- resetProgress: AppActions.resetProgress,
- createDirectoryIndex: LocationIndexActions.createDirectoryIndex,
- closeLocation: AppActions.closeLocation,
- loadDirectoryContent: AppActions.loadDirectoryContent,
- reflectCreateEntry: AppActions.reflectCreateEntry,
- deleteDirectory: AppActions.deleteDirectory,
- openDirectory: AppActions.openDirectory,
- showInFileManager: AppActions.showInFileManager,
+ addLocation: LocationActions.addLocation,
+ editLocation: LocationActions.editLocation,
+ removeLocation: LocationActions.removeLocation,
openFileNatively: AppActions.openFileNatively,
- openFsEntry: AppActions.openFsEntry,
- showNotification: AppActions.showNotification,
- reflectCreateEntries: AppActions.reflectCreateEntries,
toggleOpenLinkDialog: AppActions.toggleOpenLinkDialog,
- moveFiles: IOActions.moveFiles,
- uploadFiles: IOActions.uploadFiles,
- openURLExternally: AppActions.openURLExternally,
- setSelectedEntries: AppActions.setSelectedEntries
+ openURLExternally: AppActions.openURLExternally
},
dispatch
);
diff --git a/app/components/LocationView.tsx b/app/components/LocationView.tsx
new file mode 100644
index 000000000..baeec9257
--- /dev/null
+++ b/app/components/LocationView.tsx
@@ -0,0 +1,358 @@
+/**
+ * TagSpaces - universal file and folder organizer
+ * Copyright (C) 2017-present TagSpaces UG (haftungsbeschraenkt)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License (version 3) as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+import React, { useRef, useState } from 'react';
+import { bindActionCreators } from 'redux';
+import { connect } from 'react-redux';
+import { withStyles } from '@material-ui/core/styles';
+import ListItem from '@material-ui/core/ListItem';
+import ListItemIcon from '@material-ui/core/ListItemIcon';
+import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction';
+import MoreVertIcon from '@material-ui/icons/MoreVert';
+import Typography from '@material-ui/core/Typography';
+import IconButton from '@material-ui/core/IconButton';
+import LocationIcon from '@material-ui/icons/WorkOutline';
+import CloudLocationIcon from '@material-ui/icons/CloudQueue';
+import DefaultLocationIcon from '@material-ui/icons/Highlight';
+import { Progress } from 'aws-sdk/clients/s3';
+import styles from './SidePanels.css';
+import { locationType, Location } from '-/reducers/locations';
+import {
+ actions as AppActions,
+ getCurrentLocationId,
+ isReadOnlyMode
+} from '../reducers/app';
+import i18n from '../services/i18n';
+import AppConfig from '../config';
+import PlatformIO from '../services/platform-io';
+import TargetMoveFileBox from './TargetMoveFileBox';
+import DragItemTypes from './DragItemTypes';
+import IOActions from '../reducers/io-actions';
+import DirectoryTreeView, {
+ DirectoryTreeViewRef
+} from '-/components/DirectoryTreeView';
+import { FileSystemEntry } from '-/services/utils-io';
+import { getShowUnixHiddenEntries } from '-/reducers/settings';
+import LocationContextMenu from '-/components/menus/LocationContextMenu';
+
+interface Props {
+ classes: any;
+ location: Location;
+ currentLocationId: string;
+ openLocation: (location: Location) => void;
+ loadDirectoryContent: (path: string) => void;
+ setSelectedEntries: (selectedEntries: Array<Object>) => void;
+ hideDrawer: () => void;
+ isReadOnlyMode: boolean;
+ showNotification: (
+ text: string,
+ notificationType: string,
+ autohide: boolean
+ ) => void;
+ resetProgress: () => void;
+ uploadFiles: (
+ files: Array<string>,
+ destination: string,
+ onUploadProgress?: (progress: Progress, response: any) => void
+ ) => Promise<Array<FileSystemEntry>>;
+ onUploadProgress: (progress: Progress, response: any) => void;
+ reflectCreateEntries: (fsEntries: Array<FileSystemEntry>) => void;
+ toggleUploadDialog: () => void;
+ moveFiles: (files: Array<string>, destination: string) => void;
+ showUnixHiddenEntries: boolean;
+ setEditLocationDialogOpened: boolean;
+ setDeleteLocationDialogOpened: boolean;
+ selectedLocation: Location;
+ setSelectedLocation: (loc: Location) => void;
+}
+
+const LocationView = React.memo((props: Props) => {
+ const directoryTreeRef = useRef<DirectoryTreeViewRef>(null);
+ const [
+ locationDirectoryContextMenuAnchorEl,
+ setLocationDirectoryContextMenuAnchorEl
+ ] = useState<null | HTMLElement>(null);
+
+ const { location } = props;
+ const isCloudLocation = location.type === locationType.TYPE_CLOUD;
+
+ const handleLocationClick = () => {
+ directoryTreeRef.current.changeLocation(location);
+ if (location.uuid === props.currentLocationId) {
+ // the same location click
+ props.loadDirectoryContent(location.path || location.paths[0]);
+ } else {
+ // this.directoryTreeRef[location.uuid].loadSubDir(location, 1);
+ props.setSelectedEntries([]);
+ props.openLocation(location);
+ if (props.hideDrawer) {
+ props.hideDrawer();
+ }
+ }
+ };
+
+ const closeLocationTree = () => {
+ directoryTreeRef.current.closeLocation();
+ };
+
+ const handleLocationContextMenuClick = (event: any) => {
+ event.preventDefault();
+ event.stopPropagation();
+ setLocationDirectoryContextMenuAnchorEl(event.currentTarget);
+ props.setSelectedLocation(location);
+ };
+
+ /**
+ * https://github.com/react-component/table/blob/master/examples/react-dnd.js
+ * @param item
+ * @param monitor
+ */
+ const handleFileMoveDrop = (item, monitor) => {
+ if (monitor) {
+ const { path, selectedEntries } = monitor.getItem();
+ const arrPath = [];
+ if (selectedEntries && selectedEntries.length > 0) {
+ selectedEntries.map(entry => {
+ arrPath.push(entry.path);
+ return true;
+ });
+ } else {
+ arrPath.push(path);
+ }
+ if (props.isReadOnlyMode) {
+ props.showNotification(
+ i18n.t('core:dndDisabledReadOnlyMode'),
+ 'error',
+ true
+ );
+ return;
+ }
+ if (!AppConfig.isWin && !path.startsWith('/')) {
+ props.showNotification(
+ i18n.t('Moving file not possible'),
+ 'error',
+ true
+ );
+ return;
+ }
+ if (AppConfig.isWin && !path.substr(1).startsWith(':')) {
+ props.showNotification(
+ i18n.t('Moving file not possible'),
+ 'error',
+ true
+ );
+ return;
+ }
+ let targetPath = item.path;
+ const targetLocation = item.location;
+ if (targetPath === undefined) {
+ targetPath = targetLocation.path;
+ }
+ /* if (item.children && item.children.props && item.children.props.path) {
+ targetPath = item.children.props.path;
+ } else {
+ targetPath = item.children[1].props.record.path;
+ } */
+ if (monitor && targetPath !== undefined && targetLocation !== undefined) {
+ // TODO handle monitor -> isOver and change folder icon
+ console.log('Dropped files: ' + path);
+ if (targetLocation.type === locationType.TYPE_CLOUD) {
+ PlatformIO.enableObjectStoreSupport(targetLocation)
+ .then(() => {
+ props.resetProgress();
+ props
+ .uploadFiles(arrPath, targetPath, props.onUploadProgress)
+ .then((fsEntries: Array<FileSystemEntry>) => {
+ props.reflectCreateEntries(fsEntries);
+ return true;
+ })
+ .catch(error => {
+ console.log('uploadFiles', error);
+ });
+ props.toggleUploadDialog();
+ return true;
+ })
+ .catch(error => {
+ console.log('enableObjectStoreSupport', error);
+ });
+ } else if (targetLocation.type === locationType.TYPE_LOCAL) {
+ PlatformIO.disableObjectStoreSupport();
+ props.moveFiles(arrPath, targetPath);
+ }
+ props.setSelectedEntries([]);
+ }
+ }
+ };
+
+ return (
+ /* <div key={location.uuid}> */
+ <>
+ {locationDirectoryContextMenuAnchorEl && (
+ <LocationContextMenu
+ setEditLocationDialogOpened={props.setEditLocationDialogOpened}
+ setDeleteLocationDialogOpened={props.setDeleteLocationDialogOpened}
+ selectedLocation={props.selectedLocation}
+ locationDirectoryContextMenuAnchorEl={
+ locationDirectoryContextMenuAnchorEl
+ }
+ setLocationDirectoryContextMenuAnchorEl={
+ setLocationDirectoryContextMenuAnchorEl
+ }
+ closeLocationTree={closeLocationTree}
+ />
+ )}
+ <ListItem
+ data-tid={'location_' + location.name.replace(/ /g, '_')}
+ className={
+ props.currentLocationId === location.uuid
+ ? props.classes.listItemSelected
+ : props.classes.listItem
+ }
+ title={
+ location.isDefault
+ ? i18n.t('core: thisIsStartupLocation') + ' : ' + location.path ||
+ location.paths[0]
+ : location.path || location.paths[0]
+ }
+ button
+ onClick={() => handleLocationClick()}
+ onContextMenu={event => handleLocationContextMenuClick(event)}
+ >
+ <ListItemIcon
+ // onClick={(e) => {
+ // e.preventDefault();
+ // this.loadSubDirectories(location, 1);
+ // }}
+ style={{
+ minWidth: 'auto'
+ }}
+ >
+ {isCloudLocation ? (
+ <CloudLocationIcon className={props.classes.icon} />
+ ) : (
+ <LocationIcon className={props.classes.icon} />
+ )}
+ </ListItemIcon>
+
+ {isCloudLocation && !AppConfig.isElectron ? (
+ <div
+ style={{
+ maxWidth: 250
+ }}
+ >
+ <Typography
+ variant="inherit"
+ style={{
+ paddingLeft: 5,
+ paddingRight: 5
+ }}
+ className={props.classes.header}
+ data-tid="locationTitleElement"
+ noWrap
+ >
+ {location.name}
+ </Typography>
+ </div>
+ ) : (
+ <TargetMoveFileBox
+ accepts={[DragItemTypes.FILE]}
+ onDrop={handleFileMoveDrop}
+ path={location.path || location.paths[0]}
+ location={location}
+ >
+ <div
+ style={{
+ maxWidth: 250
+ }}
+ >
+ <Typography
+ variant="inherit"
+ style={{
+ paddingLeft: 5,
+ paddingRight: 5
+ }}
+ className={props.classes.header}
+ data-tid="locationTitleElement"
+ noWrap
+ >
+ {location.name}
+ </Typography>
+ </div>
+ </TargetMoveFileBox>
+ )}
+ {!AppConfig.locationsReadOnly && (
+ <ListItemSecondaryAction>
+ <IconButton
+ aria-label={i18n.t('core:options')}
+ aria-haspopup="true"
+ edge="end"
+ data-tid={'locationMoreButton_' + location.name}
+ onClick={event => handleLocationContextMenuClick(event)}
+ onContextMenu={event => handleLocationContextMenuClick(event)}
+ >
+ {location.isDefault && (
+ <DefaultLocationIcon data-tid="startupIndication" />
+ )}
+ <MoreVertIcon />
+ </IconButton>
+ </ListItemSecondaryAction>
+ )}
+ </ListItem>
+ <DirectoryTreeView
+ key={'tree_' + location.uuid}
+ ref={directoryTreeRef}
+ classes={props.classes}
+ loadDirectoryContent={props.loadDirectoryContent}
+ location={location}
+ showUnixHiddenEntries={props.showUnixHiddenEntries}
+ handleFileMoveDrop={handleFileMoveDrop}
+ />
+ </>
+ );
+});
+
+function mapStateToProps(state) {
+ return {
+ currentLocationId: getCurrentLocationId(state),
+ isReadOnlyMode: isReadOnlyMode(state),
+ showUnixHiddenEntries: getShowUnixHiddenEntries(state)
+ };
+}
+
+function mapDispatchToProps(dispatch) {
+ return bindActionCreators(
+ {
+ showNotification: AppActions.showNotification,
+ toggleUploadDialog: AppActions.toggleUploadDialog,
+ reflectCreateEntries: AppActions.reflectCreateEntries,
+ resetProgress: AppActions.resetProgress,
+ uploadFiles: IOActions.uploadFiles,
+ moveFiles: IOActions.moveFiles,
+ onUploadProgress: AppActions.onUploadProgress,
+ setSelectedEntries: AppActions.setSelectedEntries,
+ openLocation: AppActions.openLocation,
+ loadDirectoryContent: AppActions.loadDirectoryContent
+ },
+ dispatch
+ );
+}
+
+export default withStyles(styles)(
+ // @ts-ignore
+ connect(mapStateToProps, mapDispatchToProps)(LocationView)
+);
diff --git a/app/components/TargetMoveFileBox.tsx b/app/components/TargetMoveFileBox.tsx
index 29c35a8ee..a6c9c3089 100644
--- a/app/components/TargetMoveFileBox.tsx
+++ b/app/components/TargetMoveFileBox.tsx
@@ -19,6 +19,7 @@
import React from 'react';
import { DropTarget } from 'react-dnd';
import { withStyles } from '@material-ui/core/styles/index';
+import { Location } from '-/reducers/locations';
const styles: any = () => ({
dropzone: {
@@ -42,11 +43,15 @@ const boxTarget = {
};
interface Props {
+ accepts: Array<string>;
+ onDrop: (item: any, monitor: any) => void;
classes?: any;
canDrop: boolean;
isOver: boolean;
connectDropTarget: any;
children: Object;
+ path?: string;
+ location?: Location;
}
const TargetMoveFileBox = (props: Props) => {
diff --git a/app/components/TargetTableMoveFileBox.tsx b/app/components/TargetTableMoveFileBox.tsx
index 4ddb1f0e6..7b37c7517 100644
--- a/app/components/TargetTableMoveFileBox.tsx
+++ b/app/components/TargetTableMoveFileBox.tsx
@@ -26,6 +26,8 @@ const boxTarget = {
};
interface Props {
+ accepts: Array<string>;
+ onDrop: (item: any, monitor: any) => void;
canDrop: boolean;
isOver: boolean;
connectDropTarget: any;
@@ -37,6 +39,7 @@ const TargetTableMoveFileBox = (props: Props) => {
if (canDrop && isOver) {
restProps.className += ' dropzone'; // TODO set props.location type and add dropzonecopy based on this type
}
+ // @ts-ignore
return connectDropTarget(<tr {...restProps} />);
};
diff --git a/app/components/dialogs/CreateLocationDialog.tsx b/app/components/dialogs/CreateLocationDialog.tsx
index 0b15603e6..9f72ec3f7 100644
--- a/app/components/dialogs/CreateLocationDialog.tsx
+++ b/app/components/dialogs/CreateLocationDialog.tsx
@@ -59,7 +59,6 @@ interface Props {
fullScreen: boolean;
addLocation: (location: Location) => void;
showSelectDirectoryDialog: () => void;
- resetState: (stateMember: string) => void;
}
interface State {
@@ -242,13 +241,13 @@ class CreateLocationDialog extends React.Component<Props, State> {
});
}
this.props.onClose();
- this.props.resetState('createLocationDialogKey');
+ // this.props.resetState('createLocationDialogKey');
}
};
onCancel = () => {
this.props.onClose();
- this.props.resetState('createLocationDialogKey');
+ // this.props.resetState('createLocationDialogKey');
};
render() {
diff --git a/app/components/dialogs/EditLocationDialog.tsx b/app/components/dialogs/EditLocationDialog.tsx
index cd3732196..06b0cf82f 100644
--- a/app/components/dialogs/EditLocationDialog.tsx
+++ b/app/components/dialogs/EditLocationDialog.tsx
@@ -42,7 +42,6 @@ import PlatformIO from '-/services/platform-io';
interface Props {
open: boolean;
fullScreen?: boolean;
- resetState: (param: string) => void;
onClose: () => void;
location: Location | null;
editLocation: (location: Location) => void;
@@ -320,13 +319,13 @@ class EditLocationDialog extends React.Component<Props, State> {
});
}
this.props.onClose();
- this.props.resetState('editLocationDialogKey');
+ // this.props.resetState('editLocationDialogKey');
}
};
onCancel = () => {
this.props.onClose();
- this.props.resetState('editLocationDialogKey');
+ // this.props.resetState('editLocationDialogKey');
};
renderTitle = () => (
@@ -483,7 +482,7 @@ class EditLocationDialog extends React.Component<Props, State> {
color="primary"
onClick={() => {
this.props.onClose();
- this.props.resetState('editLocationDialogKey');
+ // this.props.resetState('editLocationDialogKey');
}}
>
{i18n.t('core:cancel')}
diff --git a/app/components/menus/LocationContextMenu.tsx b/app/components/menus/LocationContextMenu.tsx
new file mode 100644
index 000000000..c0d377c32
--- /dev/null
+++ b/app/components/menus/LocationContextMenu.tsx
@@ -0,0 +1,202 @@
+/**
+ * TagSpaces - universal file and folder organizer
+ * Copyright (C) 2017-present TagSpaces UG (haftungsbeschraenkt)
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License (version 3) as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
+ *
+ */
+
+import React from 'react';
+import ListItemText from '@material-ui/core/ListItemText';
+import ListItemIcon from '@material-ui/core/ListItemIcon';
+import Menu from '@material-ui/core/Menu';
+import MenuItem from '@material-ui/core/MenuItem';
+import EditIcon from '@material-ui/icons/Edit';
+import RefreshIcon from '@material-ui/icons/Refresh';
+import ArrowUpwardIcon from '@material-ui/icons/ArrowUpward';
+import ArrowDownwardIcon from '@material-ui/icons/ArrowDownward';
+import DeleteIcon from '@material-ui/icons/DeleteForever';
+import OpenFolderNativelyIcon from '@material-ui/icons/Launch';
+import CloseIcon from '@material-ui/icons/Close';
+import { bindActionCreators } from 'redux';
+import { connect } from 'react-redux';
+import {
+ actions as LocationActions,
+ Location,
+ locationType
+} from '-/reducers/locations';
+import PlatformIO from '-/services/platform-io';
+import { actions as LocationIndexActions } from '-/reducers/location-index';
+import i18n from '-/services/i18n';
+import { actions as AppActions } from '-/reducers/app';
+
+interface Props {
+ setEditLocationDialogOpened: (open: boolean) => void;
+ setDeleteLocationDialogOpened: (open: boolean) => void;
+ createDirectoryIndex: (
+ path: string,
+ fullTextIndex: boolean,
+ isCurrentLocation: boolean
+ ) => void;
+ selectedLocation: Location;
+ isCurrentLocation: (uuid: string) => boolean;
+ moveLocationUp: (locationId: string) => void;
+ moveLocationDown: (locationId: string) => void;
+ showInFileManager: (path: string) => void;
+ closeLocation: (locationId: string) => void;
+ closeLocationTree: () => void;
+ locationDirectoryContextMenuAnchorEl: HTMLElement;
+ setLocationDirectoryContextMenuAnchorEl: (el: HTMLElement) => void;
+}
+
+const LocationContextMenu = (props: Props) => {
+ const indexLocation = () => {
+ props.setLocationDirectoryContextMenuAnchorEl(null);
+ const { createDirectoryIndex, selectedLocation } = props;
+ /* const isCurrentLocation =
+ selectedLocation &&
+ selectedLocation.uuid &&
+ selectedLocation.uuid === currentLocationId; */
+ const isCurrentLocation =
+ selectedLocation && props.isCurrentLocation(selectedLocation.uuid);
+ if (selectedLocation.type === locationType.TYPE_CLOUD) {
+ PlatformIO.enableObjectStoreSupport(selectedLocation)
+ .then(() => {
+ createDirectoryIndex(
+ selectedLocation.path || selectedLocation.paths[0],
+ selectedLocation.fullTextIndex,
+ isCurrentLocation
+ );
+ return true;
+ })
+ .catch(() => {
+ PlatformIO.disableObjectStoreSupport();
+ });
+ } else if (selectedLocation.type === locationType.TYPE_LOCAL) {
+ PlatformIO.disableObjectStoreSupport();
+ createDirectoryIndex(
+ selectedLocation.path || selectedLocation.paths[0],
+ selectedLocation.fullTextIndex,
+ isCurrentLocation
+ );
+ }
+ };
+
+ const showEditLocationDialog = () => {
+ props.setLocationDirectoryContextMenuAnchorEl(null);
+ props.setEditLocationDialogOpened(true);
+ };
+
+ const moveLocationUp = () => {
+ props.setLocationDirectoryContextMenuAnchorEl(null);
+ if (props.selectedLocation && props.selectedLocation.uuid) {
+ props.moveLocationUp(props.selectedLocation.uuid);
+ }
+ };
+
+ const moveLocationDown = () => {
+ props.setLocationDirectoryContextMenuAnchorEl(null);
+ if (props.selectedLocation && props.selectedLocation.uuid) {
+ props.moveLocationDown(props.selectedLocation.uuid);
+ }
+ };
+
+ const showDeleteLocationDialog = () => {
+ props.setLocationDirectoryContextMenuAnchorEl(null);
+ props.setDeleteLocationDialogOpened(true);
+ };
+
+ const showInFileManager = () => {
+ props.setLocationDirectoryContextMenuAnchorEl(null);
+ props.showInFileManager(
+ props.selectedLocation.path || props.selectedLocation.paths[0]
+ );
+ // props.openDirectory(selectedLocation.path || selectedLocation.paths[0]);
+ };
+
+ const closeLocation = () => {
+ props.setLocationDirectoryContextMenuAnchorEl(null);
+ if (props.selectedLocation && props.selectedLocation.uuid) {
+ props.closeLocation(props.selectedLocation.uuid);
+ props.closeLocationTree();
+ }
+ };
+
+ return (
+ <Menu
+ anchorEl={props.locationDirectoryContextMenuAnchorEl}
+ open={Boolean(props.locationDirectoryContextMenuAnchorEl)}
+ onClose={() => props.setLocationDirectoryContextMenuAnchorEl(null)}
+ >
+ <MenuItem data-tid="editLocation" onClick={showEditLocationDialog}>
+ <ListItemIcon>
+ <EditIcon />
+ </ListItemIcon>
+ <ListItemText primary={i18n.t('core:editLocationTitle')} />
+ </MenuItem>
+ <MenuItem data-tid="indexLocation" onClick={indexLocation}>
+ <ListItemIcon>
+ <RefreshIcon />
+ </ListItemIcon>
+ <ListItemText primary={i18n.t('core:indexLocation')} />
+ </MenuItem>
+ <MenuItem data-tid="moveLocationUp" onClick={moveLocationUp}>
+ <ListItemIcon>
+ <ArrowUpwardIcon />
+ </ListItemIcon>
+ <ListItemText primary={i18n.t('core:moveUp')} />
+ </MenuItem>
+ <MenuItem data-tid="moveLocationDown" onClick={moveLocationDown}>
+ <ListItemIcon>
+ <ArrowDownwardIcon />
+ </ListItemIcon>
+ <ListItemText primary={i18n.t('core:moveDown')} />
+ </MenuItem>
+ <MenuItem data-tid="removeLocation" onClick={showDeleteLocationDialog}>
+ <ListItemIcon>
+ <DeleteIcon />
+ </ListItemIcon>
+ <ListItemText primary={i18n.t('core:removeLocation')} />
+ </MenuItem>
+ <MenuItem data-tid="showInFileManager" onClick={showInFileManager}>
+ <ListItemIcon>
+ <OpenFolderNativelyIcon />
+ </ListItemIcon>
+ <ListItemText primary={i18n.t('core:showInFileManager')} />
+ </MenuItem>
+ <MenuItem data-tid="removeLocation" onClick={closeLocation}>
+ <ListItemIcon>
+ <CloseIcon />
+ </ListItemIcon>
+ <ListItemText primary={i18n.t('core:closeLocation')} />
+ </MenuItem>
+ </Menu>
+ );
+};
+
+function mapDispatchToProps(dispatch) {
+ return bindActionCreators(
+ {
+ createDirectoryIndex: LocationIndexActions.createDirectoryIndex,
+ isCurrentLocation: AppActions.isCurrentLocation,
+ moveLocationUp: LocationActions.moveLocationUp,
+ moveLocationDown: LocationActions.moveLocationDown,
+ showInFileManager: AppActions.showInFileManager,
+ closeLocation: AppActions.closeLocation
+ },
+ dispatch
+ );
+}
+
+// @ts-ignore
+export default connect(undefined, mapDispatchToProps)(LocationContextMenu);
diff --git a/app/components/menus/LocationManagerMenu.tsx b/app/components/menus/LocationManagerMenu.tsx
index 9193ef021..34b3ce84b 100644
--- a/app/components/menus/LocationManagerMenu.tsx
+++ b/app/components/menus/LocationManagerMenu.tsx
@@ -16,7 +16,7 @@
*
*/
-import React from 'react';
+import React, { useState } from 'react';
import ListItemText from '@material-ui/core/ListItemText';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import Menu from '@material-ui/core/Menu';
@@ -24,62 +24,94 @@ import MenuItem from '@material-ui/core/MenuItem';
import CreateLocationIcon from '@material-ui/icons/CreateNewFolder';
import OpenLinkIcon from '@material-ui/icons/Link';
import HelpIcon from '@material-ui/icons/Help';
-import i18n from '-/services/i18n';
+import classNames from 'classnames';
+import Typography from '@material-ui/core/Typography';
+import IconButton from '@material-ui/core/IconButton';
+import MoreVertIcon from '@material-ui/icons/MoreVert';
import AppConfig from '-/config';
+import i18n from '-/services/i18n';
interface Props {
- classes?: any;
- open: boolean;
- anchorEl: Element;
- onClose: () => void;
+ classes: any;
showCreateLocationDialog: () => void;
toggleOpenLinkDialog: () => void;
openURLExternally: (url: string, skipConfirmation?: boolean) => void;
}
-const LocationManagerMenu = (props: Props) => (
- <div style={{ overflowY: 'hidden' }}>
- <Menu anchorEl={props.anchorEl} open={props.open} onClose={props.onClose}>
- {!AppConfig.locationsReadOnly && (
+const LocationManagerMenu = (props: Props) => {
+ const [
+ locationManagerMenuAnchorEl,
+ setLocationManagerMenuAnchorEl
+ ] = useState<null | HTMLElement>(null);
+
+ return (
+ <>
+ <div className={props.classes.toolbar}>
+ <Typography
+ className={classNames(props.classes.panelTitle, props.classes.header)}
+ variant="subtitle1"
+ >
+ {i18n.t('core:locationManager')}
+ </Typography>
+ <IconButton
+ data-tid="locationManagerMenu"
+ onClick={event => setLocationManagerMenuAnchorEl(event.currentTarget)}
+ >
+ <MoreVertIcon />
+ </IconButton>
+ </div>
+ {/* <div style={{ overflowY: 'hidden' }}> */}
+ <Menu
+ anchorEl={locationManagerMenuAnchorEl}
+ open={Boolean(locationManagerMenuAnchorEl)}
+ onClose={() => {
+ setLocationManagerMenuAnchorEl(null);
+ }}
+ >
+ {!AppConfig.locationsReadOnly && (
+ <MenuItem
+ data-tid="locationManagerMenuCreateLocation"
+ onClick={() => {
+ setLocationManagerMenuAnchorEl(null);
+ props.showCreateLocationDialog();
+ }}
+ >
+ <ListItemIcon>
+ <CreateLocationIcon />
+ </ListItemIcon>
+ <ListItemText primary={i18n.t('core:createLocationTitle')} />
+ </MenuItem>
+ )}
<MenuItem
- data-tid="locationManagerMenuCreateLocation"
+ data-tid="locationManagerMenuOpenLink"
onClick={() => {
- props.onClose();
- props.showCreateLocationDialog();
+ setLocationManagerMenuAnchorEl(null);
+ props.toggleOpenLinkDialog();
}}
>
<ListItemIcon>
- <CreateLocationIcon />
+ <OpenLinkIcon />
</ListItemIcon>
- <ListItemText primary={i18n.t('core:createLocationTitle')} />
+ <ListItemText primary={i18n.t('core:openLink')} />
</MenuItem>
- )}
- <MenuItem
- data-tid="locationManagerMenuOpenLink"
- onClick={() => {
- props.onClose();
- props.toggleOpenLinkDialog();
- }}
- >
- <ListItemIcon>
- <OpenLinkIcon />
- </ListItemIcon>
- <ListItemText primary={i18n.t('core:openLink')} />
- </MenuItem>
- <MenuItem
- data-tid="locationManagerMenuHelp"
- onClick={() => {
- props.onClose();
- props.openURLExternally(AppConfig.documentationLinks.locations, true);
- }}
- >
- <ListItemIcon>
- <HelpIcon />
- </ListItemIcon>
- <ListItemText primary={i18n.t('core:help')} />
- </MenuItem>
- </Menu>
- </div>
-);
+ <MenuItem
+ data-tid="locationManagerMenuHelp"
+ onClick={() => {
+ setLocationManagerMenuAnchorEl(null);
+ props.openURLExternally(
+ AppConfig.documentationLinks.locations,
+ true
+ );
+ }}
+ >
+ <ListItemIcon>
+ <HelpIcon />
+ </ListItemIcon>
+ <ListItemText primary={i18n.t('core:help')} />
+ </MenuItem>
+ </Menu>
+ </>
+ );
+};
export default LocationManagerMenu;
diff --git a/app/reducers/app.ts b/app/reducers/app.ts
index be47de777..d01666f9e 100644
--- a/app/reducers/app.ts
+++ b/app/reducers/app.ts
@@ -1880,6 +1880,13 @@ export const actions = {
true
)
);
+ },
+ isCurrentLocation: (uuid: string) => (
+ dispatch: (actions: Object) => void,
+ getState: () => any
+ ) => {
+ const { currentLocationId } = getState().app;
+ return currentLocationId === uuid;
}
};