TagSpaces is an offline, open source, document manager with tagging support
typescript fixes
Ilian Sapundshiev0ed13d98465e
diff --git a/app/components/AppOnboarding.tsx b/app/components/AppOnboarding.tsxindex 226052a71..e228f2896 100644--- a/app/components/AppOnboarding.tsx+++ b/app/components/AppOnboarding.tsx@@ -21,11 +21,11 @@ import Joyride from 'react-joyride';import i18n from '../services/i18n';class AppOnboarding extends Component {- state = {- run: false- };+ state = {+ run: false+ };- /* componentDidMount() {+ /* componentDidMount() {setTimeout(() => {this.setState({run: true@@ -33,26 +33,26 @@ class AppOnboarding extends Component {}, 1000);} */- callback = data => {- const { action, index, type } = data;- };+ callback = data => {+ // const { action, index, type } = data;+ };- render() {- const { run } = this.state;- const steps = [- {- target: '[data-tid=createNewLocation]',- content: i18n.t('welcomeContent'),- placement: 'bottom'- },- {- target: '[data-tid=aboutTagSpaces]',- content: 'Hello world',- placement: 'bottom'- }- ];- return <Joyride steps={steps} run={run} callback={this.callback} />;- }+ render() {+ const { run } = this.state;+ const steps = [+ {+ target: '[data-tid=createNewLocation]',+ content: i18n.t('welcomeContent'),+ placement: 'bottom'+ },+ {+ target: '[data-tid=aboutTagSpaces]',+ content: 'Hello world',+ placement: 'bottom'+ }+ ];+ return <Joyride steps={steps} run={run} callback={this.callback} />;+ }}export default AppOnboarding;diff --git a/app/components/EntryContainer.tsx b/app/components/EntryContainer.tsxindex 0b7bc8ed3..5f2aae93e 100644--- a/app/components/EntryContainer.tsx+++ b/app/components/EntryContainer.tsx@@ -46,7 +46,7 @@ import PlatformIO from '../services/platform-io';import AddRemoveTagsDialog from './dialogs/AddRemoveTagsDialog';import {// getAllPropertiesPromise,- openLinkExternally+ openLinkExternally, FileSystemEntry} from '../services/utils-io';import i18n from '../services/i18n';import {@@ -165,10 +165,10 @@ const styles = theme => ({});type Props = {- classes: Object,+ classes: any,openedFiles: Array<OpenedEntry>,- settings: Object,- keyBindings: Object,+ settings: any,+ keyBindings: any,closeAllFiles: () => void,renameFile: () => void,renameDirectory: () => void,@@ -369,7 +369,7 @@ class EntryContainer extends React.Component<Props, State> {this.handleMessage(JSON.stringify(event.channel));};- handleMessage = (msg: Object | string) => {+ handleMessage = (msg: any) => {let data;let message;let textFilePath;@@ -397,7 +397,7 @@ class EntryContainer extends React.Component<Props, State> {case 'playbackEnded':nextFilePath = this.props.getNextFile(this.state.currentEntry.path);nextFile = this.props.directoryContent.filter(- entry => entry.path === nextFilePath+ (entry: any) => entry.path === nextFilePath);this.props.openFile(nextFilePath);this.props.setLastSelectedEntry(nextFilePath);@@ -684,7 +684,7 @@ class EntryContainer extends React.Component<Props, State> {if (this.state.currentEntry && this.state.currentEntry.path) {const nextFilePath = this.props.getNextFile(this.state.currentEntry.path);const nextFile = this.props.directoryContent.filter(- entry => entry.path === nextFilePath+ (entry: FileSystemEntry) => entry.path === nextFilePath);this.props.openFile(nextFilePath);this.props.setLastSelectedEntry(nextFilePath);@@ -696,7 +696,7 @@ class EntryContainer extends React.Component<Props, State> {if (this.state.currentEntry && this.state.currentEntry.path) {const prevFilePath = this.props.getPrevFile(this.state.currentEntry.path);const prevFile = this.props.directoryContent.filter(- entry => entry.path === prevFilePath+ (entry: FileSystemEntry) => entry.path === prevFilePath);this.props.openFile(prevFilePath);this.props.setLastSelectedEntry(prevFilePath);@@ -1000,7 +1000,7 @@ class EntryContainer extends React.Component<Props, State> {}}cancelDialogTID={'cancelSaveBeforeCloseDialog'}confirmDialogTID={'confirmSaveBeforeCloseDialog'}- confirmDialogContent={'confirmDialogContent'}+ confirmDialogContentTID={'confirmDialogContent'}/><ConfirmDialogopen={this.state.isSaveBeforeReloadConfirmDialogOpened}@@ -1025,7 +1025,7 @@ class EntryContainer extends React.Component<Props, State> {}}cancelDialogTID={'cancelSaveBeforeCloseDialog'}confirmDialogTID={'confirmSaveBeforeCloseDialog'}- confirmDialogContent={'confirmDialogContent'}+ confirmDialogContentTID={'confirmDialogContent'}/><ConfirmDialogopen={this.state.isDeleteEntryModalOpened}@@ -1053,7 +1053,7 @@ class EntryContainer extends React.Component<Props, State> {}}cancelDialogTID={'cancelSaveBeforeCloseDialog'}confirmDialogTID={'confirmSaveBeforeCloseDialog'}- confirmDialogContent={'confirmDialogContent'}+ confirmDialogContentTID={'confirmDialogContent'}/><AddRemoveTagsDialogopen={isEditTagsModalOpened}diff --git a/app/components/EntryProperties.tsx b/app/components/EntryProperties.tsxindex d8b5f0c4e..270a92646 100644--- a/app/components/EntryProperties.tsx+++ b/app/components/EntryProperties.tsx@@ -484,7 +484,7 @@ class EntryProperties extends Component<Props, State> {handleCloseTagMenu = () => this.setState({ tagMenuOpened: false });- handleInputChange = (event: Object) => {+ handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {const target = event.target;const value = target.type === 'checkbox' ? target.checked : target.value;const name = target.name;diff --git a/app/components/FileSourceDnd.tsx b/app/components/FileSourceDnd.tsxindex 433c6380f..defd9e97f 100644--- a/app/components/FileSourceDnd.tsx+++ b/app/components/FileSourceDnd.tsx@@ -18,23 +18,23 @@import React from 'react';import { DragSource } from 'react-dnd';-import type { ConnectDragSource } from 'react-dnd';+import { ConnectDragSource } from 'react-dnd';import DragItemTypes from './DragItemTypes';type Props = {- children: Array<Object>,- connectDragSource: ConnectDragSource+ children: Array<Object>;+ connectDragSource: ConnectDragSource;};const boxSource = {- beginDrag(props) {- // console.log('beginDrag', props);- return {- path: props.children.props.entryPath- };- }+ beginDrag(props) {+ // console.log('beginDrag', props);+ return {+ path: props.children.props.entryPath+ };+ }- /* endDrag(props, monitor) {+ /* endDrag(props, monitor) {const item = monitor.getItem();const dropResult = monitor.getDropResult();@@ -51,13 +51,13 @@ const boxSource = {};const FileSourceDnd = (props: Props) =>- props.connectDragSource(<span>{props.children}</span>);+ props.connectDragSource(<span>{props.children}</span>);export default DragSource(- DragItemTypes.FILE,- boxSource,- (connect, monitor) => ({- connectDragSource: connect.dragSource(),- isDragging: monitor.isDragging()- })+ DragItemTypes.FILE,+ boxSource,+ (connect, monitor) => ({+ connectDragSource: connect.dragSource(),+ isDragging: monitor.isDragging()+ }))(FileSourceDnd);diff --git a/app/components/FolderContainer.tsx b/app/components/FolderContainer.tsxindex 9e6e6d2cb..76c2200dc 100644--- a/app/components/FolderContainer.tsx+++ b/app/components/FolderContainer.tsx@@ -29,18 +29,18 @@ import LocationMenu from './menus/LocationMenu';import DirectoryMenu from './menus/DirectoryMenu';import i18n from '../services/i18n';import {- getPerspectives,- getMaxSearchResults,- getDesktopMode+ getPerspectives,+ getMaxSearchResults,+ getDesktopMode} from '../reducers/settings';import {- actions as AppActions,- getDirectoryContent,- getDirectoryPath,- getLastSelectedEntry,- getSearchResultCount,- isReadOnlyMode,- getCurrentLocationPath+ actions as AppActions,+ getDirectoryContent,+ getDirectoryPath,+ getLastSelectedEntry,+ getSearchResultCount,+ isReadOnlyMode,+ getCurrentLocationPath} from '../reducers/app';import TaggingActions from '../reducers/tagging-actions';import { normalizePath, extractShortDirectoryName } from '../utils/paths';@@ -49,498 +49,498 @@ import LoadingLazy from '../components/LoadingLazy';import { Pro } from '../pro';const GridPerspective = React.lazy(() =>- import(- /* webpackChunkName: "GridPerspective" */ '../perspectives/grid-perspective/'- )+ import(+ /* webpackChunkName: "GridPerspective" */ '../perspectives/grid-perspective/'+ ));const GridPerspectiveAsync = props => (- <React.Suspense fallback={<LoadingLazy />}>- <GridPerspective {...props} />- </React.Suspense>+ <React.Suspense fallback={<LoadingLazy />}>+ <GridPerspective {...props} />+ </React.Suspense>);let GalleryPerspective = React.Fragment;if (Pro && Pro.Perspectives && Pro.Perspectives.GalleryPerspective) {- // GalleryPerspective = React.lazy(() => import(/* webpackChunkName: "GalleryPerspective" */ '../node_modules/@tagspaces/pro/modules/perspectives/gallery'));- GalleryPerspective = Pro.Perspectives.GalleryPerspective;+ // GalleryPerspective = React.lazy(() => import(/* webpackChunkName: "GalleryPerspective" */ '../node_modules/@tagspaces/pro/modules/perspectives/gallery'));+ GalleryPerspective = Pro.Perspectives.GalleryPerspective;}const GalleryPerspectiveAsync = props => (- <React.Suspense fallback={<LoadingLazy />}>- <GalleryPerspective {...props} />- </React.Suspense>+ <React.Suspense fallback={<LoadingLazy />}>+ <GalleryPerspective {...props} />+ </React.Suspense>);let MapiquePerspective = React.Fragment;if (Pro && Pro.Perspectives && Pro.Perspectives.MapiquePerspective) {- // MapiquePerspective = React.lazy(() => import(/* webpackChunkName: "MapiquePerspective" */ '../node_modules/@tagspaces/pro/modules/perspectives/mapique'));- MapiquePerspective = Pro.Perspectives.MapiquePerspective;+ // MapiquePerspective = React.lazy(() => import(/* webpackChunkName: "MapiquePerspective" */ '../node_modules/@tagspaces/pro/modules/perspectives/mapique'));+ MapiquePerspective = Pro.Perspectives.MapiquePerspective;}const MapiquePerspectiveAsync = props => (- <React.Suspense fallback={<LoadingLazy />}>- <MapiquePerspective {...props} />- </React.Suspense>+ <React.Suspense fallback={<LoadingLazy />}>+ <MapiquePerspective {...props} />+ </React.Suspense>);let TreeVizPerspective = React.Fragment;if (Pro && Pro.Perspectives && Pro.Perspectives.TreeVizPerspective) {- // TreeVizPerspective = React.lazy(() => import(/* webpackChunkName: "TreeVizPerspective" */ '../node_modules/@tagspaces/pro/modules/perspectives/treeviz'));- TreeVizPerspective = Pro.Perspectives.TreeVizPerspective;+ // TreeVizPerspective = React.lazy(() => import(/* webpackChunkName: "TreeVizPerspective" */ '../node_modules/@tagspaces/pro/modules/perspectives/treeviz'));+ TreeVizPerspective = Pro.Perspectives.TreeVizPerspective;}const TreeVizPerspectiveAsync = props => (- <React.Suspense fallback={<LoadingLazy />}>- <TreeVizPerspective {...props} />- </React.Suspense>+ <React.Suspense fallback={<LoadingLazy />}>+ <TreeVizPerspective {...props} />+ </React.Suspense>);const WelcomePanel = React.lazy(() =>- import(/* webpackChunkName: "WelcomePanel" */ './WelcomePanel')+ import(/* webpackChunkName: "WelcomePanel" */ './WelcomePanel'));const WelcomePanelAsync = props => (- <React.Suspense fallback={<LoadingLazy />}>- <WelcomePanel {...props} />- </React.Suspense>+ <React.Suspense fallback={<LoadingLazy />}>+ <WelcomePanel {...props} />+ </React.Suspense>);const CounterBadge = withStyles(theme => ({- badge: {- top: '50%',- right: -15,- color:- theme.palette.type === 'light'- ? theme.palette.grey[900]- : theme.palette.grey[200],- backgroundColor:- theme.palette.type === 'light'- ? theme.palette.grey[200]- : theme.palette.grey[900]- }+ badge: {+ top: '50%',+ right: -15,+ color:+ theme.palette.type === 'light'+ ? theme.palette.grey[900]+ : theme.palette.grey[200],+ backgroundColor:+ theme.palette.type === 'light'+ ? theme.palette.grey[200]+ : theme.palette.grey[900]+ }}))(Badge);const styles = theme => ({- mainPanel: {- flex: '1 1 100%',- width: '100%',- height: '100%',- maxHeight: '100%',- overflow: 'hidden',- backgroundColor: theme.palette.background.default,- display: 'flex',- flexDirection: 'column'- },- toolbar: {- paddingLeft: 5,- paddingRight: 5,- paddingTop: 5,- display: 'flex',- justifyContent: 'center'- },- topPanel: {- height: 50,- width: '100%',- overflowX: 'overlay',- backgroundColor: theme.palette.background.default- },- centerPanel: {- flex: '1 1 auto',- width: '100%',- backgroundColor: theme.palette.background.default- },- flexMiddle: {- flex: '1 1 10%',- display: 'flex',- flexDirection: 'column'- },- folderButton: {- minWidth: 30,- whiteSpace: 'nowrap',- paddingLeft: 3,- paddingRight: 3,- margin: '0 auto'- },- locationSelectorButton: {- whiteSpace: 'nowrap',- paddingLeft: 10,- paddingRight: 10,- alignItems: 'center'- }+ mainPanel: {+ flex: '1 1 100%',+ width: '100%',+ height: '100%',+ maxHeight: '100%',+ overflow: 'hidden',+ backgroundColor: theme.palette.background.default,+ display: 'flex',+ flexDirection: 'column'+ },+ toolbar: {+ paddingLeft: 5,+ paddingRight: 5,+ paddingTop: 5,+ display: 'flex',+ justifyContent: 'center'+ },+ topPanel: {+ height: 50,+ width: '100%',+ overflowX: 'overlay',+ backgroundColor: theme.palette.background.default+ },+ centerPanel: {+ flex: '1 1 auto',+ width: '100%',+ backgroundColor: theme.palette.background.default+ },+ flexMiddle: {+ flex: '1 1 10%',+ display: 'flex',+ flexDirection: 'column'+ },+ folderButton: {+ minWidth: 30,+ whiteSpace: 'nowrap',+ paddingLeft: 3,+ paddingRight: 3,+ margin: '0 auto'+ },+ locationSelectorButton: {+ whiteSpace: 'nowrap',+ paddingLeft: 10,+ paddingRight: 10,+ alignItems: 'center'+ }});-type Props = {- classes: Object,- windowHeight: number,- windowWidth: number,- directoryContent: Array<Object>,- currentDirectoryPath: string | null,- searchResultCount: number,- addTags: () => void,- removeTags: () => void,- removeAllTags: () => void,- editTagForEntry: () => void,- openFileNatively: (path: string) => void,- toggleCreateFileDialog: () => void,- deleteFile: () => void,- renameFile: () => void,- openDirectory: () => void,- showInFileManager: () => void,- openFile: (path: string) => void,- deleteDirectory: (path: string) => void,- reflectCreateEntry: (path: string, isFile: boolean) => void,- loadDirectoryContent: (path: string) => void,- loadParentDirectoryContent: () => void,- setLastSelectedEntry: (entryPath: string | null) => void,- isReadOnlyMode: boolean,- isDesktopMode: boolean,- showNotification: (content: string) => void,- openSearchPanel: () => void,- showDrawer: () => void,- maxSearchResults: number-};+interface Props {+ classes: Object;+ windowHeight: number;+ windowWidth: number;+ directoryContent: Array<Object>;+ currentDirectoryPath: string | null;+ searchResultCount: number;+ addTags: () => void;+ removeTags: () => void;+ removeAllTags: () => void;+ editTagForEntry: () => void;+ openFileNatively: (path: string) => void;+ toggleCreateFileDialog: () => void;+ deleteFile: () => void;+ renameFile: () => void;+ openDirectory: () => void;+ showInFileManager: () => void;+ openFile: (path: string) => void;+ deleteDirectory: (path: string) => void;+ reflectCreateEntry: (path: string, isFile: boolean) => void;+ loadDirectoryContent: (path: string) => void;+ loadParentDirectoryContent: () => void;+ setLastSelectedEntry: (entryPath: string | null) => void;+ isReadOnlyMode: boolean;+ isDesktopMode: boolean;+ showNotification: (content: string) => void;+ openSearchPanel: () => void;+ showDrawer: () => void;+ maxSearchResults: number;+}-type State = {- currentPerspective: string,- currentPath?: string,- pathParts?: Array<string>,- isPropertiesPanelVisible?: boolean,- locationChooserMenuOpened?: boolean,- locationChooserMenuAnchorEl?: null | Object,- directoryMenuOpened?: boolean,- directoryMenuAnchorEl?: null | Object,- perspectiveChooserMenuOpened?: boolean,- perspectiveChooserMenuAnchorEl?: null | Object,- directoryContextMenuOpened: boolean,- directoryContextMenuAnchorEl: null | Object,- perspectiveCommand?: null | Object-};+interface State {+ currentPerspective: string;+ currentPath?: string;+ pathParts?: Array<string>;+ isPropertiesPanelVisible?: boolean;+ locationChooserMenuOpened?: boolean;+ locationChooserMenuAnchorEl?: null | Object;+ directoryMenuOpened?: boolean;+ directoryMenuAnchorEl?: null | Object;+ perspectiveChooserMenuOpened?: boolean;+ perspectiveChooserMenuAnchorEl?: null | Object;+ directoryContextMenuOpened: boolean;+ directoryContextMenuAnchorEl: null | Object;+ perspectiveCommand?: null | Object;+}class FolderContainer extends React.Component<Props, State> {- state = {- currentPerspective: window.ExtDefaultPerspective || 'default',- currentPath: '',- pathParts: [],- isPropertiesPanelVisible: false,- isDirectoryMenuOpened: false,- directoryContextMenuOpened: false,- directoryContextMenuAnchorEl: null,- perspectiveChooserMenuOpened: false,- perspectiveChooserMenuAnchorEl: null,- perspectiveCommand: null- };+ state = {+ currentPerspective: window.ExtDefaultPerspective || 'default',+ currentPath: '',+ pathParts: [],+ isPropertiesPanelVisible: false,+ isDirectoryMenuOpened: false,+ directoryContextMenuOpened: false,+ directoryContextMenuAnchorEl: null,+ perspectiveChooserMenuOpened: false,+ perspectiveChooserMenuAnchorEl: null,+ perspectiveCommand: null+ };- static getDerivedStateFromProps(nextProps, prevState) {- if (- nextProps.currentDirectoryPath &&- prevState.currentPath !== nextProps.currentDirectoryPath- ) {- let currentLocationPath = '';- if (nextProps.currentLocationPath) {- currentLocationPath = nextProps.currentLocationPath;- }- // Make the path unix like ending always with /- const addSlash = PlatformIO.haveObjectStoreSupport() ? '//' : '/';- let normalizedCurrentPath =- addSlash +- normalizePath(nextProps.currentDirectoryPath.split('\\').join('/'));- const normalizedCurrentLocationPath =- addSlash + normalizePath(currentLocationPath.split('\\').join('/'));- // console.log('Current path : ' + normalizedCurrentPath);- // console.log('Current location path : ' + normalizedCurrentLocationPath);- let pathParts = [];- while (- normalizedCurrentPath.lastIndexOf('/') > 0 &&- normalizedCurrentPath.startsWith(normalizedCurrentLocationPath)- ) {- pathParts.push(- normalizedCurrentPath.substring(- PlatformIO.haveObjectStoreSupport() ? 2 : 1- )- );- normalizedCurrentPath = normalizedCurrentPath.substring(- 0,- normalizedCurrentPath.lastIndexOf('/')- );- }- // console.log('Path parts : ' + JSON.stringify(pathParts));- if (pathParts.length >= 1) {- pathParts = pathParts.slice(1, pathParts.length); // remove current directory- }- pathParts = pathParts.reverse();- if (pathParts.length > 2) {- pathParts = pathParts.slice(pathParts.length - 2, pathParts.length); // leave only the last 2 dirs in the path- }- return {- ...prevState,- currentPath: nextProps.currentDirectoryPath,- pathParts- };- }- return null;- }+ static getDerivedStateFromProps(nextProps, prevState) {+ if (+ nextProps.currentDirectoryPath &&+ prevState.currentPath !== nextProps.currentDirectoryPath+ ) {+ let currentLocationPath = '';+ if (nextProps.currentLocationPath) {+ currentLocationPath = nextProps.currentLocationPath;+ }+ // Make the path unix like ending always with /+ const addSlash = PlatformIO.haveObjectStoreSupport() ? '//' : '/';+ let normalizedCurrentPath =+ addSlash ++ normalizePath(nextProps.currentDirectoryPath.split('\\').join('/'));+ const normalizedCurrentLocationPath =+ addSlash + normalizePath(currentLocationPath.split('\\').join('/'));+ // console.log('Current path : ' + normalizedCurrentPath);+ // console.log('Current location path : ' + normalizedCurrentLocationPath);+ let pathParts = [];+ while (+ normalizedCurrentPath.lastIndexOf('/') > 0 &&+ normalizedCurrentPath.startsWith(normalizedCurrentLocationPath)+ ) {+ pathParts.push(+ normalizedCurrentPath.substring(+ PlatformIO.haveObjectStoreSupport() ? 2 : 1+ )+ );+ normalizedCurrentPath = normalizedCurrentPath.substring(+ 0,+ normalizedCurrentPath.lastIndexOf('/')+ );+ }+ // console.log('Path parts : ' + JSON.stringify(pathParts));+ if (pathParts.length >= 1) {+ pathParts = pathParts.slice(1, pathParts.length); // remove current directory+ }+ pathParts = pathParts.reverse();+ if (pathParts.length > 2) {+ pathParts = pathParts.slice(pathParts.length - 2, pathParts.length); // leave only the last 2 dirs in the path+ }+ return {+ ...prevState,+ currentPath: nextProps.currentDirectoryPath,+ pathParts+ };+ }+ return null;+ }- openDirectoryMenu = (event: Object) => {- this.setState({- directoryContextMenuOpened: true,- directoryContextMenuAnchorEl: event ? event.currentTarget : null- });- };+ openDirectoryMenu = (event: React.ChangeEvent<HTMLInputElement>) => {+ this.setState({+ directoryContextMenuOpened: true,+ directoryContextMenuAnchorEl: event ? event.currentTarget : null+ });+ };- closeDirectoryMenu = () => {- this.setState({- directoryContextMenuOpened: false,- directoryContextMenuAnchorEl: null- });- };+ closeDirectoryMenu = () => {+ this.setState({+ directoryContextMenuOpened: false,+ directoryContextMenuAnchorEl: null+ });+ };- switchPerspective = (perspectiveId: string) => {- if (!Pro) {- this.props.showNotification(i18n.t('core:needProVersion'));- return;- }- this.setState({- currentPerspective: perspectiveId || 'default'- });- };+ switchPerspective = (perspectiveId: string) => {+ if (!Pro) {+ this.props.showNotification(i18n.t('core:needProVersion'));+ return;+ }+ this.setState({+ currentPerspective: perspectiveId || 'default'+ });+ };- togglePerspectiveChooserClose = (event?: Object) => {- this.setState({- perspectiveChooserMenuOpened: !this.state.perspectiveChooserMenuOpened,- perspectiveChooserMenuAnchorEl: event ? event.currentTarget : null- });- };+ togglePerspectiveChooserClose = (event?: Object) => {+ this.setState({+ perspectiveChooserMenuOpened: !this.state.perspectiveChooserMenuOpened,+ perspectiveChooserMenuAnchorEl: event ? event.currentTarget : null+ });+ };- renderPerspective() {- if (- !this.props.currentDirectoryPath ||- this.props.currentDirectoryPath.length < 2- ) {- return <WelcomePanelAsync />;- } else if (this.state.currentPerspective === 'gallery') {- return (- <GalleryPerspectiveAsync- directoryContent={this.props.directoryContent}- currentDirectoryPath={this.props.currentDirectoryPath}- windowWidth={this.props.windowWidth}- switchPerspective={this.switchPerspective}- />- );- } else if (this.state.currentPerspective === 'treeviz') {- return (- <TreeVizPerspectiveAsync- directoryContent={this.props.directoryContent}- currentDirectoryPath={this.props.currentDirectoryPath}- windowWidth={this.props.windowWidth}- switchPerspective={this.switchPerspective}- />- );- } else if (this.state.currentPerspective === 'mapique') {- return (- <MapiquePerspectiveAsync- directoryContent={this.props.directoryContent}- currentDirectoryPath={this.props.currentDirectoryPath}- windowWidth={this.props.windowWidth}- switchPerspective={this.switchPerspective}- />- );- }- // else if (this.state.currentPerspective === 'default') {- return (- <GridPerspectiveAsync- directoryContent={this.props.directoryContent}- loadDirectoryContent={this.props.loadDirectoryContent}- openFile={this.props.openFile}- loadParentDirectoryContent={this.props.loadParentDirectoryContent}- deleteFile={this.props.deleteFile}- renameFile={this.props.renameFile}- openDirectory={this.props.openDirectory}- showInFileManager={this.props.showInFileManager}- currentDirectoryPath={this.props.currentDirectoryPath}- setLastSelectedEntry={this.props.setLastSelectedEntry}- perspectiveCommand={this.state.perspectiveCommand}- addTags={this.props.addTags}- editTagForEntry={this.props.editTagForEntry}- deleteDirectory={this.props.deleteDirectory}- removeTags={this.props.removeTags}- removeAllTags={this.props.removeAllTags}- windowWidth={this.props.windowWidth}- />- );- }+ renderPerspective() {+ if (+ !this.props.currentDirectoryPath ||+ this.props.currentDirectoryPath.length < 2+ ) {+ return <WelcomePanelAsync />;+ } else if (this.state.currentPerspective === 'gallery') {+ return (+ <GalleryPerspectiveAsync+ directoryContent={this.props.directoryContent}+ currentDirectoryPath={this.props.currentDirectoryPath}+ windowWidth={this.props.windowWidth}+ switchPerspective={this.switchPerspective}+ />+ );+ } else if (this.state.currentPerspective === 'treeviz') {+ return (+ <TreeVizPerspectiveAsync+ directoryContent={this.props.directoryContent}+ currentDirectoryPath={this.props.currentDirectoryPath}+ windowWidth={this.props.windowWidth}+ switchPerspective={this.switchPerspective}+ />+ );+ } else if (this.state.currentPerspective === 'mapique') {+ return (+ <MapiquePerspectiveAsync+ directoryContent={this.props.directoryContent}+ currentDirectoryPath={this.props.currentDirectoryPath}+ windowWidth={this.props.windowWidth}+ switchPerspective={this.switchPerspective}+ />+ );+ }+ // else if (this.state.currentPerspective === 'default') {+ return (+ <GridPerspectiveAsync+ directoryContent={this.props.directoryContent}+ loadDirectoryContent={this.props.loadDirectoryContent}+ openFile={this.props.openFile}+ loadParentDirectoryContent={this.props.loadParentDirectoryContent}+ deleteFile={this.props.deleteFile}+ renameFile={this.props.renameFile}+ openDirectory={this.props.openDirectory}+ showInFileManager={this.props.showInFileManager}+ currentDirectoryPath={this.props.currentDirectoryPath}+ setLastSelectedEntry={this.props.setLastSelectedEntry}+ perspectiveCommand={this.state.perspectiveCommand}+ addTags={this.props.addTags}+ editTagForEntry={this.props.editTagForEntry}+ deleteDirectory={this.props.deleteDirectory}+ removeTags={this.props.removeTags}+ removeAllTags={this.props.removeAllTags}+ windowWidth={this.props.windowWidth}+ />+ );+ }- render() {- const {- currentDirectoryPath = '',- loadDirectoryContent,- searchResultCount,- classes,- maxSearchResults,- openSearchPanel,- showDrawer,- isDesktopMode,- loadParentDirectoryContent- } = this.props;- const normalizedCurrentDirPath = normalizePath(- currentDirectoryPath.split('\\').join('/')- );- let searchResultCounterText = searchResultCount + ' ' + i18n.t('entries');- if (searchResultCount >= maxSearchResults) {- searchResultCounterText =- 'More than ' +- (maxSearchResults - 1) +- ' entries found, showing only the first ' +- maxSearchResults;- }- return (- <div>- <div className={classes.mainPanel}>- <div className={classes.topPanel}>- <div className={classes.toolbar}>- {isDesktopMode ? (- <LocationMenu />- ) : (- <Button- id="mobileMenuButton"- style={{ marginLeft: -8 }}- onClick={showDrawer}- >- <MenuIcon />- </Button>- )}- <CounterBadge- showZero={true}- title={searchResultCounterText}- badgeContent={searchResultCount}- color="secondary"- max={maxSearchResults - 1}- onClick={() => {- openSearchPanel();- }}- />- <div className={classes.flexMiddle} />- {currentDirectoryPath && (- <React.Fragment>- {isDesktopMode &&- this.state.pathParts &&- this.state.pathParts.map(pathPart => (- <Button- key={pathPart}- onClick={() => loadDirectoryContent(pathPart)}- title={'Navigate to: ' + pathPart}- style={{- paddingLeft: 3,- paddingRight: 0,- minWidth: 10- }}- >- {extractShortDirectoryName(pathPart, '/')}- / - </Button>- ))}- {!isDesktopMode &&- this.state.pathParts &&- this.state.pathParts.length > 0 && (- <React.Fragment>- <Button- onClick={loadParentDirectoryContent}- data-tid="openParentDirectory"- style={{ paddingLeft: 3, paddingRight: 0 }}- >- <BackButtonIcon />- </Button>- </React.Fragment>- )}- <Button- data-tid="folderContainerOpenDirMenu"- title={- i18n.t('core:openDirectoryMenu') +- ' - ' +- (currentDirectoryPath || '')- }- className={classes.folderButton}- onClick={this.openDirectoryMenu}- onContextMenu={this.openDirectoryMenu}- >- {extractShortDirectoryName(- normalizePath(normalizedCurrentDirPath),- '/'- )}- <MoreVertIcon />- </Button>- <DirectoryMenu- open={this.state.directoryContextMenuOpened}- onClose={this.closeDirectoryMenu}- anchorEl={this.state.directoryContextMenuAnchorEl}- directoryPath={currentDirectoryPath}- loadDirectoryContent={this.props.loadDirectoryContent}- openFileNatively={this.props.openFileNatively}- openDirectory={this.props.openDirectory}- loadParentDirectoryContent={loadParentDirectoryContent}- showInFileManager={this.props.showInFileManager}- reflectCreateEntry={this.props.reflectCreateEntry}- openFile={this.props.openFile}- toggleCreateFileDialog={this.props.toggleCreateFileDialog}- deleteDirectory={this.props.deleteDirectory}- showNotification={this.props.showNotification}- switchPerspective={this.switchPerspective}- isReadOnlyMode={this.props.isReadOnlyMode}- />- </React.Fragment>- )}- </div>- </div>- <div- className={classes.centerPanel}- style={{ height: this.props.windowHeight }}- >- {this.renderPerspective()}- </div>- </div>- </div>- );- }+ render() {+ const {+ currentDirectoryPath = '',+ loadDirectoryContent,+ searchResultCount,+ classes,+ maxSearchResults,+ openSearchPanel,+ showDrawer,+ isDesktopMode,+ loadParentDirectoryContent+ } = this.props;+ const normalizedCurrentDirPath = normalizePath(+ currentDirectoryPath.split('\\').join('/')+ );+ let searchResultCounterText = searchResultCount + ' ' + i18n.t('entries');+ if (searchResultCount >= maxSearchResults) {+ searchResultCounterText =+ 'More than ' ++ (maxSearchResults - 1) ++ ' entries found, showing only the first ' ++ maxSearchResults;+ }+ return (+ <div>+ <div className={classes.mainPanel}>+ <div className={classes.topPanel}>+ <div className={classes.toolbar}>+ {isDesktopMode ? (+ <LocationMenu />+ ) : (+ <Button+ id="mobileMenuButton"+ style={{ marginLeft: -8 }}+ onClick={showDrawer}+ >+ <MenuIcon />+ </Button>+ )}+ <CounterBadge+ showZero={true}+ title={searchResultCounterText}+ badgeContent={searchResultCount}+ color="secondary"+ max={maxSearchResults - 1}+ onClick={() => {+ openSearchPanel();+ }}+ />+ <div className={classes.flexMiddle} />+ {currentDirectoryPath && (+ <React.Fragment>+ {isDesktopMode &&+ this.state.pathParts &&+ this.state.pathParts.map(pathPart => (+ <Button+ key={pathPart}+ onClick={() => loadDirectoryContent(pathPart)}+ title={'Navigate to: ' + pathPart}+ style={{+ paddingLeft: 3,+ paddingRight: 0,+ minWidth: 10+ }}+ >+ {extractShortDirectoryName(pathPart, '/')}+ / + </Button>+ ))}+ {!isDesktopMode &&+ this.state.pathParts &&+ this.state.pathParts.length > 0 && (+ <React.Fragment>+ <Button+ onClick={loadParentDirectoryContent}+ data-tid="openParentDirectory"+ style={{ paddingLeft: 3, paddingRight: 0 }}+ >+ <BackButtonIcon />+ </Button>+ </React.Fragment>+ )}+ <Button+ data-tid="folderContainerOpenDirMenu"+ title={+ i18n.t('core:openDirectoryMenu') ++ ' - ' ++ (currentDirectoryPath || '')+ }+ className={classes.folderButton}+ onClick={this.openDirectoryMenu}+ onContextMenu={this.openDirectoryMenu}+ >+ {extractShortDirectoryName(+ normalizePath(normalizedCurrentDirPath),+ '/'+ )}+ <MoreVertIcon />+ </Button>+ <DirectoryMenu+ open={this.state.directoryContextMenuOpened}+ onClose={this.closeDirectoryMenu}+ anchorEl={this.state.directoryContextMenuAnchorEl}+ directoryPath={currentDirectoryPath}+ loadDirectoryContent={this.props.loadDirectoryContent}+ openFileNatively={this.props.openFileNatively}+ openDirectory={this.props.openDirectory}+ loadParentDirectoryContent={loadParentDirectoryContent}+ showInFileManager={this.props.showInFileManager}+ reflectCreateEntry={this.props.reflectCreateEntry}+ openFile={this.props.openFile}+ toggleCreateFileDialog={this.props.toggleCreateFileDialog}+ deleteDirectory={this.props.deleteDirectory}+ showNotification={this.props.showNotification}+ switchPerspective={this.switchPerspective}+ isReadOnlyMode={this.props.isReadOnlyMode}+ />+ </React.Fragment>+ )}+ </div>+ </div>+ <div+ className={classes.centerPanel}+ style={{ height: this.props.windowHeight }}+ >+ {this.renderPerspective()}+ </div>+ </div>+ </div>+ );+ }}function mapStateToProps(state) {- return {- currentDirectoryPath: getDirectoryPath(state),- lastSelectedEntry: getLastSelectedEntry(state),- perspectives: getPerspectives(state),- directoryContent: getDirectoryContent(state),- searchResultCount: getSearchResultCount(state),- currentLocationPath: getCurrentLocationPath(state),- maxSearchResults: getMaxSearchResults(state),- isDesktopMode: getDesktopMode(state),- isReadOnlyMode: isReadOnlyMode(state)- };+ return {+ currentDirectoryPath: getDirectoryPath(state),+ lastSelectedEntry: getLastSelectedEntry(state),+ perspectives: getPerspectives(state),+ directoryContent: getDirectoryContent(state),+ searchResultCount: getSearchResultCount(state),+ currentLocationPath: getCurrentLocationPath(state),+ maxSearchResults: getMaxSearchResults(state),+ isDesktopMode: getDesktopMode(state),+ isReadOnlyMode: isReadOnlyMode(state)+ };}function mapActionCreatorsToProps(dispatch) {- return bindActionCreators(- {- addTags: TaggingActions.addTags,- removeTags: TaggingActions.removeTags,- removeAllTags: TaggingActions.removeAllTags,- editTagForEntry: TaggingActions.editTagForEntry,- openFileNatively: AppActions.openFileNatively,- toggleCreateFileDialog: AppActions.toggleCreateFileDialog,- deleteFile: AppActions.deleteFile,- renameFile: AppActions.renameFile,- getNextFile: AppActions.getNextFile,- getPrevFile: AppActions.getPrevFile,- openDirectory: AppActions.openDirectory,- showInFileManager: AppActions.showInFileManager,- openFile: AppActions.openFile,- deleteDirectory: AppActions.deleteDirectory,- reflectCreateEntry: AppActions.reflectCreateEntry,- loadDirectoryContent: AppActions.loadDirectoryContent,- loadParentDirectoryContent: AppActions.loadParentDirectoryContent,- setLastSelectedEntry: AppActions.setLastSelectedEntry,- showNotification: AppActions.showNotification,- openSearchPanel: AppActions.openSearchPanel- },- dispatch- );+ return bindActionCreators(+ {+ addTags: TaggingActions.addTags,+ removeTags: TaggingActions.removeTags,+ removeAllTags: TaggingActions.removeAllTags,+ editTagForEntry: TaggingActions.editTagForEntry,+ openFileNatively: AppActions.openFileNatively,+ toggleCreateFileDialog: AppActions.toggleCreateFileDialog,+ deleteFile: AppActions.deleteFile,+ renameFile: AppActions.renameFile,+ getNextFile: AppActions.getNextFile,+ getPrevFile: AppActions.getPrevFile,+ openDirectory: AppActions.openDirectory,+ showInFileManager: AppActions.showInFileManager,+ openFile: AppActions.openFile,+ deleteDirectory: AppActions.deleteDirectory,+ reflectCreateEntry: AppActions.reflectCreateEntry,+ loadDirectoryContent: AppActions.loadDirectoryContent,+ loadParentDirectoryContent: AppActions.loadParentDirectoryContent,+ setLastSelectedEntry: AppActions.setLastSelectedEntry,+ showNotification: AppActions.showNotification,+ openSearchPanel: AppActions.openSearchPanel+ },+ dispatch+ );}export default connect(- mapStateToProps,- mapActionCreatorsToProps+ mapStateToProps,+ mapActionCreatorsToProps)(withStyles(styles)(FolderContainer));diff --git a/app/components/LocationManager.tsx b/app/components/LocationManager.tsxindex 4d4b480e8..acdb24c43 100644--- a/app/components/LocationManager.tsx+++ b/app/components/LocationManager.tsx@@ -58,7 +58,7 @@ import {actions as LocationActions,getLocations,locationType,- type Location+ Location} from '../reducers/locations';import {actions as AppActions,@@ -71,7 +71,6 @@ import {getShowUnixHiddenEntries} from '../reducers/settings';import i18n from '../services/i18n';-import { isObj } from '../utils/misc';import AppConfig from '../config';import PlatformIO from '../services/platform-io';import TargetMoveFileBox from './TargetMoveFileBox';@@ -80,7 +79,7 @@ import IOActions from '../reducers/io-actions';const isLocationsReadOnly = window.ExtLocationsReadOnly;-type Props = {+interface Props {classes: Object,locations: Array<Location>,perspectives: Array<Object>,@@ -112,7 +111,7 @@ type Props = {moveFiles: (files: Array<string>, destination: string) => void};-type State = {+interface State {locationDirectoryContextMenuAnchorEl?: Object | null,locationContextMenuOpened?: boolean,directoryContextMenuAnchorEl?: Object | null,@@ -124,7 +123,6 @@ type State = {isEditLocationDialogOpened?: boolean,isDeleteLocationDialogOpened?: boolean,isSelectDirectoryDialogOpened?: boolean,- isCreateDirectoryDialogOpened?: boolean,createLocationDialogKey: string,isCreateDirectoryDialogOpened?: boolean,locationManagerMenuOpened: boolean,@@ -270,7 +268,7 @@ class LocationManager extends React.Component<Props, State> {getMergedDirsCopy = (path: string, arrChildren: Array<SubFolder>) => {const entries = Object.entries(this.state.dirs);for (const [uuid, arrSubDirs] of entries) {- const arr = arrSubDirs.length;+ const arr: number = arrSubDirs.length;let a;for (a = 0; a < arr; a += 1) {if (path === arrSubDirs[a].path) {@@ -406,7 +404,7 @@ class LocationManager extends React.Component<Props, State> {this.setState({ isDeleteLocationDialogOpened: true });};- handleDirectoryContextMenu = (event: Object, directoryPath: string) => {+ handleDirectoryContextMenu = (event: React.ChangeEvent<HTMLInputElement> , directoryPath: string) => {this.setState({directoryContextMenuOpened: true,directoryContextMenuAnchorEl: event.currentTarget,@@ -414,7 +412,7 @@ class LocationManager extends React.Component<Props, State> {});};- toggleDirectoryMenuClose = (event: Object) => {+ toggleDirectoryMenuClose = (event: React.ChangeEvent<HTMLInputElement>) => {this.setState({directoryContextMenuOpened: !this.state.directoryContextMenuOpened,directoryContextMenuAnchorEl: event ? event.currentTarget : null@@ -696,7 +694,7 @@ class LocationManager extends React.Component<Props, State> {);};- handleLocationManagerMenu = (event: Object) => {+ handleLocationManagerMenu = (event: React.ChangeEvent<HTMLInputElement> ) => {this.setState({locationManagerMenuOpened: true,locationManagerMenuAnchorEl: event.currentTargetdiff --git a/app/components/Search.tsx b/app/components/Search.tsxindex e0c1e3127..c84877063 100644--- a/app/components/Search.tsx+++ b/app/components/Search.tsx@@ -59,48 +59,48 @@ import {import { getMaxSearchResults } from '../reducers/settings';import styles from './SidePanels.css';import i18n from '../services/i18n';-import { FileTypeGroups, type SearchQuery } from '../services/search';+import { FileTypeGroups, SearchQuery } from '../services/search';import { Pro } from '../pro';import SearchMenu from './menus/SearchMenu';-import type { Tag } from '../reducers/taglibrary';+import { Tag } from '../reducers/taglibrary';import ocl from '../utils/openlocationcode';import { formatDateTime, extractTimePeriod } from '../utils/dates';import { isPlusCode, parseLatLon } from '../utils/misc';import PlatformIO from '../services/platform-io';-type Props = {- classes: Object,- style: Object,- searchLocationIndex: (searchQuery: SearchQuery) => void,- loadDirectoryContent: (path: string) => void,- hideDrawer?: () => void,- currentDirectory: string,- indexedEntriesCount: number,- maxSearchResults: number,- indexing: boolean-};+interface Props {+ classes: Object;+ style: Object;+ searchLocationIndex: (searchQuery: SearchQuery) => void;+ loadDirectoryContent: (path: string) => void;+ hideDrawer?: () => void;+ currentDirectory: string;+ indexedEntriesCount: number;+ maxSearchResults: number;+ indexing: boolean;+}-type State = {- textQuery: string,- tagsAND: Array<Tag>,- tagsOR: Array<Tag>,- tagsNOT: Array<Tag>,- fileTypes: Array<string>,- searchBoxing: 'location' | 'folder',- lastModified: string,- tagTimePeriod: string,- tagTimePeriodHelper: string,- tagPlace: string,- tagPlaceHelper: string,- tagTimePeriodFrom: Date | null,- tagTimePeriodTo: Date | null,- tagPlaceLat: number | null,- tagPlaceLong: number | null,- tagPlaceRadius: number,- fileSize: string,- searchMenuOpened: boolean,- searchMenuAnchorEl: Object | null-};+interface State {+ textQuery: string;+ tagsAND: Array<Tag>;+ tagsOR: Array<Tag>;+ tagsNOT: Array<Tag>;+ fileTypes: Array<string>;+ searchBoxing: 'location' | 'folder';+ lastModified: string;+ tagTimePeriod: string;+ tagTimePeriodHelper: string;+ tagPlace: string;+ tagPlaceHelper: string;+ tagTimePeriodFrom: Date | null;+ tagTimePeriodTo: Date | null;+ tagPlaceLat: number | null;+ tagPlaceLong: number | null;+ tagPlaceRadius: number;+ fileSize: string;+ searchMenuOpened: boolean;+ searchMenuAnchorEl: Object | null;+}class Search extends React.Component<Props, State> {state = {@@ -286,7 +286,7 @@ class Search extends React.Component<Props, State> {this.props.searchLocationIndex(searchQuery);};- handleSearchMenu = (event: Object) => {+ handleSearchMenu = (event: React.ChangeEvent<HTMLInputElement>) => {this.setState({searchMenuOpened: true,searchMenuAnchorEl: event.currentTargetdiff --git a/app/components/TagLibrary.tsx b/app/components/TagLibrary.tsxindex e25a6eb47..1b9ecb4cc 100644--- a/app/components/TagLibrary.tsx+++ b/app/components/TagLibrary.tsx@@ -82,7 +82,6 @@ type Props = {addTags: () => void;importTagGroups: () => void;exportTagGroups: () => void;- toggleTagGroup: () => void;createTagGroup: () => void;addTag: () => void;moveTag: () => void;@@ -129,22 +128,14 @@ class TagLibrary extends React.Component<Props, State> {isDeleteTagDialogOpened: false};- handleCloseDialogs = () => {- this.setState({- isCreateLocationDialogOpened: false,- isEditLocationDialogOpened: false,- isDeleteLocationDialogOpened: false,- isDeleteDirectoryDialogOpened: false,- isCreateDirectoryDialogOpened: false,- isRenameDirectoryDialogOpened: false- });- };-handleTagGroupTitleClick = (event: Object, tagGroup) => {this.props.toggleTagGroup(tagGroup.expanded, tagGroup.uuid);};- handleTagGroupMenu = (event: Object, tagGroup) => {+ handleTagGroupMenu = (+ event: React.ChangeEvent<HTMLInputElement>,+ tagGroup+ ) => {this.setState({tagGroupMenuOpened: true,tagGroupMenuAnchorEl: event.currentTarget,@@ -152,7 +143,11 @@ class TagLibrary extends React.Component<Props, State> {});};- handleTagMenu = (event: Object, tag, tagGroup) => {+ handleTagMenu = (+ event: React.ChangeEvent<HTMLInputElement>,+ tag,+ tagGroup: TagGroup+ ) => {this.setState({tagMenuOpened: true,tagMenuAnchorEl: event.currentTarget,@@ -161,7 +156,7 @@ class TagLibrary extends React.Component<Props, State> {});};- handleTagLibraryMenu = (event: Object) => {+ handleTagLibraryMenu = (event: React.ChangeEvent<HTMLInputElement>) => {this.setState({tagLibraryMenuOpened: true,tagLibraryMenuAnchorEl: event.currentTargetdiff --git a/app/components/VerticalNavigation.tsx b/app/components/VerticalNavigation.tsxindex a44bc59d4..f385f1136 100644--- a/app/components/VerticalNavigation.tsx+++ b/app/components/VerticalNavigation.tsx@@ -40,7 +40,6 @@ import LocationManager from '../components/LocationManager';import HelpFeedbackPanel from '../components/HelpFeedbackPanel';import i18n from '../services/i18n';import { Pro } from '../pro';-import { Tag } from '../reducers/taglibrary';import {actions as AppActions,getDirectoryPath,@@ -64,7 +63,7 @@ const ProTeaserDialogAsync = props => (</React.Suspense>);-type Props = {+interface Props {theme: Object;isFirstRun: boolean;directoryPath: string;@@ -91,11 +90,11 @@ type Props = {switchTheme: () => void;showNotification: (message: string) => void;isReadOnlyMode: boolean;-};+}-type State = {+interface State {isProTeaserVisible: boolean; // evtl. redux migration-};+}class VerticalNavigation extends React.Component<Props, State> {state = {@@ -144,7 +143,6 @@ class VerticalNavigation extends React.Component<Props, State> {render() {const {- isFirstRun,isLocationManagerPanelOpened,isTagLibraryPanelOpened,isSearchPanelOpened,@@ -167,7 +165,6 @@ class VerticalNavigation extends React.Component<Props, State> {openURLExternally,showNotification,directoryPath,- setFirstRun,theme} = this.props;return (diff --git a/app/components/dialogs/ColorPickerDialog.tsx b/app/components/dialogs/ColorPickerDialog.tsxindex fd80e919c..271c79cc7 100644--- a/app/components/dialogs/ColorPickerDialog.tsx+++ b/app/components/dialogs/ColorPickerDialog.tsx@@ -27,105 +27,105 @@ import { SketchPicker } from 'react-color';import i18n from '../../services/i18n';const presetColors = [- '#ffffff',- '#000000',- '#ac725e',- '#d06b64',- '#f83a22',- '#fa573c',- '#ff7537',- '#ffad46',- '#42d692',- '#008000',- '#7bd148',- '#fad165',- '#FFCC24',- '#92e1c0',- '#9fe1e7',- '#9fc6e7',- '#4986e7',- '#9a9cff',- '#b99aff',- '#c2c2c2',- '#cabdbf',- '#cca6ac',- '#f691b2',- '#cd74e6',- '#a47ae2'+ '#ffffff',+ '#000000',+ '#ac725e',+ '#d06b64',+ '#f83a22',+ '#fa573c',+ '#ff7537',+ '#ffad46',+ '#42d692',+ '#008000',+ '#7bd148',+ '#fad165',+ '#FFCC24',+ '#92e1c0',+ '#9fe1e7',+ '#9fc6e7',+ '#4986e7',+ '#9a9cff',+ '#b99aff',+ '#c2c2c2',+ '#cabdbf',+ '#cca6ac',+ '#f691b2',+ '#cd74e6',+ '#a47ae2'];-type Props = {- classes: Object,- open: boolean,- color: string,- setColor: (color: string) => void,- presetColors: Array<string>,- onClose: () => void-};+interface Props {+ classes: Object;+ open: boolean;+ color: string;+ setColor: (color: string) => void;+ presetColors?: Array<string>;+ onClose: () => void;+}const styles = {- noBorder: {- padding: '0 !important',- boxShadow: 'none !important',- backgroundColor: 'transparent !important'- }+ noBorder: {+ padding: '0 !important',+ boxShadow: 'none !important',+ backgroundColor: 'transparent !important'+ }};const ColorPickerDialog = (props: Props) => {- const [color, setColor] = useState(undefined);- const [colorHex, setColorHex] = useState(undefined);- const { open = false, onClose } = props;+ const [color, setColor] = useState(undefined);+ const [colorHex, setColorHex] = useState(undefined);+ const { open = false, onClose } = props;- function onConfirm() {- if (color && colorHex) {- const hexAlphaColor = colorHex + Math.round(color.a * 255).toString(16);- props.setColor(hexAlphaColor);- }- props.onClose();- }+ function onConfirm() {+ if (color && colorHex) {+ const hexAlphaColor = colorHex + Math.round(color.a * 255).toString(16);+ props.setColor(hexAlphaColor);+ }+ props.onClose();+ }- function handleChangeComplete(newColor: Object) {- setColor(newColor.rgb);- setColorHex(newColor.hex);- }+ function handleChangeComplete(newColor: Object) {+ setColor(newColor.rgb);+ setColorHex(newColor.hex);+ }- return (- <Dialog open={open} onClose={onClose} keepMounted scroll="paper">- <DialogTitle data-tid="colorPickerDialogTitle">- {i18n.t('core:colorPickerDialogTitle')}- </DialogTitle>- <DialogContent- style={{- marginLeft: 'auto',- marginRight: 'auto'- }}- >- <SketchPicker- className={props.classes.noBorder}- name="color"- presetColors={props.presetColors ? props.presetColors : presetColors}- color={color || props.color}- onChangeComplete={handleChangeComplete}- />- </DialogContent>- <DialogActions>- <Button- data-tid="colorPickerCloseDialog"- onClick={props.onClose}- color="primary"- >- {i18n.t('core:cancel')}- </Button>- <Button- onClick={onConfirm}- data-tid="colorPickerConfirm"- color="primary"- >- {i18n.t('core:ok')}- </Button>- </DialogActions>- </Dialog>- );+ return (+ <Dialog open={open} onClose={onClose} keepMounted scroll="paper">+ <DialogTitle data-tid="colorPickerDialogTitle">+ {i18n.t('core:colorPickerDialogTitle')}+ </DialogTitle>+ <DialogContent+ style={{+ marginLeft: 'auto',+ marginRight: 'auto'+ }}+ >+ <SketchPicker+ className={props.classes.noBorder}+ name="color"+ presetColors={props.presetColors ? props.presetColors : presetColors}+ color={color || props.color}+ onChangeComplete={handleChangeComplete}+ />+ </DialogContent>+ <DialogActions>+ <Button+ data-tid="colorPickerCloseDialog"+ onClick={props.onClose}+ color="primary"+ >+ {i18n.t('core:cancel')}+ </Button>+ <Button+ onClick={onConfirm}+ data-tid="colorPickerConfirm"+ color="primary"+ >+ {i18n.t('core:ok')}+ </Button>+ </DialogActions>+ </Dialog>+ );};export default withStyles(styles)(ColorPickerDialog);diff --git a/app/components/dialogs/CreateFileDialog.tsx b/app/components/dialogs/CreateFileDialog.tsxindex a38535d77..868e27380 100644--- a/app/components/dialogs/CreateFileDialog.tsx+++ b/app/components/dialogs/CreateFileDialog.tsx@@ -44,286 +44,283 @@ import { actions as AppActions } from '../../reducers/app';import PlatformIO from '../../services/platform-io';const styles = theme => ({- root: {- width: 550,- height: '100%',- marginBottom: 30,- background: theme.palette.background.paper- },- form: {- width: '98%',- height: 'auto'- },- formControl: {- margin: theme.spacing(3)- },- group: {- margin: theme.spacing(1, 0)- }+ root: {+ width: 550,+ height: '100%',+ marginBottom: 30,+ background: theme.palette.background.paper+ },+ form: {+ width: '98%',+ height: 'auto'+ },+ formControl: {+ margin: theme.spacing(3)+ },+ group: {+ margin: theme.spacing(1, 0)+ }});-type Props = {- open: boolean,- fullScreen: boolean,- onClose: () => void,- selectedDirectoryPath: string | null,- showSelectDirectoryDialog: () => void,- createFileAdvanced: (- targetPath: string,- fileName: string,- content: string,- fileType: string- ) => void-};--type State = {- errorTextName: boolean,- errorTextPath: boolean,- disableConfirmButton: boolean,- selectedDirectoryPath: string | null,- fileName: string,- fileContent: string,- fileType: string-};--const { open, onClose, fullScreen } = props;+interface Props {+ open: boolean;+ fullScreen: boolean;+ onClose: () => void;+ selectedDirectoryPath: string | null;+ showSelectDirectoryDialog: () => void;+ createFileAdvanced: (+ targetPath: string,+ fileName: string,+ content: string,+ fileType: string+ ) => void;+}+interface State {+ errorTextName: boolean;+ errorTextPath: boolean;+ disableConfirmButton: boolean;+ selectedDirectoryPath: string | null;+ fileName: string;+ fileContent: string;+ fileType: string;+}class CreateFileDialog extends React.Component<Props, State> {- state = {- errorTextName: false,- errorTextPath: false,- openFolder: false,- disableConfirmButton: !(- this.props.selectedDirectoryPath &&- this.props.selectedDirectoryPath.length > 0- ),- selectedDirectoryPath: this.props.selectedDirectoryPath,- fileName:- 'note' +- AppConfig.beginTagContainer +- formatDateTime4Tag(new Date(), true) +- AppConfig.endTagContainer,- fileContent: '',- fileType: 'txt'- };+ state = {+ errorTextName: false,+ errorTextPath: false,+ openFolder: false,+ disableConfirmButton: !(+ this.props.selectedDirectoryPath &&+ this.props.selectedDirectoryPath.length > 0+ ),+ selectedDirectoryPath: this.props.selectedDirectoryPath,+ fileName:+ 'note' ++ AppConfig.beginTagContainer ++ formatDateTime4Tag(new Date(), true) ++ AppConfig.endTagContainer,+ fileContent: '',+ fileType: 'txt'+ };- fileName;+ fileName;- handleTypeChange = (event: Object) => {- const target = event.target;- this.setState({ fileType: target.value });- };+ handleTypeChange = (event: React.ChangeEvent<HTMLInputElement>) => {+ const target = event.target;+ this.setState({ fileType: target.value });+ };- handleInputChange = (event: Object) => {- const target = event.target;- const value = target.type === 'checkbox' ? target.checked : target.value;- const name = target.name;- this.setState(- {- [name]: value- },- this.handleValidation- );- };+ handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {+ const target = event.target;+ const value = target.type === 'checkbox' ? target.checked : target.value;+ const name = target.name;+ this.setState(+ {+ [name]: value+ },+ this.handleValidation+ );+ };- handleValidation() {- if (this.state.fileName && this.state.fileName.length > 0) {- this.setState({ errorTextName: false });- } else {- this.setState({ errorTextName: true });- }+ handleValidation() {+ if (this.state.fileName && this.state.fileName.length > 0) {+ this.setState({ errorTextName: false });+ } else {+ this.setState({ errorTextName: true });+ }- if (- this.state.selectedDirectoryPath &&- this.state.selectedDirectoryPath.length > 0- ) {- this.setState({ errorTextPath: false });- } else {- this.setState({ errorTextPath: true });- }+ if (+ this.state.selectedDirectoryPath &&+ this.state.selectedDirectoryPath.length > 0+ ) {+ this.setState({ errorTextPath: false });+ } else {+ this.setState({ errorTextPath: true });+ }- this.setState({- disableConfirmButton:- !this.state.fileName || !this.state.selectedDirectoryPath- });- }+ this.setState({+ disableConfirmButton:+ !this.state.fileName || !this.state.selectedDirectoryPath+ });+ }- openFolderChooser = () => {- if (AppConfig.isElectron) {- PlatformIO.selectDirectoryDialog()- .then(selectedPaths => {- this.setState(- {- selectedDirectoryPath: selectedPaths[0]- },- this.handleValidation- );- return true;- })- .catch(err => {- console.log('selectDirectoryDialog failed with: ' + err);- });- } else {- this.props.showSelectDirectoryDialog();- }- };+ openFolderChooser = () => {+ if (AppConfig.isElectron) {+ PlatformIO.selectDirectoryDialog()+ .then(selectedPaths => {+ this.setState(+ {+ selectedDirectoryPath: selectedPaths[0]+ },+ this.handleValidation+ );+ return true;+ })+ .catch(err => {+ console.log('selectDirectoryDialog failed with: ' + err);+ });+ } else {+ this.props.showSelectDirectoryDialog();+ }+ };- onConfirm = () => {- if (!this.state.disableConfirmButton) {- const {- fileName,- fileContent,- fileType,- selectedDirectoryPath- } = this.state;- this.props.createFileAdvanced(- selectedDirectoryPath,- fileName,- fileContent,- fileType- );- this.props.onClose();- }- };+ onConfirm = () => {+ if (!this.state.disableConfirmButton) {+ const {+ fileName,+ fileContent,+ fileType,+ selectedDirectoryPath+ } = this.state;+ this.props.createFileAdvanced(+ selectedDirectoryPath,+ fileName,+ fileContent,+ fileType+ );+ this.props.onClose();+ }+ };- handleKeyPress = (event: any) => {- if (event.key === 'Enter' || event.keyCode === 13) {- event.stopPropagation();- }- };+ handleKeyPress = (event: any) => {+ if (event.key === 'Enter' || event.keyCode === 13) {+ event.stopPropagation();+ }+ };- return = () => {- <Dialog- open={open}- onClose={onClose}- fullScreen={fullScreen}- keepMounted- scroll="paper"- // onKeyDown={confirmFunction}- >- <DialogTitle>{i18n.t('core:createFileTitle')}</DialogTitle>- <DialogContent data-tid="createFileDialog">- <FormControl fullWidth={true} error={this.state.errorTextName}>- <TextField- fullWidth={true}- error={this.state.errorTextName}- autoFocus- margin="dense"- name="fileName"- label={i18n.t('core:fileName')}- inputRef={ref => {- this.fileName = ref;- }}- onChange={this.handleInputChange}- value={this.state.fileName}- data-tid="createFileDialog_fileName"- />- {this.state.errorTextName && (- <FormHelperText>{i18n.t('core:fileNameHelp')}</FormHelperText>- )}- </FormControl>- <FormControl fullWidth={true}>- <TextField- id="textarea"- placeholder="Enter the content of your file / note"- multiline- name="fileContent"- value={this.state.fileContent}- onChange={this.handleInputChange}- onKeyDown={this.handleKeyPress}- margin="normal"- fullWidth={true}- rows={4}- rowsMax={10}- />- </FormControl>- <ListItem>- <Radio- checked={this.state.fileType === 'txt'}- onChange={this.handleTypeChange}- value="txt"- name="type"- aria-label={i18n.t('core:createTextFile')}- />- <FormHelperText>{i18n.t('core:createTextFile')}</FormHelperText>- <Radio- checked={this.state.fileType === 'md'}- onChange={this.handleTypeChange}- value="md"- name="type"- aria-label={i18n.t('core:createMarkdown')}- />- <FormHelperText>{i18n.t('core:createMarkdown')}</FormHelperText>- <Radio- checked={this.state.fileType === 'html'}- onChange={this.handleTypeChange}- value="html"- name="html"- aria-label={i18n.t('core:createRichTextFile')}- />- <FormHelperText>{i18n.t('core:createRichTextFile')}</FormHelperText>- </ListItem>- <FormControl fullWidth={true}>- <InputLabel htmlFor="name">{i18n.t('core:filePath')}</InputLabel>- <Input- required- margin="dense"- name="selectedDirectoryPath"- label={i18n.t('core:filePath')}- fullWidth={true}- data-tid="createFileDialog_filePath"- value={this.state.selectedDirectoryPath}- onChange={this.handleInputChange}- endAdornment={- PlatformIO.haveObjectStoreSupport() ? (- undefined- ) : (- <InputAdornment position="end" style={{ height: 32 }}>- <IconButton onClick={this.openFolderChooser}>- <FolderIcon />- </IconButton>- </InputAdornment>- )- }- />- {this.state.errorTextPath && (- <FormHelperText>{i18n.t('core:invalidPath')}</FormHelperText>- )}- </FormControl>- </DialogContent>- <DialogActions>- <Button- data-tid="closeCreateFileDialog"- onClick={this.props.onClose}- color="primary"- >- {i18n.t('core:cancel')}- </Button>- <Button- disabled={this.state.disableConfirmButton}- onClick={this.onConfirm}- data-tid="confirmCreateFileDialog"- color="primary"- >- {i18n.t('core:ok')}- </Button>- </DialogActions>- </Dialog>;- };+ return = () => {+ <Dialog+ open={open}+ onClose={onClose}+ fullScreen={fullScreen}+ keepMounted+ scroll="paper"+ // onKeyDown={confirmFunction}+ >+ <DialogTitle>{i18n.t('core:createFileTitle')}</DialogTitle>+ <DialogContent data-tid="createFileDialog">+ <FormControl fullWidth={true} error={this.state.errorTextName}>+ <TextField+ fullWidth={true}+ error={this.state.errorTextName}+ autoFocus+ margin="dense"+ name="fileName"+ label={i18n.t('core:fileName')}+ inputRef={ref => {+ this.fileName = ref;+ }}+ onChange={this.handleInputChange}+ value={this.state.fileName}+ data-tid="createFileDialog_fileName"+ />+ {this.state.errorTextName && (+ <FormHelperText>{i18n.t('core:fileNameHelp')}</FormHelperText>+ )}+ </FormControl>+ <FormControl fullWidth={true}>+ <TextField+ id="textarea"+ placeholder="Enter the content of your file / note"+ multiline+ name="fileContent"+ value={this.state.fileContent}+ onChange={this.handleInputChange}+ onKeyDown={this.handleKeyPress}+ margin="normal"+ fullWidth={true}+ rows={4}+ rowsMax={10}+ />+ </FormControl>+ <ListItem>+ <Radio+ checked={this.state.fileType === 'txt'}+ onChange={this.handleTypeChange}+ value="txt"+ name="type"+ aria-label={i18n.t('core:createTextFile')}+ />+ <FormHelperText>{i18n.t('core:createTextFile')}</FormHelperText>+ <Radio+ checked={this.state.fileType === 'md'}+ onChange={this.handleTypeChange}+ value="md"+ name="type"+ aria-label={i18n.t('core:createMarkdown')}+ />+ <FormHelperText>{i18n.t('core:createMarkdown')}</FormHelperText>+ <Radio+ checked={this.state.fileType === 'html'}+ onChange={this.handleTypeChange}+ value="html"+ name="html"+ aria-label={i18n.t('core:createRichTextFile')}+ />+ <FormHelperText>{i18n.t('core:createRichTextFile')}</FormHelperText>+ </ListItem>+ <FormControl fullWidth={true}>+ <InputLabel htmlFor="name">{i18n.t('core:filePath')}</InputLabel>+ <Input+ required+ margin="dense"+ name="selectedDirectoryPath"+ label={i18n.t('core:filePath')}+ fullWidth={true}+ data-tid="createFileDialog_filePath"+ value={this.state.selectedDirectoryPath}+ onChange={this.handleInputChange}+ endAdornment={+ PlatformIO.haveObjectStoreSupport() ? (+ undefined+ ) : (+ <InputAdornment position="end" style={{ height: 32 }}>+ <IconButton onClick={this.openFolderChooser}>+ <FolderIcon />+ </IconButton>+ </InputAdornment>+ )+ }+ />+ {this.state.errorTextPath && (+ <FormHelperText>{i18n.t('core:invalidPath')}</FormHelperText>+ )}+ </FormControl>+ </DialogContent>+ <DialogActions>+ <Button+ data-tid="closeCreateFileDialog"+ onClick={this.props.onClose}+ color="primary"+ >+ {i18n.t('core:cancel')}+ </Button>+ <Button+ disabled={this.state.disableConfirmButton}+ onClick={this.onConfirm}+ data-tid="confirmCreateFileDialog"+ color="primary"+ >+ {i18n.t('core:ok')}+ </Button>+ </DialogActions>+ </Dialog>;+ };}function mapActionCreatorsToProps(dispatch) {- return bindActionCreators(- {- createFileAdvanced: AppActions.createFileAdvanced,- showSelectDirectoryDialog: AppActions.showSelectDirectoryDialog,- ...TaggingActions- },- dispatch- );+ return bindActionCreators(+ {+ createFileAdvanced: AppActions.createFileAdvanced,+ showSelectDirectoryDialog: AppActions.showSelectDirectoryDialog,+ ...TaggingActions+ },+ dispatch+ );}export default connect(- undefined,- mapActionCreatorsToProps+ undefined,+ mapActionCreatorsToProps)(withMobileDialog()(withStyles(styles)(CreateFileDialog)));diff --git a/app/components/dialogs/CreateLocationDialog.tsx b/app/components/dialogs/CreateLocationDialog.tsxindex c935b409c..0aee4564c 100644--- a/app/components/dialogs/CreateLocationDialog.tsx+++ b/app/components/dialogs/CreateLocationDialog.tsx@@ -34,443 +34,442 @@ import RadioGroup from '@material-ui/core/RadioGroup';import { Typography } from '@material-ui/core';import Dialog from '@material-ui/core/Dialog';import i18n from '../../services/i18n';-import { type Location, locationType } from '../../reducers/locations';+import { Location, locationType } from '../../reducers/locations';import { Pro } from '../../pro';import ObjectStoreForm from './ObjectStoreForm';import LocalForm from './LocalForm';const styles = theme => ({- root: {- display: 'flex'- },- formControl: {- margin: theme.spacing(3)- },- group: {- margin: theme.spacing(1, 0),- display: 'flex',- flexDirection: 'row'- }+ root: {+ display: 'flex'+ },+ formControl: {+ margin: theme.spacing(3)+ },+ group: {+ margin: theme.spacing(1, 0),+ display: 'flex',+ flexDirection: 'row'+ }});-type Props = {- // classes: Object,- open: boolean,- onClose: () => void,- fullScreen: boolean,- onClose: () => void,- addLocation: (location: Location) => void,- showSelectDirectoryDialog: () => void,- resetState: () => void-};+interface Props {+ // classes: Object,+ open: boolean;+ onClose: () => void;+ fullScreen: boolean;+ addLocation: (location: Location) => void;+ showSelectDirectoryDialog: () => void;+ resetState: () => void;+}-type State = {- errorTextPath: boolean,- errorTextName: boolean,- disableConfirmButton: boolean,- name: string,- path: string,- perspective?: string,- isDefault: boolean,- isReadOnly: boolean,- watchForChanges: boolean,- persistIndex: boolean,- fullTextIndex: boolean,- type: string-};+interface State {+ errorTextPath: boolean;+ errorTextName: boolean;+ disableConfirmButton: boolean;+ name: string;+ path: string;+ perspective?: string;+ isDefault: boolean;+ isReadOnly: boolean;+ watchForChanges: boolean;+ persistIndex: boolean;+ fullTextIndex: boolean;+ type: string;+}class CreateLocationDialog extends React.Component<Props, State> {- state = {- errorTextPath: false,- errorTextName: false,- disableConfirmButton: true,- name: '',- path: '',- perspective: '',- isDefault: false,- isReadOnly: false,- watchForChanges: Pro,- persistIndex: false,- fullTextIndex: false,- type: locationType.TYPE_LOCAL- };+ state = {+ errorTextPath: false,+ errorTextName: false,+ disableConfirmButton: true,+ name: '',+ path: '',+ perspective: '',+ isDefault: false,+ isReadOnly: false,+ watchForChanges: Pro,+ persistIndex: false,+ fullTextIndex: false,+ type: locationType.TYPE_LOCAL+ };- handleInputChange = (event: Object) => {- const target = event.target;- const value = target.type === 'checkbox' ? target.checked : target.value;- const name = target.name;- if (target.type === 'radio') {- // type is changed (skip validation)- this.setState({- [name]: value- });- } else {- this.handleChange(name, value);- }- };+ handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {+ const target = event.target;+ const value = target.type === 'checkbox' ? target.checked : target.value;+ const name = target.name;+ if (target.type === 'radio') {+ // type is changed (skip validation)+ this.setState({+ [name]: value+ });+ } else {+ this.handleChange(name, value);+ }+ };- handleChange = (name, value) => {- this.setState(- {- [name]: value- },- () => {- this.handleValidation(name);- }- );- };+ handleChange = (name, value) => {+ this.setState(+ {+ [name]: value+ },+ () => {+ this.handleValidation(name);+ }+ );+ };- handleValidation(field) {- // const pathRegex = this.state.path.match('^((\.\./|[a-zA-Z0-9_/\-\\])*\.[a-zA-Z0-9]+)$');- // const nameRegex = this.state.name.match('^[A-Z][-a-zA-Z]+$');- if (this.state.type === locationType.TYPE_LOCAL) {- let errorTextName = false;- let errorTextPath = false;- let disableConfirmButton = false;- if (!this.state.name || this.state.name.length === 0) {- errorTextName = true;- disableConfirmButton = true;- } else if (- field === 'name' &&- !this.state.errorTextName &&- !this.state.errorTextPath &&- this.state.disableConfirmButton- ) {- // initial skip validation for other fields- return new Promise(resolve => {- resolve(true);- });- }- if (!this.state.path || this.state.path.length === 0) {- errorTextPath = true; // make it optinal in cloud mode- disableConfirmButton = true;- }- return new Promise(resolve =>- this.setState(- { errorTextName, errorTextPath, disableConfirmButton },- resolve(!disableConfirmButton)- )- );- } else if (this.state.type === locationType.TYPE_CLOUD) {- let cloudErrorTextName = false;- // let cloudErrorTextPath = false;- let cloudErrorAccessKey = false;- let cloudErrorSecretAccessKey = false;- let cloudErrorBucketName = false;- let cloudErrorRegion = false;- let disableConfirmButton = false;- if (!this.state.storeName || this.state.storeName.length === 0) {- cloudErrorTextName = true;- disableConfirmButton = true;- } else if (- field === 'storeName' &&- !this.state.cloudErrorTextName &&- // && !this.state.cloudErrorTextPath- !this.state.cloudErrorAccessKey &&- !this.state.cloudErrorSecretAccessKey &&- !this.state.cloudErrorBucketName &&- !this.state.cloudErrorRegion &&- this.state.disableConfirmButton- ) {- // initial skip validation for other fields- return new Promise(resolve => {- resolve(true);- });- }+ handleValidation(field) {+ // const pathRegex = this.state.path.match('^((\.\./|[a-zA-Z0-9_/\-\\])*\.[a-zA-Z0-9]+)$');+ // const nameRegex = this.state.name.match('^[A-Z][-a-zA-Z]+$');+ if (this.state.type === locationType.TYPE_LOCAL) {+ let errorTextName = false;+ let errorTextPath = false;+ let disableConfirmButton = false;+ if (!this.state.name || this.state.name.length === 0) {+ errorTextName = true;+ disableConfirmButton = true;+ } else if (+ field === 'name' &&+ !this.state.errorTextName &&+ !this.state.errorTextPath &&+ this.state.disableConfirmButton+ ) {+ // initial skip validation for other fields+ return new Promise(resolve => {+ resolve(true);+ });+ }+ if (!this.state.path || this.state.path.length === 0) {+ errorTextPath = true; // make it optinal in cloud mode+ disableConfirmButton = true;+ }+ return new Promise(resolve =>+ this.setState(+ { errorTextName, errorTextPath, disableConfirmButton },+ resolve(!disableConfirmButton)+ )+ );+ } else if (this.state.type === locationType.TYPE_CLOUD) {+ let cloudErrorTextName = false;+ // let cloudErrorTextPath = false;+ let cloudErrorAccessKey = false;+ let cloudErrorSecretAccessKey = false;+ let cloudErrorBucketName = false;+ let cloudErrorRegion = false;+ let disableConfirmButton = false;+ if (!this.state.storeName || this.state.storeName.length === 0) {+ cloudErrorTextName = true;+ disableConfirmButton = true;+ } else if (+ field === 'storeName' &&+ !this.state.cloudErrorTextName &&+ // && !this.state.cloudErrorTextPath+ !this.state.cloudErrorAccessKey &&+ !this.state.cloudErrorSecretAccessKey &&+ !this.state.cloudErrorBucketName &&+ !this.state.cloudErrorRegion &&+ this.state.disableConfirmButton+ ) {+ // initial skip validation for other fields+ return new Promise(resolve => {+ resolve(true);+ });+ }- if (!this.state.accessKeyId || this.state.accessKeyId.length === 0) {- cloudErrorAccessKey = true;- disableConfirmButton = true;- } else if (- field === 'accessKeyId' &&- !this.state.cloudErrorTextName &&- // && !this.state.cloudErrorTextPath- !this.state.cloudErrorAccessKey &&- !this.state.cloudErrorSecretAccessKey &&- !this.state.cloudErrorBucketName &&- !this.state.cloudErrorRegion &&- this.state.disableConfirmButton- ) {- // initial skip validation for other fields- return new Promise(resolve => {- resolve(true);- });- }+ if (!this.state.accessKeyId || this.state.accessKeyId.length === 0) {+ cloudErrorAccessKey = true;+ disableConfirmButton = true;+ } else if (+ field === 'accessKeyId' &&+ !this.state.cloudErrorTextName &&+ // && !this.state.cloudErrorTextPath+ !this.state.cloudErrorAccessKey &&+ !this.state.cloudErrorSecretAccessKey &&+ !this.state.cloudErrorBucketName &&+ !this.state.cloudErrorRegion &&+ this.state.disableConfirmButton+ ) {+ // initial skip validation for other fields+ return new Promise(resolve => {+ resolve(true);+ });+ }- if (- !this.state.secretAccessKey ||- this.state.secretAccessKey.length === 0- ) {- cloudErrorSecretAccessKey = true;- disableConfirmButton = true;- } else if (- field === 'secretAccessKey' &&- !this.state.cloudErrorTextName &&- // && !this.state.cloudErrorTextPath- !this.state.cloudErrorAccessKey &&- !this.state.cloudErrorSecretAccessKey &&- !this.state.cloudErrorBucketName &&- !this.state.cloudErrorRegion &&- this.state.disableConfirmButton- ) {- // initial skip validation for other fields- return new Promise(resolve => {- resolve(true);- });- }+ if (+ !this.state.secretAccessKey ||+ this.state.secretAccessKey.length === 0+ ) {+ cloudErrorSecretAccessKey = true;+ disableConfirmButton = true;+ } else if (+ field === 'secretAccessKey' &&+ !this.state.cloudErrorTextName &&+ // && !this.state.cloudErrorTextPath+ !this.state.cloudErrorAccessKey &&+ !this.state.cloudErrorSecretAccessKey &&+ !this.state.cloudErrorBucketName &&+ !this.state.cloudErrorRegion &&+ this.state.disableConfirmButton+ ) {+ // initial skip validation for other fields+ return new Promise(resolve => {+ resolve(true);+ });+ }- if (!this.state.bucketName || this.state.bucketName.length === 0) {- cloudErrorBucketName = true;- disableConfirmButton = true;- } else if (- field === 'bucketName' &&- !this.state.cloudErrorTextName &&- // && !this.state.cloudErrorTextPath- !this.state.cloudErrorAccessKey &&- !this.state.cloudErrorSecretAccessKey &&- !this.state.cloudErrorBucketName &&- !this.state.cloudErrorRegion &&- this.state.disableConfirmButton- ) {- // initial skip validation for other fields- return new Promise(resolve => {- resolve(true);- });- }+ if (!this.state.bucketName || this.state.bucketName.length === 0) {+ cloudErrorBucketName = true;+ disableConfirmButton = true;+ } else if (+ field === 'bucketName' &&+ !this.state.cloudErrorTextName &&+ // && !this.state.cloudErrorTextPath+ !this.state.cloudErrorAccessKey &&+ !this.state.cloudErrorSecretAccessKey &&+ !this.state.cloudErrorBucketName &&+ !this.state.cloudErrorRegion &&+ this.state.disableConfirmButton+ ) {+ // initial skip validation for other fields+ return new Promise(resolve => {+ resolve(true);+ });+ }- if (!this.state.region) {- cloudErrorRegion = true;- disableConfirmButton = true;- }+ if (!this.state.region) {+ cloudErrorRegion = true;+ disableConfirmButton = true;+ }- return new Promise(resolve =>- this.setState(- {- cloudErrorTextName,- // cloudErrorTextPath,- cloudErrorAccessKey,- cloudErrorSecretAccessKey,- cloudErrorBucketName,- disableConfirmButton,- cloudErrorRegion- },- resolve(!disableConfirmButton)- )- );- }- return new Promise(resolve => {- resolve(true);- });- }+ return new Promise(resolve =>+ this.setState(+ {+ cloudErrorTextName,+ // cloudErrorTextPath,+ cloudErrorAccessKey,+ cloudErrorSecretAccessKey,+ cloudErrorBucketName,+ disableConfirmButton,+ cloudErrorRegion+ },+ resolve(!disableConfirmButton)+ )+ );+ }+ return new Promise(resolve => {+ resolve(true);+ });+ }- onConfirm = () => {- this.handleValidation()- .then(success => {- if (success) {- if (this.state.type === locationType.TYPE_LOCAL) {- this.props.addLocation({- uuid: uuidv1(),- type: locationType.TYPE_LOCAL,- name: this.state.name,- paths: [this.state.path],- perspective: this.state.perspective,- isDefault: this.state.isDefault,- isReadOnly: this.state.isReadOnly,- persistIndex: this.state.persistIndex,- fullTextIndex: this.state.fullTextIndex,- watchForChanges: this.state.watchForChanges- });- } else if (this.state.type === locationType.TYPE_CLOUD) {- this.props.addLocation({- uuid: uuidv1(),- type: locationType.TYPE_CLOUD,- name: this.state.storeName,- paths: [this.state.storePath],- accessKeyId: this.state.accessKeyId,- secretAccessKey: this.state.secretAccessKey,- bucketName: this.state.bucketName,- region: this.state.region.value,- perspective: this.state.perspective,- isDefault: this.state.isDefault,- isReadOnly: this.state.isReadOnly,- persistIndex: this.state.persistIndex,- fullTextIndex: this.state.fullTextIndex,- watchForChanges: false- });- }- this.props.onClose();- this.props.resetState('createLocationDialogKey');- }- return true;- })- .catch(error => {- console.debug('Failed validation', error);- });- };+ onConfirm = () => {+ this.handleValidation()+ .then(success => {+ if (success) {+ if (this.state.type === locationType.TYPE_LOCAL) {+ this.props.addLocation({+ uuid: uuidv1(),+ type: locationType.TYPE_LOCAL,+ name: this.state.name,+ paths: [this.state.path],+ perspective: this.state.perspective,+ isDefault: this.state.isDefault,+ isReadOnly: this.state.isReadOnly,+ persistIndex: this.state.persistIndex,+ fullTextIndex: this.state.fullTextIndex,+ watchForChanges: this.state.watchForChanges+ });+ } else if (this.state.type === locationType.TYPE_CLOUD) {+ this.props.addLocation({+ uuid: uuidv1(),+ type: locationType.TYPE_CLOUD,+ name: this.state.storeName,+ paths: [this.state.storePath],+ accessKeyId: this.state.accessKeyId,+ secretAccessKey: this.state.secretAccessKey,+ bucketName: this.state.bucketName,+ region: this.state.region.value,+ perspective: this.state.perspective,+ isDefault: this.state.isDefault,+ isReadOnly: this.state.isReadOnly,+ persistIndex: this.state.persistIndex,+ fullTextIndex: this.state.fullTextIndex,+ watchForChanges: false+ });+ }+ this.props.onClose();+ this.props.resetState('createLocationDialogKey');+ }+ return true;+ })+ .catch(error => {+ console.debug('Failed validation', error);+ });+ };- onCancel = () => {- this.props.onClose();- this.props.resetState('createLocationDialogKey');- };+ onCancel = () => {+ this.props.onClose();+ this.props.resetState('createLocationDialogKey');+ };- render() {- const { fullScreen, open, onClose } = this.props;+ render() {+ const { fullScreen, open, onClose } = this.props;- // const { classes } = this.props;- let content;- if (this.state.type === locationType.TYPE_CLOUD) {- content = (- <ObjectStoreForm- handleInputChange={this.handleInputChange}- handleChange={this.handleChange}- state={this.state}- />- );- } else {- content = (- <LocalForm- showSelectDirectoryDialog={this.props.showSelectDirectoryDialog}- handleInputChange={this.handleInputChange}- handleChange={this.handleChange}- state={this.state}- />- );- }+ // const { classes } = this.props;+ let content;+ if (this.state.type === locationType.TYPE_CLOUD) {+ content = (+ <ObjectStoreForm+ handleInputChange={this.handleInputChange}+ handleChange={this.handleChange}+ state={this.state}+ />+ );+ } else {+ content = (+ <LocalForm+ showSelectDirectoryDialog={this.props.showSelectDirectoryDialog}+ handleInputChange={this.handleInputChange}+ handleChange={this.handleChange}+ state={this.state}+ />+ );+ }- return (- <Dialog- open={open}- onClose={onClose}- fullScreen={fullScreen}- keepMounted- scroll="paper"- // onKeyDown={confirmFunction}- >- <DialogTitle>{i18n.t('core:createLocationTitle')}</DialogTitle>- <DialogContent>- <Grid container spacing={2}>- <Grid item xs={2} style={{ marginTop: 13, textAlign: 'left' }}>- <Typography>{i18n.t('core:locationType')}</Typography>- </Grid>- <Grid item xs={10}>- <FormControl disabled={!Pro}>- <RadioGroup- title={- Pro ? '' : i18n.t('core:thisFunctionalityIsAvailableInPro')- }- component="label"- aria-label={i18n.t('core:locationType')}- name="type"- value={this.state.type}- onChange={this.handleInputChange}- row- >- <FormControlLabel- value={locationType.TYPE_LOCAL}- control={<Radio />}- label="Local"- />- <FormControlLabel- value={locationType.TYPE_CLOUD}- control={<Radio />}- title="AWS S3 compatible object storage"- label="AWS S3 Object Storage"- />- </RadioGroup>- </FormControl>- </Grid>- </Grid>- {content}- <FormGroup>- <FormControlLabel- control={- <Switch- data-tid="locationIsDefault"- name="isDefault"- checked={this.state.isDefault}- onChange={this.handleInputChange}- />- }- label={i18n.t('core:startupLocation')}- />- <FormControlLabel- control={- <Switch- disabled={!Pro}- data-tid="changeReadOnlyMode"- name="isReadOnly"- checked={this.state.isReadOnly}- onChange={this.handleInputChange}- />- }- label={- i18n.t('core:readonlyModeSwitch') +- (Pro ? '' : ' - ' + i18n.t('core:proFeature'))- }- />- <FormControlLabel- control={- <Switch- disabled={!Pro}- data-tid="changeFullTextIndex"- name="fullTextIndex"- checked={this.state.fullTextIndex}- onChange={this.handleInputChange}- />- }- label={- i18n.t('core:createFullTextIndex') +- (Pro ? '' : ' - ' + i18n.t('core:proFeature'))- }- />- <FormControlLabel- control={- <Switch- disabled={!Pro}- data-tid="changePersistIndex"- name="persistIndex"- checked={this.state.persistIndex}- onChange={this.handleInputChange}- />- }- label={- i18n.t('core:persistIndexSwitch') +- (Pro ? '' : ' - ' + i18n.t('core:proFeature'))- }- />- <FormControlLabel- control={- <Switch- disabled={!Pro || this.state.type === locationType.TYPE_CLOUD}- data-tid="changeWatchForChanges"- name="watchForChanges"- checked={this.state.watchForChanges}- onChange={this.handleInputChange}- />- }- label={- i18n.t('core:watchForChangesInLocation') +- (Pro ? '' : ' - ' + i18n.t('core:proFeature'))- }- />- </FormGroup>- </DialogContent>- <DialogActions>- <Button onClick={this.onCancel} color="primary">- {i18n.t('core:cancel')}- </Button>- <Button- disabled={this.state.disableConfirmButton}- onClick={this.onConfirm}- data-tid="confirmLocationCreation"- color="primary"- >- {i18n.t('core:ok')}- </Button>- </DialogActions>- </Dialog>- );- }+ return (+ <Dialog+ open={open}+ onClose={onClose}+ fullScreen={fullScreen}+ keepMounted+ scroll="paper"+ // onKeyDown={confirmFunction}+ >+ <DialogTitle>{i18n.t('core:createLocationTitle')}</DialogTitle>+ <DialogContent>+ <Grid container spacing={2}>+ <Grid item xs={2} style={{ marginTop: 13, textAlign: 'left' }}>+ <Typography>{i18n.t('core:locationType')}</Typography>+ </Grid>+ <Grid item xs={10}>+ <FormControl disabled={!Pro}>+ <RadioGroup+ title={+ Pro ? '' : i18n.t('core:thisFunctionalityIsAvailableInPro')+ }+ component="label"+ aria-label={i18n.t('core:locationType')}+ name="type"+ value={this.state.type}+ onChange={this.handleInputChange}+ row+ >+ <FormControlLabel+ value={locationType.TYPE_LOCAL}+ control={<Radio />}+ label="Local"+ />+ <FormControlLabel+ value={locationType.TYPE_CLOUD}+ control={<Radio />}+ title="AWS S3 compatible object storage"+ label="AWS S3 Object Storage"+ />+ </RadioGroup>+ </FormControl>+ </Grid>+ </Grid>+ {content}+ <FormGroup>+ <FormControlLabel+ control={+ <Switch+ data-tid="locationIsDefault"+ name="isDefault"+ checked={this.state.isDefault}+ onChange={this.handleInputChange}+ />+ }+ label={i18n.t('core:startupLocation')}+ />+ <FormControlLabel+ control={+ <Switch+ disabled={!Pro}+ data-tid="changeReadOnlyMode"+ name="isReadOnly"+ checked={this.state.isReadOnly}+ onChange={this.handleInputChange}+ />+ }+ label={+ i18n.t('core:readonlyModeSwitch') ++ (Pro ? '' : ' - ' + i18n.t('core:proFeature'))+ }+ />+ <FormControlLabel+ control={+ <Switch+ disabled={!Pro}+ data-tid="changeFullTextIndex"+ name="fullTextIndex"+ checked={this.state.fullTextIndex}+ onChange={this.handleInputChange}+ />+ }+ label={+ i18n.t('core:createFullTextIndex') ++ (Pro ? '' : ' - ' + i18n.t('core:proFeature'))+ }+ />+ <FormControlLabel+ control={+ <Switch+ disabled={!Pro}+ data-tid="changePersistIndex"+ name="persistIndex"+ checked={this.state.persistIndex}+ onChange={this.handleInputChange}+ />+ }+ label={+ i18n.t('core:persistIndexSwitch') ++ (Pro ? '' : ' - ' + i18n.t('core:proFeature'))+ }+ />+ <FormControlLabel+ control={+ <Switch+ disabled={!Pro || this.state.type === locationType.TYPE_CLOUD}+ data-tid="changeWatchForChanges"+ name="watchForChanges"+ checked={this.state.watchForChanges}+ onChange={this.handleInputChange}+ />+ }+ label={+ i18n.t('core:watchForChangesInLocation') ++ (Pro ? '' : ' - ' + i18n.t('core:proFeature'))+ }+ />+ </FormGroup>+ </DialogContent>+ <DialogActions>+ <Button onClick={this.onCancel} color="primary">+ {i18n.t('core:cancel')}+ </Button>+ <Button+ disabled={this.state.disableConfirmButton}+ onClick={this.onConfirm}+ data-tid="confirmLocationCreation"+ color="primary"+ >+ {i18n.t('core:ok')}+ </Button>+ </DialogActions>+ </Dialog>+ );+ }}export default withStyles(styles)(withMobileDialog()(CreateLocationDialog));diff --git a/app/components/dialogs/CreateTagGroupDialog.tsx b/app/components/dialogs/CreateTagGroupDialog.tsxindex b8f8e3577..e7f87d412 100644--- a/app/components/dialogs/CreateTagGroupDialog.tsx+++ b/app/components/dialogs/CreateTagGroupDialog.tsx@@ -30,15 +30,16 @@ import { TagGroup } from '../../reducers/taglibrary';import i18n from '../../services/i18n';import TransparentBackground from '../TransparentBackground';-type Props = {+interface Props {open: boolean;onClose: () => void;createTagGroup: (tagGroup: TagGroup) => void;+ fullScreen: boolean;color: string;textcolor: string;-};+}-type State = {+interface State {inputError: boolean;displayColorPicker: boolean;displayTextColorPicker: boolean;@@ -49,7 +50,7 @@ type State = {textcolor: string;children: string;expanded: boolean;-};+}class CreateTagGroupDialog extends React.Component<Props, State> {state = {@@ -65,7 +66,7 @@ class CreateTagGroupDialog extends React.Component<Props, State> {uuid: ''};- handleInputChange = (event: Object) => {+ handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {const target = event.target;const value = target.type === 'checkbox' ? target.checked : target.value;const name = target.name;diff --git a/app/components/dialogs/CreateTagsDialog.tsx b/app/components/dialogs/CreateTagsDialog.tsxindex c605101f7..fd2f4a4a5 100644--- a/app/components/dialogs/CreateTagsDialog.tsx+++ b/app/components/dialogs/CreateTagsDialog.tsx@@ -28,20 +28,20 @@ import Dialog from '@material-ui/core/Dialog';import i18n from '../../services/i18n';import { TagGroup } from '../../reducers/taglibrary';-type Props = {+interface Props {open: boolean;onClose: () => void;addTag: (tags: string, uuid: string) => void;fullScreen: boolean;selectedTagGroupEntry: TagGroup;-};+}-type State = {+interface State {inputError: boolean;disableConfirmButton: boolean;open: boolean;tagTitle: string;-};+}class CreateTagsDialog extends React.Component<Props, State> {state = {@@ -51,7 +51,7 @@ class CreateTagsDialog extends React.Component<Props, State> {tagTitle: ''};- handleInputChange = (event: Object) => {+ handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {const target = event.target;const value = target.type === 'checkbox' ? target.checked : target.value;const name = target.name;diff --git a/app/components/dialogs/EditLocationDialog.tsx b/app/components/dialogs/EditLocationDialog.tsxindex 0be3e12d1..ffd06886a 100644--- a/app/components/dialogs/EditLocationDialog.tsx+++ b/app/components/dialogs/EditLocationDialog.tsx@@ -33,181 +33,182 @@ import { Typography } from '@material-ui/core';import Dialog from '@material-ui/core/Dialog';import i18n from '../../services/i18n';import { extractDirectoryName } from '../../utils/paths';-import { type Location, locationType } from '../../reducers/locations';+import { Location, locationType } from '../../reducers/locations';import ObjectStoreForm, { suggestions } from './ObjectStoreForm';import LocalForm from './LocalForm';import { Pro } from '../../pro';-type Props = {- open: boolean,- fullScreen: boolean,- resetState: () => void,- onClose: () => void,- location: Location | null,- editLocation: (location: Location) => void,- showSelectDirectoryDialog: () => void,- selectedDirectoryPath: string | null,- onCancel: () => void-};+interface Props {+ open: boolean;+ fullScreen: boolean;+ resetState: () => void;+ onClose: () => void;+ location: Location | null;+ editLocation: (location: Location) => void;+ showSelectDirectoryDialog: () => void;+ selectedDirectoryPath: string | null;+ onCancel: () => void;+}-type State = {- errorTextPath: boolean,- errorTextName: boolean,- disableConfirmButton: boolean,- // openDirectoryButtonDisabled?: boolean,- uuid: string,- name: string,- path: string,- perspective: '',- isDefault: boolean,- isReadOnly: boolean,- watchForChanges: boolean,- fullTextIndex: boolean,- persistIndex: boolean-};+interface State {+ errorTextPath: boolean;+ errorTextName: boolean;+ disableConfirmButton: boolean;+ // openDirectoryButtonDisabled?: boolean,+ uuid: string;+ name: string;+ path: string;+ perspective: '';+ isDefault: boolean;+ isReadOnly: boolean;+ watchForChanges: boolean;+ fullTextIndex: boolean;+ persistIndex: boolean;+ type: string;+}class EditLocationDialog extends React.Component<Props, State> {- state = {- errorTextPath: false,- errorTextName: false,- disableConfirmButton: true,- // openDirectoryButtonDisabled: false,- uuid: '',- name: '',- path: '',- perspective: '',- isDefault: false,- isReadOnly: false,- watchForChanges: false,- persistIndex: false,- fullTextIndex: false,- type: locationType.TYPE_LOCAL- };+ state = {+ errorTextPath: false,+ errorTextName: false,+ disableConfirmButton: true,+ // openDirectoryButtonDisabled: false,+ uuid: '',+ name: '',+ path: '',+ perspective: '',+ isDefault: false,+ isReadOnly: false,+ watchForChanges: false,+ persistIndex: false,+ fullTextIndex: false,+ type: locationType.TYPE_LOCAL+ };- componentWillReceiveProps = (nextProps: any) => {- if (nextProps.open === true && nextProps.location) {- const dir = nextProps.selectedDirectoryPath;- let properties;- if (nextProps.location.type === locationType.TYPE_CLOUD) {- properties = {- storeName: dir ? extractDirectoryName(dir) : nextProps.location.name,- storePath: dir || nextProps.location.paths[0]- };- } else {- properties = {- // TODO maybe its better to separate name/path keys for different locationTypes ??- name: dir ? extractDirectoryName(dir) : nextProps.location.name,- path: dir || nextProps.location.paths[0]- };- }- this.setState({- ...properties,- uuid: nextProps.location.uuid,- perspective: nextProps.location.perspective,- isDefault: nextProps.location.isDefault,- isReadOnly: nextProps.location.isReadOnly,- watchForChanges: nextProps.location.watchForChanges,- persistIndex: nextProps.location.persistIndex,- fullTextIndex: nextProps.location.fullTextIndex,- type: nextProps.location.type || locationType.TYPE_LOCAL,- accessKeyId: nextProps.location.accessKeyId,- secretAccessKey: nextProps.location.secretAccessKey,- bucketName: nextProps.location.bucketName,- region: suggestions.find(obj => obj.value === nextProps.location.region)- });- }- };+ componentWillReceiveProps = (nextProps: any) => {+ if (nextProps.open === true && nextProps.location) {+ const dir = nextProps.selectedDirectoryPath;+ let properties;+ if (nextProps.location.type === locationType.TYPE_CLOUD) {+ properties = {+ storeName: dir ? extractDirectoryName(dir) : nextProps.location.name,+ storePath: dir || nextProps.location.paths[0]+ };+ } else {+ properties = {+ // TODO maybe its better to separate name/path keys for different locationTypes ??+ name: dir ? extractDirectoryName(dir) : nextProps.location.name,+ path: dir || nextProps.location.paths[0]+ };+ }+ this.setState({+ ...properties,+ uuid: nextProps.location.uuid,+ perspective: nextProps.location.perspective,+ isDefault: nextProps.location.isDefault,+ isReadOnly: nextProps.location.isReadOnly,+ watchForChanges: nextProps.location.watchForChanges,+ persistIndex: nextProps.location.persistIndex,+ fullTextIndex: nextProps.location.fullTextIndex,+ type: nextProps.location.type || locationType.TYPE_LOCAL,+ accessKeyId: nextProps.location.accessKeyId,+ secretAccessKey: nextProps.location.secretAccessKey,+ bucketName: nextProps.location.bucketName,+ region: suggestions.find(obj => obj.value === nextProps.location.region)+ });+ }+ };- handleInputChange = (event: Object) => {- const target = event.target;- const value = target.type === 'checkbox' ? target.checked : target.value;- const name = target.name;- if (target.type === 'radio') {- // type is changed (skip validation)- this.setState({- [name]: value- });- } else {- this.handleChange(name, value);- }- };+ handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {+ const target = event.target;+ const value = target.type === 'checkbox' ? target.checked : target.value;+ const name = target.name;+ if (target.type === 'radio') {+ // type is changed (skip validation)+ this.setState({+ [name]: value+ });+ } else {+ this.handleChange(name, value);+ }+ };- handleChange = (name, value) => {- this.setState(- {- [name]: value- },- this.handleValidation- );- };+ handleChange = (name, value) => {+ this.setState(+ {+ [name]: value+ },+ this.handleValidation+ );+ };- handleValidation() {- // const pathRegex = this.state.path.match('^((\.\./|[a-zA-Z0-9_/\-\\])*\.[a-zA-Z0-9]+)$');- // const nameRegex = this.state.name.match('^[A-Z][-a-zA-Z]+$');- if (this.state.type === locationType.TYPE_CLOUD) {- let cloudErrorTextName = false;- // let cloudErrorTextPath = false;- let cloudErrorAccessKey = false;- let cloudErrorSecretAccessKey = false;- let cloudErrorBucketName = false;- let cloudErrorRegion = false;- let disableConfirmButton = false;- if (!this.state.storeName || this.state.storeName.length === 0) {- cloudErrorTextName = true;- disableConfirmButton = true;- }+ handleValidation() {+ // const pathRegex = this.state.path.match('^((\.\./|[a-zA-Z0-9_/\-\\])*\.[a-zA-Z0-9]+)$');+ // const nameRegex = this.state.name.match('^[A-Z][-a-zA-Z]+$');+ if (this.state.type === locationType.TYPE_CLOUD) {+ let cloudErrorTextName = false;+ // let cloudErrorTextPath = false;+ let cloudErrorAccessKey = false;+ let cloudErrorSecretAccessKey = false;+ let cloudErrorBucketName = false;+ let cloudErrorRegion = false;+ let disableConfirmButton = false;+ if (!this.state.storeName || this.state.storeName.length === 0) {+ cloudErrorTextName = true;+ disableConfirmButton = true;+ }- /* if (!this.state.storePath || this.state.storePath.length === 0) {+ /* if (!this.state.storePath || this.state.storePath.length === 0) {cloudErrorTextPath = true;disableConfirmButton = true;} */- // if (!this.state.accessKeyId || this.state.accessKeyId.length === 0) {- // cloudErrorAccessKey = true;- // disableConfirmButton = true;- // }+ // if (!this.state.accessKeyId || this.state.accessKeyId.length === 0) {+ // cloudErrorAccessKey = true;+ // disableConfirmButton = true;+ // }- // if (!this.state.secretAccessKey || this.state.secretAccessKey.length === 0) {- // cloudErrorSecretAccessKey = true;- // disableConfirmButton = true;- // }+ // if (!this.state.secretAccessKey || this.state.secretAccessKey.length === 0) {+ // cloudErrorSecretAccessKey = true;+ // disableConfirmButton = true;+ // }- if (!this.state.bucketName || this.state.bucketName.length === 0) {- cloudErrorBucketName = true;- disableConfirmButton = true;- }+ if (!this.state.bucketName || this.state.bucketName.length === 0) {+ cloudErrorBucketName = true;+ disableConfirmButton = true;+ }- if (!this.state.region) {- cloudErrorRegion = true;- disableConfirmButton = true;- }+ if (!this.state.region) {+ cloudErrorRegion = true;+ disableConfirmButton = true;+ }- this.setState({- cloudErrorTextName,- // cloudErrorTextPath,- // cloudErrorAccessKey,- // cloudErrorSecretAccessKey,- cloudErrorBucketName,- disableConfirmButton,- cloudErrorRegion- });- } else {- let errorTextName = false;- let errorTextPath = false;- let disableConfirmButton = false;- if (!this.state.name || this.state.name.length === 0) {- errorTextName = true;- disableConfirmButton = true;- }- if (!this.state.path || this.state.path.length === 0) {- errorTextPath = true; // make in optional in cloud mode- disableConfirmButton = true;- }- this.setState({ errorTextName, errorTextPath, disableConfirmButton });- }- }+ this.setState({+ cloudErrorTextName,+ // cloudErrorTextPath,+ // cloudErrorAccessKey,+ // cloudErrorSecretAccessKey,+ cloudErrorBucketName,+ disableConfirmButton,+ cloudErrorRegion+ });+ } else {+ let errorTextName = false;+ let errorTextPath = false;+ let disableConfirmButton = false;+ if (!this.state.name || this.state.name.length === 0) {+ errorTextName = true;+ disableConfirmButton = true;+ }+ if (!this.state.path || this.state.path.length === 0) {+ errorTextPath = true; // make in optional in cloud mode+ disableConfirmButton = true;+ }+ this.setState({ errorTextName, errorTextPath, disableConfirmButton });+ }+ }- /* openDirectory = () => {+ /* openDirectory = () => {if (AppConfig.isElectron) {this.setState({ openDirectoryButtonDisabled: true });PlatformIO.selectDirectoryDialog().then((selectedPaths) => {@@ -228,230 +229,230 @@ class EditLocationDialog extends React.Component<Props, State> {}} */- onConfirm = () => {- if (!this.state.disableConfirmButton) {- if (this.state.type === locationType.TYPE_LOCAL) {- this.props.editLocation({- uuid: this.state.uuid,- type: locationType.TYPE_LOCAL,- name: this.state.name,- paths: [this.state.path],- perspective: this.state.perspective,- isDefault: this.state.isDefault,- isReadOnly: this.state.isReadOnly,- persistIndex: this.state.persistIndex,- fullTextIndex: this.state.fullTextIndex,- watchForChanges: this.state.watchForChanges- });- } else if (this.state.type === locationType.TYPE_CLOUD) {- this.props.editLocation({- uuid: this.state.uuid,- type: locationType.TYPE_CLOUD,- name: this.state.storeName,- paths: [this.state.storePath],- accessKeyId: this.state.accessKeyId,- secretAccessKey: this.state.secretAccessKey,- bucketName: this.state.bucketName,- region: this.state.region.value,- perspective: this.state.perspective,- isDefault: this.state.isDefault,- isReadOnly: this.state.isReadOnly,- persistIndex: this.state.persistIndex,- fullTextIndex: this.state.fullTextIndex,- watchForChanges: false- });- }- this.props.onClose();- this.props.resetState('editLocationDialogKey');- }- };+ onConfirm = () => {+ if (!this.state.disableConfirmButton) {+ if (this.state.type === locationType.TYPE_LOCAL) {+ this.props.editLocation({+ uuid: this.state.uuid,+ type: locationType.TYPE_LOCAL,+ name: this.state.name,+ paths: [this.state.path],+ perspective: this.state.perspective,+ isDefault: this.state.isDefault,+ isReadOnly: this.state.isReadOnly,+ persistIndex: this.state.persistIndex,+ fullTextIndex: this.state.fullTextIndex,+ watchForChanges: this.state.watchForChanges+ });+ } else if (this.state.type === locationType.TYPE_CLOUD) {+ this.props.editLocation({+ uuid: this.state.uuid,+ type: locationType.TYPE_CLOUD,+ name: this.state.storeName,+ paths: [this.state.storePath],+ accessKeyId: this.state.accessKeyId,+ secretAccessKey: this.state.secretAccessKey,+ bucketName: this.state.bucketName,+ region: this.state.region.value,+ perspective: this.state.perspective,+ isDefault: this.state.isDefault,+ isReadOnly: this.state.isReadOnly,+ persistIndex: this.state.persistIndex,+ fullTextIndex: this.state.fullTextIndex,+ watchForChanges: false+ });+ }+ this.props.onClose();+ this.props.resetState('editLocationDialogKey');+ }+ };- onCancel = () => {- this.props.onClose();- this.props.resetState('editLocationDialogKey');- };+ onCancel = () => {+ this.props.onClose();+ this.props.resetState('editLocationDialogKey');+ };- renderTitle = () => (- <DialogTitle>{i18n.t('core:editLocationTitle')}</DialogTitle>- );+ renderTitle = () => (+ <DialogTitle>{i18n.t('core:editLocationTitle')}</DialogTitle>+ );- renderContent = () => {- let content;- if (this.state.type === locationType.TYPE_CLOUD) {- content = (- <ObjectStoreForm- handleInputChange={this.handleInputChange}- handleChange={this.handleChange}- state={this.state}- />- );- } else {- content = (- <LocalForm- showSelectDirectoryDialog={this.props.showSelectDirectoryDialog}- handleInputChange={this.handleInputChange}- handleChange={this.handleChange}- state={this.state}- />- );- }- return (- <DialogContent>- <Grid container spacing={2}>- <Grid item xs={2} style={{ marginTop: 13, textAlign: 'left' }}>- <Typography>{i18n.t('core:locationType')}</Typography>- </Grid>- <Grid item xs={10}>- <FormControl disabled={!Pro}>- <RadioGroup- title={- Pro ? '' : i18n.t('core:thisFunctionalityIsAvailableInPro')- }- component="label"- aria-label={i18n.t('core:locationType')}- name="type"- value={this.state.type}- onChange={this.handleInputChange}- row- >- <FormControlLabel- value={locationType.TYPE_LOCAL}- control={<Radio />}- label="Local"- />- <FormControlLabel- value={locationType.TYPE_CLOUD}- control={<Radio />}- title="AWS S3 compatible object storage"- label="AWS S3 Object Storage"- />- </RadioGroup>- </FormControl>- </Grid>- </Grid>- {content}- <FormControl>- <FormGroup>- <FormControlLabel- control={- <Switch- data-tid="editStartupLocation"- name="isDefault"- checked={this.state.isDefault}- onChange={this.handleInputChange}- />- }- label={i18n.t('core:startupLocation')}- />- <FormControlLabel- control={- <Switch- disabled={!Pro}- data-tid="changeReadOnlyMode"- name="isReadOnly"- checked={this.state.isReadOnly}- onChange={this.handleInputChange}- />- }- label={- i18n.t('core:readonlyModeSwitch') +- (Pro ? '' : ' - ' + i18n.t('core:proFeature'))- }- />- <FormControlLabel- control={- <Switch- disabled={!Pro}- data-tid="changeFullTextIndex"- name="fullTextIndex"- checked={this.state.fullTextIndex}- onChange={this.handleInputChange}- />- }- label={- i18n.t('core:createFullTextIndex') +- (Pro ? '' : ' - ' + i18n.t('core:proFeature'))- }- />- <FormControlLabel- control={- <Switch- disabled={!Pro}- data-tid="changePersistIndex"- name="persistIndex"- checked={this.state.persistIndex}- onChange={this.handleInputChange}- />- }- label={- i18n.t('core:persistIndexSwitch') +- (Pro ? '' : ' - ' + i18n.t('core:proFeature'))- }- />- <FormControlLabel- control={- <Switch- disabled={!Pro || this.state.type === locationType.TYPE_CLOUD}- data-tid="changeWatchForChanges"- name="watchForChanges"- checked={this.state.watchForChanges}- onChange={this.handleInputChange}- />- }- label={- i18n.t('core:watchForChangesInLocation') +- (Pro ? '' : ' - ' + i18n.t('core:proFeature'))- }- />- </FormGroup>- </FormControl>- </DialogContent>- );- };+ renderContent = () => {+ let content;+ if (this.state.type === locationType.TYPE_CLOUD) {+ content = (+ <ObjectStoreForm+ handleInputChange={this.handleInputChange}+ handleChange={this.handleChange}+ state={this.state}+ />+ );+ } else {+ content = (+ <LocalForm+ showSelectDirectoryDialog={this.props.showSelectDirectoryDialog}+ handleInputChange={this.handleInputChange}+ handleChange={this.handleChange}+ state={this.state}+ />+ );+ }+ return (+ <DialogContent>+ <Grid container spacing={2}>+ <Grid item xs={2} style={{ marginTop: 13, textAlign: 'left' }}>+ <Typography>{i18n.t('core:locationType')}</Typography>+ </Grid>+ <Grid item xs={10}>+ <FormControl disabled={!Pro}>+ <RadioGroup+ title={+ Pro ? '' : i18n.t('core:thisFunctionalityIsAvailableInPro')+ }+ component="label"+ aria-label={i18n.t('core:locationType')}+ name="type"+ value={this.state.type}+ onChange={this.handleInputChange}+ row+ >+ <FormControlLabel+ value={locationType.TYPE_LOCAL}+ control={<Radio />}+ label="Local"+ />+ <FormControlLabel+ value={locationType.TYPE_CLOUD}+ control={<Radio />}+ title="AWS S3 compatible object storage"+ label="AWS S3 Object Storage"+ />+ </RadioGroup>+ </FormControl>+ </Grid>+ </Grid>+ {content}+ <FormControl>+ <FormGroup>+ <FormControlLabel+ control={+ <Switch+ data-tid="editStartupLocation"+ name="isDefault"+ checked={this.state.isDefault}+ onChange={this.handleInputChange}+ />+ }+ label={i18n.t('core:startupLocation')}+ />+ <FormControlLabel+ control={+ <Switch+ disabled={!Pro}+ data-tid="changeReadOnlyMode"+ name="isReadOnly"+ checked={this.state.isReadOnly}+ onChange={this.handleInputChange}+ />+ }+ label={+ i18n.t('core:readonlyModeSwitch') ++ (Pro ? '' : ' - ' + i18n.t('core:proFeature'))+ }+ />+ <FormControlLabel+ control={+ <Switch+ disabled={!Pro}+ data-tid="changeFullTextIndex"+ name="fullTextIndex"+ checked={this.state.fullTextIndex}+ onChange={this.handleInputChange}+ />+ }+ label={+ i18n.t('core:createFullTextIndex') ++ (Pro ? '' : ' - ' + i18n.t('core:proFeature'))+ }+ />+ <FormControlLabel+ control={+ <Switch+ disabled={!Pro}+ data-tid="changePersistIndex"+ name="persistIndex"+ checked={this.state.persistIndex}+ onChange={this.handleInputChange}+ />+ }+ label={+ i18n.t('core:persistIndexSwitch') ++ (Pro ? '' : ' - ' + i18n.t('core:proFeature'))+ }+ />+ <FormControlLabel+ control={+ <Switch+ disabled={!Pro || this.state.type === locationType.TYPE_CLOUD}+ data-tid="changeWatchForChanges"+ name="watchForChanges"+ checked={this.state.watchForChanges}+ onChange={this.handleInputChange}+ />+ }+ label={+ i18n.t('core:watchForChangesInLocation') ++ (Pro ? '' : ' - ' + i18n.t('core:proFeature'))+ }+ />+ </FormGroup>+ </FormControl>+ </DialogContent>+ );+ };- renderActions = () => (- <DialogActions>- <Button- data-tid="closeEditLocationDialog"- color="primary"- onClick={() => {- this.props.onClose();- this.props.resetState('editLocationDialogKey');- }}- >- {i18n.t('core:cancel')}- </Button>- <Button- disabled={this.state.disableConfirmButton}- onClick={this.onConfirm}- data-tid="confirmEditLocationDialog"- color="primary"- >- {i18n.t('core:ok')}- </Button>- </DialogActions>- );+ renderActions = () => (+ <DialogActions>+ <Button+ data-tid="closeEditLocationDialog"+ color="primary"+ onClick={() => {+ this.props.onClose();+ this.props.resetState('editLocationDialogKey');+ }}+ >+ {i18n.t('core:cancel')}+ </Button>+ <Button+ disabled={this.state.disableConfirmButton}+ onClick={this.onConfirm}+ data-tid="confirmEditLocationDialog"+ color="primary"+ >+ {i18n.t('core:ok')}+ </Button>+ </DialogActions>+ );- render() {- const {- open,- // onClose,- fullScreen,- onCancel- } = this.props;- return (- <Dialog- open={open}- onClose={onCancel}- fullScreen={fullScreen}- // onEnterKey={(event) => onEnterKeyHandler(event, this.onConfirm)}- >- {this.renderTitle()}- {this.renderContent()}- {this.renderActions()}- </Dialog>- );- }+ render() {+ const {+ open,+ // onClose,+ fullScreen,+ onCancel+ } = this.props;+ return (+ <Dialog+ open={open}+ onClose={onCancel}+ fullScreen={fullScreen}+ // onEnterKey={(event) => onEnterKeyHandler(event, this.onConfirm)}+ >+ {this.renderTitle()}+ {this.renderContent()}+ {this.renderActions()}+ </Dialog>+ );+ }}export default withMobileDialog()(EditLocationDialog);diff --git a/app/components/dialogs/EditTagDialog.tsx b/app/components/dialogs/EditTagDialog.tsxindex 0ef5a358a..f7b0bda2d 100644--- a/app/components/dialogs/EditTagDialog.tsx+++ b/app/components/dialogs/EditTagDialog.tsx@@ -31,15 +31,15 @@ import TransparentBackground from '../TransparentBackground';import i18n from '../../services/i18n';import { Tag, TagGroup } from '../../reducers/taglibrary';-type Props = {+interface Props {open: boolean;onClose: () => void;editTag: (tag: Tag, tagGroupId: string) => void;selectedTag: Tag;selectedTagGroupEntry: TagGroup;-};+}-type State = {+interface State {inputError: boolean;displayColorPicker: boolean;displayTextColorPicker: boolean;@@ -48,7 +48,7 @@ type State = {color: string;textcolor: string;modifiedDate: string;-};+}class EditTagDialog extends React.Component<Props, State> {state = {@@ -74,7 +74,7 @@ class EditTagDialog extends React.Component<Props, State> {}};- handleInputChange = (event: Object) => {+ handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {const target = event.target;const value = target.type === 'checkbox' ? target.checked : target.value;const name = target.name;diff --git a/app/components/dialogs/EditTagGroupDialog.tsx b/app/components/dialogs/EditTagGroupDialog.tsxindex 1e5b6011c..7902ea5e2 100644--- a/app/components/dialogs/EditTagGroupDialog.tsx+++ b/app/components/dialogs/EditTagGroupDialog.tsx@@ -32,14 +32,14 @@ import { TagGroup } from '../../reducers/taglibrary';import i18n from '../../services/i18n';import TransparentBackground from '../TransparentBackground';-type Props = {+interface Props {open: boolean;editTagGroup: (tagGroup: TagGroup) => void;selectedTagGroupEntry: TagGroup;onClose: () => void;-};+}-type State = {+interface State {inputError: boolean;displayColorPicker: boolean;displayTextColorPicker: boolean;@@ -49,7 +49,7 @@ type State = {color: string;textcolor: string;modifiedDate: string;-};+}class EditTagGroupDialog extends React.Component<Props, State> {state = {@@ -77,7 +77,7 @@ class EditTagGroupDialog extends React.Component<Props, State> {}};- handleInputChange = (event: Object) => {+ handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {const target = event.target;const value = target.type === 'checkbox' ? target.checked : target.value;const name = target.name;diff --git a/app/components/dialogs/RenameDirectoryDialog.tsx b/app/components/dialogs/RenameDirectoryDialog.tsxindex 1a15b1933..bc9366447 100644--- a/app/components/dialogs/RenameDirectoryDialog.tsx+++ b/app/components/dialogs/RenameDirectoryDialog.tsx@@ -31,118 +31,118 @@ import i18n from '../../services/i18n';import { extractDirectoryName } from '../../utils/paths';import { actions as AppActions } from '../../reducers/app';-type Props = {- open: boolean,- selectedDirectoryPath: string,- onClose: () => void,- renameDirectory: (directoryPath: string, newDirectoryName: string) => void-};+interface Props {+ open: boolean;+ selectedDirectoryPath: string;+ onClose: () => void;+ renameDirectory: (directoryPath: string, newDirectoryName: string) => void;+}-type State = {- inputError: boolean,- disableConfirmButton: boolean,- name: string-};+interface State {+ inputError: boolean;+ disableConfirmButton: boolean;+ name: string;+}class RenameDirectoryDialog extends React.Component<Props, State> {- state = {- inputError: false,- disableConfirmButton: true,- name: this.props.selectedDirectoryPath- ? extractDirectoryName(this.props.selectedDirectoryPath)- : ''- };+ state = {+ inputError: false,+ disableConfirmButton: true,+ name: this.props.selectedDirectoryPath+ ? extractDirectoryName(this.props.selectedDirectoryPath)+ : ''+ };- handleInputChange = (event: Object) => {- this.setState(- {- name: event.target.value- },- this.handleValidation- );- };+ handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {+ this.setState(+ {+ name: event.target.value+ },+ this.handleValidation+ );+ };- handleValidation() {- // const nameRegex = this.state.name.match('^[A-Z][-a-zA-Z]+$');- if (this.state.name.length > 0) {- this.setState({- inputError: false,- disableConfirmButton: false- });- } else {- this.setState({- inputError: true,- disableConfirmButton: true- });- }- }+ handleValidation() {+ // const nameRegex = this.state.name.match('^[A-Z][-a-zA-Z]+$');+ if (this.state.name.length > 0) {+ this.setState({+ inputError: false,+ disableConfirmButton: false+ });+ } else {+ this.setState({+ inputError: true,+ disableConfirmButton: true+ });+ }+ }- onConfirm = () => {- if (!this.state.disableConfirmButton) {- this.props.renameDirectory(- this.props.selectedDirectoryPath,- this.state.name- );- this.setState({- inputError: false,- disableConfirmButton: true- });- this.props.onClose();- }- };+ onConfirm = () => {+ if (!this.state.disableConfirmButton) {+ this.props.renameDirectory(+ this.props.selectedDirectoryPath,+ this.state.name+ );+ this.setState({+ inputError: false,+ disableConfirmButton: true+ });+ this.props.onClose();+ }+ };- render() {- const { open, onClose } = this.props;+ render() {+ const { open, onClose } = this.props;- return (- <Dialog open={open} onClose={onClose} keepMounted scroll="paper">- <DialogTitle>{i18n.t('core:renameDirectory')}</DialogTitle>- <DialogContent>- <FormControl fullWidth={true} error={this.state.inputError}>- <TextField- fullWidth={true}- autoFocus- required- error={this.state.inputError}- margin="dense"- name="name"- label={i18n.t('core:renameDirectoryTitleName')}- onChange={this.handleInputChange}- value={this.state.name}- data-tid="renameDirectoryDialogInput"- />- <FormHelperText>{i18n.t('core:directoryNameHelp')}</FormHelperText>- </FormControl>- </DialogContent>- <DialogActions>- <Button- data-tid="closeRenameDirectoryDialog"- onClick={this.props.onClose}- color="primary"- >- {i18n.t('core:cancel')}- </Button>- <Button- disabled={this.state.disableConfirmButton}- onClick={this.onConfirm}- data-tid="confirmRenameDirectory"- color="primary"- >- {i18n.t('core:ok')}- </Button>- </DialogActions>- </Dialog>- );- }+ return (+ <Dialog open={open} onClose={onClose} keepMounted scroll="paper">+ <DialogTitle>{i18n.t('core:renameDirectory')}</DialogTitle>+ <DialogContent>+ <FormControl fullWidth={true} error={this.state.inputError}>+ <TextField+ fullWidth={true}+ autoFocus+ required+ error={this.state.inputError}+ margin="dense"+ name="name"+ label={i18n.t('core:renameDirectoryTitleName')}+ onChange={this.handleInputChange}+ value={this.state.name}+ data-tid="renameDirectoryDialogInput"+ />+ <FormHelperText>{i18n.t('core:directoryNameHelp')}</FormHelperText>+ </FormControl>+ </DialogContent>+ <DialogActions>+ <Button+ data-tid="closeRenameDirectoryDialog"+ onClick={this.props.onClose}+ color="primary"+ >+ {i18n.t('core:cancel')}+ </Button>+ <Button+ disabled={this.state.disableConfirmButton}+ onClick={this.onConfirm}+ data-tid="confirmRenameDirectory"+ color="primary"+ >+ {i18n.t('core:ok')}+ </Button>+ </DialogActions>+ </Dialog>+ );+ }}function mapActionCreatorsToProps(dispatch) {- return bindActionCreators(- {- renameDirectory: AppActions.renameDirectory- },- dispatch- );+ return bindActionCreators(+ {+ renameDirectory: AppActions.renameDirectory+ },+ dispatch+ );}export default connect(null, mapActionCreatorsToProps)(RenameDirectoryDialog);diff --git a/app/components/dialogs/RenameFileDialog.tsx b/app/components/dialogs/RenameFileDialog.tsxindex b83a9499c..d5e09a365 100644--- a/app/components/dialogs/RenameFileDialog.tsx+++ b/app/components/dialogs/RenameFileDialog.tsx@@ -32,184 +32,183 @@ import { onEnterKeyHandler, DialogTransition } from './GenericDialog';import AppConfig from '../../config';import i18n from '../../services/i18n';import {- extractFileName,- extractContainingDirectoryPath+ extractFileName,+ extractContainingDirectoryPath} from '../../utils/paths';import { actions as AppActions } from '../../reducers/app';-type Props = {- open: boolean,- selectedFilePath: string,- classes: Object,- renameFile: (source: string, target: string) => void,- onClose: () => void-};--type State = {- inputError: boolean,- disableConfirmButton: boolean,- fileName: string,- length: string-};+interface Props {+ open: boolean;+ selectedFilePath: string;+ classes: Object;+ renameFile: (source: string, target: string) => void;+ onClose: () => void;+}++interface State {+ inputError: boolean;+ disableConfirmButton: boolean;+ fileName: string;+}const styles = theme => ({- root: {- width: 550,- height: '100%',- marginBottom: 30,- background: theme.palette.background.paper- }+ root: {+ width: 550,+ height: '100%',+ marginBottom: 30,+ background: theme.palette.background.paper+ }});class RenameFileDialog extends React.Component<Props, State> {- state = {- inputError: false,- disableConfirmButton: true,- fileName: ''- };-- componentWillReceiveProps = (nextProps: any) => {- if (nextProps.open) {- const fileName = extractFileName(nextProps.selectedFilePath);- this.setState({ fileName }, () => {- this.fileName.focus();- if (fileName) {- const indexOfBracket = fileName.indexOf(AppConfig.beginTagContainer);- const indexOfDot = fileName.indexOf('.');- let endRange = fileName.length;- if (indexOfBracket > 0) {- endRange = indexOfBracket;- } else if (indexOfDot > 0) {- endRange = indexOfDot;- }- this.fileName.setSelectionRange(0, endRange);- }- return {- fileName- };- });- }- };-- fileName;-- handleInputChange = (event: Object) => {- const target = event.target;- const value = target.type === 'checkbox' ? target.checked : target.value;- const name = target.name;-- this.setState(- {- [name]: value- },- this.handleValidation- );- };-- handleValidation() {- if (this.state.fileName.length > 0) {- this.setState({ inputError: false, disableConfirmButton: false });- } else {- this.setState({ inputError: true, disableConfirmButton: true });- }- }-- onConfirm = () => {- if (!this.state.disableConfirmButton) {- const fileDirectory = extractContainingDirectoryPath(- this.props.selectedFilePath- );- const newFilePath =- fileDirectory + AppConfig.dirSeparator + this.state.fileName;- this.props.renameFile(this.props.selectedFilePath, newFilePath);- this.props.onClose();- this.setState({ inputError: false, disableConfirmButton: true });- } else {- this.handleValidation();- }- };-- renderTitle = () => (- <DialogTitle>{i18n.t('core:renameFileTitle')}</DialogTitle>- );-- renderContent = () => (- <DialogContent className={this.props.classes.root}>- <FormControl- data-tid="renameFileDialog"- fullWidth={true}- error={this.state.inputError}- >- <TextField- error={this.state.inputError}- margin="dense"- name="fileName"- autoFocus- inputRef={ref => {- this.fileName = ref;- }}- label={i18n.t('core:renameNewFileName')}- onChange={this.handleInputChange}- value={this.state.fileName}- data-tid="renameFileDialogInput"- fullWidth={true}- />- {this.state.inputError && (- <FormHelperText>Empty File Name</FormHelperText>- )}- </FormControl>- </DialogContent>- );-- renderActions = () => (- <DialogActions>- <Button- data-tid="closeRenameFileDialog"- onClick={this.props.onClose}- color="primary"- >- {i18n.t('core:cancel')}- </Button>- <Button- disabled={this.state.disableConfirmButton}- onClick={this.onConfirm}- data-tid="confirmRenameFileDialog"- color="primary"- >- {i18n.t('core:ok')}- </Button>- </DialogActions>- );-- render() {- const { onClose, open } = this.props;- return (- <Dialog- open={open}- TransitionComponent={DialogTransition}- keepMounted- onClose={onClose}- onBackdropClick={onClose}- // onKeyDown={((event) => onEnterKeyHandler(event, this.onConfirm))}- >- {this.renderTitle()}- {this.renderContent()}- {this.renderActions()}- </Dialog>- );- }+ state = {+ inputError: false,+ disableConfirmButton: true,+ fileName: ''+ };++ componentWillReceiveProps = (nextProps: any) => {+ if (nextProps.open) {+ const fileName = extractFileName(nextProps.selectedFilePath);+ this.setState({ fileName }, () => {+ this.fileName.focus();+ if (fileName) {+ const indexOfBracket = fileName.indexOf(AppConfig.beginTagContainer);+ const indexOfDot = fileName.indexOf('.');+ let endRange = fileName.length;+ if (indexOfBracket > 0) {+ endRange = indexOfBracket;+ } else if (indexOfDot > 0) {+ endRange = indexOfDot;+ }+ this.fileName.setSelectionRange(0, endRange);+ }+ return {+ fileName+ };+ });+ }+ };++ fileName;++ handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {+ const target = event.target;+ const value = target.type === 'checkbox' ? target.checked : target.value;+ const name = target.name;++ this.setState(+ {+ [name]: value+ },+ this.handleValidation+ );+ };++ handleValidation() {+ if (this.state.fileName.length > 0) {+ this.setState({ inputError: false, disableConfirmButton: false });+ } else {+ this.setState({ inputError: true, disableConfirmButton: true });+ }+ }++ onConfirm = () => {+ if (!this.state.disableConfirmButton) {+ const fileDirectory = extractContainingDirectoryPath(+ this.props.selectedFilePath+ );+ const newFilePath =+ fileDirectory + AppConfig.dirSeparator + this.state.fileName;+ this.props.renameFile(this.props.selectedFilePath, newFilePath);+ this.props.onClose();+ this.setState({ inputError: false, disableConfirmButton: true });+ } else {+ this.handleValidation();+ }+ };++ renderTitle = () => (+ <DialogTitle>{i18n.t('core:renameFileTitle')}</DialogTitle>+ );++ renderContent = () => (+ <DialogContent className={this.props.classes.root}>+ <FormControl+ data-tid="renameFileDialog"+ fullWidth={true}+ error={this.state.inputError}+ >+ <TextField+ error={this.state.inputError}+ margin="dense"+ name="fileName"+ autoFocus+ inputRef={ref => {+ this.fileName = ref;+ }}+ label={i18n.t('core:renameNewFileName')}+ onChange={this.handleInputChange}+ value={this.state.fileName}+ data-tid="renameFileDialogInput"+ fullWidth={true}+ />+ {this.state.inputError && (+ <FormHelperText>Empty File Name</FormHelperText>+ )}+ </FormControl>+ </DialogContent>+ );++ renderActions = () => (+ <DialogActions>+ <Button+ data-tid="closeRenameFileDialog"+ onClick={this.props.onClose}+ color="primary"+ >+ {i18n.t('core:cancel')}+ </Button>+ <Button+ disabled={this.state.disableConfirmButton}+ onClick={this.onConfirm}+ data-tid="confirmRenameFileDialog"+ color="primary"+ >+ {i18n.t('core:ok')}+ </Button>+ </DialogActions>+ );++ render() {+ const { onClose, open } = this.props;+ return (+ <Dialog+ open={open}+ TransitionComponent={DialogTransition}+ keepMounted+ onClose={onClose}+ onBackdropClick={onClose}+ // onKeyDown={((event) => onEnterKeyHandler(event, this.onConfirm))}+ >+ {this.renderTitle()}+ {this.renderContent()}+ {this.renderActions()}+ </Dialog>+ );+ }}function mapActionCreatorsToProps(dispatch) {- return bindActionCreators(- {- renameFile: AppActions.renameFile- },- dispatch- );+ return bindActionCreators(+ {+ renameFile: AppActions.renameFile+ },+ dispatch+ );}export default connect(- null,- mapActionCreatorsToProps+ null,+ mapActionCreatorsToProps)(withStyles(styles)(RenameFileDialog));diff --git a/app/components/dialogs/SelectDirectoryDialog.tsx b/app/components/dialogs/SelectDirectoryDialog.tsxindex 26f625e4c..447407010 100644--- a/app/components/dialogs/SelectDirectoryDialog.tsx+++ b/app/components/dialogs/SelectDirectoryDialog.tsx@@ -37,276 +37,276 @@ import AppConfig from '../../config';import PlatformIO from '../../services/platform-io';import { loadSubFolders } from '../../services/utils-io';-type Props = {- open: boolean,- onClose: () => void-};+interface Props {+ open: boolean;+ onClose: () => void;+}-type State = {- errorTextPath: boolean,- errorTextName: boolean,- open: boolean,- drives: Array<string>,- currentPath: string,- isDefault: boolean-};+interface State {+ errorTextPath: boolean;+ errorTextName: boolean;+ open: boolean;+ drives: Array<string>;+ currentPath: string;+ isDefault: boolean;+}const styles = () => ({- buttonContainer: {- color: '#212121',- backgroundColor: '#f5f5f5',- borderColor: '#dddddd',- marginLeft: 4,- marginTop: 4,- marginBottom: 4- },- buttonSuggestion: {- fontSize: 10,- textTransform: 'none',- backgroundColor: '#E5E5E5',- color: '#444444',- textAlign: 'left',- backgroundImage: 'none',- margin: 0,- paddingTop: '0',- paddingBottom: '0',- paddingRight: 0,- borderRadius: 5- },- alertWarning: {- color: '#fff',- backgroundColor: '#ff9800',- margin: 15,- padding: 15- },- folderIcon: {- color: '#ff9800'- },- contentFolder: {- overflowY: 'auto',- maxHeight: '40vh'- }+ buttonContainer: {+ color: '#212121',+ backgroundColor: '#f5f5f5',+ borderColor: '#dddddd',+ marginLeft: 4,+ marginTop: 4,+ marginBottom: 4+ },+ buttonSuggestion: {+ fontSize: 10,+ textTransform: 'none',+ backgroundColor: '#E5E5E5',+ color: '#444444',+ textAlign: 'left',+ backgroundImage: 'none',+ margin: 0,+ paddingTop: '0',+ paddingBottom: '0',+ paddingRight: 0,+ borderRadius: 5+ },+ alertWarning: {+ color: '#fff',+ backgroundColor: '#ff9800',+ margin: 15,+ padding: 15+ },+ folderIcon: {+ color: '#ff9800'+ },+ contentFolder: {+ overflowY: 'auto',+ maxHeight: '40vh'+ }});const drives = [- 'Choose Drive',- 'A:',- 'B:',- 'C:',- 'D:',- 'F:',- 'G:',- 'H:',- 'I:',- 'J:',- 'K:',- 'L:',- 'M:',- 'N:',- 'O:',- 'P:',- 'Q:',- 'R:',- 'S:',- 'T:',- 'U:',- 'V:',- 'W:',- 'X:',- 'Y:',- 'Z:'+ 'Choose Drive',+ 'A:',+ 'B:',+ 'C:',+ 'D:',+ 'F:',+ 'G:',+ 'H:',+ 'I:',+ 'J:',+ 'K:',+ 'L:',+ 'M:',+ 'N:',+ 'O:',+ 'P:',+ 'Q:',+ 'R:',+ 'S:',+ 'T:',+ 'U:',+ 'V:',+ 'W:',+ 'X:',+ 'Y:',+ 'Z:'];class SelectDirectoryDialog extends React.Component<Props, State> {- state = {- errorTextPath: false,- alertSubFolderText: false,- disableConfirmButton: true,- open: false,- currentPath: PlatformIO.getUserHomePath(),- subFolders: [],- choosePath: '',- isDefault: false- };+ state = {+ errorTextPath: false,+ alertSubFolderText: false,+ disableConfirmButton: true,+ open: false,+ currentPath: PlatformIO.getUserHomePath(),+ subFolders: [],+ choosePath: '',+ isDefault: false+ };- componentWillReceiveProps = (nextProps: any) => {- if (nextProps.open === true) {- let currentPath = this.state.currentPath;- if (nextProps.currentPath) {- currentPath = nextProps.currentPath;- }- this.setState({- open: true,- currentPath, // AppConfig.isWin ? drives[3] : AppConfig.dirSeparator,- choosePath: drives[0]- });- this.loadListDirectory(currentPath);- }- };+ componentWillReceiveProps = (nextProps: any) => {+ if (nextProps.open === true) {+ let currentPath = this.state.currentPath;+ if (nextProps.currentPath) {+ currentPath = nextProps.currentPath;+ }+ this.setState({+ open: true,+ currentPath, // AppConfig.isWin ? drives[3] : AppConfig.dirSeparator,+ choosePath: drives[0]+ });+ this.loadListDirectory(currentPath);+ }+ };- loadListDirectory = (path: string) => {- loadSubFolders(path)- .then(rootDirContent => {- this.setState({- subFolders: rootDirContent- });- return true;- })- .catch(error => {- console.log('Error listing directory ' + error);- });- };+ loadListDirectory = (path: string) => {+ loadSubFolders(path)+ .then(rootDirContent => {+ this.setState({+ subFolders: rootDirContent+ });+ return true;+ })+ .catch(error => {+ console.log('Error listing directory ' + error);+ });+ };- onConfirm = () => {- this.props.chooseDirectoryPath(this.state.currentPath);- this.setState({- open: false,- errorTextPath: false- });- this.props.onClose();- };+ onConfirm = () => {+ this.props.chooseDirectoryPath(this.state.currentPath);+ this.setState({+ open: false,+ errorTextPath: false+ });+ this.props.onClose();+ };- handleChooseDrive = (e: Object, selectedPath: string) => {- this.setState({- currentPath: selectedPath- });- this.loadListDirectory(selectedPath);- };+ handleChooseDrive = (e: Object, selectedPath: string) => {+ this.setState({+ currentPath: selectedPath+ });+ this.loadListDirectory(selectedPath);+ };- handleInputChange = (event: Object) => {- const target = event.target;- const value = target.type === 'checkbox' ? target.checked : target.value;- const name = target.name;+ handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {+ const target = event.target;+ const value = target.type === 'checkbox' ? target.checked : target.value;+ const name = target.name;- this.setState({- [name]: value,- currentPath: value- });- this.loadListDirectory(value);- };+ this.setState({+ [name]: value,+ currentPath: value+ });+ this.loadListDirectory(value);+ };- onBackButton = () => {- const lastIndex = this.state.currentPath.lastIndexOf(- AppConfig.dirSeparator- );- const path = this.state.currentPath.slice(0, lastIndex);- this.setState({- currentPath: path- });- this.loadListDirectory(path);- };+ onBackButton = () => {+ const lastIndex = this.state.currentPath.lastIndexOf(+ AppConfig.dirSeparator+ );+ const path = this.state.currentPath.slice(0, lastIndex);+ this.setState({+ currentPath: path+ });+ this.loadListDirectory(path);+ };- createNewFolder = () => {- this.props.createNewDirectoryExt(this.state.currentPath);- this.loadListDirectory(this.state.currentPath);- };+ createNewFolder = () => {+ this.props.createNewDirectoryExt(this.state.currentPath);+ this.loadListDirectory(this.state.currentPath);+ };- renderDriveSuggestions = drive => (- <div className={styles.buttonContainer}>- <Button- key={drive.name}- onClick={e => this.handleChooseDrive(e, drive.path)}- >- <FolderIcon />- <span>{drive.name}</span>- </Button>- </div>- );+ renderDriveSuggestions = drive => (+ <div className={styles.buttonContainer}>+ <Button+ key={drive.name}+ onClick={e => this.handleChooseDrive(e, drive.path)}+ >+ <FolderIcon />+ <span>{drive.name}</span>+ </Button>+ </div>+ );- render() {- const { fullScreen, open, onClose } = this.props;+ render() {+ const { fullScreen, open, onClose } = this.props;- return (- <Dialog- open={open}- onClose={onClose}- fullScreen={fullScreen}- keepMounted- scroll="paper"- // onKeyDown={confirmFunction}- >- <DialogTitle>{i18n.t('core:selectDialogTitle')}</DialogTitle>- <DialogContent>- <FormControl fullWidth={true} error={this.props.errorTextPath}>- <InputLabel htmlFor="name">- {i18n.t('core:selectDialogCurrentPath')}- </InputLabel>- <Input- fullWidth={true}- required- margin="dense"- name="path"- onChange={this.handleInputChange}- label={i18n.t('core:selectDialogCurrentPath')}- data-tid="selectDirectoryDialogInput"- value={this.state.currentPath}- disabled={AppConfig.isWin}- />- {this.state.errorTextPath && (- <FormHelperText>{i18n.t('core:invalidPath')}</FormHelperText>- )}- </FormControl>- {AppConfig.isWin ? (- <FormControl fullWidth={true}>- <Select- data-tid="selectDirectoryDialogSelect"- native- autoWidth- name="choosePath"- value={this.state.choosePath}- onChange={this.handleInputChange}- input={<Input id="choosePath" />}- >- {drives.map(drive => (- <option key={drive} value={drive}>- {drive}- </option>- ))}- </Select>- </FormControl>- ) : null}- <FormControl fullWidth={true}>- <Paper elevation={2}>- <Button- data-tid="onBackButtonSelectDirectoryDialog"- onClick={e => this.onBackButton(e)}- >- <UndoIcon />- </Button>- <Button- data-tid="createNewFolderSelectDirectoryDialog"- onClick={e => this.createNewFolder(e)}- >- <CreateFolderIcon className={this.props.classes.folderIcon} />- {i18n.t('core:createDirectory')}- </Button>- </Paper>- <Paper elevation={2} className={this.props.classes.contentFolder}>- {this.state.subFolders.length === 0 ? (- <div className={this.props.classes.alertWarning}>- {i18n.t('core:noSubfoldersFound')}- </div>- ) : (- this.state.subFolders.map(this.renderDriveSuggestions)- )}- </Paper>- </FormControl>- </DialogContent>- <DialogActions>- <Button onClick={this.props.onClose} color="primary">- {i18n.t('core:cancel')}- </Button>- <Button- onClick={this.onConfirm}- data-tid="confirmSelectDirectoryDialog"- color="primary"- >- {i18n.t('core:ok')}- </Button>- </DialogActions>- </Dialog>- );- }+ return (+ <Dialog+ open={open}+ onClose={onClose}+ fullScreen={fullScreen}+ keepMounted+ scroll="paper"+ // onKeyDown={confirmFunction}+ >+ <DialogTitle>{i18n.t('core:selectDialogTitle')}</DialogTitle>+ <DialogContent>+ <FormControl fullWidth={true} error={this.props.errorTextPath}>+ <InputLabel htmlFor="name">+ {i18n.t('core:selectDialogCurrentPath')}+ </InputLabel>+ <Input+ fullWidth={true}+ required+ margin="dense"+ name="path"+ onChange={this.handleInputChange}+ label={i18n.t('core:selectDialogCurrentPath')}+ data-tid="selectDirectoryDialogInput"+ value={this.state.currentPath}+ disabled={AppConfig.isWin}+ />+ {this.state.errorTextPath && (+ <FormHelperText>{i18n.t('core:invalidPath')}</FormHelperText>+ )}+ </FormControl>+ {AppConfig.isWin ? (+ <FormControl fullWidth={true}>+ <Select+ data-tid="selectDirectoryDialogSelect"+ native+ autoWidth+ name="choosePath"+ value={this.state.choosePath}+ onChange={this.handleInputChange}+ input={<Input id="choosePath" />}+ >+ {drives.map(drive => (+ <option key={drive} value={drive}>+ {drive}+ </option>+ ))}+ </Select>+ </FormControl>+ ) : null}+ <FormControl fullWidth={true}>+ <Paper elevation={2}>+ <Button+ data-tid="onBackButtonSelectDirectoryDialog"+ onClick={e => this.onBackButton(e)}+ >+ <UndoIcon />+ </Button>+ <Button+ data-tid="createNewFolderSelectDirectoryDialog"+ onClick={e => this.createNewFolder(e)}+ >+ <CreateFolderIcon className={this.props.classes.folderIcon} />+ {i18n.t('core:createDirectory')}+ </Button>+ </Paper>+ <Paper elevation={2} className={this.props.classes.contentFolder}>+ {this.state.subFolders.length === 0 ? (+ <div className={this.props.classes.alertWarning}>+ {i18n.t('core:noSubfoldersFound')}+ </div>+ ) : (+ this.state.subFolders.map(this.renderDriveSuggestions)+ )}+ </Paper>+ </FormControl>+ </DialogContent>+ <DialogActions>+ <Button onClick={this.props.onClose} color="primary">+ {i18n.t('core:cancel')}+ </Button>+ <Button+ onClick={this.onConfirm}+ data-tid="confirmSelectDirectoryDialog"+ color="primary"+ >+ {i18n.t('core:ok')}+ </Button>+ </DialogActions>+ </Dialog>+ );+ }}export default withStyles(styles)(SelectDirectoryDialog);diff --git a/app/components/menus/LocationMenu.tsx b/app/components/menus/LocationMenu.tsxindex 40413892d..52fe92526 100644--- a/app/components/menus/LocationMenu.tsx+++ b/app/components/menus/LocationMenu.tsx@@ -30,149 +30,148 @@ import { withTheme } from '@material-ui/core/styles';import Button from '@material-ui/core/Button';import ArrowDropDownIcon from '@material-ui/icons/ArrowDropDown';import i18n from '../../services/i18n';+import { getLocations, Location, locationType } from '../../reducers/locations';import {- getLocations,- type Location,- locationType-} from '../../reducers/locations';-import {- actions as AppActions,- getCurrentLocationId+ actions as AppActions,+ getCurrentLocationId} from '../../reducers/app';-type Props = {- currentLocationId: string | null,- theme: Object,- locations: Array<Location>,- menuAnchorEl: null | Object,- openLocation: (location: Location) => void-};+interface Props {+ currentLocationId: string | null;+ theme: Object;+ locations: Array<Location>;+ menuAnchorEl: null | Object;+ openLocation: (location: Location) => void;+}-type State = {- currentLocation?: Location | null,- locationChooserMenuOpened: boolean,- locationChooserMenuAnchorEl: null | Object-};+interface State {+ currentLocation: Location | null;+ locationChooserMenuOpened: boolean;+ locationChooserMenuAnchorEl: null | Object;+}class LocationMenu extends React.Component<Props, State> {- state = {- locationChooserMenuOpened: false,- locationChooserMenuAnchorEl: null- };+ state = {+ currentLocation: null,+ locationChooserMenuOpened: false,+ locationChooserMenuAnchorEl: null+ };- static getDerivedStateFromProps(nextProps, prevState) {- let currentLocation;- if (nextProps.currentLocationId && nextProps.locations) {- nextProps.locations.map((location: Location) => {- if (location.uuid === nextProps.currentLocationId) {- currentLocation = location;- }- });- }- return {- ...prevState,- currentLocation- };- }+ static getDerivedStateFromProps(nextProps, prevState) {+ let currentLocation;+ if (nextProps.currentLocationId && nextProps.locations) {+ nextProps.locations.map((location: Location) => {+ if (location.uuid === nextProps.currentLocationId) {+ currentLocation = location;+ }+ });+ }+ return {+ ...prevState,+ currentLocation+ };+ }- openLocation = location => {- this.props.openLocation(location);- this.toggleLocationChooser();- };+ openLocation = location => {+ this.props.openLocation(location);+ this.toggleLocationChooser(undefined);+ };- toggleLocationChooser = (event?: Object) => {- this.setState({- locationChooserMenuOpened: !this.state.locationChooserMenuOpened,- locationChooserMenuAnchorEl: event ? event.currentTarget : null- });- };+ toggleLocationChooser = (+ event: React.ChangeEvent<HTMLInputElement> | undefined+ ) => {+ this.setState({+ locationChooserMenuOpened: !this.state.locationChooserMenuOpened,+ locationChooserMenuAnchorEl: event ? event.currentTarget : null+ });+ };- render() {- const { theme } = this.props;- const { currentLocation } = this.state;- const locationIcon =- currentLocation && currentLocation.type === locationType.TYPE_CLOUD ? (- <CloudLocationIcon />- ) : (- <LocationIcon />- );+ render() {+ const { theme } = this.props;+ const { currentLocation } = this.state;+ const locationIcon =+ currentLocation && currentLocation.type === locationType.TYPE_CLOUD ? (+ <CloudLocationIcon />+ ) : (+ <LocationIcon />+ );- return (- <div- style={{- backgroundColor: theme.palette.background.default- }}- >- <Button- data-tid="folderContainerLocationChooser"- id="locationMenuButton"- onClick={this.toggleLocationChooser}- title={this.state.currentLocation && this.state.currentLocation.name}- style={{ paddingRight: 0, paddingLeft: 11 }}- >- {this.state.currentLocation- ? locationIcon // this.state.currentLocation.name- : i18n.t('core:pleaseOpenLocation')}- <ArrowDropDownIcon />- </Button>- <Menu- id="simple-menu"- open={this.state.locationChooserMenuOpened}- anchorEl={this.state.locationChooserMenuAnchorEl}- onClose={this.toggleLocationChooser}- PaperProps={{- style: {- maxHeight: 48 * 6.5,- width: 300- }- }}- >- <div style={{ display: 'none' }} />- <ListSubHeader>{i18n.t('core:chooseLocation')}</ListSubHeader>- {this.props.locations.map((location: Location) => (- <MenuItem- data-tid="folderContainerMenuOpenLocation"- key={location.uuid}- onClick={() => this.openLocation(location)}- style={- currentLocation && currentLocation.uuid === location.uuid- ? { backgroundColor: theme.palette.primary.light }- : {}- }- >- <ListItemIcon>- {location.type === locationType.TYPE_CLOUD ? (- <CloudLocationIcon />- ) : (- <LocationIcon />- )}- </ListItemIcon>- <ListItemText primary={location.name} />- </MenuItem>- ))}- </Menu>- </div>- );- }+ return (+ <div+ style={{+ backgroundColor: theme.palette.background.default+ }}+ >+ <Button+ data-tid="folderContainerLocationChooser"+ id="locationMenuButton"+ onClick={this.toggleLocationChooser}+ title={this.state.currentLocation && this.state.currentLocation.name}+ style={{ paddingRight: 0, paddingLeft: 11 }}+ >+ {this.state.currentLocation+ ? locationIcon // this.state.currentLocation.name+ : i18n.t('core:pleaseOpenLocation')}+ <ArrowDropDownIcon />+ </Button>+ <Menu+ id="simple-menu"+ open={this.state.locationChooserMenuOpened}+ anchorEl={this.state.locationChooserMenuAnchorEl}+ onClose={this.toggleLocationChooser}+ PaperProps={{+ style: {+ maxHeight: 48 * 6.5,+ width: 300+ }+ }}+ >+ <div style={{ display: 'none' }} />+ <ListSubHeader>{i18n.t('core:chooseLocation')}</ListSubHeader>+ {this.props.locations.map((location: Location) => (+ <MenuItem+ data-tid="folderContainerMenuOpenLocation"+ key={location.uuid}+ onClick={() => this.openLocation(location)}+ style={+ currentLocation && currentLocation.uuid === location.uuid+ ? { backgroundColor: theme.palette.primary.light }+ : {}+ }+ >+ <ListItemIcon>+ {location.type === locationType.TYPE_CLOUD ? (+ <CloudLocationIcon />+ ) : (+ <LocationIcon />+ )}+ </ListItemIcon>+ <ListItemText primary={location.name} />+ </MenuItem>+ ))}+ </Menu>+ </div>+ );+ }}function mapStateToProps(state) {- return {- locations: getLocations(state),- currentLocationId: getCurrentLocationId(state)- };+ return {+ locations: getLocations(state),+ currentLocationId: getCurrentLocationId(state)+ };}function mapActionCreatorsToProps(dispatch) {- return bindActionCreators(- {- openLocation: AppActions.openLocation- },- dispatch- );+ return bindActionCreators(+ {+ openLocation: AppActions.openLocation+ },+ dispatch+ );}export default connect(- mapStateToProps,- mapActionCreatorsToProps+ mapStateToProps,+ mapActionCreatorsToProps)(withTheme(LocationMenu));diff --git a/app/config.ts b/app/config.tsindex ef692053d..f7fc33bf7 100644--- a/app/config.ts+++ b/app/config.ts@@ -14,7 +14,6 @@* 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/>.*- * @flow*/const isCordovaiOS =/^file:\/{3}[^\/]/i.test(window.location.href) &&diff --git a/app/perspectives/grid-perspective/components/MainContainer.tsx b/app/perspectives/grid-perspective/components/MainContainer.tsxindex 49ef912e6..b2186d6f9 100644--- a/app/perspectives/grid-perspective/components/MainContainer.tsx+++ b/app/perspectives/grid-perspective/components/MainContainer.tsx@@ -24,8 +24,6 @@ import memoize from 'memoize-one';import { GlobalHotKeys } from 'react-hotkeys';import { withStyles } from '@material-ui/core/styles';import Typography from '@material-ui/core/Typography';-import FolderIcon from '@material-ui/icons/FolderOpen';-import FolderHiddenIcon from '@material-ui/icons/Folder';import { FileSystemEntry } from '../../../services/utils-io';import { Tag } from '../../../reducers/taglibrary';import {@@ -65,73 +63,73 @@ import GridOptionsMenu from './GridOptionsMenu';const settings = JSON.parse(localStorage.getItem('tsPerspectiveGrid')); // loading settings-type Props = {- classes: Object,- theme: Object,- desktopMode: boolean,- currentDirectoryPath: string,- currentDirectoryColor: string,- lastSelectedEntryPath: string | null,- selectedEntries: Array<Object>,- supportedFileTypes: Array<Object>,- isAppLoading: boolean,- isReadOnlyMode: boolean,- openFile: (path: string, isFile?: boolean) => void,- getNextFile: () => void,- getPrevFile: () => void,- deleteFile: (path: string) => void,- deleteDirectory: (path: string) => void,- loadDirectoryContent: (path: string) => void,- openDirectory: (path: string) => void,- showInFileManager: (path: string) => void,- openFileNatively: (path: string) => void,- openURLExternally: (path: string) => void,- loadParentDirectoryContent: () => void,- setLastSelectedEntry: (entryPath: string | null) => void,- setSelectedEntries: (selectedEntries: Array<Object>) => void,- addTags: () => void,- removeTags: () => void,- removeAllTags: () => void,- editTagForEntry: () => void,- perspectiveCommand: Object,- directoryContent: Array<FileSystemEntry>,- moveFiles: (files: Array<string>, destination: string) => void,- keyBindings: Object,+interface Props {+ classes: Object;+ theme: Object;+ desktopMode: boolean;+ currentDirectoryPath: string;+ currentDirectoryColor: string;+ lastSelectedEntryPath: string | null;+ selectedEntries: Array<Object>;+ supportedFileTypes: Array<Object>;+ isAppLoading: boolean;+ isReadOnlyMode: boolean;+ openFile: (path: string, isFile?: boolean) => void;+ getNextFile: () => void;+ getPrevFile: () => void;+ deleteFile: (path: string) => void;+ deleteDirectory: (path: string) => void;+ loadDirectoryContent: (path: string) => void;+ openDirectory: (path: string) => void;+ showInFileManager: (path: string) => void;+ openFileNatively: (path: string) => void;+ openURLExternally: (path: string) => void;+ loadParentDirectoryContent: () => void;+ setLastSelectedEntry: (entryPath: string | null) => void;+ setSelectedEntries: (selectedEntries: Array<Object>) => void;+ addTags: () => void;+ removeTags: () => void;+ removeAllTags: () => void;+ editTagForEntry: () => void;+ perspectiveCommand: any;+ directoryContent: Array<FileSystemEntry>;+ moveFiles: (files: Array<string>, destination: string) => void;+ keyBindings: any;showNotification: (text: string,notificationType: string,autohide: boolean- ) => void+ ) => void;};-type State = {- fileContextMenuAnchorEl: Object | null,- fileContextMenuOpened: boolean,- dirContextMenuAnchorEl: Object | null,- dirContextMenuOpened: boolean,- tagContextMenuAnchorEl: Object | null,- tagContextMenuOpened: boolean,- layoutType: string,- singleClickAction: string,- doubleClickAction: string,- entrySize: string,- thumbnailMode: string,- sortingContextMenuAnchorEl: Object | null,- sortingContextMenuOpened: boolean | null,- optionsContextMenuAnchorEl: Object | null,- optionsContextMenuOpened: boolean | null,- sortBy: string,- orderBy: null | boolean,- fileOperationsEnabled: boolean,- allFilesSelected: boolean,- showDirectories: boolean,- showTags: boolean,- isDeleteMultipleFilesDialogOpened: boolean,- isMoveCopyFilesDialogOpened: boolean,- isAddRemoveTagsDialogOpened: boolean,- isFileRenameDialogOpened: boolean,- selectedEntryPath: string,- selectedTag: Tag | null+interface State {+ fileContextMenuAnchorEl: Object | null;+ fileContextMenuOpened: boolean;+ dirContextMenuAnchorEl: Object | null;+ dirContextMenuOpened: boolean;+ tagContextMenuAnchorEl: Object | null;+ tagContextMenuOpened: boolean;+ layoutType: string;+ singleClickAction: string;+ doubleClickAction: string;+ entrySize: string;+ thumbnailMode: string;+ sortingContextMenuAnchorEl: Object | null;+ sortingContextMenuOpened: boolean | null;+ optionsContextMenuAnchorEl: Object | null;+ optionsContextMenuOpened: boolean | null;+ sortBy: string;+ orderBy: null | boolean;+ fileOperationsEnabled: boolean;+ allFilesSelected: boolean;+ showDirectories: boolean;+ showTags: boolean;+ isDeleteMultipleFilesDialogOpened: boolean;+ isMoveCopyFilesDialogOpened: boolean;+ isAddRemoveTagsDialogOpened: boolean;+ isFileRenameDialogOpened: boolean;+ selectedEntryPath: string;+ selectedTag: Tag | null;};class GridPerspective extends React.Component<Props, State> {@@ -474,7 +472,7 @@ class GridPerspective extends React.Component<Props, State> {}};- handleTagMenu = (event: Object, tag: Tag, entryPath: string) => {+ handleTagMenu = (event: React.ChangeEvent<HTMLInputElement>, tag: Tag, entryPath: string) => {event.preventDefault();event.stopPropagation();diff --git a/app/routes.ts b/app/routes.tsxsimilarity index 100%rename from app/routes.tsrename to app/routes.tsxdiff --git a/app/services/cordova-io.ts b/app/services/cordova-io.tsindex a2c6589e3..4b12800a7 100644--- a/app/services/cordova-io.ts+++ b/app/services/cordova-io.ts@@ -24,6 +24,7 @@ import {extractParentDirectoryPath,cleanTrailingDirSeparator} from '../utils/paths';+import { FileSystemEntry } from './utils-io';const appSettingFile = 'settings.json';const appSettingTagsFile = 'settingsTags.json';@@ -157,7 +158,7 @@ export default class CordovaIO {}};- getFileSystemPromise = (path: string): Promise<*> => {+ getFileSystemPromise = (path: string): Promise<any> => {console.log('getFileSystemPromise: ' + path);if (path.indexOf(cordova.file.applicationDirectory) === 0) {} else {@@ -429,7 +430,7 @@ export default class CordovaIO {/*** Creates a list with containing the files and the sub directories of a given directory*/- listDirectoryPromise = (path: string, lite: boolean): Promise<*> =>+ listDirectoryPromise = (path: string, lite: boolean): Promise<any> =>new Promise(async (resolve, reject) => {console.time('listDirectoryPromise');const metaContent = !lite@@ -596,7 +597,7 @@ export default class CordovaIO {});});- getEntryMeta = (eentry: Object, metaPath: string): Promise<Object> => {+ getEntryMeta = (eentry: FileSystemEntry, metaPath: string): Promise<any> => {if (eentry.isFile) {// const metaFilePath = getMetaFileLocationForFile(eentry.path);return this.loadTextFilePromise(metaPath).then(result => {@@ -623,11 +624,11 @@ export default class CordovaIO {/*** Finds out the properties of a file or directory such last modification date or file size*/- getPropertiesPromise = (path: string): Promise<*> =>+ getPropertiesPromise = (path: string): Promise<any> =>new Promise((resolve, reject) => {const entryPath = this.normalizePath(path);// getFileSystemPromise(dir).then(function(fileSystem) {- const fileProperties = {};+ const fileProperties: object = {};this.fsRoot.getFile(entryPath,{@@ -677,7 +678,7 @@ export default class CordovaIO {/*** Load the content of a text file*/- loadTextFilePromise = (filePath: string): Promise<*> =>+ loadTextFilePromise = (filePath: string): Promise<any> =>this.getFileContentPromise(filePath, 'text');/**@@ -686,8 +687,8 @@ export default class CordovaIO {getFileContentPromise = (filePath: string,type,- resolvePath: string- ): Promise<*> => {+ resolvePath?: string+ ): Promise<any> => {// TODO refactorconst getFilePromise = (filePath, resolvePath) => {const getFile = (fullPath, result, fail) => {@@ -751,7 +752,7 @@ export default class CordovaIO {content,overWrite: boolean,isRaw?: boolean- ): Promise<*> => {+ ): Promise<any> => {// eslint-disable-next-line no-param-reassignfilePath = this.normalizePath(filePath);console.log('Saving file: ' + filePath);@@ -815,7 +816,7 @@ export default class CordovaIO {);} else {const errMsg = $.i18n.t('ns.common:fileExists', { fileName: filePath });- showAlertDialog(errMsg);+ // showAlertDialog(errMsg);reject(errMsg);}});@@ -828,7 +829,7 @@ export default class CordovaIO {filePath: string,content: string,overWrite: boolean- ): Promise<*> => {+ ): Promise<any> => {console.log('Saving TEXT file: ' + filePath);// Handling the UTF8 support for text files/* var UTF8_BOM = "\ufeff";@@ -857,7 +858,7 @@ export default class CordovaIO {/*** Creates a directory*/- createDirectoryPromise = (dirPath: string): Promise<*> => {+ createDirectoryPromise = (dirPath: string): Promise<any> => {console.log('Creating directory: ' + dirPath);return new Promise((resolve, reject) => {dirPath = this.normalizePath(dirPath);@@ -885,7 +886,7 @@ export default class CordovaIO {/*** Copies a given file to a specified location*/- copyFilePromise = (filePath: string, newFilePath: string): Promise<*> =>+ copyFilePromise = (filePath: string, newFilePath: string): Promise<any> =>new Promise((resolve, reject) => {// eslint-disable-next-line no-param-reassignfilePath = this.normalizePath(filePath);@@ -946,7 +947,7 @@ export default class CordovaIO {/*** Renames a given file*/- renameFilePromise = (filePath: string, newFilePath: string): Promise<*> =>+ renameFilePromise = (filePath: string, newFilePath: string): Promise<any> =>new Promise((resolve, reject) => {// eslint-disable-next-line no-param-reassignfilePath = this.normalizePath(filePath);@@ -1011,7 +1012,7 @@ export default class CordovaIO {/*** Rename a directory*/- renameDirectoryPromise = (dirPath: string, newDirName: string): Promise<*> =>+ renameDirectoryPromise = (dirPath: string, newDirName: string): Promise<any> =>new Promise((resolve, reject) => {let newDirPath =extractParentDirectoryPath(dirPath) +@@ -1076,7 +1077,7 @@ export default class CordovaIO {/*** Delete a specified file*/- deleteFilePromise = (filePath: string): Promise<*> =>+ deleteFilePromise = (filePath: string): Promise<any> =>new Promise((resolve, reject) => {const path = this.normalizePath(filePath);this.fsRoot.getFile(@@ -1105,7 +1106,7 @@ export default class CordovaIO {/*** Delete a specified directory, the directory should be empty, if the trash can functionality is not enabled*/- deleteDirectoryPromise = (dirPath: string): Promise<*> => {+ deleteDirectoryPromise = (dirPath: string): Promise<any> => {console.log('Deleting directory: ' + dirPath);return new Promise((resolve, reject) => {const path = this.normalizePath(dirPath);diff --git a/app/services/onlineListener.ts b/app/services/onlineListener.tsindex 13a73d3ca..b814ac76e 100644--- a/app/services/onlineListener.ts+++ b/app/services/onlineListener.ts@@ -18,16 +18,16 @@import { actions as CommonActions } from '../reducers/app';-export default (dispatch: any => void) => {- window.addEventListener('online', updateOnlineStatus);- window.addEventListener('offline', updateOnlineStatus);+export default (dispatch: any) => {+ window.addEventListener('online', updateOnlineStatus);+ window.addEventListener('offline', updateOnlineStatus);- function updateOnlineStatus(event) {- console.log('Online status: ' + event.type);- if (navigator.onLine) {- dispatch(CommonActions.goOnline());- } else {- dispatch(CommonActions.goOffline());- }- }+ function updateOnlineStatus(event) {+ console.log('Online status: ' + event.type);+ if (navigator.onLine) {+ dispatch(CommonActions.goOnline());+ } else {+ dispatch(CommonActions.goOffline());+ }+ }};diff --git a/app/services/utils-io.ts b/app/services/utils-io.tsindex b3fb60d5d..c3318ee32 100644--- a/app/services/utils-io.ts+++ b/app/services/utils-io.ts@@ -33,7 +33,7 @@ import {import versionMeta from '../version.json';import { Tag } from '../reducers/taglibrary';-export type FileSystemEntry = {+export interface FileSystemEntry {uuid: string;name: string;isFile: boolean;@@ -46,9 +46,10 @@ export type FileSystemEntry = {size: number;lmdt: number;path: string;-};+ meta?: FileSystemEntryMeta;+}-export type FileSystemEntryMeta = {+export interface FileSystemEntryMeta {description: string;tags: Array<Tag>;color?: string;@@ -56,7 +57,7 @@ export type FileSystemEntryMeta = {appName: string;appVersionUpdated: string;lastUpdated: string;-};+}export function enhanceEntry(entry: any): FileSystemEntry {let fileNameTags = [];diff --git a/app/services/webdav-io.ts b/app/services/webdav-io.tsindex fe533ea13..ba6fdd3ac 100644--- a/app/services/webdav-io.ts+++ b/app/services/webdav-io.ts@@ -18,273 +18,273 @@import nl from 'js-webdav-client';import {- extractParentDirectoryPath,- normalizePath,- getMetaFileLocationForDir+ extractParentDirectoryPath,+ normalizePath,+ getMetaFileLocationForDir} from '../utils/paths';import AppConfig from '../config';export default class WebDAVIO {- davClient: any;-- constructor() {- console.log('Loading web.js..' + nl);- // exact copy of getAjax with timeout added- nl.sara.webdav.Client.prototype.getAjax = (- method,- url,- callback,- headers- ) => {- const /** @type XMLHttpRequest */ ajax =- typeof Components !== 'undefined' &&- typeof Components.classes !== 'undefined'- ? Components.classes[- '@mozilla.org/xmlextras/xmlhttprequest;1'- ].createInstance(Components.interfaces.nsIXMLHttpRequest)- : new XMLHttpRequest();- if (this._username !== null) {- ajax.open(method, url, true, this._username, this._password);- } else {- ajax.open(method, url, true);- }- ajax.onreadystatechange = () => {- nl.sara.webdav.Client.ajaxHandler(ajax, callback);- };-- ajax.ontimeout = () => {- ajax.readyState = 4;- ajax.ajax.status = -1;- nl.sara.webdav.Client.ajaxHandler(ajax, callback);- };-- if (headers === undefined) {- headers = {};- }- for (const header in this._headers) {- if (headers[header] === undefined) {- ajax.setRequestHeader(header, this._headers[header]);- }- }- for (const header in headers) {- ajax.setRequestHeader(header, headers[header]);- }- return ajax;- };-- console.log('Connecting webdav...');- let useHTTPS = false;- if (location.href.indexOf('https') === 0) {- useHTTPS = true;- }- this.davClient = new nl.sara.webdav.Client(- location.hostname,- useHTTPS,- location.port- );- }-- isWorkerAvailable = (): boolean => false;-- getDevicePaths = (): Object => {- const paths = {- Home: '/files/'- };- return paths;- };-- getAppDataPath = (): string =>- // TODO- 'SOMEPATH_FIX_ME';-- getUserHomePath = (): string => '/';-- getNameForPath = (entrypath: string, separator = '/') => {- let path = entrypath;- if (path.lastIndexOf(separator) === path.length - 1) {- path = path.substring(0, path.lastIndexOf(separator));- }- const encodedName = path.substring(- path.lastIndexOf(separator) + 1,- path.length- );- return decodeURI(encodedName);- };-- isDirectory = (path: string): boolean =>- // TODO find a better solution- path.lastIndexOf('/') === path.length - 1;-- checkStatusCode = (code: number): boolean => {- const status = parseInt(code / 100);- if (status === 2) {- return true;- }- return false;- };-- // TODO- handleStartParameters = (): void => {- /* let filePath = getURLParameter('open');+ davClient: any;++ constructor() {+ console.log('Loading web.js..' + nl);+ // exact copy of getAjax with timeout added+ nl.sara.webdav.Client.prototype.getAjax = (+ method,+ url,+ callback,+ headers+ ) => {+ const /** @type XMLHttpRequest */ ajax =+ typeof Components !== 'undefined' &&+ typeof Components.classes !== 'undefined'+ ? Components.classes[+ '@mozilla.org/xmlextras/xmlhttprequest;1'+ ].createInstance(Components.interfaces.nsIXMLHttpRequest)+ : new XMLHttpRequest();+ if (this._username !== null) {+ ajax.open(method, url, true, this._username, this._password);+ } else {+ ajax.open(method, url, true);+ }+ ajax.onreadystatechange = () => {+ nl.sara.webdav.Client.ajaxHandler(ajax, callback);+ };++ ajax.ontimeout = () => {+ ajax.readyState = 4;+ ajax.ajax.status = -1;+ nl.sara.webdav.Client.ajaxHandler(ajax, callback);+ };++ if (headers === undefined) {+ headers = {};+ }+ for (const header in this._headers) {+ if (headers[header] === undefined) {+ ajax.setRequestHeader(header, this._headers[header]);+ }+ }+ for (const header in headers) {+ ajax.setRequestHeader(header, headers[header]);+ }+ return ajax;+ };++ console.log('Connecting webdav...');+ let useHTTPS = false;+ if (location.href.indexOf('https') === 0) {+ useHTTPS = true;+ }+ this.davClient = new nl.sara.webdav.Client(+ location.hostname,+ useHTTPS,+ location.port+ );+ }++ isWorkerAvailable = (): boolean => false;++ getDevicePaths = (): Object => {+ const paths = {+ Home: '/files/'+ };+ return paths;+ };++ getAppDataPath = (): string =>+ // TODO+ 'SOMEPATH_FIX_ME';++ getUserHomePath = (): string => '/';++ getNameForPath = (entrypath: string, separator = '/') => {+ let path = entrypath;+ if (path.lastIndexOf(separator) === path.length - 1) {+ path = path.substring(0, path.lastIndexOf(separator));+ }+ const encodedName = path.substring(+ path.lastIndexOf(separator) + 1,+ path.length+ );+ return decodeURI(encodedName);+ };++ isDirectory = (path: string): boolean =>+ // TODO find a better solution+ path.lastIndexOf('/') === path.length - 1;++ checkStatusCode = (code: number): boolean => {+ const status = parseInt(code / 100);+ if (status === 2) {+ return true;+ }+ return false;+ };++ // TODO+ handleStartParameters = (): void => {+ /* let filePath = getURLParameter('open');if (filePath && filePath.length > 0) {filePath = decodeURIComponent(filePath);console.log('Opening file in browser: ' + filePath);FileOpener.openFileOnStartup(filePath);} */- };-- /**- * Creates recursively a tree structure for a given directory path- * @param {string} dirPath - the full path of the directory for which the tree will be generated- */- createDirectoryTree = (dirPath: string) => {- console.log('Creating directory index for: ' + dirPath);- const directoyTree = [];- return directoyTree;- };-- listMetaDirectoryPromise = async (path: string): Promise<Array<Object>> => {- const promise = new Promise(resolve => {- const entries = [];- const metaDirPath =- normalizePath(path) +- AppConfig.dirSeparator +- AppConfig.metaFolder +- AppConfig.dirSeparator;- const davSuccess = (status, data) => {- const dirList = data._responses;- for (const dir in dirList) {- const entryPath = dirList[dir].href;- if (entryPath.toLowerCase() === metaDirPath.toLowerCase()) {- console.log('Skipping current folder');- } else {- const fileName = this.getNameForPath(entryPath);-- const entry = {};- entry.name = fileName;- entry.path = decodeURI(entryPath);- entry.isFile = true;- entries.push(entry);- }- }- return resolve(entries);- };-- this.davClient.propfind(- metaDirPath,- davSuccess,- 1 // 1 , davClient.INFINITY- );- return resolve(entries);- });- const result = await promise; // this.listDirectoryPromise(normalizePath(path) + AppConfig.dirSeparator + AppConfig.metaFolder + AppConfig.dirSeparator, true);- return result;- };-- /**- * Creates a list with containing the files and the sub directories of a given directory- */- listDirectoryPromise = (- directoryPath: string,- lite: boolean = false- ): Promise<Array<Object>> =>- new Promise(async (resolve, reject) => {- let enhancedEntries;- let dirPath = directoryPath.split('//').join('/');-- const metaContent = !lite- ? await this.listMetaDirectoryPromise(directoryPath)- : [];-- // let containsMetaFolder = false;- const davSuccess = (status, data) => {- console.log('Dirlist Status: ' + status);- if (!this.checkStatusCode(status)) {- console.warn('Listing directory ' + dirPath + ' failed ' + status);- reject('Listing directory ' + dirPath + ' failed ' + status);- }- const dirList = data._responses;- let fileName;- let isDir;- let filesize;- let lmdt;- let path;- let eentry;-- enhancedEntries = [];- const metaPromises = [];- for (const entry in dirList) {- // if (Object.prototype.hasOwnProperty.call(dirList, entry)) {- path = dirList[entry].href;- if (dirPath.toLowerCase() === path.toLowerCase()) {- console.log('Skipping current folder');- } else {- isDir = false;- filesize = undefined;- lmdt = undefined;- // console.log(dirList[entry]._namespaces['DAV:']);- if (this.isFile(dirList[entry]._namespaces['DAV:'])) {- filesize =- dirList[entry]._namespaces['DAV:'].getcontentlength._xmlvalue[0]- .data;- lmdt =- data._responses[entry]._namespaces['DAV:'].getlastmodified- ._xmlvalue[0].data;- } else {- isDir = true;- // const metaFilePath = getMetaFileLocationForFile(path, '/');- }- fileName = this.getNameForPath(path);-- eentry = {};- eentry.name = fileName;- eentry.path = decodeURI(path);- eentry.tags = [];- eentry.thumbPath = isDir- ? eentry.path +- AppConfig.metaFolder +- '/' +- AppConfig.folderThumbFile- : '';- // eentry.meta = {};- eentry.isFile = !isDir;- eentry.size = filesize;- eentry.lmdt = Date.parse(lmdt);- // const x = getMetaFileLocationForFile(eentry.path);-- if (!lite) {- if (isDir) {- // Read tsm.json from subfolders- const pathMetaFile = getMetaFileLocationForDir(eentry.path);- metaPromises.push(this.getEntryMeta(eentry, pathMetaFile));- } else {- const metaFileAvailable = metaContent.find(- obj => obj.name === fileName + AppConfig.metaFileExt- );- if (metaFileAvailable) {- metaPromises.push(- this.getEntryMeta(eentry, metaFileAvailable.path)- );- }-- // Finding if file thumbnail available- const metaThumbAvailable = metaContent.find(- obj => obj.name === fileName + AppConfig.thumbFileExt- );- if (metaThumbAvailable) {- eentry.thumbPath = metaThumbAvailable.path;- }- }- }-- enhancedEntries.push(eentry);- // }- }- }-- Promise.all(metaPromises)- .then(entriesMeta => {- /* entriesMeta.forEach((entryMeta) => {+ };++ /**+ * Creates recursively a tree structure for a given directory path+ * @param {string} dirPath - the full path of the directory for which the tree will be generated+ */+ createDirectoryTree = (dirPath: string) => {+ console.log('Creating directory index for: ' + dirPath);+ const directoyTree = [];+ return directoyTree;+ };++ listMetaDirectoryPromise = async (path: string): Promise<Array<any>> => {+ const promise = new Promise(resolve => {+ const entries = [];+ const metaDirPath =+ normalizePath(path) ++ AppConfig.dirSeparator ++ AppConfig.metaFolder ++ AppConfig.dirSeparator;+ const davSuccess = (status, data) => {+ const dirList = data._responses;+ for (const dir in dirList) {+ const entryPath = dirList[dir].href;+ if (entryPath.toLowerCase() === metaDirPath.toLowerCase()) {+ console.log('Skipping current folder');+ } else {+ const fileName = this.getNameForPath(entryPath);++ const entry = {};+ entry.name = fileName;+ entry.path = decodeURI(entryPath);+ entry.isFile = true;+ entries.push(entry);+ }+ }+ return resolve(entries);+ };++ this.davClient.propfind(+ metaDirPath,+ davSuccess,+ 1 // 1 , davClient.INFINITY+ );+ return resolve(entries);+ });+ const result = await promise; // this.listDirectoryPromise(normalizePath(path) + AppConfig.dirSeparator + AppConfig.metaFolder + AppConfig.dirSeparator, true);+ return result;+ };++ /**+ * Creates a list with containing the files and the sub directories of a given directory+ */+ listDirectoryPromise = (+ directoryPath: string,+ lite: boolean = false+ ): Promise<Array<Object>> =>+ new Promise(async (resolve, reject) => {+ let enhancedEntries;+ let dirPath = directoryPath.split('//').join('/');++ const metaContent = !lite+ ? await this.listMetaDirectoryPromise(directoryPath)+ : [];++ // let containsMetaFolder = false;+ const davSuccess = (status, data) => {+ console.log('Dirlist Status: ' + status);+ if (!this.checkStatusCode(status)) {+ console.warn('Listing directory ' + dirPath + ' failed ' + status);+ reject('Listing directory ' + dirPath + ' failed ' + status);+ }+ const dirList = data._responses;+ let fileName;+ let isDir;+ let filesize;+ let lmdt;+ let path;+ let eentry;++ enhancedEntries = [];+ const metaPromises = [];+ for (const entry in dirList) {+ // if (Object.prototype.hasOwnProperty.call(dirList, entry)) {+ path = dirList[entry].href;+ if (dirPath.toLowerCase() === path.toLowerCase()) {+ console.log('Skipping current folder');+ } else {+ isDir = false;+ filesize = undefined;+ lmdt = undefined;+ // console.log(dirList[entry]._namespaces['DAV:']);+ if (this.isFile(dirList[entry]._namespaces['DAV:'])) {+ filesize =+ dirList[entry]._namespaces['DAV:'].getcontentlength._xmlvalue[0]+ .data;+ lmdt =+ data._responses[entry]._namespaces['DAV:'].getlastmodified+ ._xmlvalue[0].data;+ } else {+ isDir = true;+ // const metaFilePath = getMetaFileLocationForFile(path, '/');+ }+ fileName = this.getNameForPath(path);++ eentry = {};+ eentry.name = fileName;+ eentry.path = decodeURI(path);+ eentry.tags = [];+ eentry.thumbPath = isDir+ ? eentry.path ++ AppConfig.metaFolder ++ '/' ++ AppConfig.folderThumbFile+ : '';+ // eentry.meta = {};+ eentry.isFile = !isDir;+ eentry.size = filesize;+ eentry.lmdt = Date.parse(lmdt);+ // const x = getMetaFileLocationForFile(eentry.path);++ if (!lite) {+ if (isDir) {+ // Read tsm.json from subfolders+ const pathMetaFile = getMetaFileLocationForDir(eentry.path);+ metaPromises.push(this.getEntryMeta(eentry, pathMetaFile));+ } else {+ const metaFileAvailable = metaContent.find(+ obj => obj.name === fileName + AppConfig.metaFileExt+ );+ if (metaFileAvailable) {+ metaPromises.push(+ this.getEntryMeta(eentry, metaFileAvailable.path)+ );+ }++ // Finding if file thumbnail available+ const metaThumbAvailable = metaContent.find(+ obj => obj.name === fileName + AppConfig.thumbFileExt+ );+ if (metaThumbAvailable) {+ eentry.thumbPath = metaThumbAvailable.path;+ }+ }+ }++ enhancedEntries.push(eentry);+ // }+ }+ }++ Promise.all(metaPromises)+ .then(entriesMeta => {+ /* entriesMeta.forEach((entryMeta) => {enhancedEntries.some((enhancedEntry) => {if (enhancedEntry.path === entryMeta.path) {// eslint-disable-next-line no-param-reassign@@ -294,430 +294,430 @@ export default class WebDAVIO {return false;});}); */- resolve(enhancedEntries);- return true;- })- .catch(() => {- resolve(enhancedEntries);- });- };- if (dirPath.substring(dirPath.length - 1) !== '/') {- dirPath += '/';- }- dirPath = encodeURI(dirPath);-- this.davClient.propfind(- dirPath,- davSuccess,- 1 // 1 , davClient.INFINITY- );- });-- isFile = (dav: Object): boolean =>- !(- typeof dav.getcontentlength === 'undefined' ||- dav.getcontentlength._xmlvalue.length === 0 ||- (dav.resourcetype._xmlvalue.length === 1 &&- dav.resourcetype._xmlvalue[0].localName === 'collection')- );-- getEntryMeta = (eentry: Object, metaPath: string): Promise<Object> => {- return new Promise(resolve => {- if (eentry.isFile) {- this.loadTextFilePromise(metaPath)- .then(result => {- // eslint-disable-next-line no-param-reassign- eentry.meta = JSON.parse(result.trim());- return resolve(eentry);- // resolve({- // ...eentry,- // meta: JSON.parse(result.trim())- // });- })- .catch(err => {- console.log(- 'No meta file for folder found: ' + eentry.path + ' - ' + err- );- resolve(eentry);- });- } else if (!eentry.path.endsWith(AppConfig.metaFolder + '/')) {- // Skip the /.ts folder- this.loadTextFilePromise(metaPath)- .then(result => {- // eslint-disable-next-line no-param-reassign- eentry.meta = JSON.parse(result.trim());- return resolve(eentry);- // resolve({- // ...eentry,- // meta: JSON.parse(result.trim())- // });- })- .catch(err => {- console.log(- 'No meta file for folder found: ' + eentry.path + ' - ' + err- );- resolve(eentry);- });- }- resolve(eentry);- });- };-- /**- * Finds out the properties of a file or directory such last modification date or file size- */- getPropertiesPromise = (filePath: string): Promise<Object> =>- new Promise((resolve, reject) => {- this.davClient.propfind(- encodeURI(filePath),- (status, data) => {- console.log(- 'Properties Status / Content: ' +- status +- ' / ' +- JSON.stringify(data._responses)- );- const fileProperties = {};- if (this.checkStatusCode(status)) {- for (const entry in data._responses) {- fileProperties.path = filePath;- fileProperties.name = this.getNameForPath(filePath);- const isFile = this.isFile(- data._responses[entry]._namespaces['DAV:']- );- fileProperties.isFile = isFile;- if (isFile) {- fileProperties.size =- data._responses[entry]._namespaces[- 'DAV:'- ].getcontentlength._xmlvalue[0].data;- fileProperties.lmdt = Date.parse(- data._responses[entry]._namespaces['DAV:'].getlastmodified- ._xmlvalue[0].data- );- }- }- resolve(fileProperties);- } else {- resolve(false);- // reject('getFileProperties ' + filePath + ' failed ' + status);- }- },- 1- );- });-- /**- * Load the content of a text file- */- loadTextFilePromise = (filePath: string) =>- this.getFileContentPromise(filePath, 'text');-- /**- * Gets the content of file, useful for binary files- */- getFileContentPromise = (filePath: string, type): Promise<Object> => {- console.log('getFileContent file: ' + filePath);- return new Promise((resolve, reject) => {- const ajax = this.davClient.getAjax('GET', encodeURI(filePath));- ajax.onreadystatechange = null;- ajax.responseType = type || 'arraybuffer';- ajax.onerror = reject;-- ajax.onload = () => {- const response = ajax.response || ajax.responseText;- if (this.checkStatusCode(ajax.status)) {- resolve(response);- } else {- reject('getFileContentPromise ajax error');- }- };- ajax.send();- });- };-- /**- * Persists a given content(binary supported) to a specified filepath- */- saveFilePromise = (- filePath: string,- content: string,- overWrite: boolean,- mode: string- ): Promise<Object> =>- new Promise((resolve, reject) => {- let isNewFile = false;- this.davClient.propfind(- encodeURI(filePath),- (status, data) => {- console.log(- 'Check file exists: Status / Content: ' + status + ' / ' + data- );- if (parseInt(status) === 404) {- isNewFile = true;- }- if (isNewFile || overWrite === true || mode === 'text') {- this.davClient.put(- encodeURI(filePath),- (status, data, headers) => {- console.log(- 'Creating File Status/Content/Headers: ' +- status +- ' / ' +- data +- ' / ' +- headers- );- if (this.checkStatusCode(status)) {- resolve(isNewFile);- } else {- reject('saveFilePromise: ' + filePath + ' failed ' + status);- }- },- content,- 'application/octet-stream'- );- } else {- reject('File Already Exists.');- }- },- 1- );- });-- /**- * Persists a given text content to a specified filepath- */- saveTextFilePromise(- filePath: string,- content: string,- overWrite: boolean- ): Promise<Object> {- console.log('Saving text file: ' + filePath);- return this.saveFilePromise(filePath, content, overWrite, 'text');- }-- /**- * Persists a given binary content to a specified filepath- */- saveBinaryFilePromise(- filePath: string,- content: string,- overWrite: boolean- ): Promise<Object> {- console.log('Saving binary file: ' + filePath);- return this.saveFilePromise(filePath, content, overWrite);- }-- /**- * Creates a directory- */- createDirectoryPromise = (dirPath: string): Promise<Object> => {- console.log('Creating directory: ' + dirPath);- return new Promise((resolve, reject) => {- this.davClient.mkcol(encodeURI(dirPath), (status, data, headers) => {- console.log(- 'Directory Creation Status/Content/Headers: ' +- status +- ' / ' +- data +- ' / ' +- headers- );- if (this.checkStatusCode(status)) {- resolve(dirPath);- } else {- reject('createDirectory ' + dirPath + ' failed ' + status);- }- });- });- };-- /**- * Copies a given file to a specified location- */- copyFilePromise = (- filePath: string,- newFilePath: string- ): Promise<Object> => {- console.log('Copying file: ' + filePath + ' to ' + newFilePath);- return new Promise((resolve, reject) => {- if (filePath.toLowerCase() === newFilePath.toLowerCase()) {- reject('Copying file failed, files have the same path');- } else {- this.davClient.copy(- encodeURI(filePath),- (status, data, headers) => {- console.log(- 'Copy File Status/Content/Headers: ' +- status +- ' / ' +- data +- ' / ' +- headers- );- if (this.checkStatusCode(status)) {- resolve(filePath, newFilePath);- } else {- reject('copyFile ' + filePath + ' failed ' + status);- }- },- encodeURI(newFilePath),- this.davClient.FAIL_ON_OVERWRITE- );- }- });- };-- /**- * Renames a given file- */- renameFilePromise = (- filePath: string,- newFilePath: string- ): Promise<Object> => {- console.log('Renaming file: ' + filePath + ' to ' + newFilePath);- return new Promise((resolve, reject) => {- if (filePath === newFilePath) {- reject('Renaming file failed, files have the same path');- } else {- this.davClient.move(- encodeURI(filePath),- (status, data, headers) => {- console.log(- 'Rename File Status/Content/Headers: ' +- status +- ' / ' +- data +- ' / ' +- headers- );- if (this.checkStatusCode(status)) {- resolve([filePath, newFilePath]);- } else {- reject('rename: ' + filePath + ' failed ' + status);- }- },- encodeURI(newFilePath),- this.davClient.FAIL_ON_OVERWRITE- );- }- });- };-- /**- * Rename a directory- */- renameDirectoryPromise = (- dirPath: string,- newDirectoryPath: string- ): Promise<Object> => {- const newDirPath =- extractParentDirectoryPath(dirPath) + '/' + newDirectoryPath;- console.log('Renaming directory: ' + dirPath + ' to ' + newDirPath);- return new Promise((resolve, reject) => {- if (dirPath === newDirPath) {- reject('Renaming directory failed, directories have the same path');- } else {- this.davClient.move(- encodeURI(dirPath),- (status, data, headers) => {- console.log(- 'Rename Directory Status/Content/Headers: ' +- status +- ' / ' +- data +- ' / ' +- headers- );- if (this.checkStatusCode(status)) {- resolve(newDirPath);- } else {- reject('rename: ' + dirPath + ' failed ' + status);- }- },- encodeURI(newDirPath),- this.davClient.FAIL_ON_OVERWRITE- );- }- });- };-- /**- * Delete a specified file- */- deleteFilePromise = (path: string): Promise<Object> =>- this.deleteDirectoryPromise(path);-- /**- * Delete a specified directory, the directory should be empty, if the trash can functionality is not enabled- */- deleteDirectoryPromise = (path: string): Promise<Object> =>- new Promise((resolve, reject) => {- this.davClient.remove(encodeURI(path), (status, data, headers) => {- console.log(- 'Directory/File Deletion Status/Content/Headers: ' +- status +- ' / ' +- data +- ' / ' +- headers- );- if (this.checkStatusCode(status)) {- resolve(path);- } else {- reject('delete ' + path + ' failed ' + status);- }- });- });-- /**- * Choosing directory- */- selectDirectoryDialog = () => {- console.log('Selecting directory is not implemented in the web version');- };-- /**- * Choosing file- */- selectFileDialog = () => {- console.log('Selecting file not relevant for the web version');- };-- /**- * Opens directory in new tab / window- */- openDirectory = (dirPath: string) => {- console.log(- 'Opening directory ' + dirPath + ' not possible for the web version.'- );- };-- /**- * Opens directory in new tab / window, selecting the file- */- showInFileManager = (filePath: string) => {- console.log(- 'Showing item ' + filePath + ' not possible for the web version.'- );- };-- /**- * Open the file url in a new tab / window- */- openFile = (filePath: string): void => {- window.open(filePath, '_blank');- };-- openUrl = (url: string): void => {- window.open(url, '_blank');- };-- /**- * Places the application window on top of the other windows- */- focusWindow = (): void => {- window.focus();- };+ resolve(enhancedEntries);+ return true;+ })+ .catch(() => {+ resolve(enhancedEntries);+ });+ };+ if (dirPath.substring(dirPath.length - 1) !== '/') {+ dirPath += '/';+ }+ dirPath = encodeURI(dirPath);++ this.davClient.propfind(+ dirPath,+ davSuccess,+ 1 // 1 , davClient.INFINITY+ );+ });++ isFile = (dav: Object): boolean =>+ !(+ typeof dav.getcontentlength === 'undefined' ||+ dav.getcontentlength._xmlvalue.length === 0 ||+ (dav.resourcetype._xmlvalue.length === 1 &&+ dav.resourcetype._xmlvalue[0].localName === 'collection')+ );++ getEntryMeta = (eentry: Object, metaPath: string): Promise<Object> => {+ return new Promise(resolve => {+ if (eentry.isFile) {+ this.loadTextFilePromise(metaPath)+ .then(result => {+ // eslint-disable-next-line no-param-reassign+ eentry.meta = JSON.parse(result.trim());+ return resolve(eentry);+ // resolve({+ // ...eentry,+ // meta: JSON.parse(result.trim())+ // });+ })+ .catch(err => {+ console.log(+ 'No meta file for folder found: ' + eentry.path + ' - ' + err+ );+ resolve(eentry);+ });+ } else if (!eentry.path.endsWith(AppConfig.metaFolder + '/')) {+ // Skip the /.ts folder+ this.loadTextFilePromise(metaPath)+ .then(result => {+ // eslint-disable-next-line no-param-reassign+ eentry.meta = JSON.parse(result.trim());+ return resolve(eentry);+ // resolve({+ // ...eentry,+ // meta: JSON.parse(result.trim())+ // });+ })+ .catch(err => {+ console.log(+ 'No meta file for folder found: ' + eentry.path + ' - ' + err+ );+ resolve(eentry);+ });+ }+ resolve(eentry);+ });+ };++ /**+ * Finds out the properties of a file or directory such last modification date or file size+ */+ getPropertiesPromise = (filePath: string): Promise<Object> =>+ new Promise((resolve, reject) => {+ this.davClient.propfind(+ encodeURI(filePath),+ (status, data) => {+ console.log(+ 'Properties Status / Content: ' ++ status ++ ' / ' ++ JSON.stringify(data._responses)+ );+ const fileProperties = {};+ if (this.checkStatusCode(status)) {+ for (const entry in data._responses) {+ fileProperties.path = filePath;+ fileProperties.name = this.getNameForPath(filePath);+ const isFile = this.isFile(+ data._responses[entry]._namespaces['DAV:']+ );+ fileProperties.isFile = isFile;+ if (isFile) {+ fileProperties.size =+ data._responses[entry]._namespaces[+ 'DAV:'+ ].getcontentlength._xmlvalue[0].data;+ fileProperties.lmdt = Date.parse(+ data._responses[entry]._namespaces['DAV:'].getlastmodified+ ._xmlvalue[0].data+ );+ }+ }+ resolve(fileProperties);+ } else {+ resolve(false);+ // reject('getFileProperties ' + filePath + ' failed ' + status);+ }+ },+ 1+ );+ });++ /**+ * Load the content of a text file+ */+ loadTextFilePromise = (filePath: string) =>+ this.getFileContentPromise(filePath, 'text');++ /**+ * Gets the content of file, useful for binary files+ */+ getFileContentPromise = (filePath: string, type): Promise<Object> => {+ console.log('getFileContent file: ' + filePath);+ return new Promise((resolve, reject) => {+ const ajax = this.davClient.getAjax('GET', encodeURI(filePath));+ ajax.onreadystatechange = null;+ ajax.responseType = type || 'arraybuffer';+ ajax.onerror = reject;++ ajax.onload = () => {+ const response = ajax.response || ajax.responseText;+ if (this.checkStatusCode(ajax.status)) {+ resolve(response);+ } else {+ reject('getFileContentPromise ajax error');+ }+ };+ ajax.send();+ });+ };++ /**+ * Persists a given content(binary supported) to a specified filepath+ */+ saveFilePromise = (+ filePath: string,+ content: string,+ overWrite: boolean,+ mode: string+ ): Promise<Object> =>+ new Promise((resolve, reject) => {+ let isNewFile = false;+ this.davClient.propfind(+ encodeURI(filePath),+ (status, data) => {+ console.log(+ 'Check file exists: Status / Content: ' + status + ' / ' + data+ );+ if (parseInt(status) === 404) {+ isNewFile = true;+ }+ if (isNewFile || overWrite === true || mode === 'text') {+ this.davClient.put(+ encodeURI(filePath),+ (status, data, headers) => {+ console.log(+ 'Creating File Status/Content/Headers: ' ++ status ++ ' / ' ++ data ++ ' / ' ++ headers+ );+ if (this.checkStatusCode(status)) {+ resolve(isNewFile);+ } else {+ reject('saveFilePromise: ' + filePath + ' failed ' + status);+ }+ },+ content,+ 'application/octet-stream'+ );+ } else {+ reject('File Already Exists.');+ }+ },+ 1+ );+ });++ /**+ * Persists a given text content to a specified filepath+ */+ saveTextFilePromise(+ filePath: string,+ content: string,+ overWrite: boolean+ ): Promise<Object> {+ console.log('Saving text file: ' + filePath);+ return this.saveFilePromise(filePath, content, overWrite, 'text');+ }++ /**+ * Persists a given binary content to a specified filepath+ */+ saveBinaryFilePromise(+ filePath: string,+ content: string,+ overWrite: boolean+ ): Promise<Object> {+ console.log('Saving binary file: ' + filePath);+ return this.saveFilePromise(filePath, content, overWrite);+ }++ /**+ * Creates a directory+ */+ createDirectoryPromise = (dirPath: string): Promise<Object> => {+ console.log('Creating directory: ' + dirPath);+ return new Promise((resolve, reject) => {+ this.davClient.mkcol(encodeURI(dirPath), (status, data, headers) => {+ console.log(+ 'Directory Creation Status/Content/Headers: ' ++ status ++ ' / ' ++ data ++ ' / ' ++ headers+ );+ if (this.checkStatusCode(status)) {+ resolve(dirPath);+ } else {+ reject('createDirectory ' + dirPath + ' failed ' + status);+ }+ });+ });+ };++ /**+ * Copies a given file to a specified location+ */+ copyFilePromise = (+ filePath: string,+ newFilePath: string+ ): Promise<Object> => {+ console.log('Copying file: ' + filePath + ' to ' + newFilePath);+ return new Promise((resolve, reject) => {+ if (filePath.toLowerCase() === newFilePath.toLowerCase()) {+ reject('Copying file failed, files have the same path');+ } else {+ this.davClient.copy(+ encodeURI(filePath),+ (status, data, headers) => {+ console.log(+ 'Copy File Status/Content/Headers: ' ++ status ++ ' / ' ++ data ++ ' / ' ++ headers+ );+ if (this.checkStatusCode(status)) {+ resolve(filePath, newFilePath);+ } else {+ reject('copyFile ' + filePath + ' failed ' + status);+ }+ },+ encodeURI(newFilePath),+ this.davClient.FAIL_ON_OVERWRITE+ );+ }+ });+ };++ /**+ * Renames a given file+ */+ renameFilePromise = (+ filePath: string,+ newFilePath: string+ ): Promise<Object> => {+ console.log('Renaming file: ' + filePath + ' to ' + newFilePath);+ return new Promise((resolve, reject) => {+ if (filePath === newFilePath) {+ reject('Renaming file failed, files have the same path');+ } else {+ this.davClient.move(+ encodeURI(filePath),+ (status, data, headers) => {+ console.log(+ 'Rename File Status/Content/Headers: ' ++ status ++ ' / ' ++ data ++ ' / ' ++ headers+ );+ if (this.checkStatusCode(status)) {+ resolve([filePath, newFilePath]);+ } else {+ reject('rename: ' + filePath + ' failed ' + status);+ }+ },+ encodeURI(newFilePath),+ this.davClient.FAIL_ON_OVERWRITE+ );+ }+ });+ };++ /**+ * Rename a directory+ */+ renameDirectoryPromise = (+ dirPath: string,+ newDirectoryPath: string+ ): Promise<Object> => {+ const newDirPath =+ extractParentDirectoryPath(dirPath) + '/' + newDirectoryPath;+ console.log('Renaming directory: ' + dirPath + ' to ' + newDirPath);+ return new Promise((resolve, reject) => {+ if (dirPath === newDirPath) {+ reject('Renaming directory failed, directories have the same path');+ } else {+ this.davClient.move(+ encodeURI(dirPath),+ (status, data, headers) => {+ console.log(+ 'Rename Directory Status/Content/Headers: ' ++ status ++ ' / ' ++ data ++ ' / ' ++ headers+ );+ if (this.checkStatusCode(status)) {+ resolve(newDirPath);+ } else {+ reject('rename: ' + dirPath + ' failed ' + status);+ }+ },+ encodeURI(newDirPath),+ this.davClient.FAIL_ON_OVERWRITE+ );+ }+ });+ };++ /**+ * Delete a specified file+ */+ deleteFilePromise = (path: string): Promise<Object> =>+ this.deleteDirectoryPromise(path);++ /**+ * Delete a specified directory, the directory should be empty, if the trash can functionality is not enabled+ */+ deleteDirectoryPromise = (path: string): Promise<Object> =>+ new Promise((resolve, reject) => {+ this.davClient.remove(encodeURI(path), (status, data, headers) => {+ console.log(+ 'Directory/File Deletion Status/Content/Headers: ' ++ status ++ ' / ' ++ data ++ ' / ' ++ headers+ );+ if (this.checkStatusCode(status)) {+ resolve(path);+ } else {+ reject('delete ' + path + ' failed ' + status);+ }+ });+ });++ /**+ * Choosing directory+ */+ selectDirectoryDialog = () => {+ console.log('Selecting directory is not implemented in the web version');+ };++ /**+ * Choosing file+ */+ selectFileDialog = () => {+ console.log('Selecting file not relevant for the web version');+ };++ /**+ * Opens directory in new tab / window+ */+ openDirectory = (dirPath: string) => {+ console.log(+ 'Opening directory ' + dirPath + ' not possible for the web version.'+ );+ };++ /**+ * Opens directory in new tab / window, selecting the file+ */+ showInFileManager = (filePath: string) => {+ console.log(+ 'Showing item ' + filePath + ' not possible for the web version.'+ );+ };++ /**+ * Open the file url in a new tab / window+ */+ openFile = (filePath: string): void => {+ window.open(filePath, '_blank');+ };++ openUrl = (url: string): void => {+ window.open(url, '_blank');+ };++ /**+ * Places the application window on top of the other windows+ */+ focusWindow = (): void => {+ window.focus();+ };}diff --git a/app/utils/misc.ts b/app/utils/misc.tsindex 478509af5..421c4ed97 100644--- a/app/utils/misc.ts+++ b/app/utils/misc.ts@@ -18,75 +18,75 @@/** Returns true is a string is plus code e.g. 8FWH4HVG+3V 8FWH4HVG+ 8FWH4H+ */export function isPlusCode(plusCode: string): boolean {- if (!plusCode) {- return false;- }- const upperCasedPlusCode = plusCode.toUpperCase(); // needed only lowercased index- return /(^|\s)([23456789C][23456789CFGHJMPQRV][23456789CFGHJMPQRVWX]{6}\+[23456789CFGHJMPQRVWX]{2,3})(\s|$)/.test(- upperCasedPlusCode- );+ if (!plusCode) {+ return false;+ }+ const upperCasedPlusCode = plusCode.toUpperCase(); // needed only lowercased index+ return /(^|\s)([23456789C][23456789CFGHJMPQRV][23456789CFGHJMPQRVWX]{6}\+[23456789CFGHJMPQRVWX]{2,3})(\s|$)/.test(+ upperCasedPlusCode+ );}export function parseLatLon(- latLongInput: string-): { lat: number, lon: number } | false {- const cleanedInput = latLongInput.replace(/\s+/g, ''); // cleaning spaces- if (- !/^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/.test(- cleanedInput- )- ) {- return false;- }- const latLongArray = cleanedInput.split(',');- const lat = parseFloat(latLongArray[0]);- const lon = parseFloat(latLongArray[1]);- if (!isNaN(lat) && !isNaN(lon)) {- return {- lat,- lon- };- }- return false;+ latLongInput: string+): { lat: number; lon: number } | false {+ const cleanedInput = latLongInput.replace(/\s+/g, ''); // cleaning spaces+ if (+ !/^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$/.test(+ cleanedInput+ )+ ) {+ return false;+ }+ const latLongArray = cleanedInput.split(',');+ const lat = parseFloat(latLongArray[0]);+ const lon = parseFloat(latLongArray[1]);+ if (!isNaN(lat) && !isNaN(lon)) {+ return {+ lat,+ lon+ };+ }+ return false;}export function traverse(objArr: Array<Object>, func: any) {- objArr.forEach(obj => {- Object.keys(obj).map(objKey => {- func.apply(this, [obj, objKey]);- if (objKey === 'subPages' && typeof Array.isArray(obj[objKey])) {- traverse(obj[objKey], func);- }- return true;- });- });+ objArr.forEach(obj => {+ Object.keys(obj).map(objKey => {+ func.apply(this, [obj, objKey]);+ if (objKey === 'subPages' && typeof Array.isArray(obj[objKey])) {+ traverse(obj[objKey], func);+ }+ return true;+ });+ });}export function immutablySwapItems(- items: any,- firstIndex: number,- secondIndex: number+ items: any,+ firstIndex: number,+ secondIndex: number) {- const results = items.slice();- const firstItem = items[firstIndex];- results[firstIndex] = items[secondIndex];- results[secondIndex] = firstItem;- return results;+ const results = items.slice();+ const firstItem = items[firstIndex];+ results[firstIndex] = items[secondIndex];+ results[secondIndex] = firstItem;+ return results;}export function hasURLProtocol(url: string) {- return (- url.startsWith('http://') ||- url.startsWith('https://') ||- url.startsWith('file://') ||- url.startsWith('data:')- );+ return (+ url.startsWith('http://') ||+ url.startsWith('https://') ||+ url.startsWith('file://') ||+ url.startsWith('data:')+ );}export function arrayBufferToDataURL(arrayBuffer: any, mime: string) {- const blob = new Blob([arrayBuffer], { type: mime });- const url = window.URL || window.webkitURL;- return url.createObjectURL(blob);+ const blob = new Blob([arrayBuffer], { type: mime });+ const url = window.URL || window.webkitURL;+ return url.createObjectURL(blob);}/**@@ -99,359 +99,359 @@ export function arrayBufferToDataURL(arrayBuffer: any, mime: string) {* @returns {Blob}*/export function b64toBlob(- b64Data: any,- contentType: string = '',- sliceSize: number = 512+ b64Data: any,+ contentType: string = '',+ sliceSize: number = 512) {- const byteCharacters = atob(b64Data);- const byteArrays = [];-- for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {- const slice = byteCharacters.slice(offset, offset + sliceSize);- const byteNumbers = new Array(slice.length);- for (let i = 0; i < slice.length; i += 1) {- byteNumbers[i] = slice.charCodeAt(i);- }- const byteArray = new Uint8Array(byteNumbers);- byteArrays.push(byteArray);- }- const blob = new Blob(byteArrays, { type: contentType });- return blob;+ const byteCharacters = atob(b64Data);+ const byteArrays = [];++ for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {+ const slice = byteCharacters.slice(offset, offset + sliceSize);+ const byteNumbers = new Array(slice.length);+ for (let i = 0; i < slice.length; i += 1) {+ byteNumbers[i] = slice.charCodeAt(i);+ }+ const byteArray = new Uint8Array(byteNumbers);+ byteArrays.push(byteArray);+ }+ const blob = new Blob(byteArrays, { type: contentType });+ return blob;}export function getRandomInt(min: number, max: number) {- return Math.floor(Math.random() * (max - min + 1)) + min;+ return Math.floor(Math.random() * (max - min + 1)) + min;}-export function isVisibleOnScreen(element: Object) {- const rectangle = element.getBoundingClientRect();- const isVisible =- rectangle.top >= 0 &&- rectangle.left >= 0 &&- rectangle.bottom <=- (window.innerHeight || document.documentElement.clientHeight) &&- rectangle.right <=- (window.innerWidth || document.documentElement.clientWidth);- return isVisible;+export function isVisibleOnScreen(element: any) {+ const rectangle = element.getBoundingClientRect();+ const isVisible =+ rectangle.top >= 0 &&+ rectangle.left >= 0 &&+ rectangle.bottom <=+ (window.innerHeight || document.documentElement.clientHeight) &&+ rectangle.right <=+ (window.innerWidth || document.documentElement.clientWidth);+ return isVisible;}export function getURLParameter(variable: string) {- const query = window.location.search.substring(1);- const vars = query.split('&');- for (let i = 0; i < vars.length; i += 1) {- const pair = vars[i].split('=');- if (pair[0] === variable) {- return pair[1];- }- }- return false;+ const query = window.location.search.substring(1);+ const vars = query.split('&');+ for (let i = 0; i < vars.length; i += 1) {+ const pair = vars[i].split('=');+ if (pair[0] === variable) {+ return pair[1];+ }+ }+ return false;}export function dataURLtoBlob(dataURI) {- const arr = dataURI.split(',');- const mime = arr[0].match(/:(.*?);/)[1];- const arrBuff = base64ToArrayBuffer(arr[1]);- return new window.Blob([arrBuff], { type: mime });+ const arr = dataURI.split(',');+ const mime = arr[0].match(/:(.*?);/)[1];+ const arrBuff = base64ToArrayBuffer(arr[1]);+ return new window.Blob([arrBuff], { type: mime });}export function base64ToArrayBuffer(base64) {- const bstr = window.atob(base64);- const bytes = new Uint8Array(bstr.length);- for (let i = 0; i < bstr.length; i += 1) {- bytes[i] = bstr.charCodeAt(i);- }- return bytes.buffer;+ const bstr = window.atob(base64);+ const bytes = new Uint8Array(bstr.length);+ for (let i = 0; i < bstr.length; i += 1) {+ bytes[i] = bstr.charCodeAt(i);+ }+ return bytes.buffer;}export function arrayBufferToBuffer(content: any) {- const buffer = new Buffer(content.byteLength);- const view = new Uint8Array(content);- for (let i = 0; i < buffer.length; ++i) {- buffer[i] = view[i];- }- return buffer;+ const buffer = new Buffer(content.byteLength);+ const view = new Uint8Array(content);+ for (let i = 0; i < buffer.length; ++i) {+ buffer[i] = view[i];+ }+ return buffer;}export function getBase64Image(imgURL: string) {- const canvas = document.createElement('canvas');- const img = new Image();- img.crossOrigin = 'anonymous';- img.src = imgURL;- canvas.width = img.width;- canvas.height = img.height;- const ctx = canvas.getContext('2d');- ctx.drawImage(img, 0, 0);- return canvas.toDataURL('image/png');+ const canvas = document.createElement('canvas');+ const img = new Image();+ img.crossOrigin = 'anonymous';+ img.src = imgURL;+ canvas.width = img.width;+ canvas.height = img.height;+ const ctx = canvas.getContext('2d');+ ctx.drawImage(img, 0, 0);+ return canvas.toDataURL('image/png');}export function formatFileSize(sizeInBytes: number): string {- const kilobyte = 1024;- const megabyte = kilobyte * kilobyte;- const gigabyte = megabyte * kilobyte;- const terabyte = gigabyte * kilobyte;- const precision = 2;-- if (sizeInBytes >= 0 && sizeInBytes < kilobyte) {- return sizeInBytes + ' B';- } else if (sizeInBytes >= kilobyte && sizeInBytes < megabyte) {- return (sizeInBytes / kilobyte).toFixed(precision) + ' KB';- } else if (sizeInBytes >= megabyte && sizeInBytes < gigabyte) {- return (sizeInBytes / megabyte).toFixed(precision) + ' MB';- } else if (sizeInBytes >= gigabyte && sizeInBytes < terabyte) {- return (sizeInBytes / gigabyte).toFixed(precision) + ' GB';- } else if (sizeInBytes >= terabyte) {- return (sizeInBytes / terabyte).toFixed(precision) + ' TB';- }- return sizeInBytes + '';+ const kilobyte = 1024;+ const megabyte = kilobyte * kilobyte;+ const gigabyte = megabyte * kilobyte;+ const terabyte = gigabyte * kilobyte;+ const precision = 2;++ if (sizeInBytes >= 0 && sizeInBytes < kilobyte) {+ return sizeInBytes + ' B';+ } else if (sizeInBytes >= kilobyte && sizeInBytes < megabyte) {+ return (sizeInBytes / kilobyte).toFixed(precision) + ' KB';+ } else if (sizeInBytes >= megabyte && sizeInBytes < gigabyte) {+ return (sizeInBytes / megabyte).toFixed(precision) + ' MB';+ } else if (sizeInBytes >= gigabyte && sizeInBytes < terabyte) {+ return (sizeInBytes / gigabyte).toFixed(precision) + ' GB';+ } else if (sizeInBytes >= terabyte) {+ return (sizeInBytes / terabyte).toFixed(precision) + ' TB';+ }+ return sizeInBytes + '';}export function formatFileSize2(- sizeInBytes: number,- siSystem: boolean+ sizeInBytes: number,+ siSystem: boolean): string {- const threshold = siSystem ? 1000 : 1024;- if (!sizeInBytes) {- return '';- }- if (sizeInBytes < threshold) {- return sizeInBytes + ' B';- }- const units = siSystem- ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB']- : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB'];- let cUnit = -1;- do {- sizeInBytes /= threshold;- ++cUnit;- } while (sizeInBytes >= threshold);- return sizeInBytes.toFixed(1) + ' ' + units[cUnit];+ const threshold = siSystem ? 1000 : 1024;+ if (!sizeInBytes) {+ return '';+ }+ if (sizeInBytes < threshold) {+ return sizeInBytes + ' B';+ }+ const units = siSystem+ ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB']+ : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB'];+ let cUnit = -1;+ do {+ sizeInBytes /= threshold;+ ++cUnit;+ } while (sizeInBytes >= threshold);+ return sizeInBytes.toFixed(1) + ' ' + units[cUnit];}export function formatDateTime(date: string, includeTime: boolean) {- if (date === undefined || date === '') {- return '';- }- const d = new Date(date);- let cDate = d.getDate();- cDate += '';- if (cDate.length === 1) {- cDate = '0' + cDate;- }- let cMonth = d.getMonth() + 1;- cMonth += '';- if (cMonth.length === 1) {- cMonth = '0' + cMonth;- }- const cYear = d.getFullYear();- let cHour = d.getHours();- cHour += '';- if (cHour.length === 1) {- cHour = '0' + cHour;- }- let cMinute = d.getMinutes();- cMinute += '';- if (cMinute.length === 1) {- cMinute = '0' + cMinute;- }- let cSecond = d.getSeconds();- cSecond += '';- if (cSecond.length === 1) {- cSecond = '0' + cSecond;- }- let time = '';- if (includeTime) {- time = ' - ' + cHour + ':' + cMinute + ':' + cSecond;- }- return cYear + '.' + cMonth + '.' + cDate + time;+ if (date === undefined || date === '') {+ return '';+ }+ const d = new Date(date);+ let cDate: string = '' + d.getDate();+ cDate += '';+ if (cDate.length === 1) {+ cDate = '0' + cDate;+ }+ let cMonth: string = '' + (d.getMonth() + 1);+ cMonth += '';+ if (cMonth.length === 1) {+ cMonth = '0' + cMonth;+ }+ const cYear: string = '' + d.getFullYear();+ let cHour: string = '' + d.getHours();+ cHour += '';+ if (cHour.length === 1) {+ cHour = '0' + cHour;+ }+ let cMinute: string = '' + d.getMinutes();+ cMinute += '';+ if (cMinute.length === 1) {+ cMinute = '0' + cMinute;+ }+ let cSecond: string = '' + d.getSeconds();+ cSecond += '';+ if (cSecond.length === 1) {+ cSecond = '0' + cSecond;+ }+ let time = '';+ if (includeTime) {+ time = ' - ' + cHour + ':' + cMinute + ':' + cSecond;+ }+ return cYear + '.' + cMonth + '.' + cDate + time;}/** Convert a date in the following format 20191204 or 20191204~124532 */export function formatDateTime4Tag(- date: string,- includeTime: boolean,- includeMS?: boolean+ date: string,+ includeTime: boolean,+ includeMS?: boolean): string {- if (date === undefined || date === '') {- return '';- }- const d = new Date(date);- let cDate = d.getDate();- cDate += '';- if (cDate.length === 1) {- cDate = '0' + cDate;- }- let cMonth = d.getMonth() + 1;- cMonth += '';- if (cMonth.length === 1) {- cMonth = '0' + cMonth;- }- const cYear = d.getFullYear();-- let time = '';- if (includeTime) {- let cHour = d.getHours();- cHour += '';- if (cHour.length === 1) {- cHour = '0' + cHour;- }- let cMinute = d.getMinutes();- cMinute += '';- if (cMinute.length === 1) {- cMinute = '0' + cMinute;- }- let cSecond = d.getSeconds();- cSecond += '';- if (cSecond.length === 1) {- cSecond = '0' + cSecond;- }- time = '~' + cHour + '' + cMinute + '' + cSecond; // TODO fix Chrome transforms ~ to _- }-- let milliseconds = '';- if (includeMS) {- milliseconds = '~' + d.getMilliseconds();- }- return cYear + '' + cMonth + '' + cDate + time + milliseconds;+ if (date === undefined || date === '') {+ return '';+ }+ const d = new Date(date);+ let cDate: string = '' + d.getDate();+ cDate += '';+ if (cDate.length === 1) {+ cDate = '0' + cDate;+ }+ let cMonth: string = '' + (d.getMonth() + 1);+ cMonth += '';+ if (cMonth.length === 1) {+ cMonth = '0' + cMonth;+ }+ const cYear = d.getFullYear();++ let time = '';+ if (includeTime) {+ let cHour: string = '' + d.getHours();+ cHour += '';+ if (cHour.length === 1) {+ cHour = '0' + cHour;+ }+ let cMinute: string = '' + d.getMinutes();+ cMinute += '';+ if (cMinute.length === 1) {+ cMinute = '0' + cMinute;+ }+ let cSecond: string = '' + d.getSeconds();+ cSecond += '';+ if (cSecond.length === 1) {+ cSecond = '0' + cSecond;+ }+ time = '~' + cHour + '' + cMinute + '' + cSecond; // TODO fix Chrome transforms ~ to _+ }++ let milliseconds = '';+ if (includeMS) {+ milliseconds = '~' + d.getMilliseconds();+ }+ return cYear + '' + cMonth + '' + cDate + time + milliseconds;}export function convertStringToDate(dateString: string) {- if (dateString === undefined || dateString === '') {- return false;- }- if (dateString.length === 8) {- return new Date(- dateString.substring(0, 4) +- '-' +- dateString.substring(4, 6) +- '-' +- dateString.substring(6, 8)- );- }- return false;+ if (dateString === undefined || dateString === '') {+ return false;+ }+ if (dateString.length === 8) {+ return new Date(+ dateString.substring(0, 4) ++ '-' ++ dateString.substring(4, 6) ++ '-' ++ dateString.substring(6, 8)+ );+ }+ return false;}export function sortAlphaNum(a: any, b: any) {- // Regular expression to separate the digit string from the non-digit strings.- const reParts = /\d+|\D+/g;-- // Regular expression to test if the string has a digit.- const reDigit = /\d/;-- // Get rid of casing issues.- a = a.name.toLowerCase();- b = b.name.toLowerCase();-- // Separates the strings into substrings that have only digits and those- // that have no digits.- const aParts = a.match(reParts);- const bParts = b.match(reParts);-- // Used to determine if aPart and bPart are digits.- let isDigitPart;-- // If `a` and `b` are strings with substring parts that match...- if (- aParts &&- bParts &&- (isDigitPart = reDigit.test(aParts[0])) === reDigit.test(bParts[0])- ) {- // Loop through each substring part to compare the overall strings.- const len = Math.min(aParts.length, bParts.length);- for (let i = 0; i < len; i += 1) {- let aPart = aParts[i];- let bPart = bParts[i];-- // If comparing digits, convert them to numbers (assuming base 10).- if (isDigitPart) {- aPart = parseInt(aPart, 10);- bPart = parseInt(bPart, 10);- }-- // If the substrings aren't equal, return either -1 or 1.- if (aPart !== bPart) {- return aPart < bPart ? -1 : 1;- }-- // Toggle the value of isDigitPart since the parts will alternate.- isDigitPart = !isDigitPart;- }- }-- // Use normal comparison.- return (a >= b) - (a <= b);+ // Regular expression to separate the digit string from the non-digit strings.+ const reParts = /\d+|\D+/g;++ // Regular expression to test if the string has a digit.+ const reDigit = /\d/;++ // Get rid of casing issues.+ a = a.name.toLowerCase();+ b = b.name.toLowerCase();++ // Separates the strings into substrings that have only digits and those+ // that have no digits.+ const aParts = a.match(reParts);+ const bParts = b.match(reParts);++ // Used to determine if aPart and bPart are digits.+ let isDigitPart;++ // If `a` and `b` are strings with substring parts that match...+ if (+ aParts &&+ bParts &&+ (isDigitPart = reDigit.test(aParts[0])) === reDigit.test(bParts[0])+ ) {+ // Loop through each substring part to compare the overall strings.+ const len = Math.min(aParts.length, bParts.length);+ for (let i = 0; i < len; i += 1) {+ let aPart = aParts[i];+ let bPart = bParts[i];++ // If comparing digits, convert them to numbers (assuming base 10).+ if (isDigitPart) {+ aPart = parseInt(aPart, 10);+ bPart = parseInt(bPart, 10);+ }++ // If the substrings aren't equal, return either -1 or 1.+ if (aPart !== bPart) {+ return aPart < bPart ? -1 : 1;+ }++ // Toggle the value of isDigitPart since the parts will alternate.+ isDigitPart = !isDigitPart;+ }+ }++ // Use normal comparison.+ return (a >= b) - (a <= b);}// Sorting functionalityexport function sortByName(a: any, b: any) {- return !b.isFile - !a.isFile || sortAlphaNum(a, b);+ return !b.isFile - !a.isFile || sortAlphaNum(a, b);}export function sortBySize(a: any, b: any) {- return a.size - b.size;+ return a.size - b.size;}export function sortByDateModified(a: any, b: any) {- return a.lmdt - b.lmdt;+ return a.lmdt - b.lmdt;}export function sortByExtension(a: any, b: any) {- return a.extension.toString().localeCompare(b.extension);+ return a.extension.toString().localeCompare(b.extension);}export function sortByFirstTag(a: any, b: any) {- if ((!a.tags && !b.tags) || (a.tags.length < 1 && b.tags.length < 1)) {- return 0;- }- if (!a.tags || a.tags.length < 1) {- return -1;- }- if (!b.tags || b.tags.length < 1) {- return 1;- }- return a.tags[0].title.localeCompare(b.tags[0].title);+ if ((!a.tags && !b.tags) || (a.tags.length < 1 && b.tags.length < 1)) {+ return 0;+ }+ if (!a.tags || a.tags.length < 1) {+ return -1;+ }+ if (!b.tags || b.tags.length < 1) {+ return 1;+ }+ return a.tags[0].title.localeCompare(b.tags[0].title);}export function shuffleArray(array: Array<any>) {- // Durstenfeld shuffle- for (let i = array.length - 1; i > 0; i--) {- const j = Math.floor(Math.random() * (i + 1));- [array[i], array[j]] = [array[j], array[i]];- }- return array;+ // Durstenfeld shuffle+ for (let i = array.length - 1; i > 0; i--) {+ const j = Math.floor(Math.random() * (i + 1));+ [array[i], array[j]] = [array[j], array[i]];+ }+ return array;}export function sortByCriteria(data: any, criteria: string, order: boolean) {- switch (criteria) {- case 'byName':- if (order) {- return data.sort(sortByName);- }- return data.sort((a, b) => -1 * sortByName(a, b));- case 'byFileSize':- if (order) {- return data.sort(sortBySize);- }- return data.sort((a, b) => -1 * sortBySize(a, b));- case 'byDateModified':- if (order) {- return data.sort(sortByDateModified);- }- return data.sort((a, b) => -1 * sortByDateModified(a, b));- case 'byExtension':- if (order) {- return data.sort(sortByExtension);- }- return data.sort((a, b) => -1 * sortByExtension(a, b));- case 'byFirstTag':- if (order) {- return data.sort(sortByFirstTag);- }- return data.sort((a, b) => -1 * sortByFirstTag(a, b));- case 'random':- return shuffleArray(data);- default:- return data.sort(sortByName);- }+ switch (criteria) {+ case 'byName':+ if (order) {+ return data.sort(sortByName);+ }+ return data.sort((a, b) => -1 * sortByName(a, b));+ case 'byFileSize':+ if (order) {+ return data.sort(sortBySize);+ }+ return data.sort((a, b) => -1 * sortBySize(a, b));+ case 'byDateModified':+ if (order) {+ return data.sort(sortByDateModified);+ }+ return data.sort((a, b) => -1 * sortByDateModified(a, b));+ case 'byExtension':+ if (order) {+ return data.sort(sortByExtension);+ }+ return data.sort((a, b) => -1 * sortByExtension(a, b));+ case 'byFirstTag':+ if (order) {+ return data.sort(sortByFirstTag);+ }+ return data.sort((a, b) => -1 * sortByFirstTag(a, b));+ case 'random':+ return shuffleArray(data);+ default:+ return data.sort(sortByName);+ }}/**@@ -460,7 +460,7 @@ export function sortByCriteria(data: any, criteria: string, order: boolean) {* @returns {boolean}*/export const isObj = (val: any) =>- typeof val === 'object' && !isArr(val) && !isNull(val);+ typeof val === 'object' && !isArr(val) && !isNull(val);/*** @description Check if value is of type 'null'@@ -511,19 +511,19 @@ export const isBool = (val: any) => typeof val === 'boolean';* Check if object has property*/export const hasProp = (obj: Object, prop: any): boolean =>- obj.hasOwnProperty(prop);+ obj.hasOwnProperty(prop);/*** Check if object has method*/export const hasMethod = (obj: Object, method: any): boolean =>- hasProp(obj, method) && isFunc(obj[method]);+ hasProp(obj, method) && isFunc(obj[method]);/*** Check if object has key*/export const hasKey = (obj: Object, key: any): boolean =>- getKeys(obj).indexOf(key) > -1;+ getKeys(obj).indexOf(key) > -1;/*** @description Get object keys@@ -538,7 +538,7 @@ export const getKeys = (obj: Object) => Object.keys(obj);* @param callback*/export const eachKey = (obj, callback) => {- Object.keys(obj).forEach((key, index) => callback(key, obj[key], index));+ Object.keys(obj).forEach((key, index) => callback(key, obj[key], index));};/**@@ -547,7 +547,7 @@ export const eachKey = (obj, callback) => {* @param callback*/export const eachProp = (obj, callback) => {- eachKey(obj, (key, prop, index) => callback(prop, key, index));+ eachKey(obj, (key, prop, index) => callback(prop, key, index));};/**@@ -557,11 +557,11 @@ export const eachProp = (obj, callback) => {* @returns {object}*/export const extend = (baseObject, ...restObjects) => {- const assign = Object.assign;- const modifiedObject = assign({}, baseObject);+ const assign = Object.assign;+ const modifiedObject = assign({}, baseObject);- restObjects.map(obj => assign(modifiedObject, obj));- return modifiedObject;+ restObjects.map(obj => assign(modifiedObject, obj));+ return modifiedObject;};/**@@ -572,13 +572,13 @@ export const extend = (baseObject, ...restObjects) => {* @returns {*}*/export const recurIter = (handler, complete, index = 0) => {- handler(canRecur => {- if (!canRecur) {- return complete();- }- const nextIndex = index + 1;- recurIter(handler, complete, nextIndex);- }, index);+ handler(canRecur => {+ if (!canRecur) {+ return complete();+ }+ const nextIndex = index + 1;+ recurIter(handler, complete, nextIndex);+ }, index);};/**@@ -588,14 +588,14 @@ export const recurIter = (handler, complete, index = 0) => {* @param interval*/export const poll = (handler, complete, interval) => {- setTimeout(() => {- handler(canPoll => {- if (canPoll) {- return poll(handler, complete, interval);- }- complete();- });- }, interval);+ setTimeout(() => {+ handler(canPoll => {+ if (canPoll) {+ return poll(handler, complete, interval);+ }+ complete();+ });+ }, interval);};/**@@ -603,17 +603,17 @@ export const poll = (handler, complete, interval) => {* @returns {function(*=, *=, *=)}*/export const buffer = ({ timeout, id }) => {- const timers = {};-- return callback => {- if (!id) {- timers[id] = '0';- }- if (timers[id]) {- clearTimeout(timers[id]);- }- timers[id] = setTimeout(callback, timeout);- };+ const timers = {};++ return callback => {+ if (!id) {+ timers[id] = '0';+ }+ if (timers[id]) {+ clearTimeout(timers[id]);+ }+ timers[id] = setTimeout(callback, timeout);+ };};/**@@ -622,26 +622,26 @@ export const buffer = ({ timeout, id }) => {* @returns {*}*/export const determineTypeChecker = type => {- switch (type) {- case 'number':- return isNum;- case 'object':- return isObj;- case 'null':- return isNull;- case 'function':- return isFunc;- case 'array':- return isArr;- case 'string':- return isStr;- case 'bool':- case 'boolean':- return isBool;- case 'undefined':- default:- return isUndef;- }+ switch (type) {+ case 'number':+ return isNum;+ case 'object':+ return isObj;+ case 'null':+ return isNull;+ case 'function':+ return isFunc;+ case 'array':+ return isArr;+ case 'string':+ return isStr;+ case 'bool':+ case 'boolean':+ return isBool;+ case 'undefined':+ default:+ return isUndef;+ }};/**@@ -650,27 +650,27 @@ export const determineTypeChecker = type => {* @returns {*}*/export const setStrongTypedObject = config => {- const proxy = {};- eachProp(config, (prop, key) => (proxy[key] = prop.value));-- return new Proxy(proxy, {- get(target, prop) {- return target[prop];- },- set(target, prop, value) {- const type = config[prop].type;- const typeChecker = determineTypeChecker(type);-- if (!typeChecker(value)) {- throw new Error(- `[Ammo.StrongType] Invalid type. Expected type for field {${prop}} is {${type}}`- );- }-- target[prop] = value;- return true;- }- });+ const proxy = {};+ eachProp(config, (prop, key) => (proxy[key] = prop.value));++ return new Proxy(proxy, {+ get(target, prop) {+ return target[prop];+ },+ set(target, prop, value) {+ const type = config[prop].type;+ const typeChecker = determineTypeChecker(type);++ if (!typeChecker(value)) {+ throw new Error(+ `[Ammo.StrongType] Invalid type. Expected type for field {${prop}} is {${type}}`+ );+ }++ target[prop] = value;+ return true;+ }+ });};/**@@ -679,14 +679,14 @@ export const setStrongTypedObject = config => {* @param requiredKeys*/export const filterObjectData = (objectData, requiredKeys) => {- const filteredObject = {};- eachKey(objectData, (key, value) => {- if (requiredKeys.indexOf(key) === -1) {- return false;- }- filteredObject[key] = value;- });- return filteredObject;+ const filteredObject = {};+ eachKey(objectData, (key, value) => {+ if (requiredKeys.indexOf(key) === -1) {+ return false;+ }+ filteredObject[key] = value;+ });+ return filteredObject;};/**@@ -695,11 +695,11 @@ export const filterObjectData = (objectData, requiredKeys) => {* @param requiredKeys*/export const filterArrayOfObjectsData = (arrayData, requiredKeys) => {- return arrayData.reduce((accumulator, item) => {- const filteredObject = filterObjectData(item, requiredKeys);- accumulator.push(filteredObject);- return accumulator;- }, []);+ return arrayData.reduce((accumulator, item) => {+ const filteredObject = filterObjectData(item, requiredKeys);+ accumulator.push(filteredObject);+ return accumulator;+ }, []);};/**@@ -708,14 +708,14 @@ export const filterArrayOfObjectsData = (arrayData, requiredKeys) => {* @param requiredKey*/export const pluckObjectDataToArray = (objectData, requiredKey) => {- const filteredArray = [];- eachKey(objectData, (key, value) => {- if (requiredKey !== key) {- return false;- }- filteredArray.push(value);- });- return filteredArray;+ const filteredArray = [];+ eachKey(objectData, (key, value) => {+ if (requiredKey !== key) {+ return false;+ }+ filteredArray.push(value);+ });+ return filteredArray;};/**@@ -724,10 +724,10 @@ export const pluckObjectDataToArray = (objectData, requiredKey) => {* @param requiredKey*/export const pluckArrayOfObjectsDataToArray = (arrayData, requiredKey) => {- return arrayData.reduce((accumulator, item) => {- const filteredArray = pluckObjectDataToArray(item, requiredKey);- return [...accumulator, ...filteredArray];- }, []);+ return arrayData.reduce((accumulator, item) => {+ const filteredArray = pluckObjectDataToArray(item, requiredKey);+ return [...accumulator, ...filteredArray];+ }, []);};/**@@ -737,39 +737,39 @@ export const pluckArrayOfObjectsDataToArray = (arrayData, requiredKey) => {* @returns {*}*/export const extractNestedProp = (obj, keysText) => {- const keys = keysText.split('.');- const keysLength = keys.length - 1;- let keysIndex = 0;- let isValidKey = true;- let targetObj = Object.assign({}, obj);- let targetProp;- let nextTarget;-- if (keys.length > 0) {- while (isValidKey) {- nextTarget = targetObj[keys[keysIndex]];-- // ... check if final target is reached ...- if (keysIndex === keysLength) {- // ... extract target prop- targetProp =- !isUndef(nextTarget) && !isNull(nextTarget) ? nextTarget : undefined;- break;- }-- // ... check if next target is not an object ...- if (!isObj(nextTarget)) {- // ... cancel sequence- isValidKey = false;- break;- }-- targetObj = nextTarget;- keysIndex++;- }- }-- return targetProp;+ const keys = keysText.split('.');+ const keysLength = keys.length - 1;+ let keysIndex = 0;+ let isValidKey = true;+ let targetObj = Object.assign({}, obj);+ let targetProp;+ let nextTarget;++ if (keys.length > 0) {+ while (isValidKey) {+ nextTarget = targetObj[keys[keysIndex]];++ // ... check if final target is reached ...+ if (keysIndex === keysLength) {+ // ... extract target prop+ targetProp =+ !isUndef(nextTarget) && !isNull(nextTarget) ? nextTarget : undefined;+ break;+ }++ // ... check if next target is not an object ...+ if (!isObj(nextTarget)) {+ // ... cancel sequence+ isValidKey = false;+ break;+ }++ targetObj = nextTarget;+ keysIndex++;+ }+ }++ return targetProp;};/**@@ -779,41 +779,46 @@ export const extractNestedProp = (obj, keysText) => {* @param type* @param direction*/-export const sortBy = (items, keysText, type = 'string', direction = 'asc') => {- return items.sort((a, b) => {- const aVal = extractNestedProp(a, keysText);- const bVal = extractNestedProp(b, keysText);-- if (isUndef(aVal) || isNull(aVal)) {- return direction === 'asc' ? -1 : 1;- }-- if (isUndef(bVal) || isNull(bVal)) {- return direction === 'asc' ? 1 : -1;- }-- if (type === 'string' || type === 'email') {- if (aVal.toLowerCase() > bVal.toLowerCase()) {- return direction === 'asc' ? 1 : -1;- }- if (aVal.toLowerCase() < bVal.toLowerCase()) {- return direction === 'asc' ? -1 : 1;- }- return 0;- } else if (type === 'number' || type === 'integer' || type === 'float') {- if (aVal > bVal) {- return direction === 'asc' ? 1 : -1;- }- if (aVal < bVal) {- return direction === 'asc' ? -1 : 1;- }- return 0;- } else if (type === 'date') {- return direction === 'asc'- ? new Date(aVal) - new Date(bVal)- : new Date(bVal) - new Date(aVal);- }- });+export const sortBy = (+ items: any,+ keysText: any,+ type: string = 'string',+ direction: string = 'asc'+) => {+ return items.sort((a, b) => {+ const aVal = extractNestedProp(a, keysText);+ const bVal = extractNestedProp(b, keysText);++ if (isUndef(aVal) || isNull(aVal)) {+ return direction === 'asc' ? -1 : 1;+ }++ if (isUndef(bVal) || isNull(bVal)) {+ return direction === 'asc' ? 1 : -1;+ }++ if (type === 'string' || type === 'email') {+ if (aVal.toLowerCase() > bVal.toLowerCase()) {+ return direction === 'asc' ? 1 : -1;+ }+ if (aVal.toLowerCase() < bVal.toLowerCase()) {+ return direction === 'asc' ? -1 : 1;+ }+ return 0;+ } else if (type === 'number' || type === 'integer' || type === 'float') {+ if (aVal > bVal) {+ return direction === 'asc' ? 1 : -1;+ }+ if (aVal < bVal) {+ return direction === 'asc' ? -1 : 1;+ }+ return 0;+ } else if (type === 'date') {+ return direction === 'asc'+ ? new Date(aVal) - new Date(bVal)+ : new Date(bVal) - new Date(aVal);+ }+ });};/**@@ -822,34 +827,34 @@ export const sortBy = (items, keysText, type = 'string', direction = 'asc') => {* @returns {*}*/export const shape = items => {- let shapeItems = [...items];-- return {- fetch: () => shapeItems,- filterByUnique(key) {- shapeItems = filterByUnique(shapeItems, key);- return this;- },- filterByDuplicate(key, length = 2) {- shapeItems = filterByDuplicate(shapeItems, key, length);- return this;- },- sortBy({ key, type = 'string', direction = 'asc' }) {- shapeItems = sortBy(shapeItems, key, type, direction);- return this;- },- reduceTo(key) {- shapeItems = shapeItems.reduce((accumulator, item) => {- const prop = extractNestedProp(item, key);- if (isArr(prop)) {- return [...accumulator, ...prop];- } else if (!isUndef(prop) && !isNull(prop)) {- return [...accumulator, prop];- }- }, []);- return this;- }- };+ let shapeItems = [...items];++ return {+ fetch: () => shapeItems,+ filterByUnique(key) {+ shapeItems = filterByUnique(shapeItems, key);+ return this;+ },+ filterByDuplicate(key, length = 2) {+ shapeItems = filterByDuplicate(shapeItems, key, length);+ return this;+ },+ sortBy({ key, type = 'string', direction = 'asc' }) {+ shapeItems = sortBy(shapeItems, key, type, direction);+ return this;+ },+ reduceTo(key) {+ shapeItems = shapeItems.reduce((accumulator, item) => {+ const prop = extractNestedProp(item, key);+ if (isArr(prop)) {+ return [...accumulator, ...prop];+ } else if (!isUndef(prop) && !isNull(prop)) {+ return [...accumulator, prop];+ }+ }, []);+ return this;+ }+ };};/**@@ -859,23 +864,23 @@ export const shape = items => {* @returns {*}*/export const filterByUnique = (items, key) =>- items.reduce((accumulator, item) => {- const itemProp = extractNestedProp(item, key);+ items.reduce((accumulator, item) => {+ const itemProp = extractNestedProp(item, key);- const isDuplicate =- accumulator.filter(filteredItem => {- const prop = extractNestedProp(filteredItem, key);- return prop === itemProp;- }).length > 0;+ const isDuplicate =+ accumulator.filter(filteredItem => {+ const prop = extractNestedProp(filteredItem, key);+ return prop === itemProp;+ }).length > 0;- if (isDuplicate) {- return accumulator;- }+ if (isDuplicate) {+ return accumulator;+ }- const modifiedItem = extend({}, item);- accumulator.push(modifiedItem);- return accumulator;- }, []);+ const modifiedItem = extend({}, item);+ accumulator.push(modifiedItem);+ return accumulator;+ }, []);/*** @description Filter by duplicate@@ -885,14 +890,14 @@ export const filterByUnique = (items, key) =>* @returns {*}*/export const filterByDuplicate = (items, key, duplicateLength = 2) =>- items.filter(item => {- const itemProp = extractNestedProp(item, key);- const duplicatesCount = duplicateLength - 1;-- return (- items.filter(innerItem => {- const prop = extractNestedProp(innerItem, key);- return prop === itemProp;- }).length > duplicatesCount- );- });+ items.filter(item => {+ const itemProp = extractNestedProp(item, key);+ const duplicatesCount = duplicateLength - 1;++ return (+ items.filter(innerItem => {+ const prop = extractNestedProp(innerItem, key);+ return prop === itemProp;+ }).length > duplicatesCount+ );+ });diff --git a/app/utils/openlocationcode.ts b/app/utils/openlocationcode.jssimilarity index 100%rename from app/utils/openlocationcode.tsrename to app/utils/openlocationcode.js