TagSpaces is an offline, open source, document manager with tagging support
applying prettier
Ilian Sapundshiev3b364e344bce
diff --git a/app/.vscode/launch.json b/app/.vscode/launch.jsonindex b54525e32..6fd24f385 100644--- a/app/.vscode/launch.json+++ b/app/.vscode/launch.json@@ -4,51 +4,46 @@// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387"version": "0.2.0","configurations": [-- {- "type": "node",- "request": "launch",- "name": "Electron Main",- // Mac OS & Linux process runtime executable- "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron",- "windows": {- // Windows process runtime executable- "runtimeExecutable": "${workspaceRoot}\\node_modules\\.bin\\electron.cmd"- },- "program": "${workspaceRoot}/compiled/src/main/Main.js",- "protocol": "inspector",- "stopOnEntry": false,- "args": [],- "cwd": "${workspaceRoot}/",- "runtimeArgs": [- "--enable-logging"- ],- "env": {},- "sourceMaps": true,- "outFiles": [- "${workspaceRoot}/compiled/src"- ],- "internalConsoleOptions": "openOnSessionStart",- "console": "integratedTerminal"+ {+ "type": "node",+ "request": "launch",+ "name": "Electron Main",+ // Mac OS & Linux process runtime executable+ "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron",+ "windows": {+ // Windows process runtime executable+ "runtimeExecutable": "${workspaceRoot}\\node_modules\\.bin\\electron.cmd"},- {- "name": "Debug renderer process",- "type": "chrome",- "request": "launch",- // Mac OS & Linux process runtime executable- "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron",- "windows": {- // Windows process runtime executable- "runtimeExecutable": "${workspaceRoot}\\node_modules\\.bin\\electron.cmd"- },- "runtimeArgs": [- "${workspaceRoot}/",- "--enable-logging",- "--remote-debugging-port=9222"- ],- "webRoot": "${workspaceRoot}/",- "sourceMaps": true,- "internalConsoleOptions": "openOnSessionStart"- }+ "program": "${workspaceRoot}/compiled/src/main/Main.js",+ "protocol": "inspector",+ "stopOnEntry": false,+ "args": [],+ "cwd": "${workspaceRoot}/",+ "runtimeArgs": ["--enable-logging"],+ "env": {},+ "sourceMaps": true,+ "outFiles": ["${workspaceRoot}/compiled/src"],+ "internalConsoleOptions": "openOnSessionStart",+ "console": "integratedTerminal"+ },+ {+ "name": "Debug renderer process",+ "type": "chrome",+ "request": "launch",+ // Mac OS & Linux process runtime executable+ "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/electron",+ "windows": {+ // Windows process runtime executable+ "runtimeExecutable": "${workspaceRoot}\\node_modules\\.bin\\electron.cmd"+ },+ "runtimeArgs": [+ "${workspaceRoot}/",+ "--enable-logging",+ "--remote-debugging-port=9222"+ ],+ "webRoot": "${workspaceRoot}/",+ "sourceMaps": true,+ "internalConsoleOptions": "openOnSessionStart"+ }]}diff --git a/app/.vscode/tasks.json b/app/.vscode/tasks.jsonindex 5befab841..ad503fc70 100644--- a/app/.vscode/tasks.json+++ b/app/.vscode/tasks.json@@ -1,32 +1,29 @@{"version": "2.0.0","presentation": {- "echo": true,- "reveal": "always",- "focus": false,- "panel": "new"+ "echo": true,+ "reveal": "always",+ "focus": false,+ "panel": "new"},"tasks": [- {- // Custom prestart task i.e. npm run prestart.- "taskName": "prestart",- "command": "npm",- "args": [- "run",- "prestart"- ],- "type": "shell",- "group": "build",- // Specify tsc problem matcher.- "problemMatcher": ["$tsc-watch"]- },- {- // Default compile task from package.json i.e. npm run compile.- "type": "npm",- "script": "compile",- "group": "build",- // Specify tsc problem matcher.- "problemMatcher": ["$tsc-watch"]- }+ {+ // Custom prestart task i.e. npm run prestart.+ "taskName": "prestart",+ "command": "npm",+ "args": ["run", "prestart"],+ "type": "shell",+ "group": "build",+ // Specify tsc problem matcher.+ "problemMatcher": ["$tsc-watch"]+ },+ {+ // Default compile task from package.json i.e. npm run compile.+ "type": "npm",+ "script": "compile",+ "group": "build",+ // Specify tsc problem matcher.+ "problemMatcher": ["$tsc-watch"]+ }]}diff --git a/app/components/AppOnboarding.js b/app/components/AppOnboarding.jsindex 4f48fd597..c47642249 100644--- a/app/components/AppOnboarding.js+++ b/app/components/AppOnboarding.js@@ -34,7 +34,7 @@ class AppOnboarding extends Component {}, 1000);} */- callback = (data) => {+ callback = data => {const { action, index, type } = data;};@@ -44,21 +44,15 @@ class AppOnboarding extends Component {{target: '[data-tid=createNewLocation]',content: i18n.t('welcomeContent'),- placement: 'bottom',+ placement: 'bottom'},{target: '[data-tid=aboutTagSpaces]',content: 'Hello world',- placement: 'bottom',- },+ placement: 'bottom'+ }];- return (- <Joyride- steps={steps}- run={run}- callback={this.callback}- />- );+ return <Joyride steps={steps} run={run} callback={this.callback} />;}}diff --git a/app/components/CustomLogo.js b/app/components/CustomLogo.jsindex 2d8396d22..0c33d5f51 100644--- a/app/components/CustomLogo.js+++ b/app/components/CustomLogo.js@@ -32,9 +32,15 @@ const AppVersionBadge = withStyles(theme => ({badge: {top: '25%',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]- },+ 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);type Props = {@@ -49,7 +55,11 @@ if (externalLogo) {}const CustomLogo = (props: Props) => (- <AppVersionBadge title="App Version" badgeContent={'v' + versionMeta.version} color="primary">+ <AppVersionBadge+ title="App Version"+ badgeContent={'v' + versionMeta.version}+ color="primary"+ ><IconButtonstyle={{ height: 50, padding: 0, marginBottom: 15 }}data-tid="aboutTagSpaces"@@ -61,9 +71,12 @@ const CustomLogo = (props: Props) => ();function mapActionCreatorsToProps(dispatch) {- return bindActionCreators({- toggleAboutDialog: AppActions.toggleAboutDialog,- }, dispatch);+ return bindActionCreators(+ {+ toggleAboutDialog: AppActions.toggleAboutDialog+ },+ dispatch+ );}export default connect(undefined, mapActionCreatorsToProps)(CustomLogo);diff --git a/app/components/EntryContainer.js b/app/components/EntryContainer.jsindex ee55e7768..e448615c0 100644--- a/app/components/EntryContainer.js+++ b/app/components/EntryContainer.js@@ -60,7 +60,10 @@ import {extractDirectoryName} from '../utils/paths';import { buffer } from '../utils/misc';-import { actions as SettingsActions, getKeyBindingObject } from '../reducers/settings';+import {+ actions as SettingsActions,+ getKeyBindingObject+} from '../reducers/settings';import TaggingActions from '../reducers/tagging-actions';import {type OpenedEntry,@@ -75,7 +78,10 @@ const defaultSplitSize = 103;const openedSplitSize = 360;const fullSplitSize = 600;const maxCharactersTitleLength = 50;-const bufferedSplitResize = buffer({ timeout: 300, id: 'buffered-split-resize' });+const bufferedSplitResize = buffer({+ timeout: 300,+ id: 'buffered-split-resize'+});const styles = theme => ({panel: {@@ -83,7 +89,7 @@ const styles = theme => ({flexDirection: 'column',flex: '1 1 100%',display: 'flex',- backgroundColor: theme.palette.background.default,+ backgroundColor: theme.palette.background.default},fileContent: {width: '100%',@@ -141,7 +147,7 @@ const styles = theme => ({paddingBottom: 0,minWidth: 20,height: 44,- whiteSpace: 'nowrap',+ whiteSpace: 'nowrap'},entryCloseSection: {position: 'absolute',@@ -231,7 +237,7 @@ class EntryContainer extends React.Component<Props, State> {if (AppConfig.isElectron && this.fileViewer) {// this.fileViewer.dispatchEvent(audioEvent);this.fileViewer.executeJavaScript(- 'window.dispatchEvent(new Event("resume"));',+ 'window.dispatchEvent(new Event("resume"));');} else if (this.fileViewer) {this.fileViewer.dispatchEvent(new Event('resume'));@@ -239,8 +245,14 @@ class EntryContainer extends React.Component<Props, State> {});if (AppConfig.isElectron) {if (this.fileViewer) {- this.fileViewer.addEventListener('console-message', this.logEventsFromExtensions);- this.fileViewer.addEventListener('ipc-message', this.handleMessageProxy);+ this.fileViewer.addEventListener(+ 'console-message',+ this.logEventsFromExtensions+ );+ this.fileViewer.addEventListener(+ 'ipc-message',+ this.handleMessageProxy+ );}} else {window.addEventListener(@@ -256,11 +268,10 @@ class EntryContainer extends React.Component<Props, State> {componentWillReceiveProps(nextProps: Props) {if (nextProps.openedFiles.length > 0) {const nextEntry = nextProps.openedFiles[0];- if (- this.state.currentEntry &&- this.state.currentEntry.changed- ) {- this.props.showNotification(i18n.t('core:currentlyFileChangedSaveOrClose'));+ if (this.state.currentEntry && this.state.currentEntry.changed) {+ this.props.showNotification(+ i18n.t('core:currentlyFileChangedSaveOrClose')+ );return true;}@@ -269,13 +280,20 @@ class EntryContainer extends React.Component<Props, State> {if (nextProps.isReadOnlyMode) {this.setState({ editingSupported: false });} else {- this.setState({ editingSupported: (nextEntry.editingExtensionId && nextEntry.editingExtensionId.length > 3) });+ this.setState({+ editingSupported:+ nextEntry.editingExtensionId &&+ nextEntry.editingExtensionId.length > 3+ });}const { settings } = nextProps;const currentEntry = nextProps.openedFiles[0];- const tags = extractTagsAsObjects(currentEntry.path, settings.tagDelimiter);+ const tags = extractTagsAsObjects(+ currentEntry.path,+ settings.tagDelimiter+ );this.setState({selectedItem: {...currentEntry,@@ -285,7 +303,8 @@ class EntryContainer extends React.Component<Props, State> {this.setState({entryPropertiesSplitSize: settings.entryPropertiesSplitSize,- isPropertiesPanelVisible: settings.entryPropertiesSplitSize > defaultSplitSize+ isPropertiesPanelVisible:+ settings.entryPropertiesSplitSize > defaultSplitSize});} else {this.setState({ currentEntry: null });@@ -325,8 +344,14 @@ class EntryContainer extends React.Component<Props, State> {componentWillUnmount() {if (AppConfig.isElectron) {if (this.fileViewer && this.fileViewer.removeEventListener) {- this.fileViewer.removeEventListener('console-message', this.logEventsFromExtensions);- this.fileViewer.removeEventListener('ipc-message', this.handleMessageProxy);+ this.fileViewer.removeEventListener(+ 'console-message',+ this.logEventsFromExtensions+ );+ this.fileViewer.removeEventListener(+ 'ipc-message',+ this.handleMessageProxy+ );}} else {window.removeEventListener('message', this.handleMessage);@@ -337,13 +362,13 @@ class EntryContainer extends React.Component<Props, State> {fileViewerContainer;isPropertiesEditMode = false;- logEventsFromExtensions = (event) => {+ logEventsFromExtensions = event => {console.log('Ext. Logging >>> ', event.message);- }+ };- handleMessageProxy = (event) => {+ handleMessageProxy = event => {this.handleMessage(JSON.stringify(event.channel));- }+ };handleMessage = (msg: Object | string) => {let data;@@ -357,102 +382,99 @@ class EntryContainer extends React.Component<Props, State> {data = JSON.parse(msg); // electron case}switch (data.command) {- case 'showAlertDialog':- message = data.title ? data.title : '';- if (data.message) {- message = message + ': ' + data.message;- }- this.props.showNotification(message, NotificationTypes.default);- break;- case 'saveDocument':- this.startSavingFile();- break;- case 'editDocument':- this.editFile();- break;- case 'playbackEnded':- nextFilePath = this.props.getNextFile(this.state.currentEntry.path);- nextFile = this.props.directoryContent.filter(entry => entry.path === nextFilePath);- this.props.openFile(nextFilePath);- this.props.setLastSelectedEntry(nextFilePath);- this.props.setSelectedEntries(nextFile);- break;- case 'openLinkExternally':- console.log('Open link externally: ' + data.link);- openLinkExternally(data.link);- break;- case 'openFileNatively':- console.log('Open file natively: ' + data.link);- this.props.openFileNatively(data.link);- break;- case 'loadDefaultTextContent':- if (!this.state.currentEntry || !this.state.currentEntry.path) {+ case 'showAlertDialog':+ message = data.title ? data.title : '';+ if (data.message) {+ message = message + ': ' + data.message;+ }+ this.props.showNotification(message, NotificationTypes.default);+ break;+ case 'saveDocument':+ this.startSavingFile();+ break;+ case 'editDocument':+ this.editFile();+ break;+ case 'playbackEnded':+ nextFilePath = this.props.getNextFile(this.state.currentEntry.path);+ nextFile = this.props.directoryContent.filter(+ entry => entry.path === nextFilePath+ );+ this.props.openFile(nextFilePath);+ this.props.setLastSelectedEntry(nextFilePath);+ this.props.setSelectedEntries(nextFile);+ break;+ case 'openLinkExternally':+ console.log('Open link externally: ' + data.link);+ openLinkExternally(data.link);+ break;+ case 'openFileNatively':+ console.log('Open file natively: ' + data.link);+ this.props.openFileNatively(data.link);+ break;+ case 'loadDefaultTextContent':+ if (!this.state.currentEntry || !this.state.currentEntry.path) {+ break;+ }+ textFilePath = this.state.currentEntry.path;+ // TODO make loading index.html for folders configurable+ // if (!this.state.currentEntry.isFile) {+ // textFilePath += '/index.html';+ // }+ PlatformIO.loadTextFilePromise(+ textFilePath,+ data.preview ? data.preview : false+ )+ .then(content => {+ let fileDirectory = extractContainingDirectoryPath(textFilePath);+ if (AppConfig.isWeb) {+ fileDirectory =+ extractContainingDirectoryPath(location.href) ++ '/' ++ fileDirectory;+ }+ if (AppConfig.isElectron && this.fileViewer) {+ this.fileViewer.executeJavaScript(+ 'setContent(' ++ JSON.stringify(content) ++ ',' ++ JSON.stringify(fileDirectory) ++ ',' ++ !this.state.currentEntry.editMode ++ ')',+ false+ );+ } else {+ this.fileViewer.contentWindow.setContent(+ content,+ fileDirectory,+ !this.state.currentEntry.editMode+ );+ }+ return true;+ })+ .catch(err => {+ console.warn('Error loading text content ' + err);+ });+ break;+ case 'contentChangedInEditor':+ if (this.state.currentEntry.editMode) {+ this.setState({+ currentEntry: {+ ...this.state.currentEntry,+ changed: true+ }+ });+ }+ break;+ default:+ console.log('Not recognized messaging command: ' + msg);break;- }- textFilePath = this.state.currentEntry.path;- // TODO make loading index.html for folders configurable- // if (!this.state.currentEntry.isFile) {- // textFilePath += '/index.html';- // }- PlatformIO.loadTextFilePromise(- textFilePath,- data.preview ? data.preview : false- )- .then(content => {- let fileDirectory = extractContainingDirectoryPath(- textFilePath- );- if (AppConfig.isWeb) {- fileDirectory =- extractContainingDirectoryPath(location.href) +- '/' +- fileDirectory;- }- if (AppConfig.isElectron && this.fileViewer) {- this.fileViewer.executeJavaScript(- 'setContent(' +- JSON.stringify(content) +- ',' +- JSON.stringify(fileDirectory) +- ',' +- !this.state.currentEntry.editMode +- ')',- false- );- } else {- this.fileViewer.contentWindow.setContent(- content,- fileDirectory,- !this.state.currentEntry.editMode- );- }- return true;- })- .catch(err => {- console.warn('Error loading text content ' + err);- });- break;- case 'contentChangedInEditor':- if (this.state.currentEntry.editMode) {- this.setState({- currentEntry: {- ...this.state.currentEntry,- changed: true- }- });- }- break;- default:- console.log('Not recognized messaging command: ' + msg);- break;}};reloadDocument = () => {- if (- this.state.currentEntry &&- this.state.currentEntry.changed- ) {+ if (this.state.currentEntry && this.state.currentEntry.changed) {this.setState({ isSaveBeforeReloadConfirmDialogOpened: true });return true;}@@ -463,14 +485,13 @@ class EntryContainer extends React.Component<Props, State> {editMode: false}});- }+ };cancelEditing = () => {- if (- this.state.currentEntry &&- this.state.currentEntry.changed- ) {- this.props.showNotification(i18n.t('core:currentlyFileChangedSaveOrClose'));+ if (this.state.currentEntry && this.state.currentEntry.changed) {+ this.props.showNotification(+ i18n.t('core:currentlyFileChangedSaveOrClose')+ );return true;}this.setState({@@ -480,9 +501,9 @@ class EntryContainer extends React.Component<Props, State> {editMode: false}});- }+ };- startClosingFile = (event) => {+ startClosingFile = event => {if (event) {event.preventDefault(); // Let's stop this event.event.stopPropagation();@@ -579,13 +600,17 @@ class EntryContainer extends React.Component<Props, State> {document.webkitExitFullscreen();this.setState({ isFullscreen: false });return;- } else if (this.state.isFullscreen && document.exitFullscreen) { // TODO exit fullscreen firefox does not work- document.exitFullscreen().then(() => {- console.log('Fullscreen exit successful');- return true;- }).catch((e) => {- console.log('Error exiting fullscreen');- });+ } else if (this.state.isFullscreen && document.exitFullscreen) {+ // TODO exit fullscreen firefox does not work+ document+ .exitFullscreen()+ .then(() => {+ console.log('Fullscreen exit successful');+ return true;+ })+ .catch(e => {+ console.log('Error exiting fullscreen');+ });this.setState({ isFullscreen: false });return;} /* else if (this.state.isFullscreen && document.mozExitFullscreen) {@@ -594,13 +619,22 @@ class EntryContainer extends React.Component<Props, State> {return;} */if (!this.state.isFullscreen && this.fileViewerContainer) {- if (this.fileViewerContainer && this.fileViewerContainer.webkitRequestFullscreen) {+ if (+ this.fileViewerContainer &&+ this.fileViewerContainer.webkitRequestFullscreen+ ) {this.fileViewerContainer.webkitRequestFullscreen();this.setState({ isFullscreen: true });- } else if (this.fileViewerContainer && this.fileViewerContainer.requestFullscreen) {+ } else if (+ this.fileViewerContainer &&+ this.fileViewerContainer.requestFullscreen+ ) {this.fileViewerContainer.requestFullscreen();this.setState({ isFullscreen: true });- } else if (this.fileViewerContainer && this.fileViewerContainer.mozRequestFullScreen) {+ } else if (+ this.fileViewerContainer &&+ this.fileViewerContainer.mozRequestFullScreen+ ) {this.fileViewerContainer.mozRequestFullScreen();this.setState({ isFullscreen: true });}@@ -619,18 +653,24 @@ class EntryContainer extends React.Component<Props, State> {});} */- this.setState({- openedSplitSize,- isPropertiesPanelVisible: true- }, () => this.props.setEntryPropertiesSplitSize(openedSplitSize));+ this.setState(+ {+ openedSplitSize,+ isPropertiesPanelVisible: true+ },+ () => this.props.setEntryPropertiesSplitSize(openedSplitSize)+ );};closePanel = () => {- this.setState({- openedSplitSize: defaultSplitSize,- entryPropertiesSplitSize: defaultSplitSize,- isPropertiesPanelVisible: false- }, () => this.props.setEntryPropertiesSplitSize(defaultSplitSize));+ this.setState(+ {+ openedSplitSize: defaultSplitSize,+ entryPropertiesSplitSize: defaultSplitSize,+ isPropertiesPanelVisible: false+ },+ () => this.props.setEntryPropertiesSplitSize(defaultSplitSize)+ );};togglePanel = () => {@@ -644,7 +684,9 @@ class EntryContainer extends React.Component<Props, State> {openNextFile = () => {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);+ const nextFile = this.props.directoryContent.filter(+ entry => entry.path === nextFilePath+ );this.props.openFile(nextFilePath);this.props.setLastSelectedEntry(nextFilePath);this.props.setSelectedEntries(nextFile);@@ -654,7 +696,9 @@ class EntryContainer extends React.Component<Props, State> {openPrevFile = () => {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);+ const prevFile = this.props.directoryContent.filter(+ entry => entry.path === prevFilePath+ );this.props.openFile(prevFilePath);this.props.setLastSelectedEntry(prevFilePath);this.props.setSelectedEntries(prevFile);@@ -715,13 +759,19 @@ class EntryContainer extends React.Component<Props, State> {if (downloadLink) {if (AppConfig.isWeb) {- const link = `${location.protocol}//${location.hostname}${location.port !== '' ? `:${location.port}` : ''}/${currentEntry.path}`;+ const link = `${location.protocol}//${location.hostname}${+ location.port !== '' ? `:${location.port}` : ''+ }/${currentEntry.path}`;downloadLink.setAttribute('href', link);} else {- downloadLink.setAttribute('href', `file:///${currentEntry.path}`);+ downloadLink.setAttribute(+ 'href',+ `file:///${currentEntry.path}`+ );}- if (currentEntry.url) { // mostly the s3 case+ if (currentEntry.url) {+ // mostly the s3 casedownloadLink.setAttribute('target', '_blank');downloadLink.setAttribute('href', currentEntry.url);}@@ -744,7 +794,7 @@ class EntryContainer extends React.Component<Props, State> {<CopyContentIcon /></IconButton>)*/}- { !this.props.isReadOnlyMode && (+ {!this.props.isReadOnlyMode && (<IconButtontitle={i18n.t('core:deleteEntry')}aria-label={i18n.t('core:deleteEntry')}@@ -761,7 +811,7 @@ class EntryContainer extends React.Component<Props, State> {<RefreshIcon /></IconButton></div>- <div className={classes.entryNavigationSection} >+ <div className={classes.entryNavigationSection}><IconButtontitle={i18n.t('core:openPrevFileTooltip')}aria-label={i18n.t('core:openPrevFileTooltip')}@@ -811,7 +861,7 @@ class EntryContainer extends React.Component<Props, State> {><RefreshIcon /></IconButton>- { !this.props.isReadOnlyMode && (+ {!this.props.isReadOnlyMode && (<div><IconButtontitle={i18n.t('core:deleteDirectory')}@@ -826,7 +876,7 @@ class EntryContainer extends React.Component<Props, State> {</div>);- renderFileView = (fileOpenerURL) => {+ renderFileView = fileOpenerURL => {if (AppConfig.isElectron) {return (<webview@@ -858,9 +908,9 @@ class EntryContainer extends React.Component<Props, State> {setPropertiesEditMode = (editMode: boolean) => {this.isPropertiesEditMode = editMode;- }+ };- resetState = (key) => {+ resetState = key => {// this.isPropertiesEditMode = false;this.setState({[key]: uuidv1()@@ -883,17 +933,21 @@ class EntryContainer extends React.Component<Props, State> {fileOpenerURL =currentEntry.editingExtensionPath +'/index.html?file=' +- encodeURIComponent(currentEntry.url ? currentEntry.url : currentEntry.path) ++ encodeURIComponent(+ currentEntry.url ? currentEntry.url : currentEntry.path+ ) +'&locale=' +i18n.language +'&edit=true';- // } else if (!currentEntry.isFile) { // TODO needed for loading folder's default html- // fileOpenerURL = 'node_modules/@tagspaces/html-viewer/index.html?locale=' + i18n.language;+ // } else if (!currentEntry.isFile) { // TODO needed for loading folder's default html+ // fileOpenerURL = 'node_modules/@tagspaces/html-viewer/index.html?locale=' + i18n.language;} else {fileOpenerURL =currentEntry.viewingExtensionPath +'/index.html?file=' +- encodeURIComponent(currentEntry.url ? currentEntry.url : currentEntry.path) ++ encodeURIComponent(+ currentEntry.url ? currentEntry.url : currentEntry.path+ ) +'&locale=' +i18n.language;}@@ -920,13 +974,13 @@ class EntryContainer extends React.Component<Props, State> {handlers={{closeViewer: this.startClosingFile,saveDocument: this.startSavingFile,- editDocument: this.editFile,+ editDocument: this.editFile// reloadDocument: this.reloadDocument,}}keyMap={{closeViewer: keyBindings.closeViewer,saveDocument: keyBindings.saveDocument,- editDocument: keyBindings.editDocument,+ editDocument: keyBindings.editDocument// reloadDocument: settings.keyBindings.reloadDocument,}}>@@ -979,8 +1033,20 @@ class EntryContainer extends React.Component<Props, State> {onClose={() => {this.setState({ isDeleteEntryModalOpened: false });}}- title={currentEntry && currentEntry.isFile ? i18n.t('core:deleteConfirmationTitle') : i18n.t('core:deleteDirectory')}- content={(currentEntry && currentEntry.isFile) ? i18n.t('core:doYouWantToDeleteFile') : i18n.t('core:deleteDirectoryContentConfirm', { dirPath: currentEntry ? extractDirectoryName(currentEntry.path) : '' })}+ title={+ currentEntry && currentEntry.isFile+ ? i18n.t('core:deleteConfirmationTitle')+ : i18n.t('core:deleteDirectory')+ }+ content={+ currentEntry && currentEntry.isFile+ ? i18n.t('core:doYouWantToDeleteFile')+ : i18n.t('core:deleteDirectoryContentConfirm', {+ dirPath: currentEntry+ ? extractDirectoryName(currentEntry.path)+ : ''+ })+ }confirmCallback={result => {if (result && currentEntry) {this.props.deleteFile(currentEntry.path);@@ -1008,17 +1074,29 @@ class EntryContainer extends React.Component<Props, State> {// minSize={defaultSplitSize}// maxSize={fullSplitSize}// defaultSize={this.state.entryPropertiesSplitSize}- size={(currentEntry && currentEntry.isFile) ? this.state.entryPropertiesSplitSize : '100%'}- minSize={(currentEntry && currentEntry.isFile) ? defaultSplitSize : '100%'}- maxSize={(currentEntry && currentEntry.isFile) ? fullSplitSize : '100%'}- defaultSize={(currentEntry && currentEntry.isFile) ? this.state.entryPropertiesSplitSize : '100%'}+ size={+ currentEntry && currentEntry.isFile+ ? this.state.entryPropertiesSplitSize+ : '100%'+ }+ minSize={+ currentEntry && currentEntry.isFile ? defaultSplitSize : '100%'+ }+ maxSize={currentEntry && currentEntry.isFile ? fullSplitSize : '100%'}+ defaultSize={+ currentEntry && currentEntry.isFile+ ? this.state.entryPropertiesSplitSize+ : '100%'+ }onChange={size => {this.setState({isPropertiesPanelVisible: size > defaultSplitSize,openedSplitSize: size,entryPropertiesSplitSize: size});- bufferedSplitResize(() => this.props.setEntryPropertiesSplitSize(size));+ bufferedSplitResize(() =>+ this.props.setEntryPropertiesSplitSize(size)+ );}}>{currentEntry ? (@@ -1038,7 +1116,9 @@ class EntryContainer extends React.Component<Props, State> {>{extractFileExtension(currentEntry.path)}</div>- {currentEntry.changed ? String.fromCharCode(0x25cf) + ' ' : ''}+ {currentEntry.changed+ ? String.fromCharCode(0x25cf) + ' '+ : ''}{fileTitle}</Button>) : (@@ -1061,7 +1141,7 @@ class EntryContainer extends React.Component<Props, State> {</Button>)}</div>- {(this.state.editingSupported && currentEntry.editMode) && (+ {this.state.editingSupported && currentEntry.editMode && (<div className={classes.entryCloseSection}><IconButtondisabled={false}@@ -1089,7 +1169,7 @@ class EntryContainer extends React.Component<Props, State> {</IconButton></div>)}- {(this.state.editingSupported && !currentEntry.editMode) && (+ {this.state.editingSupported && !currentEntry.editMode && (<div className={classes.entryCloseSection}>{/* <IconButtondisabled={false}@@ -1122,7 +1202,7 @@ class EntryContainer extends React.Component<Props, State> {</IconButton></div>)}- {(!this.state.editingSupported) && (+ {!this.state.editingSupported && (<div className={classes.entryCloseSection}><IconButtononClick={this.startClosingFile}@@ -1136,9 +1216,9 @@ class EntryContainer extends React.Component<Props, State> {)}</div><div className={classes.entryProperties}>- { currentEntry.isFile ?- this.renderFileToolbar(classes) : this.renderFolderToolbar()- }+ {currentEntry.isFile+ ? this.renderFileToolbar(classes)+ : this.renderFolderToolbar()}<EntryPropertieskey={this.state.EntryPropertiesKey}resetState={this.resetState}@@ -1151,7 +1231,9 @@ class EntryContainer extends React.Component<Props, State> {settings={this.props.settings}deleteFile={this.props.deleteFile}shouldCopyFile={this.state.shouldCopyFile}- normalizeShouldCopyFile={() => this.setState({ shouldCopyFile: false })}+ normalizeShouldCopyFile={() =>+ this.setState({ shouldCopyFile: false })+ }addTags={this.props.addTags}removeTags={this.props.removeTags}removeAllTags={this.props.removeAllTags}@@ -1162,7 +1244,9 @@ class EntryContainer extends React.Component<Props, State> {/></div></div>- ) : <div>{i18n.t('core:noEntrySelected')}</div> }+ ) : (+ <div>{i18n.t('core:noEntrySelected')}</div>+ )}<divref={element => {this.fileViewerContainer = element;@@ -1197,34 +1281,38 @@ function mapStateToProps(state) {settings: state.settings,isReadOnlyMode: isReadOnlyMode(state),directoryContent: getDirectoryContent(state),- keyBindings: getKeyBindingObject(state),+ keyBindings: getKeyBindingObject(state)};}function mapActionCreatorsToProps(dispatch) {- return bindActionCreators({- setEntryPropertiesSplitSize: SettingsActions.setEntryPropertiesSplitSize,- closeAllFiles: AppActions.closeAllFiles,- renameFile: AppActions.renameFile,- renameDirectory: AppActions.renameDirectory,- openFile: AppActions.openFile,- openFileNatively: AppActions.openFileNatively,- showNotification: AppActions.showNotification,- getNextFile: AppActions.getNextFile,- getPrevFile: AppActions.getPrevFile,- deleteFile: AppActions.deleteFile,- toggleEntryFullWidth: AppActions.toggleEntryFullWidth,- addTags: TaggingActions.addTags,- removeTags: TaggingActions.removeTags,- removeAllTags: TaggingActions.removeAllTags,- editTagForEntry: TaggingActions.editTagForEntry,- reflectUpdateSidecarMeta: AppActions.reflectUpdateSidecarMeta,- updateThumbnailUrl: AppActions.updateThumbnailUrl,- setLastSelectedEntry: AppActions.setLastSelectedEntry,- setSelectedEntries: AppActions.setSelectedEntries,- }, dispatch);+ return bindActionCreators(+ {+ setEntryPropertiesSplitSize: SettingsActions.setEntryPropertiesSplitSize,+ closeAllFiles: AppActions.closeAllFiles,+ renameFile: AppActions.renameFile,+ renameDirectory: AppActions.renameDirectory,+ openFile: AppActions.openFile,+ openFileNatively: AppActions.openFileNatively,+ showNotification: AppActions.showNotification,+ getNextFile: AppActions.getNextFile,+ getPrevFile: AppActions.getPrevFile,+ deleteFile: AppActions.deleteFile,+ toggleEntryFullWidth: AppActions.toggleEntryFullWidth,+ addTags: TaggingActions.addTags,+ removeTags: TaggingActions.removeTags,+ removeAllTags: TaggingActions.removeAllTags,+ editTagForEntry: TaggingActions.editTagForEntry,+ reflectUpdateSidecarMeta: AppActions.reflectUpdateSidecarMeta,+ updateThumbnailUrl: AppActions.updateThumbnailUrl,+ setLastSelectedEntry: AppActions.setLastSelectedEntry,+ setSelectedEntries: AppActions.setSelectedEntries+ },+ dispatch+ );}-export default connect(mapStateToProps, mapActionCreatorsToProps)(- withStyles(styles, { withTheme: true })(EntryContainer)-);+export default connect(+ mapStateToProps,+ mapActionCreatorsToProps+)(withStyles(styles, { withTheme: true })(EntryContainer));diff --git a/app/components/EntryProperties.js b/app/components/EntryProperties.jsindex 07596b106..8550611af 100644--- a/app/components/EntryProperties.js+++ b/app/components/EntryProperties.js@@ -38,15 +38,22 @@ import MoveCopyFilesDialog from './dialogs/MoveCopyFilesDialog';import i18n from '../services/i18n';import { getAllPropertiesPromise } from '../services/utils-io';import { formatFileSize } from '../utils/misc';-import { extractContainingDirectoryPath, getThumbFileLocationForFile } from '../utils/paths';+import {+ extractContainingDirectoryPath,+ getThumbFileLocationForFile+} from '../utils/paths';import AppConfig from '../config';import { Pro } from '../pro';import TagsSelect from './TagsSelect';import TransparentBackground from './TransparentBackground';-import { replaceThumbnailURLPromise, getThumbnailURLPromise } from '../services/thumbsgenerator';+import {+ replaceThumbnailURLPromise,+ getThumbnailURLPromise+} from '../services/thumbsgenerator';// import { actions as AppActions } from '../reducers/app';-const ThumbnailChooserDialog = Pro && Pro.UI ? Pro.UI.ThumbnailChooserDialog : false;+const ThumbnailChooserDialog =+ Pro && Pro.UI ? Pro.UI.ThumbnailChooserDialog : false;const styles = theme => ({entryProperties: {@@ -105,7 +112,7 @@ const styles = theme => ({position: 'relative',padding: '8px 12px 6px 8px',margin: '0 10px 0 0',- cursor: 'pointer',+ cursor: 'pointer'},buttonIcon: {cursor: 'pointer'@@ -135,7 +142,8 @@ const styles = theme => ({const customRenderer = new marked.Renderer();// customRenderer.link = (href, title, text) => `<a href="javascript:window.open('${href}', '_blank', 'nodeIntegration=no')" target="_blank">${text}</a>`;-customRenderer.link = (href, title, text) => `<a href="#" onClick="event.preventDefault();event.stopPropagation(); window.open('${href}', '_blank', 'nodeIntegration=no');return false;">${text}</a>`;+customRenderer.link = (href, title, text) =>+ `<a href="#" onClick="event.preventDefault();event.stopPropagation(); window.open('${href}', '_blank', 'nodeIntegration=no');return false;">${text}</a>`;marked.setOptions({renderer: customRenderer,@@ -227,29 +235,34 @@ class EntryProperties extends Component<Props, State> {}}- loadEntryProperties = (entryPath) => {- getAllPropertiesPromise(entryPath).then(entryProps => {- this.setState({- isEditName: false,- name: entryProps.name,- path: entryProps.path,- size: entryProps.size,- tags: entryProps.tags,- ldtm: entryProps.lmdt ? new Date(entryProps.lmdt)- .toISOString()- .substring(0, 19)- .split('T')- .join(' ') : '',- color: entryProps.color,- isFile: entryProps.isFile,- description: entryProps.description ? entryProps.description : ''- });- return true;- })+ loadEntryProperties = entryPath => {+ getAllPropertiesPromise(entryPath)+ .then(entryProps => {+ this.setState({+ isEditName: false,+ name: entryProps.name,+ path: entryProps.path,+ size: entryProps.size,+ tags: entryProps.tags,+ ldtm: entryProps.lmdt+ ? new Date(entryProps.lmdt)+ .toISOString()+ .substring(0, 19)+ .split('T')+ .join(' ')+ : '',+ color: entryProps.color,+ isFile: entryProps.isFile,+ description: entryProps.description ? entryProps.description : ''+ });+ return true;+ }).catch(error =>- console.warn('Error getting properties for entry: ' + entryPath + ' - ' + error)+ console.warn(+ 'Error getting properties for entry: ' + entryPath + ' - ' + error+ ));- }+ };renameEntry = () => {if (this.state.isEditName) {@@ -283,32 +296,40 @@ class EntryProperties extends Component<Props, State> {return;}if (this.state.isEditName) {- this.setState({- isEditName: false,- name: this.state.originalName- }, () => {- this.props.setPropertiesEditMode(false);- });+ this.setState(+ {+ isEditName: false,+ name: this.state.originalName+ },+ () => {+ this.props.setPropertiesEditMode(false);+ }+ );} else {- this.setState({- isEditName: true,- originalName: this.state.name- }, () => {- this.fileName.focus();- this.props.setPropertiesEditMode(true);- const { originalName } = this.state;- if (originalName) {- const indexOfBracket = originalName.indexOf(AppConfig.beginTagContainer);- const indexOfDot = originalName.indexOf('.');- let endRange = originalName.length;- if (indexOfBracket > 0) {- endRange = indexOfBracket;- } else if (indexOfDot > 0) {- endRange = indexOfDot;+ this.setState(+ {+ isEditName: true,+ originalName: this.state.name+ },+ () => {+ this.fileName.focus();+ this.props.setPropertiesEditMode(true);+ const { originalName } = this.state;+ if (originalName) {+ const indexOfBracket = originalName.indexOf(+ AppConfig.beginTagContainer+ );+ const indexOfDot = originalName.indexOf('.');+ let endRange = originalName.length;+ if (indexOfBracket > 0) {+ endRange = indexOfBracket;+ } else if (indexOfDot > 0) {+ endRange = indexOfDot;+ }+ this.fileName.setSelectionRange(0, endRange);}- this.fileName.setSelectionRange(0, endRange);}- });+ );}};@@ -320,7 +341,9 @@ class EntryProperties extends Component<Props, State> {return;}if (!Pro) {- this.props.showNotification(i18n.t('core:thisFunctionalityIsAvailableInPro'));+ this.props.showNotification(+ i18n.t('core:thisFunctionalityIsAvailableInPro')+ );return;}if (!Pro.MetaOperations) {@@ -328,30 +351,44 @@ class EntryProperties extends Component<Props, State> {return;}if (this.state.isEditDescription) {- Pro.MetaOperations.saveDescription(this.props.entryPath, this.state.description).then((entryMeta) => {- this.setState({- isEditDescription: false- }, () => {- this.props.setPropertiesEditMode(false);- this.props.reflectUpdateSidecarMeta(this.props.entryPath, entryMeta);- });- return true;- }).catch((error) => {- console.warn('Error saving description ' + error);- this.setState({- isEditDescription: false+ Pro.MetaOperations.saveDescription(+ this.props.entryPath,+ this.state.description+ )+ .then(entryMeta => {+ this.setState(+ {+ isEditDescription: false+ },+ () => {+ this.props.setPropertiesEditMode(false);+ this.props.reflectUpdateSidecarMeta(+ this.props.entryPath,+ entryMeta+ );+ }+ );+ return true;+ })+ .catch(error => {+ console.warn('Error saving description ' + error);+ this.setState({+ isEditDescription: false+ });+ this.props.showNotification(i18n.t('Error saving description'));});- this.props.showNotification(i18n.t('Error saving description'));- });} else {- this.setState({- isEditDescription: true- }, () => {- this.props.setPropertiesEditMode(true);- if (this.fileDescription) {- this.fileDescription.focus();+ this.setState(+ {+ isEditDescription: true+ },+ () => {+ this.props.setPropertiesEditMode(true);+ if (this.fileDescription) {+ this.fileDescription.focus();+ }}- });+ );}};@@ -369,33 +406,35 @@ class EntryProperties extends Component<Props, State> {this.props.showNotification(i18n.t('core:needProVersion'));return true;}- this.setState(- ({ isFileThumbChooseDialogOpened }) => ({- isFileThumbChooseDialogOpened: !isFileThumbChooseDialogOpened- })- );+ this.setState(({ isFileThumbChooseDialogOpened }) => ({+ isFileThumbChooseDialogOpened: !isFileThumbChooseDialogOpened+ }));};setThumb = (filePath, thumbFilePath) => {if (filePath !== undefined) {- return replaceThumbnailURLPromise(filePath, thumbFilePath).then((objUrl) => {+ return replaceThumbnailURLPromise(filePath, thumbFilePath)+ .then(objUrl => {+ this.setState({ thumbPath: objUrl.tmbPath });+ this.props.updateThumbnailUrl(this.props.entryPath, objUrl.tmbPath);+ return true;+ })+ .catch(err => {+ console.warn('Error replaceThumbnailURLPromise ' + err);+ this.props.showNotification('Error replace Thumbnail');+ });+ }+ // reset Thumbnail+ return getThumbnailURLPromise(this.props.entryPath)+ .then(objUrl => {this.setState({ thumbPath: objUrl.tmbPath });this.props.updateThumbnailUrl(this.props.entryPath, objUrl.tmbPath);return true;- }).catch(err => {- console.warn('Error replaceThumbnailURLPromise ' + err);- this.props.showNotification('Error replace Thumbnail');+ })+ .catch(err => {+ console.warn('Error getThumbnailURLPromise ' + err);+ this.props.showNotification('Error reset Thumbnail');});- }- // reset Thumbnail- return getThumbnailURLPromise(this.props.entryPath).then((objUrl) => {- this.setState({ thumbPath: objUrl.tmbPath });- this.props.updateThumbnailUrl(this.props.entryPath, objUrl.tmbPath);- return true;- }).catch(err => {- console.warn('Error getThumbnailURLPromise ' + err);- this.props.showNotification('Error reset Thumbnail');- });};saveEditDescription = () => {@@ -407,7 +446,9 @@ class EntryProperties extends Component<Props, State> {return;}if (!Pro) {- this.props.showNotification(i18n.t('core:thisFunctionalityIsAvailableInPro'));+ this.props.showNotification(+ i18n.t('core:thisFunctionalityIsAvailableInPro')+ );return;}if (!Pro.MetaOperations) {@@ -421,13 +462,15 @@ class EntryProperties extends Component<Props, State> {handleChangeColor = color => {this.setState({ color }, () => {- Pro.MetaOperations.saveColor(this.props.entryPath, this.state.color).then((entryMeta) => {- this.props.reflectUpdateSidecarMeta(this.props.entryPath, entryMeta);- return true;- }).catch((error) => {- console.warn('Error saving color for folder ' + error);- this.props.showNotification(i18n.t('Error saving color for folder'));- });+ Pro.MetaOperations.saveColor(this.props.entryPath, this.state.color)+ .then(entryMeta => {+ this.props.reflectUpdateSidecarMeta(this.props.entryPath, entryMeta);+ return true;+ })+ .catch(error => {+ console.warn('Error saving color for folder ' + error);+ this.props.showNotification(i18n.t('Error saving color for folder'));+ });});};@@ -452,10 +495,11 @@ class EntryProperties extends Component<Props, State> {handleChange = (name, value, action) => {if (action === 'remove-value') {- if (!value) { // no tags left in the select element+ if (!value) {+ // no tags left in the select elementthis.props.removeAllTags([this.state.path]);} else {- this.state.tags.map((tag) => {+ this.state.tags.map(tag => {if (value.findIndex(obj => obj.title === tag.title) === -1) {this.props.removeTags([this.state.path], [tag]);}@@ -464,8 +508,9 @@ class EntryProperties extends Component<Props, State> {}} else if (action === 'clear') {this.props.removeAllTags([this.state.path]);- } else { // create-option or select-option- value.map((tag) => {+ } else {+ // create-option or select-option+ value.map(tag => {if (this.state.tags.findIndex(obj => obj.title === tag.title) === -1) {this.props.addTags([this.state.path], [tag]);}@@ -509,14 +554,17 @@ class EntryProperties extends Component<Props, State> {if (this.state.isFile) {thumbPath = getThumbFileLocationForFile(path);} else {- thumbPath = path ++ thumbPath =+ path +AppConfig.dirSeparator +AppConfig.metaFolder +AppConfig.dirSeparator +AppConfig.folderThumbFile;}}- let thumbPathUrl = thumbPath ? 'url("' + thumbPath + '?' + new Date().getTime() + '")' : '';+ let thumbPathUrl = thumbPath+ ? 'url("' + thumbPath + '?' + new Date().getTime() + '")'+ : '';if (AppConfig.isWin) {thumbPathUrl = thumbPathUrl.split('\\').join('\\\\');}@@ -528,7 +576,11 @@ class EntryProperties extends Component<Props, State> {<div className={classes.entryItem}><div className={classes.fluidGrid}><div className="grid-item">- <Typography variant="caption" className={classes.header} style={{ display: 'block' }}>+ <Typography+ variant="caption"+ className={classes.header}+ style={{ display: 'block' }}+ >{i18n.t('core:editTagMasterName')}</Typography></div>@@ -576,7 +628,9 @@ class EntryProperties extends Component<Props, State> {fullWidth={true}data-tid="fileNameProperties"value={name}- inputRef={(ref) => { this.fileName = ref; }}+ inputRef={ref => {+ this.fileName = ref;+ }}className={classes.field}onClick={() => {if (!isEditName) {@@ -597,21 +651,34 @@ class EntryProperties extends Component<Props, State> {<div className={classes.entryItem}><div className={classes.fluidGrid}><div className="grid-item">- <Typography variant="caption" className={classes.header} style={{ display: 'block' }}>+ <Typography+ variant="caption"+ className={classes.header}+ style={{ display: 'block' }}+ >{i18n.t('core:fileTags')}</Typography></div><div className="grid-item" /></div><TagDropContainer entryPath={path}>- <TagsSelect placeholderText={i18n.t('core:dropHere')} isReadOnlyMode={isReadOnlyMode} tags={tags} handleChange={this.handleChange} />+ <TagsSelect+ placeholderText={i18n.t('core:dropHere')}+ isReadOnlyMode={isReadOnlyMode}+ tags={tags}+ handleChange={this.handleChange}+ /></TagDropContainer></div><div className={classes.entryItem}><div className={classes.fluidGrid}><div className="grid-item">- <Typography variant="caption" className={classNames(classes.header, classes.header)} style={{ display: 'block' }}>+ <Typography+ variant="caption"+ className={classNames(classes.header, classes.header)}+ style={{ display: 'block' }}+ >{i18n.t('core:filePropertiesDescription')}</Typography></div>@@ -645,7 +712,9 @@ class EntryProperties extends Component<Props, State> {{isEditDescription ? (<TextFieldmultiline- inputRef={(ref) => { this.fileDescription = ref; }}+ inputRef={ref => {+ this.fileDescription = ref;+ }}disabled={!isEditDescription}id="textarea"placeholder=""@@ -670,7 +739,9 @@ class EntryProperties extends Component<Props, State> {__html:description !== ''? marked(DOMPurify.sanitize(description))- : Pro ? 'Click to add description' : i18n.t('core:addDescription')+ : Pro+ ? 'Click to add description'+ : i18n.t('core:addDescription')}}onClick={() => {if (!isEditDescription) {@@ -707,7 +778,7 @@ class EntryProperties extends Component<Props, State> {</FormControl></div>- { isFile ? (+ {isFile ? (<div className="grid-item" style={{ width: '50%' }}><Typographyvariant="caption"@@ -741,10 +812,7 @@ class EntryProperties extends Component<Props, State> {>{i18n.t('core:changeBackgroundColor')}</Typography>- <FormControl- fullWidth={true}- className={classes.formControl}- >+ <FormControl fullWidth={true} className={classes.formControl}><TransparentBackground><ButtonfullWidth={true}@@ -753,7 +821,7 @@ class EntryProperties extends Component<Props, State> {classes.button].join(' ')}style={{- backgroundColor: color,+ backgroundColor: color}}onClick={this.toggleBackgroundColorPicker}/>@@ -763,10 +831,27 @@ class EntryProperties extends Component<Props, State> {setColor={this.handleChangeColor}onClose={this.toggleBackgroundColorPicker}presetColors={[- '#FFFFFF44', '#00000044', '#ac725e44', '#f83a2244', '#fa573c44',- '#ff753744', '#ffad4644', '#42d69244', '#00800044', '#7bd14844',- '#fad16544', '#92e1c044', '#9fe1e744', '#9fc6e744', '#4986e744',- '#9a9cff44', '#c2c2c244', '#cca6ac44', '#f691b244', '#cd74e644', '#a47ae244'+ '#FFFFFF44',+ '#00000044',+ '#ac725e44',+ '#f83a2244',+ '#fa573c44',+ '#ff753744',+ '#ffad4644',+ '#42d69244',+ '#00800044',+ '#7bd14844',+ '#fad16544',+ '#92e1c044',+ '#9fe1e744',+ '#9fc6e744',+ '#4986e744',+ '#9a9cff44',+ '#c2c2c244',+ '#cca6ac44',+ '#f691b244',+ '#cd74e644',+ '#a47ae244']}/></TransparentBackground>@@ -778,7 +863,11 @@ class EntryProperties extends Component<Props, State> {<div className={classes.entryItem}><div className={classes.fluidGrid}>- <Typography variant="caption" className={classNames(classes.header)} style={{ display: 'block' }}>+ <Typography+ variant="caption"+ className={classNames(classes.header)}+ style={{ display: 'block' }}+ >{i18n.t('core:filePath')}</Typography>{isFile && !isReadOnlyMode && (@@ -808,7 +897,11 @@ class EntryProperties extends Component<Props, State> {<div className={classes.entryItem}><div className={classes.fluidGrid}>- <Typography variant="caption" className={classNames(classes.header)} style={{ display: 'block' }}>+ <Typography+ variant="caption"+ className={classNames(classes.header)}+ style={{ display: 'block' }}+ >{i18n.t('core:thumbnail')}</Typography>{!isReadOnlyMode && (@@ -838,7 +931,9 @@ class EntryProperties extends Component<Props, State> {/></div></div>- <div className={classes.entryItem}><br /></div>+ <div className={classes.entryItem}>+ <br />+ </div></Grid><EntryTagMenudiff --git a/app/components/FileSourceDnd.js b/app/components/FileSourceDnd.jsindex 312f39e92..c5e2d2ef5 100644--- a/app/components/FileSourceDnd.js+++ b/app/components/FileSourceDnd.js@@ -33,7 +33,7 @@ const boxSource = {return {path: props.children.props.entryPath};- },+ }/* endDrag(props, monitor) {const item = monitor.getItem();@@ -51,9 +51,14 @@ const boxSource = {} */};-const FileSourceDnd = (props: Props) => props.connectDragSource(<span>{props.children}</span>);+const FileSourceDnd = (props: Props) =>+ props.connectDragSource(<span>{props.children}</span>);-export default DragSource(DragItemTypes.FILE, boxSource, (connect, monitor) => ({- connectDragSource: connect.dragSource(),- isDragging: monitor.isDragging()-}))(FileSourceDnd);+export default DragSource(+ DragItemTypes.FILE,+ boxSource,+ (connect, monitor) => ({+ connectDragSource: connect.dragSource(),+ isDragging: monitor.isDragging()+ })+)(FileSourceDnd);diff --git a/app/components/FolderContainer.js b/app/components/FolderContainer.jsindex beba14bed..ceab5b4a1 100644--- a/app/components/FolderContainer.js+++ b/app/components/FolderContainer.js@@ -44,15 +44,16 @@ import {getCurrentLocationPath} from '../reducers/app';import TaggingActions from '../reducers/tagging-actions';-import {- normalizePath,- extractShortDirectoryName-} from '../utils/paths';+import { normalizePath, extractShortDirectoryName } from '../utils/paths';import PlatformIO from '../services/platform-io';import LoadingLazy from '../components/LoadingLazy';import { Pro } from '../pro';-const GridPerspective = React.lazy(() => import(/* webpackChunkName: "GridPerspective" */ '../perspectives/grid-perspective/'));+const GridPerspective = React.lazy(() =>+ import(+ /* webpackChunkName: "GridPerspective" */ '../perspectives/grid-perspective/'+ )+);const GridPerspectiveAsync = props => (<React.Suspense fallback={<LoadingLazy />}><GridPerspective {...props} />@@ -61,7 +62,7 @@ const GridPerspectiveAsync = props => (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 = React.lazy(() => import(/* webpackChunkName: "GalleryPerspective" */ '../node_modules/@tagspaces/pro/modules/perspectives/gallery'));GalleryPerspective = Pro.Perspectives.GalleryPerspective;}const GalleryPerspectiveAsync = props => (@@ -72,7 +73,7 @@ const GalleryPerspectiveAsync = props => (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 = React.lazy(() => import(/* webpackChunkName: "MapiquePerspective" */ '../node_modules/@tagspaces/pro/modules/perspectives/mapique'));MapiquePerspective = Pro.Perspectives.MapiquePerspective;}const MapiquePerspectiveAsync = props => (@@ -83,7 +84,7 @@ const MapiquePerspectiveAsync = props => (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 = React.lazy(() => import(/* webpackChunkName: "TreeVizPerspective" */ '../node_modules/@tagspaces/pro/modules/perspectives/treeviz'));TreeVizPerspective = Pro.Perspectives.TreeVizPerspective;}const TreeVizPerspectiveAsync = props => (@@ -92,7 +93,9 @@ const TreeVizPerspectiveAsync = props => (</React.Suspense>);-const WelcomePanel = React.lazy(() => import(/* webpackChunkName: "WelcomePanel" */ './WelcomePanel'));+const WelcomePanel = React.lazy(() =>+ import(/* webpackChunkName: "WelcomePanel" */ './WelcomePanel')+);const WelcomePanelAsync = props => (<React.Suspense fallback={<LoadingLazy />}><WelcomePanel {...props} />@@ -103,9 +106,15 @@ 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]- },+ 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 => ({@@ -124,7 +133,7 @@ const styles = theme => ({paddingRight: 5,paddingTop: 5,display: 'flex',- justifyContent: 'center',+ justifyContent: 'center'},topPanel: {height: 50,@@ -219,21 +228,37 @@ class FolderContainer extends React.Component<Props, State> {};static getDerivedStateFromProps(nextProps, prevState) {- if (nextProps.currentDirectoryPath && prevState.currentPath !== nextProps.currentDirectoryPath) {+ 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('/'));+ 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('/'));+ 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) {@@ -274,7 +299,7 @@ class FolderContainer extends React.Component<Props, State> {this.setState({currentPerspective: perspectiveId || 'default'});- }+ };togglePerspectiveChooserClose = (event?: Object) => {this.setState({@@ -284,10 +309,11 @@ class FolderContainer extends React.Component<Props, State> {};renderPerspective() {- if (!this.props.currentDirectoryPath || this.props.currentDirectoryPath.length < 2) {- return (- <WelcomePanelAsync />- );+ if (+ !this.props.currentDirectoryPath ||+ this.props.currentDirectoryPath.length < 2+ ) {+ return <WelcomePanelAsync />;} else if (this.state.currentPerspective === 'gallery') {return (<GalleryPerspectiveAsync@@ -352,10 +378,16 @@ class FolderContainer extends React.Component<Props, State> {isDesktopMode,loadParentDirectoryContent} = this.props;- const normalizedCurrentDirPath = normalizePath(currentDirectoryPath.split('\\').join('/'));+ 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;+ searchResultCounterText =+ 'More than ' ++ (maxSearchResults - 1) ++ ' entries found, showing only the first ' ++ maxSearchResults;}return (<div>@@ -365,7 +397,11 @@ class FolderContainer extends React.Component<Props, State> {{isDesktopMode ? (<LocationMenu />) : (- <Button id="mobileMenuButton" style={{ marginLeft: -8 }} onClick={showDrawer}>+ <Button+ id="mobileMenuButton"+ style={{ marginLeft: -8 }}+ onClick={showDrawer}+ ><MenuIcon /></Button>)}@@ -382,29 +418,36 @@ class FolderContainer extends React.Component<Props, State> {<div className={classes.flexMiddle} />{currentDirectoryPath && (<React.Fragment>- {isDesktopMode && this.state.pathParts &&+ {isDesktopMode &&+ this.state.pathParts &&this.state.pathParts.map(pathPart => (<Buttonkey={pathPart}onClick={() => loadDirectoryContent(pathPart)}title={'Navigate to: ' + pathPart}- style={{ paddingLeft: 3, paddingRight: 0, minWidth: 10 }}+ 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>- )}+ {!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>+ )}<Buttondata-tid="folderContainerOpenDirMenu"title={@@ -417,7 +460,8 @@ class FolderContainer extends React.Component<Props, State> {onContextMenu={this.openDirectoryMenu}>{extractShortDirectoryName(- normalizePath(normalizedCurrentDirPath), '/'+ normalizePath(normalizedCurrentDirPath),+ '/')}<MoreVertIcon /></Button>diff --git a/app/components/HelpFeedbackPanel.js b/app/components/HelpFeedbackPanel.jsindex 75e020d81..30f4dba27 100644--- a/app/components/HelpFeedbackPanel.js+++ b/app/components/HelpFeedbackPanel.js@@ -76,16 +76,30 @@ class HelpFeedbackPanel extends React.Component<Props> {return (<div className={classes.panel} style={this.props.style}><CustomLogo />- <Typography className={classNames(classes.panelTitle, classes.header)} type="subtitle1">Help & Feedback</Typography>+ <Typography+ className={classNames(classes.panelTitle, classes.header)}+ type="subtitle1"+ >+ Help & Feedback+ </Typography><div className={classes.helpFeedbackArea}><List dense={false} component="nav" aria-label="main help area">- <ListItem button onClick={toggleAboutDialog} title="Opens the about dialog">+ <ListItem+ button+ onClick={toggleAboutDialog}+ title="Opens the about dialog"+ ><ListItemIcon><AboutIcon /></ListItemIcon><ListItemText primary={i18n.t('core:aboutTitle')} /></ListItem>- <ListItem button onClick={() => openURLExternally(AppConfig.documentationLinks.general)}>+ <ListItem+ button+ onClick={() =>+ openURLExternally(AppConfig.documentationLinks.general)+ }+ ><ListItemIcon><DocumentationIcon /></ListItemIcon>@@ -97,7 +111,11 @@ class HelpFeedbackPanel extends React.Component<Props> {</ListItemIcon><ListItemText primary={i18n.t('core:shortcutKeys')} title="" /></ListItem>- <ListItem button onClick={() => openURLExternally(AppConfig.links.changelogURL)} title="Opens the changelog of the app">+ <ListItem+ button+ onClick={() => openURLExternally(AppConfig.links.changelogURL)}+ title="Opens the changelog of the app"+ ><ListItemIcon><ChangeLogIcon /></ListItemIcon>@@ -109,109 +127,140 @@ class HelpFeedbackPanel extends React.Component<Props> {</ListItemIcon><ListItemText primary={i18n.t('core:onboardingWizard')} /></ListItem>- <ListItem button onClick={() => openURLExternally(AppConfig.links.webClipper)}>+ <ListItem+ button+ onClick={() => openURLExternally(AppConfig.links.webClipper)}+ ><ListItemIcon><WebClipperIcon /></ListItemIcon><ListItemText primary={i18n.t('core:webClipper')} /></ListItem><Divider />- <ListItem button onClick={() => openURLExternally(AppConfig.links.suggestFeature)}>+ <ListItem+ button+ onClick={() => openURLExternally(AppConfig.links.suggestFeature)}+ ><ListItemIcon><NewFeatureIcon /></ListItemIcon><ListItemText primary={i18n.t('core:suggestNewFeatures')} /></ListItem>- <ListItem button onClick={() => openURLExternally(AppConfig.links.reportIssue)}>+ <ListItem+ button+ onClick={() => openURLExternally(AppConfig.links.reportIssue)}+ ><ListItemIcon><IssueIcon /></ListItemIcon><ListItemText primary={i18n.t('core:reportIssues')} /></ListItem>- <ListItem button onClick={() => openURLExternally(AppConfig.links.helpTranslating)}>+ <ListItem+ button+ onClick={() => openURLExternally(AppConfig.links.helpTranslating)}+ ><ListItemIcon><TranslationIcon /></ListItemIcon><ListItemText primary={i18n.t('core:helpWithTranslation')} /></ListItem><Divider />- <ListItem button onClick={() => openFileNatively(AppConfig.links.emailContact)}>+ <ListItem+ button+ onClick={() => openFileNatively(AppConfig.links.emailContact)}+ ><ListItemIcon><EmailIcon /></ListItemIcon><ListItemText primary={i18n.t('core:emailContact')} /></ListItem>- <ListItem button onClick={() => openURLExternally(AppConfig.links.twitter)}>+ <ListItem+ button+ onClick={() => openURLExternally(AppConfig.links.twitter)}+ ><ListItemIcon><Social2Icon /></ListItemIcon><ListItemText primary={i18n.t('core:followOnTwitter')} /></ListItem>- <ListItem button onClick={() => openURLExternally(AppConfig.links.facebook)}>+ <ListItem+ button+ onClick={() => openURLExternally(AppConfig.links.facebook)}+ ><ListItemIcon><SocialIcon /></ListItemIcon><ListItemText primary={i18n.t('core:likeUsOnFacebook')} /></ListItem>- {Pro && <React.Fragment>- <Divider />- <ListItem button onClick={toggleProTeaser}>- <ListItemIcon>- <ProTeaserIcon />- </ListItemIcon>- <ListItemText primary="TagSpaces Pro Overview" />- </ListItem>- </React.Fragment>}+ {Pro && (+ <React.Fragment>+ <Divider />+ <ListItem button onClick={toggleProTeaser}>+ <ListItemIcon>+ <ProTeaserIcon />+ </ListItemIcon>+ <ListItemText primary="TagSpaces Pro Overview" />+ </ListItem>+ </React.Fragment>+ )}</List>- {!Pro && <React.Fragment>- {/* <Divider /> */}- <div- onClick={toggleProTeaser}- role="button"- tabIndex="0"- style={{- backgroundColor: 'rgba(29, 209, 159, 0.08)',- textAlign: 'center'- }}- >- <CardContent+ {!Pro && (+ <React.Fragment>+ {/* <Divider /> */}+ <div+ onClick={toggleProTeaser}+ role="button"+ tabIndex="0"style={{- paddingBottom: 0+ backgroundColor: 'rgba(29, 209, 159, 0.08)',+ textAlign: 'center'}}>- <Typography color="textSecondary" gutterBottom>- Achieve more with- </Typography>- <Typography variant="h6" component="h2" color="textPrimary">- TagSpaces Pro- </Typography>- <img- style={{ maxHeight: 80, marginTop: 10 }}- src={ProTeaser}- alt=""- />- </CardContent>- <CardActions style={{ flexDirection: 'row', justifyContent: 'center' }}>- <Button- size="small"- onClick={(event: any) => {- event.preventDefault();- event.stopPropagation();- toggleProTeaser();- }}- >Learn More</Button>- <Button- size="small"- onClick={(event: any) => {- event.preventDefault();- event.stopPropagation();- openURLExternally(AppConfig.links.productsOverview);+ <CardContent+ style={{+ paddingBottom: 0}}- >Get It</Button>- </CardActions>- </div>- {/* <Divider /> */}- </React.Fragment>}+ >+ <Typography color="textSecondary" gutterBottom>+ Achieve more with+ </Typography>+ <Typography variant="h6" component="h2" color="textPrimary">+ TagSpaces Pro+ </Typography>+ <img+ style={{ maxHeight: 80, marginTop: 10 }}+ src={ProTeaser}+ alt=""+ />+ </CardContent>+ <CardActions+ style={{ flexDirection: 'row', justifyContent: 'center' }}+ >+ <Button+ size="small"+ onClick={(event: any) => {+ event.preventDefault();+ event.stopPropagation();+ toggleProTeaser();+ }}+ >+ Learn More+ </Button>+ <Button+ size="small"+ onClick={(event: any) => {+ event.preventDefault();+ event.stopPropagation();+ openURLExternally(AppConfig.links.productsOverview);+ }}+ >+ Get It+ </Button>+ </CardActions>+ </div>+ {/* <Divider /> */}+ </React.Fragment>+ )}</div></div>);diff --git a/app/components/LoadingLazy.js b/app/components/LoadingLazy.jsindex 274d18380..9d47e05f5 100644--- a/app/components/LoadingLazy.js+++ b/app/components/LoadingLazy.js@@ -22,5 +22,7 @@ import React from 'react';// {i18n.t('core:loading')}// <div style={{ padding: 10, backgroundColor: 'transparent' }}>...</div>-const LoadingLazy = () => (<div style={{ width: 1, height: 1, backgroundColor: 'transparent' }}>...</div>);+const LoadingLazy = () => (+ <div style={{ width: 1, height: 1, backgroundColor: 'transparent' }}>...</div>+);export default LoadingLazy;diff --git a/app/components/LoadingScreen.js b/app/components/LoadingScreen.jsindex 305ac4d15..9a4437f37 100644--- a/app/components/LoadingScreen.js+++ b/app/components/LoadingScreen.js@@ -1,7 +1,5 @@import React from 'react';-const LoadingScreen = () => (- <div id="loadingLogo">Loading ...</div>-);+const LoadingScreen = () => <div id="loadingLogo">Loading ...</div>;export default LoadingScreen;diff --git a/app/components/LocationManager.js b/app/components/LocationManager.jsindex 93b9a83a1..8cbde5815 100644--- a/app/components/LocationManager.js+++ b/app/components/LocationManager.js@@ -61,9 +61,16 @@ import {locationType,type Location} from '../reducers/locations';-import { actions as AppActions, getCurrentLocationId, isReadOnlyMode } from '../reducers/app';+import {+ actions as AppActions,+ getCurrentLocationId,+ isReadOnlyMode+} from '../reducers/app';import { actions as LocationIndexActions } from '../reducers/location-index';-import { getPerspectives, getShowUnixHiddenEntries } from '../reducers/settings';+import {+ getPerspectives,+ getShowUnixHiddenEntries+} from '../reducers/settings';import i18n from '../services/i18n';import { isObj } from '../utils/misc';import AppConfig from '../config';@@ -119,7 +126,7 @@ type State = {isSelectDirectoryDialogOpened?: boolean,isCreateDirectoryDialogOpened?: boolean,createLocationDialogKey: string,- isCreateDirectoryDialogOpened?: boolean,+ isCreateDirectoryDialogOpened?: boolean,locationManagerMenuOpened: boolean,locationManagerMenuAnchorEl: Object | null,dirs?: Object@@ -146,7 +153,7 @@ class LocationManager extends React.Component<Props, State> {isEditLocationDialogOpened: false,isDeleteLocationDialogOpened: false,isCreateDirectoryDialogOpened: false,- isSelectDirectoryDialogOpened: false,+ isSelectDirectoryDialogOpened: false,locationManagerMenuOpened: false,locationManagerMenuAnchorEl: null,createLocationDialogKey: uuidv1(),@@ -159,15 +166,18 @@ class LocationManager extends React.Component<Props, State> {const devicePaths = PlatformIO.getDevicePaths();Object.keys(devicePaths).forEach(key => {- this.props.addLocation({- uuid: uuidv1(),- type: locationType.TYPE_LOCAL,- name: key, // TODO use i18n- paths: [devicePaths[key]],- isDefault: (AppConfig.isWeb && devicePaths[key] === '/files/'), // Used for the web ts demo- isReadOnly: false,- persistIndex: false- }, false);+ this.props.addLocation(+ {+ uuid: uuidv1(),+ type: locationType.TYPE_LOCAL,+ name: key, // TODO use i18n+ paths: [devicePaths[key]],+ isDefault: AppConfig.isWeb && devicePaths[key] === '/files/', // Used for the web ts demo+ isReadOnly: false,+ persistIndex: false+ },+ false+ );});}}@@ -176,35 +186,38 @@ class LocationManager extends React.Component<Props, State> {const subFolder = {uuid: location.uuid,name: location.name,- path: location.path || location.paths[0],+ path: location.path || location.paths[0]};- this.getDirectoriesTree(subFolder, deepLevel).then(children => {- if (children instanceof Array) {- if (location.uuid) {- const dirsTree = {}; // this.state.dirs; (uncomment to allow open multiple Locations folders) //TODO set settings for this- if (location.path === undefined) { // location- dirsTree[location.uuid] = children;- } else {- const dirsCopy = this.getMergedDirsCopy(location.path, children);- if (dirsCopy) {- dirsTree[location.uuid] = dirsCopy;+ this.getDirectoriesTree(subFolder, deepLevel)+ .then(children => {+ if (children instanceof Array) {+ if (location.uuid) {+ const dirsTree = {}; // this.state.dirs; (uncomment to allow open multiple Locations folders) //TODO set settings for this+ if (location.path === undefined) {+ // location+ dirsTree[location.uuid] = children;} else {- // eslint-disable-next-line no-param-reassign- location.children = children;- dirsTree[location.uuid] = [location];+ const dirsCopy = this.getMergedDirsCopy(location.path, children);+ if (dirsCopy) {+ dirsTree[location.uuid] = dirsCopy;+ } else {+ // eslint-disable-next-line no-param-reassign+ location.children = children;+ dirsTree[location.uuid] = [location];+ }}+ this.setState({+ dirs: dirsTree+ });}+ } else if (location.path === undefined) {+ // if is Locationthis.setState({- dirs: dirsTree+ dirs: {}});}- } else if (location.path === undefined) { // if is Location- this.setState({- dirs: {}- });- }- return true;- })+ return true;+ }).catch(error => {console.log('loadSubDirectories', error);});@@ -216,9 +229,11 @@ class LocationManager extends React.Component<Props, State> {.then(dirEntries => {const directoryContent = [];dirEntries.map(entry => {- if (entry.name === AppConfig.metaFolder- || entry.name.endsWith('/' + AppConfig.metaFolder)- || (!this.props.showUnixHiddenEntries && entry.name.startsWith('.'))) {+ if (+ entry.name === AppConfig.metaFolder ||+ entry.name.endsWith('/' + AppConfig.metaFolder) ||+ (!this.props.showUnixHiddenEntries && entry.name.startsWith('.'))+ ) {return true;}// const enhancedEntry = enhanceEntry(entry);@@ -234,7 +249,11 @@ class LocationManager extends React.Component<Props, State> {subFolder.children = directoryContent;if (deepLevel > 0) {const promisesArr = [];- directoryContent.map(directory => promisesArr.push(this.getDirectoriesTree(directory, deepLevel - 1)));+ directoryContent.map(directory =>+ promisesArr.push(+ this.getDirectoriesTree(directory, deepLevel - 1)+ )+ );return Promise.all(promisesArr);}}@@ -242,8 +261,7 @@ class LocationManager extends React.Component<Props, State> {}).catch(error => {console.log('getDirectoriesTree', error);- })- ;+ });/*** https://codereview.stackexchange.com/questions/47932/recursion-vs-iteration-of-tree-structure@@ -261,11 +279,13 @@ class LocationManager extends React.Component<Props, State> {return copyObj;}if (arrSubDirs[a].children !== undefined) {- const stack = [{- depth: 0,- element: arrSubDirs[a],- propPath: ''- }];+ const stack = [+ {+ depth: 0,+ element: arrSubDirs[a],+ propPath: ''+ }+ ];let stackItem = 0;let current;let children;@@ -273,7 +293,7 @@ class LocationManager extends React.Component<Props, State> {let stackPath;let propPath = a + '.children';- while (current = stack[stackItem++]) {+ while ((current = stack[stackItem++])) {// get the argumentsstackPath = current.propPath;depth = current.depth;@@ -283,7 +303,12 @@ class LocationManager extends React.Component<Props, State> {const len = children.length;for (let i = 0; i < len; i++) {if (path === children[i].path) {- propPath = propPath + '.' + (stackPath ? stackPath + '.' : '') + i + '.children';+ propPath =+ propPath ++ '.' ++ (stackPath ? stackPath + '.' : '') ++ i ++ '.children';const copyObj = [...this.state.dirs[uuid]];let schema = copyObj; // a moving reference to internal objects within obj@@ -298,7 +323,8 @@ class LocationManager extends React.Component<Props, State> {return copyObj;}- stack.push({ // pass args via object or array+ stack.push({+ // pass args via object or arrayelement: children[i],depth: depth + 1,propPath: (stackPath ? stackPath + '.' : '') + i + '.children'@@ -480,7 +506,7 @@ class LocationManager extends React.Component<Props, State> {}};- resetState = (dialogKey) => {+ resetState = dialogKey => {this.setState({[dialogKey]: uuidv1()});@@ -489,7 +515,10 @@ class LocationManager extends React.Component<Props, State> {renderNameColumnAction = (field, location, key) => {const children = (<span style={{ fontSize: 15, marginLeft: 5 }} title={field}>- <FolderIcon style={{ marginTop: 0, marginBottom: -8 }} className={this.props.classes.icon} />+ <FolderIcon+ style={{ marginTop: 0, marginBottom: -8 }}+ className={this.props.classes.icon}+ />{field && field.length > 25 ? field.substr(0, 25) + '...' : field}{/* <IconButtonstyle={{ float: 'right', paddingTop: 0, paddingBottom: 0, paddingLeft: 0, paddingRight: 0 }}@@ -504,7 +533,7 @@ class LocationManager extends React.Component<Props, State> {);return {children,- props: {},+ props: {}}; // (<span>{ name }</span>);};@@ -514,7 +543,7 @@ class LocationManager extends React.Component<Props, State> {}, */onClick: () => {this.onRowClick(record);- },+ }/* onDoubleClick: (e) => {this.onRowClick(record, index, e);} */@@ -528,7 +557,7 @@ class LocationManager extends React.Component<Props, State> {}};- onRowClick = (subDir) => {+ onRowClick = subDir => {this.loadSubDirectories(subDir, 1);this.props.loadDirectoryContent(subDir.path);};@@ -547,20 +576,24 @@ class LocationManager extends React.Component<Props, State> {);return;}- if (monitor) { // TODO handle monitor -> isOver and change folder icon+ if (monitor) {+ // TODO handle monitor -> isOver and change folder iconconst { path } = monitor.getItem();console.log('Dropped files: ' + path);this.props.moveFiles([path], item.children[1].props.record.path);}};- renderBodyCell = (props) =>- (- <td {...props} style={{ position: 'relative' }} >- <TargetMoveFileBox accepts={[DragItemTypes.FILE]} onDrop={this.handleFileMoveDrop} >{props.children}</TargetMoveFileBox>- </td>- )- ;+ renderBodyCell = props => (+ <td {...props} style={{ position: 'relative' }}>+ <TargetMoveFileBox+ accepts={[DragItemTypes.FILE]}+ onDrop={this.handleFileMoveDrop}+ >+ {props.children}+ </TargetMoveFileBox>+ </td>+ );// <Tooltip id="tooltip-icon" title={i18n.t('core:moreOperations')} placement="bottom"></Tooltip>renderLocation = (location: Location) => {@@ -573,29 +606,31 @@ class LocationManager extends React.Component<Props, State> {key: 'name',width: '80%',render: this.renderNameColumnAction,- onCell: this.handleCellClick,+ onCell: this.handleCellClick}];- table = (<Table- // defaultExpandAllRows- // className={classes.locationListArea}- components={{- // header: { cell: this.renderHeaderRow },- body: { cell: this.renderBodyCell }- }}- showHeader={false}- // className="table"- rowKey="path"- data={this.state.dirs[location.uuid]}- columns={columns}- // expandedRowRender={this.expandedRowRender}- onExpand={this.onExpand}- // expandIcon={this.CustomExpandIcon}- // expandIconAsCell- /* onRow={(record, index) => ({+ table = (+ <Table+ // defaultExpandAllRows+ // className={classes.locationListArea}+ components={{+ // header: { cell: this.renderHeaderRow },+ body: { cell: this.renderBodyCell }+ }}+ showHeader={false}+ // className="table"+ rowKey="path"+ data={this.state.dirs[location.uuid]}+ columns={columns}+ // expandedRowRender={this.expandedRowRender}+ onExpand={this.onExpand}+ // expandIcon={this.CustomExpandIcon}+ // expandIconAsCell+ /* onRow={(record, index) => ({onClick: this.onRowClick.bind(null, record, index),})} */- />);+ />+ );}return (<div key={location.uuid}>@@ -606,10 +641,18 @@ class LocationManager extends React.Component<Props, State> {? this.props.classes.listItemSelected: this.props.classes.listItem}- title={location.isDefault ? i18n.t('core: thisIsStartupLocation') + ' : ' + location.paths[0] : location.paths[0]}+ title={+ location.isDefault+ ? i18n.t('core: thisIsStartupLocation') ++ ' : ' ++ location.paths[0]+ : location.paths[0]+ }buttononClick={() => this.handleLocationClick(location)}- onContextMenu={event => this.handleLocationContextMenuClick(event, location)}+ onContextMenu={event =>+ this.handleLocationContextMenuClick(event, location)+ }><ListItemIcon// onClick={(e) => {@@ -618,10 +661,11 @@ class LocationManager extends React.Component<Props, State> {// }}style={{ minWidth: 'auto' }}>- {location.type === locationType.TYPE_CLOUD ?- (<CloudLocationIcon className={this.props.classes.icon} />) :- (<LocationIcon className={this.props.classes.icon} />)- }+ {location.type === locationType.TYPE_CLOUD ? (+ <CloudLocationIcon className={this.props.classes.icon} />+ ) : (+ <LocationIcon className={this.props.classes.icon} />+ )}</ListItemIcon><div style={{ maxWidth: 250 }}><Typography@@ -641,8 +685,12 @@ class LocationManager extends React.Component<Props, State> {aria-haspopup="true"edge="end"data-tid={'locationMoreButton_' + location.name}- onClick={event => this.handleLocationContextMenuClick(event, location)}- onContextMenu={event => this.handleLocationContextMenuClick(event, location)}+ onClick={event =>+ this.handleLocationContextMenuClick(event, location)+ }+ onContextMenu={event =>+ this.handleLocationContextMenuClick(event, location)+ }>{location.isDefault && (<DefaultLocationIcon data-tid="startupIndication" />@@ -655,17 +703,17 @@ class LocationManager extends React.Component<Props, State> {{table}</div>);- };-- handleLocationManagerMenu = (event: Object) => {- this.setState({+ };++ handleLocationManagerMenu = (event: Object) => {+ this.setState({locationManagerMenuOpened: true,locationManagerMenuAnchorEl: event.currentTarget});};-+handleCloseLocationManagerMenu = () => {- this.setState({ locationManagerMenuOpened: false});+ this.setState({ locationManagerMenuOpened: false });};render() {@@ -674,22 +722,25 @@ class LocationManager extends React.Component<Props, State> {<div className={classes.panel} style={this.props.style}><CustomLogo /><div className={classes.toolbar}>- <Typography className={classNames(classes.panelTitle, classes.header)} type="subtitle1">+ <Typography+ className={classNames(classes.panelTitle, classes.header)}+ type="subtitle1"+ >{i18n.t('core:locationManager')}</Typography><IconButton- data-tid="locationManagerMenu"- onClick={this.handleLocationManagerMenu}- >- <MoreVertIcon />- </IconButton>+ data-tid="locationManagerMenu"+ onClick={this.handleLocationManagerMenu}+ >+ <MoreVertIcon />+ </IconButton></div>- <LocationManagerMenu- anchorEl={this.state.locationManagerMenuAnchorEl}- open={this.state.locationManagerMenuOpened}+ <LocationManagerMenu+ anchorEl={this.state.locationManagerMenuAnchorEl}+ open={this.state.locationManagerMenuOpened}onClose={this.handleCloseLocationManagerMenu}openURLExternally={this.props.openURLExternally}- />+ />{!isLocationsReadOnly && (<div style={{ width: '100%', textAlign: 'center', marginBottom: 10 }}><Button@@ -772,17 +823,16 @@ class LocationManager extends React.Component<Props, State> {</ListItemIcon><ListItemText primary={i18n.t('core:editLocationTitle')} /></MenuItem>- {this.state.selectedLocation && this.props.currentLocationId === this.state.selectedLocation.uuid && (- <MenuItem- data-tid="indexLocation"- onClick={this.indexLocation}- >- <ListItemIcon>- <RefreshIcon />- </ListItemIcon>- <ListItemText primary={i18n.t('core:indexLocation')} />- </MenuItem>- )}+ {this.state.selectedLocation &&+ this.props.currentLocationId ===+ this.state.selectedLocation.uuid && (+ <MenuItem data-tid="indexLocation" onClick={this.indexLocation}>+ <ListItemIcon>+ <RefreshIcon />+ </ListItemIcon>+ <ListItemText primary={i18n.t('core:indexLocation')} />+ </MenuItem>+ )}<MenuItem data-tid="moveLocationUp" onClick={this.moveLocationUp}><ListItemIcon><ArrowUpwardIcon />@@ -816,10 +866,7 @@ class LocationManager extends React.Component<Props, State> {</ListItemIcon><ListItemText primary={i18n.t('core:showInFileManager')} /></MenuItem>- <MenuItem- data-tid="removeLocation"- onClick={this.closeLocation}- >+ <MenuItem data-tid="removeLocation" onClick={this.closeLocation}><ListItemIcon><CloseIcon /></ListItemIcon>@@ -868,22 +915,25 @@ function mapStateToProps(state) {}function mapDispatchToProps(dispatch) {- return bindActionCreators({- ...LocationActions,- openLocation: AppActions.openLocation,- createDirectoryIndex: LocationIndexActions.createDirectoryIndex,- closeLocation: AppActions.closeLocation,- loadDirectoryContent: AppActions.loadDirectoryContent,- reflectCreateEntry: AppActions.reflectCreateEntry,- deleteDirectory: AppActions.deleteDirectory,- openDirectory: AppActions.openDirectory,- showInFileManager: AppActions.showInFileManager,- openFileNatively: AppActions.openFileNatively,- openFile: AppActions.openFile,- showNotification: AppActions.showNotification,- moveFiles: IOActions.moveFiles,- openURLExternally: AppActions.openURLExternally,- }, dispatch);+ return bindActionCreators(+ {+ ...LocationActions,+ openLocation: AppActions.openLocation,+ createDirectoryIndex: LocationIndexActions.createDirectoryIndex,+ closeLocation: AppActions.closeLocation,+ loadDirectoryContent: AppActions.loadDirectoryContent,+ reflectCreateEntry: AppActions.reflectCreateEntry,+ deleteDirectory: AppActions.deleteDirectory,+ openDirectory: AppActions.openDirectory,+ showInFileManager: AppActions.showInFileManager,+ openFileNatively: AppActions.openFileNatively,+ openFile: AppActions.openFile,+ showNotification: AppActions.showNotification,+ moveFiles: IOActions.moveFiles,+ openURLExternally: AppActions.openURLExternally+ },+ dispatch+ );}export default withStyles(styles)(diff --git a/app/components/PerspectiveManager.js b/app/components/PerspectiveManager.jsindex 369b3c29b..5f2b9cad7 100644--- a/app/components/PerspectiveManager.js+++ b/app/components/PerspectiveManager.js@@ -37,7 +37,9 @@ class PerspectiveManager extends React.Component<Props, State> {return (<div className={classes.panel} style={this.props.style}>- <Typography className={classes.panelTitle} type="subtitle1">Perspectives</Typography>+ <Typography className={classes.panelTitle} type="subtitle1">+ Perspectives+ </Typography></div>);}diff --git a/app/components/SidePanels.css.js b/app/components/SidePanels.css.jsindex ddf6af395..721ddf51b 100644--- a/app/components/SidePanels.css.js+++ b/app/components/SidePanels.css.js@@ -18,7 +18,7 @@*/import AppConfig from '../config';-export default (theme) => ({+export default theme => ({panel: {height: '100%',maxHeight: '100%',@@ -89,19 +89,19 @@ export default (theme) => ({textTransform: 'uppercase',flex: 1,paddingLeft: 5,- paddingTop: 12,+ paddingTop: 12},nested: {paddingLeft: theme.spacing(4)},listItemTitleText: {- fontWeight: 'bold',+ fontWeight: 'bold'},hiddenFileInput: {- display: 'none',+ display: 'none'},toolbar: {- display: 'flex',+ display: 'flex'},formControl: {width: '100%',@@ -113,7 +113,7 @@ export default (theme) => ({paddingLeft: 8},leftIcon: {- marginRight: theme.spacing(1),+ marginRight: theme.spacing(1)},badge: {display: 'inline-block',diff --git a/app/components/TagContainer.js b/app/components/TagContainer.jsindex 609f2d500..3cd48db68 100644--- a/app/components/TagContainer.js+++ b/app/components/TagContainer.js@@ -92,9 +92,9 @@ const TagContainer = React.memo((props: Props) => {return false;});- let description = tag.title+ let description = tag.title;if (tag.description) {- description = tag.title + ' - ' + tag.description+ description = tag.title + ' - ' + tag.description;}return (@@ -107,16 +107,26 @@ const TagContainer = React.memo((props: Props) => {const selectedEntryPaths = [];selectedEntries.map(entry => selectedEntryPaths.push(entry.path));addTags(selectedEntryPaths, [tag]);- // Removing tags doesn't seem to work correctly here, yet. Using sidecar tagging, but the removeTagsFromEntry function in tagging.actions.js- // doesn't recignize it correctly, thinking it's a plain tag and thus tries to rename the files- // } else if (event.shiftKey) {- // const selectedEntryPaths = [];- // selectedEntries.map(entry => selectedEntryPaths.push(entry.path));- // removeTags(selectedEntryPaths, [tag]);- } else if (handleTagMenu) { handleTagMenu(event, tag, entryPath || tagGroup); }+ // Removing tags doesn't seem to work correctly here, yet. Using sidecar tagging, but the removeTagsFromEntry function in tagging.actions.js+ // doesn't recignize it correctly, thinking it's a plain tag and thus tries to rename the files+ // } else if (event.shiftKey) {+ // const selectedEntryPaths = [];+ // selectedEntries.map(entry => selectedEntryPaths.push(entry.path));+ // removeTags(selectedEntryPaths, [tag]);+ } else if (handleTagMenu) {+ handleTagMenu(event, tag, entryPath || tagGroup);+ }+ }}+ onContextMenu={event => {+ if (handleTagMenu) {+ handleTagMenu(event, tag, entryPath || tagGroup);+ }+ }}+ onDoubleClick={event => {+ if (handleTagMenu) {+ handleTagMenu(event, tag, entryPath || tagGroup);+ }}}- onContextMenu={event => { if (handleTagMenu) { handleTagMenu(event, tag, entryPath || tagGroup); } }}- onDoubleClick={event => { if (handleTagMenu) { handleTagMenu(event, tag, entryPath || tagGroup); } }}style={{backgroundColor: 'transparent',display: 'inline-block'@@ -163,17 +173,19 @@ const TagContainer = React.memo((props: Props) => {)}{!isGeoTag && title}</span>- {(tagMode === 'remove') ? (deleteIcon || (- <RemoveTagIcon- data-tid={'tagRemoveButton_' + title.replace(/ /g, '_')}- style={{- color: tag.textColor,- fontSize: 20,- marginBottom: -5- }}- onClick={event => handleRemoveTag(event, tag)}- />- )) : (+ {tagMode === 'remove' ? (+ deleteIcon || (+ <RemoveTagIcon+ data-tid={'tagRemoveButton_' + title.replace(/ /g, '_')}+ style={{+ color: tag.textColor,+ fontSize: 20,+ marginBottom: -5+ }}+ onClick={event => handleRemoveTag(event, tag)}+ />+ )+ ) : (<MoreVertIcondata-tid={'tagMoreButton_' + title.replace(/ /g, '_')}style={{@@ -193,7 +205,7 @@ function mapStateToProps(state) {return {allTags: getAllTags(state),defaultBackgroundColor: getTagColor(state),- defaultTextColor: getTagTextColor(state),+ defaultTextColor: getTagTextColor(state)// selectedEntries: getSelectedEntries(state)};}diff --git a/app/components/TagContainerDnd.js b/app/components/TagContainerDnd.jsindex c753b2341..237bfcaba 100644--- a/app/components/TagContainerDnd.js+++ b/app/components/TagContainerDnd.js@@ -40,12 +40,19 @@ const boxSource = {// console.log('DropRESULT: ', dropResult);// console.log('item: ', item);- if (dropResult && dropResult.tagGroupId && dropResult.tagGroupId !== item.sourceTagGroupId && props.moveTag) {+ if (+ dropResult &&+ dropResult.tagGroupId &&+ dropResult.tagGroupId !== item.sourceTagGroupId &&+ props.moveTag+ ) {// console.log(`Dropped ${item.tagId} from ${item.sourceTagGroupId} into ${dropResult.tagGroupId}!`);props.moveTag(item.tagId, item.sourceTagGroupId, dropResult.tagGroupId);} else if (dropResult && dropResult.entryPath && props.addTags) {// console.log(`Dropped item: ${item.tag.title} onto file: ${dropResult.entryPath}!`);- if (props.selectedEntries.some(entry => entry.path === dropResult.entryPath)) {+ if (+ props.selectedEntries.some(entry => entry.path === dropResult.entryPath)+ ) {const selectedEntryPaths = [];props.selectedEntries.map(entry => selectedEntryPaths.push(entry.path));props.addTags(selectedEntryPaths, [item.tag]);@@ -134,7 +141,8 @@ const TagContainerDnd = (props: Props) => {isDragging={isDragging}selectedEntries={selectedEntries}/>- </span>);+ </span>+ );};export default DragSource(DragItemTypes.TAG, boxSource, (connect, monitor) => ({diff --git a/app/components/TagGroupContainer.js b/app/components/TagGroupContainer.jsindex abcad8273..17aeb9272 100644--- a/app/components/TagGroupContainer.js+++ b/app/components/TagGroupContainer.js@@ -31,7 +31,7 @@ type Props = {const boxTarget = {drop(props) {return { tagGroupId: props.taggroup.uuid };- },+ }};const TagGroupContainer = (props: Props) => {@@ -68,6 +68,5 @@ const TagGroupContainer = (props: Props) => {export default DropTarget(DragItemTypes.TAG, boxTarget, (connect, monitor) => ({connectDropTarget: connect.dropTarget(),isOver: monitor.isOver(),- canDrop: monitor.canDrop(),+ canDrop: monitor.canDrop()}))(TagGroupContainer);-diff --git a/app/components/TagLibrary.js b/app/components/TagLibrary.jsindex 30c5e443d..93f5ad163 100644--- a/app/components/TagLibrary.js+++ b/app/components/TagLibrary.js@@ -55,10 +55,15 @@ import {import TaggingActions from '../reducers/tagging-actions';import i18n from '../services/i18n';import { getTagColor, getTagTextColor } from '../reducers/settings';-import { actions as AppActions, getSelectedEntries, isReadOnlyMode } from '../reducers/app';+import {+ actions as AppActions,+ getSelectedEntries,+ isReadOnlyMode+} from '../reducers/app';import SmartTags from '../reducers/smart-tags';-const isTagLibraryReadOnly = (window.ExtTagLibrary && window.ExtTagLibrary.length > 0);+const isTagLibraryReadOnly =+ window.ExtTagLibrary && window.ExtTagLibrary.length > 0;type Props = {classes: Object,@@ -210,7 +215,7 @@ class TagLibrary extends React.Component<Props, State> {this.setState({ tagLibraryMenuOpened: false });};- renderTagGroup = (tagGroup) => {+ renderTagGroup = tagGroup => {const isReadOnly = tagGroup.readOnly || isTagLibraryReadOnly;return (<div key={tagGroup.uuid}>@@ -221,7 +226,9 @@ class TagLibrary extends React.Component<Props, State> {className={this.props.classes.listItem}onClick={event => this.handleTagGroupTitleClick(event, tagGroup)}onContextMenu={event => this.handleTagGroupMenu(event, tagGroup)}- title={'Number of tags in this tag group: ' + tagGroup.children.length}+ title={+ 'Number of tags in this tag group: ' + tagGroup.children.length+ }><ListItemIcon style={{ minWidth: 'auto' }}>{tagGroup.expanded ? <ArrowDownIcon /> : <ArrowRightIcon />}@@ -235,18 +242,24 @@ class TagLibrary extends React.Component<Props, State> {>{tagGroup.title + ' '}{!tagGroup.expanded && (- <span className={this.props.classes.badge}>{tagGroup.children.length}</span>+ <span className={this.props.classes.badge}>+ {tagGroup.children.length}+ </span>)}</Typography>- { !isReadOnly && (+ {!isReadOnly && (<ListItemSecondaryAction><IconButtonaria-label={i18n.t('core:options')}aria-haspopup="true"edge="end"- data-tid={'tagLibraryMoreButton_' + tagGroup.title.replace(/ /g, '_')}+ data-tid={+ 'tagLibraryMoreButton_' + tagGroup.title.replace(/ /g, '_')+ }onClick={event => this.handleTagGroupMenu(event, tagGroup)}- onContextMenu={event => this.handleTagGroupMenu(event, tagGroup)}+ onContextMenu={event =>+ this.handleTagGroupMenu(event, tagGroup)+ }><MoreVertIcon /></IconButton>@@ -254,11 +267,27 @@ class TagLibrary extends React.Component<Props, State> {)}</ListItem><Collapse in={tagGroup.expanded} unmountOnExit>- <TagGroupContainer taggroup={tagGroup} data-tid={'tagGroupContainer_' + tagGroup.title}>- {tagGroup.children && tagGroup.children.map((tag: Tag) => {- if (this.props.isReadOnlyMode) {+ <TagGroupContainer+ taggroup={tagGroup}+ data-tid={'tagGroupContainer_' + tagGroup.title}+ >+ {tagGroup.children &&+ tagGroup.children.map((tag: Tag) => {+ if (this.props.isReadOnlyMode) {+ return (+ <TagContainer+ key={tagGroup.uuid + tag.title}+ tag={tag}+ tagGroup={tagGroup}+ handleTagMenu={this.handleTagMenu}+ addTags={this.props.addTags}+ moveTag={this.props.moveTag}+ selectedEntries={this.props.selectedEntries}+ />+ );+ }return (- <TagContainer+ <TagContainerDndkey={tagGroup.uuid + tag.title}tag={tag}tagGroup={tagGroup}@@ -268,25 +297,12 @@ class TagLibrary extends React.Component<Props, State> {selectedEntries={this.props.selectedEntries}/>);- }- return (- <TagContainerDnd- key={tagGroup.uuid + tag.title}- tag={tag}- tagGroup={tagGroup}- handleTagMenu={this.handleTagMenu}- addTags={this.props.addTags}- moveTag={this.props.moveTag}- selectedEntries={this.props.selectedEntries}- />- );- }- )}+ })}</TagGroupContainer></Collapse></div>);-};+ };render() {const { tagGroups, classes, allTags } = this.props;@@ -297,12 +313,18 @@ class TagLibrary extends React.Component<Props, State> {<div className={classes.toolbar}><TypographyclassName={classNames(classes.panelTitle, classes.header)}- title={'Your tag library contains ' + allTags.length + ' tags \ndistributed in ' + tagGroups.length + ' tag groups'}+ title={+ 'Your tag library contains ' ++ allTags.length ++ ' tags \ndistributed in ' ++ tagGroups.length ++ ' tag groups'+ }type="subtitle1">{i18n.t('core:tagLibrary')}</Typography>- { !isTagLibraryReadOnly && (+ {!isTagLibraryReadOnly && (<IconButtondata-tid="tagLibraryMenu"onClick={this.handleTagLibraryMenu}@@ -382,9 +404,16 @@ class TagLibrary extends React.Component<Props, State> {editTag={this.props.editTag}deleteTag={this.props.deleteTag}/>- <div className={classes.taggroupsArea} data-tid="tagLibraryTagGroupList">- <List style={{ paddingTop: 0 }}>{SmartTags(i18n).map(this.renderTagGroup)}</List>- <List style={{ paddingTop: 0 }}>{tagGroups.map(this.renderTagGroup)}</List>+ <div+ className={classes.taggroupsArea}+ data-tid="tagLibraryTagGroupList"+ >+ <List style={{ paddingTop: 0 }}>+ {SmartTags(i18n).map(this.renderTagGroup)}+ </List>+ <List style={{ paddingTop: 0 }}>+ {tagGroups.map(this.renderTagGroup)}+ </List></div></div>);@@ -403,12 +432,15 @@ function mapStateToProps(state) {}function mapDispatchToProps(dispatch) {- return bindActionCreators({- ...TagLibraryActions, // TODO connect only the really needed- addTags: TaggingActions.addTags,- collectTagsFromLocation: TaggingActions.collectTagsFromLocation,- openURLExternally: AppActions.openURLExternally,- }, dispatch);+ return bindActionCreators(+ {+ ...TagLibraryActions, // TODO connect only the really needed+ addTags: TaggingActions.addTags,+ collectTagsFromLocation: TaggingActions.collectTagsFromLocation,+ openURLExternally: AppActions.openURLExternally+ },+ dispatch+ );}export default withStyles(styles)(diff --git a/app/components/TagsSelect.js b/app/components/TagsSelect.jsindex 84a738b90..bb9849f0b 100644--- a/app/components/TagsSelect.js+++ b/app/components/TagsSelect.js@@ -35,7 +35,7 @@ import TagContainer from './TagContainer';const styles = theme => ({root: {- flexGrow: 1,+ flexGrow: 1// height: 250,/* '& div': { //https://github.com/JedWatson/react-select/issues/1085zIndex: 1@@ -44,34 +44,34 @@ const styles = theme => ({input: {display: 'flex',padding: 0,- height: 'auto',+ height: 'auto'},valueContainer: {display: 'flex',flexWrap: 'wrap',flex: 1,alignItems: 'center',- overflow: 'hidden',+ overflow: 'hidden'},noOptionsMessage: {- padding: theme.spacing(1, 2),+ padding: theme.spacing(1, 2)},singleValue: {- fontSize: 16,+ fontSize: 16},placeholder: {position: 'absolute',left: 2,bottom: 6,- fontSize: 16,+ fontSize: 16},paper: {position: 'absolute',zIndex: 2,marginTop: theme.spacing(1),left: 0,- right: 0,- },+ right: 0+ }});function NoOptionsMessage(props) {@@ -96,7 +96,7 @@ function Control(props) {children,innerProps,innerRef,- selectProps: { classes, TextFieldProps },+ selectProps: { classes, TextFieldProps }} = props;return (@@ -108,8 +108,8 @@ function Control(props) {className: classes.input,ref: innerRef,children,- ...innerProps,- },+ ...innerProps+ }}}{...TextFieldProps}/>@@ -123,7 +123,7 @@ function Option(props) {selected={props.isFocused}component="div"style={{- fontWeight: props.isSelected ? 500 : 400,+ fontWeight: props.isSelected ? 500 : 400}}{...props.innerProps}>@@ -147,14 +147,21 @@ function Placeholder(props) {function SingleValue(props) {return (- <Typography className={props.selectProps.classes.singleValue} {...props.innerProps}>+ <Typography+ className={props.selectProps.classes.singleValue}+ {...props.innerProps}+ >{props.children}</Typography>);}function ValueContainer(props) {- return <div className={props.selectProps.classes.valueContainer}>{props.children}</div>;+ return (+ <div className={props.selectProps.classes.valueContainer}>+ {props.children}+ </div>+ );}function MultiValue(props) {@@ -170,7 +177,12 @@ function MultiValue(props) {function Menu(props) {return (- <Paper elevation={22} square className={props.selectProps.classes.paper} {...props.innerProps}>+ <Paper+ elevation={22}+ square+ className={props.selectProps.classes.paper}+ {...props.innerProps}+ >{props.children}</Paper>);@@ -239,9 +251,9 @@ const TagsSelect = (props: Props) => {...base,color: theme.palette.text.primary,'& input': {- font: 'inherit',- },- }),+ font: 'inherit'+ }+ })};return (@@ -252,8 +264,8 @@ const TagsSelect = (props: Props) => {isDisabled={isReadOnlyMode}classes={classes}options={allTags}- getOptionLabel={(option) => option.title}- getOptionValue={(option) => option.id || option.title}+ getOptionLabel={option => option.title}+ getOptionValue={option => option.id || option.title}isValidNewOption={isValidNewOption}getNewOptionData={(inputValue, optionLabel) => ({id: uuidv1(),@@ -274,8 +286,8 @@ const TagsSelect = (props: Props) => {onChange={handleChange}placeholder={placeholderText}isMulti- formatCreateLabel={(label) => label}- // isSearchable+ formatCreateLabel={label => label}+ // isSearchable/></NoSsr></div>@@ -288,5 +300,6 @@ const mapStateToProps = state => ({defaultTextColor: getTagTextColor(state)});--export default connect(mapStateToProps)(withStyles(styles, { withTheme: true })(TagsSelect));+export default connect(mapStateToProps)(+ withStyles(styles, { withTheme: true })(TagsSelect)+);diff --git a/app/components/TargetFileBox.js b/app/components/TargetFileBox.jsindex 946db567d..abb451b1d 100644--- a/app/components/TargetFileBox.js+++ b/app/components/TargetFileBox.js@@ -39,7 +39,7 @@ const styles = theme => ({textAlign: 'center',fontSize: '40px',fontWeight: 'bold',- color: 'white',+ color: 'white'}});@@ -47,10 +47,11 @@ const boxTarget = {/*** http://react-dnd.github.io/react-dnd/docs/api/drop-target*/- drop(props, monitor) { // component)+ drop(props, monitor) {+ // component)// return component.props.onDrop(props, monitor);return props.onDrop(props, monitor);- },+ }};type Props = {@@ -63,7 +64,12 @@ type Props = {const TargetFileBox = (props: Props) => {const { classes, canDrop, isOver, connectDropTarget, children } = props;- const dragContent = canDrop && isOver ? (<div className={classes.dropzone}>{i18n.t('core:releaseToDrop')}</div>) : undefined;+ const dragContent =+ canDrop && isOver ? (+ <div className={classes.dropzone}>{i18n.t('core:releaseToDrop')}</div>+ ) : (+ undefined+ );return connectDropTarget(<div>{dragContent}@@ -72,8 +78,14 @@ const TargetFileBox = (props: Props) => {);};-export default withStyles(styles, { withTheme: true })(DropTarget(props => props.accepts, boxTarget, (connect, monitor) => ({- connectDropTarget: connect.dropTarget(),- isOver: monitor.isOver(),- canDrop: monitor.canDrop(),-}))(TargetFileBox));+export default withStyles(styles, { withTheme: true })(+ DropTarget(+ props => props.accepts,+ boxTarget,+ (connect, monitor) => ({+ connectDropTarget: connect.dropTarget(),+ isOver: monitor.isOver(),+ canDrop: monitor.canDrop()+ })+ )(TargetFileBox)+);diff --git a/app/components/TargetMoveFileBox.js b/app/components/TargetMoveFileBox.jsindex ebb2278bf..1c241744f 100644--- a/app/components/TargetMoveFileBox.js+++ b/app/components/TargetMoveFileBox.js@@ -39,14 +39,14 @@ const styles = theme => ({textAlign: 'center',fontSize: '20px',fontWeight: 'bold',- color: 'white',+ color: 'white'}});const boxTarget = {drop(props, monitor) {return props.onDrop(props, monitor);- },+ }};type Props = {@@ -59,7 +59,12 @@ type Props = {const TargetMoveFileBox = (props: Props) => {const { classes, canDrop, isOver, connectDropTarget, children } = props;- const dragContent = canDrop && isOver ? (<div className={classes.dropzone}>{i18n.t('core:releaseToMoveDrop')}</div>) : undefined;+ const dragContent =+ canDrop && isOver ? (+ <div className={classes.dropzone}>{i18n.t('core:releaseToMoveDrop')}</div>+ ) : (+ undefined+ );return connectDropTarget(<div>{dragContent}@@ -68,8 +73,14 @@ const TargetMoveFileBox = (props: Props) => {);};-export default withStyles(styles, { withTheme: true })(DropTarget(props => props.accepts, boxTarget, (connect, monitor) => ({- connectDropTarget: connect.dropTarget(),- isOver: monitor.isOver(),- canDrop: monitor.canDrop(),-}))(TargetMoveFileBox));+export default withStyles(styles, { withTheme: true })(+ DropTarget(+ props => props.accepts,+ boxTarget,+ (connect, monitor) => ({+ connectDropTarget: connect.dropTarget(),+ isOver: monitor.isOver(),+ canDrop: monitor.canDrop()+ })+ )(TargetMoveFileBox)+);diff --git a/app/components/TransparentBackground.js b/app/components/TransparentBackground.jsindex b9176f9ec..9c730073f 100644--- a/app/components/TransparentBackground.js+++ b/app/components/TransparentBackground.js@@ -23,9 +23,11 @@ type Props = {};const TransparentBackground = (props: Props) => (- <span style={{- background: 'url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAMUlEQVQ4T2NkYGAQYcAP3uCTZhw1gGGYhAGBZIA/nYDCgBDAm9BGDWAAJyRCgLaBCAAgXwixzAS0pgAAAABJRU5ErkJggg==")'- }}+ <span+ style={{+ background:+ 'url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAMUlEQVQ4T2NkYGAQYcAP3uCTZhw1gGGYhAGBZIA/nYDCgBDAm9BGDWAAJyRCgLaBCAAgXwixzAS0pgAAAABJRU5ErkJggg==")'+ }}>{props.children}</span>diff --git a/app/components/VerticalNavigation.js b/app/components/VerticalNavigation.jsindex c510db54f..290bae38d 100644--- a/app/components/VerticalNavigation.js+++ b/app/components/VerticalNavigation.js@@ -51,12 +51,14 @@ import {isSearchPanelOpened,isPerspectivesPanelOpened,isHelpFeedbackPanelOpened,- isReadOnlyMode,+ isReadOnlyMode} from '../reducers/app';import { actions as SettingsActions, isFirstRun } from '../reducers/settings';import LoadingLazy from './LoadingLazy';-const ProTeaserDialog = React.lazy(() => import(/* webpackChunkName: "ProTeaserDialog" */ './dialogs/ProTeaserDialog'));+const ProTeaserDialog = React.lazy(() =>+ import(/* webpackChunkName: "ProTeaserDialog" */ './dialogs/ProTeaserDialog')+);const ProTeaserDialogAsync = props => (<React.Suspense fallback={<LoadingLazy />}><ProTeaserDialog {...props} />@@ -139,7 +141,7 @@ class VerticalNavigation extends React.Component<Props, State> {toggleProTeaser = () => {this.setState({ isProTeaserVisible: !this.state.isProTeaserVisible });- }+ };render() {const {@@ -214,7 +216,9 @@ class VerticalNavigation extends React.Component<Props, State> {id="verticalNavButton"onClick={() => {if (isReadOnlyMode || !directoryPath) {- showNotification('You are in read-only mode or there is no opened location');+ showNotification(+ 'You are in read-only mode or there is no opened location'+ );} else {toggleCreateFileDialog();}@@ -328,10 +332,11 @@ class VerticalNavigation extends React.Component<Props, State> {onClick={this.toggleProTeaser}style={{ ...this.styles.button, ...this.styles.upgradeButton }}>- <UpgradeIcon style={{- ...this.styles.buttonIcon,- // color: '1DD19F'- }}+ <UpgradeIcon+ style={{+ ...this.styles.buttonIcon+ // color: '1DD19F'+ }}/></IconButton>)}@@ -352,31 +357,40 @@ class VerticalNavigation extends React.Component<Props, State> {style={isSettingsDialogOpened? {- ...this.styles.button,- ...this.styles.settingsButton,- ...this.styles.selectedButton- } : {- ...this.styles.button,- ...this.styles.settingsButton- }+ ...this.styles.button,+ ...this.styles.settingsButton,+ ...this.styles.selectedButton+ }+ : {+ ...this.styles.button,+ ...this.styles.settingsButton+ }}><SettingsIcon style={this.styles.buttonIcon} /></IconButton></div><div style={this.styles.panel}>- <LocationManager style={{ display: isLocationManagerPanelOpened ? 'block' : 'none' }} />- { isTagLibraryPanelOpened && <TagLibrary /> }- <Search style={{ display: isSearchPanelOpened ? 'block' : 'none' }} />- { isPerspectivesPanelOpened && <PerspectiveManager /> }- { isHelpFeedbackPanelOpened && <HelpFeedbackPanel- openFileNatively={openFileNatively}- openURLExternally={openURLExternally}- toggleAboutDialog={toggleAboutDialog}- toggleKeysDialog={toggleKeysDialog}- toggleOnboardingDialog={toggleOnboardingDialog}- toggleProTeaser={this.toggleProTeaser}- /> }+ <LocationManager+ style={{+ display: isLocationManagerPanelOpened ? 'block' : 'none'+ }}+ />+ {isTagLibraryPanelOpened && <TagLibrary />}+ <Search+ style={{ display: isSearchPanelOpened ? 'block' : 'none' }}+ />+ {isPerspectivesPanelOpened && <PerspectiveManager />}+ {isHelpFeedbackPanelOpened && (+ <HelpFeedbackPanel+ openFileNatively={openFileNatively}+ openURLExternally={openURLExternally}+ toggleAboutDialog={toggleAboutDialog}+ toggleKeysDialog={toggleKeysDialog}+ toggleOnboardingDialog={toggleOnboardingDialog}+ toggleProTeaser={this.toggleProTeaser}+ />+ )}</div></SplitPane></div>@@ -394,7 +408,7 @@ function mapStateToProps(state) {isPerspectivesPanelOpened: isPerspectivesPanelOpened(state),isHelpFeedbackPanelOpened: isHelpFeedbackPanelOpened(state),isReadOnlyMode: isReadOnlyMode(state),- directoryPath: getDirectoryPath(state),+ directoryPath: getDirectoryPath(state)};}@@ -416,7 +430,7 @@ function mapActionCreatorsToProps(dispatch) {closeAllVerticalPanels: AppActions.closeAllVerticalPanels,showNotification: AppActions.showNotification,switchTheme: SettingsActions.switchTheme,- setFirstRun: SettingsActions.setFirstRun,+ setFirstRun: SettingsActions.setFirstRun},dispatch);diff --git a/app/components/WelcomePanel.js b/app/components/WelcomePanel.jsindex 1305a99bb..4a5f15e8f 100644--- a/app/components/WelcomePanel.js+++ b/app/components/WelcomePanel.js@@ -62,7 +62,7 @@ const styles = theme => ({top: '45%',width: '100%',textAlign: 'center',- position: 'absolute',+ position: 'absolute'},links: {width: 300,@@ -71,7 +71,7 @@ const styles = theme => ({marginTop: 15,marginBottom: 15,overflowY: 'overlay',- backgroundColor: theme.palette.background.default,+ backgroundColor: theme.palette.background.default}});@@ -98,34 +98,51 @@ const WelcomePanel = (props: Props) => {{/* <div className={classes.slogan}></div> */}- <List dense={false} component="nav" aria-label="main help area" className={classes.links}>- <div- role="button"- tabIndex={0}- onClick={props.toggleAboutDialog}- >- <img- src={WelcomeLogo}- alt="Organize your files"- />+ <List+ dense={false}+ component="nav"+ aria-label="main help area"+ className={classes.links}+ >+ <div role="button" tabIndex={0} onClick={props.toggleAboutDialog}>+ <img src={WelcomeLogo} alt="Organize your files" /></div><ListItembuttononClick={() => {- const button = document.getElementById(isDesktopMode ? 'locationMenuButton' : 'mobileMenuButton');+ const button = document.getElementById(+ isDesktopMode ? 'locationMenuButton' : 'mobileMenuButton'+ );button.click();}}>- <Button startIcon={<DocumentationIcon />}>{i18n.t('core:chooseLocation')}</Button>+ <Button startIcon={<DocumentationIcon />}>+ {i18n.t('core:chooseLocation')}+ </Button></ListItem>- <ListItem button onClick={() => openURLExternally(AppConfig.documentationLinks.general)}>+ <ListItem+ button+ onClick={() =>+ openURLExternally(AppConfig.documentationLinks.general)+ }+ ><Button startIcon={<DocumentationIcon />}>Open Documentation</Button></ListItem><ListItem button onClick={() => toggleKeysDialog()}>- <Button startIcon={<KeyShortcutsIcon />}>{i18n.t('core:shortcutKeys')}</Button>+ <Button startIcon={<KeyShortcutsIcon />}>+ {i18n.t('core:shortcutKeys')}+ </Button></ListItem>- <ListItem button onClick={() => openURLExternally(AppConfig.links.changelogURL)}>- <Button startIcon={<ChangeLogIcon />} title="Opens the changelog of the app">{i18n.t('core:whatsNew')}</Button>+ <ListItem+ button+ onClick={() => openURLExternally(AppConfig.links.changelogURL)}+ >+ <Button+ startIcon={<ChangeLogIcon />}+ title="Opens the changelog of the app"+ >+ {i18n.t('core:whatsNew')}+ </Button></ListItem>{/* <ListItem button onClick={() => toggleOnboardingDialog()}><ListItemIcon>@@ -133,28 +150,63 @@ const WelcomePanel = (props: Props) => {</ListItemIcon><ListItemText primary={i18n.t('core:onboardingWizard')} /></ListItem> */}- <ListItem button onClick={() => openURLExternally(AppConfig.links.webClipper)}>- <Button startIcon={<WebClipperIcon />}>{i18n.t('core:webClipper')}</Button>+ <ListItem+ button+ onClick={() => openURLExternally(AppConfig.links.webClipper)}+ >+ <Button startIcon={<WebClipperIcon />}>+ {i18n.t('core:webClipper')}+ </Button></ListItem><Divider />- <ListItem button onClick={() => openURLExternally(AppConfig.links.suggestFeature)}>- <Button startIcon={<NewFeatureIcon />}>{i18n.t('core:suggestNewFeatures')}</Button>+ <ListItem+ button+ onClick={() => openURLExternally(AppConfig.links.suggestFeature)}+ >+ <Button startIcon={<NewFeatureIcon />}>+ {i18n.t('core:suggestNewFeatures')}+ </Button></ListItem>- <ListItem button onClick={() => openURLExternally(AppConfig.links.reportIssue)}>- <Button startIcon={<IssueIcon />}>{i18n.t('core:reportIssues')}</Button>+ <ListItem+ button+ onClick={() => openURLExternally(AppConfig.links.reportIssue)}+ >+ <Button startIcon={<IssueIcon />}>+ {i18n.t('core:reportIssues')}+ </Button></ListItem>- <ListItem button onClick={() => openURLExternally(AppConfig.links.helpTranslating)}>- <Button startIcon={<TranslationIcon />}>{i18n.t('core:helpWithTranslation')}</Button>+ <ListItem+ button+ onClick={() => openURLExternally(AppConfig.links.helpTranslating)}+ >+ <Button startIcon={<TranslationIcon />}>+ {i18n.t('core:helpWithTranslation')}+ </Button></ListItem><Divider />- <ListItem button onClick={() => openURLExternally(AppConfig.links.emailContact)}>- <Button startIcon={<EmailIcon />}>{i18n.t('core:emailContact')}</Button>+ <ListItem+ button+ onClick={() => openURLExternally(AppConfig.links.emailContact)}+ >+ <Button startIcon={<EmailIcon />}>+ {i18n.t('core:emailContact')}+ </Button></ListItem>- <ListItem button onClick={() => openFileNatively(AppConfig.links.twitter)}>- <Button startIcon={<Social2Icon />}>{i18n.t('core:followOnTwitter')}</Button>+ <ListItem+ button+ onClick={() => openFileNatively(AppConfig.links.twitter)}+ >+ <Button startIcon={<Social2Icon />}>+ {i18n.t('core:followOnTwitter')}+ </Button></ListItem>- <ListItem button onClick={() => openURLExternally(AppConfig.links.facebook)}>- <Button startIcon={<SocialIcon />}>{i18n.t('core:likeUsOnFacebook')}</Button>+ <ListItem+ button+ onClick={() => openURLExternally(AppConfig.links.facebook)}+ >+ <Button startIcon={<SocialIcon />}>+ {i18n.t('core:likeUsOnFacebook')}+ </Button></ListItem></List></div>@@ -164,7 +216,7 @@ const WelcomePanel = (props: Props) => {function mapStateToProps(state) {return {isFirstRun: isFirstRun(state),- isDesktopMode: getDesktopMode(state),+ isDesktopMode: getDesktopMode(state)// locations: getLocations(state),};}@@ -176,12 +228,13 @@ function mapActionCreatorsToProps(dispatch) {openURLExternally: AppActions.openURLExternally,openFileNatively: AppActions.openFileNatively,toggleKeysDialog: AppActions.toggleKeysDialog,- toggleAboutDialog: AppActions.toggleAboutDialog,+ toggleAboutDialog: AppActions.toggleAboutDialog},dispatch);}-export default connect(mapStateToProps, mapActionCreatorsToProps)(- withStyles(styles)(WelcomePanel)-);+export default connect(+ mapStateToProps,+ mapActionCreatorsToProps+)(withStyles(styles)(WelcomePanel));diff --git a/app/components/dialogs/AboutDialog.js b/app/components/dialogs/AboutDialog.jsindex 8315a1cce..26e69cfd8 100644--- a/app/components/dialogs/AboutDialog.js+++ b/app/components/dialogs/AboutDialog.js@@ -86,13 +86,13 @@ const AboutDialog = (props: Props) => {// if (event.key === 'Enter' || event.keyCode === 13) {// props.onClose();// event.stopPropagation();- // }+ // }// }let versionInfo = 'Check for updates';- if (newVersion && newVersion.length > 1) {- if (updateAvailable) {- versionInfo = i18n.t('getNewVersion', { newVersion });+ if (newVersion && newVersion.length > 1) {+ if (updateAvailable) {+ versionInfo = i18n.t('getNewVersion', { newVersion });} else {versionInfo = i18n.t('latestVersion', { productName });}@@ -106,106 +106,111 @@ const AboutDialog = (props: Props) => {keepMountedscroll="paper"// onKeyDown={confirmFunction}- >- <DialogTitle>{productName}</DialogTitle>- <DialogContent>- <img- alt="TagSpaces logo"- src={LogoIcon}- style={{ float: 'left', marginRight: 10, width: 120, height: 120 }}- />- <Typography- variant="subtitle1"- title={'Build on: ' + versionMeta.buildTime + '\nPlatform: ' + navigator.appVersion}- >- Version: {versionMeta.version} / BuildID: {buildID}- </Typography>- <br />- <Typography id="aboutContent" variant="body1">- <strong>{productName}</strong> is made possible by the- TagSpaces(github.com/tagspaces) open source project and other{' '}- <Button- size="small"- color="primary"- onClick={props.toggleThirdPartyLibsDialog}+ >+ <DialogTitle>{productName}</DialogTitle>+ <DialogContent>+ <img+ alt="TagSpaces logo"+ src={LogoIcon}+ style={{ float: 'left', marginRight: 10, width: 120, height: 120 }}+ />+ <Typography+ variant="subtitle1"+ title={+ 'Build on: ' ++ versionMeta.buildTime ++ '\nPlatform: ' ++ navigator.appVersion+ }>- open source software- </Button>- .+ Version: {versionMeta.version} / BuildID: {buildID}+ </Typography><br />+ <Typography id="aboutContent" variant="body1">+ <strong>{productName}</strong> is made possible by the+ TagSpaces(github.com/tagspaces) open source project and other{' '}+ <Button+ size="small"+ color="primary"+ onClick={props.toggleThirdPartyLibsDialog}+ >+ open source software+ </Button>+ .+ <br />+ {!Pro && (+ <span>+ This program is free software: you can redistribute it and/or+ modify it under the terms of the GNU Affero General Public License+ (version 3) as published by the Free Software Foundation.+ </span>+ )}+ <br />+ This program is distributed in the hope that it will be useful, but+ WITHOUT ANY WARRANTY; without even the implied warranty of+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License+ for more details.+ <br />+ <br />+ <Button+ size="small"+ color="primary"+ onClick={() => {+ PlatformIO.openUrl(AppConfig.links.imprintURL);+ }}+ >+ Imprint+ </Button>+ <Button+ size="small"+ color="primary"+ onClick={() => {+ PlatformIO.openUrl(AppConfig.links.privacyURL);+ }}+ >+ Privacy Policy+ </Button>+ <Button+ size="small"+ color="primary"+ onClick={() => {+ PlatformIO.openUrl(AppConfig.links.changelogURL);+ }}+ >+ Changelog+ </Button>+ <Button+ size="small"+ color="primary"+ data-tid="openLicenseDialog"+ onClick={props.toggleLicenseDialog}+ >+ License Agreement+ </Button>+ </Typography>+ </DialogContent>+ <DialogActions>{!Pro && (- <span>- This program is free software: you can redistribute it and/or modify- it under the terms of the GNU Affero General Public License (version- 3) as published by the Free Software Foundation.- </span>+ <Button+ data-tid="checkForUpdates"+ title={i18n.t('core:checkForNewVersion')}+ onClick={() => {+ PlatformIO.openUrl(AppConfig.links.productsOverview);+ }}+ color="primary"+ >+ Upgrade to PRO+ </Button>)}- <br />- This program is distributed in the hope that it will be useful, but- WITHOUT ANY WARRANTY; without even the implied warranty of- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for- more details.- <br />- <br />- <Button- size="small"- color="primary"- onClick={() => {- PlatformIO.openUrl(AppConfig.links.imprintURL);- }}- >- Imprint- </Button>- <Button- size="small"- color="primary"- onClick={() => {- PlatformIO.openUrl(AppConfig.links.privacyURL);- }}- >- Privacy Policy- </Button>- <Button- size="small"- color="primary"- onClick={() => {- PlatformIO.openUrl(AppConfig.links.changelogURL);- }}- >- Changelog- </Button>- <Button- size="small"- color="primary"- data-tid="openLicenseDialog"- onClick={props.toggleLicenseDialog}- >- License Agreement- </Button>- </Typography>- </DialogContent>- <DialogActions>- {!Pro && (<Buttondata-tid="checkForUpdates"title={i18n.t('core:checkForNewVersion')}- onClick={() => {- PlatformIO.openUrl(AppConfig.links.productsOverview);- }}+ onClick={checkForUpdates}color="primary">- Upgrade to PRO+ {versionInfo}</Button>- )}- <Button- data-tid="checkForUpdates"- title={i18n.t('core:checkForNewVersion')}- onClick={checkForUpdates}- color="primary"- >- {versionInfo}- </Button>- {/* <Button+ {/* <Buttondata-tid="openLicenseDialog"onClick={this.props.toggleLicenseDialog}>@@ -217,14 +222,14 @@ const AboutDialog = (props: Props) => {>{i18n.t('core:thirdPartyLibs')}</Button> */}- <Button- data-tid="closeAboutDialog"- onClick={props.onClose}- color="primary"- >- {i18n.t('core:ok')}- </Button>- </DialogActions>+ <Button+ data-tid="closeAboutDialog"+ onClick={props.onClose}+ color="primary"+ >+ {i18n.t('core:ok')}+ </Button>+ </DialogActions></Dialog>);};diff --git a/app/components/dialogs/AddRemoveTagsDialog.js b/app/components/dialogs/AddRemoveTagsDialog.jsindex 554b2664b..5dfe49b3b 100644--- a/app/components/dialogs/AddRemoveTagsDialog.js+++ b/app/components/dialogs/AddRemoveTagsDialog.js@@ -79,14 +79,14 @@ class AddRemoveTagsDialog extends React.Component<Props, State> {addTags = () => {if (this.props.selectedEntries && this.props.selectedEntries.length > 0) {const paths = [];- this.props.selectedEntries.map((entry) => {+ this.props.selectedEntries.map(entry => {paths.push(entry.path);return true;});this.props.addTags(paths, this.state.newlyAddedTags);}this.onClose();- }+ };render() {const {@@ -111,24 +111,27 @@ class AddRemoveTagsDialog extends React.Component<Props, State> {><DialogTitle>{i18n.t('core:tagOperationTitle')}</DialogTitle><DialogContent style={{ minHeight: 330 }}>- <TagsSelect placeholderText={i18n.t('core:selectTags')} tags={newlyAddedTags} handleChange={this.handleChange} />+ <TagsSelect+ placeholderText={i18n.t('core:selectTags')}+ tags={newlyAddedTags}+ handleChange={this.handleChange}+ /><List dense style={{ width: 550 }}>- {selectedEntries.length > 0 && selectedEntries.map((entry) => (- <ListItem key={uuidv1()} title={entry.path}>- <ListItemIcon>- <FileIcon />- </ListItemIcon>- <Typography variant="inherit" noWrap>{extractFileName(entry.path || '')}</Typography>- </ListItem>- ))}+ {selectedEntries.length > 0 &&+ selectedEntries.map(entry => (+ <ListItem key={uuidv1()} title={entry.path}>+ <ListItemIcon>+ <FileIcon />+ </ListItemIcon>+ <Typography variant="inherit" noWrap>+ {extractFileName(entry.path || '')}+ </Typography>+ </ListItem>+ ))}</List></DialogContent><DialogActions>- <Button- data-tid="cancel"- onClick={this.onClose}- color="primary"- >+ <Button data-tid="cancel" onClick={this.onClose} color="primary">{i18n.t('core:cancel')}</Button><Button@@ -138,7 +141,7 @@ class AddRemoveTagsDialog extends React.Component<Props, State> {onClick={() => {if (selectedEntries && selectedEntries.length > 0) {const paths = [];- selectedEntries.map((entry) => {+ selectedEntries.map(entry => {paths.push(entry.path);return true;});@@ -151,12 +154,16 @@ class AddRemoveTagsDialog extends React.Component<Props, State> {</Button><Buttondata-tid="removeTagsMultipleEntries"- disabled={!newlyAddedTags || newlyAddedTags.length < 1 || selectedEntries.length < 1}+ disabled={+ !newlyAddedTags ||+ newlyAddedTags.length < 1 ||+ selectedEntries.length < 1+ }color="primary"onClick={() => {if (selectedEntries && selectedEntries.length > 0) {const paths = [];- selectedEntries.map((entry) => {+ selectedEntries.map(entry => {paths.push(entry.path);return true;});@@ -169,7 +176,11 @@ class AddRemoveTagsDialog extends React.Component<Props, State> {</Button><Buttondata-tid="addTagsMultipleEntries"- disabled={!newlyAddedTags || newlyAddedTags.length < 1 || selectedEntries.length < 1}+ disabled={+ !newlyAddedTags ||+ newlyAddedTags.length < 1 ||+ selectedEntries.length < 1+ }color="primary"onClick={this.addTags}>diff --git a/app/components/dialogs/ColorPickerDialog.js b/app/components/dialogs/ColorPickerDialog.jsindex 250ec893b..618de5464 100644--- a/app/components/dialogs/ColorPickerDialog.js+++ b/app/components/dialogs/ColorPickerDialog.js@@ -27,10 +27,33 @@ import Dialog from '@material-ui/core/Dialog';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'];+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'+];type Props = {classes: Object,@@ -52,10 +75,7 @@ const styles = {const ColorPickerDialog = (props: Props) => {const [color, setColor] = useState(undefined);const [colorHex, setColorHex] = useState(undefined);- const {- open = false,- onClose- } = props;+ const { open = false, onClose } = props;function onConfirm() {if (color && colorHex) {@@ -71,13 +91,8 @@ const ColorPickerDialog = (props: Props) => {}return (- <Dialog- open={open}- onClose={onClose}- keepMounted- scroll="paper"- >- <DialogTitle data-tid="colorPickerDialogTitle" >+ <Dialog open={open} onClose={onClose} keepMounted scroll="paper">+ <DialogTitle data-tid="colorPickerDialogTitle">{i18n.t('core:colorPickerDialogTitle')}</DialogTitle><DialogContent@@ -110,7 +125,7 @@ const ColorPickerDialog = (props: Props) => {{i18n.t('core:ok')}</Button></DialogActions>- </Dialog>+ </Dialog>);};diff --git a/app/components/dialogs/ConfirmDialog.js b/app/components/dialogs/ConfirmDialog.jsindex c310801bc..b38a455e0 100644--- a/app/components/dialogs/ConfirmDialog.js+++ b/app/components/dialogs/ConfirmDialog.js@@ -41,7 +41,7 @@ type Props = {};const ConfirmDialog = (props: Props) => {- const { open, onClose } = props;+ const { open, onClose } = props;function onConfirm(result) {props.confirmCallback(result);@@ -49,24 +49,22 @@ const ConfirmDialog = (props: Props) => {}return (- <Dialog- open={open}- onClose={onClose}- keepMounted- scroll="paper"- >+ <Dialog open={open} onClose={onClose} keepMounted scroll="paper"><DialogTitle>{props.title}</DialogTitle>- <DialogContent>- <DialogContentText data-tid={props.confirmDialogContentTID}>- {props.content}- {props.list && props.list.map((listItem) => (+ <DialogContent>+ <DialogContentText data-tid={props.confirmDialogContentTID}>+ {props.content}+ {props.list &&+ props.list.map(listItem => (<ListItem title={listItem}>- <Typography variant="inherit" noWrap>{listItem}</Typography>+ <Typography variant="inherit" noWrap>+ {listItem}+ </Typography></ListItem>))}- </DialogContentText>- </DialogContent>- <DialogActions>+ </DialogContentText>+ </DialogContent>+ <DialogActions><ButtononClick={() => onConfirm(false)}color="primary"@@ -82,8 +80,8 @@ const ConfirmDialog = (props: Props) => {{i18n.t('core:yes')}</Button></DialogActions>- </Dialog>- )+ </Dialog>+ );};ConfirmDialog.defaultProps = {diff --git a/app/components/dialogs/CreateDialog.js b/app/components/dialogs/CreateDialog.jsindex bc61d5d2d..8f6d884e0 100644--- a/app/components/dialogs/CreateDialog.js+++ b/app/components/dialogs/CreateDialog.js@@ -71,15 +71,30 @@ type Props = {selectedDirectoryPath: string,showNotification: (message: string, type: string, autohide: boolean) => void,reflectCreateEntry: (path: string, isFile: boolean) => void,- createFileAdvanced: (targetPath: string, fileName: string, content: string, fileType: string) => void,+ createFileAdvanced: (+ targetPath: string,+ fileName: string,+ content: string,+ fileType: string+ ) => void,onClose: () => void};const CreateDialog = (props: Props) => {let fileInput; // Object | null;- const fileName = 'note' + AppConfig.beginTagContainer + formatDateTime4Tag(new Date(), true) + AppConfig.endTagContainer;+ const fileName =+ 'note' ++ AppConfig.beginTagContainer ++ formatDateTime4Tag(new Date(), true) ++ AppConfig.endTagContainer;const fileContent = '';- const { classes, selectedDirectoryPath, showNotification, open, onClose } = props;+ const {+ classes,+ selectedDirectoryPath,+ showNotification,+ open,+ onClose+ } = props;function handleKeyPress(event: any) {if (event.key === 'n') {@@ -99,21 +114,36 @@ const CreateDialog = (props: Props) => {function createRichTextFile() {if (selectedDirectoryPath) {- props.createFileAdvanced(selectedDirectoryPath, fileName, fileContent, 'html');+ props.createFileAdvanced(+ selectedDirectoryPath,+ fileName,+ fileContent,+ 'html'+ );props.onClose();}}function createTextFile() {if (selectedDirectoryPath) {- props.createFileAdvanced(selectedDirectoryPath, fileName, fileContent, 'txt');+ props.createFileAdvanced(+ selectedDirectoryPath,+ fileName,+ fileContent,+ 'txt'+ );props.onClose();}}function createMarkdownFile() {if (selectedDirectoryPath) {- props.createFileAdvanced(selectedDirectoryPath, fileName, fileContent, 'md');+ props.createFileAdvanced(+ selectedDirectoryPath,+ fileName,+ fileContent,+ 'md'+ );props.onClose();}}@@ -150,46 +180,48 @@ const CreateDialog = (props: Props) => {const reader = new FileReader();reader.onload = event => {- PlatformIO.getPropertiesPromise(filePath).then((entryProps) => {- if (entryProps) {- showNotification(- 'File with the same name already exist, importing skipped!',- 'warning',- true- );- } else {- PlatformIO.saveBinaryFilePromise(- filePath,- event.currentTarget.result,- true- )- .then(() => {- showNotification(- 'File ' + filePath + ' successfully imported.',- 'default',- true- );- props.reflectCreateEntry(filePath, true);- props.onClose();- return true;- })- .catch(error => {- // TODO showAlertDialog("Saving " + filePath + " failed.");- console.error('Save to file ' + filePath + ' failed ' + error);- showNotification(- 'Importing file ' + filePath + ' failed.',- 'error',- true- );- props.onClose();- return true;- });- }- return true;- }).catch((err) => {- console.log('Error getting properties ' + err);- props.onClose();- });+ PlatformIO.getPropertiesPromise(filePath)+ .then(entryProps => {+ if (entryProps) {+ showNotification(+ 'File with the same name already exist, importing skipped!',+ 'warning',+ true+ );+ } else {+ PlatformIO.saveBinaryFilePromise(+ filePath,+ event.currentTarget.result,+ true+ )+ .then(() => {+ showNotification(+ 'File ' + filePath + ' successfully imported.',+ 'default',+ true+ );+ props.reflectCreateEntry(filePath, true);+ props.onClose();+ return true;+ })+ .catch(error => {+ // TODO showAlertDialog("Saving " + filePath + " failed.");+ console.error('Save to file ' + filePath + ' failed ' + error);+ showNotification(+ 'Importing file ' + filePath + ' failed.',+ 'error',+ true+ );+ props.onClose();+ return true;+ });+ }+ return true;+ })+ .catch(err => {+ console.log('Error getting properties ' + err);+ props.onClose();+ });};if (AppConfig.isCordova) {@@ -208,23 +240,30 @@ const CreateDialog = (props: Props) => {// onEnterKey={(event) => onEnterKeyHandler(event, this.addTags)}// TransitionComponent={Transition}>- <DialogTitle style={{ alignSelf: 'center' }}>Create new content</DialogTitle>- <DialogContent onKeyPress={handleKeyPress} className={classes.root} data-tid="keyboardShortCutsDialog">+ <DialogTitle style={{ alignSelf: 'center' }}>+ Create new content+ </DialogTitle>+ <DialogContent+ onKeyPress={handleKeyPress}+ className={classes.root}+ data-tid="keyboardShortCutsDialog"+ ><Grid className={classes.grid} container spacing={1}><Grid item xs><ButtononClick={createRichTextFile}className={classes.createButton}>- <div><NoteFileIcon /></div>- <div><Container>Create Note</Container></div>+ <div>+ <NoteFileIcon />+ </div>+ <div>+ <Container>Create Note</Container>+ </div></Button></Grid><Grid item xs>- <Button- onClick={createTextFile}- className={classes.createButton}- >+ <Button onClick={createTextFile} className={classes.createButton}><TextFileIcon /><Container>Create Text File</Container></Button>@@ -241,10 +280,7 @@ const CreateDialog = (props: Props) => {</Button></Grid><Grid item xs>- <Button- onClick={addFile}- className={classes.createButton}- >+ <Button onClick={addFile} className={classes.createButton}><AddFileIcon /><Container>Add file</Container></Button>@@ -275,18 +311,22 @@ const CreateDialog = (props: Props) => {function mapStateToProps(state) {return {- keyBindings: getKeyBindingObject(state),+ keyBindings: getKeyBindingObject(state)};}function mapActionCreatorsToProps(dispatch) {- return bindActionCreators({- createFileAdvanced: AppActions.createFileAdvanced,- showNotification: AppActions.showNotification,- reflectCreateEntry: AppActions.reflectCreateEntry,- }, dispatch);+ return bindActionCreators(+ {+ createFileAdvanced: AppActions.createFileAdvanced,+ showNotification: AppActions.showNotification,+ reflectCreateEntry: AppActions.reflectCreateEntry+ },+ dispatch+ );}-export default connect(mapStateToProps, mapActionCreatorsToProps)(- withStyles(styles)(CreateDialog)-);+export default connect(+ mapStateToProps,+ mapActionCreatorsToProps+)(withStyles(styles)(CreateDialog));diff --git a/app/components/dialogs/CreateDirectoryDialog.js b/app/components/dialogs/CreateDirectoryDialog.jsindex ccb913378..824f486ca 100644--- a/app/components/dialogs/CreateDirectoryDialog.js+++ b/app/components/dialogs/CreateDirectoryDialog.js@@ -63,7 +63,8 @@ const CreateDirectoryDialog = (props: Props) => {function onConfirm() {if (!disableConfirmButton && name) {- const dirPath = props.selectedDirectoryPath + AppConfig.dirSeparator + name;+ const dirPath =+ props.selectedDirectoryPath + AppConfig.dirSeparator + name;props.createDirectory(dirPath);resetState();props.onClose();@@ -89,13 +90,10 @@ const CreateDirectoryDialog = (props: Props) => {keepMountedscroll="paper"// onKeyDown={confirmFunction} TODO- >+ ><DialogTitle>{i18n.t('core:createNewDirectoryTitle')}</DialogTitle><DialogContent>- <FormControl- fullWidth={true}- error={inputError}- >+ <FormControl fullWidth={true} error={inputError}><TextFieldfullWidtherror={inputError}@@ -137,9 +135,15 @@ const CreateDirectoryDialog = (props: Props) => {};function mapActionCreatorsToProps(dispatch) {- return bindActionCreators({- createDirectory: AppActions.createDirectory- }, dispatch);+ return bindActionCreators(+ {+ createDirectory: AppActions.createDirectory+ },+ dispatch+ );}-export default connect(undefined, mapActionCreatorsToProps)(CreateDirectoryDialog);+export default connect(+ undefined,+ mapActionCreatorsToProps+)(CreateDirectoryDialog);diff --git a/app/components/dialogs/CreateFileDialog.js b/app/components/dialogs/CreateFileDialog.jsindex 169cb006c..5e60dee43 100644--- a/app/components/dialogs/CreateFileDialog.js+++ b/app/components/dialogs/CreateFileDialog.js@@ -56,11 +56,11 @@ const styles = theme => ({height: 'auto'},formControl: {- margin: theme.spacing(3),+ margin: theme.spacing(3)},group: {- margin: theme.spacing(1, 0),- },+ margin: theme.spacing(1, 0)+ }});type Props = {@@ -69,7 +69,12 @@ type Props = {onClose: () => void,selectedDirectoryPath: string | null,showSelectDirectoryDialog: () => void,- createFileAdvanced: (targetPath: string, fileName: string, content: string, fileType: string) => void+ createFileAdvanced: (+ targetPath: string,+ fileName: string,+ content: string,+ fileType: string+ ) => void};type State = {@@ -89,11 +94,18 @@ class CreateFileDialog extends React.Component<Props, State> {errorTextName: false,errorTextPath: false,openFolder: false,- disableConfirmButton: !(this.props.selectedDirectoryPath && this.props.selectedDirectoryPath.length > 0),+ disableConfirmButton: !(+ this.props.selectedDirectoryPath &&+ this.props.selectedDirectoryPath.length > 0+ ),selectedDirectoryPath: this.props.selectedDirectoryPath,- fileName: 'note' + AppConfig.beginTagContainer + formatDateTime4Tag(new Date(), true) + AppConfig.endTagContainer,+ fileName:+ 'note' ++ AppConfig.beginTagContainer ++ formatDateTime4Tag(new Date(), true) ++ AppConfig.endTagContainer,fileContent: '',- fileType: 'txt',+ fileType: 'txt'};fileName;@@ -107,9 +119,12 @@ class CreateFileDialog extends React.Component<Props, State> {const target = event.target;const value = target.type === 'checkbox' ? target.checked : target.value;const name = target.name;- this.setState({- [name]: value- }, this.handleValidation);+ this.setState(+ {+ [name]: value+ },+ this.handleValidation+ );};handleValidation() {@@ -119,27 +134,36 @@ class CreateFileDialog extends React.Component<Props, State> {this.setState({ errorTextName: true });}- if (this.state.selectedDirectoryPath && this.state.selectedDirectoryPath.length > 0) {+ 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+ 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);- });+ 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();}@@ -147,8 +171,18 @@ class CreateFileDialog extends React.Component<Props, State> {onConfirm = () => {if (!this.state.disableConfirmButton) {- const { fileName, fileContent, fileType, selectedDirectoryPath } = this.state;- this.props.createFileAdvanced(selectedDirectoryPath, fileName, fileContent, fileType);+ const {+ fileName,+ fileContent,+ fileType,+ selectedDirectoryPath+ } = this.state;+ this.props.createFileAdvanced(+ selectedDirectoryPath,+ fileName,+ fileContent,+ fileType+ );this.props.onClose();}};@@ -170,10 +204,7 @@ class CreateFileDialog extends React.Component<Props, State> {><DialogTitle>{i18n.t('core:createFileTitle')}</DialogTitle><DialogContent data-tid="createFileDialog">- <FormControl- fullWidth={true}- error={this.state.errorTextName}- >+ <FormControl fullWidth={true} error={this.state.errorTextName}><TextFieldfullWidth={true}error={this.state.errorTextName}@@ -181,12 +212,16 @@ class CreateFileDialog extends React.Component<Props, State> {margin="dense"name="fileName"label={i18n.t('core:fileName')}- inputRef={(ref) => { this.fileName = ref; }}+ 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>}+ {this.state.errorTextName && (+ <FormHelperText>{i18n.t('core:fileNameHelp')}</FormHelperText>+ )}</FormControl><FormControl fullWidth={true}><TextField@@ -241,15 +276,20 @@ class CreateFileDialog extends React.Component<Props, State> {value={this.state.selectedDirectoryPath}onChange={this.handleInputChange}endAdornment={- PlatformIO.haveObjectStoreSupport() ? undefined :- (<InputAdornment position="end" style={{ height: 32 }}>+ PlatformIO.haveObjectStoreSupport() ? (+ undefined+ ) : (+ <InputAdornment position="end" style={{ height: 32 }}><IconButton onClick={this.openFolderChooser}><FolderIcon /></IconButton>- </InputAdornment>)+ </InputAdornment>+ )}/>- {this.state.errorTextPath && <FormHelperText>{i18n.t('core:invalidPath')}</FormHelperText>}+ {this.state.errorTextPath && (+ <FormHelperText>{i18n.t('core:invalidPath')}</FormHelperText>+ )}</FormControl></DialogContent><DialogActions>@@ -269,16 +309,22 @@ class CreateFileDialog extends React.Component<Props, State> {{i18n.t('core:ok')}</Button></DialogActions>- </Dialog>- }+ </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)(withMobileDialog()(withStyles(styles)(CreateFileDialog)));+export default connect(+ undefined,+ mapActionCreatorsToProps+)(withMobileDialog()(withStyles(styles)(CreateFileDialog)));diff --git a/app/components/dialogs/CreateLocationDialog.js b/app/components/dialogs/CreateLocationDialog.jsindex 70bceccde..2faf5102d 100644--- a/app/components/dialogs/CreateLocationDialog.js+++ b/app/components/dialogs/CreateLocationDialog.js@@ -42,16 +42,16 @@ import LocalForm from './LocalForm';const styles = theme => ({root: {- display: 'flex',+ display: 'flex'},formControl: {- margin: theme.spacing(3),+ margin: theme.spacing(3)},group: {margin: theme.spacing(1, 0),display: 'flex',flexDirection: 'row'- },+ }});type Props = {@@ -100,7 +100,8 @@ class CreateLocationDialog extends React.Component<Props, State> {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)+ if (target.type === 'radio') {+ // type is changed (skip validation)this.setState({[name]: value});@@ -110,11 +111,14 @@ class CreateLocationDialog extends React.Component<Props, State> {};handleChange = (name, value) => {- this.setState({- [name]: value- }, () => {- this.handleValidation(name);- });+ this.setState(+ {+ [name]: value+ },+ () => {+ this.handleValidation(name);+ }+ );};handleValidation(field) {@@ -127,16 +131,27 @@ class CreateLocationDialog extends React.Component<Props, State> {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) => {+ } 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 modedisableConfirmButton = true;}- return new Promise(resolve => this.setState({ errorTextName, errorTextPath, disableConfirmButton }, resolve(!disableConfirmButton)));+ 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;@@ -148,65 +163,80 @@ class CreateLocationDialog extends React.Component<Props, State> {if (!this.state.storeName || this.state.storeName.length === 0) {cloudErrorTextName = true;disableConfirmButton = true;- } else if (field === 'storeName'- && !this.state.cloudErrorTextName+ } 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) => {+ !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+ } 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) => {+ !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) {+ if (+ !this.state.secretAccessKey ||+ this.state.secretAccessKey.length === 0+ ) {cloudErrorSecretAccessKey = true;disableConfirmButton = true;- } else if (field === 'secretAccessKey'- && !this.state.cloudErrorTextName+ } 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) => {+ !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+ } 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) => {+ !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) {@@ -214,195 +244,232 @@ class CreateLocationDialog extends React.Component<Props, State> {disableConfirmButton = true;}- return new Promise(resolve => this.setState({- cloudErrorTextName,- // cloudErrorTextPath,- cloudErrorAccessKey,- cloudErrorSecretAccessKey,- cloudErrorBucketName,- disableConfirmButton,- cloudErrorRegion }, resolve(!disableConfirmButton)));+ return new Promise(resolve =>+ this.setState(+ {+ cloudErrorTextName,+ // cloudErrorTextPath,+ cloudErrorAccessKey,+ cloudErrorSecretAccessKey,+ cloudErrorBucketName,+ disableConfirmButton,+ cloudErrorRegion+ },+ resolve(!disableConfirmButton)+ )+ );}- return new Promise(((resolve) => {+ 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.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');}- this.props.onClose();- this.props.resetState('createLocationDialogKey');- }- return true;- }).catch((error) => {- console.debug('Failed validation', error);- });+ return true;+ })+ .catch(error => {+ console.debug('Failed validation', error);+ });};onCancel = () => {this.props.onClose();this.props.resetState('createLocationDialogKey');- }+ };render() {- const {- fullScreen,- open,- onClose- } = this.props;+ 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} />)+ 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} />)+ 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>+ 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>- </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>+ {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>);}}diff --git a/app/components/dialogs/CreateTagGroupDialog.js b/app/components/dialogs/CreateTagGroupDialog.jsindex af5a12ea6..91cb91f80 100644--- a/app/components/dialogs/CreateTagGroupDialog.js+++ b/app/components/dialogs/CreateTagGroupDialog.js@@ -71,9 +71,12 @@ class CreateTagGroupDialog extends React.Component<Props, State> {const value = target.type === 'checkbox' ? target.checked : target.value;const name = target.name;- this.setState({- [name]: value- }, this.handleValidation);+ this.setState(+ {+ [name]: value+ },+ this.handleValidation+ );};handleValidation() {@@ -100,13 +103,13 @@ class CreateTagGroupDialog extends React.Component<Props, State> {};toggleDefaultTagBackgroundColorPicker = () => {- this.setState((prevState) => ({+ this.setState(prevState => ({displayColorPicker: !prevState.displayColorPicker}));};toggleDefaultTagTextColorPicker = () => {- this.setState((prevState) => ({+ this.setState(prevState => ({displayTextColorPicker: !prevState.displayTextColorPicker}));};@@ -120,11 +123,7 @@ class CreateTagGroupDialog extends React.Component<Props, State> {};render() {- const {- fullScreen,- open,- onClose- } = this.props;+ const { fullScreen, open, onClose } = this.props;const styles = {color: {@@ -155,24 +154,21 @@ class CreateTagGroupDialog extends React.Component<Props, State> {helpText: {marginBottom: '5px',fontSize: '1rem'- },- }+ }+ };return (<Dialog- open={open}- onClose={onClose}- fullScreen={fullScreen}- keepMounted- scroll="paper"- // onKeyDown={confirmFunction}+ open={open}+ onClose={onClose}+ fullScreen={fullScreen}+ keepMounted+ scroll="paper"+ // onKeyDown={confirmFunction}><DialogTitle>{i18n.t('core:createTagGroupTitle')}</DialogTitle><DialogContent>- <FormControl- fullWidth={true}- error={this.state.inputError}- >+ <FormControl fullWidth={true} error={this.state.inputError}><TextFieldfullWidth={true}error={this.state.inputError}@@ -183,19 +179,24 @@ class CreateTagGroupDialog extends React.Component<Props, State> {onChange={this.handleInputChange}data-tid="createTagGroupInput"/>- {this.state.inputError && <FormHelperText>{i18n.t('core:taggroupTitleHelper')}</FormHelperText>}+ {this.state.inputError && (+ <FormHelperText>+ {i18n.t('core:taggroupTitleHelper')}+ </FormHelperText>+ )}</FormControl>- <FormControl- fullWidth={true}- >- <FormHelperText style={styles.helpText}>{i18n.t('core:tagBackgroundColor')}</FormHelperText>+ <FormControl fullWidth={true}>+ <FormHelperText style={styles.helpText}>+ {i18n.t('core:tagBackgroundColor')}+ </FormHelperText><TransparentBackground><ButtononClick={this.toggleDefaultTagBackgroundColorPicker}data-tid="createTagGroupBackgroundColor"style={styles.color}role="presentation"- > + >+ </Button></TransparentBackground><ColorPickerDialog@@ -205,17 +206,18 @@ class CreateTagGroupDialog extends React.Component<Props, State> {color={this.state.color}/></FormControl>- <FormControl- fullWidth={true}- >- <FormHelperText style={styles.helpText}>{i18n.t('core:tagForegroundColor')}</FormHelperText>+ <FormControl fullWidth={true}>+ <FormHelperText style={styles.helpText}>+ {i18n.t('core:tagForegroundColor')}+ </FormHelperText><TransparentBackground><ButtononClick={this.toggleDefaultTagTextColorPicker}data-tid="createTagGroupForegroundColor"style={styles.textcolor}role="presentation"- > + >+ </Button></TransparentBackground><ColorPickerDialog@@ -227,10 +229,7 @@ class CreateTagGroupDialog extends React.Component<Props, State> {</FormControl></DialogContent><DialogActions>- <Button- onClick={this.props.onClose}- color="primary"- >+ <Button onClick={this.props.onClose} color="primary">{i18n.t('core:cancel')}</Button><Button@@ -242,9 +241,9 @@ class CreateTagGroupDialog extends React.Component<Props, State> {{i18n.t('core:ok')}</Button></DialogActions>- </Dialog>+ </Dialog>);- }+ }}export default CreateTagGroupDialog;diff --git a/app/components/dialogs/CreateTagsDialog.js b/app/components/dialogs/CreateTagsDialog.jsindex da3b31cc5..d76ead5cf 100644--- a/app/components/dialogs/CreateTagsDialog.js+++ b/app/components/dialogs/CreateTagsDialog.js@@ -49,7 +49,7 @@ class CreateTagsDialog extends React.Component<Props, State> {inputError: false,disableConfirmButton: true,open: false,- tagTitle: '',+ tagTitle: ''};handleInputChange = (event: Object) => {@@ -57,9 +57,12 @@ class CreateTagsDialog extends React.Component<Props, State> {const value = target.type === 'checkbox' ? target.checked : target.value;const name = target.name;- this.setState({- [name]: value- }, this.handleValidation);+ this.setState(+ {+ [name]: value+ },+ this.handleValidation+ );};handleValidation() {@@ -74,17 +77,16 @@ class CreateTagsDialog extends React.Component<Props, State> {onConfirm = () => {if (!this.state.disableConfirmButton) {this.setState({ open: false, disableConfirmButton: true });- this.props.addTag(this.state.tagTitle, this.props.selectedTagGroupEntry.uuid);+ this.props.addTag(+ this.state.tagTitle,+ this.props.selectedTagGroupEntry.uuid+ );this.props.onClose();}};render() {- const {- fullScreen,- open,- onClose- } = this.props;+ const { fullScreen, open, onClose } = this.props;return (<Dialog@@ -96,10 +98,7 @@ class CreateTagsDialog extends React.Component<Props, State> {><DialogTitle>{i18n.t('core:addTagsToGroupTitle')}</DialogTitle><DialogContent style={{ minWidth: 400 }}>- <FormControl- fullWidth={true}- error={this.state.inputError}- >+ <FormControl fullWidth={true} error={this.state.inputError}><TextFielderror={this.state.inputError}name="tagTitle"@@ -110,14 +109,13 @@ class CreateTagsDialog extends React.Component<Props, State> {data-tid="addTagsInput"fullWidth={true}/>- {this.state.inputError && <FormHelperText>{i18n.t('core:tagTitleHelper')}</FormHelperText>}+ {this.state.inputError && (+ <FormHelperText>{i18n.t('core:tagTitleHelper')}</FormHelperText>+ )}</FormControl></DialogContent><DialogActions>- <Button- onClick={this.props.onClose}- color="primary"- >+ <Button onClick={this.props.onClose} color="primary">{i18n.t('core:cancel')}</Button><Buttondiff --git a/app/components/dialogs/Dialogs.css.js b/app/components/dialogs/Dialogs.css.jsindex b24e5d144..1d55ba6c6 100644--- a/app/components/dialogs/Dialogs.css.js+++ b/app/components/dialogs/Dialogs.css.js@@ -24,5 +24,5 @@ export default (theme: Object) => ({padding: 5,overflowY: 'hidden',backgroundColor: theme.palette.background.default- },+ }});diff --git a/app/components/dialogs/EditEntryTagDialog.js b/app/components/dialogs/EditEntryTagDialog.jsindex 9dc519a64..cb4e23990 100644--- a/app/components/dialogs/EditEntryTagDialog.js+++ b/app/components/dialogs/EditEntryTagDialog.js@@ -35,15 +35,17 @@ import { isPlusCode } from '../../utils/misc';import { type Tag } from '../../reducers/taglibrary';import { Pro } from '../../pro';import { getSelectedTag } from '../../reducers/app';-import TaggingActions, { defaultTagLocation } from '../../reducers/tagging-actions';+import TaggingActions, {+ defaultTagLocation+} from '../../reducers/tagging-actions';import { isDateTimeTag } from '../../utils/dates';const styles = () => ({root: {minWidth: 400,height: '100%',- marginBottom: 30,- },+ marginBottom: 30+ }});type Props = {@@ -63,7 +65,9 @@ const DateTagEditor = Pro && Pro.UI ? Pro.UI.DateTagEditor : React.Fragment;const EditEntryTagDialog = (props: Props) => {const [disableConfirmButton, setDisableConfirmButton] = useState(true);const [errorTag, setErrorTag] = useState(false);- const [title, setTitle] = useState(props.selectedTag && props.selectedTag.title);+ const [title, setTitle] = useState(+ props.selectedTag && props.selectedTag.title+ );const { onClose, open, fullScreen } = props;useEffect(() => {@@ -91,9 +95,7 @@ const EditEntryTagDialog = (props: Props) => {}function renderTitle() {- return (- <DialogTitle>{i18n.t('core:tagProperties')}</DialogTitle>- );+ return <DialogTitle>{i18n.t('core:tagProperties')}</DialogTitle>;}function renderContent() {@@ -115,11 +117,11 @@ const EditEntryTagDialog = (props: Props) => {showDatePeriodEditor = DateTagEditor && showDatePeriodEditor;return (- <DialogContent data-tid="editEntryTagDialog" className={props.classes.root}>- <FormControl- fullWidth={true}- error={errorTag}- >+ <DialogContent+ data-tid="editEntryTagDialog"+ className={props.classes.root}+ >+ <FormControl fullWidth={true} error={errorTag}><TextFieldfullWidth={true}error={errorTag}@@ -134,10 +136,25 @@ const EditEntryTagDialog = (props: Props) => {value={title}data-tid="editTagEntryDialog_input"/>- {errorTag && <FormHelperText>{i18n.t('core:tagTitleHelper')}</FormHelperText>}+ {errorTag && (+ <FormHelperText>{i18n.t('core:tagTitleHelper')}</FormHelperText>+ )}</FormControl>- { showGeoEditor && <GeoTagEditor key={title} geoTag={title} onChange={setTitle} zoom={title === defaultTagLocation ? 2 : undefined} /> }- { showDatePeriodEditor && <DateTagEditor key={title} datePeriodTag={title} onChange={setTitle} /> }+ {showGeoEditor && (+ <GeoTagEditor+ key={title}+ geoTag={title}+ onChange={setTitle}+ zoom={title === defaultTagLocation ? 2 : undefined}+ />+ )}+ {showDatePeriodEditor && (+ <DateTagEditor+ key={title}+ datePeriodTag={title}+ onChange={setTitle}+ />+ )}</DialogContent>);}@@ -174,23 +191,30 @@ const EditEntryTagDialog = (props: Props) => {{renderTitle()}{renderContent()}{renderActions()}- </Dialog>+ </Dialog>);};function mapStateToProps(state) {return {selectedTag: getSelectedTag(state),- currentEntryPath: getSelectedTag(state) ? getSelectedTag(state).path : undefined+ currentEntryPath: getSelectedTag(state)+ ? getSelectedTag(state).path+ : undefined};}function mapDispatchToProps(dispatch) {- return bindActionCreators({- editTagForEntry: TaggingActions.editTagForEntry- }, dispatch);+ return bindActionCreators(+ {+ editTagForEntry: TaggingActions.editTagForEntry+ },+ dispatch+ );}-export default withMobileDialog()(withStyles(styles)(- connect(mapStateToProps, mapDispatchToProps)(EditEntryTagDialog)-));+export default withMobileDialog()(+ withStyles(styles)(+ connect(mapStateToProps, mapDispatchToProps)(EditEntryTagDialog)+ )+);diff --git a/app/components/dialogs/EditLocationDialog.js b/app/components/dialogs/EditLocationDialog.jsindex 24b1281ca..95050854d 100644--- a/app/components/dialogs/EditLocationDialog.js+++ b/app/components/dialogs/EditLocationDialog.js@@ -85,44 +85,46 @@ class EditLocationDialog extends React.Component<Props, State> {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)+ if (target.type === 'radio') {+ // type is changed (skip validation)this.setState({[name]: value});@@ -132,9 +134,12 @@ class EditLocationDialog extends React.Component<Props, State> {};handleChange = (name, value) => {- this.setState({- [name]: value- }, this.handleValidation);+ this.setState(+ {+ [name]: value+ },+ this.handleValidation+ );};handleValidation() {@@ -265,7 +270,7 @@ class EditLocationDialog extends React.Component<Props, State> {onCancel = () => {this.props.onClose();this.props.resetState('editLocationDialogKey');- }+ };renderTitle = () => (<DialogTitle>{i18n.t('core:editLocationTitle')}</DialogTitle>@@ -274,18 +279,22 @@ class EditLocationDialog extends React.Component<Props, State> {renderContent = () => {let content;if (this.state.type === locationType.TYPE_CLOUD) {- content = (<ObjectStoreForm- handleInputChange={this.handleInputChange}- handleChange={this.handleChange}- state={this.state}- />);+ 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}- />);+ content = (+ <LocalForm+ showSelectDirectoryDialog={this.props.showSelectDirectoryDialog}+ handleInputChange={this.handleInputChange}+ handleChange={this.handleChange}+ state={this.state}+ />+ );}return (<DialogContent>@@ -296,7 +305,9 @@ class EditLocationDialog extends React.Component<Props, State> {<Grid item xs={10}><FormControl disabled={!Pro}><RadioGroup- title={Pro ? '' : i18n.t('core:thisFunctionalityIsAvailableInPro')}+ title={+ Pro ? '' : i18n.t('core:thisFunctionalityIsAvailableInPro')+ }component="label"aria-label={i18n.t('core:locationType')}name="type"@@ -304,8 +315,17 @@ class EditLocationDialog extends React.Component<Props, State> {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" />+ <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>@@ -334,7 +354,10 @@ class EditLocationDialog extends React.Component<Props, State> {onChange={this.handleInputChange}/>}- label={i18n.t('core:readonlyModeSwitch') + (Pro ? '' : ' - ' + i18n.t('core:proFeature'))}+ label={+ i18n.t('core:readonlyModeSwitch') ++ (Pro ? '' : ' - ' + i18n.t('core:proFeature'))+ }/><FormControlLabelcontrol={@@ -346,7 +369,10 @@ class EditLocationDialog extends React.Component<Props, State> {onChange={this.handleInputChange}/>}- label={i18n.t('core:createFullTextIndex') + (Pro ? '' : ' - ' + i18n.t('core:proFeature'))}+ label={+ i18n.t('core:createFullTextIndex') ++ (Pro ? '' : ' - ' + i18n.t('core:proFeature'))+ }/><FormControlLabelcontrol={@@ -358,7 +384,10 @@ class EditLocationDialog extends React.Component<Props, State> {onChange={this.handleInputChange}/>}- label={i18n.t('core:persistIndexSwitch') + (Pro ? '' : ' - ' + i18n.t('core:proFeature'))}+ label={+ i18n.t('core:persistIndexSwitch') ++ (Pro ? '' : ' - ' + i18n.t('core:proFeature'))+ }/><FormControlLabelcontrol={@@ -370,7 +399,10 @@ class EditLocationDialog extends React.Component<Props, State> {onChange={this.handleInputChange}/>}- label={i18n.t('core:watchForChangesInLocation') + (Pro ? '' : ' - ' + i18n.t('core:proFeature'))}+ label={+ i18n.t('core:watchForChangesInLocation') ++ (Pro ? '' : ' - ' + i18n.t('core:proFeature'))+ }/></FormGroup></FormControl>@@ -383,7 +415,10 @@ class EditLocationDialog extends React.Component<Props, State> {<Buttondata-tid="closeEditLocationDialog"color="primary"- onClick={() => { this.props.onClose(); this.props.resetState('editLocationDialogKey'); }}+ onClick={() => {+ this.props.onClose();+ this.props.resetState('editLocationDialogKey');+ }}>{i18n.t('core:cancel')}</Button>@@ -415,10 +450,9 @@ class EditLocationDialog extends React.Component<Props, State> {{this.renderTitle()}{this.renderContent()}{this.renderActions()}- </Dialog>+ </Dialog>);}}export default withMobileDialog()(EditLocationDialog);-diff --git a/app/components/dialogs/EditTagDialog.js b/app/components/dialogs/EditTagDialog.jsindex 2619c94da..113e41771 100644--- a/app/components/dialogs/EditTagDialog.js+++ b/app/components/dialogs/EditTagDialog.js@@ -80,9 +80,12 @@ class EditTagDialog extends React.Component<Props, State> {const value = target.type === 'checkbox' ? target.checked : target.value;const name = target.name;- this.setState({- [name]: value- }, this.handleValidation);+ this.setState(+ {+ [name]: value+ },+ this.handleValidation+ );};handleValidation() {@@ -95,17 +98,21 @@ class EditTagDialog extends React.Component<Props, State> {}onConfirm = () => {- if (!this.state.disableConfirmButton &&- this.props.editTag &&- this.props.selectedTagGroupEntry &&- this.props.selectedTag+ if (+ !this.state.disableConfirmButton &&+ this.props.editTag &&+ this.props.selectedTagGroupEntry &&+ this.props.selectedTag) {- this.props.editTag({- ...this.props.selectedTag,- title: this.state.title,- color: this.state.color,- textcolor: this.state.textcolor,- }, this.props.selectedTagGroupEntry.uuid);+ this.props.editTag(+ {+ ...this.props.selectedTag,+ title: this.state.title,+ color: this.state.color,+ textcolor: this.state.textcolor+ },+ this.props.selectedTagGroupEntry.uuid+ );this.setState({ inputError: false, disableConfirmButton: true });this.props.onClose();}@@ -133,11 +140,7 @@ class EditTagDialog extends React.Component<Props, State> {render() {const { color, textcolor, modifiedDate } = this.state;- const {- fullScreen,- open,- onClose- } = this.props;+ const { fullScreen, open, onClose } = this.props;const styles = {color: {width: '100%',@@ -147,7 +150,7 @@ class EditTagDialog extends React.Component<Props, State> {borderStyle: 'solid',borderColor: 'gray',padding: '5px',- background: color,+ background: color},textcolor: {width: '100%',@@ -157,12 +160,12 @@ class EditTagDialog extends React.Component<Props, State> {borderStyle: 'solid',borderColor: 'gray',padding: '5px',- background: textcolor,+ background: textcolor},helpText: {marginBottom: '5px',fontSize: '1rem'- },+ }};return (@@ -174,7 +177,10 @@ class EditTagDialog extends React.Component<Props, State> {scroll="paper"// onEnterKey={(event) => onEnterKeyHandler(event, this.addTags)}>- <DialogTitle style={{ overflow: 'visible' }}>{i18n.t('core:editTagTitle')}{` '${this.state.title}'`}</DialogTitle>+ <DialogTitle style={{ overflow: 'visible' }}>+ {i18n.t('core:editTagTitle')}+ {` '${this.state.title}'`}+ </DialogTitle><DialogContent style={{ overflow: 'visible' }}><FormControlfullWidth={true}@@ -182,8 +188,18 @@ class EditTagDialog extends React.Component<Props, State> {style={{ overflow: 'visible' }}>{modifiedDate && (- <div className="tag-date" style={{ fontSize: 12, position: 'relative', bottom: 20, color: '#808080' }}>- <span className="text" style={{ fontWeight: 600 }}>{`${i18n.t('core:modifiedDate')}: `}</span>+ <div+ className="tag-date"+ style={{+ fontSize: 12,+ position: 'relative',+ bottom: 20,+ color: '#808080'+ }}+ >+ <span className="text" style={{ fontWeight: 600 }}>{`${i18n.t(+ 'core:modifiedDate'+ )}: `}</span><time>{format(new Date(modifiedDate), 'yyyy-mm-dd')}</time></div>)}@@ -198,19 +214,24 @@ class EditTagDialog extends React.Component<Props, State> {data-tid="editTagInput"fullWidth={true}/>- {this.state.inputError && <FormHelperText style={styles.helpText}>{i18n.t('core:tagTitleHelper')}</FormHelperText>}+ {this.state.inputError && (+ <FormHelperText style={styles.helpText}>+ {i18n.t('core:tagTitleHelper')}+ </FormHelperText>+ )}</FormControl>- <FormControl- fullWidth={true}- >- <FormHelperText style={styles.helpText}>{i18n.t('core:tagBackgroundColor')}</FormHelperText>+ <FormControl fullWidth={true}>+ <FormHelperText style={styles.helpText}>+ {i18n.t('core:tagBackgroundColor')}+ </FormHelperText><TransparentBackground><ButtononClick={this.toggleDefaultTagBackgroundColorPicker}data-tid="tagBackgroundColorEditTagDialog"style={styles.color}role="presentation"- > + >+ </Button></TransparentBackground><ColorPickerDialog@@ -220,17 +241,18 @@ class EditTagDialog extends React.Component<Props, State> {color={this.state.color}/></FormControl>- <FormControl- fullWidth={true}- >- <FormHelperText style={styles.helpText}>{i18n.t('core:tagForegroundColor')}</FormHelperText>+ <FormControl fullWidth={true}>+ <FormHelperText style={styles.helpText}>+ {i18n.t('core:tagForegroundColor')}+ </FormHelperText><TransparentBackground><ButtononClick={this.toggleDefaultTagTextColorPicker}data-tid="tagForegroundColorEditTagDialog"style={styles.textcolor}role="presentation"- > + >+ </Button></TransparentBackground><ColorPickerDialog@@ -258,9 +280,9 @@ class EditTagDialog extends React.Component<Props, State> {{i18n.t('core:ok')}</Button></DialogActions>- </Dialog>+ </Dialog>);- }+ }}export default EditTagDialog;diff --git a/app/components/dialogs/EditTagGroupDialog.js b/app/components/dialogs/EditTagGroupDialog.jsindex 1bee0d4e5..3e38a97c9 100644--- a/app/components/dialogs/EditTagGroupDialog.js+++ b/app/components/dialogs/EditTagGroupDialog.js@@ -83,9 +83,12 @@ class EditTagGroupDialog extends React.Component<Props, State> {const value = target.type === 'checkbox' ? target.checked : target.value;const name = target.name;- this.setState({- [name]: value- }, this.handleValidation);+ this.setState(+ {+ [name]: value+ },+ this.handleValidation+ );};handleValidation() {@@ -109,7 +112,7 @@ class EditTagGroupDialog extends React.Component<Props, State> {title: this.state.title,color: this.state.color,textcolor: this.state.textcolor,- children: selectedTagGroupEntry.children.map((tag) => ({+ children: selectedTagGroupEntry.children.map(tag => ({...tag,color: applyChanges ? this.state.color : tag.color,textcolor: applyChanges ? this.state.textcolor : tag.textcolor,@@ -126,7 +129,9 @@ class EditTagGroupDialog extends React.Component<Props, State> {};toggleDefaultTagTextColorPicker = () => {- this.setState({ displayTextColorPicker: !this.state.displayTextColorPicker });+ this.setState({+ displayTextColorPicker: !this.state.displayTextColorPicker+ });};handleChangeColor = (color: string) => {@@ -142,7 +147,10 @@ class EditTagGroupDialog extends React.Component<Props, State> {};renderTitle = () => (- <DialogTitle style={{ overflow: 'visible' }}>{i18n.t('core:editTagGroupTitle')}{` '${this.state.title}'`}</DialogTitle>+ <DialogTitle style={{ overflow: 'visible' }}>+ {i18n.t('core:editTagGroupTitle')}+ {` '${this.state.title}'`}+ </DialogTitle>);renderContent = () => {@@ -171,7 +179,7 @@ class EditTagGroupDialog extends React.Component<Props, State> {helpText: {marginBottom: '5px',fontSize: '1rem'- },+ }};return (@@ -182,8 +190,18 @@ class EditTagGroupDialog extends React.Component<Props, State> {style={{ overflow: 'visible' }}>{modifiedDate && (- <div className="tag-date" style={{ fontSize: 12, position: 'relative', bottom: 20, color: '#808080' }}>- <span className="text" style={{ fontWeight: 600 }}>{`${i18n.t('core:modifiedDate')}: `}</span>+ <div+ className="tag-date"+ style={{+ fontSize: 12,+ position: 'relative',+ bottom: 20,+ color: '#808080'+ }}+ >+ <span className="text" style={{ fontWeight: 600 }}>{`${i18n.t(+ 'core:modifiedDate'+ )}: `}</span><time>{format(new Date(modifiedDate), 'yyyy-mm-dd')}</time></div>)}@@ -198,18 +216,23 @@ class EditTagGroupDialog extends React.Component<Props, State> {data-tid="editTagGroupInput"fullWidth={true}/>- {this.state.inputError && <FormHelperText>{i18n.t('core:taggroupTitleHelper')}</FormHelperText>}+ {this.state.inputError && (+ <FormHelperText>+ {i18n.t('core:taggroupTitleHelper')}+ </FormHelperText>+ )}</FormControl>- <FormControl- fullWidth={true}- >- <FormHelperText style={styles.helpText}>{i18n.t('core:tagBackgroundColor')}</FormHelperText>+ <FormControl fullWidth={true}>+ <FormHelperText style={styles.helpText}>+ {i18n.t('core:tagBackgroundColor')}+ </FormHelperText><TransparentBackground><ButtononClick={this.toggleDefaultTagBackgroundColorPicker}data-tid="editTagGroupBackgroundColor"style={styles.color}- > + >+ </Button></TransparentBackground><ColorPickerDialog@@ -219,17 +242,18 @@ class EditTagGroupDialog extends React.Component<Props, State> {color={this.state.color}/></FormControl>- <FormControl- fullWidth={true}- >- <FormHelperText style={styles.helpText}>{i18n.t('core:tagForegroundColor')}</FormHelperText>+ <FormControl fullWidth={true}>+ <FormHelperText style={styles.helpText}>+ {i18n.t('core:tagForegroundColor')}+ </FormHelperText><TransparentBackground><ButtononClick={this.toggleDefaultTagTextColorPicker}data-tid="editTagGroupForegroundColor"style={styles.textcolor}role="presentation"- > + >+ </Button></TransparentBackground><ColorPickerDialog@@ -240,7 +264,9 @@ class EditTagGroupDialog extends React.Component<Props, State> {/></FormControl><FormControl>- <FormHelperText style={styles.helpText}>{i18n.t('core:colorChangesToAllTags')}</FormHelperText>+ <FormHelperText style={styles.helpText}>+ {i18n.t('core:colorChangesToAllTags')}+ </FormHelperText><Switchdata-tid="editTagGroupSwitch"onClick={() => this.setApplyChanges(!this.state.applyChanges)}@@ -253,10 +279,7 @@ class EditTagGroupDialog extends React.Component<Props, State> {renderActions = () => (<DialogActions>- <Button- onClick={this.props.onClose}- color="primary"- >+ <Button onClick={this.props.onClose} color="primary">{i18n.t('core:cancel')}</Button><Buttondiff --git a/app/components/dialogs/GenericDialog.js b/app/components/dialogs/GenericDialog.jsindex 2acad01b7..6d6eaebfd 100644--- a/app/components/dialogs/GenericDialog.js+++ b/app/components/dialogs/GenericDialog.js@@ -69,13 +69,7 @@ const GenericDialog = (props: Props) => {// );// }- const {- fullScreen,- open,- onEnterKey,- onClose,- onBackdropClick- } = props;+ const { fullScreen, open, onEnterKey, onClose, onBackdropClick } = props;return (<DialogfullScreen={fullScreen}@@ -86,7 +80,9 @@ const GenericDialog = (props: Props) => {onClose={onClose}onBackdropClick={onBackdropClick && onClose}// onEscapeKeyDown={onClose}- onKeyDown={onEnterKey || ((event) => onEnterKeyHandler(event, props.onClose))}+ onKeyDown={+ onEnterKey || (event => onEnterKeyHandler(event, props.onClose))+ }>{props.renderTitle && props.renderTitle()}{props.renderContent && props.renderContent()}diff --git a/app/components/dialogs/ImportExportTagGroupsDialog.js b/app/components/dialogs/ImportExportTagGroupsDialog.jsindex 2d70202a9..6da705ced 100644--- a/app/components/dialogs/ImportExportTagGroupsDialog.js+++ b/app/components/dialogs/ImportExportTagGroupsDialog.js@@ -41,7 +41,7 @@ const styles = {height: '100%',overflowY: AppConfig.isFirefox ? 'auto' : 'overlay',marginBottom: 30- },+ }};type Props = {@@ -90,7 +90,10 @@ class ImportExportTagGroupsDialog extends React.Component<Props, State> {selected: true});});- this.setState({ tagGroupList, selectedAll: true }, this.handleValidation);+ this.setState(+ { tagGroupList, selectedAll: true },+ this.handleValidation+ );}}};@@ -110,7 +113,10 @@ class ImportExportTagGroupsDialog extends React.Component<Props, State> {});return true;});- this.setState({ tagGroupList, selectedAll: !this.state.selectedAll }, this.handleValidation);+ this.setState(+ { tagGroupList, selectedAll: !this.state.selectedAll },+ this.handleValidation+ );};handleChange = name => (event: Object, checked: boolean) => {@@ -147,7 +153,7 @@ class ImportExportTagGroupsDialog extends React.Component<Props, State> {const { showNotification } = this.props;const groupList = [];const selectedTagGroup = this.state.tagGroupList;- selectedTagGroup.map((tagGroup) => {+ selectedTagGroup.map(tagGroup => {if (tagGroup.selected) {groupList.push({uuid: tagGroup.uuid || tagGroup.key,@@ -184,7 +190,9 @@ class ImportExportTagGroupsDialog extends React.Component<Props, State> {<Checkboxid={tagGroup.uuid || tagGroup.key}checked={tagGroup.selected}- onClick={e => this.handleTagGroup(e, tagGroup.selected, index)}+ onClick={e =>+ this.handleTagGroup(e, tagGroup.selected, index)+ }onChange={e => this.handleChange(e)}value={tagGroup.title}name={tagGroup.title}@@ -195,12 +203,10 @@ class ImportExportTagGroupsDialog extends React.Component<Props, State> {</FormGroup></FormControl><TagGroupContainer taggroup={tagGroup}>- {tagGroup.children && tagGroup.children.map(tag => (- <TagContainer- tag={tag}- tagMode="display"- />- ))}+ {tagGroup.children &&+ tagGroup.children.map(tag => (+ <TagContainer tag={tag} tagMode="display" />+ ))}</TagGroupContainer></div>);@@ -208,18 +214,15 @@ class ImportExportTagGroupsDialog extends React.Component<Props, State> {renderTitle = () => {if (this.props.dialogModeImport) {- return (<DialogTitle>{i18n.t('core:importGroupTagsTitle')}</DialogTitle>);+ return <DialogTitle>{i18n.t('core:importGroupTagsTitle')}</DialogTitle>;}- return (<DialogTitle>{i18n.t('core:exportGroupTagsTitle')}</DialogTitle>);+ return <DialogTitle>{i18n.t('core:exportGroupTagsTitle')}</DialogTitle>;};renderContent = () => {return (<DialogContent className={this.props.classes.root}>- <Button- color="primary"- onClick={this.handleToggleSelectAll}- >+ <Button color="primary" onClick={this.handleToggleSelectAll}>{i18n.t('core:selectAllTagGroups')}</Button><FormControl fullWidth={true}>@@ -231,10 +234,7 @@ class ImportExportTagGroupsDialog extends React.Component<Props, State> {renderActions = () => (<DialogActions>- <Button- onClick={this.props.onClose}- color="primary"- >+ <Button onClick={this.props.onClose} color="primary">{i18n.t('core:cancel')}</Button><Button@@ -243,7 +243,7 @@ class ImportExportTagGroupsDialog extends React.Component<Props, State> {data-tid="confirmImportExport"color="primary">- { this.props.dialogModeImport ? 'Import' : 'Export' }+ {this.props.dialogModeImport ? 'Import' : 'Export'}</Button></DialogActions>);@@ -265,4 +265,6 @@ class ImportExportTagGroupsDialog extends React.Component<Props, State> {}}-export default withStyles(styles)(withMobileDialog()(ImportExportTagGroupsDialog));+export default withStyles(styles)(+ withMobileDialog()(ImportExportTagGroupsDialog)+);diff --git a/app/components/dialogs/KeyboardDialog.js b/app/components/dialogs/KeyboardDialog.jsindex 0b7bd6c1c..1c644bdd2 100644--- a/app/components/dialogs/KeyboardDialog.js+++ b/app/components/dialogs/KeyboardDialog.js@@ -42,7 +42,7 @@ const styles = theme => ({font: 'Console',fontFamily: 'monospace',padding: '5px',- borderRadius: '5px',+ borderRadius: '5px'}});@@ -65,16 +65,20 @@ const KeyboardDialog = (props: Props) => {scroll="paper"><DialogTitle>{i18n.t('core:shortcutKeys')}</DialogTitle>- <DialogContent className={props.classes.root} data-tid="keyboardShortCutsDialog">+ <DialogContent+ className={props.classes.root}+ data-tid="keyboardShortCutsDialog"+ ><List dense={false}>- {props.keyBindings && Object.keys(props.keyBindings).map((shortcutKey) => (- <ListItem key={shortcutKey}>- <ListItemText primary={i18n.t('core:' + shortcutKey)} />- <ListItemSecondaryAction className={props.classes.shortcutKey}>- {props.keyBindings[shortcutKey]}- </ListItemSecondaryAction>- </ListItem>- ))}+ {props.keyBindings &&+ Object.keys(props.keyBindings).map(shortcutKey => (+ <ListItem key={shortcutKey}>+ <ListItemText primary={i18n.t('core:' + shortcutKey)} />+ <ListItemSecondaryAction className={props.classes.shortcutKey}>+ {props.keyBindings[shortcutKey]}+ </ListItemSecondaryAction>+ </ListItem>+ ))}</List></DialogContent><DialogActions>@@ -92,7 +96,7 @@ const KeyboardDialog = (props: Props) => {function mapStateToProps(state) {return {- keyBindings: getKeyBindingObject(state),+ keyBindings: getKeyBindingObject(state)};}diff --git a/app/components/dialogs/LicenseDialog.js b/app/components/dialogs/LicenseDialog.jsindex 1b7064cac..5ec0c61a3 100644--- a/app/components/dialogs/LicenseDialog.js+++ b/app/components/dialogs/LicenseDialog.js@@ -72,7 +72,7 @@ const LicenseDialog = (props: Props) => {// }}style={{ overflow: AppConfig.isFirefox ? 'auto' : 'overlay' }}>- <pre style={{ whiteSpace: 'pre-wrap' }} >+ <pre style={{ whiteSpace: 'pre-wrap' }}>{Pro ? Pro.EULAContent : LicenseContent}</pre></DialogContent>diff --git a/app/components/dialogs/LocalForm.js b/app/components/dialogs/LocalForm.jsindex 5331bfad5..45fdf5ca1 100644--- a/app/components/dialogs/LocalForm.js+++ b/app/components/dialogs/LocalForm.js@@ -42,15 +42,20 @@ type Props = {class LocalForm extends React.Component<Props> {openDirectory = () => {if (AppConfig.isElectron) {- PlatformIO.selectDirectoryDialog().then((selectedPaths) => {- this.props.handleChange('path', selectedPaths[0]);- if (this.props.state.name.length < 1) {- this.props.handleChange('name', extractDirectoryName(selectedPaths[0]));- }- return true;- }).catch((err) => {- console.log('selectDirectoryDialog failed with: ' + err);- });+ PlatformIO.selectDirectoryDialog()+ .then(selectedPaths => {+ this.props.handleChange('path', selectedPaths[0]);+ if (this.props.state.name.length < 1) {+ this.props.handleChange(+ 'name',+ extractDirectoryName(selectedPaths[0])+ );+ }+ return true;+ })+ .catch(err => {+ console.log('selectDirectoryDialog failed with: ' + err);+ });} else {this.props.showSelectDirectoryDialog();}@@ -61,10 +66,7 @@ class LocalForm extends React.Component<Props> {return (<div>- <FormControl- fullWidth={true}- error={state.errorTextName}- >+ <FormControl fullWidth={true} error={state.errorTextName}><TextFielderror={state.errorTextName}required@@ -77,13 +79,14 @@ class LocalForm extends React.Component<Props> {data-tid="locationName"fullWidth={true}/>- {state.errorTextName && <FormHelperText>{i18n.t('core:invalidName')}</FormHelperText>}+ {state.errorTextName && (+ <FormHelperText>{i18n.t('core:invalidName')}</FormHelperText>+ )}</FormControl>- <FormControl- fullWidth={true}- error={state.errorTextPath}- >- <InputLabel htmlFor="path">{i18n.t('core:createLocationPath')}</InputLabel>+ <FormControl fullWidth={true} error={state.errorTextPath}>+ <InputLabel htmlFor="path">+ {i18n.t('core:createLocationPath')}+ </InputLabel><Inputrequiredmargin="dense"@@ -95,15 +98,15 @@ class LocalForm extends React.Component<Props> {value={state.path}endAdornment={<InputAdornment position="end" style={{ height: 32 }}>- <IconButton- onClick={this.openDirectory}- >+ <IconButton onClick={this.openDirectory}><FolderIcon /></IconButton></InputAdornment>}/>- {state.errorTextPath && <FormHelperText>{i18n.t('core:invalidPath')}</FormHelperText>}+ {state.errorTextPath && (+ <FormHelperText>{i18n.t('core:invalidPath')}</FormHelperText>+ )}</FormControl></div>);diff --git a/app/components/dialogs/MoveCopyFilesDialog.js b/app/components/dialogs/MoveCopyFilesDialog.jsindex a4b2e8058..6b9c7d36c 100644--- a/app/components/dialogs/MoveCopyFilesDialog.js+++ b/app/components/dialogs/MoveCopyFilesDialog.js@@ -97,12 +97,14 @@ const MoveCopyFilesDialog = (props: Props) => {function selectDirectory() {if (AppConfig.isElectron) {- PlatformIO.selectDirectoryDialog().then(selectedPaths => {- setTargetPath(selectedPaths[0]);- return true;- }).catch((err) => {- console.log('selectDirectoryDialog failed with: ' + err);- });+ PlatformIO.selectDirectoryDialog()+ .then(selectedPaths => {+ setTargetPath(selectedPaths[0]);+ return true;+ })+ .catch(err => {+ console.log('selectDirectoryDialog failed with: ' + err);+ });} else {// TODO handle case on other platforms// this.props.showSelectDirectoryDialog();@@ -121,14 +123,18 @@ const MoveCopyFilesDialog = (props: Props) => {<DialogTitle>{i18n.t('core:copyMoveFilesTitle')}</DialogTitle><DialogContent><List dense style={{ width: 550 }}>- {props.selectedFiles && props.selectedFiles.length > 0 && props.selectedFiles.map(path => (- <ListItem title={path}>- <ListItemIcon>- <FileIcon />- </ListItemIcon>- <Typography variant="inherit" noWrap>{extractFileName(path)}</Typography>- </ListItem>- ))}+ {props.selectedFiles &&+ props.selectedFiles.length > 0 &&+ props.selectedFiles.map(path => (+ <ListItem title={path}>+ <ListItemIcon>+ <FileIcon />+ </ListItemIcon>+ <Typography variant="inherit" noWrap>+ {extractFileName(path)}+ </Typography>+ </ListItem>+ ))}</List><FormControl fullWidth={true}><Input@@ -145,25 +151,25 @@ const MoveCopyFilesDialog = (props: Props) => {}}value={targetPath}endAdornment={- PlatformIO.haveObjectStoreSupport() || AppConfig.isWeb ? undefined :- (<InputAdornment position="end" style={{ height: 33 }}>+ PlatformIO.haveObjectStoreSupport() || AppConfig.isWeb ? (+ undefined+ ) : (+ <InputAdornment position="end" style={{ height: 33 }}><IconButtondata-tid="openDirectoryMoveCopyDialog"onClick={selectDirectory}><FolderIcon /></IconButton>- </InputAdornment>)+ </InputAdornment>+ )}/>{inputError && <FormHelperText>Empty Input Field</FormHelperText>}</FormControl></DialogContent><DialogActions>- <Button- data-tid="closeMoveCopyDialog"- onClick={props.onClose}- >+ <Button data-tid="closeMoveCopyDialog" onClick={props.onClose}>{i18n.t('core:cancel')}</Button><Button@@ -183,17 +189,21 @@ const MoveCopyFilesDialog = (props: Props) => {{i18n.t('core:copyFilesButton')}</Button></DialogActions>- </Dialog>+ </Dialog>);-}+};function mapActionCreatorsToProps(dispatch) {- return bindActionCreators({- copyFiles: IOActions.copyFiles,- moveFiles: IOActions.moveFiles- }, dispatch);+ return bindActionCreators(+ {+ copyFiles: IOActions.copyFiles,+ moveFiles: IOActions.moveFiles+ },+ dispatch+ );}-export default connect(null, mapActionCreatorsToProps)(- withMobileDialog()(MoveCopyFilesDialog)-);+export default connect(+ null,+ mapActionCreatorsToProps+)(withMobileDialog()(MoveCopyFilesDialog));diff --git a/app/components/dialogs/ObjectStoreForm.js b/app/components/dialogs/ObjectStoreForm.jsindex 3bdf0d3c8..ecb9aa4e8 100644--- a/app/components/dialogs/ObjectStoreForm.js+++ b/app/components/dialogs/ObjectStoreForm.js@@ -38,7 +38,10 @@ export const suggestions = [{ label: 'us-west-1 (US West N. California)', value: 'us-west-1' },{ label: 'us-west-2 (US West Oregon)', value: 'us-west-2' },{ label: 'ap-south-1 (Asia Pacific Mumbai)', value: 'ap-south-1' },- { label: 'ap-northeast-3 (Asia Pacific Osaka-Local)', value: 'ap-northeast-3' },+ {+ label: 'ap-northeast-3 (Asia Pacific Osaka-Local)',+ value: 'ap-northeast-3'+ },{ label: 'ap-northeast-2 (Asia Pacific Seoul)', value: 'ap-northeast-2' },{ label: 'ap-southeast-1 (Asia Pacific Singapore)', value: 'ap-southeast-1' },{ label: 'ap-southeast-2 (Asia Pacific Sydney)', value: 'ap-southeast-2' },@@ -50,13 +53,13 @@ export const suggestions = [{ label: 'eu-west-1 (EU Ireland)', value: 'eu-west-1' },{ label: 'eu-west-2 (EU London)', value: 'eu-west-2' },{ label: 'eu-west-3 (EU Paris)', value: 'eu-west-3' },- { label: 'sa-east-1 (South America São Paulo)', value: 'sa-east-1' },+ { label: 'sa-east-1 (South America São Paulo)', value: 'sa-east-1' }];const styles = theme => ({root: {flexGrow: 1,- height: 250,+ height: 250},input: {display: 'flex',@@ -69,29 +72,29 @@ const styles = theme => ({flexWrap: 'wrap',flex: 1,alignItems: 'center',- overflow: 'hidden',+ overflow: 'hidden'},noOptionsMessage: {- padding: theme.spacing(1, 2),+ padding: theme.spacing(1, 2)},singleValue: {- fontSize: 16,+ fontSize: 16},placeholder: {position: 'absolute',left: 2,- fontSize: 16,+ fontSize: 16},paper: {// position: 'absolute',zIndex: 1,marginTop: theme.spacing(1),left: 0,- right: 0,+ right: 0},divider: {- height: theme.spacing(2),- },+ height: theme.spacing(2)+ }});function NoOptionsMessage(props) {@@ -120,8 +123,8 @@ function Control(props) {className: props.selectProps.classes.input,inputRef: props.innerRef,children: props.children,- ...props.innerProps,- },+ ...props.innerProps+ }}}{...props.selectProps.textFieldProps}/>@@ -135,7 +138,7 @@ function Option(props) {selected={props.isFocused}component="div"style={{- fontWeight: props.isSelected ? 500 : 400,+ fontWeight: props.isSelected ? 500 : 400}}{...props.innerProps}>@@ -158,19 +161,31 @@ function Placeholder(props) {function SingleValue(props) {return (- <Typography className={props.selectProps.classes.singleValue} {...props.innerProps}>+ <Typography+ className={props.selectProps.classes.singleValue}+ {...props.innerProps}+ >{props.children}</Typography>);}function ValueContainer(props) {- return <div className={props.selectProps.classes.valueContainer}>{props.children}</div>;+ return (+ <div className={props.selectProps.classes.valueContainer}>+ {props.children}+ </div>+ );}function Menu(props) {return (- <Paper elevation={2} square className={props.selectProps.classes.paper} {...props.innerProps}>+ <Paper+ elevation={2}+ square+ className={props.selectProps.classes.paper}+ {...props.innerProps}+ >{props.children}</Paper>);@@ -184,7 +199,7 @@ const components = {Option,Placeholder,SingleValue,- ValueContainer,+ ValueContainer};type Props = {@@ -202,7 +217,10 @@ class ObjectStoreForm extends React.Component<Props> {handleInputSelectChange = (inputValue: any, actionMeta: any) => {if (actionMeta.action === 'set-value') {- suggestions.push({ label: this.props.state.region, value: this.props.state.region });+ suggestions.push({+ label: this.props.state.region,+ value: this.props.state.region+ });} else if (actionMeta.action === 'input-change') {this.props.handleChange('region', inputValue);}@@ -216,19 +234,18 @@ class ObjectStoreForm extends React.Component<Props> {...base,color: theme.palette.text.primary,'& input': {- font: 'inherit',- },- }),+ font: 'inherit'+ }+ })};return (<Grid container spacing={2}><Grid item xs={12}>- <FormControl- fullWidth={true}- error={state.cloudErrorTextName}- >- <InputLabel htmlFor="storeName">{i18n.t('core:createLocationName')}</InputLabel>+ <FormControl fullWidth={true} error={state.cloudErrorTextName}>+ <InputLabel htmlFor="storeName">+ {i18n.t('core:createLocationName')}+ </InputLabel><Inputrequiredmargin="dense"@@ -239,15 +256,16 @@ class ObjectStoreForm extends React.Component<Props> {onChange={handleInputChange}value={state.storeName}/>- {state.cloudErrorTextName && <FormHelperText>{i18n.t('core:invalidName')}</FormHelperText>}+ {state.cloudErrorTextName && (+ <FormHelperText>{i18n.t('core:invalidName')}</FormHelperText>+ )}</FormControl></Grid><Grid item xs={12}>- <FormControl- fullWidth={true}- error={state.cloudErrorTextPath}- >- <InputLabel htmlFor="path">{i18n.t('core:createLocationPath')}</InputLabel>+ <FormControl fullWidth={true} error={state.cloudErrorTextPath}>+ <InputLabel htmlFor="path">+ {i18n.t('core:createLocationPath')}+ </InputLabel><Inputmargin="dense"name="storePath"@@ -257,15 +275,16 @@ class ObjectStoreForm extends React.Component<Props> {onChange={handleInputChange}value={state.storePath}/>- {state.cloudErrorTextPath && <FormHelperText>{i18n.t('core:invalidPath')}</FormHelperText>}+ {state.cloudErrorTextPath && (+ <FormHelperText>{i18n.t('core:invalidPath')}</FormHelperText>+ )}</FormControl></Grid><Grid item xs={12}>- <FormControl- fullWidth={true}- error={state.cloudErrorAccessKey}- >- <InputLabel htmlFor="accessKeyId">{i18n.t('core:accessKeyId')}</InputLabel>+ <FormControl fullWidth={true} error={state.cloudErrorAccessKey}>+ <InputLabel htmlFor="accessKeyId">+ {i18n.t('core:accessKeyId')}+ </InputLabel><Inputmargin="dense"name="accessKeyId"@@ -275,15 +294,16 @@ class ObjectStoreForm extends React.Component<Props> {onChange={handleInputChange}value={state.accessKeyId}/>- {state.cloudErrorAccessKey && <FormHelperText>{i18n.t('core:invalidAccessKey')}</FormHelperText>}+ {state.cloudErrorAccessKey && (+ <FormHelperText>{i18n.t('core:invalidAccessKey')}</FormHelperText>+ )}</FormControl></Grid><Grid item xs={12}>- <FormControl- fullWidth={true}- error={state.cloudErrorSecretAccessKey}- >- <InputLabel htmlFor="secretAccessKey">{i18n.t('core:secretAccessKey')}</InputLabel>+ <FormControl fullWidth={true} error={state.cloudErrorSecretAccessKey}>+ <InputLabel htmlFor="secretAccessKey">+ {i18n.t('core:secretAccessKey')}+ </InputLabel><Inputmargin="dense"name="secretAccessKey"@@ -294,12 +314,18 @@ class ObjectStoreForm extends React.Component<Props> {onChange={handleInputChange}value={state.secretAccessKey}/>- {state.cloudErrorSecretAccessKey && <FormHelperText>{i18n.t('core:invalidSecretAccessKey')}</FormHelperText>}+ {state.cloudErrorSecretAccessKey && (+ <FormHelperText>+ {i18n.t('core:invalidSecretAccessKey')}+ </FormHelperText>+ )}</FormControl></Grid><Grid item xs={5}><FormControl error={state.cloudErrorBucketName}>- <InputLabel htmlFor="bucketName">{i18n.t('core:bucketName')}</InputLabel>+ <InputLabel htmlFor="bucketName">+ {i18n.t('core:bucketName')}+ </InputLabel><Inputrequiredmargin="dense"@@ -310,7 +336,11 @@ class ObjectStoreForm extends React.Component<Props> {onChange={handleInputChange}value={state.bucketName}/>- {state.cloudErrorBucketName && <FormHelperText>{i18n.t('core:invalidBucketName')}</FormHelperText>}+ {state.cloudErrorBucketName && (+ <FormHelperText>+ {i18n.t('core:invalidBucketName')}+ </FormHelperText>+ )}</FormControl></Grid><Grid item xs={7}>@@ -329,12 +359,13 @@ class ObjectStoreForm extends React.Component<Props> {placeholder={i18n.t('core:regionSearch')}/></NoSsr>- {state.cloudErrorRegion && <FormHelperText>{i18n.t('core:invalidRegion')}</FormHelperText>}+ {state.cloudErrorRegion && (+ <FormHelperText>{i18n.t('core:invalidRegion')}</FormHelperText>+ )}</FormControl></Grid></Grid>);-}}diff --git a/app/components/dialogs/OnboardingDialog.js b/app/components/dialogs/OnboardingDialog.jsindex 412a0a1b5..38335fcb3 100644--- a/app/components/dialogs/OnboardingDialog.js+++ b/app/components/dialogs/OnboardingDialog.js@@ -66,20 +66,16 @@ type Props = {const OnboardingDialog = (props: Props) => {const [activeStep, setActiveStep] = useState(0);const [isPersistTagsInSidecar, setIsPersistTagInSidecar] = useState(false);- const {- fullScreen,- open,- onClose- } = props;+ const { fullScreen, open, onClose } = props;let maxSteps = 5;function handleNext() {- setActiveStep(activeStep => activeStep + 1)+ setActiveStep(activeStep => activeStep + 1);}function handleBack() {- setActiveStep(activeStep => activeStep - 1)+ setActiveStep(activeStep => activeStep - 1);}function handleStepChange(activeStep) {@@ -124,15 +120,13 @@ const OnboardingDialog = (props: Props) => {<ToggleButtonGroupvalue={props.currentTheme}exclusive- onChange={(event, theme) => { props.setCurrentTheme(theme); }}+ onChange={(event, theme) => {+ props.setCurrentTheme(theme);+ }}style={{ boxShadow: 'none' }}>- <ToggleButton value="light">- Light- </ToggleButton>- <ToggleButton value="dark">- Dark- </ToggleButton>+ <ToggleButton value="light">Light</ToggleButton>+ <ToggleButton value="dark">Dark</ToggleButton></ToggleButtonGroup></div><div@@ -149,14 +143,22 @@ const OnboardingDialog = (props: Props) => {</div><divstyle={{-textAlign: 'center'}}>- <Typography variant="h5">Choose your the default tagging method for files</Typography>+ <Typography variant="h5">+ Choose your the default tagging method for files+ </Typography><Typography variant="h5"> </Typography>- <Typography variant="body">Core functionality of the application the ability to add tags to files and folders. Here you can choose how tags will applied on files.</Typography>- <FormControl style={{ marginTop: 20, marginBottom: 20 }} component="fieldset">+ <Typography variant="body">+ Core functionality of the application the ability to add tags to+ files and folders. Here you can choose how tags will applied on+ files.+ </Typography>+ <FormControl+ style={{ marginTop: 20, marginBottom: 20 }}+ component="fieldset"+ ><RadioGrouparia-label="Gender"name="isPersistTagsInSidecar"@@ -165,11 +167,12 @@ const OnboardingDialog = (props: Props) => {><FormControlLabelvalue="false"- control={- <Radio checked={!props.isPersistTagsInSidecar} />- }+ control={<Radio checked={!props.isPersistTagsInSidecar} />}label={- <Typography variant="subtitle1" style={{ textAlign: 'left' }}>+ <Typography+ variant="subtitle1"+ style={{ textAlign: 'left' }}+ >Use the name of file for saving the tags - Tagging thefile <strong>image.jpg</strong> with a tag{' '}<strong>sunset</strong> will rename it to{' '}@@ -181,16 +184,18 @@ const OnboardingDialog = (props: Props) => {<FormControlLabelstyle={{ marginTop: 20 }}value="true"- control={- <Radio checked={props.isPersistTagsInSidecar} />- }+ control={<Radio checked={props.isPersistTagsInSidecar} />}label={- <Typography variant="subtitle1" style={{ textAlign: 'left' }}>+ <Typography+ variant="subtitle1"+ style={{ textAlign: 'left' }}+ >Use sidecar file for saving the tags - Tagging the file{' '}<strong>image.jpg</strong> with a tag{' '}<strong>sunset</strong> will save this tag in an- additional sidecar file called <strong>image.jpg.json</strong>{' '}- located in a sub folder with the name <strong>.ts</strong>+ additional sidecar file called{' '}+ <strong>image.jpg.json</strong> located in a sub folder+ with the name <strong>.ts</strong></Typography>}/>@@ -201,21 +206,31 @@ const OnboardingDialog = (props: Props) => {/></RadioGroup></FormControl>- <Typography variant="body">You can always revise you decision and change the tagging method. But tags already tagged by renaming the files will stay renamed and the created sidecar file containing tags will stay.</Typography>+ <Typography variant="body">+ You can always revise you decision and change the tagging method.+ But tags already tagged by renaming the files will stay renamed+ and the created sidecar file containing tags will stay.+ </Typography></div><divstyle={{textAlign: 'center'}}>- <Typography variant="h5">Collect web content in Chrome and Firefox</Typography>+ <Typography variant="h5">+ Collect web content in Chrome and Firefox+ </Typography><imgstyle={{ maxHeight: 300, marginTop: 15 }}src={BrowserExtension}alt=""/>- <Typography variant="h6">We have a web clipper extension for your browser.</Typography>- <Typography variant="h6">It is open source and available for free on the official stores.</Typography>+ <Typography variant="h6">+ We have a web clipper extension for your browser.+ </Typography>+ <Typography variant="h6">+ It is open source and available for free on the official stores.+ </Typography><Buttonstyle={{ marginTop: 20 }}onClick={() => {@@ -251,7 +266,7 @@ const OnboardingDialog = (props: Props) => {position="static"activeStep={activeStep}nextButton={- (activeStep === maxSteps - 1) ? (+ activeStep === maxSteps - 1 ? (<Buttonsize="small"onClick={props.onClose}@@ -259,14 +274,17 @@ const OnboardingDialog = (props: Props) => {color="primary"style={{ marginLeft: 5 }}data-tid="startTagSpacesAfterOnboarding"- >Start using TagSpaces+ >+ Start using TagSpaces</Button>) : (<Buttonsize="small"onClick={handleNext}data-tid="nextStepOnboarding"- >{i18n.t('core:next')}</Button>+ >+ {i18n.t('core:next')}+ </Button>)}backButton={@@ -274,7 +292,9 @@ const OnboardingDialog = (props: Props) => {size="small"onClick={handleBack}disabled={activeStep === 0}- >{i18n.t('core:prev')}</Button>+ >+ {i18n.t('core:prev')}+ </Button>}/></DialogActions>diff --git a/app/components/dialogs/ProTeaserDialog.js b/app/components/dialogs/ProTeaserDialog.jsindex b0dbb0bab..93a5b5ad9 100644--- a/app/components/dialogs/ProTeaserDialog.js+++ b/app/components/dialogs/ProTeaserDialog.js@@ -50,7 +50,7 @@ type State = {class ProTeaserDialog extends React.Component<Props, State> {state = {- activeStep: 0,+ activeStep: 0};maxSteps = 7;@@ -77,11 +77,7 @@ class ProTeaserDialog extends React.Component<Props, State> {padding: 5,textAlign: 'left'};- const {- fullScreen,- open,- onClose- } = this.props;+ const { fullScreen, open, onClose } = this.props;return (<Dialog@@ -91,192 +87,335 @@ class ProTeaserDialog extends React.Component<Props, State> {keepMountedscroll="paper">- <DialogContent- style={{ paddingBottom: 0 }}- >+ <DialogContent style={{ paddingBottom: 0 }}><SwipeableViewsindex={activeStep}onChangeIndex={this.handleStepChange}enableMouseEvents><div style={slideStyles}>- <Typography variant="h5" style={{ textAlign: 'center' }}>TagSpaces Pro - Key Features</Typography>+ <Typography variant="h5" style={{ textAlign: 'center' }}>+ TagSpaces Pro - Key Features+ </Typography><br />- <Typography variant="subtitle1">★ Connect AWS S3 object storages (buckets) as locations</Typography>- <Typography variant="subtitle1">★ Advanced search with full text support for some file types</Typography>- <Typography variant="subtitle1">★ Description and custom thumbnails for files and folder</Typography>- <Typography variant="subtitle1">★ Custom background color for folders</Typography>- <Typography variant="subtitle1">★ Advanced tagging with geo location support</Typography>- <Typography variant="subtitle1">★ Generating persistent thumbnails</Typography>+ <Typography variant="subtitle1">+ ★ Connect AWS S3 object storages (buckets) as locations+ </Typography>+ <Typography variant="subtitle1">+ ★ Advanced search with full text support for some file+ types+ </Typography>+ <Typography variant="subtitle1">+ ★ Description and custom thumbnails for files and folder+ </Typography>+ <Typography variant="subtitle1">+ ★ Custom background color for folders+ </Typography>+ <Typography variant="subtitle1">+ ★ Advanced tagging with geo location support+ </Typography>+ <Typography variant="subtitle1">+ ★ Generating persistent thumbnails+ </Typography><Typography variant="subtitle1"> </Typography><div style={{ textAlign: 'center' }}><imgstyle={{maxHeight: 150,marginTop: 15,- marginBottom: 15,+ marginBottom: 15}}src={DecideImage}alt=""/><br /><Button- onClick={() => { this.props.openURLExternally(AppConfig.links.productsOverview); }}+ onClick={() => {+ this.props.openURLExternally(+ AppConfig.links.productsOverview+ );+ }}variant="contained"color="primary"- >Open Product Comparison</Button>+ >+ Open Product Comparison+ </Button></div></div><div style={slideStyles}>- <Typography variant="h5" style={{ textAlign: 'center' }}>Advanced Search Options</Typography>+ <Typography variant="h5" style={{ textAlign: 'center' }}>+ Advanced Search Options+ </Typography><br /><Typography variant="h6">Full text search</Typography>- <Typography variant="subtitle1">★ Keywords from your text files will be included in the index</Typography>- <Typography variant="subtitle1">★ Currently we support TXT, MD and HTML files</Typography>+ <Typography variant="subtitle1">+ ★ Keywords from your text files will be included in the+ index+ </Typography>+ <Typography variant="subtitle1">+ ★ Currently we support TXT, MD and HTML files+ </Typography><Typography variant="h6">Filter by file type</Typography>- <Typography variant="subtitle1">★ Documents, Notes, Audio files, Video files, Archives, Bookmarks, eBooks</Typography>- <Typography variant="subtitle1">★ Filter for files, folders and untagged files</Typography>- <Typography variant="h6">Filter by size, date and gps-coordinates</Typography>+ <Typography variant="subtitle1">+ ★ Documents, Notes, Audio files, Video files, Archives,+ Bookmarks, eBooks+ </Typography>+ <Typography variant="subtitle1">+ ★ Filter for files, folders and untagged files+ </Typography>+ <Typography variant="h6">+ Filter by size, date and gps-coordinates+ </Typography><div style={{ textAlign: 'center' }}><imgstyle={{maxHeight: 150,marginTop: 15,- marginBottom: 15,+ marginBottom: 15}}src={SearchImage}alt=""/><br /><Button- onClick={() => this.props.openURLExternally(AppConfig.links.productProAdvancedSearch)}+ onClick={() =>+ this.props.openURLExternally(+ AppConfig.links.productProAdvancedSearch+ )+ }variant="contained"color="primary"- >Learn more</Button>+ >+ Learn more+ </Button></div></div><div style={slideStyles}>- <Typography variant="h5" style={{ textAlign: 'center' }}>Connect S3 object storages as locations</Typography>+ <Typography variant="h5" style={{ textAlign: 'center' }}>+ Connect S3 object storages as locations+ </Typography><br />- <Typography variant="subtitle1">With this feature, TagSpaces Pro supports the AWS S3 buckets as file storage. In general it enables you to creating a location pointing to a remote object storages also knows as buckets on AWS S3 infrastructure. By doing this, you get a full-fledged <strong>file organizer, browser and navigator for AWS buckets</strong>, directly in TagSpaces. You do not have to download every file separately and eventually upload it back in order to preview, edit or annotate it.+ <Typography variant="subtitle1">+ With this feature, TagSpaces Pro supports the AWS S3 buckets as+ file storage. In general it enables you to creating a location+ pointing to a remote object storages also knows as buckets on+ AWS S3 infrastructure. By doing this, you get a full-fledged{' '}+ <strong>+ file organizer, browser and navigator for AWS buckets+ </strong>+ , directly in TagSpaces. You do not have to download every file+ separately and eventually upload it back in order to preview,+ edit or annotate it.</Typography><div style={{ textAlign: 'center' }}><imgstyle={{maxHeight: 120,marginTop: 15,- marginBottom: 15,+ marginBottom: 15}}src={CloudImage}alt=""- /><br />+ />+ <br /><Button- onClick={() => this.props.openURLExternally(AppConfig.links.productProObjectStore)}+ onClick={() =>+ this.props.openURLExternally(+ AppConfig.links.productProObjectStore+ )+ }variant="contained"color="primary"- >Learn more</Button>+ >+ Learn more+ </Button></div></div><div style={slideStyles}>- <Typography variant="h5" style={{ textAlign: 'center' }}>Annotate your files and folders visually</Typography>+ <Typography variant="h5" style={{ textAlign: 'center' }}>+ Annotate your files and folders visually+ </Typography><br />- <Typography variant="subtitle1">★ Add <b>custom description</b> to every document, photo or folder</Typography>- <Typography variant="subtitle1">★ The description can be in markdown allowing images and links</Typography>- <Typography variant="subtitle1">★ Set a <b>custom thumbnail</b> for every file or folder</Typography>- <Typography variant="subtitle1">★ Set a <b>custom background color</b> to folders</Typography>- <Typography variant="subtitle1">These features will enable you to find with ease your documents via the build-in search or just visually.</Typography>+ <Typography variant="subtitle1">+ ★ Add <b>custom description</b> to every document, photo+ or folder+ </Typography>+ <Typography variant="subtitle1">+ ★ The description can be in markdown allowing images and+ links+ </Typography>+ <Typography variant="subtitle1">+ ★ Set a <b>custom thumbnail</b> for every file or folder+ </Typography>+ <Typography variant="subtitle1">+ ★ Set a <b>custom background color</b> to folders+ </Typography>+ <Typography variant="subtitle1">+ These features will enable you to find with ease your documents+ via the build-in search or just visually.+ </Typography><div style={{ textAlign: 'center' }}><imgstyle={{maxHeight: 200,marginTop: 15,- marginBottom: 15,+ marginBottom: 15}}src={AnnotateImage}alt=""- /><br />+ />+ <br /><Button- onClick={() => this.props.openURLExternally(AppConfig.links.productProFileFolderMeta)}+ onClick={() =>+ this.props.openURLExternally(+ AppConfig.links.productProFileFolderMeta+ )+ }variant="contained"color="primary"- >Learn more</Button>+ >+ Learn more+ </Button></div></div><div style={slideStyles}>- <Typography variant="h5" style={{ textAlign: 'center' }}>Tag with geo coordinates</Typography>+ <Typography variant="h5" style={{ textAlign: 'center' }}>+ Tag with geo coordinates+ </Typography><br />- <Typography variant="subtitle1">★ This feature can be used to add geo coordinates to every file or folder. </Typography>- <Typography variant="subtitle1">★ Dedicated perspective for showing geo-tags on a build-in map</Typography>- <Typography variant="subtitle1">★ Extract geo location data from EXIF in JPGs files.</Typography>- <Typography variant="subtitle1">★ Useful for planing or documenting trips and vacations.</Typography>- <Typography variant="subtitle1">★ Useful for adding annotations for places on a map.</Typography>+ <Typography variant="subtitle1">+ ★ This feature can be used to add geo coordinates to+ every file or folder.{' '}+ </Typography>+ <Typography variant="subtitle1">+ ★ Dedicated perspective for showing geo-tags on a+ build-in map+ </Typography>+ <Typography variant="subtitle1">+ ★ Extract geo location data from EXIF in JPGs files.+ </Typography>+ <Typography variant="subtitle1">+ ★ Useful for planing or documenting trips and vacations.+ </Typography>+ <Typography variant="subtitle1">+ ★ Useful for adding annotations for places on a map.+ </Typography><div style={{ textAlign: 'center' }}><imgstyle={{maxHeight: 200,marginTop: 15,- marginBottom: 15,+ marginBottom: 15}}src={MapImage}alt=""- /><br />+ />+ <br /><Button- onClick={() => this.props.openURLExternally(AppConfig.links.productProGeoTagging)}+ onClick={() =>+ this.props.openURLExternally(+ AppConfig.links.productProGeoTagging+ )+ }variant="contained"color="primary"- >Learn more</Button>+ >+ Learn more+ </Button></div></div><div style={slideStyles}>- <Typography variant="h5" style={{ textAlign: 'center' }}>Generating persistent thumbnails</Typography>+ <Typography variant="h5" style={{ textAlign: 'center' }}>+ Generating persistent thumbnails+ </Typography><br />- <Typography variant="subtitle1">TagSpaces Pro generates persistent thumbnails for many file type such as: images, videos, notes, source code, office documents, bookmarks, ebooks, archives and PDFs.</Typography>+ <Typography variant="subtitle1">+ TagSpaces Pro generates persistent thumbnails for many file type+ such as: images, videos, notes, source code, office documents,+ bookmarks, ebooks, archives and PDFs.+ </Typography><div style={{ textAlign: 'center' }}><imgstyle={{maxHeight: 200,marginTop: 15,- marginBottom: 15,+ marginBottom: 15}}src={ThumbsImage}alt=""- /><br />+ />+ <br /><Button- onClick={() => this.props.openURLExternally(AppConfig.links.productProThumbnailsGeneration)}+ onClick={() =>+ this.props.openURLExternally(+ AppConfig.links.productProThumbnailsGeneration+ )+ }variant="contained"color="primary"- >Learn more</Button>+ >+ Learn more+ </Button></div></div><div style={slideStyles}>- <Typography variant="h5" style={{ textAlign: 'center' }}>TagSpaces Enterprise</Typography>+ <Typography variant="h5" style={{ textAlign: 'center' }}>+ TagSpaces Enterprise+ </Typography><br />- <Typography variant="subtitle1">★ On-prem web based version of TagSpaces Pro</Typography>- <Typography variant="subtitle1">★ PWA version of TagSpaces Pro optimized for use om mobile devices</Typography>- <Typography variant="subtitle1">★ White label packages, with custom colors and logo</Typography>- <Typography variant="subtitle1">★ Development of custom viewers for file (e.g. 3D-assets, medical data ...)</Typography>- <Typography variant="subtitle1">★ Development of custom perspectives for folders (e.g. graphs, maps, trees)</Typography>- <Typography variant="subtitle1">★ Premium technical support and signed installers</Typography>+ <Typography variant="subtitle1">+ ★ On-prem web based version of TagSpaces Pro+ </Typography>+ <Typography variant="subtitle1">+ ★ PWA version of TagSpaces Pro optimized for use om+ mobile devices+ </Typography>+ <Typography variant="subtitle1">+ ★ White label packages, with custom colors and logo+ </Typography>+ <Typography variant="subtitle1">+ ★ Development of custom viewers for file (e.g. 3D-assets,+ medical data ...)+ </Typography>+ <Typography variant="subtitle1">+ ★ Development of custom perspectives for folders (e.g.+ graphs, maps, trees)+ </Typography>+ <Typography variant="subtitle1">+ ★ Premium technical support and signed installers+ </Typography><div style={{ textAlign: 'center' }}><imgstyle={{maxHeight: 200,marginTop: 15,- marginBottom: 15,+ marginBottom: 15}}src={EnterpriseImage}alt=""- /><br />+ />+ <br /><Button- onClick={() => this.props.openURLExternally(AppConfig.links.productsOverview)}+ onClick={() =>+ this.props.openURLExternally(+ AppConfig.links.productsOverview+ )+ }variant="outlined"color="primary"- >Product Landscape</Button> + >+ Product Landscape+ </Button>+ <Button- onClick={() => this.props.openURLExternally('mailto:[email protected]')}+ onClick={() =>+ this.props.openURLExternally('mailto:[email protected]')+ }variant="outlined"color="primary"- >{i18n.t('core:emailContact')}</Button>+ >+ {i18n.t('core:emailContact')}+ </Button></div></div></SwipeableViews>@@ -288,16 +427,14 @@ class ProTeaserDialog extends React.Component<Props, State> {position="static"activeStep={this.state.activeStep}nextButton={- (this.state.activeStep === this.maxSteps - 1) ? (- <Button- size="small"- onClick={this.props.onClose}- >{i18n.t('core:closeButton')}</Button>+ this.state.activeStep === this.maxSteps - 1 ? (+ <Button size="small" onClick={this.props.onClose}>+ {i18n.t('core:closeButton')}+ </Button>) : (- <Button- size="small"- onClick={this.handleNext}- >{i18n.t('core:next')}</Button>+ <Button size="small" onClick={this.handleNext}>+ {i18n.t('core:next')}+ </Button>)}backButton={@@ -305,7 +442,9 @@ class ProTeaserDialog extends React.Component<Props, State> {size="small"onClick={this.handleBack}disabled={this.state.activeStep === 0}- >{i18n.t('core:prev')}</Button>+ >+ {i18n.t('core:prev')}+ </Button>}/></DialogActions>@@ -314,4 +453,4 @@ class ProTeaserDialog extends React.Component<Props, State> {}}-export default (withMobileDialog()(ProTeaserDialog));+export default withMobileDialog()(ProTeaserDialog);diff --git a/app/components/dialogs/RenameDirectoryDialog.js b/app/components/dialogs/RenameDirectoryDialog.jsindex 0bbb2114e..9184197a1 100644--- a/app/components/dialogs/RenameDirectoryDialog.js+++ b/app/components/dialogs/RenameDirectoryDialog.js@@ -49,13 +49,18 @@ class RenameDirectoryDialog extends React.Component<Props, State> {state = {inputError: false,disableConfirmButton: true,- name: this.props.selectedDirectoryPath ? extractDirectoryName(this.props.selectedDirectoryPath) : '',+ name: this.props.selectedDirectoryPath+ ? extractDirectoryName(this.props.selectedDirectoryPath)+ : ''};handleInputChange = (event: Object) => {- this.setState({- name: event.target.value- }, this.handleValidation);+ this.setState(+ {+ name: event.target.value+ },+ this.handleValidation+ );};handleValidation() {@@ -75,7 +80,10 @@ class RenameDirectoryDialog extends React.Component<Props, State> {onConfirm = () => {if (!this.state.disableConfirmButton) {- this.props.renameDirectory(this.props.selectedDirectoryPath, this.state.name);+ this.props.renameDirectory(+ this.props.selectedDirectoryPath,+ this.state.name+ );this.setState({inputError: false,disableConfirmButton: true@@ -85,24 +93,13 @@ class RenameDirectoryDialog extends React.Component<Props, State> {};render() {- const {- open,- onClose- } = this.props;+ const { open, onClose } = this.props;return (- <Dialog- open={open}- onClose={onClose}- keepMounted- scroll="paper"- >+ <Dialog open={open} onClose={onClose} keepMounted scroll="paper"><DialogTitle>{i18n.t('core:renameDirectory')}</DialogTitle><DialogContent>- <FormControl- fullWidth={true}- error={this.state.inputError}- >+ <FormControl fullWidth={true} error={this.state.inputError}><TextFieldfullWidth={true}autoFocus@@ -141,9 +138,12 @@ class RenameDirectoryDialog extends React.Component<Props, State> {}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.js b/app/components/dialogs/RenameFileDialog.jsindex 2c7d5aaae..2a1f1e095 100644--- a/app/components/dialogs/RenameFileDialog.js+++ b/app/components/dialogs/RenameFileDialog.js@@ -32,7 +32,10 @@ import FormHelperText from '@material-ui/core/FormHelperText';import { onEnterKeyHandler, DialogTransition } from './GenericDialog';import AppConfig from '../../config';import i18n from '../../services/i18n';-import { extractFileName, extractContainingDirectoryPath } from '../../utils/paths';+import {+ extractFileName,+ extractContainingDirectoryPath+} from '../../utils/paths';import { actions as AppActions } from '../../reducers/app';type Props = {@@ -63,7 +66,7 @@ class RenameFileDialog extends React.Component<Props, State> {state = {inputError: false,disableConfirmButton: true,- fileName: '',+ fileName: ''};componentWillReceiveProps = (nextProps: any) => {@@ -83,7 +86,7 @@ class RenameFileDialog extends React.Component<Props, State> {this.fileName.setSelectionRange(0, endRange);}return {- fileName,+ fileName};});}@@ -96,9 +99,12 @@ class RenameFileDialog extends React.Component<Props, State> {const value = target.type === 'checkbox' ? target.checked : target.value;const name = target.name;- this.setState({- [name]: value- }, this.handleValidation);+ this.setState(+ {+ [name]: value+ },+ this.handleValidation+ );};handleValidation() {@@ -111,8 +117,11 @@ class RenameFileDialog extends React.Component<Props, State> {onConfirm = () => {if (!this.state.disableConfirmButton) {- const fileDirectory = extractContainingDirectoryPath(this.props.selectedFilePath);- const newFilePath = fileDirectory + AppConfig.dirSeparator + this.state.fileName;+ 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 });@@ -137,14 +146,18 @@ class RenameFileDialog extends React.Component<Props, State> {margin="dense"name="fileName"autoFocus- inputRef={(ref) => { this.fileName = ref; }}+ 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>}+ {this.state.inputError && (+ <FormHelperText>Empty File Name</FormHelperText>+ )}</FormControl></DialogContent>);@@ -189,9 +202,15 @@ class RenameFileDialog extends React.Component<Props, State> {}function mapActionCreatorsToProps(dispatch) {- return bindActionCreators({- renameFile: AppActions.renameFile,- }, dispatch);+ return bindActionCreators(+ {+ renameFile: AppActions.renameFile+ },+ dispatch+ );}-export default connect(null, mapActionCreatorsToProps)(withStyles(styles)(RenameFileDialog));+export default connect(+ null,+ mapActionCreatorsToProps+)(withStyles(styles)(RenameFileDialog));diff --git a/app/components/dialogs/SelectDirectoryDialog.js b/app/components/dialogs/SelectDirectoryDialog.jsindex 4d674b4d5..1a6832526 100644--- a/app/components/dialogs/SelectDirectoryDialog.js+++ b/app/components/dialogs/SelectDirectoryDialog.js@@ -89,9 +89,34 @@ const styles = () => ({}});-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:'];+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:'+];class SelectDirectoryDialog extends React.Component<Props, State> {state = {@@ -102,7 +127,7 @@ class SelectDirectoryDialog extends React.Component<Props, State> {currentPath: PlatformIO.getUserHomePath(),subFolders: [],choosePath: '',- isDefault: false,+ isDefault: false};componentWillReceiveProps = (nextProps: any) => {@@ -121,14 +146,16 @@ class SelectDirectoryDialog extends React.Component<Props, State> {};loadListDirectory = (path: string) => {- loadSubFolders(path).then((rootDirContent) => {- this.setState({- subFolders: rootDirContent+ loadSubFolders(path)+ .then(rootDirContent => {+ this.setState({+ subFolders: rootDirContent+ });+ return true;+ })+ .catch(error => {+ console.log('Error listing directory ' + error);});- return true;- }).catch((error) => {- console.log('Error listing directory ' + error);- });};onConfirm = () => {@@ -160,7 +187,9 @@ class SelectDirectoryDialog extends React.Component<Props, State> {};onBackButton = () => {- const lastIndex = this.state.currentPath.lastIndexOf(AppConfig.dirSeparator);+ const lastIndex = this.state.currentPath.lastIndexOf(+ AppConfig.dirSeparator+ );const path = this.state.currentPath.slice(0, lastIndex);this.setState({currentPath: path@@ -173,7 +202,7 @@ class SelectDirectoryDialog extends React.Component<Props, State> {this.loadListDirectory(this.state.currentPath);};- renderDriveSuggestions = (drive) => (+ renderDriveSuggestions = drive => (<div className={styles.buttonContainer}><Buttonkey={drive.name}@@ -186,28 +215,23 @@ class SelectDirectoryDialog extends React.Component<Props, State> {);render() {- const {- fullScreen,- open,- onClose- } = this.props;+ const { fullScreen, open, onClose } = this.props;return (<Dialog- open={open}- onClose={onClose}- fullScreen={fullScreen}- keepMounted- scroll="paper"- // onKeyDown={confirmFunction}+ 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>+ <FormControl fullWidth={true} error={this.props.errorTextPath}>+ <InputLabel htmlFor="name">+ {i18n.t('core:selectDialogCurrentPath')}+ </InputLabel><InputfullWidth={true}required@@ -219,12 +243,12 @@ class SelectDirectoryDialog extends React.Component<Props, State> {value={this.state.currentPath}disabled={AppConfig.isWin}/>- {this.state.errorTextPath && <FormHelperText>{i18n.t('core:invalidPath')}</FormHelperText>}+ {this.state.errorTextPath && (+ <FormHelperText>{i18n.t('core:invalidPath')}</FormHelperText>+ )}</FormControl>{AppConfig.isWin ? (- <FormControl- fullWidth={true}- >+ <FormControl fullWidth={true}><Selectdata-tid="selectDirectoryDialogSelect"native@@ -234,14 +258,15 @@ class SelectDirectoryDialog extends React.Component<Props, State> {onChange={this.handleInputChange}input={<Input id="choosePath" />}>- {drives.map((drive) => (<option key={drive} value={drive}>{drive}</option>))}+ {drives.map(drive => (+ <option key={drive} value={drive}>+ {drive}+ </option>+ ))}</Select></FormControl>- ) : null- }- <FormControl- fullWidth={true}- >+ ) : null}+ <FormControl fullWidth={true}><Paper elevation={2}><Buttondata-tid="onBackButtonSelectDirectoryDialog"@@ -257,24 +282,19 @@ class SelectDirectoryDialog extends React.Component<Props, State> {{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>- )- :+ <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"- >+ <Button onClick={this.props.onClose} color="primary">{i18n.t('core:cancel')}</Button><Button@@ -285,9 +305,9 @@ class SelectDirectoryDialog extends React.Component<Props, State> {{i18n.t('core:ok')}</Button></DialogActions>- </Dialog>+ </Dialog>);- }+ }}export default withStyles(styles)(SelectDirectoryDialog);diff --git a/app/components/dialogs/ThirdPartyLibsDialog.js b/app/components/dialogs/ThirdPartyLibsDialog.jsindex 109845679..db5b05be0 100644--- a/app/components/dialogs/ThirdPartyLibsDialog.js+++ b/app/components/dialogs/ThirdPartyLibsDialog.js@@ -45,7 +45,7 @@ const ThirdPartyLibsDialog = (props: Props) => {><DialogTitle>{i18n.t('core:thirdPartyLibs')}</DialogTitle><DialogContent style={{ overflowX: 'auto' }}>- <pre style={{ whiteSpace: 'pre-wrap' }}>{ ThirdPartyLibs }</pre>+ <pre style={{ whiteSpace: 'pre-wrap' }}>{ThirdPartyLibs}</pre></DialogContent><DialogActions><Buttondiff --git a/app/components/dialogs/settings/SettingsDialog.js b/app/components/dialogs/settings/SettingsDialog.jsindex 070c77501..01939f3d1 100644--- a/app/components/dialogs/settings/SettingsDialog.js+++ b/app/components/dialogs/settings/SettingsDialog.js@@ -41,7 +41,7 @@ import AppConfig from '../../../config';const styles = theme => ({mainContent: {- overflowY: AppConfig.isFirefox ? 'auto' : 'overlay',+ overflowY: AppConfig.isFirefox ? 'auto' : 'overlay'}});@@ -74,15 +74,18 @@ class SettingsDialog extends React.Component<Props, State> {componentWillReceiveProps = nextProps => {const { settings } = nextProps;- const supportedFileTypes = settings.supportedFileTypes.reduce((accumulator, fileType) => {- const modifiedFileType = extend({}, fileType, {- id: fileType.id || uuidv1()- });- if (fileType.viewer !== '') {- accumulator.push(modifiedFileType);- }- return accumulator;- }, []);+ const supportedFileTypes = settings.supportedFileTypes.reduce(+ (accumulator, fileType) => {+ const modifiedFileType = extend({}, fileType, {+ id: fileType.id || uuidv1()+ });+ if (fileType.viewer !== '') {+ accumulator.push(modifiedFileType);+ }+ return accumulator;+ },+ []+ );this.setState({items: supportedFileTypes,@@ -94,7 +97,7 @@ class SettingsDialog extends React.Component<Props, State> {this.setState({ currentTab });};- onAddFileType = (item) => {+ onAddFileType = item => {const { items } = this.state;this.setState({ items: [...items, item] }, () => {const settingsFileTypeRef = this.settingsFileTypeRef;@@ -103,11 +106,17 @@ class SettingsDialog extends React.Component<Props, State> {});};- setSelectedItem = (selectedItem) => {+ setSelectedItem = selectedItem => {this.setState({ selectedItem });};- updateItems = (identifierKey, identifierValue, targetKey, targetValue, disableSave = false) => {+ updateItems = (+ identifierKey,+ identifierValue,+ targetKey,+ targetValue,+ disableSave = false+ ) => {const { items } = this.state;let isSaveable = false;let hasViewer = false;@@ -124,14 +133,19 @@ class SettingsDialog extends React.Component<Props, State> {return accumulator;}, []);- this.setState({- items: modifiedItems- }, () => {- if ((targetKey !== 'type' && isSaveable && !disableSave) ||- (targetKey === 'type' && hasViewer && isSaveable && !disableSave)) {- this.saveFileTypes();+ this.setState(+ {+ items: modifiedItems+ },+ () => {+ if (+ (targetKey !== 'type' && isSaveable && !disableSave) ||+ (targetKey === 'type' && hasViewer && isSaveable && !disableSave)+ ) {+ this.saveFileTypes();+ }}- });+ );};getDefaultFileTypeObject = () => ({@@ -164,9 +178,13 @@ class SettingsDialog extends React.Component<Props, State> {let isValid = true;items.map(item => {- const hasDuplicates = items.filter(targetItem => targetItem.type === item.type).length > 1;+ const hasDuplicates =+ items.filter(targetItem => targetItem.type === item.type).length > 1;- if (isValid && (item.type === '' || item.viewer === '' || hasDuplicates)) {+ if (+ isValid &&+ (item.type === '' || item.viewer === '' || hasDuplicates)+ ) {isValid = false;}return item;@@ -177,7 +195,9 @@ class SettingsDialog extends React.Component<Props, State> {removeItem = (itemForRemoval = Object) => {const { items } = this.state;- const filteredItems = items.filter(item => item.type !== itemForRemoval.type);+ const filteredItems = items.filter(+ item => item.type !== itemForRemoval.type+ );this.setState({ items: filteredItems }, () => this.saveFileTypes());};@@ -191,9 +211,18 @@ class SettingsDialog extends React.Component<Props, State> {indicatorColor="primary"variant="fullWidth">- <Tab data-tid="generalSettingsDialog" label={i18n.t('core:generalTab')} />- <Tab data-tid="fileTypeSettingsDialog" label={i18n.t('core:fileTypeTab')} />- <Tab data-tid="keyBindingsSettingsDialog" label={i18n.t('core:keyBindingsTab')} />+ <Tab+ data-tid="generalSettingsDialog"+ label={i18n.t('core:generalTab')}+ />+ <Tab+ data-tid="fileTypeSettingsDialog"+ label={i18n.t('core:fileTypeTab')}+ />+ <Tab+ data-tid="keyBindingsSettingsDialog"+ label={i18n.t('core:keyBindingsTab')}+ /></Tabs></AppBar></React.Fragment>@@ -201,7 +230,6 @@ class SettingsDialog extends React.Component<Props, State> {renderContent = () => (<DialogContent className={this.props.classes.mainContent}>-<ConfirmDialogopen={this.state.isConfirmDialogOpened}onClose={() => {@@ -226,9 +254,11 @@ class SettingsDialog extends React.Component<Props, State> {<divdata-tid="settingsDialog"className={this.props.classes.mainContent}- ref={el => { this.settingsFileTypeRef = el; }}+ ref={el => {+ this.settingsFileTypeRef = el;+ }}>- {this.state.currentTab === 0 && (<SettingsGeneral />)}+ {this.state.currentTab === 0 && <SettingsGeneral />}{this.state.currentTab === 1 && (<SettingsFileTypesitems={this.state.items}@@ -245,7 +275,7 @@ class SettingsDialog extends React.Component<Props, State> {}}/>)}- {this.state.currentTab === 2 && (<SettingsKeyBindings />)}+ {this.state.currentTab === 2 && <SettingsKeyBindings />}</div></DialogContent>);@@ -253,7 +283,8 @@ class SettingsDialog extends React.Component<Props, State> {renderActions = () => (<DialogActionsstyle={{- justifyContent: this.state.currentTab === 1 ? 'space-between' : 'flex-end'+ justifyContent:+ this.state.currentTab === 1 ? 'space-between' : 'flex-end'}}>{this.state.currentTab === 1 && (@@ -277,11 +308,7 @@ class SettingsDialog extends React.Component<Props, State> {);render() {- const {- fullScreen,- open,- onClose- } = this.props;+ const { fullScreen, open, onClose } = this.props;return (<GenericDialogopen={open}@@ -295,12 +322,16 @@ class SettingsDialog extends React.Component<Props, State> {}}-const mapStateToProps = (state) => ({+const mapStateToProps = state => ({settings: getSettings(state)});const mapDispatchToProps = dispatch => ({- setSupportedFileTypes: supportedFileTypes => dispatch(actions.setSupportedFileTypes(supportedFileTypes))+ setSupportedFileTypes: supportedFileTypes =>+ dispatch(actions.setSupportedFileTypes(supportedFileTypes))});-export default connect(mapStateToProps, mapDispatchToProps)(withMobileDialog()(withStyles(styles)(SettingsDialog)));+export default connect(+ mapStateToProps,+ mapDispatchToProps+)(withMobileDialog()(withStyles(styles)(SettingsDialog)));diff --git a/app/components/dialogs/settings/SettingsFileTypes.js b/app/components/dialogs/settings/SettingsFileTypes.jsindex 315e61af2..78e8c78a5 100644--- a/app/components/dialogs/settings/SettingsFileTypes.js+++ b/app/components/dialogs/settings/SettingsFileTypes.js@@ -40,25 +40,25 @@ const styles = theme => ({},fileExtension: {width: '15%',- padding: '0 12px 0 0',+ padding: '0 12px 0 0'},fileType: {paddingBottom: 0,paddingTop: 0,paddingRight: 0,- padding: '0 12px 0 0',+ padding: '0 12px 0 0'},fileOpener: {width: '25%',- padding: '0 12px 0 0',+ padding: '0 12px 0 0'},fileTypeColorDialog: {width: '15%',- padding: '0 12px 0 0',+ padding: '0 12px 0 0'},fileTypeColorDialogButton: {width: '100px',- padding: '0 10px 0 0',+ padding: '0 10px 0 0'},colorChooserButton: {maxWidth: 30,@@ -102,9 +102,11 @@ class SettingsFileTypes extends Component<Props, State> {this.setState({ isComponentActive: true });};- openColorPicker = (selectedItem) => {+ openColorPicker = selectedItem => {const { setSelectedItem } = this.props;- this.setState({ isColorPickerVisible: true }, () => setSelectedItem(selectedItem));+ this.setState({ isColorPickerVisible: true }, () =>+ setSelectedItem(selectedItem)+ );};closeColorPicker = () => {@@ -112,7 +114,7 @@ class SettingsFileTypes extends Component<Props, State> {this.setState({ isColorPickerVisible: false }, () => setSelectedItem({}));};- handleChangeColor = (color) => {+ handleChangeColor = color => {const { updateItems, selectedItem } = this.props;updateItems('id', selectedItem.id, 'color', color);};@@ -123,9 +125,21 @@ class SettingsFileTypes extends Component<Props, State> {render() {const classes = this.props.classes;- const { items, selectedItem, updateItems = () => {}, onRemoveItem = () => {}, isValidationInProgress = false } = this.props;- const { availableExtensions, isColorPickerVisible, isComponentActive } = this.state;- const modifiedItems = !isComponentActive ? sortBy(items, 'type', 'string', 'asc') : items;+ const {+ items,+ selectedItem,+ updateItems = () => {},+ onRemoveItem = () => {},+ isValidationInProgress = false+ } = this.props;+ const {+ availableExtensions,+ isColorPickerVisible,+ isComponentActive+ } = this.state;+ const modifiedItems = !isComponentActive+ ? sortBy(items, 'type', 'string', 'asc')+ : items;return (<div className={classes.root}>@@ -144,41 +158,76 @@ class SettingsFileTypes extends Component<Props, State> {style={{borderBottom: '1px solid rgba(0, 0, 0, 0.1)',padding: '16px 0',- alignItems: 'flex-end',+ alignItems: 'flex-end'}}>- <FormControl className={classes.fileExtension} error={(isValidationInProgress && item.type === '') || items.filter(targetItem => targetItem.type === item.type).length > 1}>- <InputLabel htmlFor="name-disabled" data-shrink={false}>{i18n.t('core:fileExtension')}</InputLabel>+ <FormControl+ className={classes.fileExtension}+ error={+ (isValidationInProgress && item.type === '') ||+ items.filter(targetItem => targetItem.type === item.type)+ .length > 1+ }+ >+ <InputLabel htmlFor="name-disabled" data-shrink={false}>+ {i18n.t('core:fileExtension')}+ </InputLabel><Inputvalue={item.type}- error={(isValidationInProgress && item.type === '') || items.filter(targetItem => targetItem.type === item.type).length > 1}+ error={+ (isValidationInProgress && item.type === '') ||+ items.filter(targetItem => targetItem.type === item.type)+ .length > 1+ }onChange={event => {event.persist();const nextValue = event.target.value;- const withoutSpecialChars = this.sanitizeFileTypeInput(nextValue);- updateItems('type', item.type, 'type', withoutSpecialChars, true);+ const withoutSpecialChars = this.sanitizeFileTypeInput(+ nextValue+ );+ updateItems(+ 'type',+ item.type,+ 'type',+ withoutSpecialChars,+ true+ );}}onBlur={event => {const nextValue = event.target.value;- const withoutSpecialChars = this.sanitizeFileTypeInput(nextValue);+ const withoutSpecialChars = this.sanitizeFileTypeInput(+ nextValue+ );updateItems('type', item.type, 'type', withoutSpecialChars);}}/></FormControl>- <FormControl className={classes.fileOpener} error={isValidationInProgress && item.viewer === ''}>+ <FormControl+ className={classes.fileOpener}+ error={isValidationInProgress && item.viewer === ''}+ ><InputLabel htmlFor="">{i18n.t('core:fileOpener')}</InputLabel><Selecterror={isValidationInProgress && item.viewer === ''}value={item.viewer}input={<Input id="" />}- onChange={event => updateItems('id', item.id, 'viewer', event.target.value)}+ onChange={event =>+ updateItems('id', item.id, 'viewer', event.target.value)+ }><MenuItem value="" />- {availableExtensions.map(extension => (- (extension.extensionType === 'viewer' || extension.extensionType === 'editor') && (- <MenuItem key={extension.extensionName} value={extension.extensionId}>{extension.extensionName}</MenuItem>- )- ))}+ {availableExtensions.map(+ extension =>+ (extension.extensionType === 'viewer' ||+ extension.extensionType === 'editor') && (+ <MenuItem+ key={extension.extensionName}+ value={extension.extensionId}+ >+ {extension.extensionName}+ </MenuItem>+ )+ )}</Select></FormControl><FormControl className={classes.fileOpener}>@@ -186,15 +235,21 @@ class SettingsFileTypes extends Component<Props, State> {<Selectvalue={item.editor}input={<Input id="" />}- onChange={event => updateItems('id', item.id, 'editor', event.target.value)}+ onChange={event =>+ updateItems('id', item.id, 'editor', event.target.value)+ }><MenuItem value="" />{availableExtensions.filter(extension => extension.extensionType === 'editor').map(extension => (- <MenuItem key={extension.extensionName} value={extension.extensionId}>{extension.extensionName}</MenuItem>- )- )}+ <MenuItem+ key={extension.extensionName}+ value={extension.extensionId}+ >+ {extension.extensionName}+ </MenuItem>+ ))}</Select></FormControl><FormControl className={classes.fileTypeColorDialogButton}>@@ -205,12 +260,13 @@ class SettingsFileTypes extends Component<Props, State> {style={{backgroundColor: `${item.color}`,minWidth: '100px',- cursor: 'pointer',+ cursor: 'pointer'}}onClick={() => {this.openColorPicker(item);}}- > + >+ <div style={styles.color} /></Button></TransparentBackground>diff --git a/app/components/dialogs/settings/SettingsGeneral.js b/app/components/dialogs/settings/SettingsGeneral.jsindex c375e5ddc..bc72dea4a 100644--- a/app/components/dialogs/settings/SettingsGeneral.js+++ b/app/components/dialogs/settings/SettingsGeneral.js@@ -38,8 +38,7 @@ import ColorPickerDialog from '../../dialogs/ColorPickerDialog';import TransparentBackground from '../../TransparentBackground';const styles = theme => ({- root: {- },+ root: {},listItem: {paddingLeft: 0,paddingRight: 0@@ -81,7 +80,7 @@ type State = {class SettingsGeneral extends React.Component<Props, State> {state = {displayColorPicker: false,- displayTextColorPicker: false,+ displayTextColorPicker: false};toggleDefaultTagBackgroundColorPicker = () => {@@ -200,11 +199,15 @@ class SettingsGeneral extends React.Component<Props, State> {backgroundColor: this.props.settings.tagBackgroundColor}}onClick={this.toggleDefaultTagBackgroundColorPicker}- > </Button>+ >+ + </Button></TransparentBackground><ColorPickerDialogopen={this.state.displayColorPicker}- setColor={(color) => { this.props.setTagColor(color); }}+ setColor={color => {+ this.props.setTagColor(color);+ }}onClose={this.toggleDefaultTagBackgroundColorPicker}color={this.props.settings.tagBackgroundColor}/>@@ -218,11 +221,15 @@ class SettingsGeneral extends React.Component<Props, State> {size="small"style={{ backgroundColor: this.props.settings.tagTextColor }}onClick={this.toggleDefaultTagTextColorPicker}- > </Button>+ >+ + </Button></TransparentBackground><ColorPickerDialogopen={this.state.displayTextColorPicker}- setColor={(color) => { this.props.setTagTextColor(color); }}+ setColor={color => {+ this.props.setTagTextColor(color);+ }}onClose={this.toggleDefaultTagTextColorPicker}color={this.props.settings.tagTextColor}/>@@ -245,17 +252,19 @@ class SettingsGeneral extends React.Component<Props, State> {checked={this.props.settings.showUnixHiddenEntries}/></ListItem>- {<ListItem className={classes.listItem}>- <ListItemText primary="Mobile Mode (experimental)" />- <Switch- data-tid="settingsSetDesktopMode"- disabled={!(typeof window.ExtDisplayMode === 'undefined')}- onClick={() =>- this.props.setDesktopMode(!this.props.settings.desktopMode)- }- checked={!this.props.settings.desktopMode}- />- </ListItem>}+ {+ <ListItem className={classes.listItem}>+ <ListItemText primary="Mobile Mode (experimental)" />+ <Switch+ data-tid="settingsSetDesktopMode"+ disabled={!(typeof window.ExtDisplayMode === 'undefined')}+ onClick={() =>+ this.props.setDesktopMode(!this.props.settings.desktopMode)+ }+ checked={!this.props.settings.desktopMode}+ />+ </ListItem>+ }{/* <ListItem className={classes.listItem}><ListItemText style={{ maxWidth: '300px' }} primary={i18n.t('core:tagDelimiterChoose')} /><Select@@ -284,7 +293,7 @@ class SettingsGeneral extends React.Component<Props, State> {onChange={this.handleMaxSearchResult}/></ListItem>- { /* <ListItem className={classes.listItem}>+ {/* <ListItem className={classes.listItem}><ListItemText primary={i18n.t('core:coloredFileExtensionsEnabled')} /><Switchdata-tid="settingsSetColoredFileExtension"@@ -295,8 +304,8 @@ class SettingsGeneral extends React.Component<Props, State> {}checked={this.props.settings.coloredFileExtension}/>- </ListItem> */ }- { /* <ListItem className={classes.listItem}>+ </ListItem> */}+ {/* <ListItem className={classes.listItem}><ListItemText primary={i18n.t('core:loadLocationMetaData')} /><Switchdata-tid="settingsSetLoadsLocationMetaData"@@ -307,7 +316,7 @@ class SettingsGeneral extends React.Component<Props, State> {}checked={this.props.settings.loadsLocationMetaData}/>- </ListItem> */ }+ </ListItem> */}</List>);}@@ -344,6 +353,7 @@ function mapActionCreatorsToProps(dispatch) {return bindActionCreators(SettingsActions, dispatch);}-export default connect(mapStateToProps, mapActionCreatorsToProps)(- withStyles(styles)(SettingsGeneral)-);+export default connect(+ mapStateToProps,+ mapActionCreatorsToProps+)(withStyles(styles)(SettingsGeneral));diff --git a/app/components/dialogs/settings/SettingsKeyBindings.js b/app/components/dialogs/settings/SettingsKeyBindings.jsindex dd36fe932..b53e1a522 100644--- a/app/components/dialogs/settings/SettingsKeyBindings.js+++ b/app/components/dialogs/settings/SettingsKeyBindings.js@@ -29,7 +29,8 @@ import PlatformIO from '../../../services/platform-io';import i18n from '../../../services/i18n';import {actions as SettingsActions,- getKeyBindings, isGlobalKeyBindingEnabled,+ getKeyBindings,+ isGlobalKeyBindingEnabled} from '../../../reducers/settings';import DefaultSettings from '../../../reducers/settings-default';import { isStr } from '../../../utils/misc';@@ -40,12 +41,12 @@ const styles = theme => ({},keyBinding: {marginTop: 10,- marginBottom: 10,+ marginBottom: 10},listItem: {paddingLeft: 0,paddingRight: 0- },+ }});type Props = {@@ -57,7 +58,13 @@ type Props = {};const SettingsKeyBindings = (props: Props) => {- const { keyBindings, classes, setKeyBinding, setGlobalKeyBinding, globalKeyBindingEnabled } = props;+ const {+ keyBindings,+ classes,+ setKeyBinding,+ setGlobalKeyBinding,+ globalKeyBindingEnabled+ } = props;return (<form className={classes.root} noValidate autoComplete="off"><ListItem className={classes.listItem}>@@ -70,8 +77,10 @@ const SettingsKeyBindings = (props: Props) => {checked={globalKeyBindingEnabled}/></ListItem>- {keyBindings.map((keyBinding) => {- const defaultBinding = DefaultSettings.keyBindings.filter(kb => kb.name === keyBinding.name)[0];+ {keyBindings.map(keyBinding => {+ const defaultBinding = DefaultSettings.keyBindings.filter(+ kb => kb.name === keyBinding.name+ )[0];return (<TextFieldclassName={classes.keyBinding}@@ -80,8 +89,11 @@ const SettingsKeyBindings = (props: Props) => {fullWidthonBlur={event => setKeyBinding(keyBinding.name, event.target.value)}label={i18n.t('core:' + keyBinding.name)}- placeholder={'suggested binding: ' + (defaultBinding ? defaultBinding.command : '')}- defaultValue={(isStr(keyBinding.command) ? keyBinding.command : '')}+ placeholder={+ 'suggested binding: ' ++ (defaultBinding ? defaultBinding.command : '')+ }+ defaultValue={isStr(keyBinding.command) ? keyBinding.command : ''}/>);})}@@ -100,4 +112,7 @@ function mapActionCreatorsToProps(dispatch) {return bindActionCreators(SettingsActions, dispatch);}-export default connect(mapStateToProps, mapActionCreatorsToProps)(withStyles(styles)(SettingsKeyBindings));+export default connect(+ mapStateToProps,+ mapActionCreatorsToProps+)(withStyles(styles)(SettingsKeyBindings));diff --git a/app/components/menus/DirectoryMenu.js b/app/components/menus/DirectoryMenu.jsindex 280b6710f..81abe246a 100644--- a/app/components/menus/DirectoryMenu.js+++ b/app/components/menus/DirectoryMenu.js@@ -76,9 +76,18 @@ type Props = {const DirectoryMenu = (props: Props) => {let fileInput; // Object | null;- const [isCreateDirectoryDialogOpened, setIsCreateDirectoryDialogOpened] = useState(false);- const [isDeleteDirectoryDialogOpened, setIsDeleteDirectoryDialogOpened] = useState(false);- const [isRenameDirectoryDialogOpened, setIsRenameDirectoryDialogOpened] = useState(false);+ const [+ isCreateDirectoryDialogOpened,+ setIsCreateDirectoryDialogOpened+ ] = useState(false);+ const [+ isDeleteDirectoryDialogOpened,+ setIsDeleteDirectoryDialogOpened+ ] = useState(false);+ const [+ isRenameDirectoryDialogOpened,+ setIsRenameDirectoryDialogOpened+ ] = useState(false);function reloadDirectory() {props.onClose();@@ -146,17 +155,26 @@ const DirectoryMenu = (props: Props) => {}function onCameraSuccess(imageURL) {- window.resolveLocalFileSystemURL(imageURL, (fp) => {- moveFile(fp.nativeURL);- }, () => { console.log('Failed to get filesystem url'); });+ window.resolveLocalFileSystemURL(+ imageURL,+ fp => {+ moveFile(fp.nativeURL);+ },+ () => {+ console.log('Failed to get filesystem url');+ }+ );}function moveFile(filePath) {- const fileName = 'IMG_TS' + AppConfig.beginTagContainer + formatDateTime4Tag(new Date(), true) + AppConfig.endTagContainer + '.jpg';+ const fileName =+ 'IMG_TS' ++ AppConfig.beginTagContainer ++ formatDateTime4Tag(new Date(), true) ++ AppConfig.endTagContainer ++ '.jpg';const newFilePath =- normalizePath(props.directoryPath) +- AppConfig.dirSeparator +- fileName;+ normalizePath(props.directoryPath) + AppConfig.dirSeparator + fileName;PlatformIO.renameFilePromise(filePath, newFilePath).then(() => {@@ -216,43 +234,45 @@ const DirectoryMenu = (props: Props) => {// }// TODO event.currentTarget.result is ArrayBuffer// Sample call from PRO version using content = Utils.base64ToArrayBuffer(baseString);- PlatformIO.getPropertiesPromise(filePath).then((entryProps) => {- if (entryProps) {- props.showNotification(- 'File with the same name already exist, importing skipped!',- 'warning',- true- );- } else {- PlatformIO.saveBinaryFilePromise(- filePath,- event.currentTarget.result,- true- )- .then(() => {- props.showNotification(- 'File ' + filePath + ' successfully imported.',- 'default',- true- );- props.reflectCreateEntry(filePath, true);- return true;- })- .catch(error => {- // TODO showAlertDialog("Saving " + filePath + " failed.");- console.error('Save to file ' + filePath + ' failed ' + error);- props.showNotification(- 'Importing file ' + filePath + ' failed.',- 'error',- true- );- return true;- });- }- return true;- }).catch((err) => {- console.log('Error getting properties ' + err);- });+ PlatformIO.getPropertiesPromise(filePath)+ .then(entryProps => {+ if (entryProps) {+ props.showNotification(+ 'File with the same name already exist, importing skipped!',+ 'warning',+ true+ );+ } else {+ PlatformIO.saveBinaryFilePromise(+ filePath,+ event.currentTarget.result,+ true+ )+ .then(() => {+ props.showNotification(+ 'File ' + filePath + ' successfully imported.',+ 'default',+ true+ );+ props.reflectCreateEntry(filePath, true);+ return true;+ })+ .catch(error => {+ // TODO showAlertDialog("Saving " + filePath + " failed.");+ console.error('Save to file ' + filePath + ' failed ' + error);+ props.showNotification(+ 'Importing file ' + filePath + ' failed.',+ 'error',+ true+ );+ return true;+ });+ }+ return true;+ })+ .catch(err => {+ console.log('Error getting properties ' + err);+ });};if (AppConfig.isCordova) {@@ -294,16 +314,9 @@ const DirectoryMenu = (props: Props) => {cancelDialogTID={'cancelDeleteDirectoryDialog'}confirmDialogTID={'confirmDeleteDirectoryDialog'}/>- <Menu- anchorEl={props.anchorEl}- open={props.open}- onClose={props.onClose}- >+ <Menu anchorEl={props.anchorEl} open={props.open} onClose={props.onClose}>{props.perspectiveMode && (- <MenuItem- data-tid="openDirectory"- onClick={openDirectory}- >+ <MenuItem data-tid="openDirectory" onClick={openDirectory}><ListItemIcon><OpenFolderIcon /></ListItemIcon>@@ -341,19 +354,14 @@ const DirectoryMenu = (props: Props) => {</MenuItem>)}{!AppConfig.isWeb && (- <MenuItem- data-tid="showInFileManager"- onClick={showInFileManager}- >+ <MenuItem data-tid="showInFileManager" onClick={showInFileManager}><ListItemIcon><OpenFolderNativelyIcon /></ListItemIcon><ListItemText primary={i18n.t('core:showInFileManager')} /></MenuItem>)}- {!props.perspectiveMode && (- <Divider />- )}+ {!props.perspectiveMode && <Divider />}{!props.isReadOnlyMode && !props.perspectiveMode && (<MenuItemdata-tid="newSubDirectory"@@ -390,21 +398,33 @@ const DirectoryMenu = (props: Props) => {</MenuItem>)}<Divider />- { !props.perspectiveMode && (+ {!props.perspectiveMode && (<div>- <MenuItem data-tid="openDefaultPerspective" onClick={() => switchPerspective('default')} title="Switch to default perspective">+ <MenuItem+ data-tid="openDefaultPerspective"+ onClick={() => switchPerspective('default')}+ title="Switch to default perspective"+ ><ListItemIcon><DefaultPerspectiveIcon /></ListItemIcon><ListItemText primary="Default perspective" /></MenuItem>- <MenuItem data-tid="openGalleryPerspective" onClick={() => switchPerspective('gallery')} title="Switch to gallery perspective">+ <MenuItem+ data-tid="openGalleryPerspective"+ onClick={() => switchPerspective('gallery')}+ title="Switch to gallery perspective"+ ><ListItemIcon><GalleryPerspectiveIcon /></ListItemIcon><ListItemText primary="Gallery Perspective - Beta" /></MenuItem>- <MenuItem data-tid="openMapiquePerspective" onClick={() => switchPerspective('mapique')} title="Switch to mapique perspective">+ <MenuItem+ data-tid="openMapiquePerspective"+ onClick={() => switchPerspective('mapique')}+ title="Switch to mapique perspective"+ ><ListItemIcon><MapiquePerspectiveIcon /></ListItemIcon>@@ -450,10 +470,13 @@ const DirectoryMenu = (props: Props) => {};function mapDispatchToProps(dispatch) {- return bindActionCreators({- showNotification: AppActions.showNotification,- extractContent: IOActions.extractContent- }, dispatch);+ return bindActionCreators(+ {+ showNotification: AppActions.showNotification,+ extractContent: IOActions.extractContent+ },+ dispatch+ );}export default connect(null, mapDispatchToProps)(DirectoryMenu);diff --git a/app/components/menus/EntryTagMenu.js b/app/components/menus/EntryTagMenu.jsindex 502c72be4..5d30b3e88 100644--- a/app/components/menus/EntryTagMenu.js+++ b/app/components/menus/EntryTagMenu.js@@ -82,20 +82,13 @@ const EntryTagMenu = (props: Props) => {}function confirmRemoveTag() {- props.removeTags(- [props.currentEntryPath],- [props.selectedTag]- );+ props.removeTags([props.currentEntryPath], [props.selectedTag]);handleCloseDialogs();}return (<div style={{ overflowY: 'hidden !important' }}>- <Menu- anchorEl={props.anchorEl}- open={props.open}- onClose={props.onClose}- >+ <Menu anchorEl={props.anchorEl} open={props.open} onClose={props.onClose}><MenuItemdata-tid="showFilesWithThisTag"onClick={showFilesWithThisTag}@@ -147,11 +140,14 @@ function mapStateToProps(state) {}function mapDispatchToProps(dispatch) {- return bindActionCreators({- searchLocationIndex: LocationIndexActions.searchLocationIndex,- openSearchPanel: AppActions.openSearchPanel,- toggleEditTagDialog: AppActions.toggleEditTagDialog,- }, dispatch);+ return bindActionCreators(+ {+ searchLocationIndex: LocationIndexActions.searchLocationIndex,+ openSearchPanel: AppActions.openSearchPanel,+ toggleEditTagDialog: AppActions.toggleEditTagDialog+ },+ dispatch+ );}export default connect(mapStateToProps, mapDispatchToProps)(EntryTagMenu);diff --git a/app/components/menus/FileMenu.js b/app/components/menus/FileMenu.jsindex afb2a5769..16b5ce988 100644--- a/app/components/menus/FileMenu.js+++ b/app/components/menus/FileMenu.js@@ -92,15 +92,8 @@ const FileMenu = (props: Props) => {return (<div style={{ overflowY: 'hidden !important' }}>- <Menu- anchorEl={props.anchorEl}- open={props.open}- onClose={props.onClose}- >- <MenuItem- data-tid="fileMenuOpenFile"- onClick={openFile}- >+ <Menu anchorEl={props.anchorEl} open={props.open} onClose={props.onClose}>+ <MenuItem data-tid="fileMenuOpenFile" onClick={openFile}><ListItemIcon><OpenFile /></ListItemIcon>@@ -158,7 +151,10 @@ const FileMenu = (props: Props) => {</ListItemIcon><ListItemText primary={i18n.t('core:moveCopyFile')} /></MenuItem>- <MenuItem data-tid="fileMenuDeleteFile" onClick={showDeleteFileDialog}>+ <MenuItem+ data-tid="fileMenuDeleteFile"+ onClick={showDeleteFileDialog}+ ><ListItemIcon><DeleteForever /></ListItemIcon>diff --git a/app/components/menus/LocationManagerMenu.js b/app/components/menus/LocationManagerMenu.jsindex d93aec2c4..c7f062e37 100644--- a/app/components/menus/LocationManagerMenu.js+++ b/app/components/menus/LocationManagerMenu.js@@ -28,36 +28,31 @@ import AppConfig from '../../config';type Props = {classes: Object,- open: boolean,- anchorEl: Object,- onClose: () => void,- openURLExternally: (url: string) => void,+ open: boolean,+ anchorEl: Object,+ onClose: () => void,+ openURLExternally: (url: string) => void};const LocationManagerMenu = (props: Props) => {+ return (+ <div style={{ overflowY: 'hidden !important' }}>+ <Menu anchorEl={props.anchorEl} open={props.open} onClose={props.onClose}>+ <MenuItem+ data-tid="locationManagerMenu"+ onClick={() => {+ props.onClose();+ props.openURLExternally(AppConfig.documentationLinks.locations);+ }}+ >+ <ListItemIcon>+ <HelpIcon />+ </ListItemIcon>+ <ListItemText primary={i18n.t('core:help')} />+ </MenuItem>+ </Menu>+ </div>+ );+};- return (- <div style={{ overflowY: 'hidden !important' }}>- <Menu- anchorEl={props.anchorEl}- open={props.open}- onClose={props.onClose}- >- <MenuItem- data-tid="locationManagerMenu"- onClick={() => {- props.onClose();- props.openURLExternally(AppConfig.documentationLinks.locations)- }}- >- <ListItemIcon>- <HelpIcon />- </ListItemIcon>- <ListItemText primary={i18n.t('core:help')} />- </MenuItem>- </Menu>- </div>- );-};--export default LocationManagerMenu;\ No newline at end of file+export default LocationManagerMenu;diff --git a/app/components/menus/LocationMenu.js b/app/components/menus/LocationMenu.jsindex c26cfee77..e68baa5b0 100644--- a/app/components/menus/LocationMenu.js+++ b/app/components/menus/LocationMenu.js@@ -31,10 +31,15 @@ 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, type Location, locationType } from '../../reducers/locations';+import {+ getLocations,+ type Location,+ locationType+} from '../../reducers/locations';import {actions as AppActions,- getCurrentLocationId } from '../../reducers/app';+ getCurrentLocationId+} from '../../reducers/app';type Props = {currentLocationId: string | null,@@ -53,8 +58,8 @@ type State = {class LocationMenu extends React.Component<Props, State> {state = {locationChooserMenuOpened: false,- locationChooserMenuAnchorEl: null,- }+ locationChooserMenuAnchorEl: null+ };static getDerivedStateFromProps(nextProps, prevState) {let currentLocation;@@ -67,7 +72,7 @@ class LocationMenu extends React.Component<Props, State> {}return {...prevState,- currentLocation,+ currentLocation};}@@ -86,13 +91,18 @@ class LocationMenu extends React.Component<Props, State> {render() {const { theme } = this.props;const { currentLocation } = this.state;- const locationIcon = (currentLocation && currentLocation.type === locationType.TYPE_CLOUD) ?- <CloudLocationIcon /> : <LocationIcon />;+ const locationIcon =+ currentLocation && currentLocation.type === locationType.TYPE_CLOUD ? (+ <CloudLocationIcon />+ ) : (+ <LocationIcon />+ );return (- <div style={{- backgroundColor: theme.palette.background.default,- }}+ <div+ style={{+ backgroundColor: theme.palette.background.default+ }}><Buttondata-tid="folderContainerLocationChooser"@@ -125,12 +135,18 @@ class LocationMenu extends React.Component<Props, State> {data-tid="folderContainerMenuOpenLocation"key={location.uuid}onClick={() => this.openLocation(location)}- style={(currentLocation && currentLocation.uuid === location.uuid) ? { backgroundColor: theme.palette.primary.light } : {}}+ style={+ currentLocation && currentLocation.uuid === location.uuid+ ? { backgroundColor: theme.palette.primary.light }+ : {}+ }><ListItemIcon>- { location.type === locationType.TYPE_CLOUD ?- (<CloudLocationIcon />) : (<LocationIcon />)- }+ {location.type === locationType.TYPE_CLOUD ? (+ <CloudLocationIcon />+ ) : (+ <LocationIcon />+ )}</ListItemIcon><ListItemText primary={location.name} /></MenuItem>@@ -151,7 +167,7 @@ function mapStateToProps(state) {function mapActionCreatorsToProps(dispatch) {return bindActionCreators({- openLocation: AppActions.openLocation,+ openLocation: AppActions.openLocation},dispatch);diff --git a/app/components/menus/SearchMenu.js b/app/components/menus/SearchMenu.jsindex d2bea092c..8c4916e8e 100644--- a/app/components/menus/SearchMenu.js+++ b/app/components/menus/SearchMenu.js@@ -30,25 +30,20 @@ type Props = {classes: Object,open: boolean,anchorEl: Object,- onClose: () => void,- openURLExternally: (url: string) => void,+ onClose: () => void,+ openURLExternally: (url: string) => void};const SearchMenu = (props: Props) => {-return (<div style={{ overflowY: 'hidden !important' }}>- <Menu- anchorEl={props.anchorEl}- open={props.open}- onClose={props.onClose}- >+ <Menu anchorEl={props.anchorEl} open={props.open} onClose={props.onClose}><MenuItemdata-tid="searchMenuHelp"onClick={() => {- props.onClose();- props.openURLExternally(AppConfig.documentationLinks.search)- }}+ props.onClose();+ props.openURLExternally(AppConfig.documentationLinks.search);+ }}><ListItemIcon><HelpIcon />diff --git a/app/components/menus/TagGroupMenu.js b/app/components/menus/TagGroupMenu.jsindex 009cac762..6764fac4c 100644--- a/app/components/menus/TagGroupMenu.js+++ b/app/components/menus/TagGroupMenu.js@@ -137,7 +137,11 @@ const TagLibraryMenu = (props: Props) => {<ListItemIcon><CollectTagsIcon /></ListItemIcon>- <ListItemText primary={i18n.t('core:collectTagsFromLocation') + (Pro ? '' : ' PRO')} />+ <ListItemText+ primary={+ i18n.t('core:collectTagsFromLocation') + (Pro ? '' : ' PRO')+ }+ /></MenuItem></Menu></div>diff --git a/app/components/menus/TagLibraryMenu.js b/app/components/menus/TagLibraryMenu.jsindex d1bac59a1..809ff8f0f 100644--- a/app/components/menus/TagLibraryMenu.js+++ b/app/components/menus/TagLibraryMenu.js@@ -46,8 +46,14 @@ const TagLibraryMenu = (props: Props) => {let fileInput;const [tagGroups, setTagGroups] = useState(null);const [selectedDirectoryPath, setSelectedDirectoryPath] = useState('');- const [isSelectDirectoryDialogOpened, setIsSelectDirectoryDialogOpened] = useState(false);- const [isImportExportTagGroupDialogOpened, setIsImportExportTagGroupDialogOpened] = useState(false);+ const [+ isSelectDirectoryDialogOpened,+ setIsSelectDirectoryDialogOpened+ ] = useState(false);+ const [+ isImportExportTagGroupDialogOpened,+ setIsImportExportTagGroupDialogOpened+ ] = useState(false);const [dialogModeImport, setDialogModeImport] = useState(false);function handleCloseDialogs() {@@ -126,11 +132,7 @@ const TagLibraryMenu = (props: Props) => {onClose={closeSelectDirectoryExtDialog}selectedDirectoryPath={selectedDirectoryPath}/>- <Menu- anchorEl={props.anchorEl}- open={props.open}- onClose={props.onClose}- >+ <Menu anchorEl={props.anchorEl} open={props.open} onClose={props.onClose}><MenuItemdata-tid="createNewTagGroup"onClick={() => {@@ -143,19 +145,13 @@ const TagLibraryMenu = (props: Props) => {</ListItemIcon><ListItemText primary={i18n.t('core:createTagGroupTitle')} /></MenuItem>- <MenuItem- data-tid="importTagGroup"- onClick={handleImportTagGroup}- >+ <MenuItem data-tid="importTagGroup" onClick={handleImportTagGroup}><ListItemIcon><ImportExportIcon /></ListItemIcon><ListItemText primary={i18n.t('core:importTags')} /></MenuItem>- <MenuItem- data-tid="exportTagGroup"- onClick={handleExportTagGroup}- >+ <MenuItem data-tid="exportTagGroup" onClick={handleExportTagGroup}><ListItemIcon><ImportExportIcon /></ListItemIcon>@@ -165,7 +161,7 @@ const TagLibraryMenu = (props: Props) => {data-tid="taglibraryHelp"onClick={() => {props.onClose();- props.openURLExternally(AppConfig.documentationLinks.taglibrary)+ props.openURLExternally(AppConfig.documentationLinks.taglibrary);}}><ListItemIcon>diff --git a/app/components/menus/TagMenu.js b/app/components/menus/TagMenu.jsindex 4bf306dc0..590e6a0d9 100644--- a/app/components/menus/TagMenu.js+++ b/app/components/menus/TagMenu.js@@ -36,7 +36,8 @@ import { type SearchQuery } from '../../services/search';import { getMaxSearchResults } from '../../reducers/settings';import { actions as AppActions } from '../../reducers/app';-const isTagLibraryReadOnly = (window.ExtTagLibrary && window.ExtTagLibrary.length > 0);+const isTagLibraryReadOnly =+ window.ExtTagLibrary && window.ExtTagLibrary.length > 0;type Props = {anchorEl?: Object,@@ -88,20 +89,13 @@ const TagLibraryMenu = (props: Props) => {function confirmDeleteTag() {if (props.selectedTag && props.selectedTagGroupEntry) {- props.deleteTag(- props.selectedTag.id,- props.selectedTagGroupEntry.uuid- );+ props.deleteTag(props.selectedTag.id, props.selectedTagGroupEntry.uuid);}}return (<div style={{ overflowY: 'hidden !important' }}>- <Menu- anchorEl={props.anchorEl}- open={props.open}- onClose={props.onClose}- >+ <Menu anchorEl={props.anchorEl} open={props.open} onClose={props.onClose}><MenuItemdata-tid="showFilesWithThisTag"onClick={showFilesWithThisTag}@@ -124,8 +118,7 @@ const TagLibraryMenu = (props: Props) => {<ListItemIcon><DeleteIcon /></ListItemIcon>- <ListItemText primary={i18n.t('core:deleteTagFromTagGroup')}- />+ <ListItemText primary={i18n.t('core:deleteTagFromTagGroup')} /></MenuItem>)}</Menu>@@ -162,10 +155,13 @@ function mapStateToProps(state) {}function mapDispatchToProps(dispatch) {- return bindActionCreators({- openSearchPanel: AppActions.openSearchPanel,- searchLocationIndex: LocationIndexActions.searchLocationIndex,- }, dispatch);+ return bindActionCreators(+ {+ openSearchPanel: AppActions.openSearchPanel,+ searchLocationIndex: LocationIndexActions.searchLocationIndex+ },+ dispatch+ );}export default connect(mapStateToProps, mapDispatchToProps)(TagLibraryMenu);diff --git a/app/config.js b/app/config.jsindex e7810ee42..ef692053d 100644--- a/app/config.js+++ b/app/config.js@@ -16,7 +16,9 @@** @flow*/-const isCordovaiOS = /^file:\/{3}[^\/]/i.test(window.location.href) && /ios|iphone|ipod|ipad/i.test(navigator.userAgent);+const isCordovaiOS =+ /^file:\/{3}[^\/]/i.test(window.location.href) &&+ /ios|iphone|ipod|ipad/i.test(navigator.userAgent);const isCordovaAndroid = document.URL.indexOf('file:///android_asset') === 0;const isIOS = navigator.userAgent.match(/(iPad|iPhone|iPod)/i);const isAndroid = navigator.userAgent.toLowerCase().includes('android');@@ -45,10 +47,14 @@ export default {links: {checkNewVersionURL: 'https://www.tagspaces.org/releases/tagspaces.json',productsOverview: 'https://www.tagspaces.org/products/',- productProObjectStore: 'https://www.tagspaces.org/products/pro/#connectingObjectStores',- productProAdvancedSearch: 'https://www.tagspaces.org/products/pro/#advancedSearch',- productProFileFolderMeta: 'https://www.tagspaces.org/products/pro/#fileFolderMeta',- productProThumbnailsGeneration: 'https://www.tagspaces.org/products/pro/#thumbnailsGeneration',+ productProObjectStore:+ 'https://www.tagspaces.org/products/pro/#connectingObjectStores',+ productProAdvancedSearch:+ 'https://www.tagspaces.org/products/pro/#advancedSearch',+ productProFileFolderMeta:+ 'https://www.tagspaces.org/products/pro/#fileFolderMeta',+ productProThumbnailsGeneration:+ 'https://www.tagspaces.org/products/pro/#thumbnailsGeneration',productProGeoTagging: 'https://www.tagspaces.org/usecases/geotagging/',productPro: 'https://www.tagspaces.org/products/pro/',productEnterprise: 'https://www.tagspaces.org/products/enterprise/',@@ -59,12 +65,14 @@ export default {suggestFeature: 'https://trello.com/b/TGeG5bi9',reportIssue: 'https://github.com/tagspaces/tagspaces/issues/',helpTranslating: 'https://www.transifex.com/tagspaces/tagspaces/',- webClipperChrome: 'https://chrome.google.com/webstore/detail/tagspaces-web-clipper/ldalmgifdlgpiiadeccbcjojljeanhjk',- webClipperFirefox: 'https://addons.mozilla.org/en-US/firefox/addon/tagspaces/',+ webClipperChrome:+ 'https://chrome.google.com/webstore/detail/tagspaces-web-clipper/ldalmgifdlgpiiadeccbcjojljeanhjk',+ webClipperFirefox:+ 'https://addons.mozilla.org/en-US/firefox/addon/tagspaces/',webClipper: 'https://www.tagspaces.org/products/webclipper/',twitter: 'https://twitter.com/tagspaces',facebook: 'https://www.facebook.com/tagspacesapp',- emailContact: 'mailto:[email protected]?subject=App',+ emailContact: 'mailto:[email protected]?subject=App'},documentationLinks: {general: 'https://docs.tagspaces.org/',@@ -75,18 +83,23 @@ export default {locations: 'https://docs.tagspaces.org/ui/locations',taglibrary: 'https://docs.tagspaces.org/ui/taglibrary',search: 'https://docs.tagspaces.org/search',- settings: 'https://docs.tagspaces.org/ui/settings',+ settings: 'https://docs.tagspaces.org/ui/settings'},- isElectron: (navigator.userAgent.toLowerCase().indexOf(' electron/') > -1),- isFirefox: (navigator.userAgent.toLowerCase().includes('firefox')), // typeof InstallTrigger !== 'undefined';+ isElectron: navigator.userAgent.toLowerCase().indexOf(' electron/') > -1,+ isFirefox: navigator.userAgent.toLowerCase().includes('firefox'), // typeof InstallTrigger !== 'undefined';isWin: navigator.appVersion.includes('Win'),isMacLike: navigator.userAgent.match(/(Mac|iPhone|iPod|iPad)/i),isIOS,isAndroid,- isWeb: (document.URL.startsWith('http') && !document.URL.startsWith('http://localhost:1212/')),+ isWeb:+ document.URL.startsWith('http') &&+ !document.URL.startsWith('http://localhost:1212/'),isCordovaiOS,isCordovaAndroid,isCordova: isCordovaiOS || isCordovaAndroid,isMobile: isCordovaiOS || isCordovaAndroid || isIOS || isAndroid,- dirSeparator: (navigator.appVersion.includes('Win') && !document.URL.startsWith('http')) ? '\\' : '/',+ dirSeparator:+ navigator.appVersion.includes('Win') && !document.URL.startsWith('http')+ ? '\\'+ : '/'};diff --git a/app/containers/App.js b/app/containers/App.jsindex 0825ed836..d581546f1 100644--- a/app/containers/App.js+++ b/app/containers/App.js@@ -37,10 +37,10 @@ const lightTheme = createMuiTheme({light: '#dcf3ec',main: '#1DD19F',dark: '#1DD19F',- contrastText: '#ffffff',+ contrastText: '#ffffff'},secondary: {- main: '#1DD19F',+ main: '#1DD19F'},divider: '#ddd'// secondary: { main: '#cccccc', 200: '#ddd' }@@ -54,10 +54,10 @@ const darkTheme = createMuiTheme({light: '#56454e',main: '#ff9abe',dark: '#a21547',- contrastText: '#ffffff',+ contrastText: '#ffffff'},secondary: {- main: '#ff9abe',+ main: '#ff9abe'},divider: '#555'// secondary: { main: '#555', 200: '#777' }@@ -89,18 +89,18 @@ class App extends Component {render() {let theme;switch (this.props.currentTheme) {- case 'light': {- theme = lightTheme;- break;- }- case 'dark': {- theme = darkTheme;- break;- }- default: {- theme = lightTheme;- break;- }+ case 'light': {+ theme = lightTheme;+ break;+ }+ case 'dark': {+ theme = darkTheme;+ break;+ }+ default: {+ theme = lightTheme;+ break;+ }}return (@@ -114,7 +114,7 @@ class App extends Component {function mapStateToProps(state) {return {- currentTheme: getCurrentTheme(state),+ currentTheme: getCurrentTheme(state)};}diff --git a/app/containers/LoginPage.js b/app/containers/LoginPage.jsindex 0785573b9..5eb6da293 100644--- a/app/containers/LoginPage.js+++ b/app/containers/LoginPage.js@@ -52,11 +52,7 @@ class LoginPage extends Component {render() {return (<div style={{ backgroundColor: 'white' }}>- <Button- onClick={this.handleLogin}- >- {i18n.t('core:login')}- </Button>+ <Button onClick={this.handleLogin}>{i18n.t('core:login')}</Button></div>);}diff --git a/app/main.dev.js b/app/main.dev.jsindex fa9985df9..ed67a11f9 100644--- a/app/main.dev.js+++ b/app/main.dev.js@@ -42,9 +42,11 @@ process.argv.forEach((arg, count) => {} else if (arg.toLowerCase() === '-p' || arg.toLowerCase() === '--portable') {app.setPath('userData', process.cwd() + '/tsprofile'); // making the app portableportableMode = true;- } else if (arg.indexOf('-psn') >= 0) { // ignoring the -psn process serial number parameter on MacOS by double click+ } else if (arg.indexOf('-psn') >= 0) {+ // ignoring the -psn process serial number parameter on MacOS by double clickarg = '';- } else if (arg === 'babel-register' || arg === '.' || count === 0) { // ignoring the first argument+ } else if (arg === 'babel-register' || arg === '.' || count === 0) {+ // ignoring the first argument// Ignore these argument} else if (arg.length > 2) {// console.warn('Opening file: ' + arg);@@ -58,7 +60,10 @@ process.argv.forEach((arg, count) => {}});-if (process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD === 'true') {+if (+ process.env.NODE_ENV === 'development' ||+ process.env.DEBUG_PROD === 'true'+) {require('electron-debug')({ showDevTools: false, devToolsMode: 'right' });const p = path.join(__dirname, '..', 'app', 'node_modules');require('module').globalPaths.push(p);@@ -72,17 +77,18 @@ if (process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD === 'true')app.commandLine.appendSwitch('--disable-http-cache');const installExtensions = async () => {- const { default: installExtension, REACT_DEVELOPER_TOOLS, REDUX_DEVTOOLS } = require('electron-devtools-installer');-- const forceDownload = !!process.env.UPGRADE_EXTENSIONS;- const extensions = [+ const {+ default: installExtension,REACT_DEVELOPER_TOOLS,REDUX_DEVTOOLS- ];+ } = require('electron-devtools-installer');- return Promise- .all(extensions.map(name => installExtension(name.id, forceDownload)))- .catch(console.log);+ const forceDownload = !!process.env.UPGRADE_EXTENSIONS;+ const extensions = [REACT_DEVELOPER_TOOLS, REDUX_DEVTOOLS];++ return Promise.all(+ extensions.map(name => installExtension(name.id, forceDownload))+ ).catch(console.log);};app.commandLine.appendSwitch('autoplay-policy', 'no-user-gesture-required'); // Fix broken autoplay functionality in the av player@@ -96,7 +102,10 @@ app.on('ready', async () => {let workerDevMode = false;let mainHTML = `file://${__dirname}/app.html`;- if (process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD === 'true') {+ if (+ process.env.NODE_ENV === 'development' ||+ process.env.DEBUG_PROD === 'true'+ ) {await installExtensions();}@@ -132,7 +141,8 @@ app.on('ready', async () => {let startupParameter = '';if (startupFilePath) {if (startupFilePath.startsWith('./') || startupFilePath.startsWith('.\\')) {- startupParameter = '?open=' + encodeURIComponent(path.join(__dirname, startupFilePath));+ startupParameter =+ '?open=' + encodeURIComponent(path.join(__dirname, startupFilePath));} else {startupParameter = '?open=' + encodeURIComponent(startupFilePath);}@@ -185,7 +195,7 @@ app.on('ready', async () => {message: 'This process has crashed.',buttons: ['Reload', 'Close']};- dialog.showMessageBox(mainWindow, options, (index) => {+ dialog.showMessageBox(mainWindow, options, index => {mainWindow.hide();if (index === 0) {reloadApp();@@ -213,7 +223,8 @@ app.on('ready', async () => {}});- ipcMain.on('setSplashVisibility', (event, arg) => { // worker window needed to be visible for the PDF tmb generation+ ipcMain.on('setSplashVisibility', (event, arg) => {+ // worker window needed to be visible for the PDF tmb generation// console.log('worker event in main: ' + arg.visibility);if (global.splashWorkerWindow && arg.visibility) {global.splashWorkerWindow.show();@@ -221,15 +232,15 @@ app.on('ready', async () => {}});- ipcMain.on('app-data-path-request', (event) => {+ ipcMain.on('app-data-path-request', event => {event.returnValue = app.getPath('appData');});- ipcMain.on('app-version-request', (event) => {+ ipcMain.on('app-version-request', event => {event.returnValue = app.getVersion();});- ipcMain.on('app-dir-path-request', (event) => {+ ipcMain.on('app-dir-path-request', event => {event.returnValue = path.join(__dirname, '');});@@ -255,7 +266,7 @@ app.on('ready', async () => {app.quit();});- process.on('uncaughtException', (error) => {+ process.on('uncaughtException', error => {if (error.stack) {console.error('error:', error.stack);throw new Error('error:', error.stack);@@ -306,4 +317,3 @@ app.on('ready', async () => {}}});-diff --git a/app/perspectives/file-manager/index.js b/app/perspectives/file-manager/index.jsindex a738e44fd..f616c0b93 100644--- a/app/perspectives/file-manager/index.js+++ b/app/perspectives/file-manager/index.js@@ -55,7 +55,7 @@ class FileManagerPerspective extends React.Component<Props, State> {order: '',checked: [0],itemPath: '',- extension: this.props.directoryContent.map((item) => item.extension)+ extension: this.props.directoryContent.map(item => item.extension)};/*@@ -68,7 +68,7 @@ class FileManagerPerspective extends React.Component<Props, State> {</Button>*/- handleRequestSort = (sortBy) => {+ handleRequestSort = sortBy => {this.setState({ orderBy: !this.state.orderBy });this.props.sortByCriteria(sortBy, this.state.orderBy);};@@ -125,9 +125,7 @@ class FileManagerPerspective extends React.Component<Props, State> {renderExtHeadTableAction = () => (<div>- <Tooltip- title="Sort"- >+ <Tooltip title="Sort"><Buttontitle="Ext"onClick={this.handleRequestSort('ext', !this.state.order)}@@ -138,14 +136,13 @@ class FileManagerPerspective extends React.Component<Props, State> {</div>);+ renderNameColumnAction = name => <span>{name}</span>;- renderNameColumnAction = (name) => (<span>{ name }</span>);-- renderIsFileColumnAction = (isFile) => {+ renderIsFileColumnAction = isFile => {if (isFile) {- return (<span>File</span>);+ return <span>File</span>;}- return (<span>Folder</span>);+ return <span>Folder</span>;};renderTagColumnAction = (tags: Array<Tag>) =>@@ -158,21 +155,22 @@ class FileManagerPerspective extends React.Component<Props, State> {tag={tag}index={index}/>- ))- ;+ ));- renderLastModifiedColumnAction = (lmdt) => (<span>{ formatDateTime(lmdt, true) }</span>);+ renderLastModifiedColumnAction = lmdt => (+ <span>{formatDateTime(lmdt, true)}</span>+ );- renderSizeColumnAction = (size) => (<span>{ formatFileSize(size) }</span>);+ renderSizeColumnAction = size => <span>{formatFileSize(size)}</span>;handleCellClick = (record, index) => ({- onContextMenu: (e) => {+ onContextMenu: e => {this.handleFileContextMenu(e, record.path);},onClick: () => {this.setState({ checkBox: true });},- onDoubleClick: (e) => {+ onDoubleClick: e => {this.onRowClick(record, index, e);}});@@ -191,10 +189,10 @@ class FileManagerPerspective extends React.Component<Props, State> {},{title: (- <div> Name- <Tooltip- title="Sort"- >+ <div>+ {' '}+ Name+ <Tooltip title="Sort"><ArrowUpward style={{ width: 16, height: 16 }} /></Tooltip></div>@@ -207,10 +205,10 @@ class FileManagerPerspective extends React.Component<Props, State> {},{title: (- <div> Is File- <Tooltip- title="Sort"- >+ <div>+ {' '}+ Is File+ <Tooltip title="Sort"><ArrowDownward style={{ width: 16, height: 16 }} /></Tooltip></div>@@ -222,10 +220,10 @@ class FileManagerPerspective extends React.Component<Props, State> {},{title: (- <div> Tags- <Tooltip- title="Sort"- >+ <div>+ {' '}+ Tags+ <Tooltip title="Sort"><ArrowDownward style={{ width: 16, height: 16 }} /></Tooltip></div>@@ -237,10 +235,10 @@ class FileManagerPerspective extends React.Component<Props, State> {},{title: (- <div> Size- <Tooltip- title="Sort"- >+ <div>+ {' '}+ Size+ <Tooltip title="Sort"><ArrowDownward style={{ width: 16, height: 16 }} /></Tooltip></div>@@ -252,10 +250,10 @@ class FileManagerPerspective extends React.Component<Props, State> {},{title: (- <div> Last Modified- <Tooltip- title="Sort"- >+ <div>+ {' '}+ Last Modified+ <Tooltip title="Sort"><ArrowDownward style={{ width: 16, height: 16 }} /></Tooltip></div>@@ -267,7 +265,7 @@ class FileManagerPerspective extends React.Component<Props, State> {}];- handleToggle = value => (e) => {+ handleToggle = value => e => {e.preventDefault();const { checked } = this.state;const currentIndex = checked.indexOf(value);@@ -307,7 +305,7 @@ class FileManagerPerspective extends React.Component<Props, State> {});};- toggleFileMenuClose = (event) => {+ toggleFileMenuClose = event => {this.setState({fileContextMenuOpened: !this.state.fileContextMenuOpened,fileContextMenuAnchorEl: event ? event.currentTarget : nulldiff --git a/app/perspectives/virtualizing-perspective/src/index.js b/app/perspectives/virtualizing-perspective/src/index.jsindex 44986a04d..0695d0848 100644--- a/app/perspectives/virtualizing-perspective/src/index.js+++ b/app/perspectives/virtualizing-perspective/src/index.js@@ -67,9 +67,7 @@ import {findColorForFileEntry} from '../../../services/utils-io';import { type Tag } from '../../../reducers/taglibrary';-import {- getSupportedFileTypes-} from '../../../reducers/settings';+import { getSupportedFileTypes } from '../../../reducers/settings';import { extractTitle } from '../../../utils/paths';import {formatFileSize,@@ -194,14 +192,23 @@ class GridPerspective extends React.Component<Props, State> {selectedEntryPath: '',sortBy: settings && settings.sortBy ? settings.sortBy : 'byName',orderBy: settings && settings.orderBy ? settings.orderBy : true,- layoutType: settings && settings.layoutType ? settings.layoutType : 'grid',- singleClickAction: settings && settings.singleClickAction ? settings.singleClickAction : 'openInternal', // openExternal- doubleClickAction: settings && settings.doubleClickAction ? settings.doubleClickAction : 'openInternal', // openExternal+ layoutType:+ settings && settings.layoutType ? settings.layoutType : 'grid',+ singleClickAction:+ settings && settings.singleClickAction+ ? settings.singleClickAction+ : 'openInternal', // openExternal+ doubleClickAction:+ settings && settings.doubleClickAction+ ? settings.doubleClickAction+ : 'openInternal', // openExternalentrySize: settings && settings.entrySize ? settings.entrySize : 'normal', // small, big- thumbnailMode: settings && settings.thumbnailMode ? settings.thumbnailMode : 'cover', // contain+ thumbnailMode:+ settings && settings.thumbnailMode ? settings.thumbnailMode : 'cover', // containfileOperationsEnabled: false,allFilesSelected: false,- showDirectories: settings && settings.showDirectories ? settings.showDirectories : true,+ showDirectories:+ settings && settings.showDirectories ? settings.showDirectories : true,isDeleteMultipleFilesDialogOpened: false,isMoveCopyFilesDialogOpened: false,isAddRemoveTagsDialogOpened: false,@@ -211,14 +218,18 @@ class GridPerspective extends React.Component<Props, State> {height: 400,gutterSize: 10,overscanByPixels: 1000,- windowScrollerEnabled: true,+ windowScrollerEnabled: true};this.initContent(this.props.directoryContent);}componentWillReceiveProps = (nextProps: Props) => {- const { lastSelectedEntryPath, perspectiveCommand, selectedEntries } = nextProps;+ const {+ lastSelectedEntryPath,+ perspectiveCommand,+ selectedEntries+ } = nextProps;if (perspectiveCommand && perspectiveCommand.key) {this.props.setLastSelectedEntry(null);@@ -240,7 +251,10 @@ class GridPerspective extends React.Component<Props, State> {this.openFileRenameDialog();});}- } else if (perspectiveCommand.key === 'DELETE_SELECTED_ENTRIES' && this.state.fileOperationsEnabled) {+ } else if (+ perspectiveCommand.key === 'DELETE_SELECTED_ENTRIES' &&+ this.state.fileOperationsEnabled+ ) {this.openDeleteFileDialog();}}@@ -275,13 +289,13 @@ class GridPerspective extends React.Component<Props, State> {}};- initContent = (directoryContent) => {+ initContent = directoryContent => {const { sortBy, orderBy } = this.state;this.sortedContent = this.sort(directoryContent, sortBy, orderBy);};- sort = memoize(- (data, criteria, order) => sortByCriteria(data, criteria, order)+ sort = memoize((data, criteria, order) =>+ sortByCriteria(data, criteria, order));makeFirstSelectedEntryVisible = () => {@@ -327,10 +341,13 @@ class GridPerspective extends React.Component<Props, State> {handleSortBy = sortBy => {this.closeSortingMenu();- this.setState({- orderBy: !this.state.orderBy,- sortBy- }, this.saveSettings);+ this.setState(+ {+ orderBy: !this.state.orderBy,+ sortBy+ },+ this.saveSettings+ );};handleSortingMenu = event => {@@ -350,8 +367,12 @@ class GridPerspective extends React.Component<Props, State> {handleGridCellClick = (event, fsEntry: FileSystemEntry) => {const { selectedEntries } = this.props;if (event.shiftKey) {- let lastSelectedIndex = this.props.directoryContent.findIndex(entry => entry.path === this.props.lastSelectedEntryPath);- const currentSelectedIndex = this.props.directoryContent.findIndex(entry => entry.path === fsEntry.path);+ let lastSelectedIndex = this.props.directoryContent.findIndex(+ entry => entry.path === this.props.lastSelectedEntryPath+ );+ const currentSelectedIndex = this.props.directoryContent.findIndex(+ entry => entry.path === fsEntry.path+ );if (lastSelectedIndex < 0) {lastSelectedIndex = currentSelectedIndex;}@@ -359,9 +380,15 @@ class GridPerspective extends React.Component<Props, State> {let entriesToSelect;// console.log('lastSelectedIndex: ' + lastSelectedIndex + ' currentSelectedIndex: ' + currentSelectedIndex);if (currentSelectedIndex > lastSelectedIndex) {- entriesToSelect = this.props.directoryContent.slice(lastSelectedIndex, currentSelectedIndex + 1);+ entriesToSelect = this.props.directoryContent.slice(+ lastSelectedIndex,+ currentSelectedIndex + 1+ );} else if (currentSelectedIndex < lastSelectedIndex) {- entriesToSelect = this.props.directoryContent.slice(currentSelectedIndex, lastSelectedIndex + 1);+ entriesToSelect = this.props.directoryContent.slice(+ currentSelectedIndex,+ lastSelectedIndex + 1+ );} else if (currentSelectedIndex === lastSelectedIndex) {entriesToSelect = [fsEntry];this.props.setLastSelectedEntry(fsEntry.path);@@ -374,7 +401,9 @@ class GridPerspective extends React.Component<Props, State> {selectedEntries &&selectedEntries.some(entry => entry.path === fsEntry.path)) {- this.props.setSelectedEntries(selectedEntries.filter(entry => entry.path !== fsEntry.path)); // deselect selected entry+ this.props.setSelectedEntries(+ selectedEntries.filter(entry => entry.path !== fsEntry.path)+ ); // deselect selected entrythis.setState(this.computeFileOperationsEnabled);// this.props.setLastSelectedEntry(null);} else {@@ -443,36 +472,29 @@ class GridPerspective extends React.Component<Props, State> {this.closeOptionsMenu();this.setState({- thumbnailMode: this.state.thumbnailMode === 'cover' ? 'contain' : 'cover'+ thumbnailMode:+ this.state.thumbnailMode === 'cover' ? 'contain' : 'cover'},this.saveSettings);};- changeEntrySize = (entrySize) => {+ changeEntrySize = entrySize => {this.closeOptionsMenu();- this.setState({ entrySize },- this.saveSettings- );+ this.setState({ entrySize }, this.saveSettings);};- changeSingleClickAction = (singleClickAction) => {+ changeSingleClickAction = singleClickAction => {this.closeOptionsMenu();- this.setState({ singleClickAction },- this.saveSettings- );+ this.setState({ singleClickAction }, this.saveSettings);};handleGridCellDblClick = (event, fsEntry: FileSystemEntry) => {this.props.setSelectedEntries([]);- this.setState(- this.computeFileOperationsEnabled- );+ this.setState(this.computeFileOperationsEnabled);if (fsEntry.isFile) {this.props.setSelectedEntries([fsEntry]);- this.setState(- this.computeFileOperationsEnabled- );+ this.setState(this.computeFileOperationsEnabled);this.props.openFile(fsEntry.path);} else {console.log('Handle Grid cell db click, selected path : ', fsEntry.path);@@ -484,7 +506,9 @@ class GridPerspective extends React.Component<Props, State> {const { selectedEntries } = this.props;if (fsEntry.isFile) {- this.props.setSelectedEntries(event.ctrlKey ? [...selectedEntries, fsEntry] : [fsEntry]);+ this.props.setSelectedEntries(+ event.ctrlKey ? [...selectedEntries, fsEntry] : [fsEntry]+ );this.setState({fileContextMenuOpened: true,fileContextMenuAnchorEl: event.currentTarget,@@ -650,16 +674,15 @@ class GridPerspective extends React.Component<Props, State> {</TagDropContainer>);if (fsEntry.isFile) {- return (- <FileSourceDnd>- {cellContent}- </FileSourceDnd>- );+ return <FileSourceDnd>{cellContent}</FileSourceDnd>;}return (<div style={{ position: 'relative' }}>- <TargetMoveFileBox accepts={[DragItemTypes.FILE]} onDrop={this.handleFileMoveDrop}>+ <TargetMoveFileBox+ accepts={[DragItemTypes.FILE]}+ onDrop={this.handleFileMoveDrop}+ >{cellContent}</TargetMoveFileBox></div>@@ -691,7 +714,9 @@ class GridPerspective extends React.Component<Props, State> {renderCellContent = (fsEntry: FileSystemEntry, entryHeight: number) => {const { classes, theme, supportedFileTypes } = this.props;- const fsEntryBackgroundColor = fsEntry.color ? fsEntry.color : 'transparent';+ const fsEntryBackgroundColor = fsEntry.color+ ? fsEntry.color+ : 'transparent';let description = removeMd(fsEntry.description);if (description.length > maxDescriptionPreviewLength) {description = description.substr(0, maxDescriptionPreviewLength) + '...';@@ -710,9 +735,10 @@ class GridPerspective extends React.Component<Props, State> {}if (this.state.layoutType === 'grid') {return (- <div style={{- backgroundColor: fsEntryBackgroundColor- }}+ <div+ style={{+ backgroundColor: fsEntryBackgroundColor+ }}><divclassName={classes.gridCellThumb}@@ -723,9 +749,7 @@ class GridPerspective extends React.Component<Props, State> {}}><div id="gridCellTags" className={classes.gridCellTags}>- {- fsEntry.tags.map(tag => this.renderTag(tag, fsEntry))- }+ {fsEntry.tags.map(tag => this.renderTag(tag, fsEntry))}</div>{description.length > 0 && (<Typography@@ -848,7 +872,7 @@ class GridPerspective extends React.Component<Props, State> {{fsEntry.isFile && fsEntry.lmdt && '️ ' + fsEntry.lmdt + ' '}</span><span title={i18n.t('core:entryDescription')}>- {description && description }+ {description && description}</span></Typography></Grid>@@ -879,16 +903,10 @@ class GridPerspective extends React.Component<Props, State> {};cellRenderer = ({ index, key, parent, style }) => (-- <CellMeasurer- cache={this.cache}- index={index}- key={key}- parent={parent}- >+ <CellMeasurer cache={this.cache} index={index} key={key} parent={parent}><div style={style}><div style={{ height: '225px' }}>- {(this.renderCell(this.sortedContent[index]))}+ {this.renderCell(this.sortedContent[index])}</div></div></CellMeasurer>@@ -908,7 +926,7 @@ class GridPerspective extends React.Component<Props, State> {this.cellPositioner.reset({columnCount: this._columnCount,columnWidth,- spacer: gutterSize,+ spacer: gutterSize});};@@ -935,7 +953,9 @@ class GridPerspective extends React.Component<Props, State> {cellRenderer={this.cellRenderer}height={this._height}overscanByPixels={overscanByPixels}- ref={(ref) => { this._masonry = ref; }}+ ref={ref => {+ this._masonry = ref;+ }}scrollTop={this.scrollTop}width={width}/>@@ -969,7 +989,7 @@ class GridPerspective extends React.Component<Props, State> {cellMeasurerCache: this.cache,columnCount: this._columnCount,columnWidth,- spacer: gutterSize,+ spacer: gutterSize});}};@@ -977,7 +997,7 @@ class GridPerspective extends React.Component<Props, State> {cache = new CellMeasurerCache({defaultHeight: 250,defaultWidth: 200,- fixedWidth: true,+ fixedWidth: true});render() {@@ -989,8 +1009,16 @@ class GridPerspective extends React.Component<Props, State> {selectedEntries,theme} = this.props;- const { layoutType, entrySize, sortBy, orderBy, overscanByPixels } = this.state;- const selectedFilePaths = selectedEntries.filter(fsEntry => fsEntry.isFile).map(fsentry => fsentry.path);+ const {+ layoutType,+ entrySize,+ sortBy,+ orderBy,+ overscanByPixels+ } = this.state;+ const selectedFilePaths = selectedEntries+ .filter(fsEntry => fsEntry.isFile)+ .map(fsentry => fsentry.path);const sortedContent = this.sort(directoryContent, sortBy, orderBy);const sortedDirectories = sortedContent.filter(entry => !entry.isFile);const sortedFiles = sortedContent.filter(entry => entry.isFile);@@ -1111,20 +1139,23 @@ class GridPerspective extends React.Component<Props, State> {<MoreVertIcon /></IconButton></Toolbar>- <div style={{- height: '100%',- backgroundColor: theme.palette.background.default- }}- >- <div style={{+ <div+ style={{height: '100%',- overflowY: AppConfig.isFirefox ? 'auto' : 'overlay',- backgroundColor: currentDirectoryColor || 'transparent',+ backgroundColor: theme.palette.background.default}}+ >+ <div+ style={{+ height: '100%',+ overflowY: AppConfig.isFirefox ? 'auto' : 'overlay',+ backgroundColor: currentDirectoryColor || 'transparent'+ }}><WindowScroller overscanByPixels={overscanByPixels}>{this.renderAutoSizer}- </WindowScroller> {/*+ </WindowScroller>{' '}+ {/*<GridVirtualizedcellRenderer={this.cellRenderer}columnCount={5}@@ -1244,67 +1275,72 @@ class GridPerspective extends React.Component<Props, State> {{/* <ListSubHeader>Sort by</ListSubHeader> */}<MenuItemdata-tid="gridPerspectiveSortByName"- onClick={() => { this.handleSortBy('byName'); }}+ onClick={() => {+ this.handleSortBy('byName');+ }}><ListItemIcon style={{ minWidth: 25 }}>- {(this.state.sortBy === 'byName') && (- this.state.orderBy ? <ArrowUpIcon /> : <ArrowDownIcon />- )}+ {this.state.sortBy === 'byName' &&+ (this.state.orderBy ? <ArrowUpIcon /> : <ArrowDownIcon />)}</ListItemIcon><ListItemText inset primary={i18n.t('core:fileTitle')} /></MenuItem><MenuItemdata-tid="gridPerspectiveSortBySize"- onClick={() => { this.handleSortBy('byFileSize'); }}+ onClick={() => {+ this.handleSortBy('byFileSize');+ }}><ListItemIcon style={{ minWidth: 25 }}>- {(this.state.sortBy === 'byFileSize') && (- this.state.orderBy ? <ArrowUpIcon /> : <ArrowDownIcon />- )}+ {this.state.sortBy === 'byFileSize' &&+ (this.state.orderBy ? <ArrowUpIcon /> : <ArrowDownIcon />)}</ListItemIcon><ListItemText inset primary={i18n.t('core:fileSize')} /></MenuItem><MenuItemdata-tid="gridPerspectiveSortByDate"- onClick={() => { this.handleSortBy('byDateModified'); }}+ onClick={() => {+ this.handleSortBy('byDateModified');+ }}><ListItemIcon style={{ minWidth: 25 }}>- {(this.state.sortBy === 'byDateModified') && (- this.state.orderBy ? <ArrowUpIcon /> : <ArrowDownIcon />- )}+ {this.state.sortBy === 'byDateModified' &&+ (this.state.orderBy ? <ArrowUpIcon /> : <ArrowDownIcon />)}</ListItemIcon><ListItemText inset primary={i18n.t('core:fileLDTM')} /></MenuItem><MenuItemdata-tid="gridPerspectiveSortByFirstTag"- onClick={() => { this.handleSortBy('byFirstTag'); }}+ onClick={() => {+ this.handleSortBy('byFirstTag');+ }}><ListItemIcon style={{ minWidth: 25 }}>- {(this.state.sortBy === 'byFirstTag') && (- this.state.orderBy ? <ArrowUpIcon /> : <ArrowDownIcon />- )}+ {this.state.sortBy === 'byFirstTag' &&+ (this.state.orderBy ? <ArrowUpIcon /> : <ArrowDownIcon />)}</ListItemIcon><ListItemText inset primary={i18n.t('core:fileFirstTag')} /></MenuItem><MenuItemdata-tid="gridPerspectiveSortByExt"- onClick={() => { this.handleSortBy('byExtension'); }}+ onClick={() => {+ this.handleSortBy('byExtension');+ }}><ListItemIcon style={{ minWidth: 25 }}>- {(this.state.sortBy === 'byExtension') && (- this.state.orderBy ? <ArrowUpIcon /> : <ArrowDownIcon />- )}+ {this.state.sortBy === 'byExtension' &&+ (this.state.orderBy ? <ArrowUpIcon /> : <ArrowDownIcon />)}</ListItemIcon><ListItemText inset primary={i18n.t('core:fileExtension')} /></MenuItem><MenuItemdata-tid="gridPerspectiveSortRandom"- onClick={() => { this.handleSortBy('random'); }}+ onClick={() => {+ this.handleSortBy('random');+ }}><ListItemIcon style={{ minWidth: 25 }}>- {(this.state.sortBy === 'random') && (- <ArrowDownIcon />- )}+ {this.state.sortBy === 'random' && <ArrowDownIcon />}</ListItemIcon><ListItemText inset primary={i18n.t('core:random')} /></MenuItem>@@ -1321,7 +1357,11 @@ class GridPerspective extends React.Component<Props, State> {onClick={this.toggleShowDirectories}><ListItemIcon style={{ minWidth: 25 }}>- {this.state.showDirectories ? <FolderIcon /> : <FolderHiddenIcon />}+ {this.state.showDirectories ? (+ <FolderIcon />+ ) : (+ <FolderHiddenIcon />+ )}</ListItemIcon><ListItemText inset primary={i18n.t('core:showHideDirectories')} /></MenuItem>@@ -1332,7 +1372,11 @@ class GridPerspective extends React.Component<Props, State> {onClick={this.toggleThumbnailsMode}><ListItemIcon>- {this.state.thumbnailMode === 'cover' ? <ThumbnailCoverIcon /> : <ThumbnailContainIcon />}+ {this.state.thumbnailMode === 'cover' ? (+ <ThumbnailCoverIcon />+ ) : (+ <ThumbnailContainIcon />+ )}</ListItemIcon><ListItemText inset primary={i18n.t('core:toggleThumbnailMode')} /></MenuItem>@@ -1344,7 +1388,11 @@ class GridPerspective extends React.Component<Props, State> {onClick={() => this.changeEntrySize('small')}><ListItemIcon>- {this.state.entrySize === 'small' ? <RadioCheckedIcon /> : <RadioUncheckedIcon />}+ {this.state.entrySize === 'small' ? (+ <RadioCheckedIcon />+ ) : (+ <RadioUncheckedIcon />+ )}</ListItemIcon><ListItemText inset primary={i18n.t('core:entrySizeSmall')} /></MenuItem>@@ -1355,7 +1403,11 @@ class GridPerspective extends React.Component<Props, State> {onClick={() => this.changeEntrySize('normal')}><ListItemIcon>- {this.state.entrySize === 'normal' ? <RadioCheckedIcon /> : <RadioUncheckedIcon />}+ {this.state.entrySize === 'normal' ? (+ <RadioCheckedIcon />+ ) : (+ <RadioUncheckedIcon />+ )}</ListItemIcon><ListItemText inset primary={i18n.t('core:entrySizeNormal')} /></MenuItem>@@ -1366,7 +1418,11 @@ class GridPerspective extends React.Component<Props, State> {onClick={() => this.changeEntrySize('big')}><ListItemIcon>- {this.state.entrySize === 'big' ? <RadioCheckedIcon /> : <RadioUncheckedIcon />}+ {this.state.entrySize === 'big' ? (+ <RadioCheckedIcon />+ ) : (+ <RadioUncheckedIcon />+ )}</ListItemIcon><ListItemText inset primary={i18n.t('core:entrySizeBig')} /></MenuItem>@@ -1378,9 +1434,16 @@ class GridPerspective extends React.Component<Props, State> {onClick={() => this.changeSingleClickAction('openInternal')}><ListItemIcon>- {this.state.singleClickAction === 'openInternal' ? <RadioCheckedIcon /> : <RadioUncheckedIcon />}+ {this.state.singleClickAction === 'openInternal' ? (+ <RadioCheckedIcon />+ ) : (+ <RadioUncheckedIcon />+ )}</ListItemIcon>- <ListItemText inset primary={i18n.t('core:singleClickOpenInternally')} />+ <ListItemText+ inset+ primary={i18n.t('core:singleClickOpenInternally')}+ /></MenuItem><MenuItemdata-tid="gridPerspectiveSingleClickOpenExternally"@@ -1389,9 +1452,16 @@ class GridPerspective extends React.Component<Props, State> {onClick={() => this.changeSingleClickAction('openExternal')}><ListItemIcon>- {this.state.singleClickAction === 'openExternal' ? <RadioCheckedIcon /> : <RadioUncheckedIcon />}+ {this.state.singleClickAction === 'openExternal' ? (+ <RadioCheckedIcon />+ ) : (+ <RadioUncheckedIcon />+ )}</ListItemIcon>- <ListItemText inset primary={i18n.t('core:singleClickOpenExternally')} />+ <ListItemText+ inset+ primary={i18n.t('core:singleClickOpenExternally')}+ /></MenuItem><MenuItemdata-tid="gridPerspectiveSingleClickSelects"@@ -1400,7 +1470,11 @@ class GridPerspective extends React.Component<Props, State> {onClick={() => this.changeSingleClickAction('selects')}><ListItemIcon>- {this.state.singleClickAction === 'selects' ? <RadioCheckedIcon /> : <RadioUncheckedIcon />}+ {this.state.singleClickAction === 'selects' ? (+ <RadioCheckedIcon />+ ) : (+ <RadioUncheckedIcon />+ )}</ListItemIcon><ListItemText inset primary={i18n.t('core:singleClickSelects')} /></MenuItem>@@ -1411,12 +1485,15 @@ class GridPerspective extends React.Component<Props, State> {}function mapActionCreatorsToProps(dispatch) {- return bindActionCreators({- moveFiles: IOActions.moveFiles,- setSelectedEntries: AppActions.setSelectedEntries,- showNotification: AppActions.showNotification,- addTags: TaggingActions.addTags- }, dispatch);+ return bindActionCreators(+ {+ moveFiles: IOActions.moveFiles,+ setSelectedEntries: AppActions.setSelectedEntries,+ showNotification: AppActions.showNotification,+ addTags: TaggingActions.addTags+ },+ dispatch+ );}function mapStateToProps(state) {@@ -1430,6 +1507,7 @@ function mapStateToProps(state) {};}-export default connect(mapStateToProps, mapActionCreatorsToProps)(- withStyles(styles, { withTheme: true })(GridPerspective)-);+export default connect(+ mapStateToProps,+ mapActionCreatorsToProps+)(withStyles(styles, { withTheme: true })(GridPerspective));diff --git a/app/perspectives/virtualizing-perspective/src/styles.css.js b/app/perspectives/virtualizing-perspective/src/styles.css.jsindex 8fdbbe537..2b5588ed8 100644--- a/app/perspectives/virtualizing-perspective/src/styles.css.js+++ b/app/perspectives/virtualizing-perspective/src/styles.css.js@@ -18,7 +18,7 @@*/import AppConfig from '../../../config';-export default (theme) => ({+export default theme => ({gridContainer: {display: 'grid',gridGap: '2px 2px',diff --git a/app/pro/index.js b/app/pro/index.jsindex aa9c86236..3377ec199 100644--- a/app/pro/index.js+++ b/app/pro/index.js@@ -23,7 +23,7 @@ try {tsPro = require('../node_modules/@tagspaces/pro');} catch (e) {if (e instanceof Error && e.code === 'MODULE_NOT_FOUND') {- console.log("PRO functionality not available");+ console.log('PRO functionality not available');} else {throw e;}diff --git a/app/reducers/app.js b/app/reducers/app.jsindex 25c29d443..5d292b5b1 100644--- a/app/reducers/app.js+++ b/app/reducers/app.js@@ -35,7 +35,8 @@ import {getMetaFileLocationForFile,getThumbFileLocationForFile,extractParentDirectoryPath,- extractTagsAsObjects, normalizePath+ extractTagsAsObjects,+ normalizePath} from '../utils/paths';import { formatDateTime4Tag, getURLParameter } from '../utils/misc';import i18n from '../services/i18n';@@ -175,355 +176,379 @@ export const initialState = {tagLibraryPanelOpened: showTagLibrary,searchPanelOpened: showSearch,perspectivesPanelOpened: false,- helpFeedbackPanelOpened: false,+ helpFeedbackPanelOpened: false};// The state described here will not be persistedexport default (state: Object = initialState, action: Object) => {switch (action.type) {- case types.DEVICE_ONLINE: {- return { ...state, isOnline: true, error: null };- }- case types.DEVICE_OFFLINE: {- return { ...state, isOnline: false, error: null };- }- case types.SET_READONLYMODE: {- return { ...state, isReadOnlyMode: action.isReadOnlyMode };- }- case types.SET_NEW_VERSION_AVAILABLE: {- return {- ...state,- isUpdateAvailable: action.isUpdateAvailable- };- }- case types.LOAD_DIRECTORY_SUCCESS: {- return {- ...state,- currentDirectoryEntries: action.directoryContent,- currentDirectoryPath: action.directoryPath,- isLoading: action.showIsLoading || false- };- }- case types.CLEAR_DIRECTORY_CONTENT: {- return {- ...state,- currentDirectoryEntries: [],- currentDirectoryPath: ''- };- }- case types.SET_CURRENLOCATIONID: {- return {- ...state,- currentLocationId: action.locationId- };- }- case types.SET_LAST_SELECTED_ENTRY: {- /* console.time('SET_LAST_SELECTED_ENTRY'); // Measure set last selected entry+ case types.DEVICE_ONLINE: {+ return { ...state, isOnline: true, error: null };+ }+ case types.DEVICE_OFFLINE: {+ return { ...state, isOnline: false, error: null };+ }+ case types.SET_READONLYMODE: {+ return { ...state, isReadOnlyMode: action.isReadOnlyMode };+ }+ case types.SET_NEW_VERSION_AVAILABLE: {+ return {+ ...state,+ isUpdateAvailable: action.isUpdateAvailable+ };+ }+ case types.LOAD_DIRECTORY_SUCCESS: {+ return {+ ...state,+ currentDirectoryEntries: action.directoryContent,+ currentDirectoryPath: action.directoryPath,+ isLoading: action.showIsLoading || false+ };+ }+ case types.CLEAR_DIRECTORY_CONTENT: {+ return {+ ...state,+ currentDirectoryEntries: [],+ currentDirectoryPath: ''+ };+ }+ case types.SET_CURRENLOCATIONID: {+ return {+ ...state,+ currentLocationId: action.locationId+ };+ }+ case types.SET_LAST_SELECTED_ENTRY: {+ /* console.time('SET_LAST_SELECTED_ENTRY'); // Measure set last selected entryconst result = { ...state, lastSelectedEntry: action.entryPath };console.timeEnd('SET_LAST_SELECTED_ENTRY');return result; */- return { ...state, lastSelectedEntry: action.entryPath };- }- case types.SET_SELECTED_ENTRIES: {- return { ...state, selectedEntries: action.selectedEntries };- }- case types.SET_CURRENDIRECTORYCOLOR: {- return { ...state, currentDirectoryColor: action.color };- }- case types.TOGGLE_EDIT_TAG_DIALOG: {- return { ...state,- tag: action.tag,- editTagDialogOpened: !state.editTagDialogOpened- };- }- case types.TOGGLE_ABOUT_DIALOG: {- return { ...state, aboutDialogOpened: !state.aboutDialogOpened };- }- case types.TOGGLE_ONBOARDING_DIALOG: {- return { ...state, onboardingDialogOpened: !state.onboardingDialogOpened };- }- case types.TOGGLE_KEYBOARD_DIALOG: {- return { ...state, keysDialogOpened: !state.keysDialogOpened };- }- case types.TOGGLE_CREATE_FILE_DIALOG: {- return { ...state, createFileDialogOpened: !state.createFileDialogOpened };- }- case types.TOGGLE_LICENSE_DIALOG: {- return { ...state, licenseDialogOpened: !state.licenseDialogOpened };- }- case types.TOGGLE_THIRD_PARTY_LIBS_DIALOG: {- return { ...state, thirdPartyLibsDialogOpened: !state.thirdPartyLibsDialogOpened };- }- case types.TOGGLE_SETTINGS_DIALOG: {- return { ...state, settingsDialogOpened: !state.settingsDialogOpened };- }- case types.TOGGLE_CREATE_DIRECTORY_DIALOG: {- return { ...state, createDirectoryDialogOpened: !state.createDirectoryDialogOpened };- }- case types.TOGGLE_SELECT_DIRECTORY_DIALOG: {- return { ...state, selectDirectoryDialogOpened: !state.selectDirectoryDialogOpened };- }- case types.INDEX_DIRECTORY_SEARCH: {- return {- ...state,- currentDirectoryEntries: action.searchResults,- isLoading: false- };- }- case types.SET_NOTIFICATION: {- return {- ...state,- notificationStatus: {- visible: action.visible,- text: action.text,- notificationType: action.notificationType,- autohide: action.autohide- }- };- }- case types.SET_GENERATING_THUMBNAILS: {- return {- ...state,- isGeneratingThumbs: action.isGeneratingThumbs- };- }- case types.OPEN_FILE: {- return {- ...state,- openedFiles: [- action.file- // ...state.openedFiles // TODO uncomment for multiple file support- ]- };- }- case types.TOGGLE_ENTRY_FULLWIDTH: {- return { ...state, isEntryInFullWidth: !state.isEntryInFullWidth };- }- case types.SET_ENTRY_FULLWIDTH: {- return { ...state, isEntryInFullWidth: action.isFullWidth };- }- case types.UPDATE_THUMB_URL: {- const dirEntries = [...state.currentDirectoryEntries];- dirEntries.map((entry) => {- if (entry.path === action.filePath) {- entry.thumbPath = action.thumbUrl;- }- return true;- });- return {- ...state,- currentDirectoryEntries: [- ...dirEntries- ]- };- }- case types.UPDATE_THUMB_URLS: {- const dirEntries = [...state.currentDirectoryEntries];- for (const entry of dirEntries) {- for (const tmbUrl of action.tmbURLs) {- if (entry.path === tmbUrl.filePath) {- entry.thumbPath = tmbUrl.tmbPath;- break;+ return { ...state, lastSelectedEntry: action.entryPath };+ }+ case types.SET_SELECTED_ENTRIES: {+ return { ...state, selectedEntries: action.selectedEntries };+ }+ case types.SET_CURRENDIRECTORYCOLOR: {+ return { ...state, currentDirectoryColor: action.color };+ }+ case types.TOGGLE_EDIT_TAG_DIALOG: {+ return {+ ...state,+ tag: action.tag,+ editTagDialogOpened: !state.editTagDialogOpened+ };+ }+ case types.TOGGLE_ABOUT_DIALOG: {+ return { ...state, aboutDialogOpened: !state.aboutDialogOpened };+ }+ case types.TOGGLE_ONBOARDING_DIALOG: {+ return {+ ...state,+ onboardingDialogOpened: !state.onboardingDialogOpened+ };+ }+ case types.TOGGLE_KEYBOARD_DIALOG: {+ return { ...state, keysDialogOpened: !state.keysDialogOpened };+ }+ case types.TOGGLE_CREATE_FILE_DIALOG: {+ return {+ ...state,+ createFileDialogOpened: !state.createFileDialogOpened+ };+ }+ case types.TOGGLE_LICENSE_DIALOG: {+ return { ...state, licenseDialogOpened: !state.licenseDialogOpened };+ }+ case types.TOGGLE_THIRD_PARTY_LIBS_DIALOG: {+ return {+ ...state,+ thirdPartyLibsDialogOpened: !state.thirdPartyLibsDialogOpened+ };+ }+ case types.TOGGLE_SETTINGS_DIALOG: {+ return { ...state, settingsDialogOpened: !state.settingsDialogOpened };+ }+ case types.TOGGLE_CREATE_DIRECTORY_DIALOG: {+ return {+ ...state,+ createDirectoryDialogOpened: !state.createDirectoryDialogOpened+ };+ }+ case types.TOGGLE_SELECT_DIRECTORY_DIALOG: {+ return {+ ...state,+ selectDirectoryDialogOpened: !state.selectDirectoryDialogOpened+ };+ }+ case types.INDEX_DIRECTORY_SEARCH: {+ return {+ ...state,+ currentDirectoryEntries: action.searchResults,+ isLoading: false+ };+ }+ case types.SET_NOTIFICATION: {+ return {+ ...state,+ notificationStatus: {+ visible: action.visible,+ text: action.text,+ notificationType: action.notificationType,+ autohide: action.autohide}- }+ };}- return {- ...state,- currentDirectoryEntries: [- ...dirEntries- ]- };- }- case types.REFLECT_DELETE_ENTRY: {- const newDirectoryEntries = state.currentDirectoryEntries.filter((entry) => entry.path !== action.path);- const newOpenedFiles = state.openedFiles.filter((entry) => entry.path !== action.path);- if (- state.currentDirectoryEntries.length > newDirectoryEntries.length ||- state.openedFiles.length > newOpenedFiles.length- ) {+ case types.SET_GENERATING_THUMBNAILS: {return {...state,- currentDirectoryEntries: newDirectoryEntries,- openedFiles: newOpenedFiles+ isGeneratingThumbs: action.isGeneratingThumbs};}- return state;- }- case types.REFLECT_CREATE_ENTRY: {- // Prevent adding entry twice e.g. by the watcher- const entryIndex = state.currentDirectoryEntries.findIndex((entry) => entry.path === action.newEntry.path);- if (- entryIndex < 0 &&- extractParentDirectoryPath(action.newEntry.path).replace(/(^\/)|(\/$)/g, '') === state.currentDirectoryPath.replace(/(^\/)|(\/$)/g, '')- ) {+ case types.OPEN_FILE: {return {...state,- currentDirectoryEntries: [- ...state.currentDirectoryEntries,- action.newEntry+ openedFiles: [+ action.file+ // ...state.openedFiles // TODO uncomment for multiple file support]};}- return state;- }- case types.REFLECT_RENAME_ENTRY: {- return {- ...state,- currentDirectoryEntries: state.currentDirectoryEntries.map((entry) => {- if (entry.path !== action.path) {- return entry;+ case types.TOGGLE_ENTRY_FULLWIDTH: {+ return { ...state, isEntryInFullWidth: !state.isEntryInFullWidth };+ }+ case types.SET_ENTRY_FULLWIDTH: {+ return { ...state, isEntryInFullWidth: action.isFullWidth };+ }+ case types.UPDATE_THUMB_URL: {+ const dirEntries = [...state.currentDirectoryEntries];+ dirEntries.map(entry => {+ if (entry.path === action.filePath) {+ entry.thumbPath = action.thumbUrl;}- return {- ...entry,- path: action.newPath,- // thumbPath: getThumbFileLocationForFile(action.newPath), // not needed due timing issue- name: extractFileName(action.newPath),- extension: extractFileExtension(action.newPath),- tags: [- ...entry.tags.filter(tag => tag.type === 'sidecar'), // add only sidecar tags- ...extractTagsAsObjects(action.newPath) // , getTagDelimiter(state)) TODO https://itnext.io/passing-state-between-reducers-in-redux-318de6db06cd- ]- };- }),- openedFiles: state.openedFiles.map((entry) => {- if (entry.path !== action.path) {- return entry;+ return true;+ });+ return {+ ...state,+ currentDirectoryEntries: [...dirEntries]+ };+ }+ case types.UPDATE_THUMB_URLS: {+ const dirEntries = [...state.currentDirectoryEntries];+ for (const entry of dirEntries) {+ for (const tmbUrl of action.tmbURLs) {+ if (entry.path === tmbUrl.filePath) {+ entry.thumbPath = tmbUrl.tmbPath;+ break;+ }}+ }+ return {+ ...state,+ currentDirectoryEntries: [...dirEntries]+ };+ }+ case types.REFLECT_DELETE_ENTRY: {+ const newDirectoryEntries = state.currentDirectoryEntries.filter(+ entry => entry.path !== action.path+ );+ const newOpenedFiles = state.openedFiles.filter(+ entry => entry.path !== action.path+ );+ if (+ state.currentDirectoryEntries.length > newDirectoryEntries.length ||+ state.openedFiles.length > newOpenedFiles.length+ ) {return {- ...entry,- path: action.newPath, // TODO handle change extension case- shouldReload: true,+ ...state,+ currentDirectoryEntries: newDirectoryEntries,+ openedFiles: newOpenedFiles};- })- };- }- case types.REFLECT_UPDATE_SIDECARTAGS: {- return {- ...state,- currentDirectoryEntries: state.currentDirectoryEntries.map((entry) => {- if (entry.path !== action.path) {- return entry;- }+ }+ return state;+ }+ case types.REFLECT_CREATE_ENTRY: {+ // Prevent adding entry twice e.g. by the watcher+ const entryIndex = state.currentDirectoryEntries.findIndex(+ entry => entry.path === action.newEntry.path+ );+ if (+ entryIndex < 0 &&+ extractParentDirectoryPath(action.newEntry.path).replace(+ /(^\/)|(\/$)/g,+ ''+ ) === state.currentDirectoryPath.replace(/(^\/)|(\/$)/g, '')+ ) {return {- ...entry,- tags: [- ...entry.tags.filter(tag => tag.type === 'plain'),- ...action.tags+ ...state,+ currentDirectoryEntries: [+ ...state.currentDirectoryEntries,+ action.newEntry]};- }),- openedFiles: state.openedFiles.map((entry) => {- if (entry.path !== action.path) {- return entry;- }- return {- ...entry,- shouldReload: true,- };- })- };- }- case types.REFLECT_UPDATE_SIDECARMETA: {- return {- ...state,- currentDirectoryEntries: state.currentDirectoryEntries.map((entry) => {- if (entry.path !== action.path) {- return entry;- }- return {- ...entry,- ...action.entryMeta- };- }),- openedFiles: state.openedFiles.map((entry) => {- if (entry.path !== action.path) {- return entry;- }- return {- ...entry,- shouldReload: true,- };- })- };- }- case types.CLOSE_ALL_FILES: {- window.history.pushState('', 'TagSpaces', location.pathname);- return {- ...state,- openedFiles: [],- isEntryInFullWidth: false- };- }- case types.OPEN_LOCATIONMANAGER_PANEL: {- return {- ...state,- locationManagerPanelOpened: true,- tagLibraryPanelOpened: false,- searchPanelOpened: false,- perspectivesPanelOpened: false,- helpFeedbackPanelOpened: false,- };- }- case types.OPEN_TAGLIBRARY_PANEL: {- return {- ...state,- locationManagerPanelOpened: false,- tagLibraryPanelOpened: true,- searchPanelOpened: false,- perspectivesPanelOpened: false,- helpFeedbackPanelOpened: false,- };- }- case types.OPEN_SEARCH_PANEL: {- return {- ...state,- locationManagerPanelOpened: false,- tagLibraryPanelOpened: false,- searchPanelOpened: true,- perspectivesPanelOpened: false,- helpFeedbackPanelOpened: false,- };- }- case types.OPEN_PERSPECTIVES_PANEL: {- return {- ...state,- locationManagerPanelOpened: false,- tagLibraryPanelOpened: false,- searchPanelOpened: false,- perspectivesPanelOpened: true,- helpFeedbackPanelOpened: false,- };- }- case types.OPEN_HELPFEEDBACK_PANEL: {- return {- ...state,- locationManagerPanelOpened: false,- tagLibraryPanelOpened: false,- searchPanelOpened: false,- perspectivesPanelOpened: false,- helpFeedbackPanelOpened: true,- };- }- case types.CLOSE_ALLVERTICAL_PANELS: {- return {- ...state,- locationManagerPanelOpened: false,- tagLibraryPanelOpened: false,- searchPanelOpened: false,- perspectivesPanelOpened: false,- helpFeedbackPanelOpened: false,- };- }- default: {- return state;- }+ }+ return state;+ }+ case types.REFLECT_RENAME_ENTRY: {+ return {+ ...state,+ currentDirectoryEntries: state.currentDirectoryEntries.map(entry => {+ if (entry.path !== action.path) {+ return entry;+ }+ return {+ ...entry,+ path: action.newPath,+ // thumbPath: getThumbFileLocationForFile(action.newPath), // not needed due timing issue+ name: extractFileName(action.newPath),+ extension: extractFileExtension(action.newPath),+ tags: [+ ...entry.tags.filter(tag => tag.type === 'sidecar'), // add only sidecar tags+ ...extractTagsAsObjects(action.newPath) // , getTagDelimiter(state)) TODO https://itnext.io/passing-state-between-reducers-in-redux-318de6db06cd+ ]+ };+ }),+ openedFiles: state.openedFiles.map(entry => {+ if (entry.path !== action.path) {+ return entry;+ }+ return {+ ...entry,+ path: action.newPath, // TODO handle change extension case+ shouldReload: true+ };+ })+ };+ }+ case types.REFLECT_UPDATE_SIDECARTAGS: {+ return {+ ...state,+ currentDirectoryEntries: state.currentDirectoryEntries.map(entry => {+ if (entry.path !== action.path) {+ return entry;+ }+ return {+ ...entry,+ tags: [+ ...entry.tags.filter(tag => tag.type === 'plain'),+ ...action.tags+ ]+ };+ }),+ openedFiles: state.openedFiles.map(entry => {+ if (entry.path !== action.path) {+ return entry;+ }+ return {+ ...entry,+ shouldReload: true+ };+ })+ };+ }+ case types.REFLECT_UPDATE_SIDECARMETA: {+ return {+ ...state,+ currentDirectoryEntries: state.currentDirectoryEntries.map(entry => {+ if (entry.path !== action.path) {+ return entry;+ }+ return {+ ...entry,+ ...action.entryMeta+ };+ }),+ openedFiles: state.openedFiles.map(entry => {+ if (entry.path !== action.path) {+ return entry;+ }+ return {+ ...entry,+ shouldReload: true+ };+ })+ };+ }+ case types.CLOSE_ALL_FILES: {+ window.history.pushState('', 'TagSpaces', location.pathname);+ return {+ ...state,+ openedFiles: [],+ isEntryInFullWidth: false+ };+ }+ case types.OPEN_LOCATIONMANAGER_PANEL: {+ return {+ ...state,+ locationManagerPanelOpened: true,+ tagLibraryPanelOpened: false,+ searchPanelOpened: false,+ perspectivesPanelOpened: false,+ helpFeedbackPanelOpened: false+ };+ }+ case types.OPEN_TAGLIBRARY_PANEL: {+ return {+ ...state,+ locationManagerPanelOpened: false,+ tagLibraryPanelOpened: true,+ searchPanelOpened: false,+ perspectivesPanelOpened: false,+ helpFeedbackPanelOpened: false+ };+ }+ case types.OPEN_SEARCH_PANEL: {+ return {+ ...state,+ locationManagerPanelOpened: false,+ tagLibraryPanelOpened: false,+ searchPanelOpened: true,+ perspectivesPanelOpened: false,+ helpFeedbackPanelOpened: false+ };+ }+ case types.OPEN_PERSPECTIVES_PANEL: {+ return {+ ...state,+ locationManagerPanelOpened: false,+ tagLibraryPanelOpened: false,+ searchPanelOpened: false,+ perspectivesPanelOpened: true,+ helpFeedbackPanelOpened: false+ };+ }+ case types.OPEN_HELPFEEDBACK_PANEL: {+ return {+ ...state,+ locationManagerPanelOpened: false,+ tagLibraryPanelOpened: false,+ searchPanelOpened: false,+ perspectivesPanelOpened: false,+ helpFeedbackPanelOpened: true+ };+ }+ case types.CLOSE_ALLVERTICAL_PANELS: {+ return {+ ...state,+ locationManagerPanelOpened: false,+ tagLibraryPanelOpened: false,+ searchPanelOpened: false,+ perspectivesPanelOpened: false,+ helpFeedbackPanelOpened: false+ };+ }+ default: {+ return state;+ }}};export const actions = {goOnline: () => ({ type: types.DEVICE_ONLINE }),goOffline: () => ({ type: types.DEVICE_OFFLINE }),- setUpdateAvailable: (isUpdateAvailable: boolean) => ({ type: types.SET_NEW_VERSION_AVAILABLE, isUpdateAvailable }),+ setUpdateAvailable: (isUpdateAvailable: boolean) => ({+ type: types.SET_NEW_VERSION_AVAILABLE,+ isUpdateAvailable+ }),showCreateDirectoryDialog: () => (dispatch: (actions: Object) => void,getState: () => Object@@ -531,7 +556,11 @@ export const actions = {const { app } = getState();if (!app.currentDirectoryPath) {dispatch(- actions.showNotification(i18n.t('core:firstOpenaFolder'), 'warning', true)+ actions.showNotification(+ i18n.t('core:firstOpenaFolder'),+ 'warning',+ true+ ));} else {dispatch(actions.toggleCreateDirectoryDialog());@@ -544,27 +573,38 @@ export const actions = {const { app } = getState();if (!app.currentDirectoryPath) {dispatch(- actions.showNotification(i18n.t('core:firstOpenaFolder'), 'warning', true)+ actions.showNotification(+ i18n.t('core:firstOpenaFolder'),+ 'warning',+ true+ ));} else {dispatch(actions.toggleCreateFileDialog());}},- showSelectDirectoryDialog: () => (- dispatch: (actions: Object) => void,- ) => {+ showSelectDirectoryDialog: () => (dispatch: (actions: Object) => void) => {dispatch(actions.toggleSelectDirectoryDialog());},- toggleEditTagDialog: (tag: Tag) => ({ type: types.TOGGLE_EDIT_TAG_DIALOG, tag }),+ toggleEditTagDialog: (tag: Tag) => ({+ type: types.TOGGLE_EDIT_TAG_DIALOG,+ tag+ }),toggleAboutDialog: () => ({ type: types.TOGGLE_ABOUT_DIALOG }),toggleOnboardingDialog: () => ({ type: types.TOGGLE_ONBOARDING_DIALOG }),toggleKeysDialog: () => ({ type: types.TOGGLE_KEYBOARD_DIALOG }),toggleLicenseDialog: () => ({ type: types.TOGGLE_LICENSE_DIALOG }),- toggleThirdPartyLibsDialog: () => ({ type: types.TOGGLE_THIRD_PARTY_LIBS_DIALOG }),+ toggleThirdPartyLibsDialog: () => ({+ type: types.TOGGLE_THIRD_PARTY_LIBS_DIALOG+ }),toggleSettingsDialog: () => ({ type: types.TOGGLE_SETTINGS_DIALOG }),- toggleCreateDirectoryDialog: () => ({ type: types.TOGGLE_CREATE_DIRECTORY_DIALOG }),+ toggleCreateDirectoryDialog: () => ({+ type: types.TOGGLE_CREATE_DIRECTORY_DIALOG+ }),toggleCreateFileDialog: () => ({ type: types.TOGGLE_CREATE_FILE_DIALOG }),- toggleSelectDirectoryDialog: () => ({ type: types.TOGGLE_SELECT_DIRECTORY_DIALOG }),+ toggleSelectDirectoryDialog: () => ({+ type: types.TOGGLE_SELECT_DIRECTORY_DIALOG+ }),openLocationManagerPanel: () => ({ type: types.OPEN_LOCATIONMANAGER_PANEL }),openTagLibraryPanel: () => ({ type: types.OPEN_TAGLIBRARY_PANEL }),openSearchPanel: () => ({ type: types.OPEN_SEARCH_PANEL }),@@ -580,16 +620,33 @@ export const actions = {const currentLocationPath = normalizePath(getCurrentLocationPath(state));if (currentDirectoryPath) {- const dirSep = PlatformIO.haveObjectStoreSupport() ? '/' : AppConfig.dirSeparator;- const parentDirectory = extractParentDirectoryPath(currentDirectoryPath, dirSep);+ const dirSep = PlatformIO.haveObjectStoreSupport()+ ? '/'+ : AppConfig.dirSeparator;+ const parentDirectory = extractParentDirectoryPath(+ currentDirectoryPath,+ dirSep+ );// console.log('parentDirectory: ' + parentDirectory + ' - currentLocationPath: ' + currentLocationPath);if (parentDirectory.includes(currentLocationPath)) {dispatch(actions.loadDirectoryContent(parentDirectory));} else {- dispatch(actions.showNotification(i18n.t('core:parentDirNotInLocation'), 'warning', true));+ dispatch(+ actions.showNotification(+ i18n.t('core:parentDirNotInLocation'),+ 'warning',+ true+ )+ );}} else {- dispatch(actions.showNotification(i18n.t('core:firstOpenaFolder'), 'warning', true));+ dispatch(+ actions.showNotification(+ i18n.t('core:firstOpenaFolder'),+ 'warning',+ true+ )+ );}},loadDirectoryContent: (directoryPath: string) => (@@ -600,14 +657,16 @@ export const actions = {const { settings } = getState();window.walkCanceled = false;- loadMetaDataPromise(directoryPath).then(fsEntryMeta => {- if (fsEntryMeta.color) {- dispatch(actions.setCurrentDirectoryColor(fsEntryMeta.color));- }- return true;- }).catch((err) => {- console.log('Error loading color of the current folder' + err);- });+ loadMetaDataPromise(directoryPath)+ .then(fsEntryMeta => {+ if (fsEntryMeta.color) {+ dispatch(actions.setCurrentDirectoryColor(fsEntryMeta.color));+ }+ return true;+ })+ .catch(err => {+ console.log('Error loading color of the current folder' + err);+ });// Uncomment the following line will to clear all content before loading new dir contentdispatch(actions.loadDirectorySuccessInt(directoryPath, [], true));@@ -615,12 +674,7 @@ export const actions = {dispatch(actions.showNotification(i18n.t('core:loading'), 'info', false));PlatformIO.listDirectoryPromise(directoryPath, false).then(results => {- prepareDirectoryContent(- results,- directoryPath,- settings,- dispatch- );+ prepareDirectoryContent(results, directoryPath, settings, dispatch);return true;}).catch(error => {@@ -631,9 +685,7 @@ export const actions = {loadDirectorySuccess: (directoryPath: string,directoryContent: Array<Object>- ) => (- dispatch: (actions: Object) => void- ) => {+ ) => (dispatch: (actions: Object) => void) => {dispatch(actions.hideNotifications());dispatch(actions.loadDirectorySuccessInt(directoryPath, directoryContent));},@@ -653,7 +705,11 @@ export const actions = {console.warn('Error loading directory: ' + error);dispatch(actions.hideNotifications());dispatch(- actions.showNotification(i18n.t('core:errorLoadingFolder'), 'warning', true)+ actions.showNotification(+ i18n.t('core:errorLoadingFolder'),+ 'warning',+ true+ ));dispatch(actions.loadDirectorySuccess(directoryPath, []));},@@ -725,7 +781,7 @@ export const actions = {dispatch: (actions: Object) => void) => {PlatformIO.renameDirectoryPromise(directoryPath, newDirectoryName)- .then((newDirPath) => {+ .then(newDirPath => {dispatch(actions.reflectRenameEntry(directoryPath, newDirPath));dispatch(actions.showNotification(@@ -760,7 +816,9 @@ export const actions = {actions.showNotification(`Creating directory ${extractDirectoryName(directoryPath- )} successful.`, 'default', true+ )} successful.`,+ 'default',+ true));return true;@@ -783,31 +841,66 @@ export const actions = {) => {const { app } = getState();if (app.currentDirectoryPath) {- const filePath = app.currentDirectoryPath + AppConfig.dirSeparator + 'textfile' + AppConfig.beginTagContainer + formatDateTime4Tag(new Date(), true) + AppConfig.endTagContainer + '.txt';- PlatformIO.saveFilePromise(filePath, '', true).then(() => {- dispatch(actions.reflectCreateEntry(filePath, true));- dispatch(actions.showNotification(i18n.t('core:fileCreateSuccessfully'), 'info', true));- dispatch(actions.openFile(filePath));- // TODO select file // dispatch(actions.setLastSelectedEntry(filePath));- return true;- }).catch((err) => {- console.warn('File creation failed with ' + err);- dispatch(actions.showNotification(i18n.t('core:errorCreatingFile'), 'warning', true));- });+ const filePath =+ app.currentDirectoryPath ++ AppConfig.dirSeparator ++ 'textfile' ++ AppConfig.beginTagContainer ++ formatDateTime4Tag(new Date(), true) ++ AppConfig.endTagContainer ++ '.txt';+ PlatformIO.saveFilePromise(filePath, '', true)+ .then(() => {+ dispatch(actions.reflectCreateEntry(filePath, true));+ dispatch(+ actions.showNotification(+ i18n.t('core:fileCreateSuccessfully'),+ 'info',+ true+ )+ );+ dispatch(actions.openFile(filePath));+ // TODO select file // dispatch(actions.setLastSelectedEntry(filePath));+ return true;+ })+ .catch(err => {+ console.warn('File creation failed with ' + err);+ dispatch(+ actions.showNotification(+ i18n.t('core:errorCreatingFile'),+ 'warning',+ true+ )+ );+ });} else {- dispatch(actions.showNotification(i18n.t('core:firstOpenaFolder'), 'warning', true));+ dispatch(+ actions.showNotification(+ i18n.t('core:firstOpenaFolder'),+ 'warning',+ true+ )+ );}},- createFileAdvanced: (targetPath: string, fileName: string, content: string, fileType: 'md' | 'txt' | 'html') => (- dispatch: (actions: Object) => void,- getState: () => Object- ) => {+ createFileAdvanced: (+ targetPath: string,+ fileName: string,+ content: string,+ fileType: 'md' | 'txt' | 'html'+ ) => (dispatch: (actions: Object) => void, getState: () => Object) => {const fileNameAndExt = fileName + '.' + fileType;- const filePath = normalizePath(targetPath) + AppConfig.dirSeparator + fileNameAndExt;+ const filePath =+ normalizePath(targetPath) + AppConfig.dirSeparator + fileNameAndExt;let fileContent = content;if (fileType === 'html') {const newHTMLFileContent = getState().settings.newHTMLFileContent;- fileContent = newHTMLFileContent.split('<body></body>')[0] + '<body>' + content + '</body>' + newHTMLFileContent.split('<body></body>')[1];+ fileContent =+ newHTMLFileContent.split('<body></body>')[0] ++ '<body>' ++ content ++ '</body>' ++ newHTMLFileContent.split('<body></body>')[1];}PlatformIO.saveFilePromise(filePath, fileContent, true).then(() => {@@ -816,7 +909,9 @@ export const actions = {dispatch(actions.setLastSelectedEntry(filePath));dispatch(actions.showNotification(- `File '${fileNameAndExt}' created.`, 'default', true+ `File '${fileNameAndExt}' created.`,+ 'default',+ true));return true;@@ -861,24 +956,46 @@ export const actions = {}const currentLocationId = getState().app;if (location.type === locationType.TYPE_CLOUD) {- PlatformIO.enableObjectStoreSupport(location).then(() => {- dispatch(actions.showNotification(i18n.t('core:connectedtoObjectStore'), 'default', true));- dispatch(actions.setReadOnlyMode(location.isReadOnly || false));- dispatch(actions.setCurrentLocationId(location.uuid));- dispatch(actions.loadDirectoryContent(location.paths[0]));- if (location.uuid !== currentLocationId) {- if (location.persistIndex) {- dispatch(LocationIndexActions.loadDirectoryIndex(location.paths[0]));- } else {- dispatch(LocationIndexActions.createDirectoryIndex(location.paths[0], location.fullTextIndex));+ PlatformIO.enableObjectStoreSupport(location)+ .then(() => {+ dispatch(+ actions.showNotification(+ i18n.t('core:connectedtoObjectStore'),+ 'default',+ true+ )+ );+ dispatch(actions.setReadOnlyMode(location.isReadOnly || false));+ dispatch(actions.setCurrentLocationId(location.uuid));+ dispatch(actions.loadDirectoryContent(location.paths[0]));+ if (location.uuid !== currentLocationId) {+ if (location.persistIndex) {+ dispatch(+ LocationIndexActions.loadDirectoryIndex(location.paths[0])+ );+ } else {+ dispatch(+ LocationIndexActions.createDirectoryIndex(+ location.paths[0],+ location.fullTextIndex+ )+ );+ }}- }- return true;- }).catch(() => {- dispatch(actions.showNotification(i18n.t('core:connectedtoObjectStoreFailed'), 'warning', true));- PlatformIO.disableObjectStoreSupport();- });- } else { // if (location.type === locationType.TYPE_LOCAL) {+ return true;+ })+ .catch(() => {+ dispatch(+ actions.showNotification(+ i18n.t('core:connectedtoObjectStoreFailed'),+ 'warning',+ true+ )+ );+ PlatformIO.disableObjectStoreSupport();+ });+ } else {+ // if (location.type === locationType.TYPE_LOCAL) {PlatformIO.disableObjectStoreSupport();dispatch(actions.setReadOnlyMode(location.isReadOnly || false));dispatch(actions.setCurrentLocationId(location.uuid));@@ -887,7 +1004,12 @@ export const actions = {if (location.persistIndex) {dispatch(LocationIndexActions.loadDirectoryIndex(location.paths[0]));} else {- dispatch(LocationIndexActions.createDirectoryIndex(location.paths[0], location.fullTextIndex));+ dispatch(+ LocationIndexActions.createDirectoryIndex(+ location.paths[0],+ location.fullTextIndex+ )+ );}}if (Pro && Pro.Watcher && location.watchForChanges) {@@ -949,10 +1071,11 @@ export const actions = {type: types.SET_READONLYMODE,isReadOnlyMode}),- openFile: (entryPath: string, isFile?: boolean = true, editMode: boolean = false) => (- dispatch: (actions: Object) => void,- getState: () => Object- ) => {+ openFile: (+ entryPath: string,+ isFile?: boolean = true,+ editMode: boolean = false+ ) => (dispatch: (actions: Object) => void, getState: () => Object) => {const supportedFileTypes: Array<Object> = getState().settings.supportedFileTypes;const entryForOpening: OpenedEntry = findExtensionsForEntry(@@ -961,7 +1084,11 @@ export const actions = {isFile);entryForOpening.url = PlatformIO.getURLforPath(entryPath); // Needed for the s3 support- if (editMode && entryForOpening.editingExtensionId && entryForOpening.editingExtensionId.length > 1) {+ if (+ editMode &&+ entryForOpening.editingExtensionId &&+ entryForOpening.editingExtensionId.length > 1+ ) {entryForOpening.editMode = true;}const localePar = getURLParameter(entryPath);@@ -984,7 +1111,9 @@ export const actions = {dispatch: (actions: Object) => void,getState: () => Object) => {- const currentEntries = getState().app.currentDirectoryEntries.filter(entry => entry.isFile);+ const currentEntries = getState().app.currentDirectoryEntries.filter(+ entry => entry.isFile+ );const lastSelectedEntry = getState().app.lastSelectedEntry;let filePath = pivotFilePath;if (!filePath) {@@ -1013,7 +1142,9 @@ export const actions = {dispatch: (actions: Object) => void,getState: () => Object) => {- const currentEntries = getState().app.currentDirectoryEntries.filter(entry => entry.isFile);+ const currentEntries = getState().app.currentDirectoryEntries.filter(+ entry => entry.isFile+ );const lastSelectedEntry = getState().app.lastSelectedEntry;let filePath = pivotFilePath;if (!filePath) {@@ -1049,7 +1180,7 @@ export const actions = {dispatch(actions.reflectDeleteEntryInt(path));dispatch(LocationIndexActions.reflectDeleteEntry(path));},- reflectCreateEntryInt: (newEntry) => ({+ reflectCreateEntryInt: newEntry => ({type: types.REFLECT_CREATE_ENTRY,newEntry}),@@ -1064,7 +1195,7 @@ export const actions = {description: '',tags: [],size: 0,- lmdt: (new Date()).getTime(),+ lmdt: new Date().getTime(),path};dispatch(actions.reflectCreateEntryInt(newEntry));@@ -1091,9 +1222,11 @@ export const actions = {path,entryMeta}),- reflectUpdateSidecarTags: (path: string, tags: Array<Tags>, updateIndex: boolean = true) => (- dispatch: (actions: Object) => void- ) => {+ reflectUpdateSidecarTags: (+ path: string,+ tags: Array<Tags>,+ updateIndex: boolean = true+ ) => (dispatch: (actions: Object) => void) => {dispatch(actions.reflectUpdateSidecarTagsInt(path, tags));if (updateIndex) {dispatch(LocationIndexActions.reflectUpdateSidecarTags(path, tags));@@ -1124,13 +1257,17 @@ export const actions = {// Delete sidecar file and thumbdeleteFilesPromise([getMetaFileLocationForFile(filePath),- getThumbFileLocationForFile(filePath),- ]).then(() => {- console.log('Cleaning meta file and thumb successful for ' + filePath);- return true;- }).catch((err) => {- console.warn('Cleaning meta file and thumb failed with ' + err);- });+ getThumbFileLocationForFile(filePath)+ ])+ .then(() => {+ console.log(+ 'Cleaning meta file and thumb successful for ' + filePath+ );+ return true;+ })+ .catch(err => {+ console.warn('Cleaning meta file and thumb failed with ' + err);+ });return true;}).catch(error => {@@ -1146,53 +1283,68 @@ export const actions = {},renameFile: (filePath: string, newFilePath: string) => (dispatch: (actions: Object) => void- ) => PlatformIO.renameFilePromise(filePath, newFilePath)- .then(() => {- // console.log('File renamed ' + filePath + ' to ' + newFilePath);- dispatch(- actions.showNotification(- i18n.t('core:renamingSuccessfully'),- 'default',- true- )- );- // Update sidecar file and thumb- renameFilesPromise([- [getMetaFileLocationForFile(filePath), getMetaFileLocationForFile(newFilePath)],- [getThumbFileLocationForFile(filePath), getThumbFileLocationForFile(newFilePath)]- ]).then(() => {- console.log('Renaming meta file and thumb successful for ' + filePath);- dispatch(actions.reflectRenameEntry(filePath, newFilePath));+ ) =>+ PlatformIO.renameFilePromise(filePath, newFilePath)+ .then(() => {+ // console.log('File renamed ' + filePath + ' to ' + newFilePath);+ dispatch(+ actions.showNotification(+ i18n.t('core:renamingSuccessfully'),+ 'default',+ true+ )+ );+ // Update sidecar file and thumb+ renameFilesPromise([+ [+ getMetaFileLocationForFile(filePath),+ getMetaFileLocationForFile(newFilePath)+ ],+ [+ getThumbFileLocationForFile(filePath),+ getThumbFileLocationForFile(newFilePath)+ ]+ ])+ .then(() => {+ console.log(+ 'Renaming meta file and thumb successful for ' + filePath+ );+ dispatch(actions.reflectRenameEntry(filePath, newFilePath));+ return true;+ })+ .catch(err => {+ dispatch(actions.reflectRenameEntry(filePath, newFilePath));+ console.warn('Renaming meta file and thumb failed with ' + err);+ });return true;- }).catch((err) => {- dispatch(actions.reflectRenameEntry(filePath, newFilePath));- console.warn('Renaming meta file and thumb failed with ' + err);- });- return true;- })- .catch(error => {- console.warn('Error while renaming file: ' + error);- dispatch(- actions.showNotification(- `Error while renaming file ${filePath}`,- 'error',- true- )- );- }),+ })+ .catch(error => {+ console.warn('Error while renaming file: ' + error);+ dispatch(+ actions.showNotification(+ `Error while renaming file ${filePath}`,+ 'error',+ true+ )+ );+ }),openFileNatively: (selectedFile: string) => () => {PlatformIO.openFile(selectedFile);},openURLExternally: (url: string, addAppVersion: boolean = false) => () => {PlatformIO.openUrl(url);},- saveFile: () => (+ saveFile: () => () =>// dispatch: (actions: Object) => void,// getState: () => Object- ) => {- actions.showNotification(i18n.t('core:notImplementedYet'), 'warning', true);- // const { app } = getState();- /* PlatformIO.saveFilePromise(filePath, content, true).then((isNewFile) => {+ {+ actions.showNotification(+ i18n.t('core:notImplementedYet'),+ 'warning',+ true+ );+ // const { app } = getState();+ /* PlatformIO.saveFilePromise(filePath, content, true).then((isNewFile) => {console.log(isNewFile);dispatch(actions.showNotification(i18n.t('core:fileCreatedSuccessfully.'), 'successfully', true)@@ -1206,7 +1358,7 @@ export const actions = {);return true;}); */- }+ }};function prepareDirectoryContent(@@ -1220,15 +1372,13 @@ function prepareDirectoryContent(const tmbGenerationList = [];const isWorkerAvailable = PlatformIO.isWorkerAvailable();dirEntries.map(entry => {- if (- !settings.showUnixHiddenEntries &&- entry.name.startsWith('.')- ) {+ if (!settings.showUnixHiddenEntries && entry.name.startsWith('.')) {return true;}const enhancedEntry = enhanceEntry(entry);directoryContent.push(enhancedEntry);- if ( // Enable thumb generation by+ if (+ // Enable thumb generation by!AppConfig.isWeb && // not in webdav mode!PlatformIO.haveObjectStoreSupport() && // not in object store modeenhancedEntry.isFile && // only for files@@ -1264,7 +1414,13 @@ function prepareDirectoryContent(function handleTmbGenerationFailed(error) {console.warn('Thumb generation failed: ' + error);dispatch(actions.setGeneratingThumbnails(false));- dispatch(actions.showNotification(i18n.t('core:generatingThumbnailsFailed'), 'warning', true));+ dispatch(+ actions.showNotification(+ i18n.t('core:generatingThumbnailsFailed'),+ 'warning',+ true+ )+ );}dispatch(actions.setGeneratingThumbnails(false));@@ -1299,7 +1455,9 @@ function findExtensionsForEntry(isFile: boolean = true): OpenedEntry {const fileExtension = extractFileExtension(entryPath).toLowerCase();- const viewingExtensionPath = isFile ? findExtensionPathForId('@tagspaces/text-viewer') : 'about:blank';+ const viewingExtensionPath = isFile+ ? findExtensionPathForId('@tagspaces/text-viewer')+ : 'about:blank';const fileForOpening: OpenedEntry = {path: entryPath,viewingExtensionPath,@@ -1332,22 +1490,82 @@ export function findAvailableExtensions() {// TODO Search in users tagspaces folder// Search in the installation folderconst extensionsFound = [- { extensionId: '@tagspaces/archive-viewer', extensionName: 'Archive Viewer', extensionType: 'viewer' },- { extensionId: '@tagspaces/document-viewer', extensionName: 'Documents Viewer', extensionType: 'viewer' },+ {+ extensionId: '@tagspaces/archive-viewer',+ extensionName: 'Archive Viewer',+ extensionType: 'viewer'+ },+ {+ extensionId: '@tagspaces/document-viewer',+ extensionName: 'Documents Viewer',+ extensionType: 'viewer'+ },// { extensionId: '@tagspaces/ebook-viewer', extensionName: 'EPUB Viewer', extensionType: 'viewer' },- { extensionId: '@tagspaces/html-editor', extensionName: 'HTML Editor', extensionType: 'editor' },- { extensionId: '@tagspaces/html-viewer', extensionName: 'HTML Viewer', extensionType: 'viewer' },- { extensionId: '@tagspaces/image-viewer', extensionName: 'Image Viewer', extensionType: 'viewer' },- { extensionId: '@tagspaces/json-editor', extensionName: 'JSON Viewer', extensionType: 'editor' },- { extensionId: '@tagspaces/md-viewer', extensionName: 'MarkDown Viewer', extensionType: 'viewer' },- { extensionId: '@tagspaces/media-player', extensionName: 'Media Player', extensionType: 'viewer' },- { extensionId: '@tagspaces/mhtml-viewer', extensionName: 'MHTML Viewer', extensionType: 'viewer' },- { extensionId: '@tagspaces/pdf-viewer', extensionName: 'PDF Viewer', extensionType: 'viewer' },- { extensionId: '@tagspaces/plain-viewer', extensionName: 'Simple Viewer', extensionType: 'viewer' },- { extensionId: '@tagspaces/rtf-viewer', extensionName: 'RTF Viewer', extensionType: 'viewer' },- { extensionId: '@tagspaces/text-editor', extensionName: 'Text Editor', extensionType: 'editor' },- { extensionId: '@tagspaces/text-viewer', extensionName: 'Text Viewer', extensionType: 'viewer' },- { extensionId: '@tagspaces/url-viewer', extensionName: 'URL Viewer', extensionType: 'viewer' },+ {+ extensionId: '@tagspaces/html-editor',+ extensionName: 'HTML Editor',+ extensionType: 'editor'+ },+ {+ extensionId: '@tagspaces/html-viewer',+ extensionName: 'HTML Viewer',+ extensionType: 'viewer'+ },+ {+ extensionId: '@tagspaces/image-viewer',+ extensionName: 'Image Viewer',+ extensionType: 'viewer'+ },+ {+ extensionId: '@tagspaces/json-editor',+ extensionName: 'JSON Viewer',+ extensionType: 'editor'+ },+ {+ extensionId: '@tagspaces/md-viewer',+ extensionName: 'MarkDown Viewer',+ extensionType: 'viewer'+ },+ {+ extensionId: '@tagspaces/media-player',+ extensionName: 'Media Player',+ extensionType: 'viewer'+ },+ {+ extensionId: '@tagspaces/mhtml-viewer',+ extensionName: 'MHTML Viewer',+ extensionType: 'viewer'+ },+ {+ extensionId: '@tagspaces/pdf-viewer',+ extensionName: 'PDF Viewer',+ extensionType: 'viewer'+ },+ {+ extensionId: '@tagspaces/plain-viewer',+ extensionName: 'Simple Viewer',+ extensionType: 'viewer'+ },+ {+ extensionId: '@tagspaces/rtf-viewer',+ extensionName: 'RTF Viewer',+ extensionType: 'viewer'+ },+ {+ extensionId: '@tagspaces/text-editor',+ extensionName: 'Text Editor',+ extensionType: 'editor'+ },+ {+ extensionId: '@tagspaces/text-viewer',+ extensionName: 'Text Viewer',+ extensionType: 'viewer'+ },+ {+ extensionId: '@tagspaces/url-viewer',+ extensionName: 'URL Viewer',+ extensionType: 'viewer'+ }];return extensionsFound;}@@ -1360,8 +1578,11 @@ export const getDirectoryPath = (state: Object) =>export const getCurrentLocationPath = (state: Object) => {let pathCurrentLocation;if (state.locations) {- state.locations.map((location) => {- if (state.app.currentLocationId && location.uuid === state.app.currentLocationId) {+ state.locations.map(location => {+ if (+ state.app.currentLocationId &&+ location.uuid === state.app.currentLocationId+ ) {pathCurrentLocation = location.paths[0];}return true;@@ -1373,33 +1594,55 @@ export const isUpdateAvailable = (state: Object) => state.app.isUpdateAvailable;export const isUpdateInProgress = (state: Object) =>state.app.isUpdateInProgress;export const isOnline = (state: Object) => state.app.isOnline;-export const getLastSelectedEntry = (state: Object) => state.app.lastSelectedEntry;+export const getLastSelectedEntry = (state: Object) =>+ state.app.lastSelectedEntry;export const getSelectedTag = (state: Object) => state.app.tag;export const getSelectedEntries = (state: Object) => state.app.selectedEntries;export const isFileOpened = (state: Object) => state.app.openedFiles.length > 0;-export const isGeneratingThumbs = (state: Object) => state.app.isGeneratingThumbs;+export const isGeneratingThumbs = (state: Object) =>+ state.app.isGeneratingThumbs;// export const isFileDragged = (state: Object) => state.app.isFileDragged;export const isReadOnlyMode = (state: Object) => state.app.isReadOnlyMode;-export const isOnboardingDialogOpened = (state: Object) => state.app.onboardingDialogOpened;-export const isEditTagDialogOpened = (state: Object) => state.app.editTagDialogOpened;-export const isAboutDialogOpened = (state: Object) => state.app.aboutDialogOpened;+export const isOnboardingDialogOpened = (state: Object) =>+ state.app.onboardingDialogOpened;+export const isEditTagDialogOpened = (state: Object) =>+ state.app.editTagDialogOpened;+export const isAboutDialogOpened = (state: Object) =>+ state.app.aboutDialogOpened;export const isKeysDialogOpened = (state: Object) => state.app.keysDialogOpened;-export const isLicenseDialogOpened = (state: Object) => state.app.licenseDialogOpened;-export const isThirdPartyLibsDialogOpened = (state: Object) => state.app.thirdPartyLibsDialogOpened;-export const isSettingsDialogOpened = (state: Object) => state.app.settingsDialogOpened;-export const isCreateDirectoryOpened = (state: Object) => state.app.createDirectoryDialogOpened;-export const isCreateFileDialogOpened = (state: Object) => state.app.createFileDialogOpened;-export const isSelectDirectoryDialogOpened = (state: Object) => state.app.selectDirectoryDialogOpened;+export const isLicenseDialogOpened = (state: Object) =>+ state.app.licenseDialogOpened;+export const isThirdPartyLibsDialogOpened = (state: Object) =>+ state.app.thirdPartyLibsDialogOpened;+export const isSettingsDialogOpened = (state: Object) =>+ state.app.settingsDialogOpened;+export const isCreateDirectoryOpened = (state: Object) =>+ state.app.createDirectoryDialogOpened;+export const isCreateFileDialogOpened = (state: Object) =>+ state.app.createFileDialogOpened;+export const isSelectDirectoryDialogOpened = (state: Object) =>+ state.app.selectDirectoryDialogOpened;export const getOpenedFiles = (state: Object) => state.app.openedFiles;-export const getNotificationStatus = (state: Object) => state.app.notificationStatus;-export const getCurrentDirectoryColor = (state: Object) => state.app.currentDirectoryColor;-export const getSearchResults = (state: Object) => state.app.currentDirectoryEntries;-export const getSearchResultCount = (state: Object) => state.app.currentDirectoryEntries.length;-export const getCurrentLocationId = (state: Object) => state.app.currentLocationId;-export const isEntryInFullWidth = (state: Object) => state.app.isEntryInFullWidth;+export const getNotificationStatus = (state: Object) =>+ state.app.notificationStatus;+export const getCurrentDirectoryColor = (state: Object) =>+ state.app.currentDirectoryColor;+export const getSearchResults = (state: Object) =>+ state.app.currentDirectoryEntries;+export const getSearchResultCount = (state: Object) =>+ state.app.currentDirectoryEntries.length;+export const getCurrentLocationId = (state: Object) =>+ state.app.currentLocationId;+export const isEntryInFullWidth = (state: Object) =>+ state.app.isEntryInFullWidth;export const isLoading = (state: Object) => state.app.isLoading;-export const isLocationManagerPanelOpened = (state: Object) => state.app.locationManagerPanelOpened;-export const isTagLibraryPanelOpened = (state: Object) => state.app.tagLibraryPanelOpened;-export const isSearchPanelOpened = (state: Object) => state.app.searchPanelOpened;-export const isPerspectivesPanelOpened = (state: Object) => state.app.perspectivesPanelOpened;-export const isHelpFeedbackPanelOpened = (state: Object) => state.app.helpFeedbackPanelOpened;+export const isLocationManagerPanelOpened = (state: Object) =>+ state.app.locationManagerPanelOpened;+export const isTagLibraryPanelOpened = (state: Object) =>+ state.app.tagLibraryPanelOpened;+export const isSearchPanelOpened = (state: Object) =>+ state.app.searchPanelOpened;+export const isPerspectivesPanelOpened = (state: Object) =>+ state.app.perspectivesPanelOpened;+export const isHelpFeedbackPanelOpened = (state: Object) =>+ state.app.helpFeedbackPanelOpened;diff --git a/app/reducers/index.js b/app/reducers/index.jsindex f360418ac..c6ec8454a 100644--- a/app/reducers/index.js+++ b/app/reducers/index.js@@ -88,7 +88,7 @@ const rootPersistConfig = {storage,version: 2,blacklist,- debug: false,+ debug: false// migrate: createMigrate(migrations, { debug: true }),// https://github.com/rt2zz/redux-persist/blob/b6a60bd653d59c4fe462e2e0ea827fd76eb190e1/README.md#state-reconciler// stateReconciler: autoMergeLevel2,diff --git a/app/reducers/io-actions.js b/app/reducers/io-actions.jsindex e4251aa01..0709f2c7d 100644--- a/app/reducers/io-actions.js+++ b/app/reducers/io-actions.js@@ -24,29 +24,36 @@ import {getThumbFileLocationForFile,normalizePath} from '../utils/paths';-import {- copyFilesPromise,- renameFilesPromise-} from '../services/utils-io';+import { copyFilesPromise, renameFilesPromise } from '../services/utils-io';import AppConfig from '../config';import i18n from '../services/i18n';import { Pro } from '../pro';import TaggingActions from './tagging-actions';const actions = {- extractContent: (options: Object = { EXIFGeo: true, EXIFDateTime: true, IPTCDescription: true, IPTCTags: true }) => (- dispatch: (actions: Object) => void,- getState: () => Object- ) => {+ extractContent: (+ options: Object = {+ EXIFGeo: true,+ EXIFDateTime: true,+ IPTCDescription: true,+ IPTCTags: true+ }+ ) => (dispatch: (actions: Object) => void, getState: () => Object) => {const { currentDirectoryEntries } = getState().app;if (!Pro || !Pro.ContentExtractor) {dispatch(AppActions.showNotification(i18n.t('core:needProVersion')));return false;}- Pro.ContentExtractor.extractContent(currentDirectoryEntries, dispatch, AppActions, TaggingActions, options);+ Pro.ContentExtractor.extractContent(+ currentDirectoryEntries,+ dispatch,+ AppActions,+ TaggingActions,+ options+ );},moveFiles: (paths: Array<string>, targetPath: string) => (- dispatch: (actions: Object) => void,+ dispatch: (actions: Object) => void) => {/* const renameJobs = [];paths.map((path) => {@@ -61,60 +68,98 @@ const actions = {dispatch(AppActions.showNotification(i18n.t('core:movingFilesFailed')));}); */const moveJobs = [];- paths.map((path) => {- moveJobs.push([path, normalizePath(targetPath) + AppConfig.dirSeparator + extractFileName(path)]);+ paths.map(path => {+ moveJobs.push([+ path,+ normalizePath(targetPath) ++ AppConfig.dirSeparator ++ extractFileName(path)+ ]);return true;});- renameFilesPromise(moveJobs).then(() => {- dispatch(AppActions.showNotification(i18n.t('core:filesMovedSuccessful')));- const moveMetaJobs = [];- moveJobs.map((job) => {- dispatch(AppActions.reflectDeleteEntry(job[0])); // TODO moved files should be added to the index, if the target dir in index- moveMetaJobs.push([getMetaFileLocationForFile(job[0]), getMetaFileLocationForFile(job[1])]);- moveMetaJobs.push([getThumbFileLocationForFile(job[0]), getThumbFileLocationForFile(job[1])]);- renameFilesPromise(moveMetaJobs).then(() => {- console.log('Moving meta and thumbs successful');+ renameFilesPromise(moveJobs)+ .then(() => {+ dispatch(+ AppActions.showNotification(i18n.t('core:filesMovedSuccessful'))+ );+ const moveMetaJobs = [];+ moveJobs.map(job => {+ dispatch(AppActions.reflectDeleteEntry(job[0])); // TODO moved files should be added to the index, if the target dir in index+ moveMetaJobs.push([+ getMetaFileLocationForFile(job[0]),+ getMetaFileLocationForFile(job[1])+ ]);+ moveMetaJobs.push([+ getThumbFileLocationForFile(job[0]),+ getThumbFileLocationForFile(job[1])+ ]);+ renameFilesPromise(moveMetaJobs)+ .then(() => {+ console.log('Moving meta and thumbs successful');+ return true;+ })+ .catch(err => {+ console.warn('At least one meta or thumb was not moved ' + err);+ });return true;- }).catch(err => {- console.warn('At least one meta or thumb was not moved ' + err);});return true;+ })+ .catch(err => {+ console.warn('Moving files failed with ' + err);+ dispatch(+ AppActions.showNotification(i18n.t('core:copyingFilesFailed'))+ );});- return true;- }).catch((err) => {- console.warn('Moving files failed with ' + err);- dispatch(AppActions.showNotification(i18n.t('core:copyingFilesFailed')));- });},copyFiles: (paths: Array<string>, targetPath: string) => (- dispatch: (actions: Object) => void,+ dispatch: (actions: Object) => void) => {const copyJobs = [];- paths.map((path) => {- copyJobs.push([path, normalizePath(targetPath) + AppConfig.dirSeparator + extractFileName(path)]);+ paths.map(path => {+ copyJobs.push([+ path,+ normalizePath(targetPath) ++ AppConfig.dirSeparator ++ extractFileName(path)+ ]);return true;});- copyFilesPromise(copyJobs).then(() => {- dispatch(AppActions.showNotification(i18n.t('core:filesCopiedSuccessful')));- const copyMetaJobs = [];- copyJobs.map((job) => {- // dispatch(AppActions.reflectCopyEntry(job[0])); // TODO need only for the index if the target dir is indexed- copyMetaJobs.push([getMetaFileLocationForFile(job[0]), getMetaFileLocationForFile(job[1])]);- copyMetaJobs.push([getThumbFileLocationForFile(job[0]), getThumbFileLocationForFile(job[1])]);- copyFilesPromise(copyMetaJobs).then(() => {- console.log('Copy meta and thumbs successful');+ copyFilesPromise(copyJobs)+ .then(() => {+ dispatch(+ AppActions.showNotification(i18n.t('core:filesCopiedSuccessful'))+ );+ const copyMetaJobs = [];+ copyJobs.map(job => {+ // dispatch(AppActions.reflectCopyEntry(job[0])); // TODO need only for the index if the target dir is indexed+ copyMetaJobs.push([+ getMetaFileLocationForFile(job[0]),+ getMetaFileLocationForFile(job[1])+ ]);+ copyMetaJobs.push([+ getThumbFileLocationForFile(job[0]),+ getThumbFileLocationForFile(job[1])+ ]);+ copyFilesPromise(copyMetaJobs)+ .then(() => {+ console.log('Copy meta and thumbs successful');+ return true;+ })+ .catch(err => {+ console.warn('At least one meta or thumb was not copied ' + err);+ });return true;- }).catch(err => {- console.warn('At least one meta or thumb was not copied ' + err);});return true;+ })+ .catch(err => {+ console.warn('Moving files failed with ' + err);+ dispatch(+ AppActions.showNotification(i18n.t('core:copyingFilesFailed'))+ );});- return true;- }).catch((err) => {- console.warn('Moving files failed with ' + err);- dispatch(AppActions.showNotification(i18n.t('core:copyingFilesFailed')));- });- },+ }};export default actions;diff --git a/app/reducers/location-index.js b/app/reducers/location-index.jsindex 5199eefc0..8800d87e4 100644--- a/app/reducers/location-index.js+++ b/app/reducers/location-index.js@@ -23,7 +23,7 @@ import { Pro } from '../pro';import {extractFileExtension,extractFileName,- extractTagsAsObjects,+ extractTagsAsObjects// getThumbFileLocationForFile} from '../utils/paths';import type { SearchQuery } from '../services/search';@@ -49,7 +49,6 @@ export const types = {REFLECT_UPDATE_SIDECARMETA: 'INDEX/REFLECT_UPDATE_SIDECARMETA'};-export const initialState = {currentDirectoryIndex: [],isIndexing: false@@ -57,83 +56,84 @@ export const initialState = {export default (state: Object = initialState, action: Object) => {switch (action.type) {- case types.INDEX_DIRECTORY_START: {- return {- ...state,- currentDirectoryIndex: [],- isIndexing: true- };- }- case types.INDEX_DIRECTORY_CLEAR: {- return {- ...state,- currentDirectoryIndex: [],- isIndexing: false- };- }- case types.INDEX_DIRECTORY_CANCEL: {- window.walkCanceled = true;- return { ...state, isIndexing: false };- }- case types.INDEX_DIRECTORY_SUCCESS: {- return {- ...state,- currentDirectoryIndex: action.directoryIndex,- isIndexing: false- };- }- case types.INDEX_DIRECTORY_FAILURE: {- return {- ...state,- lastError: action.error,- currentDirectoryIndex: [],- isIndexing: false- };- }- case types.REFLECT_DELETE_ENTRY: {- const newDirectoryIndex = state.currentDirectoryIndex.filter((entry) => !entry.path.startsWith(action.path));- if (state.currentDirectoryIndex.length > newDirectoryIndex.length) {+ case types.INDEX_DIRECTORY_START: {return {...state,- currentDirectoryIndex: newDirectoryIndex+ currentDirectoryIndex: [],+ isIndexing: true};}- return state;- }- case types.REFLECT_CREATE_ENTRY: {- const entryIndex = state.currentDirectoryIndex.findIndex((entry) => entry.path === action.newEntry.path);- if (entryIndex) {- return state;+ case types.INDEX_DIRECTORY_CLEAR: {+ return {+ ...state,+ currentDirectoryIndex: [],+ isIndexing: false+ };}- return {- ...state,- currentDirectoryIndex: [- action.newEntry,- ...state.currentDirectoryIndex- ],- };- }- case types.REFLECT_RENAME_ENTRY: {- return {- ...state,- currentDirectoryIndex: state.currentDirectoryIndex.map((entry) => {- if (entry.path !== action.path) {- return entry;- }+ case types.INDEX_DIRECTORY_CANCEL: {+ window.walkCanceled = true;+ return { ...state, isIndexing: false };+ }+ case types.INDEX_DIRECTORY_SUCCESS: {+ return {+ ...state,+ currentDirectoryIndex: action.directoryIndex,+ isIndexing: false+ };+ }+ case types.INDEX_DIRECTORY_FAILURE: {+ return {+ ...state,+ lastError: action.error,+ currentDirectoryIndex: [],+ isIndexing: false+ };+ }+ case types.REFLECT_DELETE_ENTRY: {+ const newDirectoryIndex = state.currentDirectoryIndex.filter(+ entry => !entry.path.startsWith(action.path)+ );+ if (state.currentDirectoryIndex.length > newDirectoryIndex.length) {return {- ...entry,- path: action.newPath,- // thumbPath: getThumbFileLocationForFile(action.newPath), // disabled due performance concerns- name: extractFileName(action.newPath),- extension: extractFileExtension(action.newPath),- tags: [- ...entry.tags.filter(tag => tag.type === 'sidecar'), // add only sidecar tags- ...extractTagsAsObjects(action.newPath) // , getTagDelimiter(state))- ]+ ...state,+ currentDirectoryIndex: newDirectoryIndex};- })- };- /* const indexForRenamingInIndex = state.currentDirectoryIndex.findIndex((entry) => entry.path === action.path);+ }+ return state;+ }+ case types.REFLECT_CREATE_ENTRY: {+ const entryIndex = state.currentDirectoryIndex.findIndex(+ entry => entry.path === action.newEntry.path+ );+ if (entryIndex) {+ return state;+ }+ return {+ ...state,+ currentDirectoryIndex: [action.newEntry, ...state.currentDirectoryIndex]+ };+ }+ case types.REFLECT_RENAME_ENTRY: {+ return {+ ...state,+ currentDirectoryIndex: state.currentDirectoryIndex.map(entry => {+ if (entry.path !== action.path) {+ return entry;+ }+ return {+ ...entry,+ path: action.newPath,+ // thumbPath: getThumbFileLocationForFile(action.newPath), // disabled due performance concerns+ name: extractFileName(action.newPath),+ extension: extractFileExtension(action.newPath),+ tags: [+ ...entry.tags.filter(tag => tag.type === 'sidecar'), // add only sidecar tags+ ...extractTagsAsObjects(action.newPath) // , getTagDelimiter(state))+ ]+ };+ })+ };+ /* const indexForRenamingInIndex = state.currentDirectoryIndex.findIndex((entry) => entry.path === action.path);if (indexForRenamingInIndex >= 0) {const updateEntry = {...state.currentDirectoryIndex[indexForRenamingInIndex],@@ -156,24 +156,24 @@ export default (state: Object = initialState, action: Object) => {};}return state; */- }- case types.REFLECT_UPDATE_SIDECARTAGS: {- return {- ...state,- currentDirectoryIndex: state.currentDirectoryIndex.map((entry) => {- if (entry.path !== action.path) {- return entry;- }- return {- ...entry,- tags: [- ...entry.tags.filter(tag => tag.type === 'plain'),- ...action.tags- ]- };- })- };- /* const indexForUpdatingInIndex = state.currentDirectoryIndex.findIndex((entry) => entry.path === action.path);+ }+ case types.REFLECT_UPDATE_SIDECARTAGS: {+ return {+ ...state,+ currentDirectoryIndex: state.currentDirectoryIndex.map(entry => {+ if (entry.path !== action.path) {+ return entry;+ }+ return {+ ...entry,+ tags: [+ ...entry.tags.filter(tag => tag.type === 'plain'),+ ...action.tags+ ]+ };+ })+ };+ /* const indexForUpdatingInIndex = state.currentDirectoryIndex.findIndex((entry) => entry.path === action.path);if (indexForUpdatingInIndex >= 0) {const updateEntry = {...state.currentDirectoryIndex[indexForUpdatingInIndex],@@ -192,21 +192,21 @@ export default (state: Object = initialState, action: Object) => {};}return state; */- }- case types.REFLECT_UPDATE_SIDECARMETA: {- return {- ...state,- currentDirectoryIndex: state.currentDirectoryIndex.map((entry) => {- if (entry.path !== action.path) {- return entry;- }- return {- ...entry,- ...action.entryMeta- };- })- };- /* const indexForUpdatingInIndex = state.currentDirectoryIndex.findIndex((entry) => entry.path === action.path);+ }+ case types.REFLECT_UPDATE_SIDECARMETA: {+ return {+ ...state,+ currentDirectoryIndex: state.currentDirectoryIndex.map(entry => {+ if (entry.path !== action.path) {+ return entry;+ }+ return {+ ...entry,+ ...action.entryMeta+ };+ })+ };+ /* const indexForUpdatingInIndex = state.currentDirectoryIndex.findIndex((entry) => entry.path === action.path);if (indexForUpdatingInIndex >= 0) {const updateEntry = {...state.currentDirectoryIndex[indexForUpdatingInIndex],@@ -222,10 +222,10 @@ export default (state: Object = initialState, action: Object) => {};}return state; */- }- default: {- return state;- }+ }+ default: {+ return state;+ }}};@@ -237,13 +237,23 @@ export const actions = {getState: () => Object) => {const state = getState();- const currentLocation: Location = getLocation(state, state.app.currentLocationId);+ const currentLocation: Location = getLocation(+ state,+ state.app.currentLocationId+ );dispatch(actions.startDirectoryIndexing());createDirectoryIndex(directoryPath, extractText).then(directoryIndex => {dispatch(actions.indexDirectorySuccess(directoryIndex));- if (Pro && Pro.Indexer) { // && (currentLocation.persistIndex || PlatformIO.haveObjectStoreSupport())) { // always persist on s3 stores- Pro.Indexer.persistIndex(directoryPath, directoryIndex, (currentLocation.type === locationType.TYPE_CLOUD) ? '/' : AppConfig.dirSeparator);+ if (Pro && Pro.Indexer) {+ // && (currentLocation.persistIndex || PlatformIO.haveObjectStoreSupport())) { // always persist on s3 stores+ Pro.Indexer.persistIndex(+ directoryPath,+ directoryIndex,+ currentLocation.type === locationType.TYPE_CLOUD+ ? '/'+ : AppConfig.dirSeparator+ );}return true;})@@ -257,17 +267,35 @@ export const actions = {getState: () => Object) => {const state = getState();- const currentLocation: Location = getLocation(state, state.app.currentLocationId);+ const currentLocation: Location = getLocation(+ state,+ state.app.currentLocationId+ );dispatch(actions.startDirectoryIndexing());- dispatch(AppActions.showNotification(i18n.t('core:loadingIndex'), 'default', true));+ dispatch(+ AppActions.showNotification(i18n.t('core:loadingIndex'), 'default', true)+ );if (Pro && Pro.Indexer.loadIndex) {- Pro.Indexer.loadIndex(directoryPath, (currentLocation.type === locationType.TYPE_CLOUD) ? '/' : AppConfig.dirSeparator).then((directoryIndex) => {- dispatch(actions.indexDirectorySuccess(directoryIndex));- return true;- }).catch(err => {- dispatch(actions.indexDirectoryFailure(err));- dispatch(AppActions.showNotification(i18n.t('core:loadingIndexFailed'), 'warning', true));- });+ Pro.Indexer.loadIndex(+ directoryPath,+ currentLocation.type === locationType.TYPE_CLOUD+ ? '/'+ : AppConfig.dirSeparator+ )+ .then(directoryIndex => {+ dispatch(actions.indexDirectorySuccess(directoryIndex));+ return true;+ })+ .catch(err => {+ dispatch(actions.indexDirectoryFailure(err));+ dispatch(+ AppActions.showNotification(+ i18n.t('core:loadingIndexFailed'),+ 'warning',+ true+ )+ );+ });}},clearDirectoryIndex: () => ({@@ -277,20 +305,31 @@ export const actions = {dispatch: (actions: Object) => void,getState: () => Object) => {- dispatch(AppActions.showNotification(i18n.t('core:searching'), 'default', false));- setTimeout(() => { // Workaround used to show the start search notification+ dispatch(+ AppActions.showNotification(i18n.t('core:searching'), 'default', false)+ );+ setTimeout(() => {+ // Workaround used to show the start search notificationSearch.searchLocationIndex(getState().locationIndex.currentDirectoryIndex,searchQuery- ).then((searchResults) => {- dispatch(AppActions.updateSearchResults(searchResults));- dispatch(AppActions.hideNotifications());- return true;- }).catch(() => {- dispatch(AppActions.updateSearchResults([]));- dispatch(AppActions.hideNotifications());- dispatch(AppActions.showNotification(i18n.t('core:searchingFailed'), 'warning', true));- });+ )+ .then(searchResults => {+ dispatch(AppActions.updateSearchResults(searchResults));+ dispatch(AppActions.hideNotifications());+ return true;+ })+ .catch(() => {+ dispatch(AppActions.updateSearchResults([]));+ dispatch(AppActions.hideNotifications());+ dispatch(+ AppActions.showNotification(+ i18n.t('core:searchingFailed'),+ 'warning',+ true+ )+ );+ });}, 50);},indexDirectorySuccess: (directoryIndex: Array<Object>) => ({@@ -327,5 +366,6 @@ export const actions = {};// Selectors-export const getIndexedEntriesCount = (state: Object) => state.locationIndex.currentDirectoryIndex.length;+export const getIndexedEntriesCount = (state: Object) =>+ state.locationIndex.currentDirectoryIndex.length;export const isIndexing = (state: Object) => state.locationIndex.isIndexing;diff --git a/app/reducers/locations.js b/app/reducers/locations.jsindex ce34ea711..488ac9264 100644--- a/app/reducers/locations.js+++ b/app/reducers/locations.js@@ -33,7 +33,7 @@ export const types = {export const locationType = {TYPE_LOCAL: '0',- TYPE_CLOUD: '1',+ TYPE_CLOUD: '1'};export type Location = {@@ -58,85 +58,85 @@ export const initialState = [];export default (state: Array<Location> = initialState, action: Object) => {switch (action.type) {- case types.ADD_LOCATION: {- if (action.location.isDefault) {- state.forEach((location) => {- location.isDefault = false;- });- }- return [- ...state,- {- ...action.location,- uuid: action.location.uuid || uuidv1(),- creationDate: new Date().toJSON(),- }- ];- }- case types.EDIT_LOCATION: {- let indexForEditing = -1;- state.forEach((location, index) => {- if (location.uuid === action.location.uuid) {- indexForEditing = index;- }+ case types.ADD_LOCATION: {if (action.location.isDefault) {- location.isDefault = false;+ state.forEach(location => {+ location.isDefault = false;+ });}- });- if (indexForEditing >= 0) {return [- ...state.slice(0, indexForEditing),- { ...state[indexForEditing], ...action.location },- ...state.slice(indexForEditing + 1)+ ...state,+ {+ ...action.location,+ uuid: action.location.uuid || uuidv1(),+ creationDate: new Date().toJSON()+ }];}- return state;- }- case types.MOVE_UP_LOCATION: {- let indexForUpdating = -1;- state.forEach((location, index) => {- if (location.uuid === action.uuid) {- indexForUpdating = index;+ case types.EDIT_LOCATION: {+ let indexForEditing = -1;+ state.forEach((location, index) => {+ if (location.uuid === action.location.uuid) {+ indexForEditing = index;+ }+ if (action.location.isDefault) {+ location.isDefault = false;+ }+ });+ if (indexForEditing >= 0) {+ return [+ ...state.slice(0, indexForEditing),+ { ...state[indexForEditing], ...action.location },+ ...state.slice(indexForEditing + 1)+ ];}- });- if (indexForUpdating > 0) {- const secondIndex = indexForUpdating - 1;- return immutablySwapItems(state, indexForUpdating, secondIndex);+ return state;}- return state;- }- case types.MOVE_DOWN_LOCATION: {- let indexForUpdating = -1;- state.forEach((location, index) => {- if (location.uuid === action.uuid) {- indexForUpdating = index;+ case types.MOVE_UP_LOCATION: {+ let indexForUpdating = -1;+ state.forEach((location, index) => {+ if (location.uuid === action.uuid) {+ indexForUpdating = index;+ }+ });+ if (indexForUpdating > 0) {+ const secondIndex = indexForUpdating - 1;+ return immutablySwapItems(state, indexForUpdating, secondIndex);}- });- if (indexForUpdating >= 0 && indexForUpdating < state.length - 1) {- const secondIndex = indexForUpdating + 1;- return immutablySwapItems(state, indexForUpdating, secondIndex);+ return state;}- return state;- }- case types.REMOVE_LOCATION: {- let indexForRemoving = -1;- state.forEach((location, index) => {- if (location.uuid === action.location.uuid) {- indexForRemoving = index;+ case types.MOVE_DOWN_LOCATION: {+ let indexForUpdating = -1;+ state.forEach((location, index) => {+ if (location.uuid === action.uuid) {+ indexForUpdating = index;+ }+ });+ if (indexForUpdating >= 0 && indexForUpdating < state.length - 1) {+ const secondIndex = indexForUpdating + 1;+ return immutablySwapItems(state, indexForUpdating, secondIndex);}- });- if (indexForRemoving >= 0) {- return [- ...state.slice(0, indexForRemoving),- ...state.slice(indexForRemoving + 1)- ];- // return state.filter( (item, index) => index !== indexForRemoving);+ return state;+ }+ case types.REMOVE_LOCATION: {+ let indexForRemoving = -1;+ state.forEach((location, index) => {+ if (location.uuid === action.location.uuid) {+ indexForRemoving = index;+ }+ });+ if (indexForRemoving >= 0) {+ return [+ ...state.slice(0, indexForRemoving),+ ...state.slice(indexForRemoving + 1)+ ];+ // return state.filter( (item, index) => index !== indexForRemoving);+ }+ return state;+ }+ default: {+ return state;}- return state;- }- default: {- return state;- }}};@@ -149,9 +149,15 @@ export const actions = {dispatch(AppActions.openLocation(location));}},- createLocation: (location: Location) => ({ type: types.ADD_LOCATION, location }),+ createLocation: (location: Location) => ({+ type: types.ADD_LOCATION,+ location+ }),moveLocationUp: (uuid: string) => ({ type: types.MOVE_UP_LOCATION, uuid }),- moveLocationDown: (uuid: string) => ({ type: types.MOVE_DOWN_LOCATION, uuid }),+ moveLocationDown: (uuid: string) => ({+ type: types.MOVE_DOWN_LOCATION,+ uuid+ }),editLocation: (location: Location) => (dispatch: (actions: Object) => void) => {@@ -177,9 +183,12 @@ export const actions = {// Selectorsexport const getLocations = (state: Object): Array<Location> => state.locations;-export const getLocation = (state: Object, locationId: string): Location | null => {+export const getLocation = (+ state: Object,+ locationId: string+): Location | null => {let foundLocation = null;- state.locations.map((location) => {+ state.locations.map(location => {if (location.uuid === locationId) {foundLocation = location;}@@ -189,7 +198,7 @@ export const getLocation = (state: Object, locationId: string): Location | null};export const getDefaultLocationId = (state: Object): ?string => {let defaultLocationID;- state.locations.map((location) => {+ state.locations.map(location => {if (location.isDefault) {defaultLocationID = location.uuid;}diff --git a/app/reducers/settings-default.js b/app/reducers/settings-default.jsindex 5ce37a32f..d4f49e646 100644--- a/app/reducers/settings-default.js+++ b/app/reducers/settings-default.js@@ -180,47 +180,47 @@ export default {keyBindings: [{name: 'selectAll',- command: (AppConfig.isMacLike ? 'command' : 'ctrl') + '+a',+ command: (AppConfig.isMacLike ? 'command' : 'ctrl') + '+a'},{name: 'closeViewer',- command: (AppConfig.isMacLike ? 'command' : 'ctrl') + '+w',+ command: (AppConfig.isMacLike ? 'command' : 'ctrl') + '+w'},{name: 'saveDocument',- command: (AppConfig.isMacLike ? 'command' : 'ctrl') + '+s',+ command: (AppConfig.isMacLike ? 'command' : 'ctrl') + '+s'},{name: 'reloadDocument',- command: (AppConfig.isMacLike ? 'command' : 'ctrl') + '+r',+ command: (AppConfig.isMacLike ? 'command' : 'ctrl') + '+r'},{name: 'editDocument',- command: (AppConfig.isMacLike ? 'command' : 'ctrl') + '+e',+ command: (AppConfig.isMacLike ? 'command' : 'ctrl') + '+e'},{name: 'deleteDocument',- command: 'del',+ command: 'del'},{name: 'showLocationManager',- command: (AppConfig.isMacLike ? 'command' : 'ctrl') + '+1',+ command: (AppConfig.isMacLike ? 'command' : 'ctrl') + '+1'},{name: 'showTagLibrary',- command: (AppConfig.isMacLike ? 'command' : 'ctrl') + '+2',+ command: (AppConfig.isMacLike ? 'command' : 'ctrl') + '+2'},{name: 'showSearch',- command: (AppConfig.isMacLike ? 'command' : 'ctrl') + '+3',+ command: (AppConfig.isMacLike ? 'command' : 'ctrl') + '+3'},{name: 'toggleShowHiddenEntries',- command: (AppConfig.isMacLike ? 'command' : 'ctrl') + '+h',+ command: (AppConfig.isMacLike ? 'command' : 'ctrl') + '+h'},{name: 'addRemoveTags',- command: (AppConfig.isMacLike ? 'command' : 'ctrl') + '+t',+ command: (AppConfig.isMacLike ? 'command' : 'ctrl') + '+t'},/* {name: 'propertiesDocument',@@ -232,51 +232,51 @@ export default {},{name: 'prevDocument',- command: 'up',+ command: 'up'},{name: 'showHelp',- command: 'f1',+ command: 'f1'},{name: 'reloadApplication',- command: 'r a',+ command: 'r a'},{name: 'toggleFullScreen',- command: 'f11',+ command: 'f11'},{name: 'openDevTools',- command: 'f10',+ command: 'f10'},{name: 'openSearch',- command: (AppConfig.isMacLike ? 'command' : 'ctrl') + '+f',+ command: (AppConfig.isMacLike ? 'command' : 'ctrl') + '+f'},{name: 'renameFile',- command: 'f2',+ command: 'f2'},{name: 'openEntry',- command: 'enter',+ command: 'enter'},{name: 'openParentDirectory',- command: 'backspace',+ command: 'backspace'},{name: 'openFileExternally',- command: (AppConfig.isMacLike ? 'command' : 'ctrl') + '+enter',+ command: (AppConfig.isMacLike ? 'command' : 'ctrl') + '+enter'},{name: 'zoomIn',- command: (AppConfig.isMacLike ? 'command' : 'ctrl') + '+',+ command: (AppConfig.isMacLike ? 'command' : 'ctrl') + '+'},{name: 'zoomOut',- command: (AppConfig.isMacLike ? 'command' : 'ctrl') + '-',+ command: (AppConfig.isMacLike ? 'command' : 'ctrl') + '-'}],supportedFileTypes: [@@ -658,7 +658,7 @@ export default {type: 'docx',viewer: '@tagspaces/document-viewer',color: '#2196f3'- },+ }/* {type: 'xlsx',viewer: '@tagspaces/document-viewer',diff --git a/app/reducers/settings.js b/app/reducers/settings.jsindex 43d0ae0d1..2672cbced 100644--- a/app/reducers/settings.js+++ b/app/reducers/settings.js@@ -71,212 +71,250 @@ export const types = {export default (state = defaultSettings, action) => {switch (action.type) {- case types.UPGRADE_SETTINGS: {- const mergedKeyBindings = defaultSettings.keyBindings.map(x => Object.assign(x, state.keyBindings.find(y => y.name === x.name)));- const mergedFileTypes = defaultSettings.supportedFileTypes.map(x => Object.assign(x, state.supportedFileTypes.find(y => y.type === x.type)));- const combinedFileTypes = state.supportedFileTypes.map(x => Object.assign(x, mergedFileTypes.find(y => y.type === x.type)));- return {- ...defaultSettings,- ...state,- currentTheme: window.ExtTheme || state.currentTheme,- supportedThemes: defaultSettings.supportedThemes, // taking always the themes from default settings- supportedLanguages: defaultSettings.supportedLanguages, // taking always the languages from default settings- keyBindings: [- // ...defaultSettings.keyBindings, // use to reset to the default key bindings- ...mergedKeyBindings- ],- supportedFileTypes: [- // ...defaultSettings.supportedFileTypes, // use to reset to the default file types- ...combinedFileTypes- ]- };- }- case types.TOGGLE_SHOWUNIXHIDDENENTRIES: {- return { ...state, showUnixHiddenEntries: !state.showUnixHiddenEntries };- }- case types.SET_TAG_DELIMITER: {- return { ...state, tagDelimiter: action.delimiter };- }- case types.SET_MAX_SEARCH_RESULT: {- return { ...state, maxSearchResult: action.maxSearchResult };- }- case types.SET_DESKTOPMODE: {- return { ...state, desktopMode: action.desktopMode };- }- case types.SET_CHECKFORUPDATES: {- return { ...state, checkForUpdates: action.checkForUpdates };- }- case types.SET_USEDEFAULTLOCATION: {- return { ...state, useDefaultLocation: action.useDefaultLocation };- }- case types.SET_COLOREDFILEEXTENSION: {- return { ...state, coloredFileExtension: action.coloredFileExtension };- }- case types.SET_SHOWTAGAREAONSTARTUP: {- return { ...state, showTagAreaOnStartup: action.showTagAreaOnStartup };- }- case types.SET_LOADSLOCATIONMETADATA: {- return { ...state, loadsLocationMetaData: action.loadsLocationMetaData };- }- case types.SET_SEARCHINSUBFOLDERS: {- return { ...state, searchInSubfolders: action.searchInSubfolders };- }- case types.SET_WATCHCURRENTDIRECTORY: {- return { ...state, watchCurrentDirectory: action.watchCurrentDirectory };- }- case types.SET_FIRST_RUN: {- return { ...state, firstRun: action.firstRun };- }- case types.SET_LANGUAGE: {- i18n.changeLanguage(action.language);- return { ...state, interfaceLanguage: action.language };- }- case types.SET_APPDATAPATH: {- return { ...state, appDataPath: action.path };- }- case types.SET_CONTENTHASH: {- return { ...state, contentHash: action.contentHash };- }- case types.SET_UPDATEAVAILABLE: {- return { ...state, isUpdateAvailable: action.isUpdateAvailable };- }- case types.SET_UPDATEINPROGRESS: {- return { ...state, isUpdateInProgress: action.isUpdateInProgress };- }- case types.SET_CALCULATETAGS: {- return { ...state, calculateTags: action.calculateTags };- }- case types.SET_USETRASHCAN: {- return { ...state, useTrashCan: action.useTrashCan };- }- case types.SET_PERSISTTAGSINSIDECARFILE: {- return { ...state, persistTagsInSidecarFile: action.persistTagsInSidecarFile };- }- case types.SET_ADDTAGSTOLIBRARY: {- return { ...state, addTagsToLibrary: action.addTagsToLibrary };- }- case types.SET_USEGENERATETHUMBNAILS: {- return { ...state, useGenerateThumbnails: action.useGenerateThumbnails };- }- case types.SET_USETEXTEXTRACTION: {- return { ...state, useTextExtraction: action.useTextExtraction };- }- case types.SET_EMAIL: {- return {- ...state,- isLoading: true,- email: action.email- };- }- case types.SET_TAGCOLOR: {- return { ...state, tagBackgroundColor: action.tagColor };- }- case types.SET_TAGTEXTCOLOR: {- return { ...state, tagTextColor: action.tagTextColor };- }- case types.SET_CURRENTTHEME: {- return { ...state, currentTheme: action.currentTheme };- }- case types.SWITCH_THEME: {- let currentTheme = 'dark';- if (state.currentTheme === 'dark') {- currentTheme = 'light';- }- return { ...state, currentTheme };- }- case types.SET_KEYBINDING: {- let indexForEditing = -1;- state.keyBindings.map((kb, index) => {- if (kb.name === action.keyBindingName) {- indexForEditing = index;- }- return true;- });- if (indexForEditing >= 0) {+ case types.UPGRADE_SETTINGS: {+ const mergedKeyBindings = defaultSettings.keyBindings.map(x =>+ Object.assign(+ x,+ state.keyBindings.find(y => y.name === x.name)+ )+ );+ const mergedFileTypes = defaultSettings.supportedFileTypes.map(x =>+ Object.assign(+ x,+ state.supportedFileTypes.find(y => y.type === x.type)+ )+ );+ const combinedFileTypes = state.supportedFileTypes.map(x =>+ Object.assign(+ x,+ mergedFileTypes.find(y => y.type === x.type)+ )+ );return {+ ...defaultSettings,...state,+ currentTheme: window.ExtTheme || state.currentTheme,+ supportedThemes: defaultSettings.supportedThemes, // taking always the themes from default settings+ supportedLanguages: defaultSettings.supportedLanguages, // taking always the languages from default settingskeyBindings: [- ...state.keyBindings.slice(0, indexForEditing),- { name: action.keyBindingName, command: action.keyBindingCommand },- ...state.keyBindings.slice(indexForEditing + 1)+ // ...defaultSettings.keyBindings, // use to reset to the default key bindings+ ...mergedKeyBindings+ ],+ supportedFileTypes: [+ // ...defaultSettings.supportedFileTypes, // use to reset to the default file types+ ...combinedFileTypes]};}- return state;- }- case types.SET_GLOBAL_KEYBINDING: {- return { ...state, enableGlobalKeyboardShortcuts: action.enableGlobalKeyboardShortcuts };- }- case types.SET_ZOOM_RESET: {- PlatformIO.setZoomFactorElectron(1);- return { ...state, zoomFactor: 1 };- }- case types.SET_ZOOM_RESTORE: {- PlatformIO.setZoomFactorElectron(state.zoomFactor);- return state;- }- case types.SET_ZOOM_IN: {- let zoomLevel = state.zoomFactor;- const offSet = 0.1;- if (zoomLevel.toPrecision(2) <= zoomLevel + (offSet * 4)) {- zoomLevel += offSet;- PlatformIO.setZoomFactorElectron(zoomLevel);- }- return { ...state, zoomFactor: zoomLevel };- }- case types.SET_ZOOM_OUT: {- let zoomLevel = state.zoomFactor;- const offSet = 0.1;- if (zoomLevel.toPrecision(2) > (offSet * 4)) {- zoomLevel -= offSet;- PlatformIO.setZoomFactorElectron(zoomLevel);- }- return { ...state, zoomFactor: zoomLevel };- }- case types.SET_SUPPORTED_FILE_TYPES: {- return {- ...state,- supportedFileTypes: action.supportedFileTypes- };- }- case types.SET_ENTRY_PROPERTIES_SPLIT_SIZE: {- return {- ...state,- entryPropertiesSplitSize: action.entryPropertiesSplitSize- };- }- case types.SET_MAIN_VSPLIT_SIZE: {- return {- ...state,- mainVerticalSplitSize: action.mainVerticalSplitSize- };- }- case types.SET_LEFT_VSPLIT_SIZE: {- return {- ...state,- leftVerticalSplitSize: action.leftVerticalSplitSize- };- }- case types.SET_LAST_PUBLISHED_VERSION: {- return {- ...state,- lastPublishedVersion: action.lastPublishedVersion- };- }- default: {- return state;- }+ case types.TOGGLE_SHOWUNIXHIDDENENTRIES: {+ return { ...state, showUnixHiddenEntries: !state.showUnixHiddenEntries };+ }+ case types.SET_TAG_DELIMITER: {+ return { ...state, tagDelimiter: action.delimiter };+ }+ case types.SET_MAX_SEARCH_RESULT: {+ return { ...state, maxSearchResult: action.maxSearchResult };+ }+ case types.SET_DESKTOPMODE: {+ return { ...state, desktopMode: action.desktopMode };+ }+ case types.SET_CHECKFORUPDATES: {+ return { ...state, checkForUpdates: action.checkForUpdates };+ }+ case types.SET_USEDEFAULTLOCATION: {+ return { ...state, useDefaultLocation: action.useDefaultLocation };+ }+ case types.SET_COLOREDFILEEXTENSION: {+ return { ...state, coloredFileExtension: action.coloredFileExtension };+ }+ case types.SET_SHOWTAGAREAONSTARTUP: {+ return { ...state, showTagAreaOnStartup: action.showTagAreaOnStartup };+ }+ case types.SET_LOADSLOCATIONMETADATA: {+ return { ...state, loadsLocationMetaData: action.loadsLocationMetaData };+ }+ case types.SET_SEARCHINSUBFOLDERS: {+ return { ...state, searchInSubfolders: action.searchInSubfolders };+ }+ case types.SET_WATCHCURRENTDIRECTORY: {+ return { ...state, watchCurrentDirectory: action.watchCurrentDirectory };+ }+ case types.SET_FIRST_RUN: {+ return { ...state, firstRun: action.firstRun };+ }+ case types.SET_LANGUAGE: {+ i18n.changeLanguage(action.language);+ return { ...state, interfaceLanguage: action.language };+ }+ case types.SET_APPDATAPATH: {+ return { ...state, appDataPath: action.path };+ }+ case types.SET_CONTENTHASH: {+ return { ...state, contentHash: action.contentHash };+ }+ case types.SET_UPDATEAVAILABLE: {+ return { ...state, isUpdateAvailable: action.isUpdateAvailable };+ }+ case types.SET_UPDATEINPROGRESS: {+ return { ...state, isUpdateInProgress: action.isUpdateInProgress };+ }+ case types.SET_CALCULATETAGS: {+ return { ...state, calculateTags: action.calculateTags };+ }+ case types.SET_USETRASHCAN: {+ return { ...state, useTrashCan: action.useTrashCan };+ }+ case types.SET_PERSISTTAGSINSIDECARFILE: {+ return {+ ...state,+ persistTagsInSidecarFile: action.persistTagsInSidecarFile+ };+ }+ case types.SET_ADDTAGSTOLIBRARY: {+ return { ...state, addTagsToLibrary: action.addTagsToLibrary };+ }+ case types.SET_USEGENERATETHUMBNAILS: {+ return { ...state, useGenerateThumbnails: action.useGenerateThumbnails };+ }+ case types.SET_USETEXTEXTRACTION: {+ return { ...state, useTextExtraction: action.useTextExtraction };+ }+ case types.SET_EMAIL: {+ return {+ ...state,+ isLoading: true,+ email: action.email+ };+ }+ case types.SET_TAGCOLOR: {+ return { ...state, tagBackgroundColor: action.tagColor };+ }+ case types.SET_TAGTEXTCOLOR: {+ return { ...state, tagTextColor: action.tagTextColor };+ }+ case types.SET_CURRENTTHEME: {+ return { ...state, currentTheme: action.currentTheme };+ }+ case types.SWITCH_THEME: {+ let currentTheme = 'dark';+ if (state.currentTheme === 'dark') {+ currentTheme = 'light';+ }+ return { ...state, currentTheme };+ }+ case types.SET_KEYBINDING: {+ let indexForEditing = -1;+ state.keyBindings.map((kb, index) => {+ if (kb.name === action.keyBindingName) {+ indexForEditing = index;+ }+ return true;+ });+ if (indexForEditing >= 0) {+ return {+ ...state,+ keyBindings: [+ ...state.keyBindings.slice(0, indexForEditing),+ { name: action.keyBindingName, command: action.keyBindingCommand },+ ...state.keyBindings.slice(indexForEditing + 1)+ ]+ };+ }+ return state;+ }+ case types.SET_GLOBAL_KEYBINDING: {+ return {+ ...state,+ enableGlobalKeyboardShortcuts: action.enableGlobalKeyboardShortcuts+ };+ }+ case types.SET_ZOOM_RESET: {+ PlatformIO.setZoomFactorElectron(1);+ return { ...state, zoomFactor: 1 };+ }+ case types.SET_ZOOM_RESTORE: {+ PlatformIO.setZoomFactorElectron(state.zoomFactor);+ return state;+ }+ case types.SET_ZOOM_IN: {+ let zoomLevel = state.zoomFactor;+ const offSet = 0.1;+ if (zoomLevel.toPrecision(2) <= zoomLevel + offSet * 4) {+ zoomLevel += offSet;+ PlatformIO.setZoomFactorElectron(zoomLevel);+ }+ return { ...state, zoomFactor: zoomLevel };+ }+ case types.SET_ZOOM_OUT: {+ let zoomLevel = state.zoomFactor;+ const offSet = 0.1;+ if (zoomLevel.toPrecision(2) > offSet * 4) {+ zoomLevel -= offSet;+ PlatformIO.setZoomFactorElectron(zoomLevel);+ }+ return { ...state, zoomFactor: zoomLevel };+ }+ case types.SET_SUPPORTED_FILE_TYPES: {+ return {+ ...state,+ supportedFileTypes: action.supportedFileTypes+ };+ }+ case types.SET_ENTRY_PROPERTIES_SPLIT_SIZE: {+ return {+ ...state,+ entryPropertiesSplitSize: action.entryPropertiesSplitSize+ };+ }+ case types.SET_MAIN_VSPLIT_SIZE: {+ return {+ ...state,+ mainVerticalSplitSize: action.mainVerticalSplitSize+ };+ }+ case types.SET_LEFT_VSPLIT_SIZE: {+ return {+ ...state,+ leftVerticalSplitSize: action.leftVerticalSplitSize+ };+ }+ case types.SET_LAST_PUBLISHED_VERSION: {+ return {+ ...state,+ lastPublishedVersion: action.lastPublishedVersion+ };+ }+ default: {+ return state;+ }}};export const actions = {- setTagDelimiter: (delimiter: string) => ({ type: types.SET_TAG_DELIMITER, delimiter }),- setMaxSearchResult: (maxSearchResult: number) => ({ type: types.SET_MAX_SEARCH_RESULT, maxSearchResult }),- setDesktopMode: (desktopMode: boolean) => ({ type: types.SET_DESKTOPMODE, desktopMode }),- toggleShowUnixHiddenEntries: () => ({ type: types.TOGGLE_SHOWUNIXHIDDENENTRIES }),- setCheckForUpdates: (checkForUpdates: boolean) => ({ type: types.SET_CHECKFORUPDATES, checkForUpdates }),+ setTagDelimiter: (delimiter: string) => ({+ type: types.SET_TAG_DELIMITER,+ delimiter+ }),+ setMaxSearchResult: (maxSearchResult: number) => ({+ type: types.SET_MAX_SEARCH_RESULT,+ maxSearchResult+ }),+ setDesktopMode: (desktopMode: boolean) => ({+ type: types.SET_DESKTOPMODE,+ desktopMode+ }),+ toggleShowUnixHiddenEntries: () => ({+ type: types.TOGGLE_SHOWUNIXHIDDENENTRIES+ }),+ setCheckForUpdates: (checkForUpdates: boolean) => ({+ type: types.SET_CHECKFORUPDATES,+ checkForUpdates+ }),setLanguage: (language: string) => ({ type: types.SET_LANGUAGE, language }),- setUseDefaultLocation: (useDefaultLocation: boolean) => ({ type: types.SET_USEDEFAULTLOCATION, useDefaultLocation }),+ setUseDefaultLocation: (useDefaultLocation: boolean) => ({+ type: types.SET_USEDEFAULTLOCATION,+ useDefaultLocation+ }),setColoredFileExtension: (coloredFileExtension: boolean) => ({type: types.SET_COLOREDFILEEXTENSION,coloredFileExtension@@ -289,13 +327,22 @@ export const actions = {type: types.SET_LOADSLOCATIONMETADATA,loadsLocationMetaData}),- setSearchInSubfolders: (searchInSubfolders: boolean) => ({ type: types.SET_SEARCHINSUBFOLDERS, searchInSubfolders }),+ setSearchInSubfolders: (searchInSubfolders: boolean) => ({+ type: types.SET_SEARCHINSUBFOLDERS,+ searchInSubfolders+ }),setWatchCurrentDirectory: (watchCurrentDirectory: boolean) => ({type: types.SET_WATCHCURRENTDIRECTORY,watchCurrentDirectory}),- setCalculateTags: (calculateTags: boolean) => ({ type: types.SET_CALCULATETAGS, calculateTags }),- setUseTrashCan: (useTrashCan: boolean) => ({ type: types.SET_USETRASHCAN, useTrashCan }),+ setCalculateTags: (calculateTags: boolean) => ({+ type: types.SET_CALCULATETAGS,+ calculateTags+ }),+ setUseTrashCan: (useTrashCan: boolean) => ({+ type: types.SET_USETRASHCAN,+ useTrashCan+ }),setPersistTagsInSidecarFile: (persistTagsInSidecarFile: boolean) => ({type: types.SET_PERSISTTAGSINSIDECARFILE,persistTagsInSidecarFile@@ -308,17 +355,29 @@ export const actions = {type: types.SET_USEGENERATETHUMBNAILS,useGenerateThumbnails}),- setUseTextExtraction: (useTextExtraction: boolean) => ({ type: types.SET_USETEXTEXTRACTION, useTextExtraction }),+ setUseTextExtraction: (useTextExtraction: boolean) => ({+ type: types.SET_USETEXTEXTRACTION,+ useTextExtraction+ }),setAppDataPath: (path: string) => ({ type: types.SET_APPDATAPATH, path }),- setContentHash: (contentHash: string) => ({ type: types.SET_CONTENTHASH, contentHash }),+ setContentHash: (contentHash: string) => ({+ type: types.SET_CONTENTHASH,+ contentHash+ }),setEmail: (email: string) => ({ type: types.SET_EMAIL, email }),setZoomRestoreApp: () => ({ type: types.SET_ZOOM_RESTORE }),setZoomResetApp: () => ({ type: types.SET_ZOOM_RESET }),setZoomInApp: () => ({ type: types.SET_ZOOM_IN }),setZoomOutApp: () => ({ type: types.SET_ZOOM_OUT }),setTagColor: (tagColor: string) => ({ type: types.SET_TAGCOLOR, tagColor }),- setTagTextColor: (tagTextColor: string) => ({ type: types.SET_TAGTEXTCOLOR, tagTextColor }),- setCurrentTheme: (currentTheme: string) => ({ type: types.SET_CURRENTTHEME, currentTheme }),+ setTagTextColor: (tagTextColor: string) => ({+ type: types.SET_TAGTEXTCOLOR,+ tagTextColor+ }),+ setCurrentTheme: (currentTheme: string) => ({+ type: types.SET_CURRENTTHEME,+ currentTheme+ }),switchTheme: () => ({ type: types.SWITCH_THEME }),setKeyBinding: (keyBindingName: string, keyBindingCommand: string) => ({type: types.SET_KEYBINDING,@@ -361,33 +420,37 @@ export const actions = {getState: () => Object) => {const { settings } = getState();- getLastVersionPromise().then((lastVersion) => {- console.log('Last version on server: ' + lastVersion);- const newVersion = semver.coerce(lastVersion); // lastVersion '3.0.5' ;- const currentVersion = semver.coerce(versionMeta.version);- // const lastPublishedVersion = semver.coerce(settings.lastPublishedVersion);- if (semver.valid(newVersion) && semver.gt(newVersion, currentVersion)) {- console.log('New version available: ' + newVersion.version + '!');- dispatch(actions.setLastPublishedVersion(newVersion.version));- // if (semver.gt(newVersion, lastPublishedVersion)) {- dispatch(AppActions.setUpdateAvailable(true));- // }- } else {- console.log('Current version: ' + versionMeta.version + ' is up to date');- }- return true;- })+ getLastVersionPromise()+ .then(lastVersion => {+ console.log('Last version on server: ' + lastVersion);+ const newVersion = semver.coerce(lastVersion); // lastVersion '3.0.5' ;+ const currentVersion = semver.coerce(versionMeta.version);+ // const lastPublishedVersion = semver.coerce(settings.lastPublishedVersion);+ if (semver.valid(newVersion) && semver.gt(newVersion, currentVersion)) {+ console.log('New version available: ' + newVersion.version + '!');+ dispatch(actions.setLastPublishedVersion(newVersion.version));+ // if (semver.gt(newVersion, lastPublishedVersion)) {+ dispatch(AppActions.setUpdateAvailable(true));+ // }+ } else {+ console.log(+ 'Current version: ' + versionMeta.version + ' is up to date'+ );+ }+ return true;+ }).catch(error => {console.warn('Error while checking for update: ' + error);});- },+ }};export function getLastVersionPromise(): Promise<string> {return new Promise((resolve, reject) => {console.log('Checking for new version...');const xhr = new XMLHttpRequest();- const updateUrl = AppConfig.links.checkNewVersionURL + '?cv=' + versionMeta.version;+ const updateUrl =+ AppConfig.links.checkNewVersionURL + '?cv=' + versionMeta.version;xhr.open('GET', updateUrl, true);xhr.responseType = 'json';xhr.onerror = reject;@@ -411,37 +474,58 @@ export const getDesktopMode = (state: Object) => {if (typeof window.ExtDisplayMode === 'undefined') {return state.settings.desktopMode;}- return (window.ExtDisplayMode !== 'mobile');+ return window.ExtDisplayMode !== 'mobile';};-export const getCheckForUpdateOnStartup = (state: Object) => state.settings.checkForUpdates;-export const getLastPublishedVersion = (state: Object) => state.settings.lastPublishedVersion;-export const getShowUnixHiddenEntries = (state: Object) => state.settings.showUnixHiddenEntries;-export const getUseDefaultLocation = (state: Object) => state.settings.useDefaultLocation;-export const getColoredFileExtension = (state: Object) => state.settings.coloredFileExtension;-export const getShowTagAreaOnStartup = (state: Object) => state.settings.showTagAreaOnStartup;-export const getLoadsLocationMetaData = (state: Object) => state.settings.loadsLocationMetaData;-export const getSearchInSubfolders = (state: Object) => state.settings.searchInSubfolders;-export const getWatchCurrentDirectory = (state: Object) => state.settings.watchCurrentDirectory;-export const getCurrentLanguage = (state: Object) => state.settings.interfaceLanguage;+export const getCheckForUpdateOnStartup = (state: Object) =>+ state.settings.checkForUpdates;+export const getLastPublishedVersion = (state: Object) =>+ state.settings.lastPublishedVersion;+export const getShowUnixHiddenEntries = (state: Object) =>+ state.settings.showUnixHiddenEntries;+export const getUseDefaultLocation = (state: Object) =>+ state.settings.useDefaultLocation;+export const getColoredFileExtension = (state: Object) =>+ state.settings.coloredFileExtension;+export const getShowTagAreaOnStartup = (state: Object) =>+ state.settings.showTagAreaOnStartup;+export const getLoadsLocationMetaData = (state: Object) =>+ state.settings.loadsLocationMetaData;+export const getSearchInSubfolders = (state: Object) =>+ state.settings.searchInSubfolders;+export const getWatchCurrentDirectory = (state: Object) =>+ state.settings.watchCurrentDirectory;+export const getCurrentLanguage = (state: Object) =>+ state.settings.interfaceLanguage;export const getAppDataPath = (state: Object) => state.settings.appDataPath;-export const getSupportedLanguages = (state: Object) => state.settings.languages;+export const getSupportedLanguages = (state: Object) =>+ state.settings.languages;export const getCalculateTags = (state: Object) => state.settings.calculateTags;export const getUseTrashCan = (state: Object) => state.settings.useTrashCan;-export const getPersistTagsInSidecarFile = (state: Object) => state.settings.persistTagsInSidecarFile;-export const getUseGenerateThumbnails = (state: Object) => state.settings.useGenerateThumbnails;-export const getUseTextExtraction = (state: Object) => state.settings.useTextExtraction;+export const getPersistTagsInSidecarFile = (state: Object) =>+ state.settings.persistTagsInSidecarFile;+export const getUseGenerateThumbnails = (state: Object) =>+ state.settings.useGenerateThumbnails;+export const getUseTextExtraction = (state: Object) =>+ state.settings.useTextExtraction;export const getKeyBindings = (state: Object) => state.settings.keyBindings;-export const getKeyBindingObject = (state: Object) => generateKeyBindingObject(state.settings.keyBindings);-export const getSupportedFileTypes = (state: Object) => state.settings.supportedFileTypes;-export const getPerspectives = (state: Object) => state.settings.supportedPerspectives;+export const getKeyBindingObject = (state: Object) =>+ generateKeyBindingObject(state.settings.keyBindings);+export const getSupportedFileTypes = (state: Object) =>+ state.settings.supportedFileTypes;+export const getPerspectives = (state: Object) =>+ state.settings.supportedPerspectives;export const getTagColor = (state: Object) => state.settings.tagBackgroundColor;export const getTagTextColor = (state: Object) => state.settings.tagTextColor;export const getCurrentTheme = (state: Object) => state.settings.currentTheme;-export const isGlobalKeyBindingEnabled = (state: Object) => state.settings.enableGlobalKeyboardShortcuts;-export const getLeftVerticalSplitSize = (state: Object) => state.settings.leftVerticalSplitSize;-export const getMainVerticalSplitSize = (state: Object) => state.settings.mainVerticalSplitSize;+export const isGlobalKeyBindingEnabled = (state: Object) =>+ state.settings.enableGlobalKeyboardShortcuts;+export const getLeftVerticalSplitSize = (state: Object) =>+ state.settings.leftVerticalSplitSize;+export const getMainVerticalSplitSize = (state: Object) =>+ state.settings.mainVerticalSplitSize;export const getTagDelimiter = (state: Object) => state.settings.tagDelimiter;-export const getMaxSearchResults = (state: Object) => state.settings.maxSearchResult;+export const getMaxSearchResults = (state: Object) =>+ state.settings.maxSearchResult;export const isFirstRun = (state: Object) => {if (typeof window.ExtIsFirstRun === 'undefined') {return state.settings.firstRun;@@ -451,7 +535,7 @@ export const isFirstRun = (state: Object) => {function generateKeyBindingObject(keyBindings: Array<Object>) {const kbObject = {};- keyBindings.map((kb) => {+ keyBindings.map(kb => {kbObject[kb.name] = kb.command;return true;});diff --git a/app/reducers/smart-tags.js b/app/reducers/smart-tags.jsindex 040f1b73c..f46b237bf 100644--- a/app/reducers/smart-tags.js+++ b/app/reducers/smart-tags.js@@ -1,4 +1,4 @@-export default (i18n) => ([+export default i18n => [{title: i18n.t('core:smartTags'),uuid: 'd4b5c16a-1c3a-4561-96c7-686696cb2004',@@ -16,7 +16,7 @@ export default (i18n) => ([description: i18n.t('core:smartTagNowDescription'),color: '#4986e7',textcolor: '#ffffff',- icon: '',+ icon: ''},{id: '7505080c-b974-425f-8434-25cd08fb1013',@@ -26,7 +26,7 @@ export default (i18n) => ([description: i18n.t('core:smartTagTodayDescription'),color: '#4986e7',textcolor: '#ffffff',- icon: '',+ icon: ''},{id: '841e55a0-3596-4417-9186-d035cbcb676c',@@ -36,7 +36,7 @@ export default (i18n) => ([description: i18n.t('core:smartTagTomorrowDescription'),color: '#4986e7',textcolor: '#ffffff',- icon: '',+ icon: ''},{id: '3bf2bde9-cfa1-41cc-9154-debbf853e74c',@@ -46,7 +46,7 @@ export default (i18n) => ([description: i18n.t('core:smartTagYesterdayDescription'),color: '#4986e7',textcolor: '#ffffff',- icon: '',+ icon: ''},{id: 'e4618609-0940-4d78-b79f-7d4221df33e2',@@ -56,7 +56,7 @@ export default (i18n) => ([description: i18n.t('core:smartTagMonthDescription'),color: '#4986e7',textcolor: '#ffffff',- icon: '',+ icon: ''},{id: 'b6d6c107-741e-423b-82a4-f00ae394dee4',@@ -66,17 +66,17 @@ export default (i18n) => ([description: i18n.t('core:smartTagYearDescription'),color: '#4986e7',textcolor: '#ffffff',- icon: '',+ icon: ''},{id: 'da9fd0e6-7921-4195-b8f9-dca80f132bab',type: 'plain',- title: '📍 '+ i18n.t('core:smartTagGeo'),+ title: '📍 ' + i18n.t('core:smartTagGeo'),functionality: 'geoTagging',description: i18n.t('core:smartTagGeoDescription'),color: '#4986e7',textcolor: '#ffffff',- icon: '',+ icon: ''},{id: '67678ddd-4979-4489-8d2d-69a964af6b0d',@@ -86,8 +86,8 @@ export default (i18n) => ([description: i18n.t('core:smartTagDateDescription'),color: '#4986e7',textcolor: '#ffffff',- icon: '',+ icon: ''}]}-]);+];diff --git a/app/reducers/tagging-actions.js b/app/reducers/tagging-actions.jsindex 0877821e3..1c96829d0 100644--- a/app/reducers/tagging-actions.js+++ b/app/reducers/tagging-actions.js@@ -20,18 +20,22 @@import uuidv1 from 'uuid';import i18n from '../services/i18n';import { actions as AppActions } from './app';-import { actions as TagLibraryActions, type Tag, type TagGroup } from './taglibrary';+import {+ actions as TagLibraryActions,+ type Tag,+ type TagGroup+} from './taglibrary';import {extractFileExtension,extractFileName,extractTags,extractTitle,- extractContainingDirectoryPath,+ extractContainingDirectoryPath} from '../utils/paths';import {loadMetaDataPromise,saveMetaDataPromise,- generateFileName,+ generateFileName} from '../services/utils-io';import { formatDateTime4Tag, isPlusCode } from '../utils/misc';import AppConfig from '../config';@@ -42,14 +46,15 @@ import ocl from '../utils/openlocationcode';export const defaultTagLocation = ocl.encode(51.48, 0); // default tag coordinate Greenwichconst actions = {- addTags: (paths: Array<string>, tags: Array<Tag>, updateIndex?: boolean = true) => (- dispatch: (actions: Object) => void,- getState: () => Object- ) => {+ addTags: (+ paths: Array<string>,+ tags: Array<Tag>,+ updateIndex?: boolean = true+ ) => (dispatch: (actions: Object) => void, getState: () => Object) => {const { settings, taglibrary } = getState();const processedTags = [];- tags.map((pTag) => {+ tags.map(pTag => {const tag = { ...pTag };tag.type = 'sidecar';if (tag.functionality && tag.functionality.length > 0) {@@ -64,7 +69,9 @@ const actions = {tag.title = defaultTagLocation;dispatch(AppActions.toggleEditTagDialog(tag));} else {- dispatch(AppActions.showNotification(i18n.t('core:needProVersion')));+ dispatch(+ AppActions.showNotification(i18n.t('core:needProVersion'))+ );}} else if (tag.functionality === 'dateTagging') {if (Pro) {@@ -73,7 +80,9 @@ const actions = {tag.title = formatDateTime4Tag(new Date(), true); // defaultTagDate;dispatch(AppActions.toggleEditTagDialog(tag));} else {- dispatch(AppActions.showNotification(i18n.t('core:needProVersion')));+ dispatch(+ AppActions.showNotification(i18n.t('core:needProVersion'))+ );}} else {tag.title = generateTagValue(tag);@@ -88,19 +97,23 @@ const actions = {});if (processedTags.length > 0) {- paths.map((path) => {+ paths.map(path => {dispatch(actions.addTagsToEntry(path, processedTags, updateIndex));return true;});- if (settings.addTagsToLibrary) { // collecting tags- // filter existed in tagLibrary+ if (settings.addTagsToLibrary) {+ // collecting tags+ // filter existed in tagLibraryconst uniqueTags = [];- processedTags.map((tag) => {+ processedTags.map(tag => {if (- taglibrary.findIndex(tagGroup => tagGroup.children.findIndex(obj => obj.id === tag.id) !== -1) === -1 &&- !/^(?:\d+~\d+|\d+)$/.test(tag.title) && // skip adding of tag containing only digits- !isPlusCode(tag.title) // skip adding of tag containing geo information+ taglibrary.findIndex(+ tagGroup =>+ tagGroup.children.findIndex(obj => obj.id === tag.id) !== -1+ ) === -1 &&+ !/^(?:\d+~\d+|\d+)$/.test(tag.title) && // skip adding of tag containing only digits+ !isPlusCode(tag.title) // skip adding of tag containing geo information) {uniqueTags.push(tag);}@@ -122,10 +135,11 @@ const actions = {}}},- addTagsToEntry: (path: string, tags: Array<Tag>, updateIndex?: boolean = true) => async (- dispatch: (actions: Object) => void,- getState: () => Object- ) => {+ addTagsToEntry: (+ path: string,+ tags: Array<Tag>,+ updateIndex?: boolean = true+ ) => async (dispatch: (actions: Object) => void, getState: () => Object) => {const { settings } = getState();const entryProperties = await PlatformIO.getPropertiesPromise(path);let fsEntryMeta;@@ -138,37 +152,63 @@ const actions = {if (!entryProperties.isFile || settings.persistTagsInSidecarFile) {// Handling adding tags in sidecarif (fsEntryMeta) {- const uniqueTags = getNonExistingTags(tags, extractTags(path, settings.tagDelimiter), fsEntryMeta.tags);+ const uniqueTags = getNonExistingTags(+ tags,+ extractTags(path, settings.tagDelimiter),+ fsEntryMeta.tags+ );if (uniqueTags.length > 0) {- const newTags = [- ...fsEntryMeta.tags,- ...uniqueTags- ];+ const newTags = [...fsEntryMeta.tags, ...uniqueTags];const updatedFsEntryMeta = {...fsEntryMeta,- tags: newTags,+ tags: newTags};- saveMetaDataPromise(path, updatedFsEntryMeta).then(() => {- dispatch(AppActions.reflectUpdateSidecarTags(path, newTags, updateIndex));- return true;- }).catch((err) => {- console.warn('Error adding tags for ' + path + ' with ' + err);- dispatch(AppActions.showNotification(i18n.t('core:addingTagsFailed'), 'error', true));- });+ saveMetaDataPromise(path, updatedFsEntryMeta)+ .then(() => {+ dispatch(+ AppActions.reflectUpdateSidecarTags(path, newTags, updateIndex)+ );+ return true;+ })+ .catch(err => {+ console.warn('Error adding tags for ' + path + ' with ' + err);+ dispatch(+ AppActions.showNotification(+ i18n.t('core:addingTagsFailed'),+ 'error',+ true+ )+ );+ });}} else {const newFsEntryMeta = { tags };- saveMetaDataPromise(path, newFsEntryMeta).then(() => {- dispatch(AppActions.reflectUpdateSidecarTags(path, tags, updateIndex));- return true;- }).catch(error => {- console.warn('Error adding tags for ' + path + ' with ' + error);- dispatch(AppActions.showNotification(i18n.t('core:addingTagsFailed'), 'error', true));- });+ saveMetaDataPromise(path, newFsEntryMeta)+ .then(() => {+ dispatch(+ AppActions.reflectUpdateSidecarTags(path, tags, updateIndex)+ );+ return true;+ })+ .catch(error => {+ console.warn('Error adding tags for ' + path + ' with ' + error);+ dispatch(+ AppActions.showNotification(+ i18n.t('core:addingTagsFailed'),+ 'error',+ true+ )+ );+ });}- } else if (fsEntryMeta) { // Handling tags in filename by existing sidecar+ } else if (fsEntryMeta) {+ // Handling tags in filename by existing sidecarconst extractedTags = extractTags(path, settings.tagDelimiter);- const uniqueTags = getNonExistingTags(tags, extractedTags, fsEntryMeta.tags);+ const uniqueTags = getNonExistingTags(+ tags,+ extractedTags,+ fsEntryMeta.tags+ );if (uniqueTags.length > 0) {const fileName = extractFileName(path);const containingDirectoryPath = extractContainingDirectoryPath(path);@@ -176,10 +216,14 @@ const actions = {for (let i = 0; i < uniqueTags.length; i += 1) {extractedTags.push(uniqueTags[i].title);}- const newFilePath = containingDirectoryPath + AppConfig.dirSeparator + generateFileName(fileName, extractedTags, settings.tagDelimiter);+ const newFilePath =+ containingDirectoryPath ++ AppConfig.dirSeparator ++ generateFileName(fileName, extractedTags, settings.tagDelimiter);dispatch(AppActions.renameFile(path, newFilePath));}- } else { // Handling tags in filename by no sidecar+ } else {+ // Handling tags in filename by no sidecarconst fileName = extractFileName(path);const containingDirectoryPath = extractContainingDirectoryPath(path);const extractedTags = extractTags(path);@@ -190,19 +234,30 @@ const actions = {extractedTags.push(tags[i].title);}}- const newFilePath = containingDirectoryPath + AppConfig.dirSeparator + generateFileName(fileName, extractedTags, settings.tagDelimiter);+ const newFilePath =+ containingDirectoryPath ++ AppConfig.dirSeparator ++ generateFileName(fileName, extractedTags, settings.tagDelimiter);if (path !== newFilePath) {dispatch(AppActions.renameFile(path, newFilePath));}}- function getNonExistingTags(newTagsArray: Array<Tag>, fileTagsArray: Array<string>, sideCarTagsArray: Array<Tag>) {+ function getNonExistingTags(+ newTagsArray: Array<Tag>,+ fileTagsArray: Array<string>,+ sideCarTagsArray: Array<Tag>+ ) {const newTags = [];for (let i = 0; i < newTagsArray.length; i += 1) {// check if tag is already in the fileTagsArrayif (fileTagsArray.indexOf(newTagsArray[i].title) === -1) {// check if tag is already in the sideCarTagsArray- if (sideCarTagsArray.findIndex(sideCarTag => sideCarTag.title === newTagsArray[i].title) === -1) {+ if (+ sideCarTagsArray.findIndex(+ sideCarTag => sideCarTag.title === newTagsArray[i].title+ ) === -1+ ) {newTags.push(newTagsArray[i]);}}@@ -222,7 +277,11 @@ const actions = {getState: () => Object) => {const { settings, taglibrary } = getState();- if (tag.functionality === 'geoTagging' || tag.functionality === 'dateTagging') { // Work around solution+ if (+ tag.functionality === 'geoTagging' ||+ tag.functionality === 'dateTagging'+ ) {+ // Work around solutiondelete tag.functionality;const entryProperties = await PlatformIO.getPropertiesPromise(path);if (entryProperties.isFile && !settings.persistTagsInSidecarFile) {@@ -245,66 +304,103 @@ const actions = {tagFound = true;}}- if (!tagFound) { // needed for the current implementation of geo tagging+ if (!tagFound) {+ // needed for the current implementation of geo taggingextractedTags.push(tag.title);}- const newFileName = generateFileName(fileName, extractedTags, settings.tagDelimiter);+ const newFileName = generateFileName(+ fileName,+ extractedTags,+ settings.tagDelimiter+ );if (newFileName !== fileName) {- dispatch(AppActions.renameFile(path, containingDirectoryPath + AppConfig.dirSeparator + newFileName));+ dispatch(+ AppActions.renameFile(+ path,+ containingDirectoryPath + AppConfig.dirSeparator + newFileName+ )+ );}} else if (tag.type === 'sidecar') {- loadMetaDataPromise(path).then(fsEntryMeta => {- let addMode = true;- fsEntryMeta.tags.map((sidecarTag) => {- if (sidecarTag.title === tag.title) {+ loadMetaDataPromise(path)+ .then(fsEntryMeta => {+ let addMode = true;+ fsEntryMeta.tags.map(sidecarTag => {+ if (sidecarTag.title === tag.title) {+ // eslint-disable-next-line no-param-reassign+ sidecarTag.title = newTagTitle;+ addMode = false;+ }+ return true;+ });+ if (addMode) {// eslint-disable-next-line no-param-reassign- sidecarTag.title = newTagTitle;- addMode = false;+ tag.title = newTagTitle;+ fsEntryMeta.tags.push(tag);}+ const updatedFsEntryMeta = {+ ...fsEntryMeta,+ tags: [...fsEntryMeta.tags]+ };+ saveMetaDataPromise(path, updatedFsEntryMeta)+ .then(() => {+ dispatch(+ AppActions.reflectUpdateSidecarTags(path, fsEntryMeta.tags)+ );+ return true;+ })+ .catch(err => {+ console.warn('Error adding tags for ' + path + ' with ' + err);+ dispatch(+ AppActions.showNotification(+ i18n.t('core:addingTagsFailed'),+ 'error',+ true+ )+ );+ });return true;- });- if (addMode) {+ })+ .catch(error => {+ // json metadata not exist -create the new one+ console.warn(+ 'json metadata not exist create new ' + path + ' with ' + error+ );+ // dispatch(AppActions.showNotification(i18n.t('core:addingTagsFailed'), 'error', true));// eslint-disable-next-line no-param-reassigntag.title = newTagTitle;- fsEntryMeta.tags.push(tag);- }- const updatedFsEntryMeta = {- ...fsEntryMeta,- tags: [- ...fsEntryMeta.tags,- ],- };- saveMetaDataPromise(path, updatedFsEntryMeta).then(() => {- dispatch(AppActions.reflectUpdateSidecarTags(path, fsEntryMeta.tags));- return true;- }).catch((err) => {- console.warn('Error adding tags for ' + path + ' with ' + err);- dispatch(AppActions.showNotification(i18n.t('core:addingTagsFailed'), 'error', true));+ const fsEntryMeta = { tags: [tag] };+ saveMetaDataPromise(path, fsEntryMeta)+ .then(() => {+ dispatch(+ AppActions.reflectUpdateSidecarTags(path, fsEntryMeta.tags)+ );+ return true;+ })+ .catch(err => {+ console.warn('Error adding tags for ' + path + ' with ' + err);+ dispatch(+ AppActions.showNotification(+ i18n.t('core:addingTagsFailed'),+ 'error',+ true+ )+ );+ });});- return true;- }).catch((error) => { // json metadata not exist -create the new one- console.warn('json metadata not exist create new ' + path + ' with ' + error);- // dispatch(AppActions.showNotification(i18n.t('core:addingTagsFailed'), 'error', true));- // eslint-disable-next-line no-param-reassign- tag.title = newTagTitle;- const fsEntryMeta = { tags: [tag] };- saveMetaDataPromise(path, fsEntryMeta).then(() => {- dispatch(AppActions.reflectUpdateSidecarTags(path, fsEntryMeta.tags));- return true;- }).catch((err) => {- console.warn('Error adding tags for ' + path + ' with ' + err);- dispatch(AppActions.showNotification(i18n.t('core:addingTagsFailed'), 'error', true));- });- });}- if (settings.addTagsToLibrary) { // collecting tags+ if (settings.addTagsToLibrary) {+ // collecting tags// filter existed in tagLibraryconst uniqueTags = [];if (- taglibrary.findIndex(tagGroup => tagGroup.children.findIndex(obj => obj.title === newTagTitle) !== -1) === -1 &&+ taglibrary.findIndex(+ tagGroup =>+ tagGroup.children.findIndex(obj => obj.title === newTagTitle) !== -1+ ) === -1 &&!/^(?:\d+~\d+|\d+)$/.test(newTagTitle) &&- !isPlusCode(newTagTitle)// skip adding of tag containing only digits or geo tags+ !isPlusCode(newTagTitle) // skip adding of tag containing only digits or geo tags) {uniqueTags.push({...tag,@@ -330,9 +426,9 @@ const actions = {}},removeTags: (paths: Array<string>, tags: Array<Tag>) => (- dispatch: (actions: Object) => void,+ dispatch: (actions: Object) => void) => {- paths.map((path) => {+ paths.map(path => {dispatch(actions.removeTagsFromEntry(path, tags));return true;});@@ -347,33 +443,45 @@ const actions = {tagTitlesForRemoving.push(tag.title);return true;});- loadMetaDataPromise(path).then(fsEntryMeta => {- const newTags = [];- fsEntryMeta.tags.map((sidecarTag) => {- if (!tagTitlesForRemoving.includes(sidecarTag.title)) {- newTags.push(sidecarTag); // adds only tags which are not in the tags for removing array- }- return true;- });- const updatedFsEntryMeta = {- ...fsEntryMeta,- tags: newTags,- };- saveMetaDataPromise(path, updatedFsEntryMeta).then(() => {- dispatch(AppActions.reflectUpdateSidecarTags(path, newTags));- removeTagsFromFilename();+ loadMetaDataPromise(path)+ .then(fsEntryMeta => {+ const newTags = [];+ fsEntryMeta.tags.map(sidecarTag => {+ if (!tagTitlesForRemoving.includes(sidecarTag.title)) {+ newTags.push(sidecarTag); // adds only tags which are not in the tags for removing array+ }+ return true;+ });+ const updatedFsEntryMeta = {+ ...fsEntryMeta,+ tags: newTags+ };+ saveMetaDataPromise(path, updatedFsEntryMeta)+ .then(() => {+ dispatch(AppActions.reflectUpdateSidecarTags(path, newTags));+ removeTagsFromFilename();+ return true;+ })+ .catch(err => {+ console.warn(+ 'Removing sidecar tags failed ' + path + ' with ' + err+ );+ dispatch(+ AppActions.showNotification(+ i18n.t('core:removingSidecarTagsFailed'),+ 'error',+ true+ )+ );+ removeTagsFromFilename();+ });return true;- }).catch((err) => {- console.warn('Removing sidecar tags failed ' + path + ' with ' + err);- dispatch(AppActions.showNotification(i18n.t('core:removingSidecarTagsFailed'), 'error', true));+ })+ .catch(error => {+ console.warn('Error removing tags for ' + path + ' with ' + error);+ // dispatch(AppActions.showNotification(i18n.t('core:removingSidecarTagsFailed'), 'error', true));removeTagsFromFilename();});- return true;- }).catch((error) => {- console.warn('Error removing tags for ' + path + ' with ' + error);- // dispatch(AppActions.showNotification(i18n.t('core:removingSidecarTagsFailed'), 'error', true));- removeTagsFromFilename();- });function removeTagsFromFilename() {const extractedTags = extractTags(path, settings.tagDelimiter);@@ -383,12 +491,17 @@ const actions = {for (let i = 0; i < tagTitlesForRemoving.length; i += 1) {const tagLoc = extractedTags.indexOf(tagTitlesForRemoving[i]);if (tagLoc < 0) {- console.log('The tag cannot be removed because it is not part of the file name.');+ console.log(+ 'The tag cannot be removed because it is not part of the file name.'+ );} else {extractedTags.splice(tagLoc, 1);}}- const newFilePath = containingDirectoryPath + AppConfig.dirSeparator + generateFileName(fileName, extractedTags, settings.tagDelimiter);+ const newFilePath =+ containingDirectoryPath ++ AppConfig.dirSeparator ++ generateFileName(fileName, extractedTags, settings.tagDelimiter);if (path !== newFilePath) {dispatch(AppActions.renameFile(path, newFilePath));}@@ -396,9 +509,9 @@ const actions = {}},removeAllTags: (paths: Array<string>) => (- dispatch: (actions: Object) => void,+ dispatch: (actions: Object) => void) => {- paths.map((path) => {+ paths.map(path => {dispatch(actions.removeAllTagsFromEntry(path));return true;});@@ -408,26 +521,38 @@ const actions = {getState: () => Object) => {const { settings } = getState();- loadMetaDataPromise(path).then(fsEntryMeta => {- const updatedFsEntryMeta = {- ...fsEntryMeta,- tags: [],- };- saveMetaDataPromise(path, updatedFsEntryMeta).then(() => {- dispatch(AppActions.reflectUpdateSidecarTags(path, []));- removeAllTagsFromFilename();+ loadMetaDataPromise(path)+ .then(fsEntryMeta => {+ const updatedFsEntryMeta = {+ ...fsEntryMeta,+ tags: []+ };+ saveMetaDataPromise(path, updatedFsEntryMeta)+ .then(() => {+ dispatch(AppActions.reflectUpdateSidecarTags(path, []));+ removeAllTagsFromFilename();+ return true;+ })+ .catch(err => {+ console.warn(+ 'Removing sidecar tags failed for ' + path + ' with ' + err+ );+ dispatch(+ AppActions.showNotification(+ i18n.t('core:removingTagsInSidecarFileFailed'),+ 'error',+ true+ )+ );+ removeAllTagsFromFilename();+ });return true;- }).catch((err) => {- console.warn('Removing sidecar tags failed for ' + path + ' with ' + err);- dispatch(AppActions.showNotification(i18n.t('core:removingTagsInSidecarFileFailed'), 'error', true));+ })+ .catch(error => {+ console.warn('Could not find meta file for ' + path + ' with ' + error);+ // dispatch(AppActions.showNotification('Adding tags failed', 'error', true));removeAllTagsFromFilename();});- return true;- }).catch((error) => {- console.warn('Could not find meta file for ' + path + ' with ' + error);- // dispatch(AppActions.showNotification('Adding tags failed', 'error', true));- removeAllTagsFromFilename();- });function removeAllTagsFromFilename() {// Tags in file name case, check is file@@ -439,15 +564,23 @@ const actions = {if (fileExt.length > 0) {fileExt = '.' + fileExt;}- const newFilePath = containingDirectoryPath + AppConfig.dirSeparator + fileTitle + fileExt;+ const newFilePath =+ containingDirectoryPath ++ AppConfig.dirSeparator ++ fileTitle ++ fileExt;dispatch(AppActions.renameFile(path, newFilePath));}}},- changeTagOrder: (path: string, tag: Tag, direction: 'prev' | 'next' | 'first') => (+ changeTagOrder: (+ path: string,+ tag: Tag,+ direction: 'prev' | 'next' | 'first'+ ) => () =>// dispatch: (actions: Object) => void- ) => {- /*+ {+ /*console.log('Moves the location of tag in the file name: ' + filePath);var fileName = extractFileName(filePath);var containingDirectoryPath = extractContainingDirectoryPath(filePath);@@ -480,28 +613,28 @@ const actions = {}var newFileName = generateFileName(fileName, extractedTags);renameFile(filePath, containingDirectoryPath + AppConfig.dirSeparator + newFileName); */- },+ },// smart tagging -> PRO- addDateTag: (paths: Array<string>) => (+ addDateTag: (paths: Array<string>) => () =>// dispatch: (actions: Object) => void- ) => {- // dispatch(actions.createLocation(location));- },- editDateTag: (path: string) => (+ {+ // dispatch(actions.createLocation(location));+ },+ editDateTag: (path: string) => () =>// dispatch: (actions: Object) => void- ) => {- // dispatch(actions.createLocation(location));- },- addGeoTag: (paths: Array<string>) => (+ {+ // dispatch(actions.createLocation(location));+ },+ addGeoTag: (paths: Array<string>) => () =>// dispatch: (actions: Object) => void- ) => {- // dispatch(actions.createLocation(location));- },- editGeoTag: (path: string) => (+ {+ // dispatch(actions.createLocation(location));+ },+ editGeoTag: (path: string) => () =>// dispatch: (actions: Object) => void- ) => {- // dispatch(actions.createLocation(location));- },+ {+ // dispatch(actions.createLocation(location));+ },collectTagsFromLocation: (tagGroup: TagGroup) => (dispatch: (actions: Object) => void,getState: () => Object@@ -509,16 +642,32 @@ const actions = {const { locationIndex, settings } = getState();if (!Pro || !Pro.Indexer || !Pro.Indexer.collectTagsFromIndex) {- dispatch(AppActions.showNotification(i18n.t('core:needProVersion'), 'error', true));+ dispatch(+ AppActions.showNotification(+ i18n.t('core:needProVersion'),+ 'error',+ true+ )+ );return true;}if (locationIndex.currentDirectoryIndex.length < 1) {- dispatch(AppActions.showNotification('Please index location first', 'error', true));+ dispatch(+ AppActions.showNotification(+ 'Please index location first',+ 'error',+ true+ )+ );return true;}- const uniqueTags = Pro.Indexer.collectTagsFromIndex(locationIndex, tagGroup, settings);+ const uniqueTags = Pro.Indexer.collectTagsFromIndex(+ locationIndex,+ tagGroup,+ settings+ );if (uniqueTags.length > 0) {const changedTagGroup = {...tagGroup,@@ -527,62 +676,62 @@ const actions = {};dispatch(TagLibraryActions.mergeTagGroup(changedTagGroup));}- },+ }};function handleSmartTag(smarttagFunction: string) {switch (smarttagFunction) {- case 'today':- message = data.title ? data.title : '';- if (data.message) {- message = message + ': ' + data.message;- }- this.props.showNotification(message, NotificationTypes.default);- break;- default:- console.log('Not recognized messaging command: ' + msg);- break;+ case 'today':+ message = data.title ? data.title : '';+ if (data.message) {+ message = message + ': ' + data.message;+ }+ this.props.showNotification(message, NotificationTypes.default);+ break;+ default:+ console.log('Not recognized messaging command: ' + msg);+ break;}}function generateTagValue(tag) {let tagTitle = tag.functionality;switch (tag.functionality) {- case 'today': {- tagTitle = formatDateTime4Tag(new Date(), false);- break;- }- case 'tomorrow': {- const d = new Date();- d.setDate(d.getDate() + 1);- tagTitle = formatDateTime4Tag(d, false);- break;- }- case 'yesterday': {- const d = new Date();- d.setDate(d.getDate() - 1);- tagTitle = formatDateTime4Tag(d, false);- break;- }- case 'currentMonth': {- let cMonth = '' + (new Date().getMonth() + 1);- if (cMonth.length === 1) {- cMonth = '0' + cMonth;+ case 'today': {+ tagTitle = formatDateTime4Tag(new Date(), false);+ break;+ }+ case 'tomorrow': {+ const d = new Date();+ d.setDate(d.getDate() + 1);+ tagTitle = formatDateTime4Tag(d, false);+ break;+ }+ case 'yesterday': {+ const d = new Date();+ d.setDate(d.getDate() - 1);+ tagTitle = formatDateTime4Tag(d, false);+ break;+ }+ case 'currentMonth': {+ let cMonth = '' + (new Date().getMonth() + 1);+ if (cMonth.length === 1) {+ cMonth = '0' + cMonth;+ }+ tagTitle = '' + new Date().getFullYear() + cMonth;+ break;+ }+ case 'currentYear': {+ tagTitle = '' + new Date().getFullYear();+ break;+ }+ case 'now': {+ tagTitle = formatDateTime4Tag(new Date(), true);+ break;+ }+ default: {+ break;}- tagTitle = '' + new Date().getFullYear() + cMonth;- break;- }- case 'currentYear': {- tagTitle = '' + new Date().getFullYear();- break;- }- case 'now': {- tagTitle = formatDateTime4Tag(new Date(), true);- break;- }- default: {- break;- }}return tagTitle;}diff --git a/app/reducers/taglibrary-default.js b/app/reducers/taglibrary-default.jsindex b4b8207e1..0e90e73d0 100644--- a/app/reducers/taglibrary-default.js+++ b/app/reducers/taglibrary-default.js@@ -41,28 +41,28 @@ export default [title: 'next',type: 'plain',color: '#008000',- textcolor: '#ffffff',+ textcolor: '#ffffff'},{id: uuidv1(),title: 'maybe',type: 'plain',color: '#008000',- textcolor: '#ffffff',+ textcolor: '#ffffff'},{id: uuidv1(),title: 'waiting',type: 'plain',color: '#008000',- textcolor: '#ffffff',+ textcolor: '#ffffff'},{id: uuidv1(),type: 'plain',title: 'todo',color: '#008000',- textcolor: '#ffffff',+ textcolor: '#ffffff'}]},@@ -78,21 +78,21 @@ export default [type: 'plain',title: 'book',color: '#008000',- textcolor: '#ffffff',+ textcolor: '#ffffff'},{id: uuidv1(),type: 'plain',title: 'paper',color: '#008000',- textcolor: '#ffffff',+ textcolor: '#ffffff'},{id: uuidv1(),type: 'plain',title: 'article',color: '#008000',- textcolor: '#ffffff',+ textcolor: '#ffffff'}]},@@ -109,21 +109,21 @@ export default [title: 'high',description: '',color: '#ff7537',- textcolor: '#ffffff',+ textcolor: '#ffffff'},{id: uuidv1(),type: 'plain',title: 'medium',color: '#ffad46',- textcolor: '#ffffff',+ textcolor: '#ffffff'},{id: uuidv1(),type: 'plain',title: 'low',color: '#7bd148',- textcolor: '#ffffff',+ textcolor: '#ffffff'}]},@@ -139,35 +139,35 @@ export default [type: 'plain',title: '1star',color: '#ffcc24',- textcolor: '#ffffff',+ textcolor: '#ffffff'},{id: uuidv1(),type: 'plain',title: '2star',color: '#ffcc24',- textcolor: '#ffffff',+ textcolor: '#ffffff'},{id: uuidv1(),type: 'plain',title: '3star',color: '#ffcc24',- textcolor: '#ffffff',+ textcolor: '#ffffff'},{id: uuidv1(),type: 'plain',title: '4star',color: '#ffcc24',- textcolor: '#ffffff',+ textcolor: '#ffffff'},{id: uuidv1(),type: 'plain',title: '5star',color: '#ffcc24',- textcolor: '#ffffff',+ textcolor: '#ffffff'}]}diff --git a/app/reducers/taglibrary.js b/app/reducers/taglibrary.jsindex 0af4bf1a9..2bdd8db2e 100644--- a/app/reducers/taglibrary.js+++ b/app/reducers/taglibrary.js@@ -40,7 +40,7 @@ export const types = {MOVE_TAG_GROUP_UP: 'MOVE_TAG_GROUP_UP',MOVE_TAG_GROUP_DOWN: 'MOVE_TAG_GROUP_DOWN',EDIT_TAG_COLOR: 'EDIT_TAG_COLOR',- MOVE_TAG: 'MOVE_TAG',+ MOVE_TAG: 'MOVE_TAG'};export type Uuid = string;@@ -72,366 +72,417 @@ export type TagGroup = {export default (state: Array<TagGroup> = defaultTagLibrary, action: Object) => {switch (action.type) {- case types.CREATE_TAGGROUP: {- return [...state, {- uuid: uuidv1(),- title: action.entry.title,- expanded: action.entry.expanded,- color: action.entry.color,- textcolor: action.entry.textcolor,- children: [],- created_date: new Date(),- modified_date: new Date()- }- ];- }- case types.ADD_TAGGROUP: {- let indexForEditing = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.entry.uuid) {- indexForEditing = index;- }- });- if (indexForEditing >= 0) {+ case types.CREATE_TAGGROUP: {return [- ...state.slice(0, indexForEditing),+ ...state,{- uuid: action.entry.uuid,+ uuid: uuidv1(),title: action.entry.title,expanded: action.entry.expanded,- children: [...state[indexForEditing].children, action.entry.children[0]],+ color: action.entry.color,+ textcolor: action.entry.textcolor,+ children: [],created_date: new Date(),modified_date: new Date()- },- ...state.slice(indexForEditing + 1)+ }];}- return state;- }- case types.MERGE_TAGGROUP: {- const indexForEditing = state.findIndex(obj => obj.uuid === action.entry.uuid);- if (indexForEditing >= 0) {- const tags = [...state[indexForEditing].children, ...action.entry.children];- tags.splice(0, tags.length - AppConfig.maxCollectedTag);+ case types.ADD_TAGGROUP: {+ let indexForEditing = -1;+ state.forEach((tagGroup, index) => {+ if (tagGroup.uuid === action.entry.uuid) {+ indexForEditing = index;+ }+ });+ if (indexForEditing >= 0) {+ return [+ ...state.slice(0, indexForEditing),+ {+ uuid: action.entry.uuid,+ title: action.entry.title,+ expanded: action.entry.expanded,+ children: [+ ...state[indexForEditing].children,+ action.entry.children[0]+ ],+ created_date: new Date(),+ modified_date: new Date()+ },+ ...state.slice(indexForEditing + 1)+ ];+ }+ return state;+ }+ case types.MERGE_TAGGROUP: {+ const indexForEditing = state.findIndex(+ obj => obj.uuid === action.entry.uuid+ );+ if (indexForEditing >= 0) {+ const tags = [+ ...state[indexForEditing].children,+ ...action.entry.children+ ];+ tags.splice(0, tags.length - AppConfig.maxCollectedTag);+ return [+ ...state.slice(0, indexForEditing),+ {+ uuid: action.entry.uuid,+ title: action.entry.title,+ expanded: action.entry.expanded,+ children: tags,+ created_date: action.entry.created_date,+ modified_date: new Date()+ },+ ...state.slice(indexForEditing + 1)+ ];+ }return [- ...state.slice(0, indexForEditing),+ ...state,{- uuid: action.entry.uuid,+ uuid: action.entry.uuid || uuidv1(),title: action.entry.title,expanded: action.entry.expanded,- children: tags,- created_date: action.entry.created_date,+ color: action.entry.color,+ textcolor: action.entry.textcolor,+ children: action.entry.children,+ created_date: new Date(),modified_date: new Date()- },- ...state.slice(indexForEditing + 1)+ }];}- return [...state, {- uuid: action.entry.uuid || uuidv1(),- title: action.entry.title,- expanded: action.entry.expanded,- color: action.entry.color,- textcolor: action.entry.textcolor,- children: action.entry.children,- created_date: new Date(),- modified_date: new Date()- }- ];- }- case types.UPDATE_TAGGROUP: {- let indexForEditing = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.entry.uuid) {- indexForEditing = index;- }- });+ case types.UPDATE_TAGGROUP: {+ let indexForEditing = -1;+ state.forEach((tagGroup, index) => {+ if (tagGroup.uuid === action.entry.uuid) {+ indexForEditing = index;+ }+ });- if (indexForEditing >= 0) {- const modifiedEntry = extend({ created_date: new Date() }, action.entry, { modified_date: new Date() });- return [- ...state.slice(0, indexForEditing),- modifiedEntry,- ...state.slice(indexForEditing + 1)- ];- }- return state;- }- case types.REMOVE_TAGGROUP: {- let indexForRemoving = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.uuid) {- indexForRemoving = index;+ if (indexForEditing >= 0) {+ const modifiedEntry = extend(+ { created_date: new Date() },+ action.entry,+ { modified_date: new Date() }+ );+ return [+ ...state.slice(0, indexForEditing),+ modifiedEntry,+ ...state.slice(indexForEditing + 1)+ ];}- });- if (indexForRemoving >= 0) {- return [- ...state.slice(0, indexForRemoving),- ...state.slice(indexForRemoving + 1)- ];+ return state;}- return state;- }- case types.ADD_TAG: {- let indexForEditing = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.uuid) {- indexForEditing = index;+ case types.REMOVE_TAGGROUP: {+ let indexForRemoving = -1;+ state.forEach((tagGroup, index) => {+ if (tagGroup.uuid === action.uuid) {+ indexForRemoving = index;+ }+ });+ if (indexForRemoving >= 0) {+ return [+ ...state.slice(0, indexForRemoving),+ ...state.slice(indexForRemoving + 1)+ ];}- });+ return state;+ }+ case types.ADD_TAG: {+ let indexForEditing = -1;+ state.forEach((tagGroup, index) => {+ if (tagGroup.uuid === action.uuid) {+ indexForEditing = index;+ }+ });- if (indexForEditing >= 0) {- let tags = action.tag.split(' ').join(',').split(','); // handle spaces around commas- tags = [...new Set(tags)]; // remove duplicates- tags = tags.filter(tag => tag.length > 0); // zero length tags+ if (indexForEditing >= 0) {+ let tags = action.tag+ .split(' ')+ .join(',')+ .split(','); // handle spaces around commas+ tags = [...new Set(tags)]; // remove duplicates+ tags = tags.filter(tag => tag.length > 0); // zero length tags- const taggroupTags = state[indexForEditing].children;- taggroupTags.forEach(tag => { // filter out duplicated tags- tags = tags.filter(e => e !== tag.title);- });- return [- ...state.slice(0, indexForEditing),- {- ...state[indexForEditing],- children: taggroupTags.concat(tags.map(tagTitle => ({- id: uuidv1(),- type: taggroupTags.length > 0 ? taggroupTags[0].type : 'sidecar',- title: tagTitle.trim(),- functionality: '',- description: '',- icon: '',- color: state[indexForEditing].color ? state[indexForEditing].color : '', // default color- textcolor: state[indexForEditing].textcolor ? state[indexForEditing].textcolor : '', // default color- style: taggroupTags.length > 0 ? taggroupTags[0].style : '',- created_date: new Date(),- modified_date: new Date()- })))- },- ...state.slice(indexForEditing + 1)- ];- }- return state;- }- case types.UPDATE_TAG: {- let tagIndexForUpdating = -1;- let indexForUpdating = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.uuid) {- indexForUpdating = index;+ const taggroupTags = state[indexForEditing].children;+ taggroupTags.forEach(tag => {+ // filter out duplicated tags+ tags = tags.filter(e => e !== tag.title);+ });+ return [+ ...state.slice(0, indexForEditing),+ {+ ...state[indexForEditing],+ children: taggroupTags.concat(+ tags.map(tagTitle => ({+ id: uuidv1(),+ type:+ taggroupTags.length > 0 ? taggroupTags[0].type : 'sidecar',+ title: tagTitle.trim(),+ functionality: '',+ description: '',+ icon: '',+ color: state[indexForEditing].color+ ? state[indexForEditing].color+ : '', // default color+ textcolor: state[indexForEditing].textcolor+ ? state[indexForEditing].textcolor+ : '', // default color+ style: taggroupTags.length > 0 ? taggroupTags[0].style : '',+ created_date: new Date(),+ modified_date: new Date()+ }))+ )+ },+ ...state.slice(indexForEditing + 1)+ ];}- tagGroup.children.forEach((tag, tagIndex) => {- if (tag.id === action.entry.id) {- tagIndexForUpdating = tagIndex;+ return state;+ }+ case types.UPDATE_TAG: {+ let tagIndexForUpdating = -1;+ let indexForUpdating = -1;+ state.forEach((tagGroup, index) => {+ if (tagGroup.uuid === action.uuid) {+ indexForUpdating = index;}+ tagGroup.children.forEach((tag, tagIndex) => {+ if (tag.id === action.entry.id) {+ tagIndexForUpdating = tagIndex;+ }+ });});- });- if (tagIndexForUpdating >= 0) {- const modifiedEntry = extend({ created_date: new Date() }, action.entry, { modified_date: new Date() });- return [- ...state.slice(0, indexForUpdating),- {- ...state[indexForUpdating],- children: [- ...state[indexForUpdating].children.slice(0, tagIndexForUpdating),- modifiedEntry,- ...state[indexForUpdating].children.slice(tagIndexForUpdating + 1)- ]- },- ...state.slice(indexForUpdating + 1)- ];- }- return state;- }- case types.REMOVE_TAG: {- let tagIndexForRemoving = -1;- let indexForEditing = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.uuid) {- indexForEditing = index;+ if (tagIndexForUpdating >= 0) {+ const modifiedEntry = extend(+ { created_date: new Date() },+ action.entry,+ { modified_date: new Date() }+ );+ return [+ ...state.slice(0, indexForUpdating),+ {+ ...state[indexForUpdating],+ children: [+ ...state[indexForUpdating].children.slice(0, tagIndexForUpdating),+ modifiedEntry,+ ...state[indexForUpdating].children.slice(tagIndexForUpdating + 1)+ ]+ },+ ...state.slice(indexForUpdating + 1)+ ];}- tagGroup.children.forEach((tag, tagIndex) => {- if (tag.id === action.tagID) {- tagIndexForRemoving = tagIndex;+ return state;+ }+ case types.REMOVE_TAG: {+ let tagIndexForRemoving = -1;+ let indexForEditing = -1;+ state.forEach((tagGroup, index) => {+ if (tagGroup.uuid === action.uuid) {+ indexForEditing = index;}+ tagGroup.children.forEach((tag, tagIndex) => {+ if (tag.id === action.tagID) {+ tagIndexForRemoving = tagIndex;+ }+ });});- });- if (tagIndexForRemoving >= 0) {- return [- ...state.slice(0, indexForEditing),- {- ...state[indexForEditing],- children: [- ...state[indexForEditing].children.slice(0, tagIndexForRemoving),- ...state[indexForEditing].children.slice(tagIndexForRemoving + 1)- ]- },- ...state.slice(indexForEditing + 1)- ];- }- return state;- }- case types.TOGGLE_TAGGROUP: {- let indexForUpdating = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.uuid) {- indexForUpdating = index;+ if (tagIndexForRemoving >= 0) {+ return [+ ...state.slice(0, indexForEditing),+ {+ ...state[indexForEditing],+ children: [+ ...state[indexForEditing].children.slice(0, tagIndexForRemoving),+ ...state[indexForEditing].children.slice(tagIndexForRemoving + 1)+ ]+ },+ ...state.slice(indexForEditing + 1)+ ];}- });- if (indexForUpdating >= 0) {- return [- ...state.slice(0, indexForUpdating),- {- ...state[indexForUpdating],- expanded: !action.expanded- },- ...state.slice(indexForUpdating + 1)- ];+ return state;}- return state;- }- case types.MOVE_TAG_GROUP_DOWN: {- let indexForUpdating = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.uuid) {- indexForUpdating = index;+ case types.TOGGLE_TAGGROUP: {+ let indexForUpdating = -1;+ state.forEach((tagGroup, index) => {+ if (tagGroup.uuid === action.uuid) {+ indexForUpdating = index;+ }+ });+ if (indexForUpdating >= 0) {+ return [+ ...state.slice(0, indexForUpdating),+ {+ ...state[indexForUpdating],+ expanded: !action.expanded+ },+ ...state.slice(indexForUpdating + 1)+ ];}- });- if (indexForUpdating >= 0 && indexForUpdating < (state.length - 1)) {- const secondIndex = indexForUpdating + 1;- return immutablySwapItems(state, indexForUpdating, secondIndex);+ return state;}- return state;- }- case types.MOVE_TAG_GROUP_UP: {- let indexForUpdating = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.uuid) {- indexForUpdating = index;+ case types.MOVE_TAG_GROUP_DOWN: {+ let indexForUpdating = -1;+ state.forEach((tagGroup, index) => {+ if (tagGroup.uuid === action.uuid) {+ indexForUpdating = index;+ }+ });+ if (indexForUpdating >= 0 && indexForUpdating < state.length - 1) {+ const secondIndex = indexForUpdating + 1;+ return immutablySwapItems(state, indexForUpdating, secondIndex);}- });- if (indexForUpdating > 0) {- const secondIndex = indexForUpdating - 1;- return immutablySwapItems(state, indexForUpdating, secondIndex);+ return state;}- return state;- }- case types.SORT_TAG_GROUP_UP: {- let indexForUpdating = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.uuid) {- indexForUpdating = index;+ case types.MOVE_TAG_GROUP_UP: {+ let indexForUpdating = -1;+ state.forEach((tagGroup, index) => {+ if (tagGroup.uuid === action.uuid) {+ indexForUpdating = index;+ }+ });+ if (indexForUpdating > 0) {+ const secondIndex = indexForUpdating - 1;+ return immutablySwapItems(state, indexForUpdating, secondIndex);}- });- if (indexForUpdating >= 0) {- return [- ...state.slice(0, indexForUpdating),- {- ...state[indexForUpdating],- children: state[indexForUpdating].children.sort((a, b) => (a.title > b.title ? 1 : a.title < b.title ? -1 : 0))- },- ...state.slice(indexForUpdating + 1)- ];+ return state;}- return state;- }- case types.MOVE_TAG: {- let tagIndexForRemoving = -1;- let indexFromGroup = -1;- let indexToGroup = -1;- state.forEach((tagGroup, index) => {- if (tagGroup.uuid === action.fromTagGroupId) {- indexFromGroup = index;- }- if (tagGroup.uuid === action.toTagGroupId) {- indexToGroup = index;- }- });- if (indexFromGroup >= 0 && state[indexFromGroup].children) {- state[indexFromGroup].children.forEach((tag, tagIndex) => {- if (tag.id === action.tagID) {- tagIndexForRemoving = tagIndex;+ case types.SORT_TAG_GROUP_UP: {+ let indexForUpdating = -1;+ state.forEach((tagGroup, index) => {+ if (tagGroup.uuid === action.uuid) {+ indexForUpdating = index;}- return true;});- }- if (indexToGroup >= 0 && indexToGroup >= 0 && tagIndexForRemoving >= 0) {- const newTagLibrary = [...state];- const tag = { ...state[indexFromGroup].children[tagIndexForRemoving] };- const found = newTagLibrary[indexToGroup].children.find(t => t.title === tag.title);- if (!found) {- newTagLibrary[indexToGroup].children.push(tag);- newTagLibrary[indexFromGroup].children = [- ...newTagLibrary[indexFromGroup].children.slice(0, tagIndexForRemoving),- ...newTagLibrary[indexFromGroup].children.slice(tagIndexForRemoving + 1)+ if (indexForUpdating >= 0) {+ return [+ ...state.slice(0, indexForUpdating),+ {+ ...state[indexForUpdating],+ children: state[indexForUpdating].children.sort((a, b) =>+ a.title > b.title ? 1 : a.title < b.title ? -1 : 0+ )+ },+ ...state.slice(indexForUpdating + 1)];- return newTagLibrary;}- console.warn('Tag with this title alread exists in the target tag group');+ return state;}- return state;- }- case types.IMPORT_TAGGROUP: {- const arr = [...state];- console.log(arr);- if (action.entry[0].key) {- action.entry.forEach((tagGroup, index) => {- // migration of old tag groups 2.9 or less in the new version 3.0-present- if (tagGroup.key === state.uuid || tagGroup.key !== state.uuid) {- tagGroup = {- title: tagGroup.title,- uuid: tagGroup.key,- expanded: true,- children: tagGroup.children- };- const tagsArr = [];- tagGroup.children.forEach((tag) => {- if (!tag.id) {- tag = {- id: uuidv1(),- type: tag.type,- title: tag.title,- functionality: tag.title,- color: tag.color,- textcolor: tag.textcolor,- description: tag.description,- icon: tag.icon,- style: tag.style- };- tagsArr.push(tag);- }- tagGroup.children = tagsArr;- arr.push(tagGroup);- });+ case types.MOVE_TAG: {+ let tagIndexForRemoving = -1;+ let indexFromGroup = -1;+ let indexToGroup = -1;+ state.forEach((tagGroup, index) => {+ if (tagGroup.uuid === action.fromTagGroupId) {+ indexFromGroup = index;}- });- } else {- action.entry.forEach((tagGroup) => {- const index = state.findIndex(obj => obj.uuid === tagGroup.uuid);- if (index > -1) {- tagGroup.children.forEach((tag) => {- const stateTag = state[index].children.find(obj => obj.id === tag.id);- if (stateTag === undefined) {- arr[index].children.push(tag);- }- });- } else {- arr.push(tagGroup);+ if (tagGroup.uuid === action.toTagGroupId) {+ indexToGroup = index;}});+ if (indexFromGroup >= 0 && state[indexFromGroup].children) {+ state[indexFromGroup].children.forEach((tag, tagIndex) => {+ if (tag.id === action.tagID) {+ tagIndexForRemoving = tagIndex;+ }+ return true;+ });+ }+ if (indexToGroup >= 0 && indexToGroup >= 0 && tagIndexForRemoving >= 0) {+ const newTagLibrary = [...state];+ const tag = { ...state[indexFromGroup].children[tagIndexForRemoving] };+ const found = newTagLibrary[indexToGroup].children.find(+ t => t.title === tag.title+ );+ if (!found) {+ newTagLibrary[indexToGroup].children.push(tag);+ newTagLibrary[indexFromGroup].children = [+ ...newTagLibrary[indexFromGroup].children.slice(+ 0,+ tagIndexForRemoving+ ),+ ...newTagLibrary[indexFromGroup].children.slice(+ tagIndexForRemoving + 1+ )+ ];+ return newTagLibrary;+ }+ console.warn(+ 'Tag with this title alread exists in the target tag group'+ );+ }+ return state;}+ case types.IMPORT_TAGGROUP: {+ const arr = [...state];+ console.log(arr);+ if (action.entry[0].key) {+ action.entry.forEach((tagGroup, index) => {+ // migration of old tag groups 2.9 or less in the new version 3.0-present+ if (tagGroup.key === state.uuid || tagGroup.key !== state.uuid) {+ tagGroup = {+ title: tagGroup.title,+ uuid: tagGroup.key,+ expanded: true,+ children: tagGroup.children+ };+ const tagsArr = [];+ tagGroup.children.forEach(tag => {+ if (!tag.id) {+ tag = {+ id: uuidv1(),+ type: tag.type,+ title: tag.title,+ functionality: tag.title,+ color: tag.color,+ textcolor: tag.textcolor,+ description: tag.description,+ icon: tag.icon,+ style: tag.style+ };+ tagsArr.push(tag);+ }+ tagGroup.children = tagsArr;+ arr.push(tagGroup);+ });+ }+ });+ } else {+ action.entry.forEach(tagGroup => {+ const index = state.findIndex(obj => obj.uuid === tagGroup.uuid);+ if (index > -1) {+ tagGroup.children.forEach(tag => {+ const stateTag = state[index].children.find(+ obj => obj.id === tag.id+ );+ if (stateTag === undefined) {+ arr[index].children.push(tag);+ }+ });+ } else {+ arr.push(tagGroup);+ }+ });+ }- return arr;- }- default: {- return state;- }+ return arr;+ }+ default: {+ return state;+ }}};export const actions = {createTagGroup: (entry: TagGroup) => ({ type: types.CREATE_TAGGROUP, entry }),editTagGroup: (entry: TagGroup) => ({ type: types.UPDATE_TAGGROUP, entry }),- removeTagGroup: (parentTagGroupUuid: Uuid) => ({ type: types.REMOVE_TAGGROUP, uuid: parentTagGroupUuid }),- toggleTagGroup: (expanded: boolean, parentTagGroupUuid: Uuid) => ({ type: types.TOGGLE_TAGGROUP, expanded, uuid: parentTagGroupUuid }),+ removeTagGroup: (parentTagGroupUuid: Uuid) => ({+ type: types.REMOVE_TAGGROUP,+ uuid: parentTagGroupUuid+ }),+ toggleTagGroup: (expanded: boolean, parentTagGroupUuid: Uuid) => ({+ type: types.TOGGLE_TAGGROUP,+ expanded,+ uuid: parentTagGroupUuid+ }),addTagGroup: (entry: TagGroup) => ({ type: types.ADD_TAGGROUP, entry }),mergeTagGroup: (entry: TagGroup) => ({ type: types.MERGE_TAGGROUP, entry }),addTag: (tag: string, parentTagGroupUuid: Uuid) => {@@ -439,26 +490,51 @@ export const actions = {console.log(tag, parentTagGroupUuid);return { type: types.ADD_TAG, tag, uuid: parentTagGroupUuid };},- editTag: (entry: Tag, parentTagGroupUuid: Uuid) => ({ type: types.UPDATE_TAG, entry, uuid: parentTagGroupUuid }),- deleteTag: (tagID: string, parentTagGroupUuid: Uuid) => ({ type: types.REMOVE_TAG, tagID, uuid: parentTagGroupUuid }),- moveTagGroupUp: (parentTagGroupUuid: Uuid) => ({ type: types.MOVE_TAG_GROUP_UP, uuid: parentTagGroupUuid }),- moveTagGroupDown: (parentTagGroupUuid: Uuid) => ({ type: types.MOVE_TAG_GROUP_DOWN, uuid: parentTagGroupUuid }),- sortTagGroup: (parentTagGroupUuid: Uuid) => ({ type: types.SORT_TAG_GROUP_UP, uuid: parentTagGroupUuid }),- moveTag: (tagID: string, fromTagGroupUuid: Uuid, toTagGroupUuid: Uuid) =>- ({ type: types.MOVE_TAG, tagID, fromTagGroupId: fromTagGroupUuid, toTagGroupId: toTagGroupUuid }),- importTagGroups: (entry) => ({ type: types.IMPORT_TAGGROUP, entry }),+ editTag: (entry: Tag, parentTagGroupUuid: Uuid) => ({+ type: types.UPDATE_TAG,+ entry,+ uuid: parentTagGroupUuid+ }),+ deleteTag: (tagID: string, parentTagGroupUuid: Uuid) => ({+ type: types.REMOVE_TAG,+ tagID,+ uuid: parentTagGroupUuid+ }),+ moveTagGroupUp: (parentTagGroupUuid: Uuid) => ({+ type: types.MOVE_TAG_GROUP_UP,+ uuid: parentTagGroupUuid+ }),+ moveTagGroupDown: (parentTagGroupUuid: Uuid) => ({+ type: types.MOVE_TAG_GROUP_DOWN,+ uuid: parentTagGroupUuid+ }),+ sortTagGroup: (parentTagGroupUuid: Uuid) => ({+ type: types.SORT_TAG_GROUP_UP,+ uuid: parentTagGroupUuid+ }),+ moveTag: (tagID: string, fromTagGroupUuid: Uuid, toTagGroupUuid: Uuid) => ({+ type: types.MOVE_TAG,+ tagID,+ fromTagGroupId: fromTagGroupUuid,+ toTagGroupId: toTagGroupUuid+ }),+ importTagGroups: entry => ({ type: types.IMPORT_TAGGROUP, entry }),exportTagGroups: (entry: Array<Object>) => (dispatch: (actions: Object) => void,getState: () => Object) => {const { settings } = getState();const tagLibrary = entry;- const jsonFormat = '{ "appName": "' + versionMeta.name +- '", "appVersion": "' + versionMeta.version +- '", "settingsVersion": ' + settings.settingsVersion ++ const jsonFormat =+ '{ "appName": "' ++ versionMeta.name ++ '", "appVersion": "' ++ versionMeta.version ++ '", "settingsVersion": ' ++ settings.settingsVersion +', "tagGroups": ';const getAllTags = [];- tagLibrary.forEach((value) => {+ tagLibrary.forEach(value => {getAllTags.push(value);});@@ -480,7 +556,9 @@ export const getAllTags = (state: Object) => {allTags.push(tag);});});- return allTags.sort((a, b) => (a.title > b.title ? 1 : a.title < b.title ? -1 : 0));+ return allTags.sort((a, b) =>+ a.title > b.title ? 1 : a.title < b.title ? -1 : 0+ );};export const getTagColors = (state: Object, tagTitle: string) => {diff --git a/app/services/cordova-io.js b/app/services/cordova-io.jsindex ffb84ee35..3b2b0a7dd 100644--- a/app/services/cordova-io.js+++ b/app/services/cordova-io.js@@ -21,7 +21,10 @@import AppConfig from '../config';import { b64toBlob } from '../utils/misc';-import { extractParentDirectoryPath, cleanTrailingDirSeparator } from '../utils/paths';+import {+ extractParentDirectoryPath,+ cleanTrailingDirSeparator+} from '../utils/paths';const appSettingFile = 'settings.json';const appSettingTagsFile = 'settingsTags.json';@@ -44,7 +47,9 @@ export default class CordovaIO {loadedSettingsTags: any;onDeviceReady = () => {- console.log('Device Ready: ' + window.device.platform + ' - ' + window.device.version);+ console.log(+ 'Device Ready: ' + window.device.platform + ' - ' + window.device.version+ );// attachFastClick(document.body);this.getFileSystem();@@ -93,12 +98,12 @@ export default class CordovaIO {TestFairy.begin('ef5d3fd8bfa17164b8068e71ccb32e1beea25f2f');} */}- }+ };- onDeviceBackButton = (e) => {+ onDeviceBackButton = e => {e.preventDefault();// send event to main app- }+ };isWorkerAvailable = (): boolean => false;@@ -290,7 +295,7 @@ export default class CordovaIO {fileEntry.file(file => {const reader = new FileReader();- reader.onloadend = (evt) => {+ reader.onloadend = evt => {let content = null;if (evt.target.result.length > 0) {content = evt.target.result;@@ -385,32 +390,35 @@ export default class CordovaIO {};listMetaDirectoryPromise = async (path: string): Promise<Array<Object>> => {- const promise = new Promise((resolve) => {+ const promise = new Promise(resolve => {const entries = [];- const metaDirPath = cleanTrailingDirSeparator(path) + AppConfig.dirSeparator + AppConfig.metaFolder + AppConfig.dirSeparator;+ const metaDirPath =+ cleanTrailingDirSeparator(path) ++ AppConfig.dirSeparator ++ AppConfig.metaFolder ++ AppConfig.dirSeparator;- this.getFileSystemPromise(metaDirPath).then(- fileSystem => {+ this.getFileSystemPromise(metaDirPath)+ .then(fileSystem => {const reader = fileSystem.createReader();- reader.readEntries(- entr => {- entr.forEach(entry => {- const entryPath = entry.fullPath;- if (entryPath.toLowerCase() === metaDirPath.toLowerCase()) {- console.log('Skipping current folder');- } else {- const ee = {};- ee.name = entry.name;- ee.path = decodeURI(entryPath);- ee.isFile = true;- entries.push(ee);- }- });- resolve(entries);+ reader.readEntries(entr => {+ entr.forEach(entry => {+ const entryPath = entry.fullPath;+ if (entryPath.toLowerCase() === metaDirPath.toLowerCase()) {+ console.log('Skipping current folder');+ } else {+ const ee = {};+ ee.name = entry.name;+ ee.path = decodeURI(entryPath);+ ee.isFile = true;+ entries.push(ee);+ }});+ resolve(entries);+ });return true;})- .catch((err) => {+ .catch(err => {console.error('Error getting listMetaDirectoryPromise:', err);resolve(entries); // returning results even if any promise fails});@@ -422,56 +430,76 @@ 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<*> => new Promise(async (resolve, reject) => {- console.time('listDirectoryPromise');- const metaContent = !lite ? await this.listMetaDirectoryPromise(path) : [];-- const enhancedEntries = [];- const metaPromises = [];- this.getFileSystemPromise(path).then(- fileSystem => {- const reader = fileSystem.createReader();- reader.readEntries(- entries => {- entries.forEach(entry => {- const eentry = {};- eentry.name = entry.name;- eentry.path = entry.fullPath;- eentry.tags = [];- eentry.thumbPath = entry.isFile ? '' : eentry.path + '/' + AppConfig.metaFolder + '/' + AppConfig.folderThumbFile;- // eentry.meta = {};- eentry.isFile = entry.isFile;- if (entry.isFile) {- entry.file(- fileEntry => {- eentry.size = fileEntry.size;- eentry.lmdt = fileEntry.lastModifiedDate;- });- }-- if (!lite) {- if (entry.isDirectory) { // Read tsm.json from subfolders- const metaDirAvailable = metaContent.find(obj => obj.name === AppConfig.metaFolder);- if (metaDirAvailable) {- metaPromises.push(this.getEntryMeta(eentry, metaDirAvailable.path));- }- } else {- const metaFileAvailable = metaContent.find(obj => obj.name === entry.name + AppConfig.metaFileExt);- if (metaFileAvailable) {- metaPromises.push(this.getEntryMeta(eentry, metaFileAvailable.path));+ listDirectoryPromise = (path: string, lite: boolean): Promise<*> =>+ new Promise(async (resolve, reject) => {+ console.time('listDirectoryPromise');+ const metaContent = !lite+ ? await this.listMetaDirectoryPromise(path)+ : [];++ const enhancedEntries = [];+ const metaPromises = [];+ this.getFileSystemPromise(path)+ .then(+ fileSystem => {+ const reader = fileSystem.createReader();+ reader.readEntries(+ entries => {+ entries.forEach(entry => {+ const eentry = {};+ eentry.name = entry.name;+ eentry.path = entry.fullPath;+ eentry.tags = [];+ eentry.thumbPath = entry.isFile+ ? ''+ : eentry.path ++ '/' ++ AppConfig.metaFolder ++ '/' ++ AppConfig.folderThumbFile;+ // eentry.meta = {};+ eentry.isFile = entry.isFile;+ if (entry.isFile) {+ entry.file(fileEntry => {+ eentry.size = fileEntry.size;+ eentry.lmdt = fileEntry.lastModifiedDate;+ });}- // Finding if thumbnail available- const metaThumbAvailable = metaContent.find(obj => obj.name === entry.name + AppConfig.thumbFileExt);- if (metaThumbAvailable) {- eentry.thumbPath = metaThumbAvailable.path;+ if (!lite) {+ if (entry.isDirectory) {+ // Read tsm.json from subfolders+ const metaDirAvailable = metaContent.find(+ obj => obj.name === AppConfig.metaFolder+ );+ if (metaDirAvailable) {+ metaPromises.push(+ this.getEntryMeta(eentry, metaDirAvailable.path)+ );+ }+ } else {+ const metaFileAvailable = metaContent.find(+ obj => obj.name === entry.name + AppConfig.metaFileExt+ );+ if (metaFileAvailable) {+ metaPromises.push(+ this.getEntryMeta(eentry, metaFileAvailable.path)+ );+ }++ // Finding if thumbnail available+ const metaThumbAvailable = metaContent.find(+ obj => obj.name === entry.name + AppConfig.thumbFileExt+ );+ if (metaThumbAvailable) {+ eentry.thumbPath = metaThumbAvailable.path;+ }+ }}- }- }- enhancedEntries.push(eentry);+ enhancedEntries.push(eentry);- /* if (entry.isDirectory) {+ /* if (entry.isDirectory) {anotatedDirList.push({name: entry.name,path: entry.fullPath,@@ -516,15 +544,17 @@ export default class CordovaIO {fileWorkers.push(filePromise);}} */- });+ });- Promise.all(metaPromises).then(() => {- resolve(enhancedEntries);- return true;- }).catch(() => {- resolve(enhancedEntries);- });- /* Promise.all(fileWorkers).then(+ Promise.all(metaPromises)+ .then(() => {+ resolve(enhancedEntries);+ return true;+ })+ .catch(() => {+ resolve(enhancedEntries);+ });+ /* Promise.all(fileWorkers).then(entries => {entries.forEach(entry => {anotatedDirList.push(entry);@@ -543,29 +573,29 @@ export default class CordovaIO {resolve(anotatedDirList); // returning results even if any promise fails}); */- },- err => {- console.warn(- 'Error reading entries promise from ' +- path +- 'err ' +- JSON.stringify(err)+ },+ err => {+ console.warn(+ 'Error reading entries promise from ' ++ path ++ 'err ' ++ JSON.stringify(err)+ );+ resolve(enhancedEntries); // returning results even if any promise fails+ });+ return true;+ },+ () => {+ console.warn('Error getting file system promise');resolve(enhancedEntries); // returning results even if any promise fails}- );- return true;- },- () => {- console.warn('Error getting file system promise');- resolve(enhancedEntries); // returning results even if any promise fails- }- )- .catch((err) => {- console.error('Error getting listDirectoryPromise:', err);- resolve(enhancedEntries); // returning results even if any promise fails- });- });+ )+ .catch(err => {+ console.error('Error getting listDirectoryPromise:', err);+ resolve(enhancedEntries); // returning results even if any promise fails+ });+ });getEntryMeta = (eentry: Object, metaPath: string): Promise<Object> => {if (eentry.isFile) {@@ -577,7 +607,8 @@ export default class CordovaIO {});}// const folderMetaPath = normalizePath(eentry.path) + AppConfig.dirSeparator + AppConfig.metaFolderFile; // getMetaFileLocationForDir(eentry.path);- if (!eentry.path.endsWith(AppConfig.metaFolder + '/')) { // Skip the /.ts folder+ if (!eentry.path.endsWith(AppConfig.metaFolder + '/')) {+ // Skip the /.ts folderreturn this.loadTextFilePromise(metaPath).then(result => {// eslint-disable-next-line no-param-reassigneentry.meta = JSON.parse(result.trim());@@ -585,7 +616,7 @@ export default class CordovaIO {});}- return new Promise((resolve) => {+ return new Promise(resolve => {resolve(eentry);});};@@ -633,19 +664,22 @@ export default class CordovaIO {resolve(false);}},- (err) => {- console.log('getPropertiesPromise: Error getting file ' + entryPath, err);+ err => {+ console.log(+ 'getPropertiesPromise: Error getting file ' + entryPath,+ err+ );resolve(false);});- })- // });- ;+ });+ // });/*** Load the content of a text file*/- loadTextFilePromise = (filePath: string): Promise<*> => this.getFileContentPromise(filePath, 'text');+ loadTextFilePromise = (filePath: string): Promise<*> =>+ this.getFileContentPromise(filePath, 'text');/*** Gets the content of file, useful for binary files@@ -695,10 +729,10 @@ export default class CordovaIO {return new Promise((resolve, reject) => {getFilePromise(filePath, resolvePath).then(file => {const reader = new FileReader();- reader.onerror = function () {+ reader.onerror = function() {reject(reader.error);};- reader.onload = function () {+ reader.onload = function() {resolve(reader.result);};if (type === 'text') {@@ -748,13 +782,16 @@ export default class CordovaIO {entry => {entry.createWriter(writer => {- writer.onwriteend = function (evt) {+ writer.onwriteend = function(evt) {// resolve(this.fsRoot.fullPath + "/" + filePath);resolve(isFileNew);};if (isRaw) {writer.write(content);- } else if (typeof content === 'string' && content.indexOf(';base64,') > 0) {+ } else if (+ typeof content === 'string' &&+ content.indexOf(';base64,') > 0+ ) {const contentArray = content.split(';base64,');const type =contentArray.length > 1@@ -914,7 +951,9 @@ export default class CordovaIO {new Promise((resolve, reject) => {// eslint-disable-next-line no-param-reassignfilePath = this.normalizePath(filePath);- const newFileName = newFilePath.substring(newFilePath.lastIndexOf('/') + 1);+ const newFileName = newFilePath.substring(+ newFilePath.lastIndexOf('/') + 1+ );const newFileParentPath = this.normalizePath(newFilePath.substring(0, newFilePath.lastIndexOf('/') + 1));@@ -935,7 +974,7 @@ export default class CordovaIO {create: false,exclusive: false},- (entry) => {+ entry => {entry.moveTo(parentDirEntry,newFileName,@@ -948,12 +987,12 @@ export default class CordovaIO {);resolve([filePath, newFilePath]);},- (err) => {+ err => {reject('error renaming: ' + filePath + ' ' + err);});},- (error) => {+ error => {reject('Error getting file: ' + filePath + ' ' + error);});@@ -973,97 +1012,96 @@ export default class CordovaIO {/*** Rename a directory*/- renameDirectoryPromise = (- dirPath: string,- newDirName: string- ): Promise<*> => new Promise((resolve, reject) => {- let newDirPath =+ renameDirectoryPromise = (dirPath: string, newDirName: string): Promise<*> =>+ new Promise((resolve, reject) => {+ let newDirPath =extractParentDirectoryPath(dirPath) +AppConfig.dirSeparator +newDirName;- // eslint-disable-next-line no-param-reassign- dirPath = this.normalizePath(dirPath);- const newDirParentPath = this.normalizePath(- newDirPath.substring(0, newDirPath.lastIndexOf('/'))- );- newDirPath = this.normalizePath(newDirPath);- console.log('renameDirectoryPromise: ' + dirPath + ' to: ' + newDirPath);- // TODO check if the newFilePath exist or cause issues by renaming- this.fsRoot.getDirectory(- newDirParentPath,- {- create: false,- exclusive: false- },- parentDirEntry => {- this.fsRoot.getDirectory(- dirPath,- {- create: false,- exclusive: false- },- entry => {- entry.moveTo(- parentDirEntry,- newDirName,- () => {- console.log(- 'Directory renamed to: ' ++ // eslint-disable-next-line no-param-reassign+ dirPath = this.normalizePath(dirPath);+ const newDirParentPath = this.normalizePath(+ newDirPath.substring(0, newDirPath.lastIndexOf('/'))+ );+ newDirPath = this.normalizePath(newDirPath);+ console.log('renameDirectoryPromise: ' + dirPath + ' to: ' + newDirPath);+ // TODO check if the newFilePath exist or cause issues by renaming+ this.fsRoot.getDirectory(+ newDirParentPath,+ {+ create: false,+ exclusive: false+ },+ parentDirEntry => {+ this.fsRoot.getDirectory(+ dirPath,+ {+ create: false,+ exclusive: false+ },+ entry => {+ entry.moveTo(+ parentDirEntry,+ newDirName,+ () => {+ console.log(+ 'Directory renamed to: ' +newDirPath +' from: ' +entry.fullPath- );- resolve('/' + newDirPath);- },- err => {- reject('error renaming directory: ' + dirPath + ' ' + err);- }- );- },- error => {- reject('Error getting directory: ' + dirPath + ' ' + error);- }- );- },- error => {- console.error(- 'Getting dir: ' ++ );+ resolve('/' + newDirPath);+ },+ err => {+ reject('error renaming directory: ' + dirPath + ' ' + err);+ }+ );+ },+ error => {+ reject('Error getting directory: ' + dirPath + ' ' + error);+ }+ );+ },+ error => {+ console.error(+ 'Getting dir: ' +newDirParentPath +' failed with error code: ' +error.code- );- reject(error);- }- );- });+ );+ reject(error);+ }+ );+ });/*** Delete a specified file*/- deleteFilePromise = (filePath: string): Promise<*> => new Promise((resolve, reject) => {- const path = this.normalizePath(filePath);- this.fsRoot.getFile(- path,- {- create: false,- exclusive: false- },- entry => {- entry.remove(- () => {- console.log('file deleted: ' + path);- resolve(filePath);- },- err => {- reject('error deleting: ' + filePath + ' ' + err);- }- );- },- error => {- reject('error getting file' + path + ' ' + error);- }- );- });+ deleteFilePromise = (filePath: string): Promise<*> =>+ new Promise((resolve, reject) => {+ const path = this.normalizePath(filePath);+ this.fsRoot.getFile(+ path,+ {+ create: false,+ exclusive: false+ },+ entry => {+ entry.remove(+ () => {+ console.log('file deleted: ' + path);+ resolve(filePath);+ },+ err => {+ reject('error deleting: ' + filePath + ' ' + err);+ }+ );+ },+ error => {+ reject('error getting file' + path + ' ' + error);+ }+ );+ });/*** Delete a specified directory, the directory should be empty, if the trash can functionality is not enabled@@ -1103,14 +1141,14 @@ export default class CordovaIO {selectDirectory = () => {console.log('Open select directory dialog.');// showDirectoryBrowserDialog(this.fsRoot.fullPath);- }+ };/*** Selects a file with the help of a file chooser*/selectFile = () => {console.log('Operation selectFile not supported.');- }+ };/*** Opens a directory in the operating system's default file managerdiff --git a/app/services/electron-io.js b/app/services/electron-io.jsindex 2625b5767..524acb8cb 100644--- a/app/services/electron-io.js+++ b/app/services/electron-io.js@@ -21,7 +21,7 @@ import fsextra from 'fs-extra';import winattr from 'winattr';import {extractParentDirectoryPath,- getMetaDirectoryPath,+ getMetaDirectoryPath// extractFileExtension} from '../utils/paths';import { arrayBufferToBuffer } from '../utils/misc';@@ -172,21 +172,18 @@ export default class ElectronIO {getUserHomePath = (): string => this.app.getPath('home');- getAppDataPath = (): string => this.ipcRenderer.sendSync(- 'app-data-path-request',- 'notNeededArgument'- );+ getAppDataPath = (): string =>+ this.ipcRenderer.sendSync('app-data-path-request', 'notNeededArgument');- setZoomFactorElectron = (zoomLevel: number) => this.webFrame.setZoomFactor(zoomLevel);+ setZoomFactorElectron = (zoomLevel: number) =>+ this.webFrame.setZoomFactor(zoomLevel);setGlobalShortcuts = (globalShortcutsEnabled: boolean) => {this.ipcRenderer.send('global-shortcuts-enabled', globalShortcutsEnabled);- }+ };- getAppPath = (): string => this.ipcRenderer.sendSync(- 'app-dir-path-request',- 'notNeededArgument'- );+ getAppPath = (): string =>+ this.ipcRenderer.sendSync('app-dir-path-request', 'notNeededArgument');createDirectoryTree = (directoryPath: string): Object => {console.log('Creating directory index for: ' + directoryPath);@@ -224,7 +221,10 @@ export default class ElectronIO {return generateDirectoryTree(directoryPath);};- createDirectoryIndexInWorker = (directoryPath: string, extractText: boolean): Promise<any> => {+ createDirectoryIndexInWorker = (+ directoryPath: string,+ extractText: boolean+ ): Promise<any> => {return new Promise((resolve, reject) => {if (this.isWorkerAvailable()) {const timestamp = new Date().getTime().toString();@@ -244,230 +244,244 @@ export default class ElectronIO {});};- createThumbnailsInWorker = (tmbGenerationList: Array<string>): Promise<any> => new Promise((resolve, reject) => {- if (this.isWorkerAvailable()) {- const timestamp = new Date().getTime().toString();- this.workerWindow.webContents.send('worker', {- id: timestamp,- action: 'createThumbnails',- tmbGenerationList- });- this.ipcRenderer.once(timestamp, (event, data) => {- // console.log('Answer from worker received ' + data.result);- resolve(data.result);- });- } else {- reject('Worker window not available!');- }- });+ createThumbnailsInWorker = (tmbGenerationList: Array<string>): Promise<any> =>+ new Promise((resolve, reject) => {+ if (this.isWorkerAvailable()) {+ const timestamp = new Date().getTime().toString();+ this.workerWindow.webContents.send('worker', {+ id: timestamp,+ action: 'createThumbnails',+ tmbGenerationList+ });+ this.ipcRenderer.once(timestamp, (event, data) => {+ // console.log('Answer from worker received ' + data.result);+ resolve(data.result);+ });+ } else {+ reject('Worker window not available!');+ }+ });listDirectoryPromise = (path: string,lite: boolean = true,extractTextContent: boolean = false- ): Promise<Array<Object>> => new Promise(resolve => {- const enhancedEntries = [];- let entryPath;- let metaFolderPath;- let stats;- let eentry;- let containsMetaFolder = false;- // const metaMetaFolder = AppConfig.metaFolder + AppConfig.dirSeparator + AppConfig.metaFolder;-- this.fs.readdir(path, (error, entries) => {- if (error) {- console.warn('Error listing directory ' + path);- resolve(enhancedEntries); // returning results even if any promise fails- return;- }-- if (window.walkCanceled) {- resolve(enhancedEntries); // returning results even if walk canceled- return;- }+ ): Promise<Array<Object>> =>+ new Promise(resolve => {+ const enhancedEntries = [];+ let entryPath;+ let metaFolderPath;+ let stats;+ let eentry;+ let containsMetaFolder = false;+ // const metaMetaFolder = AppConfig.metaFolder + AppConfig.dirSeparator + AppConfig.metaFolder;++ this.fs.readdir(path, (error, entries) => {+ if (error) {+ console.warn('Error listing directory ' + path);+ resolve(enhancedEntries); // returning results even if any promise fails+ return;+ }- if (entries) {- entries.forEach(entry => {- entryPath = path + AppConfig.dirSeparator + entry;- eentry = {};- eentry.name = entry;- eentry.path = entryPath;- eentry.tags = [];- eentry.thumbPath = '';- eentry.meta = {};-- try {- stats = this.fs.statSync(entryPath);- // if (AppConfig.isWin && winattr.getSync(entryPath).hidden) {- // return;- // }- eentry.isFile = stats.isFile();- eentry.size = stats.size;- eentry.lmdt = stats.mtime.getTime();-- if (- !eentry.isFile &&- eentry.name.endsWith(AppConfig.metaFolder)- ) {- containsMetaFolder = true;- }+ if (window.walkCanceled) {+ resolve(enhancedEntries); // returning results even if walk canceled+ return;+ }- // Read tsm.json from sub folders- if (!eentry.isFile && !lite) {- const folderMetaPath =- eentry.path +- AppConfig.dirSeparator +- AppConfig.metaFolder +- AppConfig.dirSeparator +- AppConfig.metaFolderFile;- try {- const folderMeta = this.fs.readJsonSync(folderMetaPath);- eentry.meta = folderMeta;- // console.log('Success reading meta folder file ' + folderMetaPath);- } catch (err) {- // console.log('Failed reading meta folder file ' + folderMetaPath);+ if (entries) {+ entries.forEach(entry => {+ entryPath = path + AppConfig.dirSeparator + entry;+ eentry = {};+ eentry.name = entry;+ eentry.path = entryPath;+ eentry.tags = [];+ eentry.thumbPath = '';+ eentry.meta = {};++ try {+ stats = this.fs.statSync(entryPath);+ // if (AppConfig.isWin && winattr.getSync(entryPath).hidden) {+ // return;+ // }+ eentry.isFile = stats.isFile();+ eentry.size = stats.size;+ eentry.lmdt = stats.mtime.getTime();++ if (+ !eentry.isFile &&+ eentry.name.endsWith(AppConfig.metaFolder)+ ) {+ containsMetaFolder = true;}- // Loading thumbs for folders- if (!eentry.path.includes('/' + AppConfig.metaFolder)) { // skipping meta folder- const folderTmbPath =+ // Read tsm.json from sub folders+ if (!eentry.isFile && !lite) {+ const folderMetaPath =eentry.path +AppConfig.dirSeparator +AppConfig.metaFolder +AppConfig.dirSeparator +- AppConfig.folderThumbFile;- const tmbStats = this.fs.statSync(folderTmbPath);- if (tmbStats.isFile()) {- eentry.thumbPath = folderTmbPath;+ AppConfig.metaFolderFile;+ try {+ const folderMeta = this.fs.readJsonSync(folderMetaPath);+ eentry.meta = folderMeta;+ // console.log('Success reading meta folder file ' + folderMetaPath);+ } catch (err) {+ // console.log('Failed reading meta folder file ' + folderMetaPath);}- }- }- const fileName = eentry.name.toLowerCase();- if (- extractTextContent && eentry.isFile &&- Pro && Pro.Indexer && Pro.Indexer.extractTextContent &&- (fileName.endsWith('.txt') || fileName.endsWith('.md') || fileName.endsWith('.html'))- ) {- const fileContent = this.fs.readFileSync(eentry.path, 'utf8');- eentry.textContent = Pro.Indexer.extractTextContent(fileName, fileContent);- }+ // Loading thumbs for folders+ if (!eentry.path.includes('/' + AppConfig.metaFolder)) {+ // skipping meta folder+ const folderTmbPath =+ eentry.path ++ AppConfig.dirSeparator ++ AppConfig.metaFolder ++ AppConfig.dirSeparator ++ AppConfig.folderThumbFile;+ const tmbStats = this.fs.statSync(folderTmbPath);+ if (tmbStats.isFile()) {+ eentry.thumbPath = folderTmbPath;+ }+ }+ }- if (window.walkCanceled) {- resolve(enhancedEntries);- return;- }- } catch (e) {- console.warn('Can not load properties for: ' + entryPath + ' ' + e);- }- enhancedEntries.push(eentry);- });+ const fileName = eentry.name.toLowerCase();+ if (+ extractTextContent &&+ eentry.isFile &&+ Pro &&+ Pro.Indexer &&+ Pro.Indexer.extractTextContent &&+ (fileName.endsWith('.txt') ||+ fileName.endsWith('.md') ||+ fileName.endsWith('.html'))+ ) {+ const fileContent = this.fs.readFileSync(eentry.path, 'utf8');+ eentry.textContent = Pro.Indexer.extractTextContent(+ fileName,+ fileContent+ );+ }- // Read the .ts meta content- if (!lite && containsMetaFolder) {- metaFolderPath = getMetaDirectoryPath(path);- this.fs.readdir(metaFolderPath, (err, metaEntries) => {- if (err) {- console.log(- 'Error listing meta directory ' + metaFolderPath + ' - ' + err+ if (window.walkCanceled) {+ resolve(enhancedEntries);+ return;+ }+ } catch (e) {+ console.warn(+ 'Can not load properties for: ' + entryPath + ' ' + e);- resolve(enhancedEntries); // returning results even if any promise fails- return;}+ enhancedEntries.push(eentry);+ });- if (window.walkCanceled) {- resolve(enhancedEntries); // returning results even if walk canceled- return;- }+ // Read the .ts meta content+ if (!lite && containsMetaFolder) {+ metaFolderPath = getMetaDirectoryPath(path);+ this.fs.readdir(metaFolderPath, (err, metaEntries) => {+ if (err) {+ console.log(+ 'Error listing meta directory ' + metaFolderPath + ' - ' + err+ );+ resolve(enhancedEntries); // returning results even if any promise fails+ return;+ }- if (metaEntries) {- metaEntries.forEach(metaEntryName => {- /* if (metaEntryName === AppConfig.metaFolderFile) {+ if (window.walkCanceled) {+ resolve(enhancedEntries); // returning results even if walk canceled+ return;+ }++ if (metaEntries) {+ metaEntries.forEach(metaEntryName => {+ /* if (metaEntryName === AppConfig.metaFolderFile) {// Read meta folder path} */- // Reading meta json files with tags and description- if (metaEntryName.endsWith(AppConfig.metaFileExt)) {- const fileNameWithoutMetaExt = metaEntryName.substr(- 0,- metaEntryName.lastIndexOf(AppConfig.metaFileExt)- );- const origFile = enhancedEntries.find(- result => result.name === fileNameWithoutMetaExt- );- if (origFile) {- const metaFilePath =- metaFolderPath + AppConfig.dirSeparator + metaEntryName;- const metaFileObj = this.fs.readJsonSync(metaFilePath);- if (metaFileObj) {- enhancedEntries.map(enhancedEntry => {- if (enhancedEntry.name === fileNameWithoutMetaExt) {- enhancedEntry.meta = metaFileObj;- }- return true;- });+ // Reading meta json files with tags and description+ if (metaEntryName.endsWith(AppConfig.metaFileExt)) {+ const fileNameWithoutMetaExt = metaEntryName.substr(+ 0,+ metaEntryName.lastIndexOf(AppConfig.metaFileExt)+ );+ const origFile = enhancedEntries.find(+ result => result.name === fileNameWithoutMetaExt+ );+ if (origFile) {+ const metaFilePath =+ metaFolderPath + AppConfig.dirSeparator + metaEntryName;+ const metaFileObj = this.fs.readJsonSync(metaFilePath);+ if (metaFileObj) {+ enhancedEntries.map(enhancedEntry => {+ if (enhancedEntry.name === fileNameWithoutMetaExt) {+ enhancedEntry.meta = metaFileObj;+ }+ return true;+ });+ }}}- }- // Finding if thumbnail available- if (metaEntryName.endsWith(AppConfig.thumbFileExt)) {- const fileNameWithoutMetaExt = metaEntryName.substr(- 0,- metaEntryName.lastIndexOf(AppConfig.thumbFileExt)- );- enhancedEntries.map(enhancedEntry => {- if (enhancedEntry.name === fileNameWithoutMetaExt) {- const thumbFilePath =- metaFolderPath +- AppConfig.dirSeparator +- metaEntryName;- enhancedEntry.thumbPath = thumbFilePath;- }- return true;- });- }+ // Finding if thumbnail available+ if (metaEntryName.endsWith(AppConfig.thumbFileExt)) {+ const fileNameWithoutMetaExt = metaEntryName.substr(+ 0,+ metaEntryName.lastIndexOf(AppConfig.thumbFileExt)+ );+ enhancedEntries.map(enhancedEntry => {+ if (enhancedEntry.name === fileNameWithoutMetaExt) {+ const thumbFilePath =+ metaFolderPath ++ AppConfig.dirSeparator ++ metaEntryName;+ enhancedEntry.thumbPath = thumbFilePath;+ }+ return true;+ });+ }- if (window.walkCanceled) {- resolve(enhancedEntries);- }- });- }+ if (window.walkCanceled) {+ resolve(enhancedEntries);+ }+ });+ }+ resolve(enhancedEntries);+ });+ } else {resolve(enhancedEntries);- });- } else {- resolve(enhancedEntries);+ }}- }+ });});- });-- getPropertiesPromise = (path: string): Promise<any> => new Promise(resolve => {- /* stats for file:- * "dev":41, "mode":33204, "nlink":1, "uid":1000, "gid":1000, "rdev":0,- * "blksize":4096, "ino":2634172, "size":230, "blocks":24, "atime":"2015-11-24T09:56:41.932Z",- * "mtime":"2015-11-23T14:29:29.689Z", "ctime":"2015-11-23T14:29:29.689Z", "birthtime":"2015-11-23T14:29:29.689Z",- * "isFile":true, "path":"/home/somefile.txt" */- this.fs.lstat(path, (err, stats) => {- if (err) {- resolve(false);- return;- }- if (stats) {- resolve({- name: path.substring(- path.lastIndexOf(AppConfig.dirSeparator) + 1,- path.length- ),- isFile: stats.isFile(),- size: stats.size,- lmdt: stats.mtime.getTime(),- path- });- }+ getPropertiesPromise = (path: string): Promise<any> =>+ new Promise(resolve => {+ /* stats for file:+ * "dev":41, "mode":33204, "nlink":1, "uid":1000, "gid":1000, "rdev":0,+ * "blksize":4096, "ino":2634172, "size":230, "blocks":24, "atime":"2015-11-24T09:56:41.932Z",+ * "mtime":"2015-11-23T14:29:29.689Z", "ctime":"2015-11-23T14:29:29.689Z", "birthtime":"2015-11-23T14:29:29.689Z",+ * "isFile":true, "path":"/home/somefile.txt" */+ this.fs.lstat(path, (err, stats) => {+ if (err) {+ resolve(false);+ return;+ }++ if (stats) {+ resolve({+ name: path.substring(+ path.lastIndexOf(AppConfig.dirSeparator) + 1,+ path.length+ ),+ isFile: stats.isFile(),+ size: stats.size,+ lmdt: stats.mtime.getTime(),+ path+ });+ }+ });});- });createDirectoryPromise = (dirPath: string): Promise<any> => {console.log('Creating directory: ' + dirPath);@@ -478,8 +492,12 @@ export default class ElectronIO {return;}// Make newly created .ts folders hidden under Windows- if (AppConfig.isWin && !PlatformIO.haveObjectStoreSupport() && dirPath.endsWith('\\' + AppConfig.metaFolder)) {- winattr.set(dirPath, { hidden: true }, (err) => {+ if (+ AppConfig.isWin &&+ !PlatformIO.haveObjectStoreSupport() &&+ dirPath.endsWith('\\' + AppConfig.metaFolder)+ ) {+ winattr.set(dirPath, { hidden: true }, err => {resolve(dirPath);if (err) {console.warn('Error setting hidden attr. to dir: ' + dirPath);@@ -603,96 +621,96 @@ export default class ElectronIO {loadTextFilePromise = (filePath: string,isPreview?: boolean = false- ): Promise<string> => new Promise((resolve, reject) => {- if (isPreview) {- const stream = this.fs.createReadStream(filePath, {- start: 0,- end: 10000- });+ ): Promise<string> =>+ new Promise((resolve, reject) => {+ if (isPreview) {+ const stream = this.fs.createReadStream(filePath, {+ start: 0,+ end: 10000+ });- stream.on('error', err => {- reject(err);- });+ stream.on('error', err => {+ reject(err);+ });- const chunks = [];- stream.on('data', (chunk) => {- chunks.push(chunk.toString());- // console.log('stream data ' + chunk);- });+ const chunks = [];+ stream.on('data', chunk => {+ chunks.push(chunk.toString());+ // console.log('stream data ' + chunk);+ });- stream.on('end', () => {- const textContent = chunks.join('');- resolve(textContent);- // console.log('final output ' + string);- });- } else {- this.fs.readFile(filePath, 'utf8', (error, content) => {- if (error) {- reject(error);- } else {- resolve(content);- }- });- }- });-- getFileContentPromise = (- fullPath: string,- type: string- ): Promise<any> => new Promise((resolve, reject) => {- let fileURL = fullPath;- if (fileURL.indexOf('file://') === -1) {- fileURL = 'file://' + fileURL;- }- const xhr = new XMLHttpRequest();- xhr.open('GET', fileURL, true);- xhr.responseType = type || 'arraybuffer';- xhr.onerror = reject;-- xhr.onload = () => {- const response = xhr.response || xhr.responseText;- if (response) {- resolve(response);+ stream.on('end', () => {+ const textContent = chunks.join('');+ resolve(textContent);+ // console.log('final output ' + string);+ });} else {- reject('getFileContentPromise error');+ this.fs.readFile(filePath, 'utf8', (error, content) => {+ if (error) {+ reject(error);+ } else {+ resolve(content);+ }+ });}- };- xhr.send();- });+ });++ getFileContentPromise = (fullPath: string, type: string): Promise<any> =>+ new Promise((resolve, reject) => {+ let fileURL = fullPath;+ if (fileURL.indexOf('file://') === -1) {+ fileURL = 'file://' + fileURL;+ }+ const xhr = new XMLHttpRequest();+ xhr.open('GET', fileURL, true);+ xhr.responseType = type || 'arraybuffer';+ xhr.onerror = reject;++ xhr.onload = () => {+ const response = xhr.response || xhr.responseText;+ if (response) {+ resolve(response);+ } else {+ reject('getFileContentPromise error');+ }+ };+ xhr.send();+ });saveFilePromise = (filePath: string,content: any,overwrite: boolean = true- ): Promise<any> => new Promise((resolve, reject) => {- const fileSystem = this.fs;- function saveFile(fPath, tContent, isNewFile) {- fileSystem.writeFile(fPath, tContent, 'utf8', error => {- if (error) {- reject(error);- return;- }- resolve(isNewFile);- });- }+ ): Promise<any> =>+ new Promise((resolve, reject) => {+ const fileSystem = this.fs;+ function saveFile(fPath, tContent, isNewFile) {+ fileSystem.writeFile(fPath, tContent, 'utf8', error => {+ if (error) {+ reject(error);+ return;+ }+ resolve(isNewFile);+ });+ }- this.getPropertiesPromise(filePath)- .then(entry => {- if (entry && entry.isFile && overwrite) {- saveFile(filePath, content, false);- } else {+ this.getPropertiesPromise(filePath)+ .then(entry => {+ if (entry && entry.isFile && overwrite) {+ saveFile(filePath, content, false);+ } else {+ saveFile(filePath, content, true);+ }+ return true;+ })+ .catch(error => {+ // Trying to save as new file+ console.log(+ 'Getting properties for ' + filePath + ' failed with: ' + error+ );saveFile(filePath, content, true);- }- return true;- })- .catch(error => {- // Trying to save as new file- console.log(- 'Getting properties for ' + filePath + ' failed with: ' + error- );- saveFile(filePath, content, true);- });- });+ });+ });saveTextFilePromise = (filePath: string,@@ -768,17 +786,18 @@ export default class ElectronIO {});};- moveToTrash = (files: Array<string>): Promise<any> => new Promise((resolve, reject) => {- let result = true;- files.forEach(fullPath => {- result = this.electron.shell.moveItemToTrash(fullPath);+ moveToTrash = (files: Array<string>): Promise<any> =>+ new Promise((resolve, reject) => {+ let result = true;+ files.forEach(fullPath => {+ result = this.electron.shell.moveItemToTrash(fullPath);+ });+ if (result) {+ resolve(true);+ } else {+ reject('Moving of at least one file to trash failed.');+ }});- if (result) {- resolve(true);- } else {- reject('Moving of at least one file to trash failed.');- }- });openDirectory = (dirPath: string): void => {this.electron.shell.showItemInFolder(@@ -794,7 +813,8 @@ export default class ElectronIO {this.electron.shell.openItem(filePath);};- openUrl = (url: string): void => { console.log(url)+ openUrl = (url: string): void => {+ console.log(url);this.electron.shell.openExternalSync(url);};@@ -807,7 +827,7 @@ export default class ElectronIO {}] */};- return new Promise((resolve) => {+ return new Promise(resolve => {this.remote.dialog.showOpenDialog(options, fileNames => {resolve(fileNames);});diff --git a/app/services/electron-menus.js b/app/services/electron-menus.jsindex dc00df815..80dbe6591 100644--- a/app/services/electron-menus.js+++ b/app/services/electron-menus.js@@ -36,26 +36,26 @@ export default function buildDesktopMenu(mainPageProps: Object) {ipcRenderer.on('file', (event, arg) => {// console.log('Global events: ' + arg);switch (arg) {- case 'new-text-file':- mainPageProps.toggleCreateFileDialog();- break;- case 'audio':- // console.log('showAudioRecordingDialog');- break;- case 'next-file': {- const path = mainPageProps.getNextFile();- mainPageProps.openFile(path);- mainPageProps.setLastSelectedEntry(path);- break;- }- case 'previous-file': {- const path = mainPageProps.getPrevFile();- mainPageProps.openFile(path);- mainPageProps.setLastSelectedEntry(path);- break;- }- default:- return false;+ case 'new-text-file':+ mainPageProps.toggleCreateFileDialog();+ break;+ case 'audio':+ // console.log('showAudioRecordingDialog');+ break;+ case 'next-file': {+ const path = mainPageProps.getNextFile();+ mainPageProps.openFile(path);+ mainPageProps.setLastSelectedEntry(path);+ break;+ }+ case 'previous-file': {+ const path = mainPageProps.getPrevFile();+ mainPageProps.openFile(path);+ mainPageProps.setLastSelectedEntry(path);+ break;+ }+ default:+ return false;}});@@ -169,7 +169,7 @@ export default function buildDesktopMenu(mainPageProps: Object) {label: i18n.t('core:selectAll'),accelerator: 'CmdOrCtrl+A',role: 'selectall'- },+ }]},{@@ -250,7 +250,7 @@ export default function buildDesktopMenu(mainPageProps: Object) {click: () => {mainPageProps.toggleSettingsDialog();}- },+ }]},{@@ -347,7 +347,7 @@ export default function buildDesktopMenu(mainPageProps: Object) {click: () => {mainPageProps.toggleAboutDialog();}- },+ }]}];diff --git a/app/services/i18n.js b/app/services/i18n.jsindex 15122cd38..37db601c5 100644--- a/app/services/i18n.js+++ b/app/services/i18n.js@@ -24,220 +24,340 @@ import en from '../locales/en/core.json';function loadLocales(url, options, callback, data) {switch (url) {- case 'ar': {- import('../locales/ar/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'bg': {- import('../locales/bg/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'ca': {- import('../locales/ca/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'cs': {- import('../locales/cs/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'da_DK': {- import('../locales/da_DK/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'de_DE': {- import('../locales/de_DE/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'el': {- import('../locales/el/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'eo': {- import('../locales/eo/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'es': {- import('../locales/es/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'fa': {- import('../locales/fa/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'fr': {- import('../locales/fr/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'hu': {- import('../locales/hu/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'hy': {- import('../locales/hy/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'id_ID': {- import('../locales/id_ID/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'it': {- import('../locales/it/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'ja': {- import('../locales/ja/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'ko': {- import('../locales/ko/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'mt': {- import('../locales/mt/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'nl_NL': {- import('../locales/nl_NL/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'pl': {- import('../locales/pl/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'pt_BR': {- import('../locales/pt_BR/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'pt_PT': {- import('../locales/pt_PT/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'ru': {- import('../locales/ru/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'sk_SK': {- import('../locales/sk_SK/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'sv': {- import('../locales/sv/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'tr': {- import('../locales/tr/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'uk': {- import('../locales/uk/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'vi': {- import('../locales/vi/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'zh_CN': {- import('../locales/zh_CN/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- case 'zh_TW': {- import('../locales/zh_TW/core.json').then(locale => {- callback(locale, { status: '200' });- return true;- }).catch(() => { console.log('Error loading ' + url + ' locale.'); });- break;- }- default: {- callback(en, { status: '200' });- break;- }+ case 'ar': {+ import('../locales/ar/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'bg': {+ import('../locales/bg/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'ca': {+ import('../locales/ca/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'cs': {+ import('../locales/cs/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'da_DK': {+ import('../locales/da_DK/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'de_DE': {+ import('../locales/de_DE/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'el': {+ import('../locales/el/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'eo': {+ import('../locales/eo/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'es': {+ import('../locales/es/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'fa': {+ import('../locales/fa/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'fr': {+ import('../locales/fr/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'hu': {+ import('../locales/hu/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'hy': {+ import('../locales/hy/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'id_ID': {+ import('../locales/id_ID/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'it': {+ import('../locales/it/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'ja': {+ import('../locales/ja/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'ko': {+ import('../locales/ko/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'mt': {+ import('../locales/mt/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'nl_NL': {+ import('../locales/nl_NL/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'pl': {+ import('../locales/pl/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'pt_BR': {+ import('../locales/pt_BR/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'pt_PT': {+ import('../locales/pt_PT/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'ru': {+ import('../locales/ru/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'sk_SK': {+ import('../locales/sk_SK/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'sv': {+ import('../locales/sv/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'tr': {+ import('../locales/tr/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'uk': {+ import('../locales/uk/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'vi': {+ import('../locales/vi/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'zh_CN': {+ import('../locales/zh_CN/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ case 'zh_TW': {+ import('../locales/zh_TW/core.json')+ .then(locale => {+ callback(locale, { status: '200' });+ return true;+ })+ .catch(() => {+ console.log('Error loading ' + url + ' locale.');+ });+ break;+ }+ default: {+ callback(en, { status: '200' });+ break;+ }}}diff --git a/app/services/onlineListener.js b/app/services/onlineListener.jsindex 632e57309..3a87af915 100644--- a/app/services/onlineListener.js+++ b/app/services/onlineListener.js@@ -19,7 +19,7 @@import { actions as CommonActions } from '../reducers/app';-export default function (dispatch) {+export default function(dispatch) {window.addEventListener('online', updateOnlineStatus);window.addEventListener('offline', updateOnlineStatus);diff --git a/app/services/platform-io.js b/app/services/platform-io.jsindex e97261aa8..c4537155c 100644--- a/app/services/platform-io.js+++ b/app/services/platform-io.js@@ -35,19 +35,23 @@ if (AppConfig.isElectron) {let objectStoreAPI;export default class PlatformIO {- static enableObjectStoreSupport = (objectStoreConfig: Object): Promise<any> => new Promise((resolve, reject) => {- if (Pro && Pro.ObjectStoreIO) {- objectStoreAPI = new Pro.ObjectStoreIO();- objectStoreAPI.configure(objectStoreConfig).then(() => {- resolve();- return true;- }).catch((e) => {- reject(e);- });- } else {- reject('ObjectStore support available in the PRO version');- }- });+ static enableObjectStoreSupport = (objectStoreConfig: Object): Promise<any> =>+ new Promise((resolve, reject) => {+ if (Pro && Pro.ObjectStoreIO) {+ objectStoreAPI = new Pro.ObjectStoreIO();+ objectStoreAPI+ .configure(objectStoreConfig)+ .then(() => {+ resolve();+ return true;+ })+ .catch(e => {+ reject(e);+ });+ } else {+ reject('ObjectStore support available in the PRO version');+ }+ });static disableObjectStoreSupport = (): void => {objectStoreAPI = undefined;@@ -69,7 +73,7 @@ export default class PlatformIO {} else {console.log('initTrayMenu not supported');}- }+ };static isWorkerAvailable = (): boolean => nativeAPI.isWorkerAvailable();@@ -79,7 +83,7 @@ export default class PlatformIO {} else {console.log('setZoomFactorElectron not supported');}- }+ };static setGlobalShortcuts = globalShortcutsEnabled => {if (nativeAPI.setGlobalShortcuts) {@@ -87,7 +91,7 @@ export default class PlatformIO {} else {console.log('setGlobalShortcuts not supported');}- }+ };static showMainWindow = (): void => nativeAPI.showMainWindow();@@ -114,7 +118,10 @@ export default class PlatformIO {static createDirectoryTree = (directoryPath: string): Object =>nativeAPI.createDirectoryTree(directoryPath);- static createDirectoryIndexInWorker = (directoryPath: string, extractText: boolean): Promise<any> =>+ static createDirectoryIndexInWorker = (+ directoryPath: string,+ extractText: boolean+ ): Promise<any> =>nativeAPI.createDirectoryIndexInWorker(directoryPath, extractText);static createThumbnailsInWorker = (@@ -172,7 +179,9 @@ export default class PlatformIO {): Promise<any> => {if (objectStoreAPI) {// return objectStoreAPI.renameDirectoryPromise(dirPath, newDirName);- return Promise.reject('Renaming directories not supported on this platform');+ return Promise.reject(+ 'Renaming directories not supported on this platform'+ );}return nativeAPI.renameDirectoryPromise(dirPath, newDirName);};@@ -230,7 +239,10 @@ export default class PlatformIO {return nativeAPI.saveBinaryFilePromise(filePath, content, overwrite);};- static deleteFilePromise = (path: string, useTrash?: boolean): Promise<any> => {+ static deleteFilePromise = (+ path: string,+ useTrash?: boolean+ ): Promise<any> => {if (objectStoreAPI) {return objectStoreAPI.deleteFilePromise(path, useTrash);}@@ -243,7 +255,9 @@ export default class PlatformIO {): Promise<any> => {if (objectStoreAPI) {// return objectStoreAPI.deleteDirectoryPromise(path, useTrash);- return Promise.reject('Deleting directories not supported on this platform');+ return Promise.reject(+ 'Deleting directories not supported on this platform'+ );}return nativeAPI.deleteDirectoryPromise(path, useTrash);};diff --git a/app/services/search.js b/app/services/search.jsindex 3f6a3b052..61c6c24b0 100644--- a/app/services/search.js+++ b/app/services/search.js@@ -26,7 +26,18 @@ import { Pro } from '../pro';export const FileTypeGroups = {any: [''],- images: ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'tif', 'tiff', 'ico', 'webp', 'psd'],+ images: [+ 'jpg',+ 'jpeg',+ 'png',+ 'gif',+ 'bmp',+ 'tif',+ 'tiff',+ 'ico',+ 'webp',+ 'psd'+ ],notes: ['md', 'mdown', 'txt', 'html'],documents: ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'odt', 'ods'],audio: ['ogg', 'mp3', 'wav', 'wave'],@@ -36,7 +47,7 @@ export const FileTypeGroups = {ebooks: ['epub', 'mobi', 'azw', 'prc', 'azw1', 'azw3', 'azw4', 'azw8', 'azk'],folders: ['folders'],files: ['files'],- untagged: ['untagged'],+ untagged: ['untagged']};export type SearchQuery = {@@ -57,7 +68,6 @@ export type SearchQuery = {maxSearchResults?: number};-// id, name, isFile, tags, extension, size, lmdt, path// index[?size > '9000' && contains(path, 'Apple')]@@ -99,22 +109,28 @@ const fuseOptions = {tokenize: true,maxPatternLength: 32,minMatchCharLength: 1,- keys: [{- name: 'name',- weight: 0.4- }, {- name: 'description',- weight: 0.4- }, {- name: 'textContent',- weight: 0.4- }, {- name: 'tags',- weight: 0.3- }, {- name: 'path', // TODO ignore .ts folder, should not be in the index- weight: 0.1- }]+ keys: [+ {+ name: 'name',+ weight: 0.4+ },+ {+ name: 'description',+ weight: 0.4+ },+ {+ name: 'textContent',+ weight: 0.4+ },+ {+ name: 'tags',+ weight: 0.3+ },+ {+ name: 'path', // TODO ignore .ts folder, should not be in the index+ weight: 0.1+ }+ ]};// Constructs the string for the JMESPath search query. We first filter for all ORTags, then continuously pipe the result in to the@@ -134,7 +150,7 @@ function constructjmespathQuery(searchQuery: SearchQuery): string {searchQuery.tagsOR.forEach(tag => {const cleanedTagTitle = tag.title.trim().toLowerCase();if (cleanedTagTitle.length > 0) {- jmespathQuery += 'title==\'' + cleanedTagTitle + '\' || ';+ jmespathQuery += "title=='" + cleanedTagTitle + "' || ";}return true;});@@ -142,37 +158,43 @@ function constructjmespathQuery(searchQuery: SearchQuery): string {if (ANDtagsExist) {if (jmespathQuery.endsWith(' || ')) {- jmespathQuery = jmespathQuery.substring(0, jmespathQuery.length - 4) + ']] | [? tags[? ';+ jmespathQuery =+ jmespathQuery.substring(0, jmespathQuery.length - 4) ++ ']] | [? tags[? ';} else {jmespathQuery += ' tags[? ';}searchQuery.tagsAND.forEach(tag => {const cleanedTagTitle = tag.title.trim().toLowerCase();if (cleanedTagTitle.length > 0) {- jmespathQuery += 'title==\'' + cleanedTagTitle + '\']] | [? tags[? ';+ jmespathQuery += "title=='" + cleanedTagTitle + "']] | [? tags[? ";}});}if (NOTtagsExist) {if (jmespathQuery.endsWith(' || ')) {- jmespathQuery = jmespathQuery.substring(0, jmespathQuery.length - 4) + ']] | [?!(tags[? ';+ jmespathQuery =+ jmespathQuery.substring(0, jmespathQuery.length - 4) ++ ']] | [?!(tags[? ';} else if (jmespathQuery.endsWith('[? tags[? ')) {- jmespathQuery = jmespathQuery.substring(0, jmespathQuery.length - 10) + '[?!(tags[? ';+ jmespathQuery =+ jmespathQuery.substring(0, jmespathQuery.length - 10) + '[?!(tags[? ';} else {jmespathQuery += '!(tags[? ';}searchQuery.tagsNOT.forEach(tag => {const cleanedTagTitle = tag.title.trim().toLowerCase();if (cleanedTagTitle.length > 0) {- jmespathQuery += 'title==\'' + cleanedTagTitle + '\'])] | [?!(tags[? ';+ jmespathQuery += "title=='" + cleanedTagTitle + "'])] | [?!(tags[? ";}return true;});}if (jmespathQuery.endsWith(' || ')) {- jmespathQuery = jmespathQuery.substring(0, jmespathQuery.length - 4) + ']]';+ jmespathQuery =+ jmespathQuery.substring(0, jmespathQuery.length - 4) + ']]';} else if (jmespathQuery.endsWith(' | [? tags[? ')) {jmespathQuery = jmespathQuery.substring(0, jmespathQuery.length - 13);} else if (jmespathQuery.endsWith(' | [?!(tags[? ')) {@@ -180,10 +202,14 @@ function constructjmespathQuery(searchQuery: SearchQuery): string {}}-- const extensionQuery = Pro ? Pro.Search.constructFileTypeQuery(searchQuery) : '';+ const extensionQuery = Pro+ ? Pro.Search.constructFileTypeQuery(searchQuery)+ : '';if (extensionQuery.length > 0) {- jmespathQuery = (jmespathQuery.length > 0) ? jmespathQuery + ' | ' + extensionQuery : extensionQuery;+ jmespathQuery =+ jmespathQuery.length > 0+ ? jmespathQuery + ' | ' + extensionQuery+ : extensionQuery;}if (jmespathQuery.length > 0) {@@ -198,10 +224,10 @@ function prepareIndex(index: Array<Object>) {if (Pro && Pro.Search && Pro.Search.prepareIndex) {resultIndex = Pro.Search.prepareIndex(index);} else {- resultIndex = index.map((entry) => {+ resultIndex = index.map(entry => {const tags = [...entry.tags];if (tags && tags.length) {- tags.map((tag) => {+ tags.map(tag => {tag.title = tag.title.toLowerCase();return tag;});@@ -217,55 +243,64 @@ function prepareIndex(index: Array<Object>) {}export default class Search {- static searchLocationIndex = (locationContent: Array<Object>, searchQuery: SearchQuery): Promise<Array<Object> | []> => new Promise((resolve) => {- console.time('searchtime');- const jmespathQuery = constructjmespathQuery(searchQuery);- let results = prepareIndex(locationContent);- let searched = false;+ static searchLocationIndex = (+ locationContent: Array<Object>,+ searchQuery: SearchQuery+ ): Promise<Array<Object> | []> =>+ new Promise(resolve => {+ console.time('searchtime');+ const jmespathQuery = constructjmespathQuery(searchQuery);+ let results = prepareIndex(locationContent);+ let searched = false;- // Limiting the search to current folder only (with sub-folders)- if (searchQuery.searchBoxing === 'folder') {- results = results.filter(entry => entry.path.startsWith(searchQuery.currentDirectory));- }+ // Limiting the search to current folder only (with sub-folders)+ if (searchQuery.searchBoxing === 'folder') {+ results = results.filter(entry =>+ entry.path.startsWith(searchQuery.currentDirectory)+ );+ }- if (jmespathQuery) {- const resultCount = results.length;- console.log('jmespath query: ' + jmespathQuery);- console.time('jmespath');- results = jmespath.search({ index: results }, jmespathQuery);- console.timeEnd('jmespath');- console.log('jmespath results: ' + results.length);- searched = searched || (results.length < resultCount);- }+ if (jmespathQuery) {+ const resultCount = results.length;+ console.log('jmespath query: ' + jmespathQuery);+ console.time('jmespath');+ results = jmespath.search({ index: results }, jmespathQuery);+ console.timeEnd('jmespath');+ console.log('jmespath results: ' + results.length);+ searched = searched || results.length < resultCount;+ }- if (Pro && Pro.Search.filterIndex) {- const resultCount = results.length;- results = Pro.Search.filterIndex(results, searchQuery);- searched = searched || (results.length < resultCount);- }+ if (Pro && Pro.Search.filterIndex) {+ const resultCount = results.length;+ results = Pro.Search.filterIndex(results, searchQuery);+ searched = searched || results.length < resultCount;+ }- if (searchQuery.textQuery && searchQuery.textQuery.length > 1) {- const resultCount = results.length;- console.log('fuse query: ' + searchQuery.textQuery);- console.time('fuse');- const fuse = new Fuse(results, fuseOptions);- results = fuse.search(searchQuery.textQuery);- console.timeEnd('fuse');- searched = searched || (results.length < resultCount);- }+ if (searchQuery.textQuery && searchQuery.textQuery.length > 1) {+ const resultCount = results.length;+ console.log('fuse query: ' + searchQuery.textQuery);+ console.time('fuse');+ const fuse = new Fuse(results, fuseOptions);+ results = fuse.search(searchQuery.textQuery);+ console.timeEnd('fuse');+ searched = searched || results.length < resultCount;+ }- if (searched) {- console.log('Results found: ' + results.length);- if (searchQuery.maxSearchResults && results.length >= searchQuery.maxSearchResults) {- results = results.slice(0, searchQuery.maxSearchResults);+ if (searched) {+ console.log('Results found: ' + results.length);+ if (+ searchQuery.maxSearchResults &&+ results.length >= searchQuery.maxSearchResults+ ) {+ results = results.slice(0, searchQuery.maxSearchResults);+ }+ console.log('Results send: ' + results.length);+ console.timeEnd('searchtime');+ resolve(results);+ return true;}- console.log('Results send: ' + results.length);+ results = [];console.timeEnd('searchtime');resolve(results);- return true;- }- results = [];- console.timeEnd('searchtime');- resolve(results);- });+ });}diff --git a/app/services/thumbsgenerator.js b/app/services/thumbsgenerator.jsindex c953aafb1..9a4125d5b 100644--- a/app/services/thumbsgenerator.js+++ b/app/services/thumbsgenerator.js@@ -86,15 +86,21 @@ const maxFileSize = 30 * 1024 * 1024;function saveThumbnailPromise(filePath, dataURL) {return new Promise((resolve, reject) => {- if (!dataURL || dataURL.length < 7) { // data:,+ if (!dataURL || dataURL.length < 7) {+ // data:,return reject('Invalid dataURL');}const baseString = dataURL.split(',').pop();const content = base64ToArrayBuffer(baseString);PlatformIO.saveBinaryFilePromise(filePath, content, true).then(() => resolve(filePath))- .catch((error) => {- console.warn('Saving thumbnail for ' + filePath + ' failed with ' + JSON.stringify(error));+ .catch(error => {+ console.warn(+ 'Saving thumbnail for ' ++ filePath ++ ' failed with ' ++ JSON.stringify(error)+ );return reject('Saving tmb failed for: ' + filePath);});});@@ -103,55 +109,80 @@ function saveThumbnailPromise(filePath, dataURL) {function getThumbFileLocation(filePath: string) {const containingFolder = extractContainingDirectoryPath(filePath);const metaFolder = getMetaDirectoryPath(containingFolder);- return metaFolder + AppConfig.dirSeparator + extractFileName(filePath) + AppConfig.thumbFileExt;+ return (+ metaFolder ++ AppConfig.dirSeparator ++ extractFileName(filePath) ++ AppConfig.thumbFileExt+ );}-export function getThumbnailURLPromise(filePath: string): Promise<{ filePath: string }> {- return new Promise((resolve) => {- PlatformIO.getPropertiesPromise(filePath).then((origStats) => {- const thumbFilePath = getThumbFileLocation(filePath);- PlatformIO.getPropertiesPromise(thumbFilePath).then((stats) => {- if (stats) { // Thumbnail exists- if (origStats.lmdt > stats.lmdt) { // Checking if is up to date- createThumbnailPromise(filePath, origStats.size, thumbFilePath).then((tmbPath) => resolve({ filePath, tmbPath })).catch((err) => {- console.warn('Thumb generation failed ' + err);- resolve({ filePath, tmbPath: thumbFilePath });- });- } else { // Tmb up to date- resolve({ filePath });- }- } else {- // Thumbnail does not exists- createThumbnailPromise(filePath, origStats.size, thumbFilePath).then((tmbPath) => resolve({ filePath, tmbPath })).catch(err => {- console.warn('Thumb generation failed ' + err);+export function getThumbnailURLPromise(+ filePath: string+): Promise<{ filePath: string }> {+ return new Promise(resolve => {+ PlatformIO.getPropertiesPromise(filePath)+ .then(origStats => {+ const thumbFilePath = getThumbFileLocation(filePath);+ PlatformIO.getPropertiesPromise(thumbFilePath)+ .then(stats => {+ if (stats) {+ // Thumbnail exists+ if (origStats.lmdt > stats.lmdt) {+ // Checking if is up to date+ createThumbnailPromise(filePath, origStats.size, thumbFilePath)+ .then(tmbPath => resolve({ filePath, tmbPath }))+ .catch(err => {+ console.warn('Thumb generation failed ' + err);+ resolve({ filePath, tmbPath: thumbFilePath });+ });+ } else {+ // Tmb up to date+ resolve({ filePath });+ }+ } else {+ // Thumbnail does not exists+ createThumbnailPromise(filePath, origStats.size, thumbFilePath)+ .then(tmbPath => resolve({ filePath, tmbPath }))+ .catch(err => {+ console.warn('Thumb generation failed ' + err);+ resolve({ filePath });+ });+ }+ return true;+ })+ .catch(err => {+ console.warn('Error getting tmb properties ' + err);resolve({ filePath });});- }return true;- }).catch(err => {- console.warn('Error getting tmb properties ' + err);+ })+ .catch(err => {+ console.warn('Error getting file properties ' + err);resolve({ filePath });});- return true;- }).catch(err => {- console.warn('Error getting file properties ' + err);- resolve({ filePath });- });});}-export function replaceThumbnailURLPromise(filePath: string, thumbFilePath: string): Promise<any> {- return new Promise((resolve) => {- PlatformIO.getPropertiesPromise(filePath).then((origStats) => {- createThumbnailPromise(filePath, origStats.size, thumbFilePath).then((tmbPath) => resolve({ filePath, tmbPath })).catch((err) => {- console.warn('Thumb generation failed ' + err);- resolve({ filePath, tmbPath: thumbFilePath });+export function replaceThumbnailURLPromise(+ filePath: string,+ thumbFilePath: string+): Promise<any> {+ return new Promise(resolve => {+ PlatformIO.getPropertiesPromise(filePath)+ .then(origStats => {+ createThumbnailPromise(filePath, origStats.size, thumbFilePath)+ .then(tmbPath => resolve({ filePath, tmbPath }))+ .catch(err => {+ console.warn('Thumb generation failed ' + err);+ resolve({ filePath, tmbPath: thumbFilePath });+ });+ return true;+ })+ .catch(err => {+ console.warn('Error getting file properties ' + err);+ resolve({ filePath });});- return true;- }).catch(err => {- console.warn('Error getting file properties ' + err);- resolve({ filePath });- });});}@@ -160,7 +191,7 @@ export function createThumbnailPromise(fileSize: number,thumbFilePath: string): Promise<any> {- return new Promise(async (resolve) => {+ return new Promise(async resolve => {const metaDirectory = extractContainingDirectoryPath(thumbFilePath);const fileDirectory = extractContainingDirectoryPath(filePath);const normalizedFileDirectory = normalizePath(fileDirectory);@@ -173,30 +204,29 @@ export function createThumbnailPromise(await PlatformIO.createDirectoryPromise(metaDirectory);}- generateThumbnailPromise(filePath, fileSize).then((dataURL) => {- if (dataURL && dataURL.length) {- saveThumbnailPromise(thumbFilePath, dataURL)- .then(() => resolve(thumbFilePath))- .catch((err) => {- console.warn('Thumb saving failed ' + err + ' for ' + filePath);- resolve();- });+ generateThumbnailPromise(filePath, fileSize)+ .then(dataURL => {+ if (dataURL && dataURL.length) {+ saveThumbnailPromise(thumbFilePath, dataURL)+ .then(() => resolve(thumbFilePath))+ .catch(err => {+ console.warn('Thumb saving failed ' + err + ' for ' + filePath);+ resolve();+ });+ return true;+ }+ resolve();return true;- }- resolve();- return true;- }).catch((err) => {- console.warn('Thumb generation failed ' + err + ' for ' + filePath);- resolve();- });+ })+ .catch(err => {+ console.warn('Thumb generation failed ' + err + ' for ' + filePath);+ resolve();+ });return true;});}-export function generateThumbnailPromise(- fileURL: string,- fileSize: number-) {+export function generateThumbnailPromise(fileURL: string, fileSize: number) {const ext = extractFileExtension(fileURL).toLowerCase();if (supportedImgs.indexOf(ext) >= 0) {@@ -219,7 +249,11 @@ export function generateThumbnailPromise(return Pro.ThumbsGenerator.generateTextThumbnail(fileURL, maxSize);} else if (Pro && supportedContainers.indexOf(ext) >= 0) {if (fileSize && fileSize < maxFileSize) {- return Pro.ThumbsGenerator.generateZipContainerImageThumbnail(fileURL, maxSize, supportedImgs);+ return Pro.ThumbsGenerator.generateZipContainerImageThumbnail(+ fileURL,+ maxSize,+ supportedImgs+ );}} else if (supportedVideos.indexOf(ext) >= 0) {if (Pro) {@@ -235,7 +269,7 @@ function generateDefaultThumbnail() {}function generateImageThumbnail(fileURL): Promise<string> {- return new Promise((resolve) => {+ return new Promise(resolve => {let canvas: HTMLCanvasElement = document.createElement('canvas');const ctx = canvas.getContext('2d');let img: HTMLImageElement = new Image();@@ -243,16 +277,17 @@ function generateImageThumbnail(fileURL): Promise<string> {const errorHandler = err => {console.warn('Error while generating thumbnail for: ' +- fileURL +- ' - ' +- JSON.stringify(err)+ fileURL ++ ' - ' ++ JSON.stringify(err));resolve('');};img.crossOrigin = 'anonymous';img.onload = () => {- EXIF.getData(img, function () { // eslint-disable-line+ EXIF.getData(img, function() {+ // eslint-disable-line// TODO Use EXIF only for jpegsconst orientation = EXIF.getTag(this, 'Orientation');/*@@ -267,19 +302,19 @@ function generateImageThumbnail(fileURL): Promise<string> {*/let angleInRadians;switch (orientation) {- case 8:- angleInRadians = 270 * (Math.PI / 180);- break;- case 3:- angleInRadians = 180 * (Math.PI / 180);- break;- case 6:- angleInRadians = 90 * (Math.PI / 180);- break;- case 1:- // ctx.rotate(0);- break;- default:+ case 8:+ angleInRadians = 270 * (Math.PI / 180);+ break;+ case 3:+ angleInRadians = 180 * (Math.PI / 180);+ break;+ case 6:+ angleInRadians = 90 * (Math.PI / 180);+ break;+ case 1:+ // ctx.rotate(0);+ break;+ default:// ctx.rotate(0);}if (img.width >= img.height) {@@ -313,7 +348,7 @@ function generateImageThumbnail(fileURL): Promise<string> {}function generateVideoThumbnail(fileURL): Promise<string> {- return new Promise((resolve) => {+ return new Promise(resolve => {let canvas = document.createElement('canvas');const ctx = canvas.getContext('2d');let img = new Image();@@ -323,9 +358,9 @@ function generateVideoThumbnail(fileURL): Promise<string> {const errorHandler = err => {console.warn('Error while generating thumbnail for: ' +- fileURL +- ' - ' +- JSON.stringify(err)+ fileURL ++ ' - ' ++ JSON.stringify(err));resolve('');};diff --git a/app/services/utils-io.js b/app/services/utils-io.jsindex c1edf3af2..b2d6c8a3c 100644--- a/app/services/utils-io.js+++ b/app/services/utils-io.js@@ -27,7 +27,8 @@ import {cleanTrailingDirSeparator,getMetaDirectoryPath,getMetaFileLocationForFile,- getMetaFileLocationForDir, extractContainingDirectoryPath+ getMetaFileLocationForDir,+ extractContainingDirectoryPath} from '../utils/paths';// import { formatDateTime4Tag } from '../utils/misc';import versionMeta from '../version.json';@@ -70,7 +71,10 @@ export function enhanceEntry(entry: any): FileSystemEntry {sidecarDescription = entry.meta.description || '';sidecarColor = entry.meta.color || '';sidecarTags = entry.meta.tags || [];- sidecarTags.map((tag) => { tag.type = 'sidecar'; return true; });+ sidecarTags.map(tag => {+ tag.type = 'sidecar';+ return true;+ });uuid = entry.meta.uuid || undefined;}const enhancedEntry = {@@ -91,9 +95,13 @@ export function enhanceEntry(entry: any): FileSystemEntry {return enhancedEntry;}-export function createDirectoryIndex(directoryPath: string, extractText: boolean = false): Promise<Array<Object>> {+export function createDirectoryIndex(+ directoryPath: string,+ extractText: boolean = false+): Promise<Array<Object>> {const dirPath = cleanTrailingDirSeparator(directoryPath);- if (PlatformIO.isWorkerAvailable() && !PlatformIO.haveObjectStoreSupport()) { // Start indexing in worker if not in the object store mode+ if (PlatformIO.isWorkerAvailable() && !PlatformIO.haveObjectStoreSupport()) {+ // Start indexing in worker if not in the object store modereturn PlatformIO.createDirectoryIndexInWorker(dirPath, extractText);}@@ -102,35 +110,48 @@ export function createDirectoryIndex(directoryPath: string, extractText: booleanconst directoryIndex = [];let counter = 0;console.time('createDirectoryIndex');- walkDirectory(dirPath, {- recursive: true,- skipMetaFolder: true,- skipDotHiddenFolder: true,- extractText- }, (fileEntry) => {- counter += 1;- if (counter > AppConfig.indexerLimit) {- console.warn('Walk canceled by ' + AppConfig.indexerLimit);- window.walkCanceled = true;- }- directoryIndex.push(enhanceEntry(fileEntry));- }, (directoryEntry) => {- if (directoryEntry.name !== AppConfig.metaFolder) {+ walkDirectory(+ dirPath,+ {+ recursive: true,+ skipMetaFolder: true,+ skipDotHiddenFolder: true,+ extractText+ },+ fileEntry => {counter += 1;- directoryIndex.push(enhanceEntry(directoryEntry));+ if (counter > AppConfig.indexerLimit) {+ console.warn('Walk canceled by ' + AppConfig.indexerLimit);+ window.walkCanceled = true;+ }+ directoryIndex.push(enhanceEntry(fileEntry));+ },+ directoryEntry => {+ if (directoryEntry.name !== AppConfig.metaFolder) {+ counter += 1;+ directoryIndex.push(enhanceEntry(directoryEntry));+ }}- }).then(() => { // entries - can be used for further processing- window.walkCanceled = false;- console.log('Directory index created ' + dirPath + ' containing ' + directoryIndex.length);- console.timeEnd('createDirectoryIndex');- resolve(directoryIndex);- return true;- }).catch((err) => {- window.walkCanceled = false;- console.timeEnd('createDirectoryIndex');- console.warn('Error creating index: ' + err);- reject(err);- });+ )+ .then(() => {+ // entries - can be used for further processing+ window.walkCanceled = false;+ console.log(+ 'Directory index created ' ++ dirPath ++ ' containing ' ++ directoryIndex.length+ );+ console.timeEnd('createDirectoryIndex');+ resolve(directoryIndex);+ return true;+ })+ .catch(err => {+ window.walkCanceled = false;+ console.timeEnd('createDirectoryIndex');+ console.warn('Error creating index: ' + err);+ reject(err);+ });}, 2000);});}@@ -149,44 +170,61 @@ export function walkDirectory(extractText: false,...options};- return PlatformIO.listDirectoryPromise(path, false, mergedOptions.extractText).then((entries) => {- if (window.walkCanceled) {- return false;- }- return Promise.all(entries.map((entry) => {+ return PlatformIO.listDirectoryPromise(path, false, mergedOptions.extractText)+ .then(entries => {if (window.walkCanceled) {return false;}+ return Promise.all(+ entries.map(entry => {+ if (window.walkCanceled) {+ return false;+ }- if (entry.isFile) {- if (fileCallback) {- fileCallback(entry);- }- return entry;- }+ if (entry.isFile) {+ if (fileCallback) {+ fileCallback(entry);+ }+ return entry;+ }- if (dirCallback) {- dirCallback(entry);- }+ if (dirCallback) {+ dirCallback(entry);+ }- if (mergedOptions.recursive) {- if (mergedOptions.skipDotHiddenFolder && entry.name.startsWith('.')) {- return entry;- }- if (mergedOptions.skipMetaFolder && entry.name === AppConfig.metaFolder) {+ if (mergedOptions.recursive) {+ if (+ mergedOptions.skipDotHiddenFolder &&+ entry.name.startsWith('.')+ ) {+ return entry;+ }+ if (+ mergedOptions.skipMetaFolder &&+ entry.name === AppConfig.metaFolder+ ) {+ return entry;+ }+ return walkDirectory(+ entry.path,+ mergedOptions,+ fileCallback,+ dirCallback+ );+ }return entry;- }- return walkDirectory(entry.path, mergedOptions, fileCallback, dirCallback);- }- return entry;- }));- }).catch((err) => {- console.warn('Error walking directory ' + err);- return err;- });+ })+ );+ })+ .catch(err => {+ console.warn('Error walking directory ' + err);+ return err;+ });}-export async function getAllPropertiesPromise(entryPath: string): Promise<FileSystemEntry> {+export async function getAllPropertiesPromise(+ entryPath: string+): Promise<FileSystemEntry> {const entryProps = await PlatformIO.getPropertiesPromise(entryPath);let metaFilePath;if (entryProps.isFile) {@@ -235,7 +273,7 @@ export function openLinkExternally(uri: string) {export function deleteFilesPromise(filePathList: Array<string>) {const fileDeletionPromises = [];- filePathList.forEach((filePath) => {+ filePathList.forEach(filePath => {fileDeletionPromises.push(PlatformIO.deleteFilePromise(filePath));});return Promise.all(fileDeletionPromises);@@ -243,26 +281,31 @@ export function deleteFilesPromise(filePathList: Array<string>) {export function renameFilesPromise(renameJobs: Array<Array<string>>) {const fileRenamePromises = [];- renameJobs.forEach((renameJob) => {- fileRenamePromises.push(PlatformIO.renameFilePromise(renameJob[0], renameJob[1]));+ renameJobs.forEach(renameJob => {+ fileRenamePromises.push(+ PlatformIO.renameFilePromise(renameJob[0], renameJob[1])+ );});return Promise.all(fileRenamePromises);}export function copyFilesPromise(copyJobs: Array<Array<string>>) {const ioJobPromises = [];- copyJobs.forEach((copyJob) => {+ copyJobs.forEach(copyJob => {ioJobPromises.push(PlatformIO.copyFilePromise(copyJob[0], copyJob[1]));});return Promise.all(ioJobPromises);}-export async function loadSubFolders(path: string, loadHidden: boolean = false) {+export async function loadSubFolders(+ path: string,+ loadHidden: boolean = false+) {const folderContent = await PlatformIO.listDirectoryPromise(path, true);const subfolders = [];let i = 0;let isHidden = false;- folderContent.map((entry) => {+ folderContent.map(entry => {if (!entry.isFile) {isHidden = entry.name.startsWith('.');if (isHidden) {@@ -298,7 +341,11 @@ export async function loadSubFolders(path: string, loadHidden: boolean = false)return subfolders;}-export function generateFileName(fileName: string, tags: Array<string>, tagDelimiter: string) {+export function generateFileName(+ fileName: string,+ tags: Array<string>,+ tagDelimiter: string+) {let tagsString = '';const prefixTagContainer = AppConfig.prefixTagContainer;// Creating the string will all the tags by more that 0 tags@@ -321,28 +368,45 @@ export function generateFileName(fileName: string, tags: Array<string>, tagDelimconst beginTagContainer = fileName.indexOf(AppConfig.beginTagContainer);const endTagContainer = fileName.indexOf(AppConfig.endTagContainer);const lastDotPosition = fileName.lastIndexOf('.');- if (beginTagContainer < 0 || endTagContainer < 0 || beginTagContainer >= endTagContainer) {+ if (+ beginTagContainer < 0 ||+ endTagContainer < 0 ||+ beginTagContainer >= endTagContainer+ ) {// Filename does not contains tags.if (lastDotPosition < 0) {// File does not have an extensionnewFileName = fileName.trim() + tagsString;} else {// File has an extension- newFileName = fileName.substring(0, lastDotPosition).trim() + prefixTagContainer + tagsString + '.' + fileExt;+ newFileName =+ fileName.substring(0, lastDotPosition).trim() ++ prefixTagContainer ++ tagsString ++ '.' ++ fileExt;}} else {// File does not have an extension- newFileName = fileName.substring(0, beginTagContainer).trim() + prefixTagContainer + tagsString + fileName.substring(endTagContainer + 1, fileName.length).trim();+ newFileName =+ fileName.substring(0, beginTagContainer).trim() ++ prefixTagContainer ++ tagsString ++ fileName.substring(endTagContainer + 1, fileName.length).trim();}if (newFileName.length < 1) {throw 'Generated filename is invalid';}// Removing double prefix- newFileName = newFileName.split(prefixTagContainer + '' + prefixTagContainer).join(prefixTagContainer);+ newFileName = newFileName+ .split(prefixTagContainer + '' + prefixTagContainer)+ .join(prefixTagContainer);return newFileName;}-export async function loadMetaDataPromise(path: string): Promise<FileSystemEntryMeta> {+export async function loadMetaDataPromise(+ path: string+): Promise<FileSystemEntryMeta> {const entryProperties = await PlatformIO.getPropertiesPromise(path);let metaDataObject;if (entryProperties.isFile) {@@ -373,7 +437,10 @@ export async function loadMetaDataPromise(path: string): Promise<FileSystemEntryreturn metaDataObject;}-export async function saveMetaDataPromise(path: string, metaData: Object): Promise<any> {+export async function saveMetaDataPromise(+ path: string,+ metaData: Object+): Promise<any> {const entryProperties = await PlatformIO.getPropertiesPromise(path);let metaFilePath;let newFsEntryMeta;@@ -381,19 +448,23 @@ export async function saveMetaDataPromise(path: string, metaData: Object): Promiif (entryProperties.isFile) {metaFilePath = getMetaFileLocationForFile(path);// check and create meta folder if not exist- await PlatformIO.createDirectoryPromise(extractContainingDirectoryPath(metaFilePath));+ await PlatformIO.createDirectoryPromise(+ extractContainingDirectoryPath(metaFilePath)+ );newFsEntryMeta = {...metaData,appName: versionMeta.name,appVersionUpdated: versionMeta.version,- lastUpdated: (new Date()).toJSON()+ lastUpdated: new Date().toJSON()};} else {// check and create meta folder if not exist// todo not need to check if folder exist first createDirectoryPromise() recursively will skip creation of existing folders https://nodejs.org/api/fs.html#fs_fs_mkdir_path_options_callbackconst metaDirectoryPath = getMetaDirectoryPath(path);- const metaDirectoryProperties = await PlatformIO.getPropertiesPromise(metaDirectoryPath);+ const metaDirectoryProperties = await PlatformIO.getPropertiesPromise(+ metaDirectoryPath+ );if (!metaDirectoryProperties) {await PlatformIO.createDirectoryPromise(metaDirectoryPath);}@@ -403,7 +474,7 @@ export async function saveMetaDataPromise(path: string, metaData: Object): Promi...metaData,appName: versionMeta.name,appVersionUpdated: versionMeta.version,- lastUpdated: (new Date()).toJSON()+ lastUpdated: new Date().toJSON()};}const content = JSON.stringify(newFsEntryMeta);@@ -413,7 +484,7 @@ export async function saveMetaDataPromise(path: string, metaData: Object): Promiexport function findColorForFileEntry(fileExtension: string,isFile: boolean,- supportedFileTypes: Array<Object>,+ supportedFileTypes: Array<Object>): string {if (!isFile) {return AppConfig.defaultFolderColor;diff --git a/app/services/webdav-io.js b/app/services/webdav-io.jsindex a9f7f3ccd..88d7db758 100644--- a/app/services/webdav-io.js+++ b/app/services/webdav-io.js@@ -38,12 +38,12 @@ export default class WebDAVIO {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();+ 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 {@@ -89,15 +89,14 @@ export default class WebDAVIO {getDevicePaths = (): Object => {const paths = {- Home: '/files/',+ Home: '/files/'};return paths;};getAppDataPath = (): string =>// TODO- 'SOMEPATH_FIX_ME'- ;+ 'SOMEPATH_FIX_ME';getUserHomePath = (): string => '/';@@ -106,14 +105,16 @@ export default class WebDAVIO {if (path.lastIndexOf(separator) === path.length - 1) {path = path.substring(0, path.lastIndexOf(separator));}- const encodedName = path.substring(path.lastIndexOf(separator) + 1, path.length);+ 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- ;+ path.lastIndexOf('/') === path.length - 1;checkStatusCode = (code: number): boolean => {const status = parseInt(code / 100);@@ -143,11 +144,14 @@ export default class WebDAVIO {return directoyTree;};-listMetaDirectoryPromise = async (path: string): Promise<Array<Object>> => {- const promise = new Promise((resolve) => {+ const promise = new Promise(resolve => {const entries = [];- const metaDirPath = normalizePath(path) + AppConfig.dirSeparator + AppConfig.metaFolder + AppConfig.dirSeparator;+ const metaDirPath =+ normalizePath(path) ++ AppConfig.dirSeparator ++ AppConfig.metaFolder ++ AppConfig.dirSeparator;const davSuccess = (status, data) => {const dirList = data._responses;for (const dir in dirList) {@@ -181,31 +185,37 @@ export default class WebDAVIO {/*** 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)) {+ 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');@@ -215,8 +225,12 @@ export default class WebDAVIO {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;+ 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, '/');@@ -227,7 +241,12 @@ export default class WebDAVIO {eentry.name = fileName;eentry.path = decodeURI(path);eentry.tags = [];- eentry.thumbPath = isDir ? eentry.path + AppConfig.metaFolder + '/' + AppConfig.folderThumbFile : '';+ eentry.thumbPath = isDir+ ? eentry.path ++ AppConfig.metaFolder ++ '/' ++ AppConfig.folderThumbFile+ : '';// eentry.meta = {};eentry.isFile = !isDir;eentry.size = filesize;@@ -235,17 +254,24 @@ export default class WebDAVIO {// const x = getMetaFileLocationForFile(eentry.path);if (!lite) {- if (isDir) { // Read tsm.json from subfolders+ if (isDir) {+ // Read tsm.json from subfoldersconst pathMetaFile = getMetaFileLocationForDir(eentry.path);metaPromises.push(this.getEntryMeta(eentry, pathMetaFile));} else {- const metaFileAvailable = metaContent.find(obj => obj.name === fileName + AppConfig.metaFileExt);+ const metaFileAvailable = metaContent.find(+ obj => obj.name === fileName + AppConfig.metaFileExt+ );if (metaFileAvailable) {- metaPromises.push(this.getEntryMeta(eentry, metaFileAvailable.path));+ metaPromises.push(+ this.getEntryMeta(eentry, metaFileAvailable.path)+ );}// Finding if file thumbnail available- const metaThumbAvailable = metaContent.find(obj => obj.name === fileName + AppConfig.thumbFileExt);+ const metaThumbAvailable = metaContent.find(+ obj => obj.name === fileName + AppConfig.thumbFileExt+ );if (metaThumbAvailable) {eentry.thumbPath = metaThumbAvailable.path;}@@ -253,12 +279,13 @@ export default class WebDAVIO {}enhancedEntries.push(eentry);- // }+ // }+ }}- }- Promise.all(metaPromises).then((entriesMeta) => {- /* entriesMeta.forEach((entryMeta) => {+ Promise.all(metaPromises)+ .then(entriesMeta => {+ /* entriesMeta.forEach((entryMeta) => {enhancedEntries.some((enhancedEntry) => {if (enhancedEntry.path === entryMeta.path) {// eslint-disable-next-line no-param-reassign@@ -268,58 +295,70 @@ export default class WebDAVIO {return false;});}); */- resolve(enhancedEntries);- return true;- }).catch(() => {- resolve(enhancedEntries);- });- };- if (dirPath.substring(dirPath.length - 1) !== '/') {- dirPath += '/';- }- dirPath = encodeURI(dirPath);+ 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- );- });+ 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')- );+ 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) => {+ 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);- });+ 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);});@@ -328,38 +367,46 @@ export default class WebDAVIO {/*** 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: ' ++ 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);+ );+ 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);}- resolve(fileProperties);- } else {- resolve(false);- // reject('getFileProperties ' + filePath + ' failed ' + status);- }- },- 1- );- });+ },+ 1+ );+ });/*** Load the content of a text file@@ -398,50 +445,55 @@ export default class WebDAVIO {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: ' ++ ): 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- );- });+ );+ 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> {+ saveTextFilePromise(+ filePath: string,+ content: string,+ overWrite: boolean+ ): Promise<Object> {console.log('Saving text file: ' + filePath);return this.saveFilePromise(filePath, content, overWrite, 'text');}@@ -449,7 +501,11 @@ export default class WebDAVIO {/*** Persists a given binary content to a specified filepath*/- saveBinaryFilePromise(filePath: string, content: string, overWrite: boolean): Promise<Object> {+ saveBinaryFilePromise(+ filePath: string,+ content: string,+ overWrite: boolean+ ): Promise<Object> {console.log('Saving binary file: ' + filePath);return this.saveFilePromise(filePath, content, overWrite);}@@ -476,12 +532,15 @@ export default class WebDAVIO {}});});- }+ };/*** Copies a given file to a specified location*/- copyFilePromise = (filePath: string, newFilePath: string): Promise<Object> => {+ copyFilePromise = (+ filePath: string,+ newFilePath: string+ ): Promise<Object> => {console.log('Copying file: ' + filePath + ' to ' + newFilePath);return new Promise((resolve, reject) => {if (filePath.toLowerCase() === newFilePath.toLowerCase()) {@@ -509,12 +568,15 @@ export default class WebDAVIO {);}});- }+ };/*** Renames a given file*/- renameFilePromise = (filePath: string, newFilePath: string): Promise<Object> => {+ renameFilePromise = (+ filePath: string,+ newFilePath: string+ ): Promise<Object> => {console.log('Renaming file: ' + filePath + ' to ' + newFilePath);return new Promise((resolve, reject) => {if (filePath === newFilePath) {@@ -542,12 +604,15 @@ export default class WebDAVIO {);}});- }+ };/*** Rename a directory*/- renameDirectoryPromise = (dirPath: string, newDirectoryPath: string): Promise<Object> => {+ renameDirectoryPromise = (+ dirPath: string,+ newDirectoryPath: string+ ): Promise<Object> => {const newDirPath =extractParentDirectoryPath(dirPath) + '/' + newDirectoryPath;console.log('Renaming directory: ' + dirPath + ' to ' + newDirPath);@@ -582,7 +647,8 @@ export default class WebDAVIO {/*** Delete a specified file*/- deleteFilePromise = (path: string): Promise<Object> => this.deleteDirectoryPromise(path);+ deleteFilePromise = (path: string): Promise<Object> =>+ this.deleteDirectoryPromise(path);/*** Delete a specified directory, the directory should be empty, if the trash can functionality is not enableddiff --git a/app/splash-worker.js b/app/splash-worker.jsindex 917f59a43..0b5c9c920 100644--- a/app/splash-worker.js+++ b/app/splash-worker.js@@ -29,106 +29,125 @@ function init() {ipcRenderer.on('worker', (event, arg) => {// console.log('worker received: ' + JSON.stringify(arg));switch (arg.action) {- case 'createDirectoryIndex': {- console.log('createDirectoryIndex started in worker window');- console.time('createDirectoryIndex');- const directoryIndex = [];- let counter = 0;- walkDirectory(arg.path, {- recursive: true,- skipMetaFolder: true,- skipDotHiddenFolder: true,- extractText: arg.extractText- }, (fileEntry) => {- counter += 1;- if (counter > AppConfig.indexerLimit) {- console.warn('Walk canceled by ' + AppConfig.indexerLimit);- window.walkCanceled = true;- }- directoryIndex.push(enhanceEntry(fileEntry));- }, (directoryEntry) => {- if (directoryEntry.name !== AppConfig.metaFolder) {- counter += 1;- directoryIndex.push(enhanceEntry(directoryEntry));- }- }).then(() => { // entries - can be used for further processing- window.walkCanceled = false;- console.log('Directory index created ' + arg.path + ' containing ' + directoryIndex.length);- console.timeEnd('createDirectoryIndex');- ipcRenderer.send('worker', {- id: arg.id,- action: arg.action,- result: directoryIndex,- error: ''- });- return true;- }).catch((err) => {- window.walkCanceled = false;- console.timeEnd('createDirectoryIndex');- console.warn('Error creating index: ' + err);- ipcRenderer.send('worker', {- id: arg.id,- action: arg.action,- result: [], // directoryIndex,- error: err- });- });- break;- }- case 'createThumbnails': {- console.log('createThumbnails started in worker window');- if (!arg.tmbGenerationList || arg.tmbGenerationList.length < 1 || isGeneratingThumbs) {- ipcRenderer.send('worker', {- id: arg.id,- action: arg.action,- result: [],- error: 'Empty or not available tmb list or busy worker'- });+ case 'createDirectoryIndex': {+ console.log('createDirectoryIndex started in worker window');+ console.time('createDirectoryIndex');+ const directoryIndex = [];+ let counter = 0;+ walkDirectory(+ arg.path,+ {+ recursive: true,+ skipMetaFolder: true,+ skipDotHiddenFolder: true,+ extractText: arg.extractText+ },+ fileEntry => {+ counter += 1;+ if (counter > AppConfig.indexerLimit) {+ console.warn('Walk canceled by ' + AppConfig.indexerLimit);+ window.walkCanceled = true;+ }+ directoryIndex.push(enhanceEntry(fileEntry));+ },+ directoryEntry => {+ if (directoryEntry.name !== AppConfig.metaFolder) {+ counter += 1;+ directoryIndex.push(enhanceEntry(directoryEntry));+ }+ }+ )+ .then(() => {+ // entries - can be used for further processing+ window.walkCanceled = false;+ console.log(+ 'Directory index created ' ++ arg.path ++ ' containing ' ++ directoryIndex.length+ );+ console.timeEnd('createDirectoryIndex');+ ipcRenderer.send('worker', {+ id: arg.id,+ action: arg.action,+ result: directoryIndex,+ error: ''+ });+ return true;+ })+ .catch(err => {+ window.walkCanceled = false;+ console.timeEnd('createDirectoryIndex');+ console.warn('Error creating index: ' + err);+ ipcRenderer.send('worker', {+ id: arg.id,+ action: arg.action,+ result: [], // directoryIndex,+ error: err+ });+ });break;}- isGeneratingThumbs = true;- const tmbGenerationPromises = [];- let splashShown = false;- arg.tmbGenerationList.map(entry => {- if (!splashShown && entry.endsWith('pdf')) {- splashShown = true;- ipcRenderer.send('setSplashVisibility', {- visibility: true,+ case 'createThumbnails': {+ console.log('createThumbnails started in worker window');+ if (+ !arg.tmbGenerationList ||+ arg.tmbGenerationList.length < 1 ||+ isGeneratingThumbs+ ) {+ ipcRenderer.send('worker', {+ id: arg.id,+ action: arg.action,+ result: [],+ error: 'Empty or not available tmb list or busy worker'});+ break;}- tmbGenerationPromises.push(getThumbnailURLPromise(entry));- return true;- });- Promise.all(tmbGenerationPromises).then(tmbResult => {- console.log('tmb results' + JSON.stringify(tmbResult));- ipcRenderer.send('setSplashVisibility', {- visibility: false,+ isGeneratingThumbs = true;+ const tmbGenerationPromises = [];+ let splashShown = false;+ arg.tmbGenerationList.map(entry => {+ if (!splashShown && entry.endsWith('pdf')) {+ splashShown = true;+ ipcRenderer.send('setSplashVisibility', {+ visibility: true+ });+ }+ tmbGenerationPromises.push(getThumbnailURLPromise(entry));+ return true;});- ipcRenderer.send('worker', {- id: arg.id,- action: arg.action,- result: tmbResult,- error: ''- });- isGeneratingThumbs = false;- return true;- }).catch(error => {- console.warn('Tmb generation failed: ' + error);- ipcRenderer.send('worker', {- id: arg.id,- action: arg.action,- result: [],- error: 'Error generating thumbnails: ' + error- });- ipcRenderer.send('setSplashVisibility', {- visibility: false,- });- isGeneratingThumbs = false;- });- break;- }- default:- return false;+ Promise.all(tmbGenerationPromises)+ .then(tmbResult => {+ console.log('tmb results' + JSON.stringify(tmbResult));+ ipcRenderer.send('setSplashVisibility', {+ visibility: false+ });+ ipcRenderer.send('worker', {+ id: arg.id,+ action: arg.action,+ result: tmbResult,+ error: ''+ });+ isGeneratingThumbs = false;+ return true;+ })+ .catch(error => {+ console.warn('Tmb generation failed: ' + error);+ ipcRenderer.send('worker', {+ id: arg.id,+ action: arg.action,+ result: [],+ error: 'Error generating thumbnails: ' + error+ });+ ipcRenderer.send('setSplashVisibility', {+ visibility: false+ });+ isGeneratingThumbs = false;+ });+ break;+ }+ default:+ return false;}});}diff --git a/app/store/configureStore.dev.js b/app/store/configureStore.dev.jsindex 63671d329..cbb4299df 100644--- a/app/store/configureStore.dev.js+++ b/app/store/configureStore.dev.js@@ -28,7 +28,7 @@ import onlineListener from '../services/onlineListener';const history = createHashHistory();-const configureStore = (initialState) => {+const configureStore = initialState => {// Redux Configurationconst middleware = [];const enhancers = [];@@ -49,15 +49,15 @@ const configureStore = (initialState) => {// Redux DevTools Configurationconst actionCreators = {- ...routerActions,+ ...routerActions};// If Redux DevTools Extension is installed use it, otherwise use Redux compose/* eslint-disable no-underscore-dangle */const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({- // Options: http://zalmoxisus.github.io/redux-devtools-extension/API/Arguments.html- actionCreators,- })+ // Options: http://zalmoxisus.github.io/redux-devtools-extension/API/Arguments.html+ actionCreators+ }): compose;/* eslint-enable no-underscore-dangle */@@ -71,15 +71,18 @@ const configureStore = (initialState) => {onlineListener(store.dispatch);- const persistor = persistStore(store);/* , null, () => {+ const persistor = persistStore(+ store+ ); /* , null, () => {document.dispatchEvent(new Event('storeLoaded'));// store.dispatch(push('/main'));console.log('Store rehydrated.');}); */if (module.hot) {- module.hot.accept('../reducers', () =>- store.replaceReducer(require('../reducers')) // eslint-disable-line global-require+ module.hot.accept(+ '../reducers',+ () => store.replaceReducer(require('../reducers')) // eslint-disable-line global-require);}diff --git a/app/store/configureStore.prod.js b/app/store/configureStore.prod.jsindex e78bf9a7c..9e336e78c 100644--- a/app/store/configureStore.prod.js+++ b/app/store/configureStore.prod.js@@ -35,7 +35,9 @@ const enhancer = compose(function configureStore(initialState) {const store = createStore(rootReducer, initialState, enhancer);onlineListener(store.dispatch);- const persistor = persistStore(store); /* , null, () => {+ const persistor = persistStore(+ store+ ); /* , null, () => {document.dispatchEvent(new Event('storeLoaded'));}); */return { store, persistor };diff --git a/app/utils/dates.js b/app/utils/dates.jsindex 100a8263b..2286caba0 100644--- a/app/utils/dates.js+++ b/app/utils/dates.js@@ -38,62 +38,86 @@ export function isDateTimeTag(tagDate: string): boolean {/** Returns true if string is this format: 2015 */export function isYear(tagDate: string): boolean {- return /(^|\s)([0123][0123456789][0123456789][0123456789])(\s|$)/.test(tagDate);+ return /(^|\s)([0123][0123456789][0123456789][0123456789])(\s|$)/.test(+ tagDate+ );}/** Returns true if string is this format: 2015-2017 */export function isYearPeriod(tagDate: string): boolean {- return /(^|\s)([0123][0123456789][0123456789][0123456789]-[0123][0123456789][0123456789][0123456789])(\s|$)/.test(tagDate);+ return /(^|\s)([0123][0123456789][0123456789][0123456789]-[0123][0123456789][0123456789][0123456789])(\s|$)/.test(+ tagDate+ );}/** Returns true if string is this format: 201512 */export function isYearMonth(tagDate: string): boolean {- return /(^|\s)([0123][0123456789][0123456789][0123456789][01][0123456789])(\s|$)/.test(tagDate);+ return /(^|\s)([0123][0123456789][0123456789][0123456789][01][0123456789])(\s|$)/.test(+ tagDate+ );}/** Returns true if string is this format: 201512-201604 */export function isYearMonthPeriod(tagDate: string): boolean {- return /(^|\s)([0123][0123456789][0123456789][0123456789][01][0123456789]-[0123][0123456789][0123456789][0123456789][01][0123456789])(\s|$)/.test(tagDate);+ return /(^|\s)([0123][0123456789][0123456789][0123456789][01][0123456789]-[0123][0123456789][0123456789][0123456789][01][0123456789])(\s|$)/.test(+ tagDate+ );}/** Returns true if string is this format: 20151223 */export function isYearMonthDay(tagDate: string): boolean {- return /(^|\s)([0123][0123456789][0123456789][0123456789][01][0123456789][0123][0123456789])(\s|$)/.test(tagDate);+ return /(^|\s)([0123][0123456789][0123456789][0123456789][01][0123456789][0123][0123456789])(\s|$)/.test(+ tagDate+ );}/** Returns true if string is this format: 20151223-20160223 */export function isYearMonthDayPeriod(tagDate: string): boolean {- return /(^|\s)([0123][0123456789][0123456789][0123456789][01][0123456789][0123][0123456789]-[0123][0123456789][0123456789][0123456789][01][0123456789][0123][0123456789])(\s|$)/.test(tagDate);+ return /(^|\s)([0123][0123456789][0123456789][0123456789][01][0123456789][0123][0123456789]-[0123][0123456789][0123456789][0123456789][01][0123456789][0123][0123456789])(\s|$)/.test(+ tagDate+ );}/** Returns true if string is this format: 20151223~01 */export function isYearMonthDayHour(tagDate: string): boolean {- return /(^|\s)([0123][0123456789][0123456789][0123456789][01][0123456789][0123][0123456789]~[0123456][0123456789])(\s|$)/.test(tagDate);+ return /(^|\s)([0123][0123456789][0123456789][0123456789][01][0123456789][0123][0123456789]~[0123456][0123456789])(\s|$)/.test(+ tagDate+ );}/** Returns true if string is this format: 20190712~17-20190712~17 */export function isYearMonthDayHourPeriod(tagDate: string): boolean {- return /(^|\s)([0123][0123456789][0123456789][0123456789][01][0123456789][0123][0123456789]~[0123456][0123456789]-[0123][0123456789][0123456789][0123456789][01][0123456789][0123][0123456789]~[0123456][0123456789])(\s|$)/.test(tagDate);+ return /(^|\s)([0123][0123456789][0123456789][0123456789][01][0123456789][0123][0123456789]~[0123456][0123456789]-[0123][0123456789][0123456789][0123456789][01][0123456789][0123][0123456789]~[0123456][0123456789])(\s|$)/.test(+ tagDate+ );}/** Returns true if string is this format: 20151223~0112 */export function isYearMonthDayHourMin(tagDate: string): boolean {- return /(^|\s)([0123][0123456789][0123456789][0123456789][01][0123456789][0123][0123456789]~[0123456][0123456789][0123456][0123456789])(\s|$)/.test(tagDate);+ return /(^|\s)([0123][0123456789][0123456789][0123456789][01][0123456789][0123][0123456789]~[0123456][0123456789][0123456][0123456789])(\s|$)/.test(+ tagDate+ );}/** Returns true if string is this format: 20190712~1740-20190712~1740 */export function isYearMonthDayHourMinPeriod(tagDate: string): boolean {- return /(^|\s)([0123][0123456789][0123456789][0123456789][01][0123456789][0123][0123456789]~[0123456][0123456789][0123456][0123456789]-[0123][0123456789][0123456789][0123456789][01][0123456789][0123][0123456789]~[0123456][0123456789][0123456][0123456789])(\s|$)/.test(tagDate);+ return /(^|\s)([0123][0123456789][0123456789][0123456789][01][0123456789][0123][0123456789]~[0123456][0123456789][0123456][0123456789]-[0123][0123456789][0123456789][0123456789][01][0123456789][0123][0123456789]~[0123456][0123456789][0123456][0123456789])(\s|$)/.test(+ tagDate+ );}/** Returns true if string is this format: 20151223~011358 */export function isYearMonthDayHourMinSec(tagDate: string): boolean {- return /(^|\s)([0123][0123456789][0123456789][0123456789][01][0123456789][0123][0123456789]~[0123456][0123456789][0123456][0123456789][0123456][0123456789])(\s|$)/.test(tagDate);+ return /(^|\s)([0123][0123456789][0123456789][0123456789][01][0123456789][0123][0123456789]~[0123456][0123456789][0123456][0123456789][0123456][0123456789])(\s|$)/.test(+ tagDate+ );}/** Returns true if string is this format: 20190712~174031-20190712~174031 */export function isYearMonthDayHourMinSecPeriod(tagDate: string): boolean {- return /(^|\s)([0123][0123456789][0123456789][0123456789][01][0123456789][0123][0123456789]~[0123456][0123456789][0123456][0123456789][0123456][0123456789]-[0123][0123456789][0123456789][0123456789][01][0123456789][0123][0123456789]~[0123456][0123456789][0123456][0123456789][0123456][0123456789])(\s|$)/.test(tagDate);+ return /(^|\s)([0123][0123456789][0123456789][0123456789][01][0123456789][0123][0123456789]~[0123456][0123456789][0123456][0123456789][0123456][0123456789]-[0123][0123456789][0123456789][0123456789][01][0123456789][0123][0123456789]~[0123456][0123456789][0123456][0123456789][0123456][0123456789])(\s|$)/.test(+ tagDate+ );}/** Returns the number of day in month, January = 1 -> 31 .. December = 12 */@@ -104,11 +128,14 @@ export function getDaysInMonth(year: number, month: number): number {export const msInDay = 1000 * 60 * 60 * 24;/** Extract the time period from string e.g. 201902 -> fromDate: 2019-01-01 00:00:00, toDate; 2019-01-31 23:59:59 */-export function extractTimePeriod(value: string): { fromDateTime: Date | null, toDateTime: Date | null} {+export function extractTimePeriod(+ value: string+): { fromDateTime: Date | null, toDateTime: Date | null } {let fromDateTime = null;let toDateTime = null;if (value.length && !/(^|\s)([0123456789])(\s|$)/.test(value.substr(0, 1))) {- return { // Return if the first char is not a number, ignoring values starting with letters+ return {+ // Return if the first char is not a number, ignoring values starting with lettersfromDateTime,toDateTime};@@ -126,14 +153,28 @@ export function extractTimePeriod(value: string): { fromDateTime: Date | null, tconst year = value.substring(0, 4);const month = value.substring(4, 6);fromDateTime = new Date(year + '-' + month + '-01');- toDateTime = new Date(year + '-' + month + '-' + getDaysInMonth(parseInt(year, 10), parseInt(month, 10)) + ' 23:59:59.999');+ toDateTime = new Date(+ year ++ '-' ++ month ++ '-' ++ getDaysInMonth(parseInt(year, 10), parseInt(month, 10)) ++ ' 23:59:59.999'+ );} else if (isYearMonthPeriod(value)) {const fromYear = value.substring(0, 4);const fromMonth = value.substring(4, 6);const toYear = value.substring(7, 11);const toMonth = value.substring(11, 13);fromDateTime = new Date(fromYear + '-' + fromMonth + '-01');- toDateTime = new Date(toYear + '-' + toMonth + '-' + getDaysInMonth(parseInt(toYear, 10), parseInt(toMonth, 10)) + ' 23:59:59.999');+ toDateTime = new Date(+ toYear ++ '-' ++ toMonth ++ '-' ++ getDaysInMonth(parseInt(toYear, 10), parseInt(toMonth, 10)) ++ ' 23:59:59.999'+ );} else if (isYearMonthDay(value)) {const year = value.substring(0, 4);const month = value.substring(4, 6);@@ -148,14 +189,20 @@ export function extractTimePeriod(value: string): { fromDateTime: Date | null, tconst toMonth = value.substring(13, 15);const toDay = value.substring(15, 17);fromDateTime = new Date(fromYear + '-' + fromMonth + '-' + fromDay);- toDateTime = new Date(toYear + '-' + toMonth + '-' + toDay + ' 23:59:59.999');+ toDateTime = new Date(+ toYear + '-' + toMonth + '-' + toDay + ' 23:59:59.999'+ );} else if (isYearMonthDayHour(value)) {const year = value.substring(0, 4);const month = value.substring(4, 6);const day = value.substring(6, 8);const hour = value.substring(9, 11);- fromDateTime = new Date(year + '-' + month + '-' + day + ' ' + hour + ':00:00');- toDateTime = new Date(year + '-' + month + '-' + day + ' ' + hour + ':59:59.999');+ fromDateTime = new Date(+ year + '-' + month + '-' + day + ' ' + hour + ':00:00'+ );+ toDateTime = new Date(+ year + '-' + month + '-' + day + ' ' + hour + ':59:59.999'+ );} else if (isYearMonthDayHourPeriod(value)) {const fromYear = value.substring(0, 4);const fromMonth = value.substring(4, 6);@@ -165,16 +212,24 @@ export function extractTimePeriod(value: string): { fromDateTime: Date | null, tconst toMonth = value.substring(16, 18);const toDay = value.substring(18, 20);const toHour = value.substring(21, 23);- fromDateTime = new Date(fromYear + '-' + fromMonth + '-' + fromDay + ' ' + fromHour + ':00:00');- toDateTime = new Date(toYear + '-' + toMonth + '-' + toDay + ' ' + toHour + ':59:59.999');+ fromDateTime = new Date(+ fromYear + '-' + fromMonth + '-' + fromDay + ' ' + fromHour + ':00:00'+ );+ toDateTime = new Date(+ toYear + '-' + toMonth + '-' + toDay + ' ' + toHour + ':59:59.999'+ );} else if (isYearMonthDayHourMin(value)) {const year = value.substring(0, 4);const month = value.substring(4, 6);const day = value.substring(6, 8);const hour = value.substring(9, 11);const min = value.substring(11, 13);- fromDateTime = new Date(year + '-' + month + '-' + day + ' ' + hour + ':' + min + ':00');- toDateTime = new Date(year + '-' + month + '-' + day + ' ' + hour + ':' + min + ':59.999');+ fromDateTime = new Date(+ year + '-' + month + '-' + day + ' ' + hour + ':' + min + ':00'+ );+ toDateTime = new Date(+ year + '-' + month + '-' + day + ' ' + hour + ':' + min + ':59.999'+ );} else if (isYearMonthDayHourMinPeriod(value)) {const fromYear = value.substring(0, 4);const fromMonth = value.substring(4, 6);@@ -186,8 +241,30 @@ export function extractTimePeriod(value: string): { fromDateTime: Date | null, tconst toDay = value.substring(20, 22);const toHour = value.substring(23, 25);const toMin = value.substring(25, 27);- fromDateTime = new Date(fromYear + '-' + fromMonth + '-' + fromDay + ' ' + fromHour + ':' + fromMin + ':00');- toDateTime = new Date(toYear + '-' + toMonth + '-' + toDay + ' ' + toHour + ':' + toMin + ':59.999');+ fromDateTime = new Date(+ fromYear ++ '-' ++ fromMonth ++ '-' ++ fromDay ++ ' ' ++ fromHour ++ ':' ++ fromMin ++ ':00'+ );+ toDateTime = new Date(+ toYear ++ '-' ++ toMonth ++ '-' ++ toDay ++ ' ' ++ toHour ++ ':' ++ toMin ++ ':59.999'+ );} else if (isYearMonthDayHourMinSec(value)) {const year = value.substring(0, 4);const month = value.substring(4, 6);@@ -195,8 +272,23 @@ export function extractTimePeriod(value: string): { fromDateTime: Date | null, tconst hour = value.substring(9, 11);const min = value.substring(11, 13);const sec = value.substring(13, 15);- fromDateTime = new Date(year + '-' + month + '-' + day + ' ' + hour + ':' + min + ':' + sec);- toDateTime = new Date(year + '-' + month + '-' + day + ' ' + hour + ':' + min + ':' + sec + '.999');+ fromDateTime = new Date(+ year + '-' + month + '-' + day + ' ' + hour + ':' + min + ':' + sec+ );+ toDateTime = new Date(+ year ++ '-' ++ month ++ '-' ++ day ++ ' ' ++ hour ++ ':' ++ min ++ ':' ++ sec ++ '.999'+ );} else if (isYearMonthDayHourMinSecPeriod(value)) {const fromYear = value.substring(0, 4);const fromMonth = value.substring(4, 6);@@ -210,8 +302,33 @@ export function extractTimePeriod(value: string): { fromDateTime: Date | null, tconst toHour = value.substring(25, 27);const toMin = value.substring(27, 29);const toSec = value.substring(29, 31);- fromDateTime = new Date(fromYear + '-' + fromMonth + '-' + fromDay + ' ' + fromHour + ':' + fromMin + ':' + fromSec);- toDateTime = new Date(toYear + '-' + toMonth + '-' + toDay + ' ' + toHour + ':' + toMin + ':' + toSec + '.999');+ fromDateTime = new Date(+ fromYear ++ '-' ++ fromMonth ++ '-' ++ fromDay ++ ' ' ++ fromHour ++ ':' ++ fromMin ++ ':' ++ fromSec+ );+ toDateTime = new Date(+ toYear ++ '-' ++ toMonth ++ '-' ++ toDay ++ ' ' ++ toHour ++ ':' ++ toMin ++ ':' ++ toSec ++ '.999'+ );}} catch (err) {console.log('Error extracting date ' + err);@@ -223,17 +340,24 @@ export function extractTimePeriod(value: string): { fromDateTime: Date | null, t}export function pad(number: number) {- return (number < 10) ? '0' + number : number;+ return number < 10 ? '0' + number : number;}/** Convert a date in this 2013-01-02 12:23:58 format */export function formatDateTime(date: Date): string {- return date.getFullYear() +- '-' + pad(date.getMonth() + 1) +- '-' + pad(date.getDate()) +- ' ' + pad(date.getHours()) +- ':' + pad(date.getMinutes()) +- ':' + pad(date.getSeconds());+ return (+ date.getFullYear() ++ '-' ++ pad(date.getMonth() + 1) ++ '-' ++ pad(date.getDate()) ++ ' ' ++ pad(date.getHours()) ++ ':' ++ pad(date.getMinutes()) ++ ':' ++ pad(date.getSeconds())+ );}/** Converts 'Sun May 11, 2014' to 2014-05 */@@ -334,31 +458,31 @@ export function convertToDate(date: string) {let betterDateStr;switch (date.length) {- case 4:- if (parseToInt && !isNaN(parseToInt)) {- return d.getFullYear();- }- break;- case 6:- if (parseToInt && !isNaN(parseToInt)) {- dateStr = date;- match = dateStr.match(/(\d{4})(\d{2})/);- betterDateStr = match[1] + '-' + match[2];-- return betterDateStr;- }- break;- case 8:- if (parseToInt && !isNaN(parseToInt)) {- dateStr = date;- match = dateStr.match(/(\d{4})(\d{2})(\d{2})/);- betterDateStr = match[1] + '-' + match[2] + '-' + match[3];-- return betterDateStr;- }- break;- default:- return false;+ case 4:+ if (parseToInt && !isNaN(parseToInt)) {+ return d.getFullYear();+ }+ break;+ case 6:+ if (parseToInt && !isNaN(parseToInt)) {+ dateStr = date;+ match = dateStr.match(/(\d{4})(\d{2})/);+ betterDateStr = match[1] + '-' + match[2];++ return betterDateStr;+ }+ break;+ case 8:+ if (parseToInt && !isNaN(parseToInt)) {+ dateStr = date;+ match = dateStr.match(/(\d{4})(\d{2})(\d{2})/);+ betterDateStr = match[1] + '-' + match[2] + '-' + match[3];++ return betterDateStr;+ }+ break;+ default:+ return false;}}@@ -366,9 +490,14 @@ export function convertToDateTime(dateTime: string) {const dateTimeRegExp = /^\d\d\d\d-(00|[0-9]|1[0-9]|2[0-3]):([0-9]|[0-5][0-9]):([0-9]|[0-5][0-9])$/g;const dateTimeWinRegExp = /^(([0-1]?[0-9])|([2][0-3]))!([0-5]?[0-9])(!([0-5]?[0-9]))?$/g;const dateTimeWin1RegExp = /^(([0-1]?[0-9])|([2][0-3]))~([0-5]?[0-9])(!([0-5]?[0-9]))?$/g;- if (dateTime.match(dateTimeRegExp) || dateTime.match(dateTimeWinRegExp) ||- dateTime.match(dateTimeWin1RegExp) || dateTime.search('!') ||- dateTime.search(':') || dateTime.search('~')) {+ if (+ dateTime.match(dateTimeRegExp) ||+ dateTime.match(dateTimeWinRegExp) ||+ dateTime.match(dateTimeWin1RegExp) ||+ dateTime.search('!') ||+ dateTime.search(':') ||+ dateTime.search('~')+ ) {let time;let firstTime;let secondTime;diff --git a/app/utils/misc.js b/app/utils/misc.jsindex e9fdc620f..7c0f1d75d 100644--- a/app/utils/misc.js+++ b/app/utils/misc.js@@ -23,12 +23,20 @@ export function isPlusCode(plusCode: string): boolean {return false;}const upperCasedPlusCode = plusCode.toUpperCase(); // needed only lowercased index- return /(^|\s)([23456789C][23456789CFGHJMPQRV][23456789CFGHJMPQRVWX]{6}\+[23456789CFGHJMPQRVWX]{2,3})(\s|$)/.test(upperCasedPlusCode);+ return /(^|\s)([23456789C][23456789CFGHJMPQRV][23456789CFGHJMPQRVWX]{6}\+[23456789CFGHJMPQRVWX]{2,3})(\s|$)/.test(+ upperCasedPlusCode+ );}-export function parseLatLon(latLongInput: string): {lat: number, lon: number} | false {+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)) {+ 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(',');@@ -44,10 +52,10 @@ export function parseLatLon(latLongInput: string): {lat: number, lon: number} |}export function traverse(objArr, func) {- objArr.forEach((obj) => {- Object.keys(obj).map((objKey) => {+ objArr.forEach(obj => {+ Object.keys(obj).map(objKey => {func.apply(this, [obj, objKey]);- if ((objKey === 'subPages') && typeof Array.isArray(obj[objKey])) {+ if (objKey === 'subPages' && typeof Array.isArray(obj[objKey])) {traverse(obj[objKey], func);}});@@ -112,12 +120,13 @@ export function getRandomInt(min, max) {export function isVisibleOnScreen(element) {const rectangle = element.getBoundingClientRect();- const isVisible = (+ const isVisible =rectangle.top >= 0 &&rectangle.left >= 0 &&- rectangle.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&- rectangle.right <= (window.innerWidth || document.documentElement.clientWidth)- );+ rectangle.bottom <=+ (window.innerHeight || document.documentElement.clientHeight) &&+ rectangle.right <=+ (window.innerWidth || document.documentElement.clientWidth);return isVisible;}@@ -177,13 +186,13 @@ export function formatFileSize(sizeInBytes): string {const terabyte = gigabyte * kilobyte;const precision = 2;- if ((sizeInBytes >= 0) && (sizeInBytes < kilobyte)) {+ if (sizeInBytes >= 0 && sizeInBytes < kilobyte) {return sizeInBytes + ' B';- } else if ((sizeInBytes >= kilobyte) && (sizeInBytes < megabyte)) {+ } else if (sizeInBytes >= kilobyte && sizeInBytes < megabyte) {return (sizeInBytes / kilobyte).toFixed(precision) + ' KB';- } else if ((sizeInBytes >= megabyte) && (sizeInBytes < gigabyte)) {+ } else if (sizeInBytes >= megabyte && sizeInBytes < gigabyte) {return (sizeInBytes / megabyte).toFixed(precision) + ' MB';- } else if ((sizeInBytes >= gigabyte) && (sizeInBytes < terabyte)) {+ } else if (sizeInBytes >= gigabyte && sizeInBytes < terabyte) {return (sizeInBytes / gigabyte).toFixed(precision) + ' GB';} else if (sizeInBytes >= terabyte) {return (sizeInBytes / terabyte).toFixed(precision) + ' TB';@@ -199,21 +208,9 @@ export function formatFileSize2(sizeInBytes, siSystem): string {if (sizeInBytes < threshold) {return sizeInBytes + ' B';}- const units = siSystem ? [- 'kB',- 'MB',- 'GB',- 'TB',- 'PB',- 'EB'- ] : [- 'KiB',- 'MiB',- 'GiB',- 'TiB',- 'PiB',- 'EiB'- ];+ const units = siSystem+ ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB']+ : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB'];let cUnit = -1;do {sizeInBytes /= threshold;@@ -261,7 +258,11 @@ export function formatDateTime(date, includeTime: boolean) {}/** Convert a date in the following format 20191204 or 20191204~124532 */-export function formatDateTime4Tag(date: string, includeTime: boolean, includeMS?: boolean): string {+export function formatDateTime4Tag(+ date: string,+ includeTime: boolean,+ includeMS?: boolean+): string {if (date === undefined || date === '') {return '';}@@ -310,7 +311,13 @@ export function convertStringToDate(dateString) {return false;}if (dateString.length === 8) {- return new Date(dateString.substring(0, 4) + '-' + dateString.substring(4, 6) + '-' + dateString.substring(6, 8));+ return new Date(+ dateString.substring(0, 4) ++ '-' ++ dateString.substring(4, 6) ++ '-' ++ dateString.substring(6, 8)+ );}return false;}@@ -335,8 +342,11 @@ export function sortAlphaNum(a, b) {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])) {+ 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) {@@ -365,7 +375,7 @@ export function sortAlphaNum(a, b) {// Sorting functionalityexport function sortByName(a, b) {- return (!b.isFile - !a.isFile) || sortAlphaNum(a, b);+ return !b.isFile - !a.isFile || sortAlphaNum(a, b);}export function sortBySize(a, b) {@@ -381,10 +391,7 @@ export function sortByExtension(a, b) {}export function sortByFirstTag(a, b) {- if (- (!a.tags && !b.tags) ||- (a.tags.length < 1 && b.tags.length < 1)- ) {+ if ((!a.tags && !b.tags) || (a.tags.length < 1 && b.tags.length < 1)) {return 0;}if (!a.tags || a.tags.length < 1) {@@ -407,35 +414,35 @@ export function shuffleArray(array) {export function sortByCriteria(data, criteria, order) {switch (criteria) {- case 'byName':- if (order) {+ 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);- }- 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);}}@@ -444,7 +451,8 @@ export function sortByCriteria(data, criteria, order) {* @param val* @returns {boolean}*/-export const isObj = val => typeof val === 'object' && !isArr(val) && !isNull(val);+export const isObj = val =>+ typeof val === 'object' && !isArr(val) && !isNull(val);/*** @description Check if value is of type 'null'@@ -509,7 +517,8 @@ export const hasProp = (obj, prop) => obj.hasOwnProperty(prop);* @param method* @returns {boolean}*/-export const hasMethod = (obj, method) => hasProp(obj, method) && isFunc(obj[method]);+export const hasMethod = (obj, method) =>+ hasProp(obj, method) && isFunc(obj[method]);/*** @description Check if object has key@@ -583,7 +592,7 @@ export const recurIter = (handler, complete, index = 0) => {*/export const poll = (handler, complete, interval) => {setTimeout(() => {- handler((canPoll) => {+ handler(canPoll => {if (canPoll) {return poll(handler, complete, interval);}@@ -645,7 +654,7 @@ export const determineTypeChecker = type => {*/export const setStrongTypedObject = config => {const proxy = {};- eachProp(config, (prop, key) => proxy[key] = prop.value);+ eachProp(config, (prop, key) => (proxy[key] = prop.value));return new Proxy(proxy, {get(target, prop) {@@ -656,7 +665,9 @@ export const setStrongTypedObject = config => {const typeChecker = determineTypeChecker(type);if (!typeChecker(value)) {- throw new Error(`[Ammo.StrongType] Invalid type. Expected type for field {${prop}} is {${type}}`);+ throw new Error(+ `[Ammo.StrongType] Invalid type. Expected type for field {${prop}} is {${type}}`+ );}target[prop] = value;@@ -744,7 +755,8 @@ export const extractNestedProp = (obj, keysText) => {// ... check if final target is reached ...if (keysIndex === keysLength) {// ... extract target prop- targetProp = !isUndef(nextTarget) && !isNull(nextTarget) ? nextTarget : undefined;+ targetProp =+ !isUndef(nextTarget) && !isNull(nextTarget) ? nextTarget : undefined;break;}@@ -849,22 +861,24 @@ export const shape = items => {* @param key* @returns {*}*/-export const filterByUnique = (items, 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;+export const filterByUnique = (items, 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;++ if (isDuplicate) {+ return accumulator;+ }- if (isDuplicate) {+ const modifiedItem = extend({}, item);+ accumulator.push(modifiedItem);return accumulator;- }-- const modifiedItem = extend({}, item);- accumulator.push(modifiedItem);- return accumulator;-}, []);+ }, []);/*** @description Filter by duplicate@@ -873,12 +887,15 @@ export const filterByUnique = (items, key) => items.reduce((accumulator, item) =* @param duplicateLength* @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;-});+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+ );+ });diff --git a/app/utils/openlocationcode.js b/app/utils/openlocationcode.jsindex 2e01464e6..6d6f0507c 100644--- a/app/utils/openlocationcode.js+++ b/app/utils/openlocationcode.js@@ -56,7 +56,7 @@* var code = OpenLocationCode.recoverNearest('9G8F+6X', 47.4, 8.6);* var code = OpenLocationCode.recoverNearest('8F+6X', 47.4, 8.6);*/-(function (root, factory) {+(function(root, factory) {/* global define, module */if (typeof module === 'object' && module.exports) {// Node. Does not work with strict CommonJS, but@@ -67,7 +67,7 @@// Browser globalsroot.OpenLocationCode = factory();}-} (this, function () {+})(this, function() {var OpenLocationCode = {};/**@@ -114,7 +114,7 @@// The resolution values in degrees for each position in the lat/lng pair// encoding. These give the place value of each position, and therefore the// dimensions of the resulting area.- var PAIR_RESOLUTIONS_ = [20.0, 1.0, .05, .0025, .000125];+ var PAIR_RESOLUTIONS_ = [20.0, 1.0, 0.05, 0.0025, 0.000125];// Number of columns in the grid refinement method.var GRID_COLUMNS_ = 4;@@ -131,9 +131,9 @@/**Returns the OLC alphabet.*/- var getAlphabet = OpenLocationCode.getAlphabet = function() {+ var getAlphabet = (OpenLocationCode.getAlphabet = function() {return CODE_ALPHABET_;- };+ });/*** Determines if a code is valid.@@ -145,7 +145,7 @@* @param {string} code The string to check.* @return {boolean} True if the string is a valid code.*/- var isValid = OpenLocationCode.isValid = function(code) {+ var isValid = (OpenLocationCode.isValid = function(code) {if (!code || typeof code !== 'string') {return false;}@@ -161,8 +161,10 @@return false;}// Is it in an illegal position?- if (code.indexOf(SEPARATOR_) > SEPARATOR_POSITION_ ||- code.indexOf(SEPARATOR_) % 2 == 1) {+ if (+ code.indexOf(SEPARATOR_) > SEPARATOR_POSITION_ ||+ code.indexOf(SEPARATOR_) % 2 == 1+ ) {return false;}// We can have an even number of padding characters before the separator,@@ -173,9 +175,14 @@return false;}// There can only be one group and it must have even length.- var padMatch = code.match(new RegExp('(' + PADDING_CHARACTER_ + '+)', 'g'));- if (padMatch.length > 1 || padMatch[0].length % 2 == 1 ||- padMatch[0].length > SEPARATOR_POSITION_ - 2) {+ var padMatch = code.match(+ new RegExp('(' + PADDING_CHARACTER_ + '+)', 'g')+ );+ if (+ padMatch.length > 1 ||+ padMatch[0].length % 2 == 1 ||+ padMatch[0].length > SEPARATOR_POSITION_ - 2+ ) {return false;}// If the code is long enough to end with a separator, make sure it does.@@ -190,8 +197,9 @@}// Strip the separator and any padding characters.- code = code.replace(new RegExp('\\' + SEPARATOR_ + '+'), '')- .replace(new RegExp(PADDING_CHARACTER_ + '+'), '');+ code = code+ .replace(new RegExp('\\' + SEPARATOR_ + '+'), '')+ .replace(new RegExp(PADDING_CHARACTER_ + '+'), '');// Check the code contains only valid characters.for (var i = 0, len = code.length; i < len; i++) {var character = code.charAt(i).toUpperCase();@@ -200,7 +208,7 @@}}return true;- };+ });/*** Determines if a code is a valid short code.@@ -209,18 +217,20 @@* @return {boolean} True if the string can be produced by removing four or* more characters from the start of a valid code.*/- var isShort = OpenLocationCode.isShort = function(code) {+ var isShort = (OpenLocationCode.isShort = function(code) {// Check it's valid.if (!isValid(code)) {return false;}// If there are less characters than expected before the SEPARATOR.- if (code.indexOf(SEPARATOR_) >= 0 &&- code.indexOf(SEPARATOR_) < SEPARATOR_POSITION_) {+ if (+ code.indexOf(SEPARATOR_) >= 0 &&+ code.indexOf(SEPARATOR_) < SEPARATOR_POSITION_+ ) {return true;}return false;- };+ });/*** Determines if a code is a valid full Open Location Code.@@ -229,7 +239,7 @@* @return {boolean} True if the code represents a valid latitude and* longitude combination.*/- var isFull = OpenLocationCode.isFull = function(code) {+ var isFull = (OpenLocationCode.isFull = function(code) {if (!isValid(code)) {return false;}@@ -239,23 +249,23 @@}// Work out what the first latitude character indicates for latitude.- var firstLatValue = CODE_ALPHABET_.indexOf(- code.charAt(0).toUpperCase()) * ENCODING_BASE_;+ var firstLatValue =+ CODE_ALPHABET_.indexOf(code.charAt(0).toUpperCase()) * ENCODING_BASE_;if (firstLatValue >= LATITUDE_MAX_ * 2) {// The code would decode to a latitude of >= 90 degrees.return false;}if (code.length > 1) {// Work out what the first longitude character indicates for longitude.- var firstLngValue = CODE_ALPHABET_.indexOf(- code.charAt(1).toUpperCase()) * ENCODING_BASE_;+ var firstLngValue =+ CODE_ALPHABET_.indexOf(code.charAt(1).toUpperCase()) * ENCODING_BASE_;if (firstLngValue >= LONGITUDE_MAX_ * 2) {// The code would decode to a longitude of >= 180 degrees.return false;}}return true;- };+ });/*** Encode a location into an Open Location Code.@@ -271,8 +281,11 @@* @return {string} The code.* @throws {Exception} if any of the input values are not numbers.*/- var encode = OpenLocationCode.encode = function(latitude,- longitude, codeLength) {+ var encode = (OpenLocationCode.encode = function(+ latitude,+ longitude,+ codeLength+ ) {latitude = Number(latitude);longitude = Number(longitude);if (typeof codeLength == 'undefined') {@@ -281,10 +294,12 @@codeLength = Math.min(MAX_DIGIT_COUNT, Number(codeLength));}if (isNaN(latitude) || isNaN(longitude) || isNaN(codeLength)) {- throw ('ValueError: Parameters are not numbers');+ throw 'ValueError: Parameters are not numbers';}- if (codeLength < 2 ||- (codeLength < PAIR_CODE_LENGTH_ && codeLength % 2 == 1)) {+ if (+ codeLength < 2 ||+ (codeLength < PAIR_CODE_LENGTH_ && codeLength % 2 == 1)+ ) {throw 'IllegalArgumentException: Invalid Open Location Code length';}// Ensure that latitude and longitude are valid.@@ -296,14 +311,16 @@latitude = latitude - computeLatitudePrecision(codeLength);}var code = encodePairs(- latitude, longitude, Math.min(codeLength, PAIR_CODE_LENGTH_));+ latitude,+ longitude,+ Math.min(codeLength, PAIR_CODE_LENGTH_)+ );// If the requested length indicates we want grid refined codes.if (codeLength > PAIR_CODE_LENGTH_) {- code += encodeGrid(- latitude, longitude, codeLength - PAIR_CODE_LENGTH_);+ code += encodeGrid(latitude, longitude, codeLength - PAIR_CODE_LENGTH_);}return code;- };+ });/*** Decodes an Open Location Code into its location coordinates.@@ -316,10 +333,11 @@* area of the code.* @throws {Exception} If the code is not valid.*/- var decode = OpenLocationCode.decode = function(code) {+ var decode = (OpenLocationCode.decode = function(code) {if (!isFull(code)) {- throw ('IllegalArgumentException: ' +- 'Passed Open Location Code is not a valid full code: ' + code);+ throw 'IllegalArgumentException: ' ++ 'Passed Open Location Code is not a valid full code: ' ++ code;}// Strip out separator character (we've already established the code is// valid so the maximum is one), padding characters and convert to upper@@ -333,14 +351,17 @@if (code.length <= PAIR_CODE_LENGTH_) {return codeArea;}- var gridArea = decodeGrid(code.substring(PAIR_CODE_LENGTH_, MAX_DIGIT_COUNT));+ var gridArea = decodeGrid(+ code.substring(PAIR_CODE_LENGTH_, MAX_DIGIT_COUNT)+ );return CodeArea(codeArea.latitudeLo + gridArea.latitudeLo,codeArea.longitudeLo + gridArea.longitudeLo,codeArea.latitudeLo + gridArea.latitudeHi,codeArea.longitudeLo + gridArea.longitudeHi,- codeArea.codeLength + gridArea.codeLength);- };+ codeArea.codeLength + gridArea.codeLength+ );+ });/*** Recover the nearest matching code to a specified location.@@ -357,8 +378,11 @@* @throws {Exception} if the short code is not valid, or the reference* position values are not numbers.*/- var recoverNearest = OpenLocationCode.recoverNearest = function(- shortCode, referenceLatitude, referenceLongitude) {+ var recoverNearest = (OpenLocationCode.recoverNearest = function(+ shortCode,+ referenceLatitude,+ referenceLongitude+ ) {if (!isShort(shortCode)) {if (isFull(shortCode)) {return shortCode;@@ -369,7 +393,7 @@referenceLatitude = Number(referenceLatitude);referenceLongitude = Number(referenceLongitude);if (isNaN(referenceLatitude) || isNaN(referenceLongitude)) {- throw ('ValueError: Reference position are not numbers');+ throw 'ValueError: Reference position are not numbers';}// Ensure that latitude and longitude are valid.referenceLatitude = clipLatitude(referenceLatitude);@@ -380,24 +404,29 @@// Compute the number of digits we need to recover.var paddingLength = SEPARATOR_POSITION_ - shortCode.indexOf(SEPARATOR_);// The resolution (height and width) of the padded area in degrees.- var resolution = Math.pow(20, 2 - (paddingLength / 2));+ var resolution = Math.pow(20, 2 - paddingLength / 2);// Distance from the center to an edge (in degrees).var halfResolution = resolution / 2.0;// Use the reference location to pad the supplied short code and decode it.var codeArea = decode(- encode(referenceLatitude, referenceLongitude).substr(0, paddingLength)- + shortCode);+ encode(referenceLatitude, referenceLongitude).substr(0, paddingLength) ++ shortCode+ );// How many degrees latitude is the code from the reference? If it is more// than half the resolution, we need to move it north or south but keep it// within -90 to 90 degrees.- if (referenceLatitude + halfResolution < codeArea.latitudeCenter &&- codeArea.latitudeCenter - resolution >= -LATITUDE_MAX_) {+ if (+ referenceLatitude + halfResolution < codeArea.latitudeCenter &&+ codeArea.latitudeCenter - resolution >= -LATITUDE_MAX_+ ) {// If the proposed code is more than half a cell north of the reference location,// it's too far, and the best match will be one cell south.codeArea.latitudeCenter -= resolution;- } else if (referenceLatitude - halfResolution > codeArea.latitudeCenter &&- codeArea.latitudeCenter + resolution <= LATITUDE_MAX_) {+ } else if (+ referenceLatitude - halfResolution > codeArea.latitudeCenter &&+ codeArea.latitudeCenter + resolution <= LATITUDE_MAX_+ ) {// If the proposed code is more than half a cell south of the reference location,// it's too far, and the best match will be one cell north.codeArea.latitudeCenter += resolution;@@ -411,8 +440,11 @@}return encode(- codeArea.latitudeCenter, codeArea.longitudeCenter, codeArea.codeLength);- };+ codeArea.latitudeCenter,+ codeArea.longitudeCenter,+ codeArea.codeLength+ );+ });/*** Remove characters from the start of an OLC code.@@ -430,8 +462,11 @@* @throws {Exception} if the passed code is not a valid full code or the* reference location values are not numbers.*/- var shorten = OpenLocationCode.shorten = function(- code, latitude, longitude) {+ var shorten = (OpenLocationCode.shorten = function(+ code,+ latitude,+ longitude+ ) {if (!isFull(code)) {throw 'ValueError: Passed code is not valid and full: ' + code;}@@ -442,31 +477,32 @@var codeArea = decode(code);if (codeArea.codeLength < MIN_TRIMMABLE_CODE_LEN_) {throw 'ValueError: Code length must be at least ' +- MIN_TRIMMABLE_CODE_LEN_;+ MIN_TRIMMABLE_CODE_LEN_;}// Ensure that latitude and longitude are valid.latitude = Number(latitude);longitude = Number(longitude);if (isNaN(latitude) || isNaN(longitude)) {- throw ('ValueError: Reference position are not numbers');+ throw 'ValueError: Reference position are not numbers';}latitude = clipLatitude(latitude);longitude = normalizeLongitude(longitude);// How close are the latitude and longitude to the code center.var range = Math.max(- Math.abs(codeArea.latitudeCenter - latitude),- Math.abs(codeArea.longitudeCenter - longitude));+ Math.abs(codeArea.latitudeCenter - latitude),+ Math.abs(codeArea.longitudeCenter - longitude)+ );for (var i = PAIR_RESOLUTIONS_.length - 2; i >= 1; i--) {// Check if we're close enough to shorten. The range must be less than 1/2// the resolution to shorten at all, and we want to allow some safety, so// use 0.3 instead of 0.5 as a multiplier.- if (range < (PAIR_RESOLUTIONS_[i] * 0.3)) {+ if (range < PAIR_RESOLUTIONS_[i] * 0.3) {// Trim it.return code.substring((i + 1) * 2);}}return code;- };+ });/*** Clip a latitude into the range -90 to 90.@@ -552,7 +588,9 @@}}if (code.length < SEPARATOR_POSITION_) {- code = code + Array(SEPARATOR_POSITION_ - code.length + 1).join(PADDING_CHARACTER_);+ code =+ code ++ Array(SEPARATOR_POSITION_ - code.length + 1).join(PADDING_CHARACTER_);}if (code.length == SEPARATOR_POSITION_) {code = code + SEPARATOR_;@@ -617,11 +655,12 @@var longitude = decodePairsSequence(code, 1);// Correct the values and set them into the CodeArea object.return new CodeArea(- latitude[0] - LATITUDE_MAX_,- longitude[0] - LONGITUDE_MAX_,- latitude[1] - LATITUDE_MAX_,- longitude[1] - LONGITUDE_MAX_,- code.length);+ latitude[0] - LATITUDE_MAX_,+ longitude[0] - LONGITUDE_MAX_,+ latitude[1] - LATITUDE_MAX_,+ longitude[1] - LONGITUDE_MAX_,+ code.length+ );};/**@@ -641,8 +680,9 @@var i = 0;var value = 0;while (i * 2 + offset < code.length) {- value += CODE_ALPHABET_.indexOf(code.charAt(i * 2 + offset)) *- PAIR_RESOLUTIONS_[i];+ value +=+ CODE_ALPHABET_.indexOf(code.charAt(i * 2 + offset)) *+ PAIR_RESOLUTIONS_[i];i += 1;}return [value, value + PAIR_RESOLUTIONS_[i - 1]];@@ -673,8 +713,12 @@i += 1;}return CodeArea(- latitudeLo, longitudeLo, latitudeLo + latPlaceValue,- longitudeLo + lngPlaceValue, code.length);+ latitudeLo,+ longitudeLo,+ latitudeLo + latPlaceValue,+ longitudeLo + lngPlaceValue,+ code.length+ );};/**@@ -686,14 +730,29 @@** @constructor*/- var CodeArea = OpenLocationCode.CodeArea = function(- latitudeLo, longitudeLo, latitudeHi, longitudeHi, codeLength) {+ var CodeArea = (OpenLocationCode.CodeArea = function(+ latitudeLo,+ longitudeLo,+ latitudeHi,+ longitudeHi,+ codeLength+ ) {return new OpenLocationCode.CodeArea.fn.init(- latitudeLo, longitudeLo, latitudeHi, longitudeHi, codeLength);- };+ latitudeLo,+ longitudeLo,+ latitudeHi,+ longitudeHi,+ codeLength+ );+ });CodeArea.fn = CodeArea.prototype = {init: function(- latitudeLo, longitudeLo, latitudeHi, longitudeHi, codeLength) {+ latitudeLo,+ longitudeLo,+ latitudeHi,+ longitudeHi,+ codeLength+ ) {/*** The latitude of the SW corner.* @type {number}@@ -724,16 +783,20 @@* @type {number}*/this.latitudeCenter = Math.min(- latitudeLo + (latitudeHi - latitudeLo) / 2, LATITUDE_MAX_);+ latitudeLo + (latitudeHi - latitudeLo) / 2,+ LATITUDE_MAX_+ );/*** The longitude of the center in degrees.* @type {number}*/this.longitudeCenter = Math.min(- longitudeLo + (longitudeHi - longitudeLo) / 2, LONGITUDE_MAX_);+ longitudeLo + (longitudeHi - longitudeLo) / 2,+ LONGITUDE_MAX_+ );}};CodeArea.fn.init.prototype = CodeArea.fn;return OpenLocationCode;-}));+});diff --git a/app/utils/paths.js b/app/utils/paths.jsindex c8852af83..691efa238 100644--- a/app/utils/paths.js+++ b/app/utils/paths.js@@ -21,13 +21,18 @@ import AppConfig from '../config';import { type Tag } from '../reducers/taglibrary';export function baseName(dirPath: string) {- const fileName = dirPath.substring(dirPath.lastIndexOf(AppConfig.dirSeparator) + 1, dirPath.length);+ const fileName = dirPath.substring(+ dirPath.lastIndexOf(AppConfig.dirSeparator) + 1,+ dirPath.length+ );return fileName || dirPath;}export function extractFileExtension(filePath: string) {const lastindexDirSeparator = filePath.lastIndexOf(AppConfig.dirSeparator);- const lastIndexEndTagContainer = filePath.lastIndexOf(AppConfig.endTagContainer);+ const lastIndexEndTagContainer = filePath.lastIndexOf(+ AppConfig.endTagContainer+ );const lastindexDot = filePath.lastIndexOf('.');if (lastindexDot < 0) {return '';@@ -38,9 +43,13 @@ export function extractFileExtension(filePath: string) {// case: "[20120125 89.4kg 19.5% 60.5% 39.8% 2.6kg]"return '';}- let extension = filePath.substring(lastindexDot + 1, filePath.length).toLowerCase().trim();+ let extension = filePath+ .substring(lastindexDot + 1, filePath.length)+ .toLowerCase()+ .trim();const lastindexQuestionMark = extension.lastIndexOf('?');- if (lastindexQuestionMark > 0) { // Removing everything after ? in URLs .png?queryParam1=2342+ if (lastindexQuestionMark > 0) {+ // Removing everything after ? in URLs .png?queryParam1=2342extension = extension.substring(0, lastindexQuestionMark);}return extension;@@ -50,20 +59,45 @@ export function extractFileExtension(filePath: string) {return (ext === fileURL) ? '' : ext; */}-export function getMetaDirectoryPath(directoryPath: string, dirSeparator: string = AppConfig.dirSeparator) {+export function getMetaDirectoryPath(+ directoryPath: string,+ dirSeparator: string = AppConfig.dirSeparator+) {return normalizePath(directoryPath) + dirSeparator + AppConfig.metaFolder;}-export function getMetaFileLocationForFile(entryPath: string, dirSeparator: string = AppConfig.dirSeparator) {- const containingFolder = extractContainingDirectoryPath(entryPath, dirSeparator);+export function getMetaFileLocationForFile(+ entryPath: string,+ dirSeparator: string = AppConfig.dirSeparator+) {+ const containingFolder = extractContainingDirectoryPath(+ entryPath,+ dirSeparator+ );const metaFolder = getMetaDirectoryPath(containingFolder, dirSeparator);- return metaFolder + dirSeparator + extractFileName(entryPath, dirSeparator) + AppConfig.metaFileExt;+ return (+ metaFolder ++ dirSeparator ++ extractFileName(entryPath, dirSeparator) ++ AppConfig.metaFileExt+ );}-export function getThumbFileLocationForFile(entryPath: string, dirSeparator: string = AppConfig.dirSeparator) {- const containingFolder = extractContainingDirectoryPath(entryPath, dirSeparator);+export function getThumbFileLocationForFile(+ entryPath: string,+ dirSeparator: string = AppConfig.dirSeparator+) {+ const containingFolder = extractContainingDirectoryPath(+ entryPath,+ dirSeparator+ );const metaFolder = getMetaDirectoryPath(containingFolder, dirSeparator);- return metaFolder + dirSeparator + extractFileName(entryPath, dirSeparator) + AppConfig.thumbFileExt;+ return (+ metaFolder ++ dirSeparator ++ extractFileName(entryPath, dirSeparator) ++ AppConfig.thumbFileExt+ );}export function getMetaFileLocationForDir(entryPath: string) {@@ -71,8 +105,14 @@ export function getMetaFileLocationForDir(entryPath: string) {return metaFolder + AppConfig.dirSeparator + AppConfig.metaFolderFile;}-export function extractFileName(filePath: string, dirSeparator: string = AppConfig.dirSeparator): string {- return filePath.substring(filePath.lastIndexOf(dirSeparator) + 1, filePath.length);+export function extractFileName(+ filePath: string,+ dirSeparator: string = AppConfig.dirSeparator+): string {+ return filePath.substring(+ filePath.lastIndexOf(dirSeparator) + 1,+ filePath.length+ );}export function cleanTrailingDirSeparator(dirPath: string): string {@@ -100,9 +140,16 @@ export function normalizePath(path: string): string {export function extractFileNameWithoutExt(filePath: string): string {const fileName = extractFileName(filePath);const indexOfDot = fileName.lastIndexOf('.');- const lastIndexBeginTagContainer = fileName.lastIndexOf(AppConfig.beginTagContainer);- const lastIndexEndTagContainer = fileName.lastIndexOf(AppConfig.endTagContainer);- if (lastIndexBeginTagContainer === 0 && lastIndexEndTagContainer + 1 === fileName.length) {+ const lastIndexBeginTagContainer = fileName.lastIndexOf(+ AppConfig.beginTagContainer+ );+ const lastIndexEndTagContainer = fileName.lastIndexOf(+ AppConfig.endTagContainer+ );+ if (+ lastIndexBeginTagContainer === 0 &&+ lastIndexEndTagContainer + 1 === fileName.length+ ) {// case: "[tag1 tag.2]"return '';} else if (indexOfDot > 0) {@@ -115,11 +162,17 @@ export function extractFileNameWithoutExt(filePath: string): string {return fileName;}-export function extractContainingDirectoryPath(filePath: string, dirSeparator: string = AppConfig.dirSeparator) {+export function extractContainingDirectoryPath(+ filePath: string,+ dirSeparator: string = AppConfig.dirSeparator+) {return filePath.substring(0, filePath.lastIndexOf(dirSeparator));}-export function extractParentDirectoryPath(dirPath: string, dirSeparator: string = AppConfig.dirSeparator) {+export function extractParentDirectoryPath(+ dirPath: string,+ dirSeparator: string = AppConfig.dirSeparator+) {if (!dirPath) return;if (dirPath.endsWith(dirSeparator)) {dirPath = dirPath.substring(0, dirPath.lastIndexOf(dirSeparator));@@ -127,17 +180,26 @@ export function extractParentDirectoryPath(dirPath: string, dirSeparator: stringreturn dirPath.substring(0, dirPath.lastIndexOf(dirSeparator));}-export function extractDirectoryName(dirPath: string, dirSeparator: string = AppConfig.dirSeparator): string {+export function extractDirectoryName(+ dirPath: string,+ dirSeparator: string = AppConfig.dirSeparator+): string {if (!dirPath) return '';let directoryName;if (dirPath.endsWith(dirSeparator)) {directoryName = dirPath.substring(0, dirPath.lastIndexOf(dirSeparator));}- directoryName = dirPath.substring(dirPath.lastIndexOf(dirSeparator) + 1, dirPath.length);+ directoryName = dirPath.substring(+ dirPath.lastIndexOf(dirSeparator) + 1,+ dirPath.length+ );return directoryName;}-export function extractShortDirectoryName(dirPath: string, dirSeparator: string = AppConfig.dirSeparator) {+export function extractShortDirectoryName(+ dirPath: string,+ dirSeparator: string = AppConfig.dirSeparator+) {let shortDirName: string = extractDirectoryName(dirPath, dirSeparator);if (shortDirName.length > 20) {shortDirName = shortDirName.substr(0, 20) + '...';@@ -146,8 +208,14 @@ export function extractShortDirectoryName(dirPath: string, dirSeparator: string}export function extractContainingDirectoryName(filePath: string) {- const tmpStr = filePath.substring(0, filePath.lastIndexOf(AppConfig.dirSeparator));- return tmpStr.substring(tmpStr.lastIndexOf(AppConfig.dirSeparator) + 1, tmpStr.length);+ const tmpStr = filePath.substring(+ 0,+ filePath.lastIndexOf(AppConfig.dirSeparator)+ );+ return tmpStr.substring(+ tmpStr.lastIndexOf(AppConfig.dirSeparator) + 1,+ tmpStr.length+ );}export function extractTitle(entryPath: string, isDirectory?: boolean = false) {@@ -176,7 +244,10 @@ export function extractTitle(entryPath: string, isDirectory?: boolean = false) {return title.slice(0, beginTagContainer);}// case: "title1 [tag1 tag2] title2"- return title.slice(0, beginTagContainer) + title.slice(endTagContainer + 1, title.length);+ return (+ title.slice(0, beginTagContainer) ++ title.slice(endTagContainer + 1, title.length)+ );}try {title = decodeURIComponent(title);@@ -186,10 +257,13 @@ export function extractTitle(entryPath: string, isDirectory?: boolean = false) {return title;}-export function extractTagsAsObjects(filePath: string, tagDelimiter: string): Array<Tag> {+export function extractTagsAsObjects(+ filePath: string,+ tagDelimiter: string+): Array<Tag> {const tagsInFileName = extractTags(filePath, tagDelimiter);const tagArray = [];- tagsInFileName.map((tag) => {+ tagsInFileName.map(tag => {tagArray.push({title: '' + tag,type: 'plain'@@ -200,7 +274,8 @@ export function extractTagsAsObjects(filePath: string, tagDelimiter: string): Ar}export function extractTags(filePath: string, tagDelimiter: string) {- if (tagDelimiter === undefined) { // TODO get tagDelimiter from settings reducer only+ if (tagDelimiter === undefined) {+ // TODO get tagDelimiter from settings reducer only// eslint-disable-next-line no-param-reassigntagDelimiter = AppConfig.tagDelimiter;}@@ -210,12 +285,18 @@ export function extractTags(filePath: string, tagDelimiter: string) {let tags = [];const beginTagContainer = fileName.indexOf(AppConfig.beginTagContainer);const endTagContainer = fileName.indexOf(AppConfig.endTagContainer);- if (beginTagContainer < 0 || endTagContainer < 0 || beginTagContainer >= endTagContainer) {+ if (+ beginTagContainer < 0 ||+ endTagContainer < 0 ||+ beginTagContainer >= endTagContainer+ ) {// console.log('Filename does not contains tags. Aborting extraction.');return tags;}const cleanedTags = [];- const tagContainer = fileName.slice(beginTagContainer + 1, endTagContainer).trim();+ const tagContainer = fileName+ .slice(beginTagContainer + 1, endTagContainer)+ .trim();tags = tagContainer.split(tagDelimiter);for (let i = 0; i < tags.length; i += 1) {// Min tag length set to 1 characterdiff --git a/resources/builder.json b/resources/builder.jsonindex 0c4813292..1bdb16ce5 100644--- a/resources/builder.json+++ b/resources/builder.json@@ -28,9 +28,7 @@"icon": "resources/icon.ico"},"mac": {- "target": [- "zip"- ],+ "target": ["zip"],"icon": "resources/icon.icns"},"linux": {diff --git a/scripts/genswconf.js b/scripts/genswconf.jsindex e743933a2..e4b77c646 100644--- a/scripts/genswconf.js+++ b/scripts/genswconf.js@@ -1,30 +1,29 @@const sh = require('shelljs');const { version, productName } = require('../app/package.json');-const FILES_TO_CACHE = [- 'offline.html',-];+const FILES_TO_CACHE = ['offline.html'];sh.cd('web/dist');-sh.ls('*.js').forEach((file) => {+sh.ls('*.js').forEach(file => {FILES_TO_CACHE.push('dist/' + file);});-sh.ls('*.ttf').forEach((file) => {+sh.ls('*.ttf').forEach(file => {FILES_TO_CACHE.push('dist/' + file);});-sh.ls('*.woff*').forEach((file) => {+sh.ls('*.woff*').forEach(file => {FILES_TO_CACHE.push('dist/' + file);});-sh.ls('*.css').forEach((file) => {+sh.ls('*.css').forEach(file => {FILES_TO_CACHE.push('dist/' + file);});let CACHE_STRING = '\nconst FILES_TO_CACHE = [\n';-FILES_TO_CACHE.forEach((file) => {+FILES_TO_CACHE.forEach(file => {CACHE_STRING += ' "' + file + '",\n';});CACHE_STRING += '];';-const buildTime = (new Date()).getTime(); // toISOString();-sh.echo('const CACHE_NAME = "TS-' + version + '-' + buildTime + '";' + CACHE_STRING)- .to('../sw-config.js');+const buildTime = new Date().getTime(); // toISOString();+sh.echo(+ 'const CACHE_NAME = "TS-' + version + '-' + buildTime + '";' + CACHE_STRING+).to('../sw-config.js');diff --git a/scripts/setupextensions.js b/scripts/setupextensions.jsindex ae29bf7c7..87cd047af 100644--- a/scripts/setupextensions.js+++ b/scripts/setupextensions.js@@ -15,23 +15,91 @@ const extensionDir = 'extensions';const extensionBranch = 'master';const extensionList = [- { package: '@tagspaces/document-viewer', path: 'viewerDocument', url: 'https://github.com/tagspaces/viewerDocument' },- { package: '@tagspaces/pdf-viewer', path: 'viewerPDF', url: 'https://github.com/tagspaces/viewerPDF' },- { package: '@tagspaces/image-viewer', path: 'viewerImage', url: 'https://github.com/tagspaces/viewerImage' },- { package: '@tagspaces/html-viewer', path: 'viewerHTML', url: 'https://github.com/tagspaces/viewerHTML' },- { package: '@tagspaces/md-viewer', path: 'viewerMD', url: 'https://github.com/tagspaces/viewerMD' },- { package: '@tagspaces/url-viewer', path: 'viewerURL', url: 'https://github.com/tagspaces/viewerURL' },- { package: '@tagspaces/media-player', path: 'viewerAudioVideo', url: 'https://github.com/tagspaces/viewerAudioVideo' },- { package: '@tagspaces/plain-viewer', path: 'viewerBrowser', url: 'https://github.com/tagspaces/viewerBrowser' },- { package: '@tagspaces/mhtml-viewer', path: 'viewerMHTML', url: 'https://github.com/tagspaces/viewerMHTML' },- { package: '@tagspaces/rtf-viewer', path: 'viewerRTF', url: 'https://github.com/tagspaces/viewerRTF' },- { package: '@tagspaces/text-viewer', path: 'viewerText', url: 'https://github.com/tagspaces/viewerText' },- { package: '@tagspaces/archive-viewer', path: 'viewerZIP', url: 'https://github.com/tagspaces/viewerZIP' },- { package: '@tagspaces/ebook-viewer', path: 'viewerEPUB', url: 'https://github.com/tagspaces/viewerEPUB' },- { package: '@tagspaces/text-editor', path: 'editorText', url: 'https://github.com/tagspaces/editorText' },- { package: '@tagspaces/json-editor', path: 'editorJSON', url: 'https://github.com/tagspaces/editorJSON' },- { package: '@tagspaces/html-editor', path: 'editorHTML', url: 'https://github.com/tagspaces/editorHTML' },- { package: '@tagspaces/legacy-ext', path: 'extCommons', url: 'https://github.com/tagspaces/extCommons' },+ {+ package: '@tagspaces/document-viewer',+ path: 'viewerDocument',+ url: 'https://github.com/tagspaces/viewerDocument'+ },+ {+ package: '@tagspaces/pdf-viewer',+ path: 'viewerPDF',+ url: 'https://github.com/tagspaces/viewerPDF'+ },+ {+ package: '@tagspaces/image-viewer',+ path: 'viewerImage',+ url: 'https://github.com/tagspaces/viewerImage'+ },+ {+ package: '@tagspaces/html-viewer',+ path: 'viewerHTML',+ url: 'https://github.com/tagspaces/viewerHTML'+ },+ {+ package: '@tagspaces/md-viewer',+ path: 'viewerMD',+ url: 'https://github.com/tagspaces/viewerMD'+ },+ {+ package: '@tagspaces/url-viewer',+ path: 'viewerURL',+ url: 'https://github.com/tagspaces/viewerURL'+ },+ {+ package: '@tagspaces/media-player',+ path: 'viewerAudioVideo',+ url: 'https://github.com/tagspaces/viewerAudioVideo'+ },+ {+ package: '@tagspaces/plain-viewer',+ path: 'viewerBrowser',+ url: 'https://github.com/tagspaces/viewerBrowser'+ },+ {+ package: '@tagspaces/mhtml-viewer',+ path: 'viewerMHTML',+ url: 'https://github.com/tagspaces/viewerMHTML'+ },+ {+ package: '@tagspaces/rtf-viewer',+ path: 'viewerRTF',+ url: 'https://github.com/tagspaces/viewerRTF'+ },+ {+ package: '@tagspaces/text-viewer',+ path: 'viewerText',+ url: 'https://github.com/tagspaces/viewerText'+ },+ {+ package: '@tagspaces/archive-viewer',+ path: 'viewerZIP',+ url: 'https://github.com/tagspaces/viewerZIP'+ },+ {+ package: '@tagspaces/ebook-viewer',+ path: 'viewerEPUB',+ url: 'https://github.com/tagspaces/viewerEPUB'+ },+ {+ package: '@tagspaces/text-editor',+ path: 'editorText',+ url: 'https://github.com/tagspaces/editorText'+ },+ {+ package: '@tagspaces/json-editor',+ path: 'editorJSON',+ url: 'https://github.com/tagspaces/editorJSON'+ },+ {+ package: '@tagspaces/html-editor',+ path: 'editorHTML',+ url: 'https://github.com/tagspaces/editorHTML'+ },+ {+ package: '@tagspaces/legacy-ext',+ path: 'extCommons',+ url: 'https://github.com/tagspaces/extCommons'+ }];sh.rm('-rf', '~/.config/yarn/link/@tagspaces');@@ -42,7 +110,7 @@ if (!sh.test('-d', extensionDir)) {sh.cd(extensionDir);-extensionList.forEach((extension) => {+extensionList.forEach(extension => {if (sh.test('-d', extension.path)) {sh.cd(extension.path);sh.exec('git checkout ' + extensionBranch);@@ -57,7 +125,7 @@ extensionList.forEach((extension) => {});sh.cd('../app');-extensionList.forEach((extension) => {+extensionList.forEach(extension => {sh.exec('yarn link ' + extension.package);});sh.cd('..');diff --git a/scripts/versionmeta.js b/scripts/versionmeta.jsindex 90c7a1e32..444599298 100644--- a/scripts/versionmeta.js+++ b/scripts/versionmeta.js@@ -6,12 +6,25 @@ if (!sh.which('git')) {sh.exit(1);}-const buildTime = (new Date()).toISOString();-sh.exec('git log --format="%H" -n 1', { silent: true }, (code, lastCommitId) => {- if (lastCommitId.length > 1) {- lastCommitId = lastCommitId.slice(0, lastCommitId.length - 1);+const buildTime = new Date().toISOString();+sh.exec(+ 'git log --format="%H" -n 1',+ { silent: true },+ (code, lastCommitId) => {+ if (lastCommitId.length > 1) {+ lastCommitId = lastCommitId.slice(0, lastCommitId.length - 1);+ }+ sh.echo(+ '{"commitId": "' ++ lastCommitId ++ '", "buildTime": "' ++ buildTime ++ '", "version": "' ++ version ++ '", "name": "' ++ productName ++ '"}'+ ).to('app/version.json');+ // sh.sed('-i', 'BUILD_VERSION', 'v0.1.2', file);}- sh.echo('{"commitId": "' + lastCommitId + '", "buildTime": "' + buildTime + '", "version": "' + version + '", "name": "' + productName + '"}')- .to('app/version.json');- // sh.sed('-i', 'BUILD_VERSION', 'v0.1.2', file);-});+);diff --git a/scripts/webserver.js b/scripts/webserver.jsindex 9c3131f77..d2b8ce867 100644--- a/scripts/webserver.js+++ b/scripts/webserver.js@@ -3,6 +3,6 @@ var serveStatic = require('serve-static');const port = 8000;var app = express();-app.use(serveStatic('./web', { 'index': ['index.html'] }));+app.use(serveStatic('./web', { index: ['index.html'] }));app.listen(port);console.log('Webserver listining on http://127.0.0.1:' + port);diff --git a/web/pwa.js b/web/pwa.jsindex dbbfebfa9..4659c726d 100644--- a/web/pwa.js+++ b/web/pwa.js@@ -2,10 +2,15 @@if ('serviceWorker' in navigator) {window.addEventListener('load', () => {- navigator.serviceWorker.register('/sw.js').then((reg) => {- document.title = 'TagSpaces PWA - ' + document.location.hostname;- // console.log('TagSpaces service worker registered.', reg);- return true;- }).catch(err => console.warn('Error registering TagSpaces service worker ' + err));+ navigator.serviceWorker+ .register('/sw.js')+ .then(reg => {+ document.title = 'TagSpaces PWA - ' + document.location.hostname;+ // console.log('TagSpaces service worker registered.', reg);+ return true;+ })+ .catch(err =>+ console.warn('Error registering TagSpaces service worker ' + err)+ );});}diff --git a/web/sw.js b/web/sw.jsindex 02bca4ee1..48c2f8753 100644--- a/web/sw.js+++ b/web/sw.js@@ -2,41 +2,45 @@importScripts('sw-config.js');-self.addEventListener('install', (evt) => {+self.addEventListener('install', evt => {console.log('[ServiceWorker] Install');- caches.open(CACHE_NAME).then((cache) => {- console.log('[ServiceWorker] Pre-caching offline page');- return cache.addAll(FILES_TO_CACHE);- }).catch(err => console.warn('Error opening cache ' + err));+ caches+ .open(CACHE_NAME)+ .then(cache => {+ console.log('[ServiceWorker] Pre-caching offline page');+ return cache.addAll(FILES_TO_CACHE);+ })+ .catch(err => console.warn('Error opening cache ' + err));self.skipWaiting();});-self.addEventListener('activate', (evt) => {+self.addEventListener('activate', evt => {console.log('[ServiceWorker] Activate');evt.waitUntil(- caches.keys().then((keyList) => {- return Promise.all(keyList.map((key) => {- if (key !== CACHE_NAME) {- console.log('[ServiceWorker] Removing old cache', key);- return caches.delete(key);- }- }));+ caches.keys().then(keyList => {+ return Promise.all(+ keyList.map(key => {+ if (key !== CACHE_NAME) {+ console.log('[ServiceWorker] Removing old cache', key);+ return caches.delete(key);+ }+ })+ );}));self.clients.claim();});-self.addEventListener('fetch', (evt) => {+self.addEventListener('fetch', evt => {console.log('[ServiceWorker] Fetch', evt.request.url);if (evt.request.mode !== 'navigate') {return;}evt.respondWith(fetch(evt.request).catch(() => {- return caches.open(CACHE_NAME)- .then((cache) => {- return cache.match('offline.html');- });+ return caches.open(CACHE_NAME).then(cache => {+ return cache.match('offline.html');+ });}));});