From e648392330fae711d79ade2903c2f7e21e8f3425 Mon Sep 17 00:00:00 2001 From: Laurent Cozic Date: Thu, 19 Sep 2019 22:51:18 +0100 Subject: [PATCH] Chore: Apply eslint rules --- CliClient/app/ResourceServer.js | 6 +- CliClient/app/app-gui.js | 20 +-- CliClient/app/app.js | 12 +- CliClient/app/autocompletion.js | 28 +-- CliClient/app/build-doc.js | 10 +- CliClient/app/cli-integration-tests.js | 16 +- CliClient/app/cli-utils.js | 12 +- CliClient/app/command-apidoc.js | 22 +-- CliClient/app/command-e2ee.js | 14 +- CliClient/app/command-edit.js | 2 +- CliClient/app/command-export-sync-status.js | 4 +- CliClient/app/command-export.js | 2 +- CliClient/app/command-ls.js | 2 +- CliClient/app/command-server.js | 6 +- CliClient/app/command-set.js | 2 +- CliClient/app/command-status.js | 2 +- CliClient/app/command-sync.js | 8 +- CliClient/app/fuzzing.js | 42 ++--- CliClient/app/gui/FolderListWidget.js | 4 +- CliClient/app/gui/NoteListWidget.js | 2 +- CliClient/app/gui/NoteWidget.js | 2 +- CliClient/app/help-utils.js | 2 +- CliClient/app/main.js | 2 +- CliClient/app/onedrive-api-node-utils.js | 6 +- CliClient/tests/EnexToMd.js | 10 +- CliClient/tests/HtmlToMd.js | 10 +- CliClient/tests/StringUtils.js | 2 +- CliClient/tests/encryption.js | 6 +- CliClient/tests/models_Note.js | 12 +- CliClient/tests/models_Resource.js | 2 +- CliClient/tests/services_InteropService.js | 42 ++--- CliClient/tests/services_ResourceService.js | 22 +-- CliClient/tests/services_SearchEngine.js | 6 +- CliClient/tests/services_rest_Api.js | 26 +-- CliClient/tests/synchronizer.js | 28 +-- CliClient/tests/test-utils.js | 28 +-- Clipper/joplin-webclipper/background.js | 2 +- .../content_scripts/index.js | 22 +-- .../popup/scripts/postinstall.js | 2 +- Clipper/joplin-webclipper/popup/src/App.js | 14 +- Clipper/joplin-webclipper/popup/src/bridge.js | 20 +-- ElectronClient/app/ElectronAppWrapper.js | 8 +- ElectronClient/app/app.js | 34 ++-- ElectronClient/app/checkForUpdates.js | 14 +- ElectronClient/app/compile-package-info.js | 6 +- ElectronClient/app/compile.js | 22 +-- ElectronClient/app/electronRebuild.js | 10 +- ElectronClient/app/gui/ConfigMenuBar.jsx | 2 +- ElectronClient/app/gui/ConfigScreen.jsx | 14 +- ElectronClient/app/gui/ExtensionBadge.jsx | 6 +- ElectronClient/app/gui/Header.jsx | 12 +- ElectronClient/app/gui/IconButton.jsx | 2 +- ElectronClient/app/gui/NoteList.jsx | 6 +- .../app/gui/NotePropertiesDialog.jsx | 4 +- ElectronClient/app/gui/NoteRevisionViewer.jsx | 6 +- ElectronClient/app/gui/NoteSearchBar.jsx | 2 +- ElectronClient/app/gui/NoteText.jsx | 58 +++---- .../app/gui/OneDriveLoginScreen.jsx | 2 +- ElectronClient/app/gui/PromptDialog.jsx | 4 +- ElectronClient/app/gui/SideBar.jsx | 8 +- ElectronClient/app/gui/StatusScreen.jsx | 6 +- ElectronClient/app/gui/TagList.jsx | 2 +- ElectronClient/app/gui/Toolbar.jsx | 4 +- ElectronClient/app/gui/ToolbarButton.jsx | 2 +- ElectronClient/app/gui/utils/NoteListUtils.js | 2 +- ElectronClient/app/plugins/GotoAnything.jsx | 8 +- ElectronClient/app/theme.js | 4 +- ReactNativeClient/lib/BaseApplication.js | 22 +-- ReactNativeClient/lib/BaseModel.js | 38 ++-- ReactNativeClient/lib/Cache.js | 2 +- ReactNativeClient/lib/ClipperServer.js | 6 +- ReactNativeClient/lib/DropboxApi.js | 24 +-- ReactNativeClient/lib/SyncTargetDropbox.js | 4 +- ReactNativeClient/lib/SyncTargetOneDrive.js | 4 +- ReactNativeClient/lib/SyncTargetRegistry.js | 6 +- ReactNativeClient/lib/SyncTargetWebDAV.js | 4 +- ReactNativeClient/lib/TaskQueue.js | 8 +- ReactNativeClient/lib/TemplateUtils.js | 6 +- ReactNativeClient/lib/WebDavApi.js | 38 ++-- ReactNativeClient/lib/WelcomeUtils.js | 8 +- .../lib/components/action-button.js | 4 +- .../lib/components/global-style.js | 2 +- .../lib/components/note-body-viewer.js | 10 +- .../lib/components/screen-header.js | 8 +- .../lib/components/screens/config.js | 6 +- .../lib/components/screens/log.js | 2 +- .../lib/components/screens/note.js | 14 +- .../lib/components/screens/notes.js | 8 +- .../lib/components/screens/onedrive-login.js | 2 +- .../lib/components/screens/search.js | 2 +- .../lib/components/screens/status.js | 6 +- .../lib/components/shared/config-shared.js | 2 +- .../components/shared/dropbox-login-shared.js | 2 +- .../lib/components/shared/side-menu-shared.js | 2 +- .../lib/components/side-menu-content-note.js | 2 +- ReactNativeClient/lib/database.js | 34 ++-- .../lib/file-api-driver-dropbox.js | 4 +- .../lib/file-api-driver-local.js | 2 +- .../lib/file-api-driver-memory.js | 8 +- .../lib/file-api-driver-onedrive.js | 20 +-- .../lib/file-api-driver-webdav.js | 12 +- ReactNativeClient/lib/file-api.js | 20 +-- ReactNativeClient/lib/fs-driver-base.js | 12 +- ReactNativeClient/lib/fs-driver-node.js | 6 +- ReactNativeClient/lib/geolocation-node.js | 6 +- ReactNativeClient/lib/htmlUtils.js | 12 +- ReactNativeClient/lib/import-enex-html-gen.js | 6 +- ReactNativeClient/lib/import-enex-md-gen.js | 38 ++-- ReactNativeClient/lib/import-enex.js | 12 +- ReactNativeClient/lib/joplin-database.js | 26 +-- ReactNativeClient/lib/locale.js | 6 +- ReactNativeClient/lib/logger.js | 18 +- ReactNativeClient/lib/markupLanguageUtils.js | 2 +- ReactNativeClient/lib/models/BaseItem.js | 54 +++--- ReactNativeClient/lib/models/Note.js | 24 +-- ReactNativeClient/lib/models/NoteTag.js | 2 +- ReactNativeClient/lib/models/Resource.js | 26 +-- ReactNativeClient/lib/models/Revision.js | 16 +- ReactNativeClient/lib/models/Setting.js | 20 +-- ReactNativeClient/lib/models/Tag.js | 8 +- ReactNativeClient/lib/net-utils.js | 2 +- ReactNativeClient/lib/onedrive-api.js | 26 +-- ReactNativeClient/lib/path-utils.js | 8 +- ReactNativeClient/lib/reducer.js | 4 +- ReactNativeClient/lib/registry.js | 6 +- .../lib/renderers/MarkupToHtml.js | 2 +- ReactNativeClient/lib/renderers/MdToHtml.js | 16 +- .../lib/renderers/MdToHtml/rules/checkbox.js | 6 +- .../renderers/MdToHtml/rules/html_image.js | 4 +- .../lib/renderers/MdToHtml/rules/image.js | 2 +- .../lib/renderers/MdToHtml/rules/katex.js | 14 +- .../lib/renderers/MdToHtml/rules/link_open.js | 12 +- ReactNativeClient/lib/renderers/noteStyle.js | 162 +++++++++--------- ReactNativeClient/lib/renderers/utils.js | 6 +- ReactNativeClient/lib/renderers/webviewLib.js | 4 +- .../lib/services/AlarmService.js | 8 +- .../services/AlarmServiceDriver.android.js | 4 +- .../lib/services/AlarmServiceDriver.ios.js | 6 +- .../lib/services/AlarmServiceDriverNode.js | 2 +- .../lib/services/DecryptionWorker.js | 12 +- .../lib/services/EncryptionService.js | 30 ++-- .../lib/services/ExternalEditWatcher.js | 24 +-- .../lib/services/InteropService.js | 12 +- .../services/InteropService_Exporter_Base.js | 2 +- .../services/InteropService_Exporter_Jex.js | 2 +- .../services/InteropService_Exporter_Json.js | 6 +- .../services/InteropService_Exporter_Md.js | 16 +- .../services/InteropService_Exporter_Raw.js | 6 +- .../services/InteropService_Importer_Base.js | 2 +- .../services/InteropService_Importer_Jex.js | 2 +- .../services/InteropService_Importer_Md.js | 8 +- .../services/InteropService_Importer_Raw.js | 8 +- ReactNativeClient/lib/services/KvStore.js | 8 +- .../lib/services/MigrationService.js | 4 +- .../lib/services/PluginManager.js | 2 +- .../lib/services/ResourceFetcher.js | 16 +- .../lib/services/ResourceService.js | 6 +- .../lib/services/RevisionService.js | 10 +- .../lib/services/SearchEngine.js | 16 +- .../lib/services/SearchEngineUtils.js | 2 +- ReactNativeClient/lib/services/report.js | 4 +- ReactNativeClient/lib/services/rest/Api.js | 42 ++--- ReactNativeClient/lib/shim-init-node.js | 14 +- ReactNativeClient/lib/shim-init-react.js | 14 +- ReactNativeClient/lib/string-utils-common.js | 2 +- ReactNativeClient/lib/string-utils.js | 10 +- ReactNativeClient/lib/synchronizer.js | 30 ++-- ReactNativeClient/lib/time-utils.js | 12 +- ReactNativeClient/lib/urlUtils.js | 4 +- ReactNativeClient/root.js | 8 +- Tools/build-release-stats.js | 20 +-- Tools/build-translation.js | 108 ++++++------ Tools/build-website.js | 16 +- Tools/build-welcome.js | 18 +- Tools/buildReactNativeInjectedJs.js | 10 +- Tools/copycss.js | 14 +- Tools/git-changelog.js | 20 +-- Tools/release-android.js | 60 +++---- Tools/release-cli.js | 22 +-- Tools/release-clipper.js | 44 ++--- Tools/release-electron.js | 12 +- Tools/tool-utils.js | 16 +- Tools/update-homebrew.js | 10 +- Tools/update-readme-contributors.js | 14 +- Tools/update-readme-download.js | 14 +- 185 files changed, 1196 insertions(+), 1196 deletions(-) diff --git a/CliClient/app/ResourceServer.js b/CliClient/app/ResourceServer.js index c17d6e6c0..b2e9aea84 100644 --- a/CliClient/app/ResourceServer.js +++ b/CliClient/app/ResourceServer.js @@ -28,7 +28,7 @@ class ResourceServer { baseUrl() { if (!this.port_) return ''; - return 'http://127.0.0.1:' + this.port_; + return `http://127.0.0.1:${this.port_}`; } setLinkHandler(handler) { @@ -53,7 +53,7 @@ class ResourceServer { const url = urlParser.parse(request.url, true); let resourceId = url.pathname.split('/'); if (resourceId.length < 2) { - writeResponse('Error: could not get resource ID from path name: ' + url.pathname); + writeResponse(`Error: could not get resource ID from path name: ${url.pathname}`); return; } resourceId = resourceId[1]; @@ -62,7 +62,7 @@ class ResourceServer { try { const done = await this.linkHandler_(resourceId, response); - if (!done) throw new Error('Unhandled resource: ' + resourceId); + if (!done) throw new Error(`Unhandled resource: ${resourceId}`); } catch (error) { response.setHeader('Content-Type', 'text/plain'); // eslint-disable-next-line require-atomic-updates diff --git a/CliClient/app/app-gui.js b/CliClient/app/app-gui.js index bb6e8625b..23268ed16 100644 --- a/CliClient/app/app-gui.js +++ b/CliClient/app/app-gui.js @@ -288,7 +288,7 @@ class AppGui { if (!cmd) return; const isConfigPassword = cmd.indexOf('config ') >= 0 && cmd.indexOf('password') >= 0; if (isConfigPassword) return; - this.stdout(chalk.cyan.bold('> ' + cmd)); + this.stdout(chalk.cyan.bold(`> ${cmd}`)); } setupKeymap(keymap) { @@ -297,7 +297,7 @@ class AppGui { for (let i = 0; i < keymap.length; i++) { const item = Object.assign({}, keymap[i]); - if (!item.command) throw new Error('Missing command for keymap item: ' + JSON.stringify(item)); + if (!item.command) throw new Error(`Missing command for keymap item: ${JSON.stringify(item)}`); if (!('type' in item)) item.type = 'exec'; @@ -440,7 +440,7 @@ class AppGui { if (!item) return; if (item.type_ === BaseModel.TYPE_FOLDER) { - await this.processPromptCommand('rmbook ' + item.id); + await this.processPromptCommand(`rmbook ${item.id}`); } else if (item.type_ === BaseModel.TYPE_TAG) { this.stdout(_('To delete a tag, untag the associated notes.')); } else if (item.type_ === BaseModel.TYPE_SEARCH) { @@ -473,7 +473,7 @@ class AppGui { this.addCommandToConsole(cmd); await this.processPromptCommand(cmd); } else { - throw new Error('Unknown command: ' + cmd); + throw new Error(`Unknown command: ${cmd}`); } } @@ -593,7 +593,7 @@ class AppGui { if (!s) return false; s = s.trim().toLowerCase(); for (let i = 0; i < protocols.length; i++) { - if (s.indexOf(protocols[i] + '://') === 0) return true; + if (s.indexOf(`${protocols[i]}://`) === 0) return true; } return false; }; @@ -627,7 +627,7 @@ class AppGui { if (link.type === 'item') { const itemId = link.id; let item = await BaseItem.loadItemById(itemId); - if (!item) throw new Error('No item with ID ' + itemId); // Should be nearly impossible + if (!item) throw new Error(`No item with ID ${itemId}`); // Should be nearly impossible if (item.type_ === BaseModel.TYPE_RESOURCE) { if (item.mime) response.setHeader('Content-Type', item.mime); @@ -640,11 +640,11 @@ class AppGui { `, ]; - html.push('
' + htmlentities(item.title) + '\n\n' + htmlentities(item.body) + '
'); + html.push(`
${htmlentities(item.title)}\n\n${htmlentities(item.body)}
`); html.push(''); response.write(html.join('')); } else { - throw new Error('Unsupported item type: ' + item.type_); + throw new Error(`Unsupported item type: ${item.type_}`); } return true; @@ -676,7 +676,7 @@ class AppGui { return url; } - return linkStyle(this.resourceServer_.baseUrl() + '/' + index); + return linkStyle(`${this.resourceServer_.baseUrl()}/${index}`); }, }; } @@ -777,7 +777,7 @@ class AppGui { } else if (keymapItem.type === 'tkwidgets') { this.widget('root').handleKey(this.tkWidgetKeys_[keymapItem.command]); } else { - throw new Error('Unknown command type: ' + JSON.stringify(keymapItem)); + throw new Error(`Unknown command type: ${JSON.stringify(keymapItem)}`); } } diff --git a/CliClient/app/app.js b/CliClient/app/app.js index dbad25c77..250582659 100644 --- a/CliClient/app/app.js +++ b/CliClient/app/app.js @@ -136,10 +136,10 @@ class Application extends BaseApplication { if (!options.answers) options.answers = options.booleanAnswerDefault === 'y' ? [_('Y'), _('n')] : [_('N'), _('y')]; if (options.type == 'boolean') { - message += ' (' + options.answers.join('/') + ')'; + message += ` (${options.answers.join('/')})`; } - let answer = await this.gui().prompt('', message + ' ', options); + let answer = await this.gui().prompt('', `${message} `, options); if (options.type === 'boolean') { if (answer === null) return false; // Pressed ESCAPE @@ -181,7 +181,7 @@ class Application extends BaseApplication { const ext = fileExtension(path); if (ext != 'js') return; - let CommandClass = require('./' + path); + let CommandClass = require(`./${path}`); let cmd = new CommandClass(); if (!cmd.enabled()) return; cmd = this.setupCommand(cmd); @@ -248,7 +248,7 @@ class Application extends BaseApplication { let CommandClass = null; try { - CommandClass = require(__dirname + '/command-' + name + '.js'); + CommandClass = require(`${__dirname}/command-${name}.js`); } catch (error) { if (error.message && error.message.indexOf('Cannot find module') >= 0) { let e = new Error(_('No such command: %s', name)); @@ -343,7 +343,7 @@ class Application extends BaseApplication { itemsByCommand[defaultKeyMap[i].command] = defaultKeyMap[i]; } - const filePath = Setting.value('profileDir') + '/keymap.json'; + const filePath = `${Setting.value('profileDir')}/keymap.json`; if (await fs.pathExists(filePath)) { try { let configString = await fs.readFile(filePath, 'utf-8'); @@ -355,7 +355,7 @@ class Application extends BaseApplication { } } catch (error) { let msg = error.message ? error.message : ''; - msg = 'Could not load keymap ' + filePath + '\n' + msg; + msg = `Could not load keymap ${filePath}\n${msg}`; error.message = msg; throw error; } diff --git a/CliClient/app/autocompletion.js b/CliClient/app/autocompletion.js index 99edb885b..dd2175c9c 100644 --- a/CliClient/app/autocompletion.js +++ b/CliClient/app/autocompletion.js @@ -16,9 +16,9 @@ async function handleAutocompletionPromise(line) { if (names.indexOf(words[0]) === -1) { let x = names.filter(n => n.indexOf(words[0]) === 0); if (x.length === 1) { - return x[0] + ' '; + return `${x[0]} `; } - return x.length > 0 ? x.map(a => a + ' ') : line; + return x.length > 0 ? x.map(a => `${a} `) : line; } else { return line; } @@ -56,7 +56,7 @@ async function handleAutocompletionPromise(line) { return line; } let ret = l.map(a => toCommandLine(a)); - ret.prefix = toCommandLine(words.slice(0, -1)) + ' '; + ret.prefix = `${toCommandLine(words.slice(0, -1))} `; return ret; } //Complete an argument @@ -74,23 +74,23 @@ async function handleAutocompletionPromise(line) { const currentFolder = app().currentFolder(); if (argName == 'note' || argName == 'note-pattern') { - const notes = currentFolder ? await Note.previews(currentFolder.id, { titlePattern: next + '*' }) : []; + const notes = currentFolder ? await Note.previews(currentFolder.id, { titlePattern: `${next}*` }) : []; l.push(...notes.map(n => n.title)); } if (argName == 'notebook') { - const folders = await Folder.search({ titlePattern: next + '*' }); + const folders = await Folder.search({ titlePattern: `${next}*` }); l.push(...folders.map(n => n.title)); } if (argName == 'item') { - const notes = currentFolder ? await Note.previews(currentFolder.id, { titlePattern: next + '*' }) : []; - const folders = await Folder.search({ titlePattern: next + '*' }); + const notes = currentFolder ? await Note.previews(currentFolder.id, { titlePattern: `${next}*` }) : []; + const folders = await Folder.search({ titlePattern: `${next}*` }); l.push(...notes.map(n => n.title), folders.map(n => n.title)); } if (argName == 'tag') { - let tags = await Tag.search({ titlePattern: next + '*' }); + let tags = await Tag.search({ titlePattern: `${next}*` }); l.push(...tags.map(n => n.title)); } @@ -113,7 +113,7 @@ async function handleAutocompletionPromise(line) { return toCommandLine([...words.slice(0, -1), l[0]]); } else if (l.length > 1) { let ret = l.map(a => toCommandLine(a)); - ret.prefix = toCommandLine(words.slice(0, -1)) + ' '; + ret.prefix = `${toCommandLine(words.slice(0, -1))} `; return ret; } return line; @@ -128,9 +128,9 @@ function toCommandLine(args) { return args .map(function(a) { if (a.indexOf('"') !== -1 || a.indexOf(' ') !== -1) { - return '\'' + a + '\''; + return `'${a}'`; } else if (a.indexOf('\'') !== -1) { - return '"' + a + '"'; + return `"${a}"`; } else { return a; } @@ -138,11 +138,11 @@ function toCommandLine(args) { .join(' '); } else { if (args.indexOf('"') !== -1 || args.indexOf(' ') !== -1) { - return '\'' + args + '\' '; + return `'${args}' `; } else if (args.indexOf('\'') !== -1) { - return '"' + args + '" '; + return `"${args}" `; } else { - return args + ' '; + return `${args} `; } } } diff --git a/CliClient/app/build-doc.js b/CliClient/app/build-doc.js index cb0f63be8..877596a14 100644 --- a/CliClient/app/build-doc.js +++ b/CliClient/app/build-doc.js @@ -54,7 +54,7 @@ function getCommands() { const ext = fileExtension(path); if (ext != 'js') return; - let CommandClass = require('./' + path); + let CommandClass = require(`./${path}`); let cmd = new CommandClass(); if (!cmd.enabled()) return; if (cmd.hidden()) return; @@ -102,14 +102,14 @@ function getFooter() { output.push('WEBSITE'); output.push(''); - output.push(INDENT + 'https://joplinapp.org'); + output.push(`${INDENT}https://joplinapp.org`); output.push(''); output.push('LICENSE'); output.push(''); - let filePath = rootDir + '/LICENSE_' + languageCode(); - if (!fs.existsSync(filePath)) filePath = rootDir + '/LICENSE'; + let filePath = `${rootDir}/LICENSE_${languageCode()}`; + if (!fs.existsSync(filePath)) filePath = `${rootDir}/LICENSE`; const licenseText = fs.readFileSync(filePath, 'utf8'); output.push(wrap(licenseText, INDENT)); @@ -131,7 +131,7 @@ async function main() { const commandsText = commandBlocks.join('\n\n'); const footerText = getFooter(); - console.info(headerText + '\n\n' + 'USAGE' + '\n\n' + commandsText + '\n\n' + footerText); + console.info(`${headerText}\n\n` + 'USAGE' + `\n\n${commandsText}\n\n${footerText}`); } main().catch(error => { diff --git a/CliClient/app/cli-integration-tests.js b/CliClient/app/cli-integration-tests.js index 67760ef54..426118adc 100644 --- a/CliClient/app/cli-integration-tests.js +++ b/CliClient/app/cli-integration-tests.js @@ -16,8 +16,8 @@ process.on('unhandledRejection', (reason, p) => { console.error('Unhandled promise rejection', p, 'reason:', reason); }); -const baseDir = dirname(__dirname) + '/tests/cli-integration'; -const joplinAppPath = __dirname + '/main.js'; +const baseDir = `${dirname(__dirname)}/tests/cli-integration`; +const joplinAppPath = `${__dirname}/main.js`; const logger = new Logger(); logger.addTarget('console'); @@ -33,16 +33,16 @@ db.setLogger(dbLogger); function createClient(id) { return { id: id, - profileDir: baseDir + '/client' + id, + profileDir: `${baseDir}/client${id}`, }; } const client = createClient(1); function execCommand(client, command) { - let exePath = 'node ' + joplinAppPath; - let cmd = exePath + ' --update-geolocation-disabled --env dev --profile ' + client.profileDir + ' ' + command; - logger.info(client.id + ': ' + command); + let exePath = `node ${joplinAppPath}`; + let cmd = `${exePath} --update-geolocation-disabled --env dev --profile ${client.profileDir} ${command}`; + logger.info(`${client.id}: ${command}`); return new Promise((resolve, reject) => { exec(cmd, (error, stdout, stderr) => { @@ -217,7 +217,7 @@ async function main() { logger.info(await execCommand(client, 'version')); - await db.open({ name: client.profileDir + '/database.sqlite' }); + await db.open({ name: `${client.profileDir}/database.sqlite` }); BaseModel.db_ = db; await Setting.load(); @@ -230,7 +230,7 @@ async function main() { await clearDatabase(); let testName = n.substr(4).toLowerCase(); - process.stdout.write(testName + ': '); + process.stdout.write(`${testName}: `); await testUnits[n](); console.info(''); } diff --git a/CliClient/app/cli-utils.js b/CliClient/app/cli-utils.js index 0f1098bd0..e85076536 100644 --- a/CliClient/app/cli-utils.js +++ b/CliClient/app/cli-utils.js @@ -58,7 +58,7 @@ cliUtils.parseFlags = function(flags) { }; cliUtils.parseCommandArg = function(arg) { - if (arg.length <= 2) throw new Error('Invalid command arg: ' + arg); + if (arg.length <= 2) throw new Error(`Invalid command arg: ${arg}`); const c1 = arg[0]; const c2 = arg[arg.length - 1]; @@ -69,7 +69,7 @@ cliUtils.parseCommandArg = function(arg) { } else if (c1 == '[' && c2 == ']') { return { required: false, name: name }; } else { - throw new Error('Invalid command arg: ' + arg); + throw new Error(`Invalid command arg: ${arg}`); } }; @@ -82,7 +82,7 @@ cliUtils.makeCommandArgs = function(cmd, argv) { let booleanFlags = []; let aliases = {}; for (let i = 0; i < options.length; i++) { - if (options[i].length != 2) throw new Error('Invalid options: ' + options[i]); + if (options[i].length != 2) throw new Error(`Invalid options: ${options[i]}`); let flags = options[i][0]; flags = cliUtils.parseFlags(flags); @@ -136,7 +136,7 @@ cliUtils.promptMcq = function(message, answers) { message += '\n\n'; for (let n in answers) { if (!answers.hasOwnProperty(n)) continue; - message += _('%s: %s', n, answers[n]) + '\n'; + message += `${_('%s: %s', n, answers[n])}\n`; } message += '\n'; @@ -165,10 +165,10 @@ cliUtils.promptConfirm = function(message, answers = null) { output: process.stdout, }); - message += ' (' + answers.join('/') + ')'; + message += ` (${answers.join('/')})`; return new Promise((resolve) => { - rl.question(message + ' ', answer => { + rl.question(`${message} `, answer => { const ok = !answer || answer.toLowerCase() == answers[0].toLowerCase(); rl.close(); resolve(ok); diff --git a/CliClient/app/command-apidoc.js b/CliClient/app/command-apidoc.js index b571e8b66..8097cf2d0 100644 --- a/CliClient/app/command-apidoc.js +++ b/CliClient/app/command-apidoc.js @@ -168,7 +168,7 @@ class Command extends BaseCommand { // }); } - lines.push('# ' + toTitleCase(tableName)); + lines.push(`# ${toTitleCase(tableName)}`); lines.push(''); if (model.type === BaseModel.TYPE_FOLDER) { @@ -181,9 +181,9 @@ class Command extends BaseCommand { lines.push(this.createPropertiesTable(tableFields)); lines.push(''); - lines.push('## GET /' + tableName); + lines.push(`## GET /${tableName}`); lines.push(''); - lines.push('Gets all ' + tableName); + lines.push(`Gets all ${tableName}`); lines.push(''); if (model.type === BaseModel.TYPE_FOLDER) { @@ -191,9 +191,9 @@ class Command extends BaseCommand { lines.push(''); } - lines.push('## GET /' + tableName + '/:id'); + lines.push(`## GET /${tableName}/:id`); lines.push(''); - lines.push('Gets ' + singular + ' with ID :id'); + lines.push(`Gets ${singular} with ID :id`); lines.push(''); if (model.type === BaseModel.TYPE_TAG) { @@ -224,9 +224,9 @@ class Command extends BaseCommand { lines.push(''); } - lines.push('## POST /' + tableName); + lines.push(`## POST /${tableName}`); lines.push(''); - lines.push('Creates a new ' + singular); + lines.push(`Creates a new ${singular}`); lines.push(''); if (model.type === BaseModel.TYPE_RESOURCE) { @@ -270,14 +270,14 @@ class Command extends BaseCommand { lines.push(''); } - lines.push('## PUT /' + tableName + '/:id'); + lines.push(`## PUT /${tableName}/:id`); lines.push(''); - lines.push('Sets the properties of the ' + singular + ' with ID :id'); + lines.push(`Sets the properties of the ${singular} with ID :id`); lines.push(''); - lines.push('## DELETE /' + tableName + '/:id'); + lines.push(`## DELETE /${tableName}/:id`); lines.push(''); - lines.push('Deletes the ' + singular + ' with ID :id'); + lines.push(`Deletes the ${singular} with ID :id`); lines.push(''); if (model.type === BaseModel.TYPE_TAG) { diff --git a/CliClient/app/command-e2ee.js b/CliClient/app/command-e2ee.js index e3d761c41..a38a602e2 100644 --- a/CliClient/app/command-e2ee.js +++ b/CliClient/app/command-e2ee.js @@ -97,13 +97,13 @@ class Command extends BaseCommand { while (true) { try { const outputDir = options.output ? options.output : require('os').tmpdir(); - let outFile = outputDir + '/' + pathUtils.filename(args.path) + '.' + Date.now() + '.bin'; + let outFile = `${outputDir}/${pathUtils.filename(args.path)}.${Date.now()}.bin`; await EncryptionService.instance().decryptFile(args.path, outFile); const buffer = await readChunk(outFile, 0, 64); const detectedType = imageType(buffer); if (detectedType) { - const newOutFile = outFile + '.' + detectedType.ext; + const newOutFile = `${outFile}.${detectedType.ext}`; await shim.fsDriver().move(outFile, newOutFile); outFile = newOutFile; } @@ -150,7 +150,7 @@ class Command extends BaseCommand { for (let i = 0; i < paths.length; i++) { const path = paths[i]; - const fullPath = targetPath + '/' + path; + const fullPath = `${targetPath}/${path}`; const stat = await fs.stat(fullPath); // this.stdout(fullPath); @@ -160,7 +160,7 @@ class Command extends BaseCommand { for (let j = 0; j < resourcePaths.length; j++) { const resourcePath = resourcePaths[j]; resourceCount++; - const fullResourcePath = fullPath + '/' + resourcePath; + const fullResourcePath = `${fullPath}/${resourcePath}`; const isEncrypted = await EncryptionService.instance().fileIsEncrypted(fullResourcePath); if (isEncrypted) { encryptedResourceCount++; @@ -194,9 +194,9 @@ class Command extends BaseCommand { } } - this.stdout('Encrypted items: ' + encryptedItemCount + '/' + itemCount); - this.stdout('Encrypted resources: ' + encryptedResourceCount + '/' + resourceCount); - this.stdout('Other items (never encrypted): ' + otherItemCount); + this.stdout(`Encrypted items: ${encryptedItemCount}/${itemCount}`); + this.stdout(`Encrypted resources: ${encryptedResourceCount}/${resourceCount}`); + this.stdout(`Other items (never encrypted): ${otherItemCount}`); if (options.verbose) { this.stdout(''); diff --git a/CliClient/app/command-edit.js b/CliClient/app/command-edit.js index 9dc6b367a..a6dcf3292 100644 --- a/CliClient/app/command-edit.js +++ b/CliClient/app/command-edit.js @@ -60,7 +60,7 @@ class Command extends BaseCommand { const originalContent = await Note.serializeForEdit(note); - tempFilePath = Setting.value('tempDir') + '/' + uuid.create() + '.md'; + tempFilePath = `${Setting.value('tempDir')}/${uuid.create()}.md`; editorArgs.push(tempFilePath); await fs.writeFile(tempFilePath, originalContent); diff --git a/CliClient/app/command-export-sync-status.js b/CliClient/app/command-export-sync-status.js index 510bacff4..3db49b4bd 100644 --- a/CliClient/app/command-export-sync-status.js +++ b/CliClient/app/command-export-sync-status.js @@ -20,9 +20,9 @@ class Command extends BaseCommand { async action() { const service = new ReportService(); const csv = await service.basicItemList({ format: 'csv' }); - const filePath = Setting.value('profileDir') + '/syncReport-' + new Date().getTime() + '.csv'; + const filePath = `${Setting.value('profileDir')}/syncReport-${new Date().getTime()}.csv`; await fs.writeFileSync(filePath, csv); - this.stdout('Sync status exported to ' + filePath); + this.stdout(`Sync status exported to ${filePath}`); app() .gui() diff --git a/CliClient/app/command-export.js b/CliClient/app/command-export.js index e7acb002c..9532936ab 100644 --- a/CliClient/app/command-export.js +++ b/CliClient/app/command-export.js @@ -18,7 +18,7 @@ class Command extends BaseCommand { const formats = service .modules() .filter(m => m.type === 'exporter') - .map(m => m.format + (m.description ? ' (' + m.description + ')' : '')); + .map(m => m.format + (m.description ? ` (${m.description})` : '')); return [['--format ', _('Destination format: %s', formats.join(', '))], ['--note ', _('Exports only the given note.')], ['--notebook ', _('Exports only the given notebook.')]]; } diff --git a/CliClient/app/command-ls.js b/CliClient/app/command-ls.js index 54a1b8f1c..908350e6b 100644 --- a/CliClient/app/command-ls.js +++ b/CliClient/app/command-ls.js @@ -90,7 +90,7 @@ class Command extends BaseCommand { let title = item.title; if (!shortIdShown && (seenTitles.indexOf(item.title) >= 0 || !item.title)) { - title += ' (' + BaseModel.shortId(item.id) + ')'; + title += ` (${BaseModel.shortId(item.id)})`; } else { seenTitles.push(item.title); } diff --git a/CliClient/app/command-server.js b/CliClient/app/command-server.js index 91b6f3e70..eb1478b97 100644 --- a/CliClient/app/command-server.js +++ b/CliClient/app/command-server.js @@ -11,7 +11,7 @@ class Command extends BaseCommand { } description() { - return _('Start, stop or check the API server. To specify on which port it should run, set the api.port config variable. Commands are (%s).', ['start', 'stop', 'status'].join('|')) + ' This is an experimental feature - use at your own risks! It is recommended that the server runs off its own separate profile so that no two CLI instances access that profile at the same time. Use --profile to specify the profile path.'; + return `${_('Start, stop or check the API server. To specify on which port it should run, set the api.port config variable. Commands are (%s).', ['start', 'stop', 'status'].join('|'))} This is an experimental feature - use at your own risks! It is recommended that the server runs off its own separate profile so that no two CLI instances access that profile at the same time. Use --profile to specify the profile path.`; } async action(args) { @@ -20,7 +20,7 @@ class Command extends BaseCommand { const ClipperServer = require('lib/ClipperServer'); const stdoutFn = (s) => this.stdout(s); const clipperLogger = new Logger(); - clipperLogger.addTarget('file', { path: Setting.value('profileDir') + '/log-clipper.txt' }); + clipperLogger.addTarget('file', { path: `${Setting.value('profileDir')}/log-clipper.txt` }); clipperLogger.addTarget('console', { console: { info: stdoutFn, warn: stdoutFn, @@ -29,7 +29,7 @@ class Command extends BaseCommand { ClipperServer.instance().setDispatch(() => {}); ClipperServer.instance().setLogger(clipperLogger); - const pidPath = Setting.value('profileDir') + '/clipper-pid.txt'; + const pidPath = `${Setting.value('profileDir')}/clipper-pid.txt`; const runningOnPort = await ClipperServer.instance().isRunning(); if (command === 'start') { diff --git a/CliClient/app/command-set.js b/CliClient/app/command-set.js index de28bbce8..89f97e3c3 100644 --- a/CliClient/app/command-set.js +++ b/CliClient/app/command-set.js @@ -16,7 +16,7 @@ class Command extends BaseCommand { for (let i = 0; i < fields.length; i++) { const f = fields[i]; if (f.name === 'id') continue; - s.push(f.name + ' (' + Database.enumName('fieldType', f.type) + ')'); + s.push(`${f.name} (${Database.enumName('fieldType', f.type)})`); } return _('Sets the property of the given to the given [value]. Possible properties are:\n\n%s', s.join(', ')); diff --git a/CliClient/app/command-status.js b/CliClient/app/command-status.js index 20bf4dedd..aad423dd6 100644 --- a/CliClient/app/command-status.js +++ b/CliClient/app/command-status.js @@ -22,7 +22,7 @@ class Command extends BaseCommand { if (i > 0) this.stdout(''); - this.stdout('# ' + section.title); + this.stdout(`# ${section.title}`); this.stdout(''); for (let n in section.body) { diff --git a/CliClient/app/command-sync.js b/CliClient/app/command-sync.js index 81a39991f..02da9edac 100644 --- a/CliClient/app/command-sync.js +++ b/CliClient/app/command-sync.js @@ -72,7 +72,7 @@ class Command extends BaseCommand { }); this.oneDriveApiUtils_ = null; - Setting.setValue('sync.' + this.syncTargetId_ + '.auth', auth ? JSON.stringify(auth) : null); + Setting.setValue(`sync.${this.syncTargetId_}.auth`, auth ? JSON.stringify(auth) : null); if (!auth) { this.stdout(_('Authentication was not completed (did not receive an authentication token).')); return false; @@ -93,7 +93,7 @@ class Command extends BaseCommand { } const response = await api.execAuthToken(authCode); - Setting.setValue('sync.' + this.syncTargetId_ + '.auth', response.access_token); + Setting.setValue(`sync.${this.syncTargetId_}.auth`, response.access_token); api.setAuthToken(response.access_token); return true; } @@ -117,7 +117,7 @@ class Command extends BaseCommand { this.releaseLockFn_ = null; // Lock is unique per profile/database - const lockFilePath = require('os').tmpdir() + '/synclock_' + md5(escape(Setting.value('profileDir'))); // https://github.com/pvorb/node-md5/issues/41 + const lockFilePath = `${require('os').tmpdir()}/synclock_${md5(escape(Setting.value('profileDir')))}`; // https://github.com/pvorb/node-md5/issues/41 if (!(await fs.pathExists(lockFilePath))) await fs.writeFile(lockFilePath, 'synclock'); try { @@ -178,7 +178,7 @@ class Command extends BaseCommand { this.stdout(_('Starting synchronisation...')); - const contextKey = 'sync.' + this.syncTargetId_ + '.context'; + const contextKey = `sync.${this.syncTargetId_}.context`; let context = Setting.value(contextKey); context = context ? JSON.parse(context) : {}; diff --git a/CliClient/app/fuzzing.js b/CliClient/app/fuzzing.js index 0cf7f7dea..6905fc432 100644 --- a/CliClient/app/fuzzing.js +++ b/CliClient/app/fuzzing.js @@ -9,9 +9,9 @@ const lodash = require('lodash'); const exec = require('child_process').exec; const fs = require('fs-extra'); -const baseDir = dirname(__dirname) + '/tests/fuzzing'; -const syncDir = baseDir + '/sync'; -const joplinAppPath = __dirname + '/main.js'; +const baseDir = `${dirname(__dirname)}/tests/fuzzing`; +const syncDir = `${baseDir}/sync`; +const joplinAppPath = `${__dirname}/main.js`; let syncDurations = []; const fsDriver = new FsDriverNode(); @@ -29,7 +29,7 @@ process.on('unhandledRejection', (reason, p) => { function createClient(id) { return { id: id, - profileDir: baseDir + '/client' + id, + profileDir: `${baseDir}/client${id}`, }; } @@ -41,7 +41,7 @@ async function createClients() { promises.push(fs.remove(client.profileDir)); promises.push( execCommand(client, 'config sync.target 2').then(() => { - return execCommand(client, 'config sync.2.path ' + syncDir); + return execCommand(client, `config sync.2.path ${syncDir}`); }) ); output.push(client); @@ -2064,12 +2064,12 @@ function randomWord() { } function execCommand(client, command, options = {}) { - let exePath = 'node ' + joplinAppPath; - let cmd = exePath + ' --update-geolocation-disabled --env dev --log-level debug --profile ' + client.profileDir + ' ' + command; - logger.info(client.id + ': ' + command); + let exePath = `node ${joplinAppPath}`; + let cmd = `${exePath} --update-geolocation-disabled --env dev --log-level debug --profile ${client.profileDir} ${command}`; + logger.info(`${client.id}: ${command}`); if (options.killAfter) { - logger.info('Kill after: ' + options.killAfter); + logger.info(`Kill after: ${options.killAfter}`); } return new Promise((resolve, reject) => { @@ -2100,7 +2100,7 @@ async function clientItems(client) { try { return JSON.parse(itemsJson); } catch (error) { - throw new Error('Cannot parse JSON: ' + itemsJson); + throw new Error(`Cannot parse JSON: ${itemsJson}`); } } @@ -2136,13 +2136,13 @@ async function execRandomCommand(client) { if (!item) return; if (item.type_ == 1) { - return execCommand(client, 'rm -f ' + item.id); + return execCommand(client, `rm -f ${item.id}`); } else if (item.type_ == 2) { - return execCommand(client, 'rm -r -f ' + item.id); + return execCommand(client, `rm -r -f ${item.id}`); } else if (item.type_ == 5) { // tag } else { - throw new Error('Unknown type: ' + item.type_); + throw new Error(`Unknown type: ${item.type_}`); } }, 30, @@ -2168,7 +2168,7 @@ async function execRandomCommand(client) { let item = randomNote(items); if (!item) return; - return execCommand(client, 'set ' + item.id + ' title "' + randomWord() + '"'); + return execCommand(client, `set ${item.id} title "${randomWord()}"`); }, 50, ], @@ -2180,9 +2180,9 @@ async function execRandomCommand(client) { if (!note) return; let tag = randomTag(items); - let tagTitle = !tag || Math.random() >= 0.9 ? 'tag-' + randomWord() : tag.title; + let tagTitle = !tag || Math.random() >= 0.9 ? `tag-${randomWord()}` : tag.title; - return execCommand(client, 'tag add ' + tagTitle + ' ' + note.id); + return execCommand(client, `tag add ${tagTitle} ${note.id}`); }, 50, ], @@ -2211,7 +2211,7 @@ function averageSyncDuration() { function randomNextCheckTime() { let output = time.unixMs() + 1000 + Math.random() * 1000 * 120; - logger.info('Next sync check: ' + time.unixMsToIso(output) + ' (' + Math.round((output - time.unixMs()) / 1000) + ' sec.)'); + logger.info(`Next sync check: ${time.unixMsToIso(output)} (${Math.round((output - time.unixMs()) / 1000)} sec.)`); return output; } @@ -2274,7 +2274,7 @@ async function compareClientItems(clientItems) { let items = clientItems[i]; itemCounts.push(items.length); } - logger.info('Item count: ' + itemCounts.join(', ')); + logger.info(`Item count: ${itemCounts.join(', ')}`); let missingItems = findMissingItems(clientItems[0], clientItems[1]); if (missingItems[0].length || missingItems[1].length) { @@ -2290,7 +2290,7 @@ async function compareClientItems(clientItems) { for (let clientId = 1; clientId < clientItems.length; clientId++) { let item2 = findItem(clientItems[clientId], item1.id); if (!item2) { - logger.error('Item not found on client ' + clientId + ':'); + logger.error(`Item not found on client ${clientId}:`); logger.error(item1); process.exit(1); } @@ -2329,12 +2329,12 @@ async function main() { execRandomCommand(clients[clientId]) .catch(error => { - logger.info('Client ' + clientId + ':'); + logger.info(`Client ${clientId}:`); logger.error(error); }) .then(r => { if (r) { - logger.info('Client ' + clientId + ':\n' + r.trim()); + logger.info(`Client ${clientId}:\n${r.trim()}`); } clients[clientId].activeCommandCount--; }); diff --git a/CliClient/app/gui/FolderListWidget.js b/CliClient/app/gui/FolderListWidget.js index 10f709191..a19cee54b 100644 --- a/CliClient/app/gui/FolderListWidget.js +++ b/CliClient/app/gui/FolderListWidget.js @@ -26,7 +26,7 @@ class FolderListWidget extends ListWidget { } else if (item.type_ === Folder.modelType()) { output.push(' '.repeat(this.folderDepth(this.folders, item.id)) + Folder.displayTitle(item)); } else if (item.type_ === Tag.modelType()) { - output.push('[' + Folder.displayTitle(item) + ']'); + output.push(`[${Folder.displayTitle(item)}]`); } else if (item.type_ === BaseModel.TYPE_SEARCH) { output.push(_('Search:')); output.push(item.title); @@ -172,7 +172,7 @@ class FolderListWidget extends ListWidget { if (this.notesParentType === 'Folder') return this.selectedFolderId; if (this.notesParentType === 'Tag') return this.selectedTagId; if (this.notesParentType === 'Search') return this.selectedSearchId; - throw new Error('Unknown parent type: ' + this.notesParentType); + throw new Error(`Unknown parent type: ${this.notesParentType}`); } get selectedJoplinItem() { diff --git a/CliClient/app/gui/NoteListWidget.js b/CliClient/app/gui/NoteListWidget.js index 34a3029eb..407c39281 100644 --- a/CliClient/app/gui/NoteListWidget.js +++ b/CliClient/app/gui/NoteListWidget.js @@ -11,7 +11,7 @@ class NoteListWidget extends ListWidget { this.itemRenderer = note => { let label = Note.displayTitle(note); // + ' ' + note.id; if (note.is_todo) { - label = '[' + (note.todo_completed ? 'X' : ' ') + '] ' + label; + label = `[${note.todo_completed ? 'X' : ' '}] ${label}`; } return label; }; diff --git a/CliClient/app/gui/NoteWidget.js b/CliClient/app/gui/NoteWidget.js index fe2b1f3ba..da4232bec 100644 --- a/CliClient/app/gui/NoteWidget.js +++ b/CliClient/app/gui/NoteWidget.js @@ -47,7 +47,7 @@ class NoteWidget extends TextWidget { if (this.note_ && this.note_.encryption_applied) { this.text = _('One or more items are currently encrypted and you may need to supply a master password. To do so please type `e2ee decrypt`. If you have already supplied the password, the encrypted items are being decrypted in the background and will be available soon.'); } else { - this.text = this.note_ ? this.note_.title + '\n\n' + this.note_.body : ''; + this.text = this.note_ ? `${this.note_.title}\n\n${this.note_.body}` : ''; } if (this.lastLoadedNoteId_ !== this.noteId_) this.scrollTop = 0; diff --git a/CliClient/app/help-utils.js b/CliClient/app/help-utils.js index fde9421ce..c9483a97a 100644 --- a/CliClient/app/help-utils.js +++ b/CliClient/app/help-utils.js @@ -60,7 +60,7 @@ function renderCommandHelp(cmd, width = null) { if ('value' in md) { if (md.type === Setting.TYPE_STRING) { - defaultString = md.value ? '"' + md.value + '"' : null; + defaultString = md.value ? `"${md.value}"` : null; } else if (md.type === Setting.TYPE_INT) { defaultString = (md.value ? md.value : 0).toString(); } else if (md.type === Setting.TYPE_BOOL) { diff --git a/CliClient/app/main.js b/CliClient/app/main.js index d0d0b28b5..cc7ab66fe 100644 --- a/CliClient/app/main.js +++ b/CliClient/app/main.js @@ -9,7 +9,7 @@ require('app-module-path').addPath(__dirname); const compareVersion = require('compare-version'); const nodeVersion = process && process.versions && process.versions.node ? process.versions.node : '0.0.0'; if (compareVersion(nodeVersion, '8.0.0') < 0) { - console.error('Joplin requires Node 8+. Detected version ' + nodeVersion); + console.error(`Joplin requires Node 8+. Detected version ${nodeVersion}`); process.exit(1); } diff --git a/CliClient/app/onedrive-api-node-utils.js b/CliClient/app/onedrive-api-node-utils.js index 301381f98..ba5b9c4f5 100644 --- a/CliClient/app/onedrive-api-node-utils.js +++ b/CliClient/app/onedrive-api-node-utils.js @@ -44,7 +44,7 @@ class OneDriveApiNodeUtils { const port = await netUtils.findAvailablePort(this.possibleOAuthDancePorts(), 0); if (!port) throw new Error(_('All potential ports are in use - please report the issue at %s', 'https://github.com/laurent22/joplin')); - let authCodeUrl = this.api().authCodeUrl('http://localhost:' + port); + let authCodeUrl = this.api().authCodeUrl(`http://localhost:${port}`); return new Promise((resolve, reject) => { this.oauthServer_ = http.createServer(); @@ -80,7 +80,7 @@ class OneDriveApiNodeUtils { if (!query.code) return writeResponse(400, '"code" query parameter is missing'); this.api() - .execTokenRequest(query.code, 'http://localhost:' + port.toString()) + .execTokenRequest(query.code, `http://localhost:${port.toString()}`) .then(() => { writeResponse(200, _('The application has been authorised - you may now close this browser tab.')); targetConsole.log(''); @@ -114,7 +114,7 @@ class OneDriveApiNodeUtils { targetConsole.log(_('Please open the following URL in your browser to authenticate the application. The application will create a directory in "Apps/Joplin" and will only read and write files in this directory. It will have no access to any files outside this directory nor to any other personal data. No data will be shared with any third party.')); targetConsole.log(''); - targetConsole.log('http://127.0.0.1:' + port + '/auth'); + targetConsole.log(`http://127.0.0.1:${port}/auth`); }); } } diff --git a/CliClient/tests/EnexToMd.js b/CliClient/tests/EnexToMd.js index b12c84fc2..58fed5e2b 100644 --- a/CliClient/tests/EnexToMd.js +++ b/CliClient/tests/EnexToMd.js @@ -27,22 +27,22 @@ describe('EnexToMd', function() { }); it('should convert from Enex to Markdown', asyncTest(async () => { - const basePath = __dirname + '/enex_to_md'; + const basePath = `${__dirname}/enex_to_md`; const files = await shim.fsDriver().readDirStats(basePath); for (let i = 0; i < files.length; i++) { const htmlFilename = files[i].path; if (htmlFilename.indexOf('.html') < 0) continue; - const htmlPath = basePath + '/' + htmlFilename; - const mdPath = basePath + '/' + filename(htmlFilename) + '.md'; + const htmlPath = `${basePath}/${htmlFilename}`; + const mdPath = `${basePath}/${filename(htmlFilename)}.md`; // if (htmlFilename !== 'multiline_inner_text.html') continue; const html = await shim.fsDriver().readFile(htmlPath); let expectedMd = await shim.fsDriver().readFile(mdPath); - let actualMd = await enexXmlToMd('
' + html + '
', []); + let actualMd = await enexXmlToMd(`
${html}
`, []); if (os.EOL === '\r\n') { expectedMd = expectedMd.replace(/\r\n/g, '\n'); @@ -51,7 +51,7 @@ describe('EnexToMd', function() { if (actualMd !== expectedMd) { console.info(''); - console.info('Error converting file: ' + htmlFilename); + console.info(`Error converting file: ${htmlFilename}`); console.info('--------------------------------- Got:'); console.info(actualMd.split('\n')); console.info('--------------------------------- Expected:'); diff --git a/CliClient/tests/HtmlToMd.js b/CliClient/tests/HtmlToMd.js index 3ed47f075..12da8fe62 100644 --- a/CliClient/tests/HtmlToMd.js +++ b/CliClient/tests/HtmlToMd.js @@ -28,7 +28,7 @@ describe('HtmlToMd', function() { }); it('should convert from Html to Markdown', asyncTest(async () => { - const basePath = __dirname + '/html_to_md'; + const basePath = `${__dirname}/html_to_md`; const files = await shim.fsDriver().readDirStats(basePath); const htmlToMd = new HtmlToMd(); @@ -36,8 +36,8 @@ describe('HtmlToMd', function() { const htmlFilename = files[i].path; if (htmlFilename.indexOf('.html') < 0) continue; - const htmlPath = basePath + '/' + htmlFilename; - const mdPath = basePath + '/' + filename(htmlFilename) + '.md'; + const htmlPath = `${basePath}/${htmlFilename}`; + const mdPath = `${basePath}/${filename(htmlFilename)}.md`; // if (htmlFilename !== 'table_with_pipe.html') continue; @@ -54,7 +54,7 @@ describe('HtmlToMd', function() { const html = await shim.fsDriver().readFile(htmlPath); let expectedMd = await shim.fsDriver().readFile(mdPath); - let actualMd = await htmlToMd.parse('
' + html + '
', htmlToMdOptions); + let actualMd = await htmlToMd.parse(`
${html}
`, htmlToMdOptions); if (os.EOL === '\r\n') { expectedMd = expectedMd.replace(/\r\n/g, '\n'); @@ -63,7 +63,7 @@ describe('HtmlToMd', function() { if (actualMd !== expectedMd) { console.info(''); - console.info('Error converting file: ' + htmlFilename); + console.info(`Error converting file: ${htmlFilename}`); console.info('--------------------------------- Got:'); console.info(actualMd); console.info('--------------------------------- Raw:'); diff --git a/CliClient/tests/StringUtils.js b/CliClient/tests/StringUtils.js index 0e37dbd4d..67e8a0101 100644 --- a/CliClient/tests/StringUtils.js +++ b/CliClient/tests/StringUtils.js @@ -38,7 +38,7 @@ describe('StringUtils', function() { const actual = StringUtils.surroundKeywords(keywords, input, prefix, suffix); - expect(actual).toBe(expected, 'Test case ' + i); + expect(actual).toBe(expected, `Test case ${i}`); } done(); diff --git a/CliClient/tests/encryption.js b/CliClient/tests/encryption.js index e914e6afa..b00005675 100644 --- a/CliClient/tests/encryption.js +++ b/CliClient/tests/encryption.js @@ -165,9 +165,9 @@ describe('Encryption', function() { masterKey = await MasterKey.save(masterKey); await service.loadMasterKey(masterKey, '123456', true); - const sourcePath = __dirname + '/../tests/support/photo.jpg'; - const encryptedPath = __dirname + '/data/photo.crypted'; - const decryptedPath = __dirname + '/data/photo.jpg'; + const sourcePath = `${__dirname}/../tests/support/photo.jpg`; + const encryptedPath = `${__dirname}/data/photo.crypted`; + const decryptedPath = `${__dirname}/data/photo.jpg`; await service.encryptFile(sourcePath, encryptedPath); await service.decryptFile(encryptedPath, decryptedPath); diff --git a/CliClient/tests/models_Note.js b/CliClient/tests/models_Note.js index 247a55d5d..906d9c3f2 100644 --- a/CliClient/tests/models_Note.js +++ b/CliClient/tests/models_Note.js @@ -25,23 +25,23 @@ describe('models_Note', function() { it('should find resource and note IDs', asyncTest(async () => { let folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); - let note2 = await Note.save({ title: 'ma deuxième note', body: 'Lien vers première note : ' + Note.markdownTag(note1), parent_id: folder1.id }); + let note2 = await Note.save({ title: 'ma deuxième note', body: `Lien vers première note : ${Note.markdownTag(note1)}`, parent_id: folder1.id }); let items = await Note.linkedItems(note2.body); expect(items.length).toBe(1); expect(items[0].id).toBe(note1.id); - await shim.attachFileToNote(note2, __dirname + '/../tests/support/photo.jpg'); + await shim.attachFileToNote(note2, `${__dirname}/../tests/support/photo.jpg`); note2 = await Note.load(note2.id); items = await Note.linkedItems(note2.body); expect(items.length).toBe(2); expect(items[0].type_).toBe(BaseModel.TYPE_NOTE); expect(items[1].type_).toBe(BaseModel.TYPE_RESOURCE); - const resource2 = await shim.createResourceFromPath(__dirname + '/../tests/support/photo.jpg'); - const resource3 = await shim.createResourceFromPath(__dirname + '/../tests/support/photo.jpg'); - note2.body += 'bla'; - note2.body += ''; + const resource2 = await shim.createResourceFromPath(`${__dirname}/../tests/support/photo.jpg`); + const resource3 = await shim.createResourceFromPath(`${__dirname}/../tests/support/photo.jpg`); + note2.body += `bla`; + note2.body += ``; items = await Note.linkedItems(note2.body); expect(items.length).toBe(4); })); diff --git a/CliClient/tests/models_Resource.js b/CliClient/tests/models_Resource.js index a344eb130..22ff4d9da 100644 --- a/CliClient/tests/models_Resource.js +++ b/CliClient/tests/models_Resource.js @@ -16,7 +16,7 @@ process.on('unhandledRejection', (reason, p) => { console.log('Unhandled Rejection at: Promise', p, 'reason:', reason); }); -const testImagePath = __dirname + '/../tests/support/photo.jpg'; +const testImagePath = `${__dirname}/../tests/support/photo.jpg`; describe('models_Resource', function() { diff --git a/CliClient/tests/services_InteropService.js b/CliClient/tests/services_InteropService.js index 3a7bd0532..e15d54758 100644 --- a/CliClient/tests/services_InteropService.js +++ b/CliClient/tests/services_InteropService.js @@ -22,13 +22,13 @@ process.on('unhandledRejection', (reason, p) => { }); function exportDir() { - return __dirname + '/export'; + return `${__dirname}/export`; } function fieldsEqual(model1, model2, fieldNames) { for (let i = 0; i < fieldNames.length; i++) { const f = fieldNames[i]; - expect(model1[f]).toBe(model2[f], 'For key ' + f); + expect(model1[f]).toBe(model2[f], `For key ${f}`); } } @@ -48,7 +48,7 @@ describe('services_InteropService', function() { const service = new InteropService(); let folder1 = await Folder.save({ title: 'folder1' }); folder1 = await Folder.load(folder1.id); - const filePath = exportDir() + '/test.jex'; + const filePath = `${exportDir()}/test.jex`; await service.export({ path: filePath }); @@ -84,7 +84,7 @@ describe('services_InteropService', function() { let folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); note1 = await Note.load(note1.id); - const filePath = exportDir() + '/test.jex'; + const filePath = `${exportDir()}/test.jex`; await service.export({ path: filePath }); @@ -123,7 +123,7 @@ describe('services_InteropService', function() { let folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); note1 = await Note.load(note1.id); - const filePath = exportDir() + '/test.jex'; + const filePath = `${exportDir()}/test.jex`; await service.export({ path: filePath }); @@ -139,7 +139,7 @@ describe('services_InteropService', function() { it('should export and import tags', asyncTest(async () => { const service = new InteropService(); - const filePath = exportDir() + '/test.jex'; + const filePath = `${exportDir()}/test.jex`; let folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); let tag1 = await Tag.save({ title: 'mon tag' }); @@ -179,10 +179,10 @@ describe('services_InteropService', function() { it('should export and import resources', asyncTest(async () => { const service = new InteropService(); - const filePath = exportDir() + '/test.jex'; + const filePath = `${exportDir()}/test.jex`; let folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); - await shim.attachFileToNote(note1, __dirname + '/../tests/support/photo.jpg'); + await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); note1 = await Note.load(note1.id); let resourceIds = await Note.linkedResourceIds(note1.body); let resource1 = await Resource.load(resourceIds[0]); @@ -215,7 +215,7 @@ describe('services_InteropService', function() { it('should export and import single notes', asyncTest(async () => { const service = new InteropService(); - const filePath = exportDir() + '/test.jex'; + const filePath = `${exportDir()}/test.jex`; let folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); @@ -235,7 +235,7 @@ describe('services_InteropService', function() { it('should export and import single folders', asyncTest(async () => { const service = new InteropService(); - const filePath = exportDir() + '/test.jex'; + const filePath = `${exportDir()}/test.jex`; let folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); @@ -256,7 +256,7 @@ describe('services_InteropService', function() { it('should export and import folder and its sub-folders', asyncTest(async () => { const service = new InteropService(); - const filePath = exportDir() + '/test.jex'; + const filePath = `${exportDir()}/test.jex`; let folder1 = await Folder.save({ title: 'folder1' }); let folder2 = await Folder.save({ title: 'folder2', parent_id: folder1.id }); let folder3 = await Folder.save({ title: 'folder3', parent_id: folder2.id }); @@ -290,10 +290,10 @@ describe('services_InteropService', function() { it('should export and import links to notes', asyncTest(async () => { const service = new InteropService(); - const filePath = exportDir() + '/test.jex'; + const filePath = `${exportDir()}/test.jex`; let folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); - let note2 = await Note.save({ title: 'ma deuxième note', body: 'Lien vers première note : ' + Note.markdownTag(note1), parent_id: folder1.id }); + let note2 = await Note.save({ title: 'ma deuxième note', body: `Lien vers première note : ${Note.markdownTag(note1)}`, parent_id: folder1.id }); await service.export({ path: filePath, sourceFolderIds: [folder1.id] }); @@ -324,7 +324,7 @@ describe('services_InteropService', function() { // verify that the json files exist and can be parsed const items = [folder1, note1]; for (let i = 0; i < items.length; i++) { - const jsonFile = filePath + '/' + items[i].id + '.json'; + const jsonFile = `${filePath}/${items[i].id}.json`; let json = await fs.readFile(jsonFile, 'utf-8'); let obj = JSON.parse(json); expect(obj.id).toBe(items[i].id); @@ -350,13 +350,13 @@ describe('services_InteropService', function() { await service.export({ path: outDir, format: 'md' }); - expect(await shim.fsDriver().exists(outDir + '/folder1/生活.md')).toBe(true); - expect(await shim.fsDriver().exists(outDir + '/folder1/生活 (1).md')).toBe(true); - expect(await shim.fsDriver().exists(outDir + '/folder1/生活 (2).md')).toBe(true); - expect(await shim.fsDriver().exists(outDir + '/folder1/Untitled.md')).toBe(true); - expect(await shim.fsDriver().exists(outDir + '/folder1/Untitled (1).md')).toBe(true); - expect(await shim.fsDriver().exists(outDir + '/folder1/salut, ça roule _.md')).toBe(true); - expect(await shim.fsDriver().exists(outDir + '/ジョプリン/ジョプリン.md')).toBe(true); + expect(await shim.fsDriver().exists(`${outDir}/folder1/生活.md`)).toBe(true); + expect(await shim.fsDriver().exists(`${outDir}/folder1/生活 (1).md`)).toBe(true); + expect(await shim.fsDriver().exists(`${outDir}/folder1/生活 (2).md`)).toBe(true); + expect(await shim.fsDriver().exists(`${outDir}/folder1/Untitled.md`)).toBe(true); + expect(await shim.fsDriver().exists(`${outDir}/folder1/Untitled (1).md`)).toBe(true); + expect(await shim.fsDriver().exists(`${outDir}/folder1/salut, ça roule _.md`)).toBe(true); + expect(await shim.fsDriver().exists(`${outDir}/ジョプリン/ジョプリン.md`)).toBe(true); })); }); diff --git a/CliClient/tests/services_ResourceService.js b/CliClient/tests/services_ResourceService.js index 688f17e76..94b5d5e6e 100644 --- a/CliClient/tests/services_ResourceService.js +++ b/CliClient/tests/services_ResourceService.js @@ -26,13 +26,13 @@ process.on('unhandledRejection', (reason, p) => { jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; function exportDir() { - return __dirname + '/export'; + return `${__dirname}/export`; } function fieldsEqual(model1, model2, fieldNames) { for (let i = 0; i < fieldNames.length; i++) { const f = fieldNames[i]; - expect(model1[f]).toBe(model2[f], 'For key ' + f); + expect(model1[f]).toBe(model2[f], `For key ${f}`); } } @@ -50,7 +50,7 @@ describe('services_ResourceService', function() { let folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); - note1 = await shim.attachFileToNote(note1, __dirname + '/../tests/support/photo.jpg'); + note1 = await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); let resource1 = (await Resource.all())[0]; const resourcePath = Resource.fullPath(resource1); @@ -82,7 +82,7 @@ describe('services_ResourceService', function() { let folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); let note2 = await Note.save({ title: 'ma deuxième note', parent_id: folder1.id }); - note1 = await shim.attachFileToNote(note1, __dirname + '/../tests/support/photo.jpg'); + note1 = await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); let resource1 = (await Resource.all())[0]; await service.indexNoteResources(); @@ -102,7 +102,7 @@ describe('services_ResourceService', function() { it('should not delete a resource that has never been associated with any note, because it probably means the resource came via sync, and associated note has not arrived yet', asyncTest(async () => { const service = new ResourceService(); - const resource = await shim.createResourceFromPath(__dirname + '/../tests/support/photo.jpg'); + const resource = await shim.createResourceFromPath(`${__dirname}/../tests/support/photo.jpg`); await service.indexNoteResources(); await service.deleteOrphanResources(0); @@ -115,12 +115,12 @@ describe('services_ResourceService', function() { let folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); - note1 = await shim.attachFileToNote(note1, __dirname + '/../tests/support/photo.jpg'); + note1 = await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); let resource1 = (await Resource.all())[0]; await service.indexNoteResources(); - await Note.save({ id: note1.id, body: 'This is HTML: ' }); + await Note.save({ id: note1.id, body: `This is HTML: ` }); await service.indexNoteResources(); @@ -134,7 +134,7 @@ describe('services_ResourceService', function() { let folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); - note1 = await shim.attachFileToNote(note1, __dirname + '/../tests/support/photo.jpg'); + note1 = await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); let resource1 = (await Resource.all())[0]; await service.indexNoteResources(); @@ -171,7 +171,7 @@ describe('services_ResourceService', function() { await encryptionService().loadMasterKeysFromSettings(); let folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); - await shim.attachFileToNote(note1, __dirname + '/../tests/support/photo.jpg'); // R1 + await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); // R1 await resourceService().indexNoteResources(); await synchronizer().start(); expect(await allSyncTargetItemsEncrypted()).toBe(true); @@ -184,7 +184,7 @@ describe('services_ResourceService', function() { await decryptionWorker().start(); { const n1 = await Note.load(note1.id); - await shim.attachFileToNote(n1, __dirname + '/../tests/support/photo.jpg'); // R2 + await shim.attachFileToNote(n1, `${__dirname}/../tests/support/photo.jpg`); // R2 } await synchronizer().start(); @@ -201,7 +201,7 @@ describe('services_ResourceService', function() { let folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); - note1 = await shim.attachFileToNote(note1, __dirname + '/../tests/support/photo.jpg'); + note1 = await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); await resourceService().indexNoteResources(); const bodyWithResource = note1.body; await Note.save({ id: note1.id, body: '' }); diff --git a/CliClient/tests/services_SearchEngine.js b/CliClient/tests/services_SearchEngine.js index 7828f5bd8..a798d6582 100644 --- a/CliClient/tests/services_SearchEngine.js +++ b/CliClient/tests/services_SearchEngine.js @@ -297,9 +297,9 @@ describe('services_SearchEngine', function() { const titleValues = actual.terms.title ? actual.terms.title.map(v => v.value) : undefined; const bodyValues = actual.terms.body ? actual.terms.body.map(v => v.value) : undefined; - expect(JSON.stringify(_Values)).toBe(JSON.stringify(expected._), 'Test case (_) ' + i); - expect(JSON.stringify(titleValues)).toBe(JSON.stringify(expected.title), 'Test case (title) ' + i); - expect(JSON.stringify(bodyValues)).toBe(JSON.stringify(expected.body), 'Test case (body) ' + i); + expect(JSON.stringify(_Values)).toBe(JSON.stringify(expected._), `Test case (_) ${i}`); + expect(JSON.stringify(titleValues)).toBe(JSON.stringify(expected.title), `Test case (title) ${i}`); + expect(JSON.stringify(bodyValues)).toBe(JSON.stringify(expected.body), `Test case (body) ${i}`); } })); diff --git a/CliClient/tests/services_rest_Api.js b/CliClient/tests/services_rest_Api.js index 12e80f400..03d65badb 100644 --- a/CliClient/tests/services_rest_Api.js +++ b/CliClient/tests/services_rest_Api.js @@ -51,7 +51,7 @@ describe('services_rest_Api', function() { it('should update folders', async (done) => { let f1 = await Folder.save({ title: 'mon carnet' }); - const response = await api.route('PUT', 'folders/' + f1.id, null, JSON.stringify({ + const response = await api.route('PUT', `folders/${f1.id}`, null, JSON.stringify({ title: 'modifié', })); @@ -63,7 +63,7 @@ describe('services_rest_Api', function() { it('should delete folders', async (done) => { let f1 = await Folder.save({ title: 'mon carnet' }); - await api.route('DELETE', 'folders/' + f1.id); + await api.route('DELETE', `folders/${f1.id}`); let f1b = await Folder.load(f1.id); expect(!f1b).toBe(true); @@ -87,7 +87,7 @@ describe('services_rest_Api', function() { it('should get one folder', async (done) => { let f1 = await Folder.save({ title: 'mon carnet' }); - const response = await api.route('GET', 'folders/' + f1.id); + const response = await api.route('GET', `folders/${f1.id}`); expect(response.id).toBe(f1.id); const hasThrown = await checkThrowAsync(async () => await api.route('GET', 'folders/doesntexist')); @@ -98,12 +98,12 @@ describe('services_rest_Api', function() { it('should get the folder notes', async (done) => { let f1 = await Folder.save({ title: 'mon carnet' }); - const response2 = await api.route('GET', 'folders/' + f1.id + '/notes'); + const response2 = await api.route('GET', `folders/${f1.id}/notes`); expect(response2.length).toBe(0); const n1 = await Note.save({ title: 'un', parent_id: f1.id }); const n2 = await Note.save({ title: 'deux', parent_id: f1.id }); - const response = await api.route('GET', 'folders/' + f1.id + '/notes'); + const response = await api.route('GET', `folders/${f1.id}/notes`); expect(response.length).toBe(2); done(); @@ -127,10 +127,10 @@ describe('services_rest_Api', function() { response = await api.route('GET', 'notes'); expect(response.length).toBe(3); - response = await api.route('GET', 'notes/' + n1.id); + response = await api.route('GET', `notes/${n1.id}`); expect(response.id).toBe(n1.id); - response = await api.route('GET', 'notes/' + n3.id, { fields: 'id,title' }); + response = await api.route('GET', `notes/${n3.id}`, { fields: 'id,title' }); expect(Object.getOwnPropertyNames(response).length).toBe(3); expect(response.id).toBe(n3.id); expect(response.title).toBe('trois'); @@ -270,7 +270,7 @@ describe('services_rest_Api', function() { const filePath = Resource.fullPath(resource); expect(await shim.fsDriver().exists(filePath)).toBe(true); - await api.route('DELETE', 'resources/' + resource.id); + await api.route('DELETE', `resources/${resource.id}`); expect(await shim.fsDriver().exists(filePath)).toBe(false); expect(!(await Resource.load(resource.id))).toBe(true); @@ -329,7 +329,7 @@ describe('services_rest_Api', function() { const tag = await Tag.save({ title: 'mon étiquette' }); const note = await Note.save({ title: 'ma note' }); - const response = await api.route('POST', 'tags/' + tag.id + '/notes', null, JSON.stringify({ + const response = await api.route('POST', `tags/${tag.id}/notes`, null, JSON.stringify({ id: note.id, })); @@ -344,7 +344,7 @@ describe('services_rest_Api', function() { const note = await Note.save({ title: 'ma note' }); await Tag.addNote(tag.id, note.id); - const response = await api.route('DELETE', 'tags/' + tag.id + '/notes/' + note.id); + const response = await api.route('DELETE', `tags/${tag.id}/notes/${note.id}`); const noteIds = await Tag.noteIds(tag.id); expect(noteIds.length).toBe(0); @@ -360,15 +360,15 @@ describe('services_rest_Api', function() { await Tag.addNote(tag.id, note1.id); await Tag.addNote(tag.id, note2.id); - const response = await api.route('GET', 'tags/' + tag.id + '/notes'); + const response = await api.route('GET', `tags/${tag.id}/notes`); expect(response.length).toBe(2); expect('id' in response[0]).toBe(true); expect('title' in response[0]).toBe(true); - const response2 = await api.route('GET', 'notes/' + note1.id + '/tags'); + const response2 = await api.route('GET', `notes/${note1.id}/tags`); expect(response2.length).toBe(1); await Tag.addNote(tag2.id, note1.id); - const response3 = await api.route('GET', 'notes/' + note1.id + '/tags'); + const response3 = await api.route('GET', `notes/${note1.id}/tags`); expect(response3.length).toBe(2); done(); diff --git a/CliClient/tests/synchronizer.js b/CliClient/tests/synchronizer.js index 3b9d64f59..88522fd3d 100644 --- a/CliClient/tests/synchronizer.js +++ b/CliClient/tests/synchronizer.js @@ -196,13 +196,13 @@ describe('Synchronizer', function() { for (let n in conflictedNote) { if (!conflictedNote.hasOwnProperty(n)) continue; if (n == 'id' || n == 'is_conflict') continue; - expect(conflictedNote[n]).toBe(note2conf[n], 'Property: ' + n); + expect(conflictedNote[n]).toBe(note2conf[n], `Property: ${n}`); } let noteUpdatedFromRemote = await Note.load(note1.id); for (let n in noteUpdatedFromRemote) { if (!noteUpdatedFromRemote.hasOwnProperty(n)) continue; - expect(noteUpdatedFromRemote[n]).toBe(note2[n], 'Property: ' + n); + expect(noteUpdatedFromRemote[n]).toBe(note2[n], `Property: ${n}`); } })); @@ -850,7 +850,7 @@ describe('Synchronizer', function() { let folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); - await shim.attachFileToNote(note1, __dirname + '/../tests/support/photo.jpg'); + await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); let resource1 = (await Resource.all())[0]; let resourcePath1 = Resource.fullPath(resource1); await synchronizer().start(); @@ -883,7 +883,7 @@ describe('Synchronizer', function() { let folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); - await shim.attachFileToNote(note1, __dirname + '/../tests/support/photo.jpg'); + await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); let resource1 = (await Resource.all())[0]; let resourcePath1 = Resource.fullPath(resource1); await synchronizer().start(); @@ -910,7 +910,7 @@ describe('Synchronizer', function() { let folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); - await shim.attachFileToNote(note1, __dirname + '/../tests/support/photo.jpg'); + await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); await synchronizer().start(); await switchClient(2); @@ -933,7 +933,7 @@ describe('Synchronizer', function() { let folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); - await shim.attachFileToNote(note1, __dirname + '/../tests/support/photo.jpg'); + await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); let resource1 = (await Resource.all())[0]; let resourcePath1 = Resource.fullPath(resource1); await synchronizer().start(); @@ -949,7 +949,7 @@ describe('Synchronizer', function() { await synchronizer().start(); expect((await remoteNotesFoldersResources()).length).toBe(2); - const remoteBlob = await fileApi().stat('.resource/' + resource1.id); + const remoteBlob = await fileApi().stat(`.resource/${resource1.id}`); expect(!remoteBlob).toBe(true); await switchClient(1); @@ -967,7 +967,7 @@ describe('Synchronizer', function() { let folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); - await shim.attachFileToNote(note1, __dirname + '/../tests/support/photo.jpg'); + await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); let resource1 = (await Resource.all())[0]; let resourcePath1 = Resource.fullPath(resource1); await synchronizer().start(); @@ -1049,7 +1049,7 @@ describe('Synchronizer', function() { let folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); - await shim.attachFileToNote(note1, __dirname + '/../tests/support/photo.jpg'); + await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); let resource1 = (await Resource.all())[0]; await Resource.setFileSizeOnly(resource1.id, -1); let resourcePath1 = Resource.fullPath(resource1); @@ -1075,7 +1075,7 @@ describe('Synchronizer', function() { let folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); - await shim.attachFileToNote(note1, __dirname + '/../tests/support/photo.jpg'); + await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); await synchronizer().start(); expect(await allSyncTargetItemsEncrypted()).toBe(false); @@ -1094,7 +1094,7 @@ describe('Synchronizer', function() { let folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); - await shim.attachFileToNote(note1, __dirname + '/../tests/support/photo.jpg'); + await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); const masterKey = await loadEncryptionMasterKey(); await encryptionService().enableEncryption(masterKey, '123456'); await encryptionService().loadMasterKeysFromSettings(); @@ -1307,7 +1307,7 @@ describe('Synchronizer', function() { it('should not download resources over the limit', asyncTest(async () => { const note1 = await Note.save({ title: 'note' }); - await shim.attachFileToNote(note1, __dirname + '/../tests/support/photo.jpg'); + await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); await synchronizer().start(); await switchClient(2); @@ -1337,7 +1337,7 @@ describe('Synchronizer', function() { // does get uploaded. const note1 = await Note.save({ title: 'note' }); - await shim.attachFileToNote(note1, __dirname + '/../tests/support/photo.jpg'); + await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); const resource = (await Resource.all())[0]; await Resource.setLocalState(resource.id, { fetch_status: Resource.FETCH_STATUS_IDLE }); await synchronizer().start(); @@ -1352,7 +1352,7 @@ describe('Synchronizer', function() { it('should decrypt the resource metadata, but not try to decrypt the file, if it is not present', asyncTest(async () => { const note1 = await Note.save({ title: 'note' }); - await shim.attachFileToNote(note1, __dirname + '/../tests/support/photo.jpg'); + await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); const masterKey = await loadEncryptionMasterKey(); await encryptionService().enableEncryption(masterKey, '123456'); await encryptionService().loadMasterKeysFromSettings(); diff --git a/CliClient/tests/test-utils.js b/CliClient/tests/test-utils.js index 98d3649e2..8ea36a6d5 100644 --- a/CliClient/tests/test-utils.js +++ b/CliClient/tests/test-utils.js @@ -56,8 +56,8 @@ Resource.fsDriver_ = fsDriver; EncryptionService.fsDriver_ = fsDriver; FileApiDriverLocal.fsDriver_ = fsDriver; -const logDir = __dirname + '/../tests/logs'; -const tempDir = __dirname + '/../tests/tmp'; +const logDir = `${__dirname}/../tests/logs`; +const tempDir = `${__dirname}/../tests/tmp`; fs.mkdirpSync(logDir, 0o755); fs.mkdirpSync(tempDir, 0o755); @@ -71,20 +71,20 @@ SyncTargetRegistry.addClass(SyncTargetDropbox); const syncTargetId_ = SyncTargetRegistry.nameToId('memory'); //const syncTargetId_ = SyncTargetRegistry.nameToId('filesystem'); // const syncTargetId_ = SyncTargetRegistry.nameToId('dropbox'); -const syncDir = __dirname + '/../tests/sync'; +const syncDir = `${__dirname}/../tests/sync`; const sleepTime = syncTargetId_ == SyncTargetRegistry.nameToId('filesystem') ? 1001 : 100;//400; -console.info('Testing with sync target: ' + SyncTargetRegistry.idToName(syncTargetId_)); +console.info(`Testing with sync target: ${SyncTargetRegistry.idToName(syncTargetId_)}`); const dbLogger = new Logger(); dbLogger.addTarget('console'); -dbLogger.addTarget('file', { path: logDir + '/log.txt' }); +dbLogger.addTarget('file', { path: `${logDir}/log.txt` }); dbLogger.setLevel(Logger.LEVEL_WARN); const logger = new Logger(); logger.addTarget('console'); -logger.addTarget('file', { path: logDir + '/log.txt' }); +logger.addTarget('file', { path: `${logDir}/log.txt` }); logger.setLevel(Logger.LEVEL_WARN); // Set to DEBUG to display sync process in console BaseItem.loadClass('Note', Note); @@ -116,7 +116,7 @@ function sleep(n) { } async function switchClient(id) { - if (!databases_[id]) throw new Error('Call setupDatabaseAndSynchronizer(' + id + ') first!!'); + if (!databases_[id]) throw new Error(`Call setupDatabaseAndSynchronizer(${id}) first!!`); await time.msleep(sleepTime); // Always leave a little time so that updated_time properties don't overlap await Setting.saveAll(); @@ -162,8 +162,8 @@ async function clearDatabase(id = null) { const queries = []; for (const n of tableNames) { - queries.push('DELETE FROM ' + n); - queries.push('DELETE FROM sqlite_sequence WHERE name="' + n + '"'); // Reset autoincremented IDs + queries.push(`DELETE FROM ${n}`); + queries.push(`DELETE FROM sqlite_sequence WHERE name="${n}"`); // Reset autoincremented IDs } await databases_[id].transactionExecBatch(queries); @@ -181,7 +181,7 @@ async function setupDatabase(id = null) { return; } - const filePath = __dirname + '/data/test-' + id + '.sqlite'; + const filePath = `${__dirname}/data/test-${id}.sqlite`; try { await fs.unlink(filePath); @@ -199,7 +199,7 @@ async function setupDatabase(id = null) { function resourceDir(id = null) { if (id === null) id = currentClient_; - return __dirname + '/data/resources-' + id; + return `${__dirname}/data/resources-${id}`; } async function setupDatabaseAndSynchronizer(id = null) { @@ -310,9 +310,9 @@ function fileApi() { fileApi_ = new FileApi('', new FileApiDriverWebDav(api)); } else if (syncTargetId_ == SyncTargetRegistry.nameToId('dropbox')) { const api = new DropboxApi(); - const authTokenPath = __dirname + '/support/dropbox-auth.txt'; + const authTokenPath = `${__dirname}/support/dropbox-auth.txt`; const authToken = fs.readFileSync(authTokenPath, 'utf8'); - if (!authToken) throw new Error('Dropbox auth token missing in ' + authTokenPath); + if (!authToken) throw new Error(`Dropbox auth token missing in ${authTokenPath}`); api.setAuthToken(authToken); fileApi_ = new FileApi('', new FileApiDriverDropbox(api)); } @@ -380,7 +380,7 @@ async function allSyncTargetItemsEncrypted() { totalCount++; if (remoteContent.type_ === BaseModel.TYPE_RESOURCE) { - const content = await fileApi().get('.resource/' + remoteContent.id); + const content = await fileApi().get(`.resource/${remoteContent.id}`); totalCount++; if (content.substr(0, 5) === 'JED01') encryptedCount++; } diff --git a/Clipper/joplin-webclipper/background.js b/Clipper/joplin-webclipper/background.js index c9018d81f..2d2faabd8 100644 --- a/Clipper/joplin-webclipper/background.js +++ b/Clipper/joplin-webclipper/background.js @@ -65,7 +65,7 @@ browser_.runtime.onMessage.addListener(async (command) => { newArea.height *= zoom; content.crop_rect = newArea; - fetch(command.api_base_url + '/notes', { + fetch(`${command.api_base_url}/notes`, { method: 'POST', headers: { 'Accept': 'application/json', diff --git a/Clipper/joplin-webclipper/content_scripts/index.js b/Clipper/joplin-webclipper/content_scripts/index.js index f2970fb92..2e2dd8f4f 100644 --- a/Clipper/joplin-webclipper/content_scripts/index.js +++ b/Clipper/joplin-webclipper/content_scripts/index.js @@ -26,9 +26,9 @@ if (url.indexOf('//') === 0) { return location.protocol + url; } else if (url[0] === '/') { - return location.protocol + '//' + location.host + url; + return `${location.protocol}//${location.host}${url}`; } else { - return baseUrl() + '/' + url; + return `${baseUrl()}/${url}`; } } @@ -255,7 +255,7 @@ } async function prepareCommandResponse(command) { - console.info('Got command: ' + command.name); + console.info(`Got command: ${command.name}`); const convertToMarkup = command.preProcessFor ? command.preProcessFor : 'markdown'; @@ -343,15 +343,15 @@ messageComp.style.position = 'fixed'; messageComp.style.opacity = '0.95'; messageComp.style.fontSize = '14px'; - messageComp.style.width = messageCompWidth + 'px'; - messageComp.style.maxWidth = messageCompWidth + 'px'; + messageComp.style.width = `${messageCompWidth}px`; + messageComp.style.maxWidth = `${messageCompWidth}px`; messageComp.style.border = '1px solid black'; messageComp.style.background = 'white'; messageComp.style.color = 'black'; messageComp.style.top = '10px'; messageComp.style.textAlign = 'center'; messageComp.style.padding = '10px'; - messageComp.style.left = Math.round(document.body.clientWidth / 2 - messageCompWidth / 2) + 'px'; + messageComp.style.left = `${Math.round(document.body.clientWidth / 2 - messageCompWidth / 2)}px`; messageComp.style.zIndex = overlay.style.zIndex + 1; messageComp.textContent = 'Drag and release to capture a screenshot'; @@ -375,10 +375,10 @@ let selectionArea = {}; const updateSelection = function() { - selection.style.left = selectionArea.x + 'px'; - selection.style.top = selectionArea.y + 'px'; - selection.style.width = selectionArea.width + 'px'; - selection.style.height = selectionArea.height + 'px'; + selection.style.left = `${selectionArea.x}px`; + selection.style.top = `${selectionArea.y}px`; + selection.style.width = `${selectionArea.width}px`; + selection.style.height = `${selectionArea.height}px`; }; const setSelectionSizeFromMouse = function(event) { @@ -448,7 +448,7 @@ return clippedContentResponse(pageTitle(), url, getImageSizes(document), getAnchorNames(document)); } else { - throw new Error('Unknown command: ' + JSON.stringify(command)); + throw new Error(`Unknown command: ${JSON.stringify(command)}`); } } diff --git a/Clipper/joplin-webclipper/popup/scripts/postinstall.js b/Clipper/joplin-webclipper/popup/scripts/postinstall.js index 39366e551..8dd194cc7 100644 --- a/Clipper/joplin-webclipper/popup/scripts/postinstall.js +++ b/Clipper/joplin-webclipper/popup/scripts/postinstall.js @@ -1,3 +1,3 @@ const fs = require('fs-extra'); -fs.copySync(__dirname + '/../../../../ReactNativeClient/lib/randomClipperPort.js', __dirname + '/../src/randomClipperPort.js'); +fs.copySync(`${__dirname}/../../../../ReactNativeClient/lib/randomClipperPort.js`, `${__dirname}/../src/randomClipperPort.js`); diff --git a/Clipper/joplin-webclipper/popup/src/App.js b/Clipper/joplin-webclipper/popup/src/App.js index c2351c02f..0f59594cb 100644 --- a/Clipper/joplin-webclipper/popup/src/App.js +++ b/Clipper/joplin-webclipper/popup/src/App.js @@ -16,7 +16,7 @@ function commandUserString(command) { if (command.name === 'pageUrl') s.push('URL only'); const p = command.preProcessFor ? command.preProcessFor : 'markdown'; - s.push('(' + p + ')'); + s.push(`(${p})`); return s.join(' '); } @@ -234,7 +234,7 @@ class AppComponent extends Component { this.focusNewTagInput_ = false; let lastRef = null; for (let i = 0; i < 100; i++) { - const ref = this.refs['tagSelector' + i]; + const ref = this.refs[`tagSelector${i}`]; if (!ref) break; lastRef = ref; } @@ -245,7 +245,7 @@ class AppComponent extends Component { render() { if (!this.state.contentScriptLoaded) { let msg = 'Loading...'; - if (this.state.contentScriptError) msg = 'The Joplin extension is not available on this tab due to: ' + this.state.contentScriptError; + if (this.state.contentScriptError) msg = `The Joplin extension is not available on this tab due to: ${this.state.contentScriptError}`; return
{msg}
; } @@ -268,7 +268,7 @@ class AppComponent extends Component { } else if (operation.success) { msg = 'Note was successfully created!'; } else { - msg = 'There was some error creating the note: ' + operation.errorMessage; + msg = `There was some error creating the note: ${operation.errorMessage}`; } previewComponent = ( @@ -300,7 +300,7 @@ class AppComponent extends Component { const foundState = this.props.clipperServer.foundState; if (foundState === 'found') { - msg = 'Ready on port ' + this.props.clipperServer.port; + msg = `Ready on port ${this.props.clipperServer.port}`; led = led_green; } else { msg = stateToString(foundState); @@ -308,7 +308,7 @@ class AppComponent extends Component { if (foundState === 'not_found') helpLink = [Help]; } - msg = 'Service status: ' + msg; + msg = `Service status: ${msg}`; return
{foundState}{ msg }{ helpLink }
; }; @@ -346,7 +346,7 @@ class AppComponent extends Component { for (let i = 0; i < this.state.selectedTags.length; i++) { comps.push(
{ const e = this.browser().runtime.lastError; if (e) { - const msg = ['tabsExecuteScript: Cannot load ' + JSON.stringify(options)]; + const msg = [`tabsExecuteScript: Cannot load ${JSON.stringify(options)}`]; if (e.message) msg.push(e.message); reject(new Error(msg.join(': '))); } @@ -277,7 +277,7 @@ class Bridge { } async clipperApiExec(method, path, query, body) { - console.info('Popup: ' + method + ' ' + path); + console.info(`Popup: ${method} ${path}`); const baseUrl = await this.clipperServerBaseUrl(); @@ -295,13 +295,13 @@ class Bridge { const s = []; for (const k in query) { if (!query.hasOwnProperty(k)) continue; - s.push(encodeURIComponent(k) + '=' + encodeURIComponent(query[k])); + s.push(`${encodeURIComponent(k)}=${encodeURIComponent(query[k])}`); } queryString = s.join('&'); - if (queryString) queryString = '?' + queryString; + if (queryString) queryString = `?${queryString}`; } - const response = await fetch(baseUrl + '/' + path + queryString, fetchOptions); + const response = await fetch(`${baseUrl}/${path}${queryString}`, fetchOptions); if (!response.ok) { const msg = await response.text(); throw new Error(msg); diff --git a/ElectronClient/app/ElectronAppWrapper.js b/ElectronClient/app/ElectronAppWrapper.js index fddfb3b50..43c5504de 100644 --- a/ElectronClient/app/ElectronAppWrapper.js +++ b/ElectronClient/app/ElectronAppWrapper.js @@ -39,7 +39,7 @@ class ElectronAppWrapper { const stateOptions = { defaultWidth: 800, defaultHeight: 600, - file: 'window-state-' + this.env_ + '.json', + file: `window-state-${this.env_}.json`, }; if (this.profilePath_) stateOptions.path = this.profilePath_; @@ -145,9 +145,9 @@ class ElectronAppWrapper { buildDir() { if (this.buildDir_) return this.buildDir_; - let dir = __dirname + '/build'; + let dir = `${__dirname}/build`; if (!fs.pathExistsSync(dir)) { - dir = dirname(__dirname) + '/build'; + dir = `${dirname(__dirname)}/build`; if (!fs.pathExistsSync(dir)) throw new Error('Cannot find build dir'); } @@ -172,7 +172,7 @@ class ElectronAppWrapper { // Note: this must be called only after the "ready" event of the app has been dispatched createTray(contextMenu) { try { - this.tray_ = new Tray(this.buildDir() + '/icons/' + this.trayIconFilename_()); + this.tray_ = new Tray(`${this.buildDir()}/icons/${this.trayIconFilename_()}`); this.tray_.setToolTip(this.electronApp_.getName()); this.tray_.setContextMenu(contextMenu); diff --git a/ElectronClient/app/app.js b/ElectronClient/app/app.js index 88fb9796d..87a5e0544 100644 --- a/ElectronClient/app/app.js +++ b/ElectronClient/app/app.js @@ -62,7 +62,7 @@ class Application extends BaseApplication { } checkForUpdateLoggerPath() { - return Setting.value('profileDir') + '/log-autoupdater.txt'; + return `${Setting.value('profileDir')}/log-autoupdater.txt`; } reducer(state = appDefaultState, action) { @@ -203,7 +203,7 @@ class Application extends BaseApplication { } } catch (error) { - error.message = 'In reducer: ' + error.message + ' Action: ' + JSON.stringify(action); + error.message = `In reducer: ${error.message} Action: ${JSON.stringify(action)}`; throw error; } @@ -272,16 +272,16 @@ class Application extends BaseApplication { const sortNoteFolderItems = (type) => { const sortItems = []; - const sortOptions = Setting.enumOptions(type + '.sortOrder.field'); + const sortOptions = Setting.enumOptions(`${type}.sortOrder.field`); for (let field in sortOptions) { if (!sortOptions.hasOwnProperty(field)) continue; sortItems.push({ label: sortOptions[field], screens: ['Main'], type: 'checkbox', - checked: Setting.value(type + '.sortOrder.field') === field, + checked: Setting.value(`${type}.sortOrder.field`) === field, click: () => { - Setting.setValue(type + '.sortOrder.field', field); + Setting.setValue(`${type}.sortOrder.field`, field); this.refreshMenu(); }, }); @@ -290,12 +290,12 @@ class Application extends BaseApplication { sortItems.push({ type: 'separator' }); sortItems.push({ - label: Setting.settingMetadata(type + '.sortOrder.reverse').label(), + label: Setting.settingMetadata(`${type}.sortOrder.reverse`).label(), type: 'checkbox', - checked: Setting.value(type + '.sortOrder.reverse'), + checked: Setting.value(`${type}.sortOrder.reverse`), screens: ['Main'], click: () => { - Setting.setValue(type + '.sortOrder.reverse', !Setting.value(type + '.sortOrder.reverse')); + Setting.setValue(`${type}.sortOrder.reverse`, !Setting.value(`${type}.sortOrder.reverse`)); }, }); @@ -408,7 +408,7 @@ class Application extends BaseApplication { } exportItems.push({ - label: 'PDF - ' + _('PDF File'), + label: `PDF - ${_('PDF File')}`, screens: ['Main'], click: async () => { this.dispatch({ @@ -567,11 +567,11 @@ class Application extends BaseApplication { _('%s %s (%s, %s)', p.name, p.version, Setting.value('env'), process.platform), ]; if (gitInfo) { - message.push('\n' + gitInfo); + message.push(`\n${gitInfo}`); console.info(gitInfo); } bridge().showInfoMessageBox(message.join('\n'), { - icon: bridge().electronApp().buildDir() + '/icons/32x32.png', + icon: `${bridge().electronApp().buildDir()}/icons/32x32.png`, }); } @@ -1027,7 +1027,7 @@ class Application extends BaseApplication { const note = selectedNoteIds.length === 1 ? await Note.load(selectedNoteIds[0]) : null; for (const itemId of ['copy', 'paste', 'cut', 'selectAll', 'bold', 'italic', 'link', 'code', 'insertDateTime', 'commandStartExternalEditing', 'setTags', 'showLocalSearch']) { - const menuItem = Menu.getApplicationMenu().getMenuItemById('edit:' + itemId); + const menuItem = Menu.getApplicationMenu().getMenuItemById(`edit:${itemId}`); if (!menuItem) continue; menuItem.enabled = !!note && note.markup_language === Note.MARKUP_LANGUAGE_MARKDOWN; } @@ -1052,13 +1052,13 @@ class Application extends BaseApplication { updateEditorFont() { const fontFamilies = []; - if (Setting.value('style.editor.fontFamily')) fontFamilies.push('"' + Setting.value('style.editor.fontFamily') + '"'); + if (Setting.value('style.editor.fontFamily')) fontFamilies.push(`"${Setting.value('style.editor.fontFamily')}"`); fontFamilies.push('monospace'); // The '*' and '!important' parts are necessary to make sure Russian text is displayed properly // https://github.com/laurent22/joplin/issues/155 - const css = '.ace_editor * { font-family: ' + fontFamilies.join(', ') + ' !important; }'; + const css = `.ace_editor * { font-family: ${fontFamilies.join(', ')} !important; }`; const styleTag = document.createElement('style'); styleTag.type = 'text/css'; styleTag.appendChild(document.createTextNode(css)); @@ -1073,7 +1073,7 @@ class Application extends BaseApplication { } catch (error) { let msg = error.message ? error.message : ''; - msg = 'Could not load custom css from ' + filePath + '\n' + msg; + msg = `Could not load custom css from ${filePath}\n${msg}`; error.message = msg; throw error; } @@ -1139,7 +1139,7 @@ class Application extends BaseApplication { ids: Setting.value('collapsedFolderIds'), }); - const cssString = await this.loadCustomCss(Setting.value('profileDir') + '/userstyle.css'); + const cssString = await this.loadCustomCss(`${Setting.value('profileDir')}/userstyle.css`); this.store().dispatch({ type: 'LOAD_CUSTOM_CSS', @@ -1193,7 +1193,7 @@ class Application extends BaseApplication { } const clipperLogger = new Logger(); - clipperLogger.addTarget('file', { path: Setting.value('profileDir') + '/log-clipper.txt' }); + clipperLogger.addTarget('file', { path: `${Setting.value('profileDir')}/log-clipper.txt` }); clipperLogger.addTarget('console'); ClipperServer.instance().setLogger(clipperLogger); diff --git a/ElectronClient/app/checkForUpdates.js b/ElectronClient/app/checkForUpdates.js index 2372cfd20..7362f29be 100644 --- a/ElectronClient/app/checkForUpdates.js +++ b/ElectronClient/app/checkForUpdates.js @@ -42,7 +42,7 @@ async function fetchLatestRelease(options) { if (!response.ok) { const responseText = await response.text(); - throw new Error('Cannot get latest release info: ' + responseText.substr(0,500)); + throw new Error(`Cannot get latest release info: ${responseText.substr(0,500)}`); } json = await response.json(); @@ -53,7 +53,7 @@ async function fetchLatestRelease(options) { if (!response.ok) { const responseText = await response.text(); - throw new Error('Cannot get latest release info: ' + responseText.substr(0,500)); + throw new Error(`Cannot get latest release info: ${responseText.substr(0,500)}`); } json = await response.json(); @@ -112,11 +112,11 @@ function checkForUpdates(inBackground, window, logFilePath, options) { checkInBackground_ = inBackground; - autoUpdateLogger_.info('checkForUpdates: Checking with options ' + JSON.stringify(options)); + autoUpdateLogger_.info(`checkForUpdates: Checking with options ${JSON.stringify(options)}`); fetchLatestRelease(options).then(release => { - autoUpdateLogger_.info('Current version: ' + packageInfo.version); - autoUpdateLogger_.info('Latest version: ' + release.version); + autoUpdateLogger_.info(`Current version: ${packageInfo.version}`); + autoUpdateLogger_.info(`Latest version: ${release.version}`); autoUpdateLogger_.info('Is Pre-release:', release.prerelease); if (compareVersions(release.version, packageInfo.version) <= 0) { @@ -126,12 +126,12 @@ function checkForUpdates(inBackground, window, logFilePath, options) { buttons: [_('OK')], }); } else { - const releaseNotes = release.notes.trim() ? '\n\n' + release.notes.trim() : ''; + const releaseNotes = release.notes.trim() ? `\n\n${release.notes.trim()}` : ''; const newVersionString = release.prerelease ? _('%s (pre-release)', release.version) : release.version; const buttonIndex = dialog.showMessageBox(parentWindow_, { type: 'info', - message: _('An update is available, do you want to download it now?') + '\n\n' + _('Your version: %s', packageInfo.version) + '\n' + _('New version: %s', newVersionString) + releaseNotes, + message: `${_('An update is available, do you want to download it now?')}\n\n${_('Your version: %s', packageInfo.version)}\n${_('New version: %s', newVersionString)}${releaseNotes}`, buttons: [_('Yes'), _('No')], }); diff --git a/ElectronClient/app/compile-package-info.js b/ElectronClient/app/compile-package-info.js index 4aa835e7b..fbe9a6e3e 100644 --- a/ElectronClient/app/compile-package-info.js +++ b/ElectronClient/app/compile-package-info.js @@ -4,7 +4,7 @@ const execSync = require('child_process').execSync; // Electron Builder strip off certain important keys from package.json, which we need, in particular build.appId // so this script is used to preserve the keys that we need. -const packageInfo = require(__dirname + '/package.json'); +const packageInfo = require(`${__dirname}/package.json`); let removeKeys = ['scripts', 'devDependencies', 'optionalDependencies', 'dependencies']; @@ -30,8 +30,8 @@ if (typeof branch !== 'undefined' && typeof hash !== 'undefined') { packageInfo.git = { branch: branch, hash: hash }; } -let fileContent = '// Auto-generated by compile-package-info.js\n// Do not change directly\nconst packageInfo = ' + JSON.stringify(packageInfo, null, 4) + ';'; +let fileContent = `// Auto-generated by compile-package-info.js\n// Do not change directly\nconst packageInfo = ${JSON.stringify(packageInfo, null, 4)};`; fileContent += '\n'; fileContent += 'module.exports = packageInfo;'; -fs.writeFileSync(__dirname + '/packageInfo.js', fileContent); +fs.writeFileSync(`${__dirname}/packageInfo.js`, fileContent); diff --git a/ElectronClient/app/compile.js b/ElectronClient/app/compile.js index 4d8254e05..222162714 100644 --- a/ElectronClient/app/compile.js +++ b/ElectronClient/app/compile.js @@ -1,8 +1,8 @@ const fs = require('fs-extra'); const spawnSync = require('child_process').spawnSync; -const babelPath = __dirname + '/node_modules/.bin/babel' + (process.platform === 'win32' ? '.cmd' : ''); -const basePath = __dirname + '/../..'; +const babelPath = `${__dirname}/node_modules/.bin/babel${process.platform === 'win32' ? '.cmd' : ''}`; +const basePath = `${__dirname}/../..`; function fileIsNewerThan(path1, path2) { if (!fs.existsSync(path2)) return true; @@ -15,7 +15,7 @@ function fileIsNewerThan(path1, path2) { function convertJsx(path) { fs.readdirSync(path).forEach((filename) => { - const jsxPath = path + '/' + filename; + const jsxPath = `${path}/${filename}`; const p = jsxPath.split('.'); if (p.length <= 1) return; const ext = p[p.length - 1]; @@ -24,10 +24,10 @@ function convertJsx(path) { const basePath = p.join('.'); - const jsPath = basePath + '.min.js'; + const jsPath = `${basePath}.min.js`; if (fileIsNewerThan(jsxPath, jsPath)) { - console.info('Compiling ' + jsxPath + '...'); + console.info(`Compiling ${jsxPath}...`); const result = spawnSync(babelPath, ['--presets', 'react', '--out-file', jsPath, jsxPath]); if (result.status !== 0) { const msg = []; @@ -41,13 +41,13 @@ function convertJsx(path) { }); } -convertJsx(__dirname + '/gui'); -convertJsx(__dirname + '/plugins'); +convertJsx(`${__dirname}/gui`); +convertJsx(`${__dirname}/plugins`); const libContent = [ - fs.readFileSync(basePath + '/ReactNativeClient/lib/string-utils-common.js', 'utf8'), - fs.readFileSync(basePath + '/ReactNativeClient/lib/markJsUtils.js', 'utf8'), - fs.readFileSync(basePath + '/ReactNativeClient/lib/renderers/webviewLib.js', 'utf8'), + fs.readFileSync(`${basePath}/ReactNativeClient/lib/string-utils-common.js`, 'utf8'), + fs.readFileSync(`${basePath}/ReactNativeClient/lib/markJsUtils.js`, 'utf8'), + fs.readFileSync(`${basePath}/ReactNativeClient/lib/renderers/webviewLib.js`, 'utf8'), ]; -fs.writeFileSync(__dirname + '/gui/note-viewer/lib.js', libContent.join('\n'), 'utf8'); +fs.writeFileSync(`${__dirname}/gui/note-viewer/lib.js`, libContent.join('\n'), 'utf8'); diff --git a/ElectronClient/app/electronRebuild.js b/ElectronClient/app/electronRebuild.js index b0a30cf27..3f331f235 100644 --- a/ElectronClient/app/electronRebuild.js +++ b/ElectronClient/app/electronRebuild.js @@ -1,7 +1,7 @@ const execCommand = function(command) { const exec = require('child_process').exec; - console.info('Running: ' + command); + console.info(`Running: ${command}`); return new Promise((resolve, reject) => { exec(command, (error, stdout) => { @@ -25,14 +25,14 @@ const isWindows = () => { async function main() { // electron-rebuild --arch ia32 && electron-rebuild --arch x64 - let exePath = __dirname + '/node_modules/.bin/electron-rebuild'; + let exePath = `${__dirname}/node_modules/.bin/electron-rebuild`; if (isWindows()) exePath += '.cmd'; if (isWindows()) { - console.info(await execCommand(['"' + exePath + '"', '--arch ia32'].join(' '))); - console.info(await execCommand(['"' + exePath + '"', '--arch x64'].join(' '))); + console.info(await execCommand([`"${exePath}"`, '--arch ia32'].join(' '))); + console.info(await execCommand([`"${exePath}"`, '--arch x64'].join(' '))); } else { - console.info(await execCommand(['"' + exePath + '"'].join(' '))); + console.info(await execCommand([`"${exePath}"`].join(' '))); } } diff --git a/ElectronClient/app/gui/ConfigMenuBar.jsx b/ElectronClient/app/gui/ConfigMenuBar.jsx index 204cdb003..5a974f852 100644 --- a/ElectronClient/app/gui/ConfigMenuBar.jsx +++ b/ElectronClient/app/gui/ConfigMenuBar.jsx @@ -10,7 +10,7 @@ function ConfigMenuBarButton(props) { return ( ); diff --git a/ElectronClient/app/gui/ConfigScreen.jsx b/ElectronClient/app/gui/ConfigScreen.jsx index 5d0dc8a50..71c592269 100644 --- a/ElectronClient/app/gui/ConfigScreen.jsx +++ b/ElectronClient/app/gui/ConfigScreen.jsx @@ -49,14 +49,14 @@ class ConfigScreenComponent extends React.Component { if (section.name === name) return section; } - throw new Error('Invalid section name: ' + name); + throw new Error(`Invalid section name: ${name}`); } screenFromName(screenName) { if (screenName === 'encryption') return ; if (screenName === 'server') return ; - throw new Error('Invalid screen name: ' + screenName); + throw new Error(`Invalid screen name: ${screenName}`); } switchSection(name) { @@ -249,7 +249,7 @@ class ConfigScreenComponent extends React.Component {
{ @@ -261,7 +261,7 @@ class ConfigScreenComponent extends React.Component { onCheckboxClick(event); }} style={checkboxLabelStyle} - htmlFor={'setting_checkbox_' + key} + htmlFor={`setting_checkbox_${key}`} > {md.label()} @@ -289,7 +289,7 @@ class ConfigScreenComponent extends React.Component { if (!cmdArray[0] && !cmdArray[1]) return ''; let cmdString = pathUtils.quotePath(cmdArray[0]); if (!cmdString) cmdString = '""'; - if (cmdArray[1]) cmdString += ' ' + cmdArray[1]; + if (cmdArray[1]) cmdString += ` ${cmdArray[1]}`; return cmdString; }; @@ -390,7 +390,7 @@ class ConfigScreenComponent extends React.Component { }; const label = [md.label()]; - if (md.unitLabel) label.push('(' + md.unitLabel() + ')'); + if (md.unitLabel) label.push(`(${md.unitLabel()})`); const inputStyle = Object.assign({}, textInputBaseStyle); @@ -414,7 +414,7 @@ class ConfigScreenComponent extends React.Component {
); } else { - console.warn('Type not implemented: ' + key); + console.warn(`Type not implemented: ${key}`); } return output; diff --git a/ElectronClient/app/gui/ExtensionBadge.jsx b/ElectronClient/app/gui/ExtensionBadge.jsx index 326086257..0d4a03b30 100644 --- a/ElectronClient/app/gui/ExtensionBadge.jsx +++ b/ElectronClient/app/gui/ExtensionBadge.jsx @@ -6,19 +6,19 @@ const { _ } = require('lib/locale.js'); function platformAssets(type) { if (type === 'firefox') { return { - logoImage: bridge().buildDir() + '/images/firefox-logo.svg', + logoImage: `${bridge().buildDir()}/images/firefox-logo.svg`, locationLabel: _('Firefox Extension'), }; } if (type === 'chrome') { return { - logoImage: bridge().buildDir() + '/images/chrome-logo.svg', + logoImage: `${bridge().buildDir()}/images/chrome-logo.svg`, locationLabel: _('Chrome Web Store'), }; } - throw new Error('Invalid type:' + type); + throw new Error(`Invalid type:${type}`); } function ExtensionBadge(props) { diff --git a/ElectronClient/app/gui/Header.jsx b/ElectronClient/app/gui/Header.jsx index cbdd48edb..1250e9fad 100644 --- a/ElectronClient/app/gui/Header.jsx +++ b/ElectronClient/app/gui/Header.jsx @@ -123,9 +123,9 @@ class HeaderComponent extends React.Component { if (options.title) iconStyle.marginRight = 5; if ('undefined' != typeof options.iconRotation) { iconStyle.transition = 'transform 0.15s ease-in-out'; - iconStyle.transform = 'rotate(' + options.iconRotation + 'deg)'; + iconStyle.transform = `rotate(${options.iconRotation}deg)`; } - icon = ; + icon = ; } const isEnabled = !('enabled' in options) || options.enabled; @@ -195,7 +195,7 @@ class HeaderComponent extends React.Component { }; const iconName = state.searchQuery ? 'fa-times' : 'fa-search'; - const icon = ; + const icon = ; if (options.onQuery) this.searchOnQuery_ = options.onQuery; const usageLink = !this.state.showSearchUsageLink ? null : ( @@ -222,7 +222,7 @@ class HeaderComponent extends React.Component { style.height = theme.headerHeight; style.display = 'flex'; style.flexDirection = 'row'; - style.borderBottom = '1px solid ' + theme.dividerColor; + style.borderBottom = `1px solid ${theme.dividerColor}`; style.boxSizing = 'border-box'; const items = []; @@ -252,9 +252,9 @@ class HeaderComponent extends React.Component { const item = this.props.items[i]; if (item.type === 'search') { - items.push(this.makeSearch('item_' + i + '_search', itemStyle, item, this.state)); + items.push(this.makeSearch(`item_${i}_search`, itemStyle, item, this.state)); } else { - items.push(this.makeButton('item_' + i + '_' + item.title, itemStyle, item)); + items.push(this.makeButton(`item_${i}_${item.title}`, itemStyle, item)); } } } diff --git a/ElectronClient/app/gui/IconButton.jsx b/ElectronClient/app/gui/IconButton.jsx index b39461558..92199b7d7 100644 --- a/ElectronClient/app/gui/IconButton.jsx +++ b/ElectronClient/app/gui/IconButton.jsx @@ -9,7 +9,7 @@ class IconButton extends React.Component { color: theme.color, fontSize: theme.fontSize * 1.4, }; - const icon = ; + const icon = ; const rootStyle = Object.assign( { diff --git a/ElectronClient/app/gui/NoteList.jsx b/ElectronClient/app/gui/NoteList.jsx index 15fd5feb9..4eb1e3764 100644 --- a/ElectronClient/app/gui/NoteList.jsx +++ b/ElectronClient/app/gui/NoteList.jsx @@ -40,7 +40,7 @@ class NoteListComponent extends React.Component { display: 'flex', alignItems: 'stretch', backgroundColor: theme.backgroundColor, - borderBottom: '1px solid ' + theme.dividerColor, + borderBottom: `1px solid ${theme.dividerColor}`, }, listItemSelected: { backgroundColor: theme.selectedColor, @@ -222,7 +222,7 @@ class NoteListComponent extends React.Component { // Need to include "todo_completed" in key so that checkbox is updated when // item is changed via sync. return ( -
+
{checkbox} - + ); } diff --git a/ElectronClient/app/gui/NoteRevisionViewer.jsx b/ElectronClient/app/gui/NoteRevisionViewer.jsx index 4ca1e1aba..a7fb6d4a8 100644 --- a/ElectronClient/app/gui/NoteRevisionViewer.jsx +++ b/ElectronClient/app/gui/NoteRevisionViewer.jsx @@ -114,7 +114,7 @@ class NoteRevisionViewerComponent extends React.PureComponent { const theme = themeStyle(this.props.theme); const markupToHtml = new MarkupToHtml({ - resourceBaseUrl: 'file://' + Setting.value('resourceDir') + '/', + resourceBaseUrl: `file://${Setting.value('resourceDir')}/`, }); const result = markupToHtml.render(markupLanguage, noteBody, theme, { @@ -138,7 +138,7 @@ class NoteRevisionViewerComponent extends React.PureComponent { revisionListItems.push( ); } @@ -149,7 +149,7 @@ class NoteRevisionViewerComponent extends React.PureComponent { const titleInput = (