diff --git a/.eslintrc.js b/.eslintrc.js index 858f52129..391628f04 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -54,16 +54,20 @@ module.exports = { // This error is always a false positive so far since it detects // possible race conditions in contexts where we know it cannot happen. "require-atomic-updates": 0, + "prefer-const": ["error"], + "no-var": ["error"], // Checks rules of Hooks "react-hooks/rules-of-hooks": "error", // Checks effect dependencies - "react-hooks/exhaustive-deps": "warn", + // Disable because of this: https://github.com/facebook/react/issues/16265 + // "react-hooks/exhaustive-deps": "warn", // ------------------------------- // Formatting // ------------------------------- "space-in-parens": ["error", "never"], + "space-infix-ops": ["error"], "semi": ["error", "always"], "eol-last": ["error", "always"], "quotes": ["error", "single"], @@ -92,7 +96,7 @@ module.exports = { "multiline-comment-style": ["error", "separate-lines"], "space-before-blocks": "error", "spaced-comment": ["error", "always"], - "keyword-spacing": ["error", { "before": true, "after": true }] + "keyword-spacing": ["error", { "before": true, "after": true }], }, "plugins": [ "react", diff --git a/CliClient/app/app-gui.js b/CliClient/app/app-gui.js index 23268ed16..f12465250 100644 --- a/CliClient/app/app-gui.js +++ b/CliClient/app/app-gui.js @@ -134,7 +134,7 @@ class AppGui { const item = folderList.currentItem; if (item === '-') { - let newIndex = event.currentIndex + (event.previousIndex < event.currentIndex ? +1 : -1); + const newIndex = event.currentIndex + (event.previousIndex < event.currentIndex ? +1 : -1); let nextItem = folderList.itemAt(newIndex); if (!nextItem) nextItem = folderList.itemAt(event.previousIndex); @@ -186,7 +186,7 @@ class AppGui { borderRightWidth: 1, }; noteList.on('currentItemChange', async () => { - let note = noteList.currentItem; + const note = noteList.currentItem; this.store_.dispatch({ type: 'NOTE_SELECT', id: note ? note.id : null, @@ -338,7 +338,7 @@ class AppGui { if (consoleWidget.isMaximized__ === doMaximize) return; - let constraints = { + const constraints = { type: 'stretch', factor: !doMaximize ? 1 : 4, }; @@ -415,10 +415,10 @@ class AppGui { async handleModelAction(action) { this.logger().info('Action:', action); - let state = Object.assign({}, defaultState); + const state = Object.assign({}, defaultState); state.notes = this.widget('noteList').items; - let newState = reducer(state, action); + const newState = reducer(state, action); if (newState !== state) { this.widget('noteList').items = newState.notes; @@ -485,9 +485,9 @@ class AppGui { // this.logger().debug('Got command: ' + cmd); try { - let note = this.widget('noteList').currentItem; - let folder = this.widget('folderList').currentItem; - let args = splitCommandString(cmd); + const note = this.widget('noteList').currentItem; + const folder = this.widget('folderList').currentItem; + const args = splitCommandString(cmd); for (let i = 0; i < args.length; i++) { if (args[i] == '$n') { @@ -548,7 +548,7 @@ class AppGui { stdout(text) { if (text === null || text === undefined) return; - let lines = text.split('\n'); + const lines = text.split('\n'); for (let i = 0; i < lines.length; i++) { const v = typeof lines[i] === 'object' ? JSON.stringify(lines[i]) : lines[i]; this.widget('console').addLine(v); @@ -626,7 +626,7 @@ class AppGui { if (link.type === 'item') { const itemId = link.id; - let item = await BaseItem.loadItemById(itemId); + const item = await BaseItem.loadItemById(itemId); if (!item) throw new Error(`No item with ID ${itemId}`); // Should be nearly impossible if (item.type_ === BaseModel.TYPE_RESOURCE) { @@ -750,7 +750,7 @@ class AppGui { // ------------------------------------------------------------------------- const shortcutKey = this.currentShortcutKeys_.join(''); - let keymapItem = this.keymapItemByKey(shortcutKey); + const keymapItem = this.keymapItemByKey(shortcutKey); // If this command is an alias to another command, resolve to the actual command @@ -766,7 +766,7 @@ class AppGui { if (keymapItem.type === 'function') { this.processFunctionCommand(keymapItem.command); } else if (keymapItem.type === 'prompt') { - let promptOptions = {}; + const promptOptions = {}; if ('cursorPosition' in keymapItem) promptOptions.cursorPosition = keymapItem.cursorPosition; const commandString = await statusBar.prompt(keymapItem.command ? keymapItem.command : '', null, promptOptions); this.addCommandToConsole(commandString); diff --git a/CliClient/app/app.js b/CliClient/app/app.js index 1a2984222..5dcc099a5 100644 --- a/CliClient/app/app.js +++ b/CliClient/app/app.js @@ -47,7 +47,7 @@ class Application extends BaseApplication { } async loadItem(type, pattern, options = null) { - let output = await this.loadItems(type, pattern, options); + const output = await this.loadItems(type, pattern, options); if (output.length > 1) { // output.sort((a, b) => { return a.user_updated_time < b.user_updated_time ? +1 : -1; }); @@ -144,7 +144,7 @@ class Application extends BaseApplication { if (options.type === 'boolean') { if (answer === null) return false; // Pressed ESCAPE if (!answer) answer = options.answers[0]; - let positiveIndex = options.booleanAnswerDefault == 'y' ? 0 : 1; + const positiveIndex = options.booleanAnswerDefault == 'y' ? 0 : 1; return answer.toLowerCase() === options.answers[positiveIndex].toLowerCase(); } else { return answer; @@ -181,7 +181,7 @@ class Application extends BaseApplication { const ext = fileExtension(path); if (ext != 'js') return; - let CommandClass = require(`./${path}`); + const CommandClass = require(`./${path}`); let cmd = new CommandClass(); if (!cmd.enabled()) return; cmd = this.setupCommand(cmd); @@ -192,8 +192,8 @@ class Application extends BaseApplication { } if (uiType !== null) { - let temp = []; - for (let n in this.commands_) { + const temp = []; + for (const n in this.commands_) { if (!this.commands_.hasOwnProperty(n)) continue; const c = this.commands_[n]; if (!c.supportsUi(uiType)) continue; @@ -207,8 +207,8 @@ class Application extends BaseApplication { async commandNames() { const metadata = await this.commandMetadata(); - let output = []; - for (let n in metadata) { + const output = []; + for (const n in metadata) { if (!metadata.hasOwnProperty(n)) continue; output.push(n); } @@ -227,7 +227,7 @@ class Application extends BaseApplication { const commands = this.commands(); output = {}; - for (let n in commands) { + for (const n in commands) { if (!commands.hasOwnProperty(n)) continue; const cmd = commands[n]; output[n] = cmd.metadata(); @@ -251,7 +251,7 @@ class Application extends BaseApplication { 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)); + const e = new Error(_('No such command: %s', name)); e.type = 'notFound'; throw e; } else { @@ -362,7 +362,7 @@ class Application extends BaseApplication { } const output = []; - for (let n in itemsByCommand) { + for (const n in itemsByCommand) { if (!itemsByCommand.hasOwnProperty(n)) continue; output.push(itemsByCommand[n]); } diff --git a/CliClient/app/autocompletion.js b/CliClient/app/autocompletion.js index 63835dee6..73836e090 100644 --- a/CliClient/app/autocompletion.js +++ b/CliClient/app/autocompletion.js @@ -1,20 +1,20 @@ -var { app } = require('./app.js'); -var Note = require('lib/models/Note.js'); -var Folder = require('lib/models/Folder.js'); -var Tag = require('lib/models/Tag.js'); -var { cliUtils } = require('./cli-utils.js'); -var yargParser = require('yargs-parser'); -var fs = require('fs-extra'); +const { app } = require('./app.js'); +const Note = require('lib/models/Note.js'); +const Folder = require('lib/models/Folder.js'); +const Tag = require('lib/models/Tag.js'); +const { cliUtils } = require('./cli-utils.js'); +const yargParser = require('yargs-parser'); +const fs = require('fs-extra'); async function handleAutocompletionPromise(line) { // Auto-complete the command name const names = await app().commandNames(); - let words = getArguments(line); + const words = getArguments(line); // If there is only one word and it is not already a command name then you // should look for commands it could be if (words.length == 1) { if (names.indexOf(words[0]) === -1) { - let x = names.filter(n => n.indexOf(words[0]) === 0); + const x = names.filter(n => n.indexOf(words[0]) === 0); if (x.length === 1) { return `${x[0]} `; } @@ -36,8 +36,8 @@ async function handleAutocompletionPromise(line) { } // complete an option - let next = words.length > 1 ? words[words.length - 1] : ''; - let l = []; + const next = words.length > 1 ? words[words.length - 1] : ''; + const l = []; if (next[0] === '-') { for (let i = 0; i < metadata.options.length; i++) { const options = metadata.options[i][0].split(' '); @@ -60,7 +60,7 @@ async function handleAutocompletionPromise(line) { if (l.length === 0) { return line; } - let ret = l.map(a => toCommandLine(a)); + const ret = l.map(a => toCommandLine(a)); ret.prefix = `${toCommandLine(words.slice(0, -1))} `; return ret; } @@ -69,7 +69,7 @@ async function handleAutocompletionPromise(line) { // words that don't start with a - less one for the command name const positionalArgs = words.filter(a => a.indexOf('-') !== 0).length - 1; - let cmdUsage = yargParser(metadata.usage)['_']; + const cmdUsage = yargParser(metadata.usage)['_']; cmdUsage.splice(0, 1); if (cmdUsage.length >= positionalArgs) { @@ -95,29 +95,29 @@ async function handleAutocompletionPromise(line) { } if (argName == 'tag') { - let tags = await Tag.search({ titlePattern: `${next}*` }); + const tags = await Tag.search({ titlePattern: `${next}*` }); l.push(...tags.map(n => n.title)); } if (argName == 'file') { - let files = await fs.readdir('.'); + const files = await fs.readdir('.'); l.push(...files); } if (argName == 'tag-command') { - let c = filterList(['add', 'remove', 'list', 'notetags'], next); + const c = filterList(['add', 'remove', 'list', 'notetags'], next); l.push(...c); } if (argName == 'todo-command') { - let c = filterList(['toggle', 'clear'], next); + const c = filterList(['toggle', 'clear'], next); l.push(...c); } } if (l.length === 1) { return toCommandLine([...words.slice(0, -1), l[0]]); } else if (l.length > 1) { - let ret = l.map(a => toCommandLine(a)); + const ret = l.map(a => toCommandLine(a)); ret.prefix = `${toCommandLine(words.slice(0, -1))} `; return ret; } @@ -155,7 +155,7 @@ function getArguments(line) { let inSingleQuotes = false; let inDoubleQuotes = false; let currentWord = ''; - let parsed = []; + const parsed = []; for (let i = 0; i < line.length; i++) { if (line[i] === '"') { if (inDoubleQuotes) { @@ -192,7 +192,7 @@ function getArguments(line) { return parsed; } function filterList(list, next) { - let output = []; + const output = []; for (let i = 0; i < list.length; i++) { if (list[i].indexOf(next) !== 0) continue; output.push(list[i]); diff --git a/CliClient/app/base-command.js b/CliClient/app/base-command.js index 79e3df585..1e445f287 100644 --- a/CliClient/app/base-command.js +++ b/CliClient/app/base-command.js @@ -50,7 +50,7 @@ class BaseCommand { async cancel() {} name() { - let r = this.usage().split(' '); + const r = this.usage().split(' '); return r[0]; } diff --git a/CliClient/app/build-doc.js b/CliClient/app/build-doc.js index 877596a14..afdfe9924 100644 --- a/CliClient/app/build-doc.js +++ b/CliClient/app/build-doc.js @@ -15,11 +15,11 @@ function wrap(text, indent) { } function renderOptions(options) { - let output = []; + const output = []; const optionColWidth = getOptionColWidth(options); for (let i = 0; i < options.length; i++) { - let option = options[i]; + const option = options[i]; const flag = option[0]; const indent = INDENT + INDENT + ' '.repeat(optionColWidth + 2); @@ -33,7 +33,7 @@ function renderOptions(options) { } function renderCommand(cmd) { - let output = []; + const output = []; output.push(INDENT + cmd.usage()); output.push(''); output.push(wrap(cmd.description(), INDENT + INDENT)); @@ -48,14 +48,14 @@ function renderCommand(cmd) { } function getCommands() { - let output = []; + const output = []; fs.readdirSync(__dirname).forEach(path => { if (path.indexOf('command-') !== 0) return; const ext = fileExtension(path); if (ext != 'js') return; - let CommandClass = require(`./${path}`); - let cmd = new CommandClass(); + const CommandClass = require(`./${path}`); + const cmd = new CommandClass(); if (!cmd.enabled()) return; if (cmd.hidden()) return; output.push(cmd); @@ -73,7 +73,7 @@ function getOptionColWidth(options) { } function getHeader() { - let output = []; + const output = []; output.push('NAME'); output.push(''); @@ -84,7 +84,7 @@ function getHeader() { output.push('DESCRIPTION'); output.push(''); - let description = []; + const description = []; description.push('Joplin is a note taking and to-do application, which can handle a large number of notes organised into notebooks.'); description.push('The notes are searchable, can be copied, tagged and modified with your own text editor.'); description.push('\n\n'); @@ -98,7 +98,7 @@ function getHeader() { } function getFooter() { - let output = []; + const output = []; output.push('WEBSITE'); output.push(''); @@ -120,10 +120,10 @@ async function main() { // setLocale('fr_FR'); const commands = getCommands(); - let commandBlocks = []; + const commandBlocks = []; for (let i = 0; i < commands.length; i++) { - let cmd = commands[i]; + const cmd = commands[i]; commandBlocks.push(renderCommand(cmd)); } diff --git a/CliClient/app/cli-integration-tests.js b/CliClient/app/cli-integration-tests.js index 426118adc..1e900cc32 100644 --- a/CliClient/app/cli-integration-tests.js +++ b/CliClient/app/cli-integration-tests.js @@ -40,8 +40,8 @@ function createClient(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}`; + const exePath = `node ${joplinAppPath}`; + const cmd = `${exePath} --update-geolocation-disabled --env dev --profile ${client.profileDir} ${command}`; logger.info(`${client.id}: ${command}`); return new Promise((resolve, reject) => { @@ -129,8 +129,8 @@ testUnits.testCat = async () => { await execCommand(client, 'mkbook nb1'); await execCommand(client, 'mknote mynote'); - let folder = await Folder.loadByTitle('nb1'); - let note = await Note.loadFolderNoteByField(folder.id, 'title', 'mynote'); + const folder = await Folder.loadByTitle('nb1'); + const note = await Note.loadFolderNoteByField(folder.id, 'title', 'mynote'); let r = await execCommand(client, 'cat mynote'); assertTrue(r.indexOf('mynote') >= 0); @@ -149,7 +149,7 @@ testUnits.testConfig = async () => { await Setting.load(); assertEquals('subl', Setting.value('editor')); - let r = await execCommand(client, 'config'); + const r = await execCommand(client, 'config'); assertTrue(r.indexOf('editor') >= 0); assertTrue(r.indexOf('subl') >= 0); }; @@ -161,14 +161,14 @@ testUnits.testCp = async () => { await execCommand(client, 'cp n1'); - let f1 = await Folder.loadByTitle('nb1'); - let f2 = await Folder.loadByTitle('nb2'); + const f1 = await Folder.loadByTitle('nb1'); + const f2 = await Folder.loadByTitle('nb2'); let notes = await Note.previews(f1.id); assertEquals(2, notes.length); await execCommand(client, 'cp n1 nb2'); - let notesF1 = await Note.previews(f1.id); + const notesF1 = await Note.previews(f1.id); assertEquals(2, notesF1.length); notes = await Note.previews(f2.id); assertEquals(1, notes.length); @@ -179,7 +179,7 @@ testUnits.testLs = async () => { await execCommand(client, 'mkbook nb1'); await execCommand(client, 'mknote note1'); await execCommand(client, 'mknote note2'); - let r = await execCommand(client, 'ls'); + const r = await execCommand(client, 'ls'); assertTrue(r.indexOf('note1') >= 0); assertTrue(r.indexOf('note2') >= 0); @@ -191,8 +191,8 @@ testUnits.testMv = async () => { await execCommand(client, 'mknote n1'); await execCommand(client, 'mv n1 nb2'); - let f1 = await Folder.loadByTitle('nb1'); - let f2 = await Folder.loadByTitle('nb2'); + const f1 = await Folder.loadByTitle('nb1'); + const f2 = await Folder.loadByTitle('nb2'); let notes1 = await Note.previews(f1.id); let notes2 = await Note.previews(f2.id); @@ -224,12 +224,12 @@ async function main() { let onlyThisTest = 'testMv'; onlyThisTest = ''; - for (let n in testUnits) { + for (const n in testUnits) { if (!testUnits.hasOwnProperty(n)) continue; if (onlyThisTest && n != onlyThisTest) continue; await clearDatabase(); - let testName = n.substr(4).toLowerCase(); + const testName = n.substr(4).toLowerCase(); process.stdout.write(`${testName}: `); await testUnits[n](); console.info(''); diff --git a/CliClient/app/cli-utils.js b/CliClient/app/cli-utils.js index e85076536..40d072613 100644 --- a/CliClient/app/cli-utils.js +++ b/CliClient/app/cli-utils.js @@ -11,27 +11,27 @@ cliUtils.printArray = function(logFunction, rows) { const ALIGN_LEFT = 0; const ALIGN_RIGHT = 1; - let colWidths = []; - let colAligns = []; + const colWidths = []; + const colAligns = []; for (let i = 0; i < rows.length; i++) { - let row = rows[i]; + const row = rows[i]; for (let j = 0; j < row.length; j++) { - let item = row[j]; - let width = item ? item.toString().length : 0; - let align = typeof item == 'number' ? ALIGN_RIGHT : ALIGN_LEFT; + const item = row[j]; + const width = item ? item.toString().length : 0; + const align = typeof item == 'number' ? ALIGN_RIGHT : ALIGN_LEFT; if (!colWidths[j] || colWidths[j] < width) colWidths[j] = width; if (colAligns.length <= j) colAligns[j] = align; } } for (let row = 0; row < rows.length; row++) { - let line = []; + const line = []; for (let col = 0; col < colWidths.length; col++) { - let item = rows[row][col]; - let width = colWidths[col]; - let dir = colAligns[col] == ALIGN_LEFT ? stringPadding.RIGHT : stringPadding.LEFT; + const item = rows[row][col]; + const width = colWidths[col]; + const dir = colAligns[col] == ALIGN_LEFT ? stringPadding.RIGHT : stringPadding.LEFT; line.push(stringPadding(item, width, ' ', dir)); } logFunction(line.join(' ')); @@ -39,7 +39,7 @@ cliUtils.printArray = function(logFunction, rows) { }; cliUtils.parseFlags = function(flags) { - let output = {}; + const output = {}; flags = flags.split(','); for (let i = 0; i < flags.length; i++) { let f = flags[i].trim(); @@ -76,11 +76,11 @@ cliUtils.parseCommandArg = function(arg) { cliUtils.makeCommandArgs = function(cmd, argv) { let cmdUsage = cmd.usage(); cmdUsage = yargParser(cmdUsage); - let output = {}; + const output = {}; - let options = cmd.options(); - let booleanFlags = []; - let aliases = {}; + const options = cmd.options(); + const booleanFlags = []; + const aliases = {}; for (let i = 0; i < options.length; i++) { if (options[i].length != 2) throw new Error(`Invalid options: ${options[i]}`); let flags = options[i][0]; @@ -97,7 +97,7 @@ cliUtils.makeCommandArgs = function(cmd, argv) { } } - let args = yargParser(argv, { + const args = yargParser(argv, { boolean: booleanFlags, alias: aliases, string: ['_'], @@ -113,8 +113,8 @@ cliUtils.makeCommandArgs = function(cmd, argv) { } } - let argOptions = {}; - for (let key in args) { + const argOptions = {}; + for (const key in args) { if (!args.hasOwnProperty(key)) continue; if (key == '_') continue; argOptions[key] = args[key]; @@ -134,7 +134,7 @@ cliUtils.promptMcq = function(message, answers) { }); message += '\n\n'; - for (let n in answers) { + for (const n in answers) { if (!answers.hasOwnProperty(n)) continue; message += `${_('%s: %s', n, answers[n])}\n`; } diff --git a/CliClient/app/command-attach.js b/CliClient/app/command-attach.js index 7d92737bf..c7ee88f7c 100644 --- a/CliClient/app/command-attach.js +++ b/CliClient/app/command-attach.js @@ -14,9 +14,9 @@ class Command extends BaseCommand { } async action(args) { - let title = args['note']; + const title = args['note']; - let note = await app().loadItem(BaseModel.TYPE_NOTE, title, { parent: app().currentFolder() }); + const note = await app().loadItem(BaseModel.TYPE_NOTE, title, { parent: app().currentFolder() }); this.encryptionCheck(note); if (!note) throw new Error(_('Cannot find "%s".', title)); diff --git a/CliClient/app/command-cat.js b/CliClient/app/command-cat.js index fd64a5435..3a66acc21 100644 --- a/CliClient/app/command-cat.js +++ b/CliClient/app/command-cat.js @@ -18,9 +18,9 @@ class Command extends BaseCommand { } async action(args) { - let title = args['note']; + const title = args['note']; - let item = await app().loadItem(BaseModel.TYPE_NOTE, title, { parent: app().currentFolder() }); + const item = await app().loadItem(BaseModel.TYPE_NOTE, title, { parent: app().currentFolder() }); if (!item) throw new Error(_('Cannot find "%s".', title)); const content = args.options.verbose ? await Note.serialize(item) : await Note.serializeForEdit(item); diff --git a/CliClient/app/command-config.js b/CliClient/app/command-config.js index 7490a7b33..e4af92ff3 100644 --- a/CliClient/app/command-config.js +++ b/CliClient/app/command-config.js @@ -35,7 +35,7 @@ class Command extends BaseCommand { }); inputStream.on('end', () => { - let json = chunks.join(''); + const json = chunks.join(''); let settingsObj; try { settingsObj = JSON.parse(json); @@ -83,7 +83,7 @@ class Command extends BaseCommand { }; if (isExport || (!isImport && !args.value)) { - let keys = Setting.keys(!verbose, 'cli'); + const keys = Setting.keys(!verbose, 'cli'); keys.sort(); if (isExport) { diff --git a/CliClient/app/command-dump.js b/CliClient/app/command-dump.js index b8939de14..3847ccbad 100644 --- a/CliClient/app/command-dump.js +++ b/CliClient/app/command-dump.js @@ -18,15 +18,15 @@ class Command extends BaseCommand { async action() { let items = []; - let folders = await Folder.all(); + const folders = await Folder.all(); for (let i = 0; i < folders.length; i++) { - let folder = folders[i]; - let notes = await Note.previews(folder.id); + const folder = folders[i]; + const notes = await Note.previews(folder.id); items.push(folder); items = items.concat(notes); } - let tags = await Tag.all(); + const tags = await Tag.all(); for (let i = 0; i < tags.length; i++) { tags[i].notes_ = await Tag.noteIds(tags[i].id); } diff --git a/CliClient/app/command-e2ee.js b/CliClient/app/command-e2ee.js index f00984ef7..08845f581 100644 --- a/CliClient/app/command-e2ee.js +++ b/CliClient/app/command-e2ee.js @@ -138,7 +138,7 @@ class Command extends BaseCommand { if (!targetPath) throw new Error('Please specify the sync target path.'); const dirPaths = function(targetPath) { - let paths = []; + const paths = []; fs.readdirSync(targetPath).forEach(path => { paths.push(path); }); @@ -151,10 +151,10 @@ class Command extends BaseCommand { let encryptedResourceCount = 0; let otherItemCount = 0; - let encryptedPaths = []; - let decryptedPaths = []; + const encryptedPaths = []; + const decryptedPaths = []; - let paths = dirPaths(targetPath); + const paths = dirPaths(targetPath); for (let i = 0; i < paths.length; i++) { const path = paths[i]; @@ -164,7 +164,7 @@ class Command extends BaseCommand { // this.stdout(fullPath); if (path === '.resource') { - let resourcePaths = dirPaths(fullPath); + const resourcePaths = dirPaths(fullPath); for (let j = 0; j < resourcePaths.length; j++) { const resourcePath = resourcePaths[j]; resourceCount++; diff --git a/CliClient/app/command-edit.js b/CliClient/app/command-edit.js index 7eb8e5846..d13897c38 100644 --- a/CliClient/app/command-edit.js +++ b/CliClient/app/command-edit.js @@ -35,7 +35,7 @@ class Command extends BaseCommand { // Load note or create it if it doesn't exist // ------------------------------------------------------------------------- - let title = args['note']; + const title = args['note']; if (!app().currentFolder()) throw new Error(_('No active notebook.')); let note = await app().loadItem(BaseModel.TYPE_NOTE, title); @@ -91,7 +91,7 @@ class Command extends BaseCommand { const updatedContent = await fs.readFile(tempFilePath, 'utf8'); if (updatedContent !== originalContent) { - let updatedNote = await Note.unserializeForEdit(updatedContent); + const updatedNote = await Note.unserializeForEdit(updatedContent); updatedNote.id = note.id; await Note.save(updatedNote); this.stdout(_('Note has been saved.')); diff --git a/CliClient/app/command-export.js b/CliClient/app/command-export.js index 9532936ab..cd582f0ed 100644 --- a/CliClient/app/command-export.js +++ b/CliClient/app/command-export.js @@ -24,7 +24,7 @@ class Command extends BaseCommand { } async action(args) { - let exportOptions = {}; + const exportOptions = {}; exportOptions.path = args.path; exportOptions.format = args.options.format ? args.options.format : 'jex'; diff --git a/CliClient/app/command-geoloc.js b/CliClient/app/command-geoloc.js index aaf248054..8b8220a95 100644 --- a/CliClient/app/command-geoloc.js +++ b/CliClient/app/command-geoloc.js @@ -14,9 +14,9 @@ class Command extends BaseCommand { } async action(args) { - let title = args['note']; + const title = args['note']; - let item = await app().loadItem(BaseModel.TYPE_NOTE, title, { parent: app().currentFolder() }); + const item = await app().loadItem(BaseModel.TYPE_NOTE, title, { parent: app().currentFolder() }); if (!item) throw new Error(_('Cannot find "%s".', title)); const url = Note.geolocationUrl(item); this.stdout(url); diff --git a/CliClient/app/command-help.js b/CliClient/app/command-help.js index e26a88b1b..afce0ed47 100644 --- a/CliClient/app/command-help.js +++ b/CliClient/app/command-help.js @@ -15,8 +15,8 @@ class Command extends BaseCommand { allCommands() { const commands = app().commands(app().uiType()); - let output = []; - for (let n in commands) { + const output = []; + for (const n in commands) { if (!commands.hasOwnProperty(n)) continue; const command = commands[n]; if (command.hidden()) continue; @@ -48,7 +48,7 @@ class Command extends BaseCommand { .gui() .keymap(); - let rows = []; + const rows = []; for (let i = 0; i < keymap.length; i++) { const item = keymap[i]; diff --git a/CliClient/app/command-import.js b/CliClient/app/command-import.js index 4b559e897..eac6fc248 100644 --- a/CliClient/app/command-import.js +++ b/CliClient/app/command-import.js @@ -25,7 +25,7 @@ class Command extends BaseCommand { } async action(args) { - let folder = await app().loadItem(BaseModel.TYPE_FOLDER, args.notebook); + const folder = await app().loadItem(BaseModel.TYPE_FOLDER, args.notebook); if (args.notebook && !folder) throw new Error(_('Cannot find "%s".', args.notebook)); @@ -39,7 +39,7 @@ class Command extends BaseCommand { // onProgress/onError supported by Enex import only importOptions.onProgress = progressState => { - let line = []; + const line = []; line.push(_('Found: %d.', progressState.loaded)); line.push(_('Created: %d.', progressState.created)); if (progressState.updated) line.push(_('Updated: %d.', progressState.updated)); @@ -51,7 +51,7 @@ class Command extends BaseCommand { }; importOptions.onError = error => { - let s = error.trace ? error.trace : error.toString(); + const s = error.trace ? error.trace : error.toString(); this.stdout(s); }; diff --git a/CliClient/app/command-ls.js b/CliClient/app/command-ls.js index 852b025b4..cf0bf734a 100644 --- a/CliClient/app/command-ls.js +++ b/CliClient/app/command-ls.js @@ -34,11 +34,11 @@ class Command extends BaseCommand { } async action(args) { - let pattern = args['note-pattern']; + const pattern = args['note-pattern']; let items = []; - let options = args.options; + const options = args.options; - let queryOptions = {}; + const queryOptions = {}; if (options.limit) queryOptions.limit = options.limit; if (options.sort) { queryOptions.orderBy = options.sort; @@ -70,19 +70,19 @@ class Command extends BaseCommand { } else { let hasTodos = false; for (let i = 0; i < items.length; i++) { - let item = items[i]; + const item = items[i]; if (item.is_todo) { hasTodos = true; break; } } - let seenTitles = []; - let rows = []; + const seenTitles = []; + const rows = []; let shortIdShown = false; for (let i = 0; i < items.length; i++) { - let item = items[i]; - let row = []; + const item = items[i]; + const row = []; if (options.long) { row.push(BaseModel.shortId(item.id)); diff --git a/CliClient/app/command-mkbook.js b/CliClient/app/command-mkbook.js index 032a89285..1faf3cb44 100644 --- a/CliClient/app/command-mkbook.js +++ b/CliClient/app/command-mkbook.js @@ -13,7 +13,7 @@ class Command extends BaseCommand { } async action(args) { - let folder = await Folder.save({ title: args['new-notebook'] }, { userSideValidation: true }); + const folder = await Folder.save({ title: args['new-notebook'] }, { userSideValidation: true }); app().switchCurrentFolder(folder); } } diff --git a/CliClient/app/command-rmnote.js b/CliClient/app/command-rmnote.js index 9d8c18d11..c832404e8 100644 --- a/CliClient/app/command-rmnote.js +++ b/CliClient/app/command-rmnote.js @@ -26,7 +26,7 @@ class Command extends BaseCommand { const ok = force ? true : await this.prompt(notes.length > 1 ? _('%d notes match this pattern. Delete them?', notes.length) : _('Delete note?'), { booleanAnswerDefault: 'n' }); if (!ok) return; - let ids = notes.map(n => n.id); + const ids = notes.map(n => n.id); await Note.batchDelete(ids); } } diff --git a/CliClient/app/command-search.js b/CliClient/app/command-search.js index fc1385f3f..9953a3e28 100644 --- a/CliClient/app/command-search.js +++ b/CliClient/app/command-search.js @@ -18,8 +18,8 @@ class Command extends BaseCommand { } async action(args) { - let pattern = args['pattern']; - let folderTitle = args['notebook']; + const pattern = args['pattern']; + const folderTitle = args['notebook']; let folder = null; if (folderTitle) { diff --git a/CliClient/app/command-set.js b/CliClient/app/command-set.js index 402899acb..a70329f6a 100644 --- a/CliClient/app/command-set.js +++ b/CliClient/app/command-set.js @@ -23,18 +23,18 @@ class Command extends BaseCommand { } async action(args) { - let title = args['note']; - let propName = args['name']; + const title = args['note']; + const propName = args['name']; let propValue = args['value']; if (!propValue) propValue = ''; - let notes = await app().loadItems(BaseModel.TYPE_NOTE, title); + const notes = await app().loadItems(BaseModel.TYPE_NOTE, title); if (!notes.length) throw new Error(_('Cannot find "%s".', title)); for (let i = 0; i < notes.length; i++) { this.encryptionCheck(notes[i]); - let newNote = { + const newNote = { id: notes[i].id, type_: notes[i].type_, }; diff --git a/CliClient/app/command-status.js b/CliClient/app/command-status.js index aad423dd6..0f0322ba9 100644 --- a/CliClient/app/command-status.js +++ b/CliClient/app/command-status.js @@ -14,20 +14,20 @@ class Command extends BaseCommand { } async action() { - let service = new ReportService(); - let report = await service.status(Setting.value('sync.target')); + const service = new ReportService(); + const report = await service.status(Setting.value('sync.target')); for (let i = 0; i < report.length; i++) { - let section = report[i]; + const section = report[i]; if (i > 0) this.stdout(''); this.stdout(`# ${section.title}`); this.stdout(''); - for (let n in section.body) { + for (const n in section.body) { if (!section.body.hasOwnProperty(n)) continue; - let line = section.body[n]; + const line = section.body[n]; this.stdout(line); } } diff --git a/CliClient/app/command-sync.js b/CliClient/app/command-sync.js index 8c6515da1..2425a4fd1 100644 --- a/CliClient/app/command-sync.js +++ b/CliClient/app/command-sync.js @@ -161,9 +161,9 @@ class Command extends BaseCommand { const sync = await syncTarget.synchronizer(); - let options = { + const options = { onProgress: report => { - let lines = Synchronizer.reportToLines(report); + const lines = Synchronizer.reportToLines(report); if (lines.length) cliUtils.redraw(lines.join(' ')); }, onMessage: msg => { @@ -185,7 +185,7 @@ class Command extends BaseCommand { options.context = context; try { - let newContext = await sync.start(options); + const newContext = await sync.start(options); Setting.setValue(contextKey, JSON.stringify(newContext)); } catch (error) { if (error.code == 'alreadyStarted') { diff --git a/CliClient/app/command-tag.js b/CliClient/app/command-tag.js index a0c36d310..d199ff52d 100644 --- a/CliClient/app/command-tag.js +++ b/CliClient/app/command-tag.js @@ -20,7 +20,7 @@ class Command extends BaseCommand { async action(args) { let tag = null; - let options = args.options; + const options = args.options; if (args.tag) tag = await app().loadItem(BaseModel.TYPE_TAG, args.tag); let notes = []; @@ -46,7 +46,7 @@ class Command extends BaseCommand { } } else if (command == 'list') { if (tag) { - let notes = await Tag.notes(tag.id); + const notes = await Tag.notes(tag.id); notes.map(note => { let line = ''; if (options.long) { @@ -70,7 +70,7 @@ class Command extends BaseCommand { this.stdout(line); }); } else { - let tags = await Tag.all(); + const tags = await Tag.all(); tags.map(tag => { this.stdout(tag.title); }); diff --git a/CliClient/app/command-use.js b/CliClient/app/command-use.js index bcdfc3a94..067fae375 100644 --- a/CliClient/app/command-use.js +++ b/CliClient/app/command-use.js @@ -17,7 +17,7 @@ class Command extends BaseCommand { } async action(args) { - let folder = await app().loadItem(BaseModel.TYPE_FOLDER, args['notebook']); + const folder = await app().loadItem(BaseModel.TYPE_FOLDER, args['notebook']); if (!folder) throw new Error(_('Cannot find "%s".', args['notebook'])); app().switchCurrentFolder(folder); } diff --git a/CliClient/app/fuzzing.js b/CliClient/app/fuzzing.js index 6905fc432..e45a07020 100644 --- a/CliClient/app/fuzzing.js +++ b/CliClient/app/fuzzing.js @@ -12,7 +12,7 @@ const fs = require('fs-extra'); const baseDir = `${dirname(__dirname)}/tests/fuzzing`; const syncDir = `${baseDir}/sync`; const joplinAppPath = `${__dirname}/main.js`; -let syncDurations = []; +const syncDurations = []; const fsDriver = new FsDriverNode(); Logger.fsDriver_ = fsDriver; @@ -34,10 +34,10 @@ function createClient(id) { } async function createClients() { - let output = []; - let promises = []; + const output = []; + const promises = []; for (let clientId = 0; clientId < 2; clientId++) { - let client = createClient(clientId); + const client = createClient(clientId); promises.push(fs.remove(client.profileDir)); promises.push( execCommand(client, 'config sync.target 2').then(() => { @@ -2064,8 +2064,8 @@ 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}`; + const exePath = `node ${joplinAppPath}`; + const cmd = `${exePath} --update-geolocation-disabled --env dev --log-level debug --profile ${client.profileDir} ${command}`; logger.info(`${client.id}: ${command}`); if (options.killAfter) { @@ -2073,7 +2073,7 @@ function execCommand(client, command, options = {}) { } return new Promise((resolve, reject) => { - let childProcess = exec(cmd, (error, stdout, stderr) => { + const childProcess = exec(cmd, (error, stdout, stderr) => { if (error) { if (error.signal == 'SIGTERM') { resolve('Process was killed'); @@ -2096,7 +2096,7 @@ function execCommand(client, command, options = {}) { } async function clientItems(client) { - let itemsJson = await execCommand(client, 'dump'); + const itemsJson = await execCommand(client, 'dump'); try { return JSON.parse(itemsJson); } catch (error) { @@ -2105,7 +2105,7 @@ async function clientItems(client) { } function randomTag(items) { - let tags = []; + const tags = []; for (let i = 0; i < items.length; i++) { if (items[i].type_ != 5) continue; tags.push(items[i]); @@ -2115,7 +2115,7 @@ function randomTag(items) { } function randomNote(items) { - let notes = []; + const notes = []; for (let i = 0; i < items.length; i++) { if (items[i].type_ != 1) continue; notes.push(items[i]); @@ -2125,14 +2125,14 @@ function randomNote(items) { } async function execRandomCommand(client) { - let possibleCommands = [ + const possibleCommands = [ ['mkbook {word}', 40], // CREATE FOLDER ['mknote {word}', 70], // CREATE NOTE [ async () => { // DELETE RANDOM ITEM - let items = await clientItems(client); - let item = randomElement(items); + const items = await clientItems(client); + const item = randomElement(items); if (!item) return; if (item.type_ == 1) { @@ -2150,8 +2150,8 @@ async function execRandomCommand(client) { [ async () => { // SYNC - let avgSyncDuration = averageSyncDuration(); - let options = {}; + const avgSyncDuration = averageSyncDuration(); + const options = {}; if (!isNaN(avgSyncDuration)) { if (Math.random() >= 0.5) { options.killAfter = avgSyncDuration * Math.random(); @@ -2164,8 +2164,8 @@ async function execRandomCommand(client) { [ async () => { // UPDATE RANDOM ITEM - let items = await clientItems(client); - let item = randomNote(items); + const items = await clientItems(client); + const item = randomNote(items); if (!item) return; return execCommand(client, `set ${item.id} title "${randomWord()}"`); @@ -2175,12 +2175,12 @@ async function execRandomCommand(client) { [ async () => { // ADD TAG - let items = await clientItems(client); - let note = randomNote(items); + const items = await clientItems(client); + const note = randomNote(items); if (!note) return; - let tag = randomTag(items); - let tagTitle = !tag || Math.random() >= 0.9 ? `tag-${randomWord()}` : tag.title; + const tag = randomTag(items); + const tagTitle = !tag || Math.random() >= 0.9 ? `tag-${randomWord()}` : tag.title; return execCommand(client, `tag add ${tagTitle} ${note.id}`); }, @@ -2191,7 +2191,7 @@ async function execRandomCommand(client) { let cmd = null; while (true) { cmd = randomElement(possibleCommands); - let r = 1 + Math.floor(Math.random() * 100); + const r = 1 + Math.floor(Math.random() * 100); if (r <= cmd[1]) break; } @@ -2210,7 +2210,7 @@ function averageSyncDuration() { } function randomNextCheckTime() { - let output = time.unixMs() + 1000 + Math.random() * 1000 * 120; + const output = time.unixMs() + 1000 + Math.random() * 1000 * 120; logger.info(`Next sync check: ${time.unixMsToIso(output)} (${Math.round((output - time.unixMs()) / 1000)} sec.)`); return output; } @@ -2223,11 +2223,11 @@ function findItem(items, itemId) { } function compareItems(item1, item2) { - let output = []; - for (let n in item1) { + const output = []; + for (const n in item1) { if (!item1.hasOwnProperty(n)) continue; - let p1 = item1[n]; - let p2 = item2[n]; + const p1 = item1[n]; + const p2 = item2[n]; if (n == 'notes_') { p1.sort(); @@ -2243,13 +2243,13 @@ function compareItems(item1, item2) { } function findMissingItems_(items1, items2) { - let output = []; + const output = []; for (let i = 0; i < items1.length; i++) { - let item1 = items1[i]; + const item1 = items1[i]; let found = false; for (let j = 0; j < items2.length; j++) { - let item2 = items2[j]; + const item2 = items2[j]; if (item1.id == item2.id) { found = true; break; @@ -2269,33 +2269,33 @@ function findMissingItems(items1, items2) { } async function compareClientItems(clientItems) { - let itemCounts = []; + const itemCounts = []; for (let i = 0; i < clientItems.length; i++) { - let items = clientItems[i]; + const items = clientItems[i]; itemCounts.push(items.length); } logger.info(`Item count: ${itemCounts.join(', ')}`); - let missingItems = findMissingItems(clientItems[0], clientItems[1]); + const missingItems = findMissingItems(clientItems[0], clientItems[1]); if (missingItems[0].length || missingItems[1].length) { logger.error('Items are different'); logger.error(missingItems); process.exit(1); } - let differences = []; - let items = clientItems[0]; + const differences = []; + const items = clientItems[0]; for (let i = 0; i < items.length; i++) { - let item1 = items[i]; + const item1 = items[i]; for (let clientId = 1; clientId < clientItems.length; clientId++) { - let item2 = findItem(clientItems[clientId], item1.id); + const item2 = findItem(clientItems[clientId], item1.id); if (!item2) { logger.error(`Item not found on client ${clientId}:`); logger.error(item1); process.exit(1); } - let diff = compareItems(item1, item2); + const diff = compareItems(item1, item2); if (diff.length) { differences.push({ item1: JSON.stringify(item1), @@ -2315,7 +2315,7 @@ async function compareClientItems(clientItems) { async function main() { await fs.remove(syncDir); - let clients = await createClients(); + const clients = await createClients(); let clientId = 0; for (let i = 0; i < clients.length; i++) { @@ -2348,7 +2348,7 @@ async function main() { if (state == 'syncCheck') { state = 'waitForSyncCheck'; - let clientItems = []; + const clientItems = []; // Up to 3 sync operations must be performed by each clients in order for them // to be perfectly in sync - in order for each items to send their changes // and get those from the other clients, and to also get changes that are @@ -2356,12 +2356,12 @@ async function main() { // with another one). for (let loopCount = 0; loopCount < 3; loopCount++) { for (let i = 0; i < clients.length; i++) { - let beforeTime = time.unixMs(); + const beforeTime = time.unixMs(); await execCommand(clients[i], 'sync'); syncDurations.push(time.unixMs() - beforeTime); if (syncDurations.length > 20) syncDurations.splice(0, 1); if (loopCount === 2) { - let dump = await execCommand(clients[i], 'dump'); + const dump = await execCommand(clients[i], 'dump'); clientItems[i] = JSON.parse(dump); } } diff --git a/CliClient/app/gui/FolderListWidget.js b/CliClient/app/gui/FolderListWidget.js index 92054993d..404291621 100644 --- a/CliClient/app/gui/FolderListWidget.js +++ b/CliClient/app/gui/FolderListWidget.js @@ -20,7 +20,7 @@ class FolderListWidget extends ListWidget { this.trimItemTitle = false; this.itemRenderer = item => { - let output = []; + const output = []; if (item === '-') { output.push('-'.repeat(this.innerWidth)); } else if (item.type_ === Folder.modelType()) { @@ -121,7 +121,7 @@ class FolderListWidget extends ListWidget { folderHasChildren_(folders, folderId) { for (let i = 0; i < folders.length; i++) { - let folder = folders[i]; + const folder = folders[i]; if (folder.parent_id === folderId) return true; } return false; diff --git a/CliClient/app/gui/StatusBarWidget.js b/CliClient/app/gui/StatusBarWidget.js index c79e14f73..70e6788f2 100644 --- a/CliClient/app/gui/StatusBarWidget.js +++ b/CliClient/app/gui/StatusBarWidget.js @@ -106,7 +106,7 @@ class StatusBarWidget extends BaseWidget { const isSecurePrompt = !!this.promptState_.secure; - let options = { + const options = { cancelable: true, history: this.history, default: this.promptState_.initialText, diff --git a/CliClient/app/help-utils.js b/CliClient/app/help-utils.js index c9483a97a..b60f4e9c6 100644 --- a/CliClient/app/help-utils.js +++ b/CliClient/app/help-utils.js @@ -6,11 +6,11 @@ const MAX_WIDTH = 78; const INDENT = ' '; function renderTwoColumnData(options, baseIndent, width) { - let output = []; + const output = []; const optionColWidth = getOptionColWidth(options); for (let i = 0; i < options.length; i++) { - let option = options[i]; + const option = options[i]; const flag = option[0]; const indent = baseIndent + INDENT + ' '.repeat(optionColWidth + 2); @@ -28,7 +28,7 @@ function renderCommandHelp(cmd, width = null) { const baseIndent = ''; - let output = []; + const output = []; output.push(baseIndent + cmd.usage()); output.push(''); output.push(wrap(cmd.description(), baseIndent + INDENT, width)); @@ -42,7 +42,7 @@ function renderCommandHelp(cmd, width = null) { if (cmd.name() === 'config') { const renderMetadata = md => { - let desc = []; + const desc = []; if (md.label) { let label = md.label(); @@ -77,7 +77,7 @@ function renderCommandHelp(cmd, width = null) { output.push(_('Possible keys/values:')); output.push(''); - let keysValues = []; + const keysValues = []; const keys = Setting.keys(true, 'cli'); for (let i = 0; i < keys.length; i++) { if (keysValues.length) keysValues.push(['', '']); diff --git a/CliClient/app/main.js b/CliClient/app/main.js index 9530e140d..b798ede8d 100644 --- a/CliClient/app/main.js +++ b/CliClient/app/main.js @@ -54,7 +54,7 @@ shimInit(); const application = app(); if (process.platform === 'win32') { - var rl = require('readline').createInterface({ + const rl = require('readline').createInterface({ input: process.stdin, output: process.stdout, }); diff --git a/CliClient/tests/MdToMd.js b/CliClient/tests/MdToMd.js index 9afe16815..186b7f40c 100644 --- a/CliClient/tests/MdToMd.js +++ b/CliClient/tests/MdToMd.js @@ -14,14 +14,14 @@ describe('InteropService_Importer_Md: importLocalImages', function() { it('should import linked files and modify tags appropriately', async function() { const tagNonExistentFile = '![does not exist](does_not_exist.png)'; const note = await importer.importFile(`${__dirname}/md_to_md/sample.md`, 'notebook'); - let items = await Note.linkedItems(note.body); + const items = await Note.linkedItems(note.body); expect(items.length).toBe(2); const inexistentLinkUnchanged = note.body.includes(tagNonExistentFile); expect(inexistentLinkUnchanged).toBe(true); }); it('should only create 1 resource for duplicate links, all tags should be updated', async function() { const note = await importer.importFile(`${__dirname}/md_to_md/sample-duplicate-links.md`, 'notebook'); - let items = await Note.linkedItems(note.body); + const items = await Note.linkedItems(note.body); expect(items.length).toBe(1); const reg = new RegExp(items[0].id, 'g'); const matched = note.body.match(reg); @@ -29,12 +29,12 @@ describe('InteropService_Importer_Md: importLocalImages', function() { }); it('should import linked files and modify tags appropriately when link is also in alt text', async function() { const note = await importer.importFile(`${__dirname}/md_to_md/sample-link-in-alt-text.md`, 'notebook'); - let items = await Note.linkedItems(note.body); + const items = await Note.linkedItems(note.body); expect(items.length).toBe(1); }); it('should passthrough unchanged if no links present', async function() { const note = await importer.importFile(`${__dirname}/md_to_md/sample-no-links.md`, 'notebook'); - let items = await Note.linkedItems(note.body); + const items = await Note.linkedItems(note.body); expect(items.length).toBe(0); expect(note.body).toContain('Unidentified vessel travelling at sub warp speed, bearing 235.7. Fluctuations in energy readings from it, Captain. All transporters off.'); }); diff --git a/CliClient/tests/integration_ShowAllNotes.js b/CliClient/tests/integration_ShowAllNotes.js index 0c5d22b45..22b04a387 100644 --- a/CliClient/tests/integration_ShowAllNotes.js +++ b/CliClient/tests/integration_ShowAllNotes.js @@ -44,19 +44,19 @@ describe('integration_ShowAllNotes', function() { it('should show all notes', asyncTest(async () => { // setup - let folders = await createNTestFolders(3); + const folders = await createNTestFolders(3); Folder.moveToFolder(id(folders[2]), id(folders[1])); // subfolder await time.msleep(100); - let notes0 = await createNTestNotes(3, folders[0]); - let notes1 = await createNTestNotes(3, folders[1]); - let notes2 = await createNTestNotes(3, folders[2]); + const notes0 = await createNTestNotes(3, folders[0]); + const notes1 = await createNTestNotes(3, folders[1]); + const notes2 = await createNTestNotes(3, folders[2]); // TEST ACTION: View all-notes testApp.dispatch({ type: 'SMART_FILTER_SELECT', id: ALL_NOTES_FILTER_ID }); await time.msleep(100); // check: all the notes are shown - let state = testApp.store().getState(); + const state = testApp.store().getState(); expect(state.notesParentType).toEqual('SmartFilter'); expect(state.selectedSmartFilterId).toEqual(ALL_NOTES_FILTER_ID); expect(sortedIds(state.notes)).toEqual(sortedIds(notes0.concat(notes1).concat(notes2))); @@ -64,9 +64,9 @@ describe('integration_ShowAllNotes', function() { it('should show retain note selection when going from a folder to all-notes', asyncTest(async () => { // setup - let folders = await createNTestFolders(2); - let notes0 = await createNTestNotes(3, folders[0]); - let notes1 = await createNTestNotes(3, folders[1]); + const folders = await createNTestFolders(2); + const notes0 = await createNTestNotes(3, folders[0]); + const notes1 = await createNTestNotes(3, folders[1]); testApp.dispatch({ type: 'FOLDER_SELECT', id: id(folders[1]) }); await time.msleep(100); testApp.dispatch({ type: 'NOTE_SELECT', id: id(notes1[1]) }); diff --git a/CliClient/tests/integration_TagList.js b/CliClient/tests/integration_TagList.js index e8ee88362..621014442 100644 --- a/CliClient/tests/integration_TagList.js +++ b/CliClient/tests/integration_TagList.js @@ -8,27 +8,27 @@ const Tag = require('lib/models/Tag.js'); const { time } = require('lib/time-utils.js'); async function createNTestFolders(n) { - let folders = []; + const folders = []; for (let i = 0; i < n; i++) { - let folder = await Folder.save({ title: 'folder' }); + const folder = await Folder.save({ title: 'folder' }); folders.push(folder); } return folders; } async function createNTestNotes(n, folder) { - let notes = []; + const notes = []; for (let i = 0; i < n; i++) { - let note = await Note.save({ title: 'note', parent_id: folder.id, is_conflict: 0 }); + const note = await Note.save({ title: 'note', parent_id: folder.id, is_conflict: 0 }); notes.push(note); } return notes; } async function createNTestTags(n) { - let tags = []; + const tags = []; for (let i = 0; i < n; i++) { - let tag = await Tag.save({ title: 'tag' }); + const tag = await Tag.save({ title: 'tag' }); tags.push(tag); } return tags; @@ -58,9 +58,9 @@ describe('integration_TagList', function() { // the tag list should be cleared if the next note has no tags it('should clear tag list when a note is deleted', asyncTest(async () => { // setup and select the note - let folders = await createNTestFolders(1); - let notes = await createNTestNotes(5, folders[0]); - let tags = await createNTestTags(3); + const folders = await createNTestFolders(1); + const notes = await createNTestNotes(5, folders[0]); + const tags = await createNTestTags(3); await Tag.addNote(tags[2].id, notes[2].id); @@ -96,9 +96,9 @@ describe('integration_TagList', function() { // the tag list should be updated if the next note has tags it('should update tag list when a note is deleted', asyncTest(async () => { // set up and select the note - let folders = await createNTestFolders(1); - let notes = await createNTestNotes(5, folders[0]); - let tags = await createNTestTags(3); + const folders = await createNTestFolders(1); + const notes = await createNTestNotes(5, folders[0]); + const tags = await createNTestTags(3); await Tag.addNote(tags[1].id, notes[1].id); await Tag.addNote(tags[0].id, notes[0].id); @@ -130,8 +130,8 @@ describe('integration_TagList', function() { // check the tag list is updated state = testApp.store().getState(); - let tagIds = state.selectedNoteTags.map(n => n.id).sort(); - let expectedTagIds = [tags[0].id, tags[2].id].sort(); + const tagIds = state.selectedNoteTags.map(n => n.id).sort(); + const expectedTagIds = [tags[0].id, tags[2].id].sort(); expect(state.selectedNoteTags.length).toEqual(2); expect(tagIds).toEqual(expectedTagIds); })); diff --git a/CliClient/tests/models_BaseItem.js b/CliClient/tests/models_BaseItem.js index b138b62a8..cd0181b8c 100644 --- a/CliClient/tests/models_BaseItem.js +++ b/CliClient/tests/models_BaseItem.js @@ -16,8 +16,8 @@ process.on('unhandledRejection', (reason, p) => { }); async function allItems() { - let folders = await Folder.all(); - let notes = await Note.all(); + const folders = await Folder.all(); + const notes = await Note.all(); return folders.concat(notes); } @@ -32,27 +32,27 @@ describe('models_BaseItem', function() { // This is to handle the case where a property is removed from a BaseItem table - in that case files in // the sync target will still have the old property but we don't need it locally. it('should ignore properties that are present in sync file but not in database when serialising', asyncTest(async () => { - let folder = await Folder.save({ title: 'folder1' }); + const folder = await Folder.save({ title: 'folder1' }); let serialized = await Folder.serialize(folder); serialized += '\nignore_me: true'; - let unserialized = await Folder.unserialize(serialized); + const unserialized = await Folder.unserialize(serialized); expect('ignore_me' in unserialized).toBe(false); })); it('should not modify title when unserializing', asyncTest(async () => { - let folder1 = await Folder.save({ title: '' }); - let folder2 = await Folder.save({ title: 'folder1' }); + const folder1 = await Folder.save({ title: '' }); + const folder2 = await Folder.save({ title: 'folder1' }); - let serialized1 = await Folder.serialize(folder1); - let unserialized1 = await Folder.unserialize(serialized1); + const serialized1 = await Folder.serialize(folder1); + const unserialized1 = await Folder.unserialize(serialized1); expect(unserialized1.title).toBe(folder1.title); - let serialized2 = await Folder.serialize(folder2); - let unserialized2 = await Folder.unserialize(serialized2); + const serialized2 = await Folder.serialize(folder2); + const unserialized2 = await Folder.unserialize(serialized2); expect(unserialized2.title).toBe(folder2.title); })); diff --git a/CliClient/tests/models_Folder.js b/CliClient/tests/models_Folder.js index feb188a99..ff132b7eb 100644 --- a/CliClient/tests/models_Folder.js +++ b/CliClient/tests/models_Folder.js @@ -14,8 +14,8 @@ process.on('unhandledRejection', (reason, p) => { }); async function allItems() { - let folders = await Folder.all(); - let notes = await Note.all(); + const folders = await Folder.all(); + const notes = await Note.all(); return folders.concat(notes); } @@ -28,10 +28,10 @@ describe('models_Folder', function() { }); it('should tell if a notebook can be nested under another one', asyncTest(async () => { - let f1 = await Folder.save({ title: 'folder1' }); - let f2 = await Folder.save({ title: 'folder2', parent_id: f1.id }); - let f3 = await Folder.save({ title: 'folder3', parent_id: f2.id }); - let f4 = await Folder.save({ title: 'folder4' }); + const f1 = await Folder.save({ title: 'folder1' }); + const f2 = await Folder.save({ title: 'folder2', parent_id: f1.id }); + const f3 = await Folder.save({ title: 'folder3', parent_id: f2.id }); + const f4 = await Folder.save({ title: 'folder4' }); expect(await Folder.canNestUnder(f1.id, f2.id)).toBe(false); expect(await Folder.canNestUnder(f2.id, f2.id)).toBe(false); @@ -44,9 +44,9 @@ describe('models_Folder', function() { })); it('should recursively delete notes and sub-notebooks', asyncTest(async () => { - let f1 = await Folder.save({ title: 'folder1' }); - let f2 = await Folder.save({ title: 'folder2', parent_id: f1.id }); - let n1 = await Note.save({ title: 'note1', parent_id: f2.id }); + const f1 = await Folder.save({ title: 'folder1' }); + const f2 = await Folder.save({ title: 'folder2', parent_id: f1.id }); + const n1 = await Note.save({ title: 'note1', parent_id: f2.id }); await Folder.delete(f1.id); @@ -57,10 +57,10 @@ describe('models_Folder', function() { it('should sort by last modified, based on content', asyncTest(async () => { let folders; - let f1 = await Folder.save({ title: 'folder1' }); await sleep(0.1); - let f2 = await Folder.save({ title: 'folder2' }); await sleep(0.1); - let f3 = await Folder.save({ title: 'folder3' }); await sleep(0.1); - let n1 = await Note.save({ title: 'note1', parent_id: f2.id }); + const f1 = await Folder.save({ title: 'folder1' }); await sleep(0.1); + const f2 = await Folder.save({ title: 'folder2' }); await sleep(0.1); + const f3 = await Folder.save({ title: 'folder3' }); await sleep(0.1); + const n1 = await Note.save({ title: 'note1', parent_id: f2.id }); folders = await Folder.orderByLastModified(await Folder.all(), 'desc'); expect(folders.length).toBe(3); @@ -68,7 +68,7 @@ describe('models_Folder', function() { expect(folders[1].id).toBe(f3.id); expect(folders[2].id).toBe(f1.id); - let n2 = await Note.save({ title: 'note1', parent_id: f1.id }); + const n2 = await Note.save({ title: 'note1', parent_id: f1.id }); folders = await Folder.orderByLastModified(await Folder.all(), 'desc'); expect(folders[0].id).toBe(f1.id); @@ -91,10 +91,10 @@ describe('models_Folder', function() { it('should sort by last modified, based on content (sub-folders too)', asyncTest(async () => { let folders; - let f1 = await Folder.save({ title: 'folder1' }); await sleep(0.1); - let f2 = await Folder.save({ title: 'folder2' }); await sleep(0.1); - let f3 = await Folder.save({ title: 'folder3', parent_id: f1.id }); await sleep(0.1); - let n1 = await Note.save({ title: 'note1', parent_id: f3.id }); + const f1 = await Folder.save({ title: 'folder1' }); await sleep(0.1); + const f2 = await Folder.save({ title: 'folder2' }); await sleep(0.1); + const f3 = await Folder.save({ title: 'folder3', parent_id: f1.id }); await sleep(0.1); + const n1 = await Note.save({ title: 'note1', parent_id: f3.id }); folders = await Folder.orderByLastModified(await Folder.all(), 'desc'); expect(folders.length).toBe(3); @@ -102,7 +102,7 @@ describe('models_Folder', function() { expect(folders[1].id).toBe(f3.id); expect(folders[2].id).toBe(f2.id); - let n2 = await Note.save({ title: 'note2', parent_id: f2.id }); + const n2 = await Note.save({ title: 'note2', parent_id: f2.id }); folders = await Folder.orderByLastModified(await Folder.all(), 'desc'); expect(folders[0].id).toBe(f2.id); @@ -116,8 +116,8 @@ describe('models_Folder', function() { expect(folders[1].id).toBe(f3.id); expect(folders[2].id).toBe(f2.id); - let f4 = await Folder.save({ title: 'folder4', parent_id: f1.id }); await sleep(0.1); - let n3 = await Note.save({ title: 'note3', parent_id: f4.id }); + const f4 = await Folder.save({ title: 'folder4', parent_id: f1.id }); await sleep(0.1); + const n3 = await Note.save({ title: 'note3', parent_id: f4.id }); folders = await Folder.orderByLastModified(await Folder.all(), 'desc'); expect(folders.length).toBe(4); @@ -128,14 +128,14 @@ describe('models_Folder', function() { })); it('should add node counts', asyncTest(async () => { - let f1 = await Folder.save({ title: 'folder1' }); - let f2 = await Folder.save({ title: 'folder2', parent_id: f1.id }); - let f3 = await Folder.save({ title: 'folder3', parent_id: f2.id }); - let f4 = await Folder.save({ title: 'folder4' }); + const f1 = await Folder.save({ title: 'folder1' }); + const f2 = await Folder.save({ title: 'folder2', parent_id: f1.id }); + const f3 = await Folder.save({ title: 'folder3', parent_id: f2.id }); + const f4 = await Folder.save({ title: 'folder4' }); - let n1 = await Note.save({ title: 'note1', parent_id: f3.id }); - let n2 = await Note.save({ title: 'note1', parent_id: f3.id }); - let n3 = await Note.save({ title: 'note1', parent_id: f1.id }); + const n1 = await Note.save({ title: 'note1', parent_id: f3.id }); + const n2 = await Note.save({ title: 'note1', parent_id: f3.id }); + const n3 = await Note.save({ title: 'note1', parent_id: f1.id }); const folders = await Folder.all(); await Folder.addNoteCounts(folders); @@ -152,17 +152,17 @@ describe('models_Folder', function() { it('should not count completed to-dos', asyncTest(async () => { - let f1 = await Folder.save({ title: 'folder1' }); - let f2 = await Folder.save({ title: 'folder2', parent_id: f1.id }); - let f3 = await Folder.save({ title: 'folder3', parent_id: f2.id }); - let f4 = await Folder.save({ title: 'folder4' }); + const f1 = await Folder.save({ title: 'folder1' }); + const f2 = await Folder.save({ title: 'folder2', parent_id: f1.id }); + const f3 = await Folder.save({ title: 'folder3', parent_id: f2.id }); + const f4 = await Folder.save({ title: 'folder4' }); - let n1 = await Note.save({ title: 'note1', parent_id: f3.id }); - let n2 = await Note.save({ title: 'note2', parent_id: f3.id }); - let n3 = await Note.save({ title: 'note3', parent_id: f1.id }); - let n4 = await Note.save({ title: 'note4', parent_id: f3.id, is_todo: true, todo_completed: 0 }); - let n5 = await Note.save({ title: 'note5', parent_id: f3.id, is_todo: true, todo_completed: 999 }); - let n6 = await Note.save({ title: 'note6', parent_id: f3.id, is_todo: true, todo_completed: 999 }); + const n1 = await Note.save({ title: 'note1', parent_id: f3.id }); + const n2 = await Note.save({ title: 'note2', parent_id: f3.id }); + const n3 = await Note.save({ title: 'note3', parent_id: f1.id }); + const n4 = await Note.save({ title: 'note4', parent_id: f3.id, is_todo: true, todo_completed: 0 }); + const n5 = await Note.save({ title: 'note5', parent_id: f3.id, is_todo: true, todo_completed: 999 }); + const n6 = await Note.save({ title: 'note6', parent_id: f3.id, is_todo: true, todo_completed: 999 }); const folders = await Folder.all(); await Folder.addNoteCounts(folders, false); @@ -179,9 +179,9 @@ describe('models_Folder', function() { it('should recursively find folder path', asyncTest(async () => { - let f1 = await Folder.save({ title: 'folder1' }); - let f2 = await Folder.save({ title: 'folder2', parent_id: f1.id }); - let f3 = await Folder.save({ title: 'folder3', parent_id: f2.id }); + const f1 = await Folder.save({ title: 'folder1' }); + const f2 = await Folder.save({ title: 'folder2', parent_id: f1.id }); + const f3 = await Folder.save({ title: 'folder3', parent_id: f2.id }); const folders = await Folder.all(); const folderPath = await Folder.folderPath(folders, f3.id); diff --git a/CliClient/tests/models_Note.js b/CliClient/tests/models_Note.js index afab6fecb..06e0f259d 100644 --- a/CliClient/tests/models_Note.js +++ b/CliClient/tests/models_Note.js @@ -23,8 +23,8 @@ 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 }); + const folder1 = await Folder.save({ title: 'folder1' }); + const 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 items = await Note.linkedItems(note2.body); @@ -69,7 +69,7 @@ describe('models_Note', function() { })); it('should change the type of notes', asyncTest(async () => { - let folder1 = await Folder.save({ title: 'folder1' }); + const folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); note1 = await Note.load(note1.id); @@ -90,7 +90,7 @@ describe('models_Note', function() { })); it('should serialize and unserialize without modifying data', asyncTest(async () => { - let folder1 = await Folder.save({ title: 'folder1' }); + const folder1 = await Folder.save({ title: 'folder1' }); const testCases = [ [{ title: '', body: 'Body and no title\nSecond line\nThird Line', parent_id: folder1.id }, '', 'Body and no title\nSecond line\nThird Line'], @@ -107,9 +107,9 @@ describe('models_Note', function() { const expectedTitle = t[1]; const expectedBody = t[1]; - let note1 = await Note.save(input); - let serialized = await Note.serialize(note1); - let unserialized = await Note.unserialize(serialized); + const note1 = await Note.save(input); + const serialized = await Note.serialize(note1); + const unserialized = await Note.unserialize(serialized); expect(unserialized.title).toBe(input.title); expect(unserialized.body).toBe(input.body); @@ -117,10 +117,10 @@ describe('models_Note', function() { })); it('should reset fields for a duplicate', asyncTest(async () => { - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'note', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'note', parent_id: folder1.id }); - let duplicatedNote = await Note.duplicate(note1.id); + const duplicatedNote = await Note.duplicate(note1.id); expect(duplicatedNote !== note1).toBe(true); expect(duplicatedNote.created_time !== note1.created_time).toBe(true); diff --git a/CliClient/tests/models_Resource.js b/CliClient/tests/models_Resource.js index 22ff4d9da..3c693bb4d 100644 --- a/CliClient/tests/models_Resource.js +++ b/CliClient/tests/models_Resource.js @@ -27,30 +27,30 @@ describe('models_Resource', function() { }); it('should have a "done" fetch_status when created locally', asyncTest(async () => { - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); await shim.attachFileToNote(note1, testImagePath); - let resource1 = (await Resource.all())[0]; - let ls = await Resource.localState(resource1); + const resource1 = (await Resource.all())[0]; + const ls = await Resource.localState(resource1); expect(ls.fetch_status).toBe(Resource.FETCH_STATUS_DONE); })); it('should have a default local state', asyncTest(async () => { - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); await shim.attachFileToNote(note1, testImagePath); - let resource1 = (await Resource.all())[0]; - let ls = await Resource.localState(resource1); + const resource1 = (await Resource.all())[0]; + const ls = await Resource.localState(resource1); expect(!ls.id).toBe(true); expect(ls.resource_id).toBe(resource1.id); expect(ls.fetch_status).toBe(Resource.FETCH_STATUS_DONE); })); it('should save and delete local state', asyncTest(async () => { - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); await shim.attachFileToNote(note1, testImagePath); - let resource1 = (await Resource.all())[0]; + const resource1 = (await Resource.all())[0]; await Resource.setLocalState(resource1, { fetch_status: Resource.FETCH_STATUS_IDLE }); let ls = await Resource.localState(resource1); @@ -63,13 +63,13 @@ describe('models_Resource', function() { })); it('should resize the resource if the image is below the required dimensions', asyncTest(async () => { - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); const previousMax = Resource.IMAGE_MAX_DIMENSION; Resource.IMAGE_MAX_DIMENSION = 5; await shim.attachFileToNote(note1, testImagePath); Resource.IMAGE_MAX_DIMENSION = previousMax; - let resource1 = (await Resource.all())[0]; + const resource1 = (await Resource.all())[0]; const originalStat = await shim.fsDriver().stat(testImagePath); const newStat = await shim.fsDriver().stat(Resource.fullPath(resource1)); @@ -78,10 +78,10 @@ describe('models_Resource', function() { })); it('should not resize the resource if the image is below the required dimensions', asyncTest(async () => { - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); await shim.attachFileToNote(note1, testImagePath); - let resource1 = (await Resource.all())[0]; + const resource1 = (await Resource.all())[0]; const originalStat = await shim.fsDriver().stat(testImagePath); const newStat = await shim.fsDriver().stat(Resource.fullPath(resource1)); diff --git a/CliClient/tests/models_Tag.js b/CliClient/tests/models_Tag.js index 8107c16bd..843144f99 100644 --- a/CliClient/tests/models_Tag.js +++ b/CliClient/tests/models_Tag.js @@ -24,8 +24,8 @@ describe('models_Tag', function() { }); it('should add tags by title', asyncTest(async () => { - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); await Tag.setNoteTagsByTitles(note1.id, ['un', 'deux']); @@ -34,8 +34,8 @@ describe('models_Tag', function() { })); it('should not allow renaming tag to existing tag names', asyncTest(async () => { - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); await Tag.setNoteTagsByTitles(note1.id, ['un', 'deux']); @@ -46,8 +46,8 @@ describe('models_Tag', function() { })); it('should not return tags without notes', asyncTest(async () => { - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); await Tag.setNoteTagsByTitles(note1.id, ['un']); let tags = await Tag.allWithNotes(); @@ -60,9 +60,9 @@ describe('models_Tag', function() { })); it('should return tags with note counts', 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 2nd note', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); + const note2 = await Note.save({ title: 'ma 2nd note', parent_id: folder1.id }); await Tag.setNoteTagsByTitles(note1.id, ['un']); await Tag.setNoteTagsByTitles(note2.id, ['un']); @@ -83,10 +83,10 @@ describe('models_Tag', function() { })); it('should load individual tags with note count', 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 2nd note', parent_id: folder1.id }); - let tag = await Tag.save({ title: 'mytag' }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); + const note2 = await Note.save({ title: 'ma 2nd note', parent_id: folder1.id }); + const tag = await Tag.save({ title: 'mytag' }); await Tag.addNote(tag.id, note1.id); let tagWithCount = await Tag.loadWithCount(tag.id); @@ -98,16 +98,16 @@ describe('models_Tag', function() { })); it('should get common tags for set of notes', asyncTest(async () => { - let folder1 = await Folder.save({ title: 'folder1' }); - let taga = await Tag.save({ title: 'mytaga' }); - let tagb = await Tag.save({ title: 'mytagb' }); - let tagc = await Tag.save({ title: 'mytagc' }); - let tagd = await Tag.save({ title: 'mytagd' }); + const folder1 = await Folder.save({ title: 'folder1' }); + const taga = await Tag.save({ title: 'mytaga' }); + const tagb = await Tag.save({ title: 'mytagb' }); + const tagc = await Tag.save({ title: 'mytagc' }); + const tagd = await Tag.save({ title: 'mytagd' }); - let note0 = await Note.save({ title: 'ma note 0', parent_id: folder1.id }); - let note1 = await Note.save({ title: 'ma note 1', parent_id: folder1.id }); - let note2 = await Note.save({ title: 'ma note 2', parent_id: folder1.id }); - let note3 = await Note.save({ title: 'ma note 3', parent_id: folder1.id }); + const note0 = await Note.save({ title: 'ma note 0', parent_id: folder1.id }); + const note1 = await Note.save({ title: 'ma note 1', parent_id: folder1.id }); + const note2 = await Note.save({ title: 'ma note 2', parent_id: folder1.id }); + const note3 = await Note.save({ title: 'ma note 3', parent_id: folder1.id }); await Tag.addNote(taga.id, note1.id); diff --git a/CliClient/tests/reducer.js b/CliClient/tests/reducer.js index d5443917c..b17ff93f4 100644 --- a/CliClient/tests/reducer.js +++ b/CliClient/tests/reducer.js @@ -7,7 +7,7 @@ const Note = require('lib/models/Note.js'); const Tag = require('lib/models/Tag.js'); const { reducer, defaultState, stateUtils } = require('lib/reducer.js'); -function initTestState(folders, selectedFolderIndex, notes, selectedNoteIndexes, tags=null, selectedTagIndex=null) { +function initTestState(folders, selectedFolderIndex, notes, selectedNoteIndexes, tags = null, selectedTagIndex = null) { let state = defaultState; if (selectedFolderIndex != null) { @@ -20,7 +20,7 @@ function initTestState(folders, selectedFolderIndex, notes, selectedNoteIndexes, state = reducer(state, { type: 'NOTE_UPDATE_ALL', notes: notes, noteSource: 'test' }); } if (selectedNoteIndexes != null) { - let selectedIds = []; + const selectedIds = []; for (let i = 0; i < selectedNoteIndexes.length; i++) { selectedIds.push(notes[selectedNoteIndexes[i]].id); } @@ -37,7 +37,7 @@ function initTestState(folders, selectedFolderIndex, notes, selectedNoteIndexes, } function createExpectedState(items, keepIndexes, selectedIndexes) { - let expected = { items: [], selectedIds: [] }; + const expected = { items: [], selectedIds: [] }; for (let i = 0; i < selectedIndexes.length; i++) { expected.selectedIds.push(items[selectedIndexes[i]].id); @@ -48,8 +48,8 @@ function createExpectedState(items, keepIndexes, selectedIndexes) { return expected; } -function getIds(items, indexes=null) { - let ids = []; +function getIds(items, indexes = null) { + const ids = []; for (let i = 0; i < items.length; i++) { if (indexes == null || i in indexes) { ids.push(items[i].id); @@ -76,9 +76,9 @@ describe('Reducer', function() { // tests for NOTE_DELETE it('should delete selected note', asyncTest(async () => { // create 1 folder - let folders = await createNTestFolders(1); + const folders = await createNTestFolders(1); // create 5 notes - let notes = await createNTestNotes(5, folders[0]); + const notes = await createNTestNotes(5, folders[0]); // select the 1st folder and the 3rd note let state = initTestState(folders, 0, notes, [2]); @@ -87,7 +87,7 @@ describe('Reducer', function() { state = reducer(state, { type: 'NOTE_DELETE', id: notes[2].id }); // expect that the third note is missing, and the 4th note is now selected - let expected = createExpectedState(notes, [0,1,3,4], [3]); + const expected = createExpectedState(notes, [0,1,3,4], [3]); // check the ids of all the remaining notes expect(getIds(state.notes)).toEqual(getIds(expected.items)); @@ -96,136 +96,136 @@ describe('Reducer', function() { })); it('should delete selected note at top', asyncTest(async () => { - let folders = await createNTestFolders(1); - let notes = await createNTestNotes(5, folders[0]); + const folders = await createNTestFolders(1); + const notes = await createNTestNotes(5, folders[0]); let state = initTestState(folders, 0, notes, [1]); // test action state = reducer(state, { type: 'NOTE_DELETE', id: notes[0].id }); - let expected = createExpectedState(notes, [1,2,3,4], [1]); + const expected = createExpectedState(notes, [1,2,3,4], [1]); expect(getIds(state.notes)).toEqual(getIds(expected.items)); expect(state.selectedNoteIds).toEqual(expected.selectedIds); })); it('should delete last remaining note', asyncTest(async () => { - let folders = await createNTestFolders(1); - let notes = await createNTestNotes(1, folders[0]); + const folders = await createNTestFolders(1); + const notes = await createNTestNotes(1, folders[0]); let state = initTestState(folders, 0, notes, [0]); // test action state = reducer(state, { type: 'NOTE_DELETE', id: notes[0].id }); - let expected = createExpectedState(notes, [], []); + const expected = createExpectedState(notes, [], []); expect(getIds(state.notes)).toEqual(getIds(expected.items)); expect(state.selectedNoteIds).toEqual(expected.selectedIds); })); it('should delete selected note at bottom', asyncTest(async () => { - let folders = await createNTestFolders(1); - let notes = await createNTestNotes(5, folders[0]); + const folders = await createNTestFolders(1); + const notes = await createNTestNotes(5, folders[0]); let state = initTestState(folders, 0, notes, [4]); // test action state = reducer(state, { type: 'NOTE_DELETE', id: notes[4].id }); - let expected = createExpectedState(notes, [0,1,2,3], [3]); + const expected = createExpectedState(notes, [0,1,2,3], [3]); expect(getIds(state.notes)).toEqual(getIds(expected.items)); expect(state.selectedNoteIds).toEqual(expected.selectedIds); })); it('should delete note when a note below is selected', asyncTest(async () => { - let folders = await createNTestFolders(1); - let notes = await createNTestNotes(5, folders[0]); + const folders = await createNTestFolders(1); + const notes = await createNTestNotes(5, folders[0]); let state = initTestState(folders, 0, notes, [3]); // test action state = reducer(state, { type: 'NOTE_DELETE', id: notes[1].id }); - let expected = createExpectedState(notes, [0,2,3,4], [3]); + const expected = createExpectedState(notes, [0,2,3,4], [3]); expect(getIds(state.notes)).toEqual(getIds(expected.items)); expect(state.selectedNoteIds).toEqual(expected.selectedIds); })); it('should delete note when a note above is selected', asyncTest(async () => { - let folders = await createNTestFolders(1); - let notes = await createNTestNotes(5, folders[0]); + const folders = await createNTestFolders(1); + const notes = await createNTestNotes(5, folders[0]); let state = initTestState(folders, 0, notes, [1]); // test action state = reducer(state, { type: 'NOTE_DELETE', id: notes[3].id }); - let expected = createExpectedState(notes, [0,1,2,4], [1]); + const expected = createExpectedState(notes, [0,1,2,4], [1]); expect(getIds(state.notes)).toEqual(getIds(expected.items)); expect(state.selectedNoteIds).toEqual(expected.selectedIds); })); it('should delete selected notes', asyncTest(async () => { - let folders = await createNTestFolders(1); - let notes = await createNTestNotes(5, folders[0]); + const folders = await createNTestFolders(1); + const notes = await createNTestNotes(5, folders[0]); let state = initTestState(folders, 0, notes, [1,2]); // test action state = reducer(state, { type: 'NOTE_DELETE', id: notes[1].id }); state = reducer(state, { type: 'NOTE_DELETE', id: notes[2].id }); - let expected = createExpectedState(notes, [0,3,4], [3]); + const expected = createExpectedState(notes, [0,3,4], [3]); expect(getIds(state.notes)).toEqual(getIds(expected.items)); expect(state.selectedNoteIds).toEqual(expected.selectedIds); })); it('should delete note when a notes below it are selected', asyncTest(async () => { - let folders = await createNTestFolders(1); - let notes = await createNTestNotes(5, folders[0]); + const folders = await createNTestFolders(1); + const notes = await createNTestNotes(5, folders[0]); let state = initTestState(folders, 0, notes, [3,4]); // test action state = reducer(state, { type: 'NOTE_DELETE', id: notes[1].id }); - let expected = createExpectedState(notes, [0,2,3,4], [3,4]); + const expected = createExpectedState(notes, [0,2,3,4], [3,4]); expect(getIds(state.notes)).toEqual(getIds(expected.items)); expect(state.selectedNoteIds).toEqual(expected.selectedIds); })); it('should delete note when a notes above it are selected', asyncTest(async () => { - let folders = await createNTestFolders(1); - let notes = await createNTestNotes(5, folders[0]); + const folders = await createNTestFolders(1); + const notes = await createNTestNotes(5, folders[0]); let state = initTestState(folders, 0, notes, [1,2]); // test action state = reducer(state, { type: 'NOTE_DELETE', id: notes[3].id }); - let expected = createExpectedState(notes, [0,1,2,4], [1,2]); + const expected = createExpectedState(notes, [0,1,2,4], [1,2]); expect(getIds(state.notes)).toEqual(getIds(expected.items)); expect(state.selectedNoteIds).toEqual(expected.selectedIds); })); it('should delete notes at end', asyncTest(async () => { - let folders = await createNTestFolders(1); - let notes = await createNTestNotes(5, folders[0]); + const folders = await createNTestFolders(1); + const notes = await createNTestNotes(5, folders[0]); let state = initTestState(folders, 0, notes, [3,4]); // test action state = reducer(state, { type: 'NOTE_DELETE', id: notes[3].id }); state = reducer(state, { type: 'NOTE_DELETE', id: notes[4].id }); - let expected = createExpectedState(notes, [0,1,2], [2]); + const expected = createExpectedState(notes, [0,1,2], [2]); expect(getIds(state.notes)).toEqual(getIds(expected.items)); expect(state.selectedNoteIds).toEqual(expected.selectedIds); })); it('should delete notes when non-contiguous selection', asyncTest(async () => { - let folders = await createNTestFolders(1); - let notes = await createNTestNotes(5, folders[0]); + const folders = await createNTestFolders(1); + const notes = await createNTestNotes(5, folders[0]); let state = initTestState(folders, 0, notes, [0,2,4]); // test action @@ -233,7 +233,7 @@ describe('Reducer', function() { state = reducer(state, { type: 'NOTE_DELETE', id: notes[2].id }); state = reducer(state, { type: 'NOTE_DELETE', id: notes[4].id }); - let expected = createExpectedState(notes, [1,3], [1]); + const expected = createExpectedState(notes, [1,3], [1]); expect(getIds(state.notes)).toEqual(getIds(expected.items)); expect(state.selectedNoteIds).toEqual(expected.selectedIds); @@ -241,42 +241,42 @@ describe('Reducer', function() { // tests for FOLDER_DELETE it('should delete selected notebook', asyncTest(async () => { - let folders = await createNTestFolders(5); - let notes = await createNTestNotes(5, folders[0]); + const folders = await createNTestFolders(5); + const notes = await createNTestNotes(5, folders[0]); let state = initTestState(folders, 2, notes, [2]); // test action state = reducer(state, { type: 'FOLDER_DELETE', id: folders[2].id }); - let expected = createExpectedState(folders, [0,1,3,4], [3]); + const expected = createExpectedState(folders, [0,1,3,4], [3]); expect(getIds(state.folders)).toEqual(getIds(expected.items)); expect(state.selectedFolderId).toEqual(expected.selectedIds[0]); })); it('should delete notebook when a book above is selected', asyncTest(async () => { - let folders = await createNTestFolders(5); - let notes = await createNTestNotes(5, folders[0]); + const folders = await createNTestFolders(5); + const notes = await createNTestNotes(5, folders[0]); let state = initTestState(folders, 1, notes, [2]); // test action state = reducer(state, { type: 'FOLDER_DELETE', id: folders[2].id }); - let expected = createExpectedState(folders, [0,1,3,4], [1]); + const expected = createExpectedState(folders, [0,1,3,4], [1]); expect(getIds(state.folders)).toEqual(getIds(expected.items)); expect(state.selectedFolderId).toEqual(expected.selectedIds[0]); })); it('should delete notebook when a book below is selected', asyncTest(async () => { - let folders = await createNTestFolders(5); - let notes = await createNTestNotes(5, folders[0]); + const folders = await createNTestFolders(5); + const notes = await createNTestNotes(5, folders[0]); let state = initTestState(folders, 4, notes, [2]); // test action state = reducer(state, { type: 'FOLDER_DELETE', id: folders[2].id }); - let expected = createExpectedState(folders, [0,1,3,4], [4]); + const expected = createExpectedState(folders, [0,1,3,4], [4]); expect(getIds(state.folders)).toEqual(getIds(expected.items)); expect(state.selectedFolderId).toEqual(expected.selectedIds[0]); @@ -284,47 +284,47 @@ describe('Reducer', function() { // tests for TAG_DELETE it('should delete selected tag', asyncTest(async () => { - let tags = await createNTestTags(5); + const tags = await createNTestTags(5); let state = initTestState(null, null, null, null, tags, [2]); // test action state = reducer(state, { type: 'TAG_DELETE', id: tags[2].id }); - let expected = createExpectedState(tags, [0,1,3,4], [3]); + const expected = createExpectedState(tags, [0,1,3,4], [3]); expect(getIds(state.tags)).toEqual(getIds(expected.items)); expect(state.selectedTagId).toEqual(expected.selectedIds[0]); })); it('should delete tag when a tag above is selected', asyncTest(async () => { - let tags = await createNTestTags(5); + const tags = await createNTestTags(5); let state = initTestState(null, null, null, null, tags, [2]); // test action state = reducer(state, { type: 'TAG_DELETE', id: tags[4].id }); - let expected = createExpectedState(tags, [0,1,2,3], [2]); + const expected = createExpectedState(tags, [0,1,2,3], [2]); expect(getIds(state.tags)).toEqual(getIds(expected.items)); expect(state.selectedTagId).toEqual(expected.selectedIds[0]); })); it('should delete tag when a tag below is selected', asyncTest(async () => { - let tags = await createNTestTags(5); + const tags = await createNTestTags(5); let state = initTestState(null, null, null, null, tags, [2]); // test action state = reducer(state, { type: 'TAG_DELETE', id: tags[0].id }); - let expected = createExpectedState(tags, [1,2,3,4], [2]); + const expected = createExpectedState(tags, [1,2,3,4], [2]); expect(getIds(state.tags)).toEqual(getIds(expected.items)); expect(state.selectedTagId).toEqual(expected.selectedIds[0]); })); it('should select all notes', asyncTest(async () => { - let folders = await createNTestFolders(2); - let notes = []; + const folders = await createNTestFolders(2); + const notes = []; for (let i = 0; i < folders.length; i++) { notes.push(...await createNTestNotes(3, folders[i])); } diff --git a/CliClient/tests/services_EncryptionService.js b/CliClient/tests/services_EncryptionService.js index b6cb53cdb..6871b1069 100644 --- a/CliClient/tests/services_EncryptionService.js +++ b/CliClient/tests/services_EncryptionService.js @@ -94,7 +94,7 @@ describe('services_EncryptionService', function() { })); it('should not upgrade master key if invalid password', asyncTest(async () => { - let masterKey = await service.generateMasterKey('123456', { + const masterKey = await service.generateMasterKey('123456', { encryptionMethod: EncryptionService.METHOD_SJCL_2, }); @@ -207,7 +207,7 @@ describe('services_EncryptionService', function() { await service.unloadMasterKey(masterKey); - let hasThrown = await checkThrowAsync(async () => await service.decryptString(cipherText)); + const hasThrown = await checkThrowAsync(async () => await service.decryptString(cipherText)); expect(hasThrown).toBe(true); })); @@ -222,7 +222,7 @@ describe('services_EncryptionService', function() { let cipherText = await service.encryptString('some secret'); cipherText += 'ABCDEFGHIJ'; - let hasThrown = await checkThrowAsync(async () => await service.decryptString(cipherText)); + const hasThrown = await checkThrowAsync(async () => await service.decryptString(cipherText)); expect(hasThrown).toBe(true); })); @@ -232,10 +232,10 @@ describe('services_EncryptionService', function() { masterKey = await MasterKey.save(masterKey); await service.loadMasterKey_(masterKey, '123456', true); - let folder = await Folder.save({ title: 'folder' }); - let note = await Note.save({ title: 'encrypted note', body: 'something', parent_id: folder.id }); - let serialized = await Note.serializeForSync(note); - let deserialized = Note.filter(await Note.unserialize(serialized)); + const folder = await Folder.save({ title: 'folder' }); + const note = await Note.save({ title: 'encrypted note', body: 'something', parent_id: folder.id }); + const serialized = await Note.serializeForSync(note); + const deserialized = Note.filter(await Note.unserialize(serialized)); // Check that required properties are not encrypted expect(deserialized.id).toBe(note.id); diff --git a/CliClient/tests/services_InteropService.js b/CliClient/tests/services_InteropService.js index 9ced4d46a..2b030c771 100644 --- a/CliClient/tests/services_InteropService.js +++ b/CliClient/tests/services_InteropService.js @@ -59,7 +59,7 @@ describe('services_InteropService', function() { // Check that a new folder, with a new ID, has been created expect(await Folder.count()).toBe(1); - let folder2 = (await Folder.all())[0]; + const folder2 = (await Folder.all())[0]; expect(folder2.id).not.toBe(folder1.id); expect(folder2.title).toBe(folder1.title); @@ -68,7 +68,7 @@ describe('services_InteropService', function() { // As there was already a folder with the same title, check that the new one has been renamed await Folder.delete(folder2.id); - let folder3 = (await Folder.all())[0]; + const folder3 = (await Folder.all())[0]; expect(await Folder.count()).toBe(1); expect(folder3.title).not.toBe(folder2.title); @@ -81,7 +81,7 @@ describe('services_InteropService', function() { it('should export and import folders and notes', asyncTest(async () => { const service = new InteropService(); - let folder1 = await Folder.save({ title: 'folder1' }); + const 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`; @@ -95,7 +95,7 @@ describe('services_InteropService', function() { expect(await Note.count()).toBe(1); let note2 = (await Note.all())[0]; - let folder2 = (await Folder.all())[0]; + const folder2 = (await Folder.all())[0]; expect(note1.parent_id).not.toBe(note2.parent_id); expect(note1.id).not.toBe(note2.id); @@ -110,7 +110,7 @@ describe('services_InteropService', function() { await service.import({ path: filePath }); note2 = (await Note.all())[0]; - let note3 = (await Note.all())[1]; + const note3 = (await Note.all())[1]; expect(note2.id).not.toBe(note3.id); expect(note2.parent_id).not.toBe(note3.parent_id); @@ -120,7 +120,7 @@ describe('services_InteropService', function() { it('should export and import notes to specific folder', asyncTest(async () => { const service = new InteropService(); - let folder1 = await Folder.save({ title: 'folder1' }); + const 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`; @@ -140,8 +140,8 @@ describe('services_InteropService', function() { it('should export and import tags', asyncTest(async () => { const service = new InteropService(); const filePath = `${exportDir()}/test.jex`; - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); let tag1 = await Tag.save({ title: 'mon tag' }); tag1 = await Tag.load(tag1.id); await Tag.addNote(tag1.id, note1.id); @@ -155,8 +155,8 @@ describe('services_InteropService', function() { await service.import({ path: filePath }); expect(await Tag.count()).toBe(1); - let tag2 = (await Tag.all())[0]; - let note2 = (await Note.all())[0]; + const tag2 = (await Tag.all())[0]; + const note2 = (await Note.all())[0]; expect(tag1.id).not.toBe(tag2.id); let fieldNames = Note.fieldNames(); @@ -180,12 +180,12 @@ describe('services_InteropService', function() { it('should export and import resources', asyncTest(async () => { const service = new InteropService(); const filePath = `${exportDir()}/test.jex`; - let folder1 = await Folder.save({ title: 'folder1' }); + const 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`); note1 = await Note.load(note1.id); let resourceIds = await Note.linkedResourceIds(note1.body); - let resource1 = await Resource.load(resourceIds[0]); + const resource1 = await Resource.load(resourceIds[0]); await service.export({ path: filePath }); @@ -195,11 +195,11 @@ describe('services_InteropService', function() { expect(await Resource.count()).toBe(2); - let note2 = (await Note.all())[0]; + const note2 = (await Note.all())[0]; expect(note2.body).not.toBe(note1.body); resourceIds = await Note.linkedResourceIds(note2.body); expect(resourceIds.length).toBe(1); - let resource2 = await Resource.load(resourceIds[0]); + const resource2 = await Resource.load(resourceIds[0]); expect(resource2.id).not.toBe(resource1.id); let fieldNames = Note.fieldNames(); @@ -216,8 +216,8 @@ describe('services_InteropService', function() { it('should export and import single notes', asyncTest(async () => { const service = new InteropService(); const filePath = `${exportDir()}/test.jex`; - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); await service.export({ path: filePath, sourceNoteIds: [note1.id] }); @@ -229,15 +229,15 @@ describe('services_InteropService', function() { expect(await Note.count()).toBe(1); expect(await Folder.count()).toBe(1); - let folder2 = (await Folder.all())[0]; + const folder2 = (await Folder.all())[0]; expect(folder2.title).toBe('test'); })); it('should export and import single folders', asyncTest(async () => { const service = new InteropService(); const filePath = `${exportDir()}/test.jex`; - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); await service.export({ path: filePath, sourceFolderIds: [folder1.id] }); @@ -249,7 +249,7 @@ describe('services_InteropService', function() { expect(await Note.count()).toBe(1); expect(await Folder.count()).toBe(1); - let folder2 = (await Folder.all())[0]; + const folder2 = (await Folder.all())[0]; expect(folder2.title).toBe('folder1'); })); @@ -257,11 +257,11 @@ describe('services_InteropService', function() { const service = new InteropService(); 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 }); - let folder4 = await Folder.save({ title: 'folder4', parent_id: folder2.id }); - let note1 = await Note.save({ title: 'ma note', parent_id: folder4.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const folder2 = await Folder.save({ title: 'folder2', parent_id: folder1.id }); + const folder3 = await Folder.save({ title: 'folder3', parent_id: folder2.id }); + const folder4 = await Folder.save({ title: 'folder4', parent_id: folder2.id }); + const note1 = await Note.save({ title: 'ma note', parent_id: folder4.id }); await service.export({ path: filePath, sourceFolderIds: [folder1.id] }); @@ -276,11 +276,11 @@ describe('services_InteropService', function() { expect(await Note.count()).toBe(1); expect(await Folder.count()).toBe(4); - let folder1_2 = await Folder.loadByTitle('folder1'); - let folder2_2 = await Folder.loadByTitle('folder2'); - let folder3_2 = await Folder.loadByTitle('folder3'); - let folder4_2 = await Folder.loadByTitle('folder4'); - let note1_2 = await Note.loadByTitle('ma note'); + const folder1_2 = await Folder.loadByTitle('folder1'); + const folder2_2 = await Folder.loadByTitle('folder2'); + const folder3_2 = await Folder.loadByTitle('folder3'); + const folder4_2 = await Folder.loadByTitle('folder4'); + const note1_2 = await Note.loadByTitle('ma note'); expect(folder2_2.parent_id).toBe(folder1_2.id); expect(folder3_2.parent_id).toBe(folder2_2.id); @@ -291,9 +291,9 @@ describe('services_InteropService', function() { it('should export and import links to notes', asyncTest(async () => { const service = new InteropService(); 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 }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); + const 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] }); @@ -306,15 +306,15 @@ describe('services_InteropService', function() { expect(await Note.count()).toBe(2); expect(await Folder.count()).toBe(1); - let note1_2 = await Note.loadByTitle('ma note'); - let note2_2 = await Note.loadByTitle('ma deuxième note'); + const note1_2 = await Note.loadByTitle('ma note'); + const note2_2 = await Note.loadByTitle('ma deuxième note'); expect(note2_2.body.indexOf(note1_2.id) >= 0).toBe(true); })); it('should export into json format', asyncTest(async () => { const service = new InteropService(); - let folder1 = await Folder.save({ title: 'folder1' }); + const 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(); @@ -325,8 +325,8 @@ describe('services_InteropService', function() { const items = [folder1, note1]; for (let i = 0; i < items.length; i++) { const jsonFile = `${filePath}/${items[i].id}.json`; - let json = await fs.readFile(jsonFile, 'utf-8'); - let obj = JSON.parse(json); + const json = await fs.readFile(jsonFile, 'utf-8'); + const obj = JSON.parse(json); expect(obj.id).toBe(items[i].id); expect(obj.type_).toBe(items[i].type_); expect(obj.title).toBe(items[i].title); @@ -336,7 +336,7 @@ describe('services_InteropService', function() { it('should export selected notes in md format', asyncTest(async () => { const service = new InteropService(); - let folder1 = await Folder.save({ title: 'folder1' }); + const folder1 = await Folder.save({ title: 'folder1' }); let note11 = await Note.save({ title: 'title note11', parent_id: folder1.id }); note11 = await Note.load(note11.id); let note12 = await Note.save({ title: 'title note12', parent_id: folder1.id }); @@ -365,15 +365,15 @@ describe('services_InteropService', function() { it('should export MD with unicode filenames', asyncTest(async () => { const service = new InteropService(); - let folder1 = await Folder.save({ title: 'folder1' }); - let folder2 = await Folder.save({ title: 'ジョプリン' }); - let note1 = await Note.save({ title: '生活', parent_id: folder1.id }); - let note2 = await Note.save({ title: '生活', parent_id: folder1.id }); - let note2b = await Note.save({ title: '生活', parent_id: folder1.id }); - let note3 = await Note.save({ title: '', parent_id: folder1.id }); - let note4 = await Note.save({ title: '', parent_id: folder1.id }); - let note5 = await Note.save({ title: 'salut, ça roule ?', parent_id: folder1.id }); - let note6 = await Note.save({ title: 'ジョプリン', parent_id: folder2.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const folder2 = await Folder.save({ title: 'ジョプリン' }); + const note1 = await Note.save({ title: '生活', parent_id: folder1.id }); + const note2 = await Note.save({ title: '生活', parent_id: folder1.id }); + const note2b = await Note.save({ title: '生活', parent_id: folder1.id }); + const note3 = await Note.save({ title: '', parent_id: folder1.id }); + const note4 = await Note.save({ title: '', parent_id: folder1.id }); + const note5 = await Note.save({ title: 'salut, ça roule ?', parent_id: folder1.id }); + const note6 = await Note.save({ title: 'ジョプリン', parent_id: folder2.id }); const outDir = exportDir(); diff --git a/CliClient/tests/services_InteropService_Exporter_Md.js b/CliClient/tests/services_InteropService_Exporter_Md.js index 2ba5e2caf..5b4ca14d1 100644 --- a/CliClient/tests/services_InteropService_Exporter_Md.js +++ b/CliClient/tests/services_InteropService_Exporter_Md.js @@ -49,9 +49,9 @@ describe('services_InteropService_Exporter_Md', function() { }); }; - let folder1 = await Folder.save({ title: 'folder1' }); + const folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'note1', parent_id: folder1.id }); - let note2 = await Note.save({ title: 'note2', parent_id: folder1.id }); + const note2 = await Note.save({ title: 'note2', parent_id: folder1.id }); await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); note1 = await Note.load(note1.id); queueExportItem(BaseModel.TYPE_FOLDER, folder1.id); @@ -59,7 +59,7 @@ describe('services_InteropService_Exporter_Md', function() { queueExportItem(BaseModel.TYPE_NOTE, note2); queueExportItem(BaseModel.TYPE_RESOURCE, (await Note.linkedResourceIds(note1.body))[0]); - let folder2 = await Folder.save({ title: 'folder2' }); + const folder2 = await Folder.save({ title: 'folder2' }); let note3 = await Note.save({ title: 'note3', parent_id: folder2.id }); await shim.attachFileToNote(note3, `${__dirname}/../tests/support/photo.jpg`); note3 = await Note.load(note3.id); @@ -91,9 +91,9 @@ describe('services_InteropService_Exporter_Md', function() { }); }; - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'note1', parent_id: folder1.id }); - let note1_2 = await Note.save({ title: 'note1', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'note1', parent_id: folder1.id }); + const note1_2 = await Note.save({ title: 'note1', parent_id: folder1.id }); queueExportItem(BaseModel.TYPE_FOLDER, folder1.id); queueExportItem(BaseModel.TYPE_NOTE, note1); queueExportItem(BaseModel.TYPE_NOTE, note1_2); @@ -118,8 +118,8 @@ describe('services_InteropService_Exporter_Md', function() { }); }; - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'note1', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'note1', parent_id: folder1.id }); queueExportItem(BaseModel.TYPE_FOLDER, folder1.id); queueExportItem(BaseModel.TYPE_NOTE, note1); @@ -145,23 +145,23 @@ describe('services_InteropService_Exporter_Md', function() { }); }; - let folder1 = await Folder.save({ title: 'folder1' }); + const folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'note1', parent_id: folder1.id }); await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); note1 = await Note.load(note1.id); queueExportItem(BaseModel.TYPE_FOLDER, folder1.id); queueExportItem(BaseModel.TYPE_NOTE, note1); queueExportItem(BaseModel.TYPE_RESOURCE, (await Note.linkedResourceIds(note1.body))[0]); - let resource1 = await Resource.load(itemsToExport[2].itemOrId); + const resource1 = await Resource.load(itemsToExport[2].itemOrId); - let folder2 = await Folder.save({ title: 'folder2', parent_id: folder1.id }); + const folder2 = await Folder.save({ title: 'folder2', parent_id: folder1.id }); let note2 = await Note.save({ title: 'note2', parent_id: folder2.id }); await shim.attachFileToNote(note2, `${__dirname}/../tests/support/photo.jpg`); note2 = await Note.load(note2.id); queueExportItem(BaseModel.TYPE_FOLDER, folder2.id); queueExportItem(BaseModel.TYPE_NOTE, note2); queueExportItem(BaseModel.TYPE_RESOURCE, (await Note.linkedResourceIds(note2.body))[0]); - let resource2 = await Resource.load(itemsToExport[5].itemOrId); + const resource2 = await Resource.load(itemsToExport[5].itemOrId); await exporter.processResource(resource1, Resource.fullPath(resource1)); await exporter.processResource(resource2, Resource.fullPath(resource2)); @@ -182,13 +182,13 @@ describe('services_InteropService_Exporter_Md', function() { }); }; - let folder1 = await Folder.save({ title: 'folder1' }); + const folder1 = await Folder.save({ title: 'folder1' }); - let folder2 = await Folder.save({ title: 'folder2', parent_id: folder1.id }); - let note2 = await Note.save({ title: 'note2', parent_id: folder2.id }); + const folder2 = await Folder.save({ title: 'folder2', parent_id: folder1.id }); + const note2 = await Note.save({ title: 'note2', parent_id: folder2.id }); queueExportItem(BaseModel.TYPE_NOTE, note2); - let folder3 = await Folder.save({ title: 'folder3', parent_id: folder1.id }); + const folder3 = await Folder.save({ title: 'folder3', parent_id: folder1.id }); queueExportItem(BaseModel.TYPE_FOLDER, folder3.id); await exporter.processItem(Folder, folder2); @@ -213,18 +213,18 @@ describe('services_InteropService_Exporter_Md', function() { }); }; - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'note1', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'note1', parent_id: folder1.id }); queueExportItem(BaseModel.TYPE_FOLDER, folder1.id); queueExportItem(BaseModel.TYPE_NOTE, note1); - let folder2 = await Folder.save({ title: 'folder2', parent_id: folder1.id }); - let note2 = await Note.save({ title: 'note2', parent_id: folder2.id }); + const folder2 = await Folder.save({ title: 'folder2', parent_id: folder1.id }); + const note2 = await Note.save({ title: 'note2', parent_id: folder2.id }); queueExportItem(BaseModel.TYPE_FOLDER, folder2.id); queueExportItem(BaseModel.TYPE_NOTE, note2); - let folder3 = await Folder.save({ title: 'folder3' }); - let note3 = await Note.save({ title: 'note3', parent_id: folder3.id }); + const folder3 = await Folder.save({ title: 'folder3' }); + const note3 = await Note.save({ title: 'note3', parent_id: folder3.id }); queueExportItem(BaseModel.TYPE_FOLDER, folder3.id); queueExportItem(BaseModel.TYPE_NOTE, note3); @@ -250,24 +250,24 @@ describe('services_InteropService_Exporter_Md', function() { }); }; - let folder1 = await Folder.save({ title: 'folder1' }); + const folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'note1', parent_id: folder1.id }); await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); note1 = await Note.load(note1.id); queueExportItem(BaseModel.TYPE_NOTE, note1); - let resource1 = await Resource.load((await Note.linkedResourceIds(note1.body))[0]); + const resource1 = await Resource.load((await Note.linkedResourceIds(note1.body))[0]); - let folder2 = await Folder.save({ title: 'folder2', parent_id: folder1.id }); + const folder2 = await Folder.save({ title: 'folder2', parent_id: folder1.id }); let note2 = await Note.save({ title: 'note2', parent_id: folder2.id }); await shim.attachFileToNote(note2, `${__dirname}/../tests/support/photo.jpg`); note2 = await Note.load(note2.id); queueExportItem(BaseModel.TYPE_NOTE, note2); - let resource2 = await Resource.load((await Note.linkedResourceIds(note2.body))[0]); + const resource2 = await Resource.load((await Note.linkedResourceIds(note2.body))[0]); await exporter.processItem(Folder, folder1); await exporter.processItem(Folder, folder2); await exporter.prepareForProcessingItemType(BaseModel.TYPE_NOTE, itemsToExport); - let context = { + const context = { resourcePaths: {}, }; context.resourcePaths[resource1.id] = 'resource1.jpg'; @@ -276,8 +276,8 @@ describe('services_InteropService_Exporter_Md', function() { await exporter.processItem(Note, note1); await exporter.processItem(Note, note2); - let note1_body = await shim.fsDriver().readFile(`${exportDir}/${exporter.context().notePaths[note1.id]}`); - let note2_body = await shim.fsDriver().readFile(`${exportDir}/${exporter.context().notePaths[note2.id]}`); + const note1_body = await shim.fsDriver().readFile(`${exportDir}/${exporter.context().notePaths[note1.id]}`); + const note2_body = await shim.fsDriver().readFile(`${exportDir}/${exporter.context().notePaths[note2.id]}`); expect(note1_body).toContain('](../_resources/resource1.jpg)', 'Resource id should be replaced with a relative path.'); expect(note2_body).toContain('](../../_resources/resource2.jpg)', 'Resource id should be replaced with a relative path.'); @@ -301,13 +301,13 @@ describe('services_InteropService_Exporter_Md', function() { return await Note.load(note.id); }; - let folder1 = await Folder.save({ title: 'folder1' }); + const folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'note1', parent_id: folder1.id }); - let folder2 = await Folder.save({ title: 'folder2', parent_id: folder1.id }); + const folder2 = await Folder.save({ title: 'folder2', parent_id: folder1.id }); let note2 = await Note.save({ title: 'note2', parent_id: folder2.id }); - let folder3 = await Folder.save({ title: 'folder3' }); + const folder3 = await Folder.save({ title: 'folder3' }); let note3 = await Note.save({ title: 'note3', parent_id: folder3.id }); note1 = await changeNoteBodyAndReload(note1, `# Some text \n\n [A link to note3](:/${note3.id})`); @@ -325,9 +325,9 @@ describe('services_InteropService_Exporter_Md', function() { await exporter.processItem(Note, note2); await exporter.processItem(Note, note3); - let note1_body = await shim.fsDriver().readFile(`${exportDir}/${exporter.context().notePaths[note1.id]}`); - let note2_body = await shim.fsDriver().readFile(`${exportDir}/${exporter.context().notePaths[note2.id]}`); - let note3_body = await shim.fsDriver().readFile(`${exportDir}/${exporter.context().notePaths[note3.id]}`); + const note1_body = await shim.fsDriver().readFile(`${exportDir}/${exporter.context().notePaths[note1.id]}`); + const note2_body = await shim.fsDriver().readFile(`${exportDir}/${exporter.context().notePaths[note2.id]}`); + const note3_body = await shim.fsDriver().readFile(`${exportDir}/${exporter.context().notePaths[note3.id]}`); expect(note1_body).toContain('](../folder3/note3.md)', 'Note id should be replaced with a relative path.'); expect(note2_body).toContain('](../../folder3/note3.md)', 'Resource id should be replaced with a relative path.'); @@ -347,9 +347,9 @@ describe('services_InteropService_Exporter_Md', function() { }); }; - let folder1 = await Folder.save({ title: 'folder with space1' }); - let note1 = await Note.save({ title: 'note1 name with space', parent_id: folder1.id }); - let note2 = await Note.save({ title: 'note2', parent_id: folder1.id, body: `[link](:/${note1.id})` }); + const folder1 = await Folder.save({ title: 'folder with space1' }); + const note1 = await Note.save({ title: 'note1 name with space', parent_id: folder1.id }); + const note2 = await Note.save({ title: 'note2', parent_id: folder1.id, body: `[link](:/${note1.id})` }); queueExportItem(BaseModel.TYPE_NOTE, note1); queueExportItem(BaseModel.TYPE_NOTE, note2); @@ -358,7 +358,7 @@ describe('services_InteropService_Exporter_Md', function() { await exporter.processItem(Note, note1); await exporter.processItem(Note, note2); - let note2_body = await shim.fsDriver().readFile(`${exportDir}/${exporter.context().notePaths[note2.id]}`); + const note2_body = await shim.fsDriver().readFile(`${exportDir}/${exporter.context().notePaths[note2.id]}`); expect(note2_body).toContain('[link](../folder%20with%20space1/note1%20name%20with%20space.md)', 'Whitespace in URL should be encoded'); })); }); diff --git a/CliClient/tests/services_ResourceService.js b/CliClient/tests/services_ResourceService.js index 94b5d5e6e..b9ed02b76 100644 --- a/CliClient/tests/services_ResourceService.js +++ b/CliClient/tests/services_ResourceService.js @@ -48,10 +48,10 @@ describe('services_ResourceService', function() { it('should delete orphaned resources', asyncTest(async () => { const service = new ResourceService(); - let folder1 = await Folder.save({ title: 'folder1' }); + const 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`); - let resource1 = (await Resource.all())[0]; + const resource1 = (await Resource.all())[0]; const resourcePath = Resource.fullPath(resource1); await service.indexNoteResources(); @@ -79,11 +79,11 @@ describe('services_ResourceService', function() { it('should not delete resource if still associated with at least one note', asyncTest(async () => { const service = new ResourceService(); - let folder1 = await Folder.save({ title: 'folder1' }); + const 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 }); + const note2 = await Note.save({ title: 'ma deuxième note', parent_id: folder1.id }); note1 = await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); - let resource1 = (await Resource.all())[0]; + const resource1 = (await Resource.all())[0]; await service.indexNoteResources(); @@ -113,10 +113,10 @@ describe('services_ResourceService', function() { it('should not delete resource if it is used in an IMG tag', asyncTest(async () => { const service = new ResourceService(); - let folder1 = await Folder.save({ title: 'folder1' }); + const 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`); - let resource1 = (await Resource.all())[0]; + const resource1 = (await Resource.all())[0]; await service.indexNoteResources(); @@ -132,10 +132,10 @@ describe('services_ResourceService', function() { it('should not process twice the same change', asyncTest(async () => { const service = new ResourceService(); - let folder1 = await Folder.save({ title: 'folder1' }); + const 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`); - let resource1 = (await Resource.all())[0]; + const resource1 = (await Resource.all())[0]; await service.indexNoteResources(); @@ -169,8 +169,8 @@ describe('services_ResourceService', function() { const masterKey = await loadEncryptionMasterKey(); await encryptionService().enableEncryption(masterKey, '123456'); await encryptionService().loadMasterKeysFromSettings(); - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); // R1 await resourceService().indexNoteResources(); await synchronizer().start(); @@ -199,7 +199,7 @@ describe('services_ResourceService', function() { it('should double-check if the resource is still linked before deleting it', asyncTest(async () => { SearchEngine.instance().setDb(db()); // /!\ Note that we use the global search engine here, which we shouldn't but will work for now - let folder1 = await Folder.save({ title: 'folder1' }); + const 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`); await resourceService().indexNoteResources(); diff --git a/CliClient/tests/services_SearchEngine.js b/CliClient/tests/services_SearchEngine.js index ec3da9222..5d2fa6256 100644 --- a/CliClient/tests/services_SearchEngine.js +++ b/CliClient/tests/services_SearchEngine.js @@ -1,4 +1,5 @@ /* eslint-disable no-unused-vars */ +/* eslint prefer-const: 0*/ require('app-module-path').addPath(__dirname); diff --git a/CliClient/tests/services_rest_Api.js b/CliClient/tests/services_rest_Api.js index 4e7b2414a..8a16ccc93 100644 --- a/CliClient/tests/services_rest_Api.js +++ b/CliClient/tests/services_rest_Api.js @@ -37,26 +37,26 @@ describe('services_rest_Api', function() { })); it('should get folders', asyncTest(async () => { - let f1 = await Folder.save({ title: 'mon carnet' }); + const f1 = await Folder.save({ title: 'mon carnet' }); const response = await api.route('GET', 'folders'); expect(response.length).toBe(1); })); it('should update folders', asyncTest(async () => { - let f1 = await Folder.save({ title: 'mon carnet' }); + const f1 = await Folder.save({ title: 'mon carnet' }); const response = await api.route('PUT', `folders/${f1.id}`, null, JSON.stringify({ title: 'modifié', })); - let f1b = await Folder.load(f1.id); + const f1b = await Folder.load(f1.id); expect(f1b.title).toBe('modifié'); })); it('should delete folders', asyncTest(async () => { - let f1 = await Folder.save({ title: 'mon carnet' }); + const f1 = await Folder.save({ title: 'mon carnet' }); await api.route('DELETE', `folders/${f1.id}`); - let f1b = await Folder.load(f1.id); + const f1b = await Folder.load(f1.id); expect(!f1b).toBe(true); })); @@ -67,13 +67,13 @@ describe('services_rest_Api', function() { expect(!!response.id).toBe(true); - let f = await Folder.all(); + const f = await Folder.all(); expect(f.length).toBe(1); expect(f[0].title).toBe('from api'); })); it('should get one folder', asyncTest(async () => { - let f1 = await Folder.save({ title: 'mon carnet' }); + const f1 = await Folder.save({ title: 'mon carnet' }); const response = await api.route('GET', `folders/${f1.id}`); expect(response.id).toBe(f1.id); @@ -82,7 +82,7 @@ describe('services_rest_Api', function() { })); it('should get the folder notes', asyncTest(async () => { - let f1 = await Folder.save({ title: 'mon carnet' }); + const f1 = await Folder.save({ title: 'mon carnet' }); const response2 = await api.route('GET', `folders/${f1.id}/notes`); expect(response2.length).toBe(0); diff --git a/CliClient/tests/synchronizer.js b/CliClient/tests/synchronizer.js index 7ff36e263..a39e4e8ca 100644 --- a/CliClient/tests/synchronizer.js +++ b/CliClient/tests/synchronizer.js @@ -27,8 +27,8 @@ process.on('unhandledRejection', (reason, p) => { jasmine.DEFAULT_TIMEOUT_INTERVAL = 60000 + 30000; // The first test is slow because the database needs to be built async function allNotesFolders() { - let folders = await Folder.all(); - let notes = await Note.all(); + const folders = await Folder.all(); + const notes = await Note.all(); return folders.concat(notes); } @@ -66,9 +66,9 @@ async function localNotesFoldersSameAsRemote(locals, expect) { expect(locals.length).toBe(nf.length); for (let i = 0; i < locals.length; i++) { - let dbItem = locals[i]; - let path = BaseItem.systemPath(dbItem); - let remote = await fileApi().stat(path); + const dbItem = locals[i]; + const path = BaseItem.systemPath(dbItem); + const remote = await fileApi().stat(path); expect(!!remote).toBe(true); if (!remote) continue; @@ -101,10 +101,10 @@ describe('synchronizer', function() { }); it('should create remote items', asyncTest(async () => { - let folder = await Folder.save({ title: 'folder1' }); + const folder = await Folder.save({ title: 'folder1' }); await Note.save({ title: 'un', parent_id: folder.id }); - let all = await allNotesFolders(); + const all = await allNotesFolders(); await synchronizer().start(); @@ -112,20 +112,20 @@ describe('synchronizer', function() { })); it('should update remote items', asyncTest(async () => { - let folder = await Folder.save({ title: 'folder1' }); - let note = await Note.save({ title: 'un', parent_id: folder.id }); + const folder = await Folder.save({ title: 'folder1' }); + const note = await Note.save({ title: 'un', parent_id: folder.id }); await synchronizer().start(); await Note.save({ title: 'un UPDATE', id: note.id }); - let all = await allNotesFolders(); + const all = await allNotesFolders(); await synchronizer().start(); await localNotesFoldersSameAsRemote(all, expect); })); it('should create local items', asyncTest(async () => { - let folder = await Folder.save({ title: 'folder1' }); + const folder = await Folder.save({ title: 'folder1' }); await Note.save({ title: 'un', parent_id: folder.id }); await synchronizer().start(); @@ -133,14 +133,14 @@ describe('synchronizer', function() { await synchronizer().start(); - let all = await allNotesFolders(); + const all = await allNotesFolders(); await localNotesFoldersSameAsRemote(all, expect); })); it('should update local items', asyncTest(async () => { - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'un', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'un', parent_id: folder1.id }); await synchronizer().start(); await switchClient(2); @@ -160,14 +160,14 @@ describe('synchronizer', function() { await synchronizer().start(); - let all = await allNotesFolders(); + const all = await allNotesFolders(); await localNotesFoldersSameAsRemote(all, expect); })); it('should resolve note conflicts', asyncTest(async () => { - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'un', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'un', parent_id: folder1.id }); await synchronizer().start(); await switchClient(2); @@ -186,29 +186,29 @@ describe('synchronizer', function() { await Note.save(note2conf); note2conf = await Note.load(note1.id); await synchronizer().start(); - let conflictedNotes = await Note.conflictedNotes(); + const conflictedNotes = await Note.conflictedNotes(); expect(conflictedNotes.length).toBe(1); // Other than the id (since the conflicted note is a duplicate), and the is_conflict property // the conflicted and original note must be the same in every way, to make sure no data has been lost. - let conflictedNote = conflictedNotes[0]; + const conflictedNote = conflictedNotes[0]; expect(conflictedNote.id == note2conf.id).toBe(false); - for (let n in conflictedNote) { + for (const n in conflictedNote) { if (!conflictedNote.hasOwnProperty(n)) continue; if (n == 'id' || n == 'is_conflict') continue; expect(conflictedNote[n]).toBe(note2conf[n], `Property: ${n}`); } - let noteUpdatedFromRemote = await Note.load(note1.id); - for (let n in noteUpdatedFromRemote) { + const noteUpdatedFromRemote = await Note.load(note1.id); + for (const n in noteUpdatedFromRemote) { if (!noteUpdatedFromRemote.hasOwnProperty(n)) continue; expect(noteUpdatedFromRemote[n]).toBe(note2[n], `Property: ${n}`); } })); it('should resolve folders conflicts', asyncTest(async () => { - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'un', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'un', parent_id: folder1.id }); await synchronizer().start(); await switchClient(2); // ---------------------------------- @@ -235,13 +235,13 @@ describe('synchronizer', function() { await synchronizer().start(); - let folder1_final = await Folder.load(folder1.id); + const folder1_final = await Folder.load(folder1.id); expect(folder1_final.title).toBe(folder1_modRemote.title); })); it('should delete remote notes', asyncTest(async () => { - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'un', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'un', parent_id: folder1.id }); await synchronizer().start(); await switchClient(2); @@ -258,13 +258,13 @@ describe('synchronizer', function() { expect(remotes.length).toBe(1); expect(remotes[0].id).toBe(folder1.id); - let deletedItems = await BaseItem.deletedItems(syncTargetId()); + const deletedItems = await BaseItem.deletedItems(syncTargetId()); expect(deletedItems.length).toBe(0); })); it('should not created deleted_items entries for items deleted via sync', asyncTest(async () => { - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'un', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'un', parent_id: folder1.id }); await synchronizer().start(); await switchClient(2); @@ -276,7 +276,7 @@ describe('synchronizer', function() { await switchClient(1); await synchronizer().start(); - let deletedItems = await BaseItem.deletedItems(syncTargetId()); + const deletedItems = await BaseItem.deletedItems(syncTargetId()); expect(deletedItems.length).toBe(0); })); @@ -285,9 +285,9 @@ describe('synchronizer', function() { // property of the basicDelta() function is cleared properly at the end of a sync operation. If it is not cleared // it means items will no longer be deleted locally via sync. - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'un', parent_id: folder1.id }); - let note2 = await Note.save({ title: 'deux', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'un', parent_id: folder1.id }); + const note2 = await Note.save({ title: 'deux', parent_id: folder1.id }); let context1 = await synchronizer().start(); await switchClient(2); @@ -299,17 +299,17 @@ describe('synchronizer', function() { await switchClient(1); context1 = await synchronizer().start({ context: context1 }); - let items = await allNotesFolders(); + const items = await allNotesFolders(); expect(items.length).toBe(2); - let deletedItems = await BaseItem.deletedItems(syncTargetId()); + const deletedItems = await BaseItem.deletedItems(syncTargetId()); expect(deletedItems.length).toBe(0); await Note.delete(note2.id); context1 = await synchronizer().start({ context: context1 }); })); it('should delete remote folder', asyncTest(async () => { - let folder1 = await Folder.save({ title: 'folder1' }); - let folder2 = await Folder.save({ title: 'folder2' }); + const folder1 = await Folder.save({ title: 'folder1' }); + const folder2 = await Folder.save({ title: 'folder2' }); await synchronizer().start(); await switchClient(2); @@ -322,30 +322,30 @@ describe('synchronizer', function() { await synchronizer().start(); - let all = await allNotesFolders(); + const all = await allNotesFolders(); await localNotesFoldersSameAsRemote(all, expect); })); it('should delete local folder', asyncTest(async () => { - let folder1 = await Folder.save({ title: 'folder1' }); - let folder2 = await Folder.save({ title: 'folder2' }); - let context1 = await synchronizer().start(); + const folder1 = await Folder.save({ title: 'folder1' }); + const folder2 = await Folder.save({ title: 'folder2' }); + const context1 = await synchronizer().start(); await switchClient(2); - let context2 = await synchronizer().start(); + const context2 = await synchronizer().start(); await Folder.delete(folder2.id); await synchronizer().start({ context: context2 }); await switchClient(1); await synchronizer().start({ context: context1 }); - let items = await allNotesFolders(); + const items = await allNotesFolders(); await localNotesFoldersSameAsRemote(items, expect); })); it('should resolve conflict if remote folder has been deleted, but note has been added to folder locally', asyncTest(async () => { - let folder1 = await Folder.save({ title: 'folder1' }); + const folder1 = await Folder.save({ title: 'folder1' }); await synchronizer().start(); await switchClient(2); @@ -356,17 +356,17 @@ describe('synchronizer', function() { await switchClient(1); - let note = await Note.save({ title: 'note1', parent_id: folder1.id }); + const note = await Note.save({ title: 'note1', parent_id: folder1.id }); await synchronizer().start(); - let items = await allNotesFolders(); + const items = await allNotesFolders(); expect(items.length).toBe(1); expect(items[0].title).toBe('note1'); expect(items[0].is_conflict).toBe(1); })); it('should resolve conflict if note has been deleted remotely and locally', asyncTest(async () => { - let folder = await Folder.save({ title: 'folder' }); - let note = await Note.save({ title: 'note', parent_id: folder.title }); + const folder = await Folder.save({ title: 'folder' }); + const note = await Note.save({ title: 'note', parent_id: folder.title }); await synchronizer().start(); await switchClient(2); @@ -380,7 +380,7 @@ describe('synchronizer', function() { await Note.delete(note.id); await synchronizer().start(); - let items = await allNotesFolders(); + const items = await allNotesFolders(); expect(items.length).toBe(1); expect(items[0].title).toBe('folder'); @@ -391,8 +391,8 @@ describe('synchronizer', function() { // If client1 and 2 have two folders, client 1 deletes item 1 and client // 2 deletes item 2, they should both end up with no items after sync. - let folder1 = await Folder.save({ title: 'folder1' }); - let folder2 = await Folder.save({ title: 'folder2' }); + const folder1 = await Folder.save({ title: 'folder1' }); + const folder2 = await Folder.save({ title: 'folder2' }); await synchronizer().start(); await switchClient(2); @@ -413,21 +413,21 @@ describe('synchronizer', function() { await synchronizer().start(); - let items2 = await allNotesFolders(); + const items2 = await allNotesFolders(); await switchClient(1); await synchronizer().start(); - let items1 = await allNotesFolders(); + const items1 = await allNotesFolders(); expect(items1.length).toBe(0); expect(items1.length).toBe(items2.length); })); it('should handle conflict when remote note is deleted then local note is modified', asyncTest(async () => { - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'un', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'un', parent_id: folder1.id }); await synchronizer().start(); await switchClient(2); @@ -442,25 +442,25 @@ describe('synchronizer', function() { await switchClient(1); - let newTitle = 'Modified after having been deleted'; + const newTitle = 'Modified after having been deleted'; await Note.save({ id: note1.id, title: newTitle }); await synchronizer().start(); - let conflictedNotes = await Note.conflictedNotes(); + const conflictedNotes = await Note.conflictedNotes(); expect(conflictedNotes.length).toBe(1); expect(conflictedNotes[0].title).toBe(newTitle); - let unconflictedNotes = await Note.unconflictedNotes(); + const unconflictedNotes = await Note.unconflictedNotes(); expect(unconflictedNotes.length).toBe(0); })); it('should handle conflict when remote folder is deleted then local folder is renamed', asyncTest(async () => { - let folder1 = await Folder.save({ title: 'folder1' }); - let folder2 = await Folder.save({ title: 'folder2' }); - let note1 = await Note.save({ title: 'un', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const folder2 = await Folder.save({ title: 'folder2' }); + const note1 = await Note.save({ title: 'un', parent_id: folder1.id }); await synchronizer().start(); await switchClient(2); @@ -477,18 +477,18 @@ describe('synchronizer', function() { await sleep(0.1); - let newTitle = 'Modified after having been deleted'; + const newTitle = 'Modified after having been deleted'; await Folder.save({ id: folder1.id, title: newTitle }); await synchronizer().start(); - let items = await allNotesFolders(); + const items = await allNotesFolders(); expect(items.length).toBe(1); })); it('should allow duplicate folder titles', asyncTest(async () => { - let localF1 = await Folder.save({ title: 'folder' }); + const localF1 = await Folder.save({ title: 'folder' }); await switchClient(2); @@ -501,7 +501,7 @@ describe('synchronizer', function() { await synchronizer().start(); - let localF2 = await Folder.load(remoteF2.id); + const localF2 = await Folder.load(remoteF2.id); expect(localF2.title == remoteF2.title).toBe(true); @@ -528,10 +528,10 @@ describe('synchronizer', function() { masterKey = await loadEncryptionMasterKey(); } - let f1 = await Folder.save({ title: 'folder' }); - let n1 = await Note.save({ title: 'mynote' }); - let n2 = await Note.save({ title: 'mynote2' }); - let tag = await Tag.save({ title: 'mytag' }); + const f1 = await Folder.save({ title: 'folder' }); + const n1 = await Note.save({ title: 'mynote' }); + const n2 = await Note.save({ title: 'mynote2' }); + const tag = await Tag.save({ title: 'mytag' }); let context1 = await synchronizer().start(); await switchClient(2); @@ -540,10 +540,10 @@ describe('synchronizer', function() { if (withEncryption) { const masterKey_2 = await MasterKey.load(masterKey.id); await encryptionService().loadMasterKey_(masterKey_2, '123456', true); - let t = await Tag.load(tag.id); + const t = await Tag.load(tag.id); await Tag.decrypt(t); } - let remoteTag = await Tag.loadByTitle(tag.title); + const remoteTag = await Tag.loadByTitle(tag.title); expect(!!remoteTag).toBe(true); expect(remoteTag.id).toBe(tag.id); await Tag.addNote(remoteTag.id, n1.id); @@ -579,22 +579,22 @@ describe('synchronizer', function() { })); it('should not sync notes with conflicts', asyncTest(async () => { - let f1 = await Folder.save({ title: 'folder' }); - let n1 = await Note.save({ title: 'mynote', parent_id: f1.id, is_conflict: 1 }); + const f1 = await Folder.save({ title: 'folder' }); + const n1 = await Note.save({ title: 'mynote', parent_id: f1.id, is_conflict: 1 }); await synchronizer().start(); await switchClient(2); await synchronizer().start(); - let notes = await Note.all(); - let folders = await Folder.all(); + const notes = await Note.all(); + const folders = await Folder.all(); expect(notes.length).toBe(0); expect(folders.length).toBe(1); })); it('should not try to delete on remote conflicted notes that have been deleted', asyncTest(async () => { - let f1 = await Folder.save({ title: 'folder' }); - let n1 = await Note.save({ title: 'mynote', parent_id: f1.id }); + const f1 = await Folder.save({ title: 'folder' }); + const n1 = await Note.save({ title: 'mynote', parent_id: f1.id }); await synchronizer().start(); await switchClient(2); @@ -613,8 +613,8 @@ describe('synchronizer', function() { await loadEncryptionMasterKey(); } - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'un', is_todo: 1, parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'un', is_todo: 1, parent_id: folder1.id }); await synchronizer().start(); await switchClient(2); @@ -625,7 +625,7 @@ describe('synchronizer', function() { await decryptionWorker().start(); } let note2 = await Note.load(note1.id); - note2.todo_completed = time.unixMs()-1; + note2.todo_completed = time.unixMs() - 1; await Note.save(note2); note2 = await Note.load(note2.id); await synchronizer().start(); @@ -646,10 +646,10 @@ describe('synchronizer', function() { // but in practice it doesn't matter, we can just take the date when the // todo was marked as "done" the first time. - let conflictedNotes = await Note.conflictedNotes(); + const conflictedNotes = await Note.conflictedNotes(); expect(conflictedNotes.length).toBe(0); - let notes = await Note.all(); + const notes = await Note.all(); expect(notes.length).toBe(1); expect(notes[0].id).toBe(note1.id); expect(notes[0].todo_completed).toBe(note2.todo_completed); @@ -658,10 +658,10 @@ describe('synchronizer', function() { // smart conflict resolving since we don't know the content, so in that // case it's handled as a regular conflict. - let conflictedNotes = await Note.conflictedNotes(); + const conflictedNotes = await Note.conflictedNotes(); expect(conflictedNotes.length).toBe(1); - let notes = await Note.all(); + const notes = await Note.all(); expect(notes.length).toBe(2); } } @@ -675,14 +675,14 @@ describe('synchronizer', function() { })); it('items should be downloaded again when user cancels in the middle of delta operation', asyncTest(async () => { - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'un', is_todo: 1, parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'un', is_todo: 1, parent_id: folder1.id }); await synchronizer().start(); await switchClient(2); synchronizer().testingHooks_ = ['cancelDeltaLoop2']; - let context = await synchronizer().start(); + const context = await synchronizer().start(); let notes = await Note.all(); expect(notes.length).toBe(0); @@ -693,8 +693,8 @@ describe('synchronizer', function() { })); it('should skip items that cannot be synced', asyncTest(async () => { - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'un', is_todo: 1, parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'un', is_todo: 1, parent_id: folder1.id }); const noteId = note1.id; await synchronizer().start(); let disabledItems = await BaseItem.syncDisabledItems(syncTargetId()); @@ -708,7 +708,7 @@ describe('synchronizer', function() { await switchClient(2); await synchronizer().start(); - let notes = await Note.all(); + const notes = await Note.all(); expect(notes.length).toBe(1); expect(notes[0].title).toBe('un'); @@ -721,7 +721,7 @@ describe('synchronizer', function() { it('notes and folders should get encrypted when encryption is enabled', asyncTest(async () => { Setting.setValue('encryption.enabled', true); const masterKey = await loadEncryptionMasterKey(); - let folder1 = await Folder.save({ title: 'folder1' }); + const folder1 = await Folder.save({ title: 'folder1' }); let note1 = await Note.save({ title: 'un', body: 'to be encrypted', parent_id: folder1.id }); await synchronizer().start(); // After synchronisation, remote items should be encrypted but local ones remain plain text @@ -733,7 +733,7 @@ describe('synchronizer', function() { await synchronizer().start(); let folder1_2 = await Folder.load(folder1.id); let note1_2 = await Note.load(note1.id); - let masterKey_2 = await MasterKey.load(masterKey.id); + const masterKey_2 = await MasterKey.load(masterKey.id); // On this side however it should be received encrypted expect(!note1_2.title).toBe(true); expect(!folder1_2.title).toBe(true); @@ -820,7 +820,7 @@ describe('synchronizer', function() { it('should encrypt existing notes too when enabling E2EE', asyncTest(async () => { // First create a folder, without encryption enabled, and sync it - let folder1 = await Folder.save({ title: 'folder1' }); + const folder1 = await Folder.save({ title: 'folder1' }); await synchronizer().start(); let files = await fileApi().list(); let content = await fileApi().get(files.items[0].path); @@ -848,18 +848,18 @@ describe('synchronizer', function() { it('should sync resources', asyncTest(async () => { while (insideBeforeEach) await time.msleep(500); - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); - let resource1 = (await Resource.all())[0]; - let resourcePath1 = Resource.fullPath(resource1); + const resource1 = (await Resource.all())[0]; + const resourcePath1 = Resource.fullPath(resource1); await synchronizer().start(); expect((await remoteNotesFoldersResources()).length).toBe(3); await switchClient(2); await synchronizer().start(); - let allResources = await Resource.all(); + const allResources = await Resource.all(); expect(allResources.length).toBe(1); let resource1_2 = allResources[0]; let ls = await Resource.localState(resource1_2); @@ -874,18 +874,18 @@ describe('synchronizer', function() { ls = await Resource.localState(resource1_2); expect(ls.fetch_status).toBe(Resource.FETCH_STATUS_DONE); - let resourcePath1_2 = Resource.fullPath(resource1_2); + const resourcePath1_2 = Resource.fullPath(resource1_2); expect(fileContentEqual(resourcePath1, resourcePath1_2)).toBe(true); })); it('should handle resource download errors', asyncTest(async () => { while (insideBeforeEach) await time.msleep(500); - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); let resource1 = (await Resource.all())[0]; - let resourcePath1 = Resource.fullPath(resource1); + const resourcePath1 = Resource.fullPath(resource1); await synchronizer().start(); await switchClient(2); @@ -902,7 +902,7 @@ describe('synchronizer', function() { await fetcher.waitForAllFinished(); resource1 = await Resource.load(resource1.id); - let ls = await Resource.localState(resource1); + const ls = await Resource.localState(resource1); expect(ls.fetch_status).toBe(Resource.FETCH_STATUS_ERROR); expect(ls.fetch_error).toBe('did not work'); })); @@ -910,8 +910,8 @@ describe('synchronizer', function() { it('should set the resource file size if it is missing', asyncTest(async () => { while (insideBeforeEach) await time.msleep(500); - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); await synchronizer().start(); @@ -933,11 +933,11 @@ describe('synchronizer', function() { it('should delete resources', asyncTest(async () => { while (insideBeforeEach) await time.msleep(500); - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); - let resource1 = (await Resource.all())[0]; - let resourcePath1 = Resource.fullPath(resource1); + const resource1 = (await Resource.all())[0]; + const resourcePath1 = Resource.fullPath(resource1); await synchronizer().start(); await switchClient(2); @@ -945,7 +945,7 @@ describe('synchronizer', function() { await synchronizer().start(); let allResources = await Resource.all(); expect(allResources.length).toBe(1); - let all = await fileApi().list(); + const all = await fileApi().list(); expect((await remoteNotesFoldersResources()).length).toBe(3); await Resource.delete(resource1.id); await synchronizer().start(); @@ -967,11 +967,11 @@ describe('synchronizer', function() { Setting.setValue('encryption.enabled', true); const masterKey = await loadEncryptionMasterKey(); - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); - let resource1 = (await Resource.all())[0]; - let resourcePath1 = Resource.fullPath(resource1); + const resource1 = (await Resource.all())[0]; + const resourcePath1 = Resource.fullPath(resource1); await synchronizer().start(); await switchClient(2); @@ -986,7 +986,7 @@ describe('synchronizer', function() { let resource1_2 = (await Resource.all())[0]; resource1_2 = await Resource.decrypt(resource1_2); - let resourcePath1_2 = Resource.fullPath(resource1_2); + const resourcePath1_2 = Resource.fullPath(resource1_2); expect(fileContentEqual(resourcePath1, resourcePath1_2)).toBe(true); })); @@ -995,7 +995,7 @@ describe('synchronizer', function() { Setting.setValue('encryption.enabled', true); const masterKey = await loadEncryptionMasterKey(); - let folder1 = await Folder.save({ title: 'folder1' }); + const folder1 = await Folder.save({ title: 'folder1' }); await synchronizer().start(); let allEncrypted = await allSyncTargetItemsEncrypted(); @@ -1016,7 +1016,7 @@ describe('synchronizer', function() { Setting.setValue('encryption.enabled', true); const masterKey = await loadEncryptionMasterKey(); - let folder1 = await Folder.save({ title: 'folder1' }); + const folder1 = await Folder.save({ title: 'folder1' }); await synchronizer().start(); await switchClient(2); @@ -1049,12 +1049,12 @@ describe('synchronizer', function() { Setting.setValue('encryption.enabled', true); const masterKey = await loadEncryptionMasterKey(); - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); - let resource1 = (await Resource.all())[0]; + const resource1 = (await Resource.all())[0]; await Resource.setFileSizeOnly(resource1.id, -1); - let resourcePath1 = Resource.fullPath(resource1); + const resourcePath1 = Resource.fullPath(resource1); await synchronizer().start(); await switchClient(2); @@ -1075,8 +1075,8 @@ describe('synchronizer', function() { it('should encrypt remote resources after encryption has been enabled', asyncTest(async () => { while (insideBeforeEach) await time.msleep(100); - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); await synchronizer().start(); @@ -1094,22 +1094,22 @@ describe('synchronizer', function() { it('should upload encrypted resource, but it should not mark the blob as encrypted locally', asyncTest(async () => { while (insideBeforeEach) await time.msleep(100); - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'ma note', parent_id: folder1.id }); await shim.attachFileToNote(note1, `${__dirname}/../tests/support/photo.jpg`); const masterKey = await loadEncryptionMasterKey(); await encryptionService().enableEncryption(masterKey, '123456'); await encryptionService().loadMasterKeysFromSettings(); await synchronizer().start(); - let resource1 = (await Resource.all())[0]; + const resource1 = (await Resource.all())[0]; expect(resource1.encryption_blob_encrypted).toBe(0); })); it('should create remote items with UTF-8 content', asyncTest(async () => { - let folder = await Folder.save({ title: 'Fahrräder' }); + const folder = await Folder.save({ title: 'Fahrräder' }); await Note.save({ title: 'Fahrräder', body: 'Fahrräder', parent_id: folder.id }); - let all = await allNotesFolders(); + const all = await allNotesFolders(); await synchronizer().start(); @@ -1117,8 +1117,8 @@ describe('synchronizer', function() { })); it('should update remote items but not pull remote changes', asyncTest(async () => { - let folder = await Folder.save({ title: 'folder1' }); - let note = await Note.save({ title: 'un', parent_id: folder.id }); + const folder = await Folder.save({ title: 'folder1' }); + const note = await Note.save({ title: 'un', parent_id: folder.id }); await synchronizer().start(); await switchClient(2); @@ -1131,13 +1131,13 @@ describe('synchronizer', function() { await Note.save({ title: 'un UPDATE', id: note.id }); await synchronizer().start({ syncSteps: ['update_remote'] }); - let all = await allNotesFolders(); + const all = await allNotesFolders(); expect(all.length).toBe(2); await switchClient(2); await synchronizer().start(); - let note2 = await Note.load(note.id); + const note2 = await Note.load(note.id); expect(note2.title).toBe('un UPDATE'); })); @@ -1544,8 +1544,8 @@ describe('synchronizer', function() { Setting.setValue('encryption.enabled', true); await loadEncryptionMasterKey(); - let folder1 = await Folder.save({ title: 'folder1' }); - let note1 = await Note.save({ title: 'un', parent_id: folder1.id }); + const folder1 = await Folder.save({ title: 'folder1' }); + const note1 = await Note.save({ title: 'un', parent_id: folder1.id }); let note2 = await Note.save({ title: 'deux', parent_id: folder1.id }); await synchronizer().start(); @@ -1570,12 +1570,12 @@ describe('synchronizer', function() { await synchronizer().start(); // The shared note should be decrypted - let note2_2 = await Note.load(note2.id); + const note2_2 = await Note.load(note2.id); expect(note2_2.title).toBe('deux'); expect(note2_2.is_shared).toBe(1); // The non-shared note should be encrypted - let note1_2 = await Note.load(note1.id); + const note1_2 = await Note.load(note1.id); expect(note1_2.title).toBe(''); })); diff --git a/CliClient/tests/test-utils.js b/CliClient/tests/test-utils.js index 809a802c6..5b70f86c4 100644 --- a/CliClient/tests/test-utils.js +++ b/CliClient/tests/test-utils.js @@ -3,7 +3,7 @@ const fs = require('fs-extra'); const { JoplinDatabase } = require('lib/joplin-database.js'); const { DatabaseDriverNode } = require('lib/database-driver-node.js'); -const { BaseApplication }= require('lib/BaseApplication.js'); +const { BaseApplication } = require('lib/BaseApplication.js'); const BaseModel = require('lib/BaseModel.js'); const Folder = require('lib/models/Folder.js'); const Note = require('lib/models/Note.js'); @@ -41,13 +41,13 @@ const KvStore = require('lib/services/KvStore.js'); const WebDavApi = require('lib/WebDavApi'); const DropboxApi = require('lib/DropboxApi'); -let databases_ = []; -let synchronizers_ = []; -let encryptionServices_ = []; -let revisionServices_ = []; -let decryptionWorkers_ = []; -let resourceServices_ = []; -let kvStores_ = []; +const databases_ = []; +const synchronizers_ = []; +const encryptionServices_ = []; +const revisionServices_ = []; +const decryptionWorkers_ = []; +const resourceServices_ = []; +const kvStores_ = []; let fileApi_ = null; let currentClient_ = 1; @@ -341,7 +341,7 @@ function fileApi() { function objectsEqual(o1, o2) { if (Object.getOwnPropertyNames(o1).length !== Object.getOwnPropertyNames(o2).length) return false; - for (let n in o1) { + for (const n in o1) { if (!o1.hasOwnProperty(n)) continue; if (o1[n] !== o2[n]) return false; } @@ -427,7 +427,7 @@ function sortedIds(a) { } function at(a, indexes) { - let out = []; + const out = []; for (let i = 0; i < indexes.length; i++) { out.push(a[indexes[i]]); } @@ -435,19 +435,19 @@ function at(a, indexes) { } async function createNTestFolders(n) { - let folders = []; + const folders = []; for (let i = 0; i < n; i++) { - let folder = await Folder.save({ title: 'folder' }); + const folder = await Folder.save({ title: 'folder' }); folders.push(folder); } return folders; } async function createNTestNotes(n, folder, tagIds = null, title = 'note') { - let notes = []; + const notes = []; for (let i = 0; i < n; i++) { - let title_ = n > 1 ? `${title}${i}` : title; - let note = await Note.save({ title: title_, parent_id: folder.id, is_conflict: 0 }); + const title_ = n > 1 ? `${title}${i}` : title; + const note = await Note.save({ title: title_, parent_id: folder.id, is_conflict: 0 }); notes.push(note); } if (tagIds) { @@ -459,9 +459,9 @@ async function createNTestNotes(n, folder, tagIds = null, title = 'note') { } async function createNTestTags(n) { - let tags = []; + const tags = []; for (let i = 0; i < n; i++) { - let tag = await Tag.save({ title: 'tag' }); + const tag = await Tag.save({ title: 'tag' }); tags.push(tag); } return tags; diff --git a/Clipper/content_scripts/index.js b/Clipper/content_scripts/index.js index 7852ca66d..9a4f0f93f 100644 --- a/Clipper/content_scripts/index.js +++ b/Clipper/content_scripts/index.js @@ -290,8 +290,8 @@ // option to clip pages as HTML. function getStyleSheets(doc) { const output = []; - for (var i=0; i { const sortItems = []; const sortOptions = Setting.enumOptions(`${type}.sortOrder.field`); - for (let field in sortOptions) { + for (const field in sortOptions) { if (!sortOptions.hasOwnProperty(field)) continue; sortItems.push({ label: sortOptions[field], @@ -650,7 +650,7 @@ class Application extends BaseApplication { gitInfo = _('Revision: %s (%s)', p.git.hash, p.git.branch); } const copyrightText = 'Copyright © 2016-YYYY Laurent Cozic'; - let message = [ + const message = [ p.description, '', copyrightText.replace('YYYY', new Date().getFullYear()), @@ -1119,7 +1119,7 @@ class Application extends BaseApplication { const pluginMenuItems = PluginManager.instance().menuItems(); for (const item of pluginMenuItems) { - let itemParent = rootMenus[item.parent] ? rootMenus[item.parent] : 'tools'; + const itemParent = rootMenus[item.parent] ? rootMenus[item.parent] : 'tools'; itemParent.submenu.push(item); } @@ -1155,7 +1155,7 @@ class Application extends BaseApplication { } // Remove empty separator for now empty sections - let temp = []; + const temp = []; let previous = null; for (let i = 0; i < output.length; i++) { const t = Object.assign({}, output[i]); @@ -1171,7 +1171,7 @@ class Application extends BaseApplication { return output; } - let screenTemplate = removeUnwantedItems(template, screen); + const screenTemplate = removeUnwantedItems(template, screen); const menu = Menu.buildFromTemplate(screenTemplate); Menu.setApplicationMenu(menu); diff --git a/ElectronClient/gui/ClipperConfigScreen.jsx b/ElectronClient/gui/ClipperConfigScreen.jsx index 52ca415ec..6e4c200ef 100644 --- a/ElectronClient/gui/ClipperConfigScreen.jsx +++ b/ElectronClient/gui/ClipperConfigScreen.jsx @@ -57,7 +57,7 @@ class ClipperConfigScreenComponent extends React.Component { backgroundColor: theme.backgroundColor, }; - let webClipperStatusComps = []; + const webClipperStatusComps = []; if (this.props.clipperServerAutoStart) { webClipperStatusComps.push( diff --git a/ElectronClient/gui/ConfigScreen.jsx b/ElectronClient/gui/ConfigScreen.jsx index 3e0c9ceac..9b738d520 100644 --- a/ElectronClient/gui/ConfigScreen.jsx +++ b/ElectronClient/gui/ConfigScreen.jsx @@ -92,8 +92,8 @@ class ConfigScreenComponent extends React.Component { } keyValueToArray(kv) { - let output = []; - for (let k in kv) { + const output = []; + for (const k in kv) { if (!kv.hasOwnProperty(k)) continue; output.push({ key: k, @@ -205,7 +205,7 @@ class ConfigScreenComponent extends React.Component { } let advancedSettingsButton = null; - let advancedSettingsSectionStyle = { display: 'none' }; + const advancedSettingsSectionStyle = { display: 'none' }; if (advancedSettingComps.length) { const iconName = this.state.showAdvancedSettings ? 'fa fa-toggle-up' : 'fa fa-toggle-down'; @@ -227,7 +227,7 @@ class ConfigScreenComponent extends React.Component { settingToComponent(key, value) { const theme = themeStyle(this.props.theme); - let output = null; + const output = null; const rowStyle = this.rowStyle_; @@ -283,9 +283,9 @@ class ConfigScreenComponent extends React.Component { const descriptionComp = descriptionText ?
{descriptionText}
: null; if (md.isEnum) { - let items = []; + const items = []; const settingOptions = md.options(); - let array = this.keyValueToArray(settingOptions); + const array = this.keyValueToArray(settingOptions); for (let i = 0; i < array.length; i++) { const e = array[i]; items.push( @@ -547,7 +547,7 @@ class ConfigScreenComponent extends React.Component { } ); - let settings = this.state.settings; + const settings = this.state.settings; const containerStyle = Object.assign({}, theme.containerStyle, { padding: 10, paddingTop: 0, display: 'flex', flex: 1 }); diff --git a/ElectronClient/gui/EncryptionConfigScreen.jsx b/ElectronClient/gui/EncryptionConfigScreen.jsx index 3c825b00a..a98696a15 100644 --- a/ElectronClient/gui/EncryptionConfigScreen.jsx +++ b/ElectronClient/gui/EncryptionConfigScreen.jsx @@ -149,7 +149,7 @@ class EncryptionConfigScreenComponent extends React.Component { }); const mkComps = []; - let nonExistingMasterKeyIds = this.props.notLoadedMasterKeys.slice(); + const nonExistingMasterKeyIds = this.props.notLoadedMasterKeys.slice(); for (let i = 0; i < masterKeys.length; i++) { const mk = masterKeys[i]; diff --git a/ElectronClient/gui/Header.jsx b/ElectronClient/gui/Header.jsx index 924ac8336..de9787e06 100644 --- a/ElectronClient/gui/Header.jsx +++ b/ElectronClient/gui/Header.jsx @@ -149,7 +149,7 @@ class HeaderComponent extends React.Component { } const isEnabled = !('enabled' in options) || options.enabled; - let classes = ['button']; + const classes = ['button']; if (!isEnabled) classes.push('disabled'); const finalStyle = Object.assign({}, style, { diff --git a/ElectronClient/gui/HelpButton.jsx b/ElectronClient/gui/HelpButton.jsx index 923ff84a4..9aa044605 100644 --- a/ElectronClient/gui/HelpButton.jsx +++ b/ElectronClient/gui/HelpButton.jsx @@ -15,7 +15,7 @@ class HelpButtonComponent extends React.Component { render() { const theme = themeStyle(this.props.theme); - let style = Object.assign({}, this.props.style, { color: theme.color, textDecoration: 'none' }); + const style = Object.assign({}, this.props.style, { color: theme.color, textDecoration: 'none' }); const helpIconStyle = { flex: 0, width: 16, height: 16, marginLeft: 10 }; const extraProps = {}; if (this.props.tip) extraProps['data-tip'] = this.props.tip; diff --git a/ElectronClient/gui/ImportScreen.jsx b/ElectronClient/gui/ImportScreen.jsx index 6a46c0f4d..d2852442f 100644 --- a/ElectronClient/gui/ImportScreen.jsx +++ b/ElectronClient/gui/ImportScreen.jsx @@ -46,9 +46,9 @@ class ImportScreenComponent extends React.Component { } uniqueMessages() { - let output = []; + const output = []; const messages = this.state.messages.slice(); - let foundKeys = []; + const foundKeys = []; for (let i = messages.length - 1; i >= 0; i--) { const msg = messages[i]; if (foundKeys.indexOf(msg.key) >= 0) continue; @@ -68,7 +68,7 @@ class ImportScreenComponent extends React.Component { const options = { onProgress: progressState => { - let line = []; + const line = []; line.push(_('Found: %d.', progressState.loaded)); line.push(_('Created: %d.', progressState.created)); if (progressState.updated) line.push(_('Updated: %d.', progressState.updated)); diff --git a/ElectronClient/gui/ItemList.jsx b/ElectronClient/gui/ItemList.jsx index 4d2e516a0..ab5644b7d 100644 --- a/ElectronClient/gui/ItemList.jsx +++ b/ElectronClient/gui/ItemList.jsx @@ -83,7 +83,7 @@ class ItemList extends React.Component { return
; }; - let itemComps = [blankItem('top', this.state.topItemIndex * this.props.itemHeight)]; + const itemComps = [blankItem('top', this.state.topItemIndex * this.props.itemHeight)]; for (let i = this.state.topItemIndex; i <= this.state.bottomItemIndex; i++) { const itemComp = this.props.itemRenderer(items[i]); @@ -92,7 +92,7 @@ class ItemList extends React.Component { itemComps.push(blankItem('bottom', (items.length - this.state.bottomItemIndex - 1) * this.props.itemHeight)); - let classes = ['item-list']; + const classes = ['item-list']; if (this.props.className) classes.push(this.props.className); return ( diff --git a/ElectronClient/gui/MainScreen.jsx b/ElectronClient/gui/MainScreen.jsx index e6968d2be..2d28eb9f3 100644 --- a/ElectronClient/gui/MainScreen.jsx +++ b/ElectronClient/gui/MainScreen.jsx @@ -324,7 +324,7 @@ class MainScreenComponent extends React.Component { } else if (command.name === 'editAlarm') { const note = await Note.load(command.noteId); - let defaultDate = new Date(Date.now() + 2 * 3600 * 1000); + const defaultDate = new Date(Date.now() + 2 * 3600 * 1000); defaultDate.setMinutes(0); defaultDate.setSeconds(0); diff --git a/ElectronClient/gui/Navigator.jsx b/ElectronClient/gui/Navigator.jsx index d87fccaa7..5df5e67d3 100644 --- a/ElectronClient/gui/Navigator.jsx +++ b/ElectronClient/gui/Navigator.jsx @@ -7,7 +7,7 @@ class NavigatorComponent extends Component { UNSAFE_componentWillReceiveProps(newProps) { if (newProps.route) { const screenInfo = this.props.screens[newProps.route.routeName]; - let windowTitle = ['Joplin']; + const windowTitle = ['Joplin']; if (screenInfo.title) { windowTitle.push(screenInfo.title()); } diff --git a/ElectronClient/gui/NoteContentPropertiesDialog.tsx b/ElectronClient/gui/NoteContentPropertiesDialog.tsx index da8ba062e..80183be97 100644 --- a/ElectronClient/gui/NoteContentPropertiesDialog.tsx +++ b/ElectronClient/gui/NoteContentPropertiesDialog.tsx @@ -64,7 +64,7 @@ export default function NoteContentPropertiesDialog(props:NoteContentPropertiesD }; if (textProperties) { - for (let key in textProperties) { + for (const key in textProperties) { if (!textProperties.hasOwnProperty(key)) continue; const comp = createItemField(key, textProperties[key]); textComps.push(comp); diff --git a/ElectronClient/gui/NoteList.jsx b/ElectronClient/gui/NoteList.jsx index d33204418..28b7b261c 100644 --- a/ElectronClient/gui/NoteList.jsx +++ b/ElectronClient/gui/NoteList.jsx @@ -34,7 +34,7 @@ class NoteListComponent extends React.Component { // Pull request: https://github.com/laurent22/joplin/pull/2062 const itemWidth = '100%'; - let style = { + const style = { root: { backgroundColor: theme.backgroundColor, }, @@ -184,7 +184,7 @@ class NoteListComponent extends React.Component { listItemTitleStyle.paddingLeft = !checkbox ? hPadding : 4; if (item.is_todo && !!item.todo_completed) listItemTitleStyle = Object.assign(listItemTitleStyle, this.style().listItemTitleCompleted); - let displayTitle = Note.displayTitle(item); + const displayTitle = Note.displayTitle(item); let titleComp = null; if (highlightedWords.length) { @@ -435,7 +435,7 @@ class NoteListComponent extends React.Component { render() { const theme = themeStyle(this.props.theme); const style = this.props.style; - let notes = this.props.notes.slice(); + const notes = this.props.notes.slice(); if (!notes.length) { const padding = 10; diff --git a/ElectronClient/gui/NotePropertiesDialog.jsx b/ElectronClient/gui/NotePropertiesDialog.jsx index 7a82e8766..4d4dbf991 100644 --- a/ElectronClient/gui/NotePropertiesDialog.jsx +++ b/ElectronClient/gui/NotePropertiesDialog.jsx @@ -361,7 +361,7 @@ class NotePropertiesDialog extends React.Component { const noteComps = []; if (formNote) { - for (let key in formNote) { + for (const key in formNote) { if (!formNote.hasOwnProperty(key)) continue; const comp = this.createNoteField(key, formNote[key]); noteComps.push(comp); diff --git a/ElectronClient/gui/NoteRevisionViewer.jsx b/ElectronClient/gui/NoteRevisionViewer.jsx index edf4fa5ed..eee75d756 100644 --- a/ElectronClient/gui/NoteRevisionViewer.jsx +++ b/ElectronClient/gui/NoteRevisionViewer.jsx @@ -40,7 +40,7 @@ class NoteRevisionViewerComponent extends React.PureComponent { style() { const theme = themeStyle(this.props.theme); - let style = { + const style = { root: { backgroundColor: theme.backgroundColor, display: 'flex', diff --git a/ElectronClient/gui/NoteSearchBar.jsx b/ElectronClient/gui/NoteSearchBar.jsx index e874f3048..3ba74e842 100644 --- a/ElectronClient/gui/NoteSearchBar.jsx +++ b/ElectronClient/gui/NoteSearchBar.jsx @@ -19,7 +19,7 @@ class NoteSearchBarComponent extends React.Component { style() { const theme = themeStyle(this.props.theme); - let style = { + const style = { root: Object.assign({}, theme.textStyle, { backgroundColor: theme.backgroundColor, color: theme.colorFaded, @@ -130,7 +130,7 @@ class NoteSearchBarComponent extends React.Component { if (this.backgroundColor === undefined) { this.backgroundColor = theme.backgroundColor; } - let buttonEnabled = (this.backgroundColor === theme.backgroundColor); + const buttonEnabled = (this.backgroundColor === theme.backgroundColor); const closeButton = this.buttonIconComponent('fa-times', this.closeButton_click, true); const previousButton = this.buttonIconComponent('fa-chevron-up', this.previousButton_click, buttonEnabled); diff --git a/ElectronClient/gui/NoteStatusBar.jsx b/ElectronClient/gui/NoteStatusBar.jsx index 714fd8594..15a71635f 100644 --- a/ElectronClient/gui/NoteStatusBar.jsx +++ b/ElectronClient/gui/NoteStatusBar.jsx @@ -7,7 +7,7 @@ class NoteStatusBarComponent extends React.Component { style() { const theme = themeStyle(this.props.theme); - let style = { + const style = { root: Object.assign({}, theme.textStyle, { backgroundColor: theme.backgroundColor, color: theme.colorFaded, diff --git a/ElectronClient/gui/NoteText.jsx b/ElectronClient/gui/NoteText.jsx index 8bfaa76ab..23827df68 100644 --- a/ElectronClient/gui/NoteText.jsx +++ b/ElectronClient/gui/NoteText.jsx @@ -543,22 +543,22 @@ class NoteTextComponent extends React.Component { this.setState({ loading: true }); const stateNoteId = this.state.note ? this.state.note.id : null; - let noteId = props.noteId; + const noteId = props.noteId; let parentFolder = null; const isProvisionalNote = this.props.provisionalNoteIds.includes(noteId); let scrollPercent = this.props.lastEditorScrollPercents[noteId]; if (!scrollPercent) scrollPercent = 0; - let loadingNewNote = stateNoteId !== noteId; + const loadingNewNote = stateNoteId !== noteId; this.lastLoadedNoteId_ = noteId; - let note = noteId ? await Note.load(noteId) : null; + const note = noteId ? await Note.load(noteId) : null; if (noteId !== this.lastLoadedNoteId_) return defer(); // Race condition - current note was changed while this one was loading if (options.noReloadIfLocalChanges && this.isModified()) return defer(); // If the note hasn't been changed, exit now if (this.state.note && note) { - let diff = Note.diffObjects(this.state.note, note); + const diff = Note.diffObjects(this.state.note, note); delete diff.type_; if (!Object.getOwnPropertyNames(diff).length) return defer(); } @@ -622,7 +622,7 @@ class NoteTextComponent extends React.Component { parentFolder = Folder.byId(props.folders, note.parent_id); } - let newState = { + const newState = { note: note, lastSavedNote: Object.assign({}, note), webviewReady: webviewReady, @@ -686,9 +686,9 @@ class NoteTextComponent extends React.Component { for (let i = 0; i < newTags.length; ++i) { let found = false; - let currNewTag = newTags[i]; + const currNewTag = newTags[i]; for (let j = 0; j < oldTags.length; ++j) { - let currOldTag = oldTags[j]; + const currOldTag = oldTags[j]; if (currOldTag.id === currNewTag.id) { found = true; if (currOldTag.updated_time !== currNewTag.updated_time) { @@ -1299,7 +1299,7 @@ class NoteTextComponent extends React.Component { try { if (!this.state.note && !args.noteIds) throw new Error('No notes selected for pdf export'); - let noteIds = args.noteIds ? args.noteIds : [this.state.note.id]; + const noteIds = args.noteIds ? args.noteIds : [this.state.note.id]; let path = null; if (noteIds.length === 1) { @@ -1452,14 +1452,14 @@ class NoteTextComponent extends React.Component { if (selection && selection.start !== selection.end) { const selectedLines = replacementText !== null ? replacementText : this.state.note.body.substr(selection.start, selection.end - selection.start); - let selectedStrings = byLine ? selectedLines.split(/\r?\n/) : [selectedLines]; + const selectedStrings = byLine ? selectedLines.split(/\r?\n/) : [selectedLines]; newBody = this.state.note.body.substr(0, selection.start); for (let i = 0; i < selectedStrings.length; i++) { if (byLine == false) { - let start = selectedStrings[i].search(/[^\s]/); - let end = selectedStrings[i].search(/[^\s](?=[\s]*$)/); + const start = selectedStrings[i].search(/[^\s]/); + const end = selectedStrings[i].search(/[^\s](?=[\s]*$)/); newBody += selectedStrings[i].substr(0, start) + string1 + selectedStrings[i].substr(start, end - start + 1) + string2 + selectedStrings[i].substr(end + 1); if (this.state.note.body.substr(selection.end) === '') newBody = newBody.trim(); } else { newBody += string1 + selectedStrings[i] + string2; } @@ -1498,7 +1498,7 @@ class NoteTextComponent extends React.Component { editor.focus(); }); } else { - let middleText = replacementText !== null ? replacementText : defaultText; + const middleText = replacementText !== null ? replacementText : defaultText; const textOffset = this.currentTextOffset(); const s1 = this.state.note.body.substr(0, textOffset); const s2 = this.state.note.body.substr(textOffset); @@ -1541,9 +1541,9 @@ class NoteTextComponent extends React.Component { toggleWrapSelection(strings1, strings2, defaultText) { const selection = this.textOffsetSelection(); - let string = this.state.note.body.substr(selection.start, selection.end - selection.start); + const string = this.state.note.body.substr(selection.start, selection.end - selection.start); let replaced = false; - for (var i = 0; i < strings1.length; i++) { + for (let i = 0; i < strings1.length; i++) { if (string.startsWith(strings1[i]) && string.endsWith(strings1[i])) { this.wrapSelectionWithStrings('', '', '', string.substr(strings1[i].length, selection.end - selection.start - (2 * strings1[i].length))); replaced = true; @@ -1570,10 +1570,10 @@ class NoteTextComponent extends React.Component { commandTextCode() { const selection = this.textOffsetSelection(); - let string = this.state.note.body.substr(selection.start, selection.end - selection.start); + const string = this.state.note.body.substr(selection.start, selection.end - selection.start); // Look for newlines - let match = string.match(/\r?\n/); + const match = string.match(/\r?\n/); if (match && match.length > 0) { // Follow the same newline style @@ -1591,7 +1591,7 @@ class NoteTextComponent extends React.Component { this.wrapSelectionWithStrings(TemplateUtils.render(value)); } - addListItem(string1, string2 = '', defaultText = '', byLine=false) { + addListItem(string1, string2 = '', defaultText = '', byLine = false) { let newLine = '\n'; const range = this.selectionRange_; if (!range || (range.start.row === range.end.row && !this.selectionRangeCurrentLine())) { @@ -1949,7 +1949,7 @@ class NoteTextComponent extends React.Component { const theme = themeStyle(this.props.theme); const visiblePanes = this.props.visiblePanes || ['editor', 'viewer']; const isTodo = note && !!note.is_todo; - var keyboardMode = this.props.keyboardMode; + let keyboardMode = this.props.keyboardMode; if (keyboardMode === 'default' || !keyboardMode) { keyboardMode = null; } @@ -2006,7 +2006,7 @@ class NoteTextComponent extends React.Component { paddingRight: 8, marginRight: rootStyle.paddingLeft, color: theme.textStyle.color, - fontSize: theme.textStyle.fontSize * 1.25 *1.5, + fontSize: theme.textStyle.fontSize * 1.25 * 1.5, backgroundColor: theme.backgroundColor, border: '1px solid', borderColor: theme.dividerColor, @@ -2083,11 +2083,11 @@ class NoteTextComponent extends React.Component { } if (this.state.webviewReady && this.webviewRef_.current) { - let html = this.state.bodyHtml; + const html = this.state.bodyHtml; const htmlHasChanged = this.lastSetHtml_ !== html; if (htmlHasChanged) { - let options = { + const options = { pluginAssets: this.state.lastRenderPluginAssets, downloadResources: Setting.value('sync.resourceDownloadMode'), }; diff --git a/ElectronClient/gui/NoteTextViewer.jsx b/ElectronClient/gui/NoteTextViewer.jsx index 84e2984de..ec7533857 100644 --- a/ElectronClient/gui/NoteTextViewer.jsx +++ b/ElectronClient/gui/NoteTextViewer.jsx @@ -57,7 +57,7 @@ class NoteTextViewerComponent extends React.Component { }; } - for (let n in this.webviewListeners_) { + for (const n in this.webviewListeners_) { if (!this.webviewListeners_.hasOwnProperty(n)) continue; const fn = this.webviewListeners_[n]; wv.addEventListener(n, fn); @@ -70,7 +70,7 @@ class NoteTextViewerComponent extends React.Component { const wv = this.webviewRef_.current; if (!wv || !this.initialized_) return; - for (let n in this.webviewListeners_) { + for (const n in this.webviewListeners_) { if (!this.webviewListeners_.hasOwnProperty(n)) continue; const fn = this.webviewListeners_[n]; wv.removeEventListener(n, fn); diff --git a/ElectronClient/gui/ShareNoteDialog.tsx b/ElectronClient/gui/ShareNoteDialog.tsx index 4f4e76e9e..14d1560bd 100644 --- a/ElectronClient/gui/ShareNoteDialog.tsx +++ b/ElectronClient/gui/ShareNoteDialog.tsx @@ -73,7 +73,7 @@ export default function ShareNoteDialog(props:ShareNoteDialogProps) { useEffect(() => { async function fetchNotes() { const result = []; - for (let noteId of props.noteIds) { + for (const noteId of props.noteIds) { result.push(await Note.load(noteId)); } setNotes(result); @@ -180,7 +180,7 @@ export default function ShareNoteDialog(props:ShareNoteDialogProps) { const renderNoteList = (notes:any) => { const noteComps = []; - for (let noteId of Object.keys(notes)) { + for (const noteId of Object.keys(notes)) { noteComps.push(renderNote(notes[noteId])); } return
{noteComps}
; diff --git a/ElectronClient/gui/SideBar.jsx b/ElectronClient/gui/SideBar.jsx index 86cd0caac..35c41ef3b 100644 --- a/ElectronClient/gui/SideBar.jsx +++ b/ElectronClient/gui/SideBar.jsx @@ -107,7 +107,7 @@ class SideBarComponent extends React.Component { const itemHeight = 25; - let style = { + const style = { root: { backgroundColor: theme.backgroundColor2, }, @@ -459,8 +459,8 @@ class SideBarComponent extends React.Component { let containerStyle = Object.assign({}, this.style(depth).listItemContainer); if (selected) containerStyle = Object.assign(containerStyle, this.style().listItemSelected); - let expandLinkStyle = Object.assign({}, this.style().listItemExpandIcon); - let expandIconStyle = { + const expandLinkStyle = Object.assign({}, this.style().listItemExpandIcon); + const expandIconStyle = { visibility: hasChildren ? 'visible' : 'hidden', paddingLeft: 8 + depth * 10, }; @@ -562,18 +562,18 @@ class SideBarComponent extends React.Component { style.cursor = 'pointer'; } - let headerClick = extraProps.onClick || null; + const headerClick = extraProps.onClick || null; delete extraProps.onClick; // check if toggling option is set. let toggleIcon = null; const toggleKey = `${key}IsExpanded`; if (extraProps.toggleblock) { - let isExpanded = this.state[toggleKey]; + const isExpanded = this.state[toggleKey]; toggleIcon = ; } if (extraProps.selected) { - style.backgroundColor =this.style().listItemSelected.backgroundColor; + style.backgroundColor = this.style().listItemSelected.backgroundColor; } const ref = this.anchorItemRef('headers', key); @@ -645,7 +645,7 @@ class SideBarComponent extends React.Component { const focusItem = focusItems[newIndex]; - let actionName = `${focusItem.type.toUpperCase()}_SELECT`; + const actionName = `${focusItem.type.toUpperCase()}_SELECT`; this.props.dispatch({ type: actionName, @@ -712,7 +712,7 @@ class SideBarComponent extends React.Component { const style = Object.assign({}, this.style().button, { marginBottom: 5 }); const iconName = 'fa-refresh'; const label = type === 'sync' ? _('Synchronise') : _('Cancel'); - let iconStyle = { fontSize: style.fontSize, marginRight: 5 }; + const iconStyle = { fontSize: style.fontSize, marginRight: 5 }; if (type !== 'sync') { iconStyle.animation = 'icon-infinite-rotation 1s linear infinite'; @@ -743,7 +743,7 @@ class SideBarComponent extends React.Component { flexDirection: 'column', }); - let items = []; + const items = []; items.push( this.makeHeader('allNotesHeader', _('All notes'), 'fa-clone', { onClick: this.onAllNotesClick_, @@ -798,7 +798,7 @@ class SideBarComponent extends React.Component { resourceFetcherText = _('Fetching resources: %d/%d', this.props.resourceFetcher.fetchingCount, this.props.resourceFetcher.toFetchCount); } - let lines = Synchronizer.reportToLines(this.props.syncReport); + const lines = Synchronizer.reportToLines(this.props.syncReport); if (resourceFetcherText) lines.push(resourceFetcherText); if (decryptionReportText) lines.push(decryptionReportText); const syncReportText = []; diff --git a/ElectronClient/gui/StatusScreen.jsx b/ElectronClient/gui/StatusScreen.jsx index 006c4ed3b..34ff3c26e 100644 --- a/ElectronClient/gui/StatusScreen.jsx +++ b/ElectronClient/gui/StatusScreen.jsx @@ -64,13 +64,13 @@ class StatusScreenComponent extends React.Component { } const renderSectionHtml = (key, section) => { - let itemsHtml = []; + const itemsHtml = []; itemsHtml.push(renderSectionTitleHtml(section.title, section.title)); - for (let n in section.body) { + for (const n in section.body) { if (!section.body.hasOwnProperty(n)) continue; - let item = section.body[n]; + const item = section.body[n]; let text = ''; let retryLink = null; @@ -106,10 +106,10 @@ class StatusScreenComponent extends React.Component { }; function renderBodyHtml(report) { - let sectionsHtml = []; + const sectionsHtml = []; for (let i = 0; i < report.length; i++) { - let section = report[i]; + const section = report[i]; if (!section.body.length) continue; sectionsHtml.push(renderSectionHtml(i, section)); } @@ -117,7 +117,7 @@ class StatusScreenComponent extends React.Component { return
{sectionsHtml}
; } - let body = renderBodyHtml(this.state.report); + const body = renderBodyHtml(this.state.report); return (
diff --git a/ElectronClient/gui/ToolbarButton.jsx b/ElectronClient/gui/ToolbarButton.jsx index 828b10e08..1638a569a 100644 --- a/ElectronClient/gui/ToolbarButton.jsx +++ b/ElectronClient/gui/ToolbarButton.jsx @@ -21,7 +21,7 @@ class ToolbarButton extends React.Component { } const isEnabled = !('enabled' in this.props) || this.props.enabled === true; - let classes = ['button']; + const classes = ['button']; if (!isEnabled) classes.push('disabled'); const finalStyle = Object.assign({}, style, { diff --git a/ElectronClient/main-html.js b/ElectronClient/main-html.js index b3c95e173..990f1a012 100644 --- a/ElectronClient/main-html.js +++ b/ElectronClient/main-html.js @@ -100,7 +100,7 @@ app().start(bridge().processArgv()).then(() => { } else { // If something goes wrong at this stage we don't have a console or a log file // so display the error in a message box. - let msg = ['Fatal error:', error.message]; + const msg = ['Fatal error:', error.message]; if (error.fileName) msg.push(error.fileName); if (error.lineNumber) msg.push(error.lineNumber); if (error.stack) msg.push(error.stack); diff --git a/ElectronClient/theme.js b/ElectronClient/theme.js index f48cad11c..a9ba54caf 100644 --- a/ElectronClient/theme.js +++ b/ElectronClient/theme.js @@ -385,13 +385,13 @@ function addExtraStyles(style) { return style; } -let themeCache_ = {}; +const themeCache_ = {}; function themeStyle(theme) { if (!theme) throw new Error('Theme must be specified'); - var zoomRatio = 1; // Setting.value('style.zoom') / 100; - var editorFontSize = Setting.value('style.editor.fontSize'); + const zoomRatio = 1; // Setting.value('style.zoom') / 100; + const editorFontSize = Setting.value('style.editor.fontSize'); const cacheKey = [theme, zoomRatio, editorFontSize].join('-'); if (themeCache_[cacheKey]) return themeCache_[cacheKey]; @@ -399,7 +399,7 @@ function themeStyle(theme) { // Font size are not theme specific, but they must be referenced // and computed here to allow them to respond to settings changes // without the need to restart - let fontSizes = { + const fontSizes = { fontSize: Math.round(globalStyle.fontSize * zoomRatio), editorFontSize: editorFontSize, textAreaLineHeight: Math.round(globalStyle.textAreaLineHeight * editorFontSize / 12), diff --git a/ElectronClient/tools/compile-package-info.js b/ElectronClient/tools/compile-package-info.js index 5dd22d223..8a477c224 100644 --- a/ElectronClient/tools/compile-package-info.js +++ b/ElectronClient/tools/compile-package-info.js @@ -7,7 +7,7 @@ const execSync = require('child_process').execSync; const packageInfo = require(`${__dirname}/../package.json`); module.exports = async function() { - let removeKeys = ['scripts', 'devDependencies', 'optionalDependencies', 'dependencies']; + const removeKeys = ['scripts', 'devDependencies', 'optionalDependencies', 'dependencies']; for (let i = 0; i < removeKeys.length; i++) { delete packageInfo[removeKeys[i]]; diff --git a/ReactNativeClient/PluginAssetsLoader.ts b/ReactNativeClient/PluginAssetsLoader.ts index 0124baf84..92a17f6b0 100644 --- a/ReactNativeClient/PluginAssetsLoader.ts +++ b/ReactNativeClient/PluginAssetsLoader.ts @@ -36,7 +36,7 @@ export default class PluginAssetsLoader { this.logger().info(`PluginAssetsLoader: Importing assets to ${destDir}`); try { - for (let name in pluginAssets.files) { + for (const name in pluginAssets.files) { const dataBase64 = pluginAssets.files[name].data; const destPath = `${destDir}/${name}`; await shim.fsDriver().mkdir(dirname(destPath)); diff --git a/ReactNativeClient/lib/ArrayUtils.js b/ReactNativeClient/lib/ArrayUtils.js index 6cff8e2d2..f3a2d5d80 100644 --- a/ReactNativeClient/lib/ArrayUtils.js +++ b/ReactNativeClient/lib/ArrayUtils.js @@ -16,7 +16,7 @@ ArrayUtils.removeElement = function(array, element) { // https://stackoverflow.com/a/10264318/561309 ArrayUtils.binarySearch = function(items, value) { - var startIndex = 0, + let startIndex = 0, stopIndex = items.length - 1, middle = Math.floor((stopIndex + startIndex) / 2); diff --git a/ReactNativeClient/lib/BaseApplication.js b/ReactNativeClient/lib/BaseApplication.js index 94e8999a7..7c76a6b90 100644 --- a/ReactNativeClient/lib/BaseApplication.js +++ b/ReactNativeClient/lib/BaseApplication.js @@ -111,13 +111,13 @@ class BaseApplication { // Handles the initial flags passed to main script and // returns the remaining args. async handleStartFlags_(argv, setDefaults = true) { - let matched = {}; + const matched = {}; argv = argv.slice(0); argv.splice(0, 2); // First arguments are the node executable, and the node JS file while (argv.length) { - let arg = argv[0]; - let nextArg = argv.length >= 2 ? argv[1] : null; + const arg = argv[0]; + const nextArg = argv.length >= 2 ? argv[1] : null; if (arg == '--profile') { if (!nextArg) throw new JoplinError(_('Usage: %s', '--profile '), 'flagError'); @@ -245,7 +245,7 @@ class BaseApplication { this.logger().debug('Refreshing notes:', parentType, parentId); - let options = { + const options = { order: stateUtils.notesOrder(state.settings), uncompletedTodosOnTop: Setting.value('uncompletedTodosOnTop'), showCompletedTodos: Setting.value('showCompletedTodos'), @@ -333,7 +333,7 @@ class BaseApplication { } reducerActionToString(action) { - let o = [action.type]; + const o = [action.type]; if ('id' in action) o.push(action.id); if ('noteId' in action) o.push(action.noteId); if ('folderId' in action) o.push(action.folderId); @@ -580,7 +580,7 @@ class BaseApplication { } async start(argv) { - let startFlags = await this.handleStartFlags_(argv); + const startFlags = await this.handleStartFlags_(argv); argv = startFlags.argv; let initArgs = startFlags.matched; @@ -712,7 +712,7 @@ class BaseApplication { SearchEngine.instance().setLogger(reg.logger()); SearchEngine.instance().scheduleSyncTables(); - let currentFolderId = Setting.value('activeFolderId'); + const currentFolderId = Setting.value('activeFolderId'); let currentFolder = null; if (currentFolderId) currentFolder = await Folder.load(currentFolderId); if (!currentFolder) currentFolder = await Folder.defaultFolder(); diff --git a/ReactNativeClient/lib/BaseModel.js b/ReactNativeClient/lib/BaseModel.js index bb507aaf6..44b423b41 100644 --- a/ReactNativeClient/lib/BaseModel.js +++ b/ReactNativeClient/lib/BaseModel.js @@ -16,7 +16,7 @@ class BaseModel { if (!model) return model; if (Array.isArray(model)) { - let output = []; + const output = []; for (let i = 0; i < model.length; i++) { output.push(this.addModelMd(model[i])); } @@ -87,16 +87,16 @@ class BaseModel { } static hasField(name) { - let fields = this.fieldNames(); + const fields = this.fieldNames(); return fields.indexOf(name) >= 0; } static fieldNames(withPrefix = false) { - let output = this.db().tableFieldNames(this.tableName()); + const output = this.db().tableFieldNames(this.tableName()); if (!withPrefix) return output; - let p = withPrefix === true ? this.tableName() : withPrefix; - let temp = []; + const p = withPrefix === true ? this.tableName() : withPrefix; + const temp = []; for (let i = 0; i < output.length; i++) { temp.push(`${p}.${output[i]}`); } @@ -105,7 +105,7 @@ class BaseModel { } static fieldType(name, defaultValue = null) { - let fields = this.fields(); + const fields = this.fields(); for (let i = 0; i < fields.length; i++) { if (fields[i].name == name) return fields[i].type; } @@ -119,7 +119,7 @@ class BaseModel { static removeUnknownFields(model) { const newModel = {}; - for (let n in model) { + for (const n in model) { if (!model.hasOwnProperty(n)) continue; if (!this.hasField(n) && n !== 'type_') continue; newModel[n] = model[n]; @@ -128,10 +128,10 @@ class BaseModel { } static new() { - let fields = this.fields(); - let output = {}; + const fields = this.fields(); + const output = {}; for (let i = 0; i < fields.length; i++) { - let f = fields[i]; + const f = fields[i]; output[f.name] = f.default; } return output; @@ -175,7 +175,7 @@ class BaseModel { if (!options) options = {}; if (options.order && options.order.length) { - let items = []; + const items = []; for (let i = 0; i < options.order.length; i++) { const o = options.order[i]; let item = o.by; @@ -192,7 +192,7 @@ class BaseModel { } static async allIds(options = null) { - let q = this.applySqlOptions(options, `SELECT id FROM \`${this.tableName()}\``); + const q = this.applySqlOptions(options, `SELECT id FROM \`${this.tableName()}\``); const rows = await this.db().selectAll(q.sql, q.params); return rows.map(r => r.id); } @@ -208,7 +208,7 @@ class BaseModel { if (options.whereParams) params = params.concat(options.whereParams); } - let q = this.applySqlOptions(options, sql, params); + const q = this.applySqlOptions(options, sql, params); return this.modelSelectAll(q.sql, q.params); } @@ -219,7 +219,7 @@ class BaseModel { let sql = `SELECT ${this.db().escapeFields(options.fields)} FROM \`${this.tableName()}\``; sql += ` WHERE id IN ("${ids.join('","')}")`; - let q = this.applySqlOptions(options, sql); + const q = this.applySqlOptions(options, sql); return this.modelSelectAll(q.sql); } @@ -227,11 +227,11 @@ class BaseModel { if (!options) options = {}; if (!options.fields) options.fields = '*'; - let conditions = options.conditions ? options.conditions.slice(0) : []; - let params = options.conditionsParams ? options.conditionsParams.slice(0) : []; + const conditions = options.conditions ? options.conditions.slice(0) : []; + const params = options.conditionsParams ? options.conditionsParams.slice(0) : []; if (options.titlePattern) { - let pattern = options.titlePattern.replace(/\*/g, '%'); + const pattern = options.titlePattern.replace(/\*/g, '%'); conditions.push('title LIKE ?'); params.push(pattern); } @@ -241,7 +241,7 @@ class BaseModel { let sql = `SELECT ${this.db().escapeFields(options.fields)} FROM \`${this.tableName()}\``; if (conditions.length) sql += ` WHERE ${conditions.join(' AND ')}`; - let query = this.applySqlOptions(options, sql, params); + const query = this.applySqlOptions(options, sql, params); return this.modelSelectAll(query.sql, query.params); } @@ -277,7 +277,7 @@ class BaseModel { } static diffObjects(oldModel, newModel) { - let output = {}; + const output = {}; const fields = this.diffObjectsFields(oldModel, newModel); for (let i = 0; i < fields.length; i++) { output[fields[i]] = newModel[fields[i]]; @@ -287,8 +287,8 @@ class BaseModel { } static diffObjectsFields(oldModel, newModel) { - let output = []; - for (let n in newModel) { + const output = []; + for (const n in newModel) { if (!newModel.hasOwnProperty(n)) continue; if (n == 'type_') continue; if (!(n in oldModel) || newModel[n] !== oldModel[n]) { @@ -313,7 +313,7 @@ class BaseModel { if (!modelOrId) return noLockMutex; - let modelId = typeof modelOrId === 'string' ? modelOrId : modelOrId.id; + const modelId = typeof modelOrId === 'string' ? modelOrId : modelOrId.id; if (!modelId) return noLockMutex; @@ -329,11 +329,11 @@ class BaseModel { if (!release) return; if (!modelOrId) return release(); - let modelId = typeof modelOrId === 'string' ? modelOrId : modelOrId.id; + const modelId = typeof modelOrId === 'string' ? modelOrId : modelOrId.id; if (!modelId) return release(); - let mutex = BaseModel.saveMutexes_[modelId]; + const mutex = BaseModel.saveMutexes_[modelId]; if (!mutex) return release(); delete BaseModel.saveMutexes_[modelId]; @@ -342,9 +342,9 @@ class BaseModel { static saveQuery(o, options) { let temp = {}; - let fieldNames = this.fieldNames(); + const fieldNames = this.fieldNames(); for (let i = 0; i < fieldNames.length; i++) { - let n = fieldNames[i]; + const n = fieldNames[i]; if (n in o) temp[n] = o[n]; } @@ -354,7 +354,7 @@ class BaseModel { // id also will stay. if (!options.isNew && options.fields) { const filtered = {}; - for (let k in temp) { + for (const k in temp) { if (!temp.hasOwnProperty(k)) continue; if (k !== 'id' && options.fields.indexOf(k) < 0) continue; filtered[k] = temp[k]; @@ -404,8 +404,8 @@ class BaseModel { query = Database.insertQuery(this.tableName(), o); } else { - let where = { id: o.id }; - let temp = Object.assign({}, o); + const where = { id: o.id }; + const temp = Object.assign({}, o); delete temp.id; query = Database.updateQuery(this.tableName(), temp, where); @@ -445,8 +445,8 @@ class BaseModel { o = this.filter(o); let queries = []; - let saveQuery = this.saveQuery(o, options); - let modelId = saveQuery.id; + const saveQuery = this.saveQuery(o, options); + const modelId = saveQuery.id; queries.push(saveQuery); @@ -473,7 +473,7 @@ class BaseModel { o = this.addModelMd(o); if (isDiffSaving) { - for (let n in options.oldItem) { + for (const n in options.oldItem) { if (!options.oldItem.hasOwnProperty(n)) continue; if (n in o) continue; o[n] = options.oldItem[n]; @@ -499,7 +499,7 @@ class BaseModel { } static filterArray(models) { - let output = []; + const output = []; for (let i = 0; i < models.length; i++) { output.push(this.filter(models[i])); } @@ -509,8 +509,8 @@ class BaseModel { static filter(model) { if (!model) return model; - let output = Object.assign({}, model); - for (let n in output) { + const output = Object.assign({}, model); + for (const n in output) { if (!output.hasOwnProperty(n)) continue; // The SQLite database doesn't have booleans so cast everything to int diff --git a/ReactNativeClient/lib/DropboxApi.js b/ReactNativeClient/lib/DropboxApi.js index c86ae7c55..7e80fc494 100644 --- a/ReactNativeClient/lib/DropboxApi.js +++ b/ReactNativeClient/lib/DropboxApi.js @@ -51,11 +51,11 @@ class DropboxApi { } requestToCurl_(url, options) { - let output = []; + const output = []; output.push('curl'); if (options.method) output.push(`-X ${options.method}`); if (options.headers) { - for (let n in options.headers) { + for (const n in options.headers) { if (!options.headers.hasOwnProperty(n)) continue; output.push(`${'-H ' + '\''}${n}: ${options.headers[n]}'`); } @@ -74,10 +74,10 @@ class DropboxApi { client_secret: this.clientSecret(), }; - var formBody = []; - for (var property in postData) { - var encodedKey = encodeURIComponent(property); - var encodedValue = encodeURIComponent(postData[property]); + let formBody = []; + for (const property in postData) { + const encodedKey = encodeURIComponent(property); + const encodedValue = encodeURIComponent(postData[property]); formBody.push(`${encodedKey}=${encodedValue}`); } formBody = formBody.join('&'); diff --git a/ReactNativeClient/lib/EventDispatcher.js b/ReactNativeClient/lib/EventDispatcher.js index 758d7eee6..5fd795973 100644 --- a/ReactNativeClient/lib/EventDispatcher.js +++ b/ReactNativeClient/lib/EventDispatcher.js @@ -6,7 +6,7 @@ class EventDispatcher { dispatch(eventName, event = null) { if (!this.listeners_[eventName]) return; - let ls = this.listeners_[eventName]; + const ls = this.listeners_[eventName]; for (let i = 0; i < ls.length; i++) { ls[i](event); } @@ -20,7 +20,7 @@ class EventDispatcher { off(eventName, callback) { if (!this.listeners_[eventName]) return; - let ls = this.listeners_[eventName]; + const ls = this.listeners_[eventName]; for (let i = 0; i < ls.length; i++) { if (ls[i] === callback) { ls.splice(i, 1); diff --git a/ReactNativeClient/lib/JoplinServerApi.ts b/ReactNativeClient/lib/JoplinServerApi.ts index 3926ce168..b936ba2d9 100644 --- a/ReactNativeClient/lib/JoplinServerApi.ts +++ b/ReactNativeClient/lib/JoplinServerApi.ts @@ -83,12 +83,12 @@ export default class JoplinServerApi { } requestToCurl_(url:string, options:any) { - let output = []; + const output = []; output.push('curl'); output.push('-v'); if (options.method) output.push(`-X ${options.method}`); if (options.headers) { - for (let n in options.headers) { + for (const n in options.headers) { if (!options.headers.hasOwnProperty(n)) continue; output.push(`${'-H ' + '"'}${n}: ${options.headers[n]}"`); } @@ -129,7 +129,7 @@ export default class JoplinServerApi { const responseText = await response.text(); - let responseJson_:any = null; + const responseJson_:any = null; const loadResponseJson = async () => { if (!responseText) return null; if (responseJson_) return responseJson_; diff --git a/ReactNativeClient/lib/ObjectUtils.js b/ReactNativeClient/lib/ObjectUtils.js index 3e28e705b..e0b266453 100644 --- a/ReactNativeClient/lib/ObjectUtils.js +++ b/ReactNativeClient/lib/ObjectUtils.js @@ -2,7 +2,7 @@ const ObjectUtils = {}; ObjectUtils.sortByValue = function(object) { const temp = []; - for (let k in object) { + for (const k in object) { if (!object.hasOwnProperty(k)) continue; temp.push({ key: k, @@ -31,7 +31,7 @@ ObjectUtils.sortByValue = function(object) { ObjectUtils.fieldsEqual = function(o1, o2) { if ((!o1 || !o2) && o1 !== o2) return false; - for (let k in o1) { + for (const k in o1) { if (!o1.hasOwnProperty(k)) continue; if (o1[k] !== o2[k]) return false; } @@ -46,7 +46,7 @@ ObjectUtils.fieldsEqual = function(o1, o2) { ObjectUtils.convertValuesToFunctions = function(o) { const output = {}; - for (let n in o) { + for (const n in o) { if (!o.hasOwnProperty(n)) continue; output[n] = () => { return typeof o[n] === 'function' ? o[n]() : o[n]; diff --git a/ReactNativeClient/lib/SyncTargetRegistry.js b/ReactNativeClient/lib/SyncTargetRegistry.js index cd217f987..e6d4da215 100644 --- a/ReactNativeClient/lib/SyncTargetRegistry.js +++ b/ReactNativeClient/lib/SyncTargetRegistry.js @@ -16,7 +16,7 @@ class SyncTargetRegistry { } static nameToId(name) { - for (let n in this.reg_) { + for (const n in this.reg_) { if (!this.reg_.hasOwnProperty(n)) continue; if (this.reg_[n].name === name) return this.reg_[n].id; } @@ -24,7 +24,7 @@ class SyncTargetRegistry { } static idToMetadata(id) { - for (let n in this.reg_) { + for (const n in this.reg_) { if (!this.reg_.hasOwnProperty(n)) continue; if (this.reg_[n].id === id) return this.reg_[n]; } @@ -36,8 +36,8 @@ class SyncTargetRegistry { } static idAndLabelPlainObject(os) { - let output = {}; - for (let n in this.reg_) { + const output = {}; + for (const n in this.reg_) { if (!this.reg_.hasOwnProperty(n)) continue; const info = this.reg_[n]; if (info.classRef.unsupportedPlatforms().indexOf(os) >= 0) { diff --git a/ReactNativeClient/lib/TemplateUtils.js b/ReactNativeClient/lib/TemplateUtils.js index 46177476c..e6ab429fe 100644 --- a/ReactNativeClient/lib/TemplateUtils.js +++ b/ReactNativeClient/lib/TemplateUtils.js @@ -30,7 +30,7 @@ TemplateUtils.render = function(input) { }; TemplateUtils.loadTemplates = async function(filePath) { - let templates = []; + const templates = []; let files = []; if (await shim.fsDriver().exists(filePath)) { @@ -50,7 +50,7 @@ TemplateUtils.loadTemplates = async function(filePath) { files.forEach(async file => { if (file.path.endsWith('.md')) { try { - let fileString = await shim.fsDriver().readFile(`${filePath}/${file.path}`, 'utf-8'); + const fileString = await shim.fsDriver().readFile(`${filePath}/${file.path}`, 'utf-8'); templates.push({ label: file.path, value: fileString }); } catch (error) { let msg = error.message ? error.message : ''; diff --git a/ReactNativeClient/lib/WebDavApi.js b/ReactNativeClient/lib/WebDavApi.js index e4230f976..fa3c9a619 100644 --- a/ReactNativeClient/lib/WebDavApi.js +++ b/ReactNativeClient/lib/WebDavApi.js @@ -83,7 +83,7 @@ class WebDavApi { } async xmlToJson(xml) { - let davNamespaces = []; // Yes, there can be more than one... xmlns:a="DAV:" xmlns:D="DAV:" + const davNamespaces = []; // Yes, there can be more than one... xmlns:a="DAV:" xmlns:D="DAV:" const nameProcessor = name => { if (name.indexOf('xmlns') !== 0) { @@ -247,12 +247,12 @@ class WebDavApi { } requestToCurl_(url, options) { - let output = []; + const output = []; output.push('curl'); output.push('-v'); if (options.method) output.push(`-X ${options.method}`); if (options.headers) { - for (let n in options.headers) { + for (const n in options.headers) { if (!options.headers.hasOwnProperty(n)) continue; output.push(`${'-H ' + '"'}${n}: ${options.headers[n]}"`); } diff --git a/ReactNativeClient/lib/WelcomeUtils.js b/ReactNativeClient/lib/WelcomeUtils.js index 51110b780..3a8822789 100644 --- a/ReactNativeClient/lib/WelcomeUtils.js +++ b/ReactNativeClient/lib/WelcomeUtils.js @@ -30,7 +30,7 @@ class WelcomeUtils { let noteBody = noteAsset.body; - for (let resourceUrl in noteAsset.resources) { + for (const resourceUrl in noteAsset.resources) { if (!noteAsset.resources.hasOwnProperty(resourceUrl)) continue; const resourceAsset = noteAsset.resources[resourceUrl]; const ext = fileExtension(resourceUrl); diff --git a/ReactNativeClient/lib/components/CameraView.js b/ReactNativeClient/lib/components/CameraView.js index 489fd8e95..83ecbb1b8 100644 --- a/ReactNativeClient/lib/components/CameraView.js +++ b/ReactNativeClient/lib/components/CameraView.js @@ -107,10 +107,10 @@ class CameraView extends Component { } fitRectIntoBounds(rect, bounds) { - var rectRatio = rect.width / rect.height; - var boundsRatio = bounds.width / bounds.height; + const rectRatio = rect.width / rect.height; + const boundsRatio = bounds.width / bounds.height; - var newDimensions = {}; + const newDimensions = {}; // Rect is more landscape than bounds - fit to width if (rectRatio > boundsRatio) { diff --git a/ReactNativeClient/lib/components/ModalDialog.js b/ReactNativeClient/lib/components/ModalDialog.js index bb6a483f7..f2ae6fc9a 100644 --- a/ReactNativeClient/lib/components/ModalDialog.js +++ b/ReactNativeClient/lib/components/ModalDialog.js @@ -16,7 +16,7 @@ class ModalDialog extends React.Component { if (this.styles_[themeId]) return this.styles_[themeId]; this.styles_ = {}; - let styles = { + const styles = { modalWrapper: { flex: 1, justifyContent: 'center', diff --git a/ReactNativeClient/lib/components/action-button.js b/ReactNativeClient/lib/components/action-button.js index 9a192fdfb..d4f2a8848 100644 --- a/ReactNativeClient/lib/components/action-button.js +++ b/ReactNativeClient/lib/components/action-button.js @@ -56,7 +56,7 @@ class ActionButtonComponent extends React.Component { } render() { - let buttons = this.props.buttons ? this.props.buttons : []; + const buttons = this.props.buttons ? this.props.buttons : []; if (this.props.addFolderNoteButtons) { if (this.props.folders.length) { @@ -80,11 +80,11 @@ class ActionButtonComponent extends React.Component { } } - let buttonComps = []; + const buttonComps = []; for (let i = 0; i < buttons.length; i++) { - let button = buttons[i]; - let buttonTitle = button.title ? button.title : ''; - let key = `${buttonTitle.replace(/\s/g, '_')}_${button.icon}`; + const button = buttons[i]; + const buttonTitle = button.title ? button.title : ''; + const key = `${buttonTitle.replace(/\s/g, '_')}_${button.icon}`; buttonComps.push( @@ -96,14 +96,14 @@ class ActionButtonComponent extends React.Component { return ; } - let mainButton = this.props.mainButton ? this.props.mainButton : {}; - let mainIcon = mainButton.icon ? : ; + const mainButton = this.props.mainButton ? this.props.mainButton : {}; + const mainIcon = mainButton.icon ? : ; if (this.props.multiStates) { if (!this.props.buttons || !this.props.buttons.length) throw new Error('Multi-state button requires at least one state'); if (this.state.buttonIndex < 0 || this.state.buttonIndex >= this.props.buttons.length) throw new Error(`Button index out of bounds: ${this.state.buttonIndex}/${this.props.buttons.length}`); - let button = this.props.buttons[this.state.buttonIndex]; - let mainIcon = ; + const button = this.props.buttons[this.state.buttonIndex]; + const mainIcon = ; return ( ); @@ -408,7 +408,7 @@ class ScreenHeaderComponent extends React.PureComponent { /> ); } else { - let title = 'title' in this.props && this.props.title !== null ? this.props.title : ''; + const title = 'title' in this.props && this.props.title !== null ? this.props.title : ''; return {title}; } }; diff --git a/ReactNativeClient/lib/components/screens/NoteTagsDialog.js b/ReactNativeClient/lib/components/screens/NoteTagsDialog.js index 875ddf543..01b1b7468 100644 --- a/ReactNativeClient/lib/components/screens/NoteTagsDialog.js +++ b/ReactNativeClient/lib/components/screens/NoteTagsDialog.js @@ -122,7 +122,7 @@ class NoteTagsDialogComponent extends React.Component { if (this.styles_[themeId]) return this.styles_[themeId]; this.styles_ = {}; - let styles = { + const styles = { tag: { padding: 10, borderBottomWidth: 1, diff --git a/ReactNativeClient/lib/components/screens/config.js b/ReactNativeClient/lib/components/screens/config.js index 382142973..cc2206545 100644 --- a/ReactNativeClient/lib/components/screens/config.js +++ b/ReactNativeClient/lib/components/screens/config.js @@ -166,7 +166,7 @@ class ConfigScreenComponent extends BaseScreenComponent { if (this.styles_[themeId]) return this.styles_[themeId]; this.styles_ = {}; - let styles = { + const styles = { body: { flex: 1, justifyContent: 'flex-start', @@ -332,7 +332,7 @@ class ConfigScreenComponent extends BaseScreenComponent { settingToComponent(key, value) { const themeId = this.props.theme; const theme = themeStyle(themeId); - let output = null; + const output = null; const updateSettingValue = (key, value) => { return shared.updateSettingValue(this, key, value); @@ -344,9 +344,9 @@ class ConfigScreenComponent extends BaseScreenComponent { if (md.isEnum) { value = value.toString(); - let items = []; + const items = []; const settingOptions = md.options(); - for (let k in settingOptions) { + for (const k in settingOptions) { if (!settingOptions.hasOwnProperty(k)) continue; items.push({ label: settingOptions[k], value: k.toString() }); } diff --git a/ReactNativeClient/lib/components/screens/dropbox-login.js b/ReactNativeClient/lib/components/screens/dropbox-login.js index bb8b3caac..65b3e4a77 100644 --- a/ReactNativeClient/lib/components/screens/dropbox-login.js +++ b/ReactNativeClient/lib/components/screens/dropbox-login.js @@ -30,7 +30,7 @@ class DropboxLoginScreenComponent extends BaseScreenComponent { if (this.styles_[themeId]) return this.styles_[themeId]; this.styles_ = {}; - let styles = { + const styles = { container: { padding: theme.margin, }, diff --git a/ReactNativeClient/lib/components/screens/encryption-config.js b/ReactNativeClient/lib/components/screens/encryption-config.js index 383c5342b..ca8e10ebc 100644 --- a/ReactNativeClient/lib/components/screens/encryption-config.js +++ b/ReactNativeClient/lib/components/screens/encryption-config.js @@ -63,7 +63,7 @@ class EncryptionConfigScreenComponent extends BaseScreenComponent { if (this.styles_[themeId]) return this.styles_[themeId]; this.styles_ = {}; - let styles = { + const styles = { titleText: { flex: 1, fontWeight: 'bold', @@ -198,7 +198,7 @@ class EncryptionConfigScreenComponent extends BaseScreenComponent { const mkComps = []; - let nonExistingMasterKeyIds = this.props.notLoadedMasterKeys.slice(); + const nonExistingMasterKeyIds = this.props.notLoadedMasterKeys.slice(); for (let i = 0; i < masterKeys.length; i++) { const mk = masterKeys[i]; diff --git a/ReactNativeClient/lib/components/screens/folder.js b/ReactNativeClient/lib/components/screens/folder.js index 87f6111c0..8d046f701 100644 --- a/ReactNativeClient/lib/components/screens/folder.js +++ b/ReactNativeClient/lib/components/screens/folder.js @@ -30,7 +30,7 @@ class FolderScreenComponent extends BaseScreenComponent { if (this.styles_[this.props.theme]) return this.styles_[this.props.theme]; this.styles_ = {}; - let styles = { + const styles = { textInput: { color: theme.color, paddingLeft: theme.marginLeft, @@ -61,14 +61,14 @@ class FolderScreenComponent extends BaseScreenComponent { isModified() { if (!this.state.folder || !this.state.lastSavedFolder) return false; - let diff = BaseModel.diffObjects(this.state.folder, this.state.lastSavedFolder); + const diff = BaseModel.diffObjects(this.state.folder, this.state.lastSavedFolder); delete diff.type_; return !!Object.getOwnPropertyNames(diff).length; } folderComponent_change(propName, propValue) { this.setState((prevState) => { - let folder = Object.assign({}, prevState.folder); + const folder = Object.assign({}, prevState.folder); folder[propName] = propValue; return { folder: folder }; }); @@ -101,7 +101,7 @@ class FolderScreenComponent extends BaseScreenComponent { } render() { - let saveButtonDisabled = !this.isModified(); + const saveButtonDisabled = !this.isModified(); const theme = themeStyle(this.props.theme); return ( diff --git a/ReactNativeClient/lib/components/screens/log.js b/ReactNativeClient/lib/components/screens/log.js index 11e906804..8a89212c2 100644 --- a/ReactNativeClient/lib/components/screens/log.js +++ b/ReactNativeClient/lib/components/screens/log.js @@ -31,7 +31,7 @@ class LogScreenComponent extends BaseScreenComponent { if (this.styles_[this.props.theme]) return this.styles_[this.props.theme]; this.styles_ = {}; - let styles = { + const styles = { row: { flexDirection: 'row', paddingLeft: 1, @@ -81,7 +81,7 @@ class LogScreenComponent extends BaseScreenComponent { } render() { - let renderRow = ({ item }) => { + const renderRow = ({ item }) => { let textStyle = this.styles().rowText; if (item.level == Logger.LEVEL_WARN) textStyle = this.styles().rowTextWarn; if (item.level == Logger.LEVEL_ERROR) textStyle = this.styles().rowTextError; diff --git a/ReactNativeClient/lib/components/screens/note.js b/ReactNativeClient/lib/components/screens/note.js index 56b03fac4..c160335f9 100644 --- a/ReactNativeClient/lib/components/screens/note.js +++ b/ReactNativeClient/lib/components/screens/note.js @@ -82,7 +82,7 @@ class NoteScreenComponent extends BaseScreenComponent { const saveDialog = async () => { if (this.isModified()) { - let buttonId = await dialogs.pop(this, _('This note has been modified:'), [{ text: _('Save changes'), id: 'save' }, { text: _('Discard changes'), id: 'discard' }, { text: _('Cancel'), id: 'cancel' }]); + const buttonId = await dialogs.pop(this, _('This note has been modified:'), [{ text: _('Save changes'), id: 'save' }, { text: _('Discard changes'), id: 'discard' }, { text: _('Cancel'), id: 'cancel' }]); if (buttonId == 'cancel') return true; if (buttonId == 'save') await this.saveNoteButton_press(); @@ -205,7 +205,7 @@ class NoteScreenComponent extends BaseScreenComponent { if (this.styles_[cacheKey]) return this.styles_[cacheKey]; this.styles_ = {}; - let styles = { + const styles = { bodyTextInput: { flex: 1, paddingLeft: theme.marginLeft, @@ -344,13 +344,13 @@ class NoteScreenComponent extends BaseScreenComponent { } async deleteNote_onPress() { - let note = this.state.note; + const note = this.state.note; if (!note.id) return; - let ok = await dialogs.confirm(this, _('Delete note?')); + const ok = await dialogs.confirm(this, _('Delete note?')); if (!ok) return; - let folderId = note.parent_id; + const folderId = note.parent_id; await Note.delete(note.id); @@ -402,7 +402,7 @@ class NoteScreenComponent extends BaseScreenComponent { async resizeImage(localFilePath, targetPath, mimeType) { const maxSize = Resource.IMAGE_MAX_DIMENSION; - let dimensions = await this.imageDimensions(localFilePath); + const dimensions = await this.imageDimensions(localFilePath); reg.logger().info('Original dimensions ', dimensions); if (dimensions.width > maxSize || dimensions.height > maxSize) { @@ -476,7 +476,7 @@ class NoteScreenComponent extends BaseScreenComponent { if (!resource.mime) resource.mime = 'application/octet-stream'; - let targetPath = Resource.fullPath(resource); + const targetPath = Resource.fullPath(resource); try { if (mimeType == 'image/jpeg' || mimeType == 'image/jpg' || mimeType == 'image/png') { @@ -580,7 +580,7 @@ class NoteScreenComponent extends BaseScreenComponent { } async onAlarmDialogAccept(date) { - let newNote = Object.assign({}, this.state.note); + const newNote = Object.assign({}, this.state.note); newNote.todo_due = date ? date.getTime() : 0; await this.saveOneProperty('todo_due', date ? date.getTime() : 0); @@ -595,7 +595,7 @@ class NoteScreenComponent extends BaseScreenComponent { async showOnMap_onPress() { if (!this.state.note.id) return; - let note = await Note.load(this.state.note.id); + const note = await Note.load(this.state.note.id); try { const url = Note.geolocationUrl(note); Linking.openURL(url); @@ -608,7 +608,7 @@ class NoteScreenComponent extends BaseScreenComponent { async showSource_onPress() { if (!this.state.note.id) return; - let note = await Note.load(this.state.note.id); + const note = await Note.load(this.state.note.id); try { Linking.openURL(note.source_url); } catch (error) { @@ -661,7 +661,7 @@ class NoteScreenComponent extends BaseScreenComponent { if (this.menuOptionsCache_[cacheKey]) return this.menuOptionsCache_[cacheKey]; - let output = []; + const output = []; // The file attachement modules only work in Android >= 5 (Version 21) // https://github.com/react-community/react-native-image-picker/issues/606 @@ -741,7 +741,7 @@ class NoteScreenComponent extends BaseScreenComponent { titleTextInput_contentSizeChange(event) { if (!this.enableMultilineTitle_) return; - let height = event.nativeEvent.contentSize.height; + const height = event.nativeEvent.contentSize.height; this.setState({ titleTextInputHeight: height }); } @@ -866,7 +866,7 @@ class NoteScreenComponent extends BaseScreenComponent { } const renderActionButton = () => { - let buttons = []; + const buttons = []; buttons.push({ title: _('Edit'), @@ -885,8 +885,8 @@ class NoteScreenComponent extends BaseScreenComponent { const actionButtonComp = renderActionButton(); - let showSaveButton = this.state.mode == 'edit' || this.isModified() || this.saveButtonHasBeenShown_; - let saveButtonDisabled = !this.isModified(); + const showSaveButton = this.state.mode == 'edit' || this.isModified() || this.saveButtonHasBeenShown_; + const saveButtonDisabled = !this.isModified(); if (showSaveButton) this.saveButtonHasBeenShown_ = true; diff --git a/ReactNativeClient/lib/components/screens/notes.js b/ReactNativeClient/lib/components/screens/notes.js index e18cfe523..bf54e0c2b 100644 --- a/ReactNativeClient/lib/components/screens/notes.js +++ b/ReactNativeClient/lib/components/screens/notes.js @@ -26,7 +26,7 @@ class NotesScreenComponent extends BaseScreenComponent { this.onAppStateChange_ = async () => { // Force an update to the notes list when app state changes - let newProps = Object.assign({}, this.props); + const newProps = Object.assign({}, this.props); newProps.notesSource = ''; await this.refreshNotes(newProps); }; @@ -40,7 +40,7 @@ class NotesScreenComponent extends BaseScreenComponent { return (selected ? `${s} ` : '') + label; }; - for (let field in sortNoteOptions) { + for (const field in sortNoteOptions) { if (!sortNoteOptions.hasOwnProperty(field)) continue; buttons.push({ text: makeCheckboxText(Setting.value('notes.sortOrder.field') === field, 'bullet', sortNoteOptions[field]), @@ -78,7 +78,7 @@ class NotesScreenComponent extends BaseScreenComponent { if (this.styles_[cacheKey]) return this.styles_[cacheKey]; this.styles_ = {}; - let styles = { + const styles = { noteList: { flex: 1, }, @@ -106,7 +106,7 @@ class NotesScreenComponent extends BaseScreenComponent { async refreshNotes(props = null) { if (props === null) props = this.props; - let options = { + const options = { order: props.notesOrder, uncompletedTodosOnTop: props.uncompletedTodosOnTop, showCompletedTodos: props.showCompletedTodos, @@ -198,7 +198,7 @@ class NotesScreenComponent extends BaseScreenComponent { const parent = this.parentItem(); const theme = themeStyle(this.props.theme); - let rootStyle = { + const rootStyle = { flex: 1, backgroundColor: theme.backgroundColor, }; @@ -207,7 +207,7 @@ class NotesScreenComponent extends BaseScreenComponent { rootStyle.flex = 0.001; // This is a bit of a hack but it seems to work fine - it makes the component invisible but without unmounting it } - let title = parent ? parent.title : null; + const title = parent ? parent.title : null; if (!parent) { return ( diff --git a/ReactNativeClient/lib/components/screens/search.js b/ReactNativeClient/lib/components/screens/search.js index 5aa4f4661..5051edd89 100644 --- a/ReactNativeClient/lib/components/screens/search.js +++ b/ReactNativeClient/lib/components/screens/search.js @@ -35,7 +35,7 @@ class SearchScreenComponent extends BaseScreenComponent { if (this.styles_[this.props.theme]) return this.styles_[this.props.theme]; this.styles_ = {}; - let styles = { + const styles = { body: { flex: 1, }, @@ -118,10 +118,10 @@ class SearchScreenComponent extends BaseScreenComponent { if (this.props.settings['db.ftsEnabled']) { notes = await SearchEngineUtils.notesForQuery(query); } else { - let p = query.split(' '); - let temp = []; + const p = query.split(' '); + const temp = []; for (let i = 0; i < p.length; i++) { - let t = p[i].trim(); + const t = p[i].trim(); if (!t) continue; temp.push(t); } @@ -146,7 +146,7 @@ class SearchScreenComponent extends BaseScreenComponent { const theme = themeStyle(this.props.theme); - let rootStyle = { + const rootStyle = { flex: 1, backgroundColor: theme.backgroundColor, }; diff --git a/ReactNativeClient/lib/components/screens/status.js b/ReactNativeClient/lib/components/screens/status.js index e1538132f..3a56b2b48 100644 --- a/ReactNativeClient/lib/components/screens/status.js +++ b/ReactNativeClient/lib/components/screens/status.js @@ -33,8 +33,8 @@ class StatusScreenComponent extends BaseScreenComponent { } async resfreshScreen() { - let service = new ReportService(); - let report = await service.status(Setting.value('sync.target')); + const service = new ReportService(); + const report = await service.status(Setting.value('sync.target')); this.setState({ report: report }); } @@ -42,7 +42,7 @@ class StatusScreenComponent extends BaseScreenComponent { const theme = themeStyle(this.props.theme); const renderBody = report => { - let baseStyle = { + const baseStyle = { paddingLeft: 6, paddingRight: 6, paddingTop: 2, @@ -52,17 +52,17 @@ class StatusScreenComponent extends BaseScreenComponent { fontSize: theme.fontSize, }; - let lines = []; + const lines = []; for (let i = 0; i < report.length; i++) { - let section = report[i]; + const section = report[i]; let style = Object.assign({}, baseStyle); style.fontWeight = 'bold'; if (i > 0) style.paddingTop = 20; lines.push({ key: `section_${i}`, isSection: true, text: section.title }); - for (let n in section.body) { + for (const n in section.body) { if (!section.body.hasOwnProperty(n)) continue; style = Object.assign({}, baseStyle); const item = section.body[n]; @@ -92,7 +92,7 @@ class StatusScreenComponent extends BaseScreenComponent { { - let style = Object.assign({}, baseStyle); + const style = Object.assign({}, baseStyle); if (item.isSection === true) { style.fontWeight = 'bold'; @@ -122,7 +122,7 @@ class StatusScreenComponent extends BaseScreenComponent { ); }; - let body = renderBody(this.state.report); + const body = renderBody(this.state.report); return ( diff --git a/ReactNativeClient/lib/components/screens/tags.js b/ReactNativeClient/lib/components/screens/tags.js index a24645cee..d66fc550f 100644 --- a/ReactNativeClient/lib/components/screens/tags.js +++ b/ReactNativeClient/lib/components/screens/tags.js @@ -91,7 +91,7 @@ class TagsScreenComponent extends BaseScreenComponent { render() { const theme = themeStyle(this.props.theme); - let rootStyle = { + const rootStyle = { flex: 1, backgroundColor: theme.backgroundColor, }; diff --git a/ReactNativeClient/lib/components/shared/config-shared.js b/ReactNativeClient/lib/components/shared/config-shared.js index a1fd856a2..614257c07 100644 --- a/ReactNativeClient/lib/components/shared/config-shared.js +++ b/ReactNativeClient/lib/components/shared/config-shared.js @@ -93,7 +93,7 @@ shared.updateSettingValue = function(comp, key, value) { }; shared.saveSettings = function(comp) { - for (let key in comp.state.settings) { + for (const key in comp.state.settings) { if (!comp.state.settings.hasOwnProperty(key)) continue; if (comp.state.changedSettingKeys.indexOf(key) < 0) continue; console.info('Saving', key, comp.state.settings[key]); diff --git a/ReactNativeClient/lib/components/shared/note-screen-shared.js b/ReactNativeClient/lib/components/shared/note-screen-shared.js index 82482b290..02b9c5dfd 100644 --- a/ReactNativeClient/lib/components/shared/note-screen-shared.js +++ b/ReactNativeClient/lib/components/shared/note-screen-shared.js @@ -90,7 +90,7 @@ shared.saveNoteButton_press = async function(comp, folderId = null, options = nu note.body = stateNote.body; } - let newState = { + const newState = { lastSavedNote: Object.assign({}, note), note: note, }; @@ -144,9 +144,9 @@ shared.saveOneProperty = async function(comp, name, value) { }; shared.noteComponent_change = function(comp, propName, propValue) { - let newState = {}; + const newState = {}; - let note = Object.assign({}, comp.state.note); + const note = Object.assign({}, comp.state.note); note[propName] = propValue; newState.note = note; @@ -189,7 +189,7 @@ shared.attachedResources = async function(noteBody) { shared.isModified = function(comp) { if (!comp.state.note || !comp.state.lastSavedNote) return false; - let diff = BaseModel.diffObjects(comp.state.lastSavedNote, comp.state.note); + const diff = BaseModel.diffObjects(comp.state.lastSavedNote, comp.state.note); delete diff.type_; return !!Object.getOwnPropertyNames(diff).length; }; @@ -227,13 +227,13 @@ shared.initState = async function(comp) { }; shared.toggleIsTodo_onPress = function(comp) { - let newNote = Note.toggleIsTodo(comp.state.note); - let newState = { note: newNote }; + const newNote = Note.toggleIsTodo(comp.state.note); + const newState = { note: newNote }; comp.setState(newState); }; shared.toggleCheckbox = function(ipcMessage, noteBody) { - let newBody = noteBody.split('\n'); + const newBody = noteBody.split('\n'); const p = ipcMessage.split(':'); const lineIndex = Number(p[p.length - 1]); if (lineIndex >= newBody.length) { diff --git a/ReactNativeClient/lib/components/shared/side-menu-shared.js b/ReactNativeClient/lib/components/shared/side-menu-shared.js index 793ea9ca8..5de8d7675 100644 --- a/ReactNativeClient/lib/components/shared/side-menu-shared.js +++ b/ReactNativeClient/lib/components/shared/side-menu-shared.js @@ -1,11 +1,11 @@ const Folder = require('lib/models/Folder'); const BaseModel = require('lib/BaseModel'); -let shared = {}; +const shared = {}; function folderHasChildren_(folders, folderId) { for (let i = 0; i < folders.length; i++) { - let folder = folders[i]; + const folder = folders[i]; if (folder.parent_id === folderId) return true; } return false; @@ -15,7 +15,7 @@ function folderIsVisible(folders, folderId, collapsedFolderIds) { if (!collapsedFolderIds || !collapsedFolderIds.length) return true; while (true) { - let folder = BaseModel.byId(folders, folderId); + const folder = BaseModel.byId(folders, folderId); if (!folder) throw new Error(`No folder with id ${folder.id}`); if (!folder.parent_id) return true; if (collapsedFolderIds.indexOf(folder.parent_id) >= 0) return false; @@ -26,7 +26,7 @@ function folderIsVisible(folders, folderId, collapsedFolderIds) { function renderFoldersRecursive_(props, renderItem, items, parentId, depth, order) { const folders = props.folders; for (let i = 0; i < folders.length; i++) { - let folder = folders[i]; + const folder = folders[i]; if (!Folder.idsEqual(folder.parent_id, parentId)) continue; if (!folderIsVisible(props.folders, folder.id, props.collapsedFolderIds)) continue; const hasChildren = folderHasChildren_(folders, folder.id); @@ -49,11 +49,11 @@ shared.renderFolders = function(props, renderItem) { }; shared.renderTags = function(props, renderItem) { - let tags = props.tags.slice(); + const tags = props.tags.slice(); tags.sort((a, b) => { return a.title < b.title ? -1 : +1; }); - let tagItems = []; + const tagItems = []; const order = []; for (let i = 0; i < tags.length; i++) { const tag = tags[i]; diff --git a/ReactNativeClient/lib/components/side-menu-content-note.js b/ReactNativeClient/lib/components/side-menu-content-note.js index 28f42b66a..7555de3e4 100644 --- a/ReactNativeClient/lib/components/side-menu-content-note.js +++ b/ReactNativeClient/lib/components/side-menu-content-note.js @@ -20,7 +20,7 @@ class SideMenuContentNoteComponent extends Component { if (this.styles_[this.props.theme]) return this.styles_[this.props.theme]; this.styles_ = {}; - let styles = { + const styles = { menu: { flex: 1, backgroundColor: theme.backgroundColor, @@ -73,7 +73,7 @@ class SideMenuContentNoteComponent extends Component { render() { const theme = themeStyle(this.props.theme); - let items = []; + const items = []; const options = this.props.options ? this.props.options : []; let dividerIndex = 0; @@ -86,7 +86,7 @@ class SideMenuContentNoteComponent extends Component { } } - let style = { + const style = { flex: 1, borderRightWidth: 1, borderRightColor: globalStyle.dividerColor, diff --git a/ReactNativeClient/lib/components/side-menu-content.js b/ReactNativeClient/lib/components/side-menu-content.js index 4175955a3..34affcaa4 100644 --- a/ReactNativeClient/lib/components/side-menu-content.js +++ b/ReactNativeClient/lib/components/side-menu-content.js @@ -40,7 +40,7 @@ class SideMenuContentComponent extends Component { if (this.styles_[this.props.theme]) return this.styles_[this.props.theme]; this.styles_ = {}; - let styles = { + const styles = { menu: { flex: 1, backgroundColor: theme.backgroundColor, @@ -316,7 +316,7 @@ class SideMenuContentComponent extends Component { items.push(this.makeDivider('divider_2')); - let lines = Synchronizer.reportToLines(this.props.syncReport); + const lines = Synchronizer.reportToLines(this.props.syncReport); const syncReportText = lines.join('\n'); let decryptionReportText = ''; @@ -329,7 +329,7 @@ class SideMenuContentComponent extends Component { resourceFetcherText = _('Fetching resources: %d/%d', this.props.resourceFetcher.fetchingCount, this.props.resourceFetcher.toFetchCount); } - let fullReport = []; + const fullReport = []; if (syncReportText) fullReport.push(syncReportText); if (resourceFetcherText) fullReport.push(resourceFetcherText); if (decryptionReportText) fullReport.push(decryptionReportText); @@ -367,7 +367,7 @@ class SideMenuContentComponent extends Component { items = items.concat(folderItems); } - let style = { + const style = { flex: 1, borderRightWidth: 1, borderRightColor: globalStyle.dividerColor, diff --git a/ReactNativeClient/lib/database-driver-node.js b/ReactNativeClient/lib/database-driver-node.js index d2b9d6c63..e8015af88 100644 --- a/ReactNativeClient/lib/database-driver-node.js +++ b/ReactNativeClient/lib/database-driver-node.js @@ -15,10 +15,10 @@ class DatabaseDriverNode { } sqliteErrorToJsError(error, sql = null, params = null) { - let msg = [error.toString()]; + const msg = [error.toString()]; if (sql) msg.push(sql); if (params) msg.push(params); - let output = new Error(msg.join(': ')); + const output = new Error(msg.join(': ')); if (error.code) output.code = error.code; return output; } diff --git a/ReactNativeClient/lib/database-driver-react-native.js b/ReactNativeClient/lib/database-driver-react-native.js index 3fc14c84f..8b9744a05 100644 --- a/ReactNativeClient/lib/database-driver-react-native.js +++ b/ReactNativeClient/lib/database-driver-react-native.js @@ -42,7 +42,7 @@ class DatabaseDriverReactNative { selectAll(sql, params = null) { return this.exec(sql, params).then(r => { - let output = []; + const output = []; for (let i = 0; i < r.rows.length; i++) { output.push(r.rows.item(i)); } diff --git a/ReactNativeClient/lib/database.js b/ReactNativeClient/lib/database.js index 278afd042..c7ad38a6a 100644 --- a/ReactNativeClient/lib/database.js +++ b/ReactNativeClient/lib/database.js @@ -46,7 +46,7 @@ class Database { escapeField(field) { if (field == '*') return '*'; - let p = field.split('.'); + const p = field.split('.'); if (p.length == 1) return `\`${field}\``; if (p.length == 2) return `${p[0]}.\`${p[1]}\``; @@ -56,7 +56,7 @@ class Database { escapeFields(fields) { if (fields == '*') return '*'; - let output = []; + const output = []; for (let i = 0; i < fields.length; i++) { output.push(this.escapeField(fields[i])); } @@ -74,7 +74,7 @@ class Database { while (true) { try { this.logQuery(sql, params); - let result = await this.driver()[callName](sql, params); + const result = await this.driver()[callName](sql, params); return result; // No exception was thrown } catch (error) { if (error && (error.code == 'SQLITE_IOERR' || error.code == 'SQLITE_BUSY')) { @@ -120,7 +120,7 @@ class Database { if (queries.length <= 0) return; if (queries.length == 1) { - let q = this.wrapQuery(queries[0]); + const q = this.wrapQuery(queries[0]); await this.exec(q.sql, q.params); return; } @@ -132,7 +132,7 @@ class Database { await this.exec('BEGIN TRANSACTION'); for (let i = 0; i < queries.length; i++) { - let query = this.wrapQuery(queries[i]); + const query = this.wrapQuery(queries[i]); await this.exec(query.sql, query.params); } @@ -183,11 +183,11 @@ class Database { } sqlStringToLines(sql) { - let output = []; - let lines = sql.split('\n'); + const output = []; + const lines = sql.split('\n'); let statement = ''; - for (var i = 0; i < lines.length; i++) { - var line = lines[i]; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; if (line == '') continue; if (line.substr(0, 2) == '--') continue; statement += line.trim(); @@ -217,8 +217,8 @@ class Database { let keySql = ''; let valueSql = ''; - let params = []; - for (let key in data) { + const params = []; + for (const key in data) { if (!data.hasOwnProperty(key)) continue; if (key[key.length - 1] == '_') continue; if (keySql != '') keySql += ', '; @@ -237,8 +237,8 @@ class Database { if (!data || !Object.keys(data).length) throw new Error('Data is empty'); let sql = ''; - let params = []; - for (let key in data) { + const params = []; + for (const key in data) { if (!data.hasOwnProperty(key)) continue; if (key[key.length - 1] == '_') continue; if (sql != '') sql += ', '; @@ -247,8 +247,8 @@ class Database { } if (typeof where != 'string') { - let s = []; - for (let n in where) { + const s = []; + for (const n in where) { if (!where.hasOwnProperty(n)) continue; params.push(where[n]); s.push(`\`${n}\`=?`); @@ -263,14 +263,14 @@ class Database { } alterColumnQueries(tableName, fields) { - let fieldsNoType = []; - for (let n in fields) { + const fieldsNoType = []; + for (const n in fields) { if (!fields.hasOwnProperty(n)) continue; fieldsNoType.push(n); } - let fieldsWithType = []; - for (let n in fields) { + const fieldsWithType = []; + for (const n in fields) { if (!fields.hasOwnProperty(n)) continue; fieldsWithType.push(`${this.escapeField(n)} ${fields[n]}`); } @@ -293,7 +293,7 @@ class Database { } wrapQueries(queries) { - let output = []; + const output = []; for (let i = 0; i < queries.length; i++) { output.push(this.wrapQuery(queries[i])); } @@ -304,7 +304,7 @@ class Database { if (!sql) throw new Error(`Cannot wrap empty string: ${sql}`); if (sql.constructor === Array) { - let output = {}; + const output = {}; output.sql = sql[0]; output.params = sql.length >= 2 ? sql[1] : null; return output; diff --git a/ReactNativeClient/lib/dialogs.js b/ReactNativeClient/lib/dialogs.js index ef240b3e9..48bfe0f77 100644 --- a/ReactNativeClient/lib/dialogs.js +++ b/ReactNativeClient/lib/dialogs.js @@ -5,7 +5,7 @@ const { Keyboard } = require('react-native'); // // { this.dialogbox = dialogbox }}/> -let dialogs = {}; +const dialogs = {}; dialogs.confirm = (parentComponent, message) => { if (!parentComponent) throw new Error('parentComponent is required'); @@ -42,7 +42,7 @@ dialogs.pop = (parentComponent, message, buttons, options = null) => { return new Promise((resolve) => { Keyboard.dismiss(); - let btns = []; + const btns = []; for (let i = 0; i < buttons.length; i++) { btns.push({ text: buttons[i].text, diff --git a/ReactNativeClient/lib/file-api-driver-local.js b/ReactNativeClient/lib/file-api-driver-local.js index 95eaae8f0..8393f623a 100644 --- a/ReactNativeClient/lib/file-api-driver-local.js +++ b/ReactNativeClient/lib/file-api-driver-local.js @@ -17,7 +17,7 @@ class FileApiDriverLocal { fsErrorToJsError_(error, path = null) { let msg = error.toString(); if (path !== null) msg += `. Path: ${path}`; - let output = new Error(msg); + const output = new Error(msg); if (error.code) output.code = error.code; return output; } @@ -47,7 +47,7 @@ class FileApiDriverLocal { } metadataFromStats_(stats) { - let output = []; + const output = []; for (let i = 0; i < stats.length; i++) { const mdStat = this.metadataFromStat_(stats[i]); output.push(mdStat); diff --git a/ReactNativeClient/lib/file-api-driver-memory.js b/ReactNativeClient/lib/file-api-driver-memory.js index 31c4203cf..762a81e0c 100644 --- a/ReactNativeClient/lib/file-api-driver-memory.js +++ b/ReactNativeClient/lib/file-api-driver-memory.js @@ -28,12 +28,12 @@ class FileApiDriverMemory { } itemByPath(path) { - let index = this.itemIndexByPath(path); + const index = this.itemIndexByPath(path); return index < 0 ? null : this.items_[index]; } newItem(path, isDir = false) { - let now = time.unixMs(); + const now = time.unixMs(); return { path: path, isDir: isDir, @@ -44,26 +44,26 @@ class FileApiDriverMemory { } stat(path) { - let item = this.itemByPath(path); + const item = this.itemByPath(path); return Promise.resolve(item ? Object.assign({}, item) : null); } async setTimestamp(path, timestampMs) { - let item = this.itemByPath(path); + const item = this.itemByPath(path); if (!item) return Promise.reject(new Error(`File not found: ${path}`)); item.updated_time = timestampMs; } async list(path) { - let output = []; + const output = []; for (let i = 0; i < this.items_.length; i++) { - let item = this.items_[i]; + const item = this.items_[i]; if (item.path == path) continue; if (item.path.indexOf(`${path}/`) === 0) { - let s = item.path.substr(path.length + 1); + const s = item.path.substr(path.length + 1); if (s.split('/').length === 1) { - let it = Object.assign({}, item); + const it = Object.assign({}, item); it.path = it.path.substr(path.length + 1); output.push(it); } @@ -78,7 +78,7 @@ class FileApiDriverMemory { } async get(path, options) { - let item = this.itemByPath(path); + const item = this.itemByPath(path); if (!item) return Promise.resolve(null); if (item.isDir) return Promise.reject(new Error(`${path} is a directory, not a file`)); @@ -94,7 +94,7 @@ class FileApiDriverMemory { } async mkdir(path) { - let index = this.itemIndexByPath(path); + const index = this.itemIndexByPath(path); if (index >= 0) return; this.items_.push(this.newItem(path, true)); } @@ -104,9 +104,9 @@ class FileApiDriverMemory { if (options.source === 'file') content = await fs.readFile(options.path); - let index = this.itemIndexByPath(path); + const index = this.itemIndexByPath(path); if (index < 0) { - let item = this.newItem(path, false); + const item = this.newItem(path, false); item.content = this.encodeContent_(content); this.items_.push(item); } else { @@ -116,9 +116,9 @@ class FileApiDriverMemory { } async delete(path) { - let index = this.itemIndexByPath(path); + const index = this.itemIndexByPath(path); if (index >= 0) { - let item = Object.assign({}, this.items_[index]); + const item = Object.assign({}, this.items_[index]); item.isDeleted = true; item.updated_time = time.unixMs(); this.deletedItems_.push(item); @@ -127,7 +127,7 @@ class FileApiDriverMemory { } async move(oldPath, newPath) { - let sourceItem = this.itemByPath(oldPath); + const sourceItem = this.itemByPath(oldPath); if (!sourceItem) return Promise.reject(new Error(`Path not found: ${oldPath}`)); this.delete(newPath); // Overwrite if newPath already exists sourceItem.path = newPath; @@ -139,7 +139,7 @@ class FileApiDriverMemory { async delta(path, options = null) { const getStatFn = async path => { - let output = this.items_.slice(); + const output = this.items_.slice(); for (let i = 0; i < output.length; i++) { const item = Object.assign({}, output[i]); item.path = item.path.substr(path.length + 1); diff --git a/ReactNativeClient/lib/file-api-driver-onedrive.js b/ReactNativeClient/lib/file-api-driver-onedrive.js index ce4cb7885..a1c54354e 100644 --- a/ReactNativeClient/lib/file-api-driver-onedrive.js +++ b/ReactNativeClient/lib/file-api-driver-onedrive.js @@ -22,7 +22,7 @@ class FileApiDriverOneDrive { } makeItems_(odItems) { - let output = []; + const output = []; for (let i = 0; i < odItems.length; i++) { output.push(this.makeItem_(odItems[i])); } @@ -30,7 +30,7 @@ class FileApiDriverOneDrive { } makeItem_(odItem) { - let output = { + const output = { path: odItem.name, isDir: 'folder' in odItem, }; @@ -57,13 +57,13 @@ class FileApiDriverOneDrive { } async stat(path) { - let item = await this.statRaw_(path); + const item = await this.statRaw_(path); if (!item) return null; return this.makeItem_(item); } async setTimestamp(path, timestamp) { - let body = { + const body = { fileSystemInfo: { lastModifiedDateTime: `${moment @@ -72,7 +72,7 @@ class FileApiDriverOneDrive { .format('YYYY-MM-DDTHH:mm:ss.SSS')}Z`, }, }; - let item = await this.api_.execJson('PATCH', this.makePath_(path), null, body); + const item = await this.api_.execJson('PATCH', this.makePath_(path), null, body); return this.makeItem_(item); } @@ -85,7 +85,7 @@ class FileApiDriverOneDrive { url = options.context; } - let r = await this.api_.execJson('GET', url, query); + const r = await this.api_.execJson('GET', url, query); return { hasMore: !!r['@odata.nextLink'], @@ -99,10 +99,10 @@ class FileApiDriverOneDrive { try { if (options.target == 'file') { - let response = await this.api_.exec('GET', `${this.makePath_(path)}:/content`, null, null, options); + const response = await this.api_.exec('GET', `${this.makePath_(path)}:/content`, null, null, options); return response; } else { - let content = await this.api_.execText('GET', `${this.makePath_(path)}:/content`); + const content = await this.api_.execText('GET', `${this.makePath_(path)}:/content`); return content; } } catch (error) { @@ -115,7 +115,7 @@ class FileApiDriverOneDrive { let item = await this.stat(path); if (item) return item; - let parentPath = dirname(path); + const parentPath = dirname(path); item = await this.api_.execJson('POST', `${this.makePath_(parentPath)}:/children`, this.itemFilter_(), { name: basename(path), folder: {}, @@ -185,7 +185,7 @@ class FileApiDriverOneDrive { async pathDetails_(path) { if (this.pathCache_[path]) return this.pathCache_[path]; - let output = await this.api_.execJson('GET', path); + const output = await this.api_.execJson('GET', path); this.pathCache_[path] = output; return this.pathCache_[path]; } @@ -195,7 +195,7 @@ class FileApiDriverOneDrive { } async delta(path, options = null) { - let output = { + const output = { hasMore: false, context: {}, items: [], @@ -211,7 +211,7 @@ class FileApiDriverOneDrive { const pathDetails = await this.pathDetails_(path); const pathId = pathDetails.id; - let context = options ? options.context : null; + const context = options ? options.context : null; let url = context ? context.nextLink : null; let query = null; @@ -248,7 +248,7 @@ class FileApiDriverOneDrive { } } - let items = []; + const items = []; // The delta API might return things that happen in subdirectories of the root and we don't want to // deal with these since all the files we're interested in are at the root (The .resource dir @@ -282,10 +282,10 @@ class FileApiDriverOneDrive { // https://dev.onedrive.com/items/view_delta.htm // The same item may appear more than once in a delta feed, for various reasons. You should use the last occurrence you see. // So remove any duplicate item from the array. - let temp = []; - let seenPaths = []; + const temp = []; + const seenPaths = []; for (let i = output.items.length - 1; i >= 0; i--) { - let item = output.items[i]; + const item = output.items[i]; if (seenPaths.indexOf(item.path) >= 0) continue; temp.splice(0, 0, item); seenPaths.push(item.path); diff --git a/ReactNativeClient/lib/file-api-driver-webdav.js b/ReactNativeClient/lib/file-api-driver-webdav.js index 14d4cc322..f43ec498d 100644 --- a/ReactNativeClient/lib/file-api-driver-webdav.js +++ b/ReactNativeClient/lib/file-api-driver-webdav.js @@ -115,7 +115,7 @@ class FileApiDriverWebDav { statsFromResources_(resources) { const relativeBaseUrl = this.api().relativeBaseUrl(); const baseUrl = this.api().baseUrl(); - let output = []; + const output = []; for (let i = 0; i < resources.length; i++) { const resource = resources[i]; const href = this.api().stringFromJson(resource, ['d:href', 0]); diff --git a/ReactNativeClient/lib/file-api.js b/ReactNativeClient/lib/file-api.js index 821ce8dc8..754960090 100644 --- a/ReactNativeClient/lib/file-api.js +++ b/ReactNativeClient/lib/file-api.js @@ -116,7 +116,7 @@ class FileApi { } fullPath_(path) { - let output = []; + const output = []; if (this.baseDir()) output.push(this.baseDir()); if (path) output.push(path); return output.join('/'); @@ -134,7 +134,7 @@ class FileApi { const result = await tryAndRepeat(() => this.driver_.list(this.fullPath_(path), options), this.requestRepeatCount()); if (!options.includeHidden) { - let temp = []; + const temp = []; for (let i = 0; i < result.items.length; i++) { if (!isHidden(result.items[i].path)) temp.push(result.items[i]); } @@ -216,7 +216,7 @@ class FileApi { } function basicDeltaContextFromOptions_(options) { - let output = { + const output = { timestamp: 0, filesAtTimestamp: [], statsCache: null, @@ -254,7 +254,7 @@ async function basicDelta(path, getDirStatFn, options) { logger.warn('BasicDelta: Sync will continue but it is likely that nothing will be synced'); } - let newContext = { + const newContext = { timestamp: context.timestamp, filesAtTimestamp: context.filesAtTimestamp.slice(), statsCache: context.statsCache, @@ -327,7 +327,7 @@ async function basicDelta(path, getDirStatFn, options) { // we have to the items on the target. // Note that when deleted items are processed it might result in the output having // more items than outputLimit. This is acceptable since delete operations are cheap. - let deletedItems = []; + const deletedItems = []; for (let i = 0; i < itemIds.length; i++) { const itemId = itemIds[i]; diff --git a/ReactNativeClient/lib/fs-driver-base.js b/ReactNativeClient/lib/fs-driver-base.js index cb8a491dd..5c131d8a4 100644 --- a/ReactNativeClient/lib/fs-driver-base.js +++ b/ReactNativeClient/lib/fs-driver-base.js @@ -29,7 +29,7 @@ class FsDriverBase { } let counter = 1; - let nameNoExt = filename(name, true); + const nameNoExt = filename(name, true); let extension = fileExtension(name); if (extension) extension = `.${extension}`; let nameToTry = nameNoExt + extension; diff --git a/ReactNativeClient/lib/fs-driver-node.js b/ReactNativeClient/lib/fs-driver-node.js index d939f62cc..a6b75e562 100644 --- a/ReactNativeClient/lib/fs-driver-node.js +++ b/ReactNativeClient/lib/fs-driver-node.js @@ -6,7 +6,7 @@ class FsDriverNode extends FsDriverBase { fsErrorToJsError_(error, path = null) { let msg = error.toString(); if (path !== null) msg += `. Path: ${path}`; - let output = new Error(msg); + const output = new Error(msg); if (error.code) output.code = error.code; return output; } @@ -26,7 +26,7 @@ class FsDriverNode extends FsDriverBase { async writeBinaryFile(path, content) { try { // let buffer = new Buffer(content); - let buffer = Buffer.from(content); + const buffer = Buffer.from(content); return await fs.writeFile(path, buffer); } catch (error) { throw this.fsErrorToJsError_(error, path); @@ -125,7 +125,7 @@ class FsDriverNode extends FsDriverBase { let output = []; for (let i = 0; i < items.length; i++) { const item = items[i]; - let stat = await this.stat(`${path}/${item}`); + const stat = await this.stat(`${path}/${item}`); if (!stat) continue; // Has been deleted between the readdir() call and now stat.path = stat.path.substr(path.length + 1); output.push(stat); diff --git a/ReactNativeClient/lib/fs-driver-rn.js b/ReactNativeClient/lib/fs-driver-rn.js index 7755a3829..e7bce9c31 100644 --- a/ReactNativeClient/lib/fs-driver-rn.js +++ b/ReactNativeClient/lib/fs-driver-rn.js @@ -151,7 +151,7 @@ class FsDriverRN extends FsDriverBase { } if (!length) return null; - let output = await RNFS.read(handle.path, length, handle.offset, encoding); + const output = await RNFS.read(handle.path, length, handle.offset, encoding); // eslint-disable-next-line require-atomic-updates handle.offset += length; return output ? output : null; diff --git a/ReactNativeClient/lib/import-enex-html-gen.js b/ReactNativeClient/lib/import-enex-html-gen.js index d185a189c..93b675d9e 100644 --- a/ReactNativeClient/lib/import-enex-html-gen.js +++ b/ReactNativeClient/lib/import-enex-html-gen.js @@ -36,8 +36,8 @@ function addResourceTag(lines, resource, attributes) { function attributeToLowerCase(node) { if (!node.attributes) return {}; - let output = {}; - for (let n in node.attributes) { + const output = {}; + for (const n in node.attributes) { if (!node.attributes.hasOwnProperty(n)) continue; output[n.toLowerCase()] = node.attributes[n]; } @@ -45,7 +45,7 @@ function attributeToLowerCase(node) { } function enexXmlToHtml_(stream, resources) { - let remainingResources = resources.slice(); + const remainingResources = resources.slice(); const removeRemainingResource = id => { for (let i = 0; i < remainingResources.length; i++) { @@ -59,9 +59,9 @@ function enexXmlToHtml_(stream, resources) { return new Promise((resolve, reject) => { const options = {}; const strict = false; - var saxStream = require('sax').createStream(strict, options); + const saxStream = require('sax').createStream(strict, options); - let section = { + const section = { type: 'text', lines: [], parent: null, @@ -87,7 +87,7 @@ function enexXmlToHtml_(stream, resources) { let resource = null; for (let i = 0; i < resources.length; i++) { - let r = resources[i]; + const r = resources[i]; if (r.id == hash) { resource = r; removeRemainingResource(r.id); @@ -99,7 +99,7 @@ function enexXmlToHtml_(stream, resources) { // TODO: Extract this duplicate of code in ./import-enex-md-gen.js let found = false; for (let i = 0; i < remainingResources.length; i++) { - let r = remainingResources[i]; + const r = remainingResources[i]; if (!r.id) { resource = Object.assign({}, r); resource.id = hash; @@ -149,7 +149,7 @@ function enexXmlToHtml_(stream, resources) { async function enexXmlToHtml(xmlString, resources, options = {}) { const stream = stringToStream(xmlString); - let result = await enexXmlToHtml_(stream, resources, options); + const result = await enexXmlToHtml_(stream, resources, options); try { const preCleaning = result.content.lines.join(''); // xmlString diff --git a/ReactNativeClient/lib/import-enex-md-gen.js b/ReactNativeClient/lib/import-enex-md-gen.js index 9250ae78c..8fb91f22c 100644 --- a/ReactNativeClient/lib/import-enex-md-gen.js +++ b/ReactNativeClient/lib/import-enex-md-gen.js @@ -20,7 +20,7 @@ function processMdArrayNewLines(md) { let temp = []; let last = ''; for (let i = 0; i < md.length; i++) { - let v = md[i]; + const v = md[i]; if (isNewLineBlock(last) && isNewLineBlock(v) && last == v) { // Skip it } else { @@ -33,7 +33,7 @@ function processMdArrayNewLines(md) { temp = []; last = ''; for (let i = 0; i < md.length; i++) { - let v = md[i]; + const v = md[i]; if (last == BLOCK_CLOSE && v == BLOCK_OPEN) { temp.pop(); temp.push(NEWLINE_MERGED); @@ -47,7 +47,7 @@ function processMdArrayNewLines(md) { temp = []; last = ''; for (let i = 0; i < md.length; i++) { - let v = md[i]; + const v = md[i]; if (last == NEWLINE && (v == NEWLINE_MERGED || v == BLOCK_CLOSE)) { // Skip it } else { @@ -61,7 +61,7 @@ function processMdArrayNewLines(md) { temp = []; last = ''; for (let i = 0; i < md.length; i++) { - let v = md[i]; + const v = md[i]; if (last == NEWLINE && (v == NEWLINE_MERGED || v == BLOCK_OPEN)) { // Skip it } else { @@ -81,7 +81,7 @@ function processMdArrayNewLines(md) { let previous = ''; let start = true; for (let i = 0; i < md.length; i++) { - let v = md[i]; + const v = md[i]; let add = ''; if (v == BLOCK_CLOSE || v == BLOCK_OPEN || v == NEWLINE || v == NEWLINE_MERGED) { add = '\n'; @@ -103,7 +103,7 @@ function processMdArrayNewLines(md) { // To simplify the result, we only allow up to one empty line between blocks of text const mergeMultipleNewLines = function(lines) { - let output = []; + const output = []; let newlineCount = 0; for (let i = 0; i < lines.length; i++) { const line = lines[i]; @@ -191,7 +191,7 @@ const isPlainParagraph = function(line) { function formatMdLayout(lines) { let previous = ''; - let newLines = []; + const newLines = []; for (let i = 0; i < lines.length; i++) { const line = lines[i]; @@ -245,8 +245,8 @@ function simplifyString(s) { let output = ''; let previousWhite = false; for (let i = 0; i < s.length; i++) { - let c = s[i]; - let isWhite = isWhiteSpace(c); + const c = s[i]; + const isWhite = isWhiteSpace(c); if (previousWhite && isWhite) { // skip } else { @@ -271,8 +271,8 @@ function collapseWhiteSpaceAndAppend(lines, state, text) { // Collapse all white spaces to just one. If there are spaces to the left and right of the string // also collapse them to just one space. - let spaceLeft = text.length && text[0] == ' '; - let spaceRight = text.length && text[text.length - 1] == ' '; + const spaceLeft = text.length && text[0] == ' '; + const spaceRight = text.length && text[text.length - 1] == ' '; text = simplifyString(text); if (!spaceLeft && !spaceRight && text == '') return lines; @@ -369,8 +369,8 @@ function isNewLineBlock(s) { function attributeToLowerCase(node) { if (!node.attributes) return {}; - let output = {}; - for (let n in node.attributes) { + const output = {}; + for (const n in node.attributes) { if (!node.attributes.hasOwnProperty(n)) continue; output[n.toLowerCase()] = node.attributes[n]; } @@ -388,7 +388,7 @@ function isSpanWithStyle(attributes) { } function isSpanStyleBold(attributes) { - let style = attributes.style; + const style = attributes.style; if (style.includes('font-weight: bold;')) { return true; } else if (style.search(/font-family:.*,Bold.*;/) != -1) { @@ -407,7 +407,7 @@ function isSpanStyleItalic(attributes) { } function enexXmlToMdArray(stream, resources) { - let remainingResources = resources.slice(); + const remainingResources = resources.slice(); const removeRemainingResource = id => { for (let i = 0; i < remainingResources.length; i++) { @@ -419,7 +419,7 @@ function enexXmlToMdArray(stream, resources) { }; return new Promise((resolve) => { - let state = { + const state = { inCode: [], inPre: false, inQuote: false, @@ -428,9 +428,9 @@ function enexXmlToMdArray(stream, resources) { spanAttributes: [], }; - let options = {}; - let strict = false; - var saxStream = require('sax').createStream(strict, options); + const options = {}; + const strict = false; + const saxStream = require('sax').createStream(strict, options); let section = { type: 'text', @@ -475,7 +475,7 @@ function enexXmlToMdArray(stream, resources) { saxStream.on('opentag', function(node) { const nodeAttributes = attributeToLowerCase(node); - let n = node.name.toLowerCase(); + const n = node.name.toLowerCase(); const currentList = state.lists && state.lists.length ? state.lists[state.lists.length - 1] : null; @@ -493,7 +493,7 @@ function enexXmlToMdArray(stream, resources) { } else if (isBlockTag(n)) { section.lines.push(BLOCK_OPEN); } else if (n == 'table') { - let newSection = { + const newSection = { type: 'table', lines: [], parent: section, @@ -508,7 +508,7 @@ function enexXmlToMdArray(stream, resources) { return; } - let newSection = { + const newSection = { type: 'tr', lines: [], parent: section, @@ -525,7 +525,7 @@ function enexXmlToMdArray(stream, resources) { if (n == 'th') section.isHeader = true; - let newSection = { + const newSection = { type: 'td', lines: [], parent: section, @@ -543,7 +543,7 @@ function enexXmlToMdArray(stream, resources) { return; } - let container = state.lists[state.lists.length - 1]; + const container = state.lists[state.lists.length - 1]; container.startedText = false; const indent = ' '.repeat(state.lists.length - 1); @@ -577,7 +577,7 @@ function enexXmlToMdArray(stream, resources) { } else if (isEmTag(n)) { section.lines.push('*'); } else if (n == 'en-todo') { - let x = nodeAttributes && nodeAttributes.checked && nodeAttributes.checked.toLowerCase() == 'true' ? 'X' : ' '; + const x = nodeAttributes && nodeAttributes.checked && nodeAttributes.checked.toLowerCase() == 'true' ? 'X' : ' '; section.lines.push(`- [${x}] `); } else if (n == 'hr') { // Needs to be surrounded by new lines so that it's properly rendered as a line when converting to HTML @@ -610,7 +610,7 @@ function enexXmlToMdArray(stream, resources) { state.inCode.push(true); state.currentCode = ''; - let newSection = { + const newSection = { type: 'code', lines: [], parent: section, @@ -628,7 +628,7 @@ function enexXmlToMdArray(stream, resources) { let resource = null; for (let i = 0; i < resources.length; i++) { - let r = resources[i]; + const r = resources[i]; if (r.id == hash) { resource = r; removeRemainingResource(r.id); @@ -677,7 +677,7 @@ function enexXmlToMdArray(stream, resources) { let found = false; for (let i = 0; i < remainingResources.length; i++) { - let r = remainingResources[i]; + const r = remainingResources[i]; if (!r.id) { resource = Object.assign({}, r); resource.id = hash; @@ -770,8 +770,8 @@ function enexXmlToMdArray(stream, resources) { state.inPre = false; section.lines.push(BLOCK_CLOSE); } else if (isAnchor(n)) { - let attributes = state.anchorAttributes.pop(); - let url = attributes && attributes.href ? attributes.href : ''; + const attributes = state.anchorAttributes.pop(); + const url = attributes && attributes.href ? attributes.href : ''; if (section.lines.length < 1) throw new Error('Invalid anchor tag closing'); // Sanity check, but normally not possible @@ -892,7 +892,7 @@ function enexXmlToMdArray(stream, resources) { } else if (n == 'en-media') { // Skip } else if (n == 'span') { - let attributes = state.spanAttributes.pop(); + const attributes = state.spanAttributes.pop(); if (isSpanWithStyle(attributes)) { if (isSpanStyleBold(attributes)) { // console.debug('Applying style found in span tag (closing): bold') @@ -958,8 +958,8 @@ function drawTable(table) { for (let trIndex = 0; trIndex < table.lines.length; trIndex++) { const tr = table.lines[trIndex]; const isHeader = tr.isHeader; - let line = []; - let headerLine = []; + const line = []; + const headerLine = []; let emptyHeader = null; for (let tdIndex = 0; tdIndex < tr.lines.length; tdIndex++) { const td = tr.lines[tdIndex]; @@ -1015,7 +1015,7 @@ function drawTable(table) { if (!headerDone) { if (!isHeader) { if (!emptyHeader) emptyHeader = []; - let h = stringPadding(' ', width, ' ', stringPadding.RIGHT); + const h = stringPadding(' ', width, ' ', stringPadding.RIGHT); emptyHeader.push(h); } headerLine.push('-'.repeat(width)); @@ -1103,12 +1103,12 @@ function postProcessMarkdown(lines) { async function enexXmlToMd(xmlString, resources, options = {}) { const stream = stringToStream(xmlString); - let result = await enexXmlToMdArray(stream, resources, options); + const result = await enexXmlToMdArray(stream, resources, options); let mdLines = []; for (let i = 0; i < result.content.lines.length; i++) { - let line = result.content.lines[i]; + const line = result.content.lines[i]; if (typeof line === 'object' && line.type === 'table') { // A table const table = line; @@ -1127,7 +1127,7 @@ async function enexXmlToMd(xmlString, resources, options = {}) { let firstAttachment = true; for (let i = 0; i < result.resources.length; i++) { - let r = result.resources[i]; + const r = result.resources[i]; if (firstAttachment) mdLines.push(NEWLINE); mdLines.push(NEWLINE); mdLines = addResourceTag(mdLines, r, r.filename); diff --git a/ReactNativeClient/lib/import-enex.js b/ReactNativeClient/lib/import-enex.js index 51cc11475..fbf04a893 100644 --- a/ReactNativeClient/lib/import-enex.js +++ b/ReactNativeClient/lib/import-enex.js @@ -63,10 +63,10 @@ async function md5FileAsync(filePath) { } function removeUndefinedProperties(note) { - let output = {}; - for (let n in note) { + const output = {}; + for (const n in note) { if (!note.hasOwnProperty(n)) continue; - let v = note[n]; + const v = note[n]; if (v === undefined || v === null) continue; output[n] = v; } @@ -74,26 +74,26 @@ function removeUndefinedProperties(note) { } function levenshteinPercent(s1, s2) { - let l = new Levenshtein(s1, s2); + const l = new Levenshtein(s1, s2); if (!s1.length || !s2.length) return 1; return Math.abs(l.distance / s1.length); } async function fuzzyMatch(note) { if (note.created_time < time.unixMs() - 1000 * 60 * 60 * 24 * 360) { - let notes = await Note.modelSelectAll('SELECT * FROM notes WHERE is_conflict = 0 AND created_time = ? AND title = ?', [note.created_time, note.title]); + const notes = await Note.modelSelectAll('SELECT * FROM notes WHERE is_conflict = 0 AND created_time = ? AND title = ?', [note.created_time, note.title]); return notes.length !== 1 ? null : notes[0]; } - let notes = await Note.modelSelectAll('SELECT * FROM notes WHERE is_conflict = 0 AND created_time = ?', [note.created_time]); + const notes = await Note.modelSelectAll('SELECT * FROM notes WHERE is_conflict = 0 AND created_time = ?', [note.created_time]); if (notes.length === 0) return null; if (notes.length === 1) return notes[0]; let lowestL = 1; let lowestN = null; for (let i = 0; i < notes.length; i++) { - let n = notes[i]; - let l = levenshteinPercent(note.title, n.title); + const n = notes[i]; + const l = levenshteinPercent(note.title, n.title); if (l < lowestL) { lowestL = l; lowestN = n; @@ -147,14 +147,14 @@ async function saveNoteResources(note, importOptions) { continue; } - let toSave = Object.assign({}, resource); + const toSave = Object.assign({}, resource); delete toSave.dataFilePath; delete toSave.dataEncoding; // The same resource sometimes appear twice in the same enex (exact same ID and file). // In that case, just skip it - it means two different notes might be linked to the // same resource. - let existingResource = await Resource.load(toSave.id); + const existingResource = await Resource.load(toSave.id); if (existingResource) continue; await fs.move(resource.dataFilePath, Resource.fullPath(toSave), { overwrite: true }); @@ -167,7 +167,7 @@ async function saveNoteResources(note, importOptions) { async function saveNoteTags(note) { let notesTagged = 0; for (let i = 0; i < note.tags.length; i++) { - let tagTitle = note.tags[i]; + const tagTitle = note.tags[i]; let tag = await Tag.loadByTitle(tagTitle); if (!tag) tag = await Tag.save({ title: tagTitle }); @@ -186,9 +186,9 @@ async function saveNoteToStorage(note, importOptions) { note = Note.filter(note); - let existingNote = importOptions.fuzzyMatching ? await fuzzyMatch(note) : null; + const existingNote = importOptions.fuzzyMatching ? await fuzzyMatch(note) : null; - let result = { + const result = { noteCreated: false, noteUpdated: false, noteSkipped: false, @@ -196,14 +196,14 @@ async function saveNoteToStorage(note, importOptions) { notesTagged: 0, }; - let resourcesCreated = await saveNoteResources(note, importOptions); + const resourcesCreated = await saveNoteResources(note, importOptions); result.resourcesCreated += resourcesCreated; - let notesTagged = await saveNoteTags(note); + const notesTagged = await saveNoteTags(note); result.notesTagged += notesTagged; if (existingNote) { - let diff = BaseModel.diffObjects(existingNote, note); + const diff = BaseModel.diffObjects(existingNote, note); delete diff.tags; delete diff.resources; delete diff.id; @@ -236,7 +236,7 @@ function importEnex(parentFolderId, filePath, importOptions = null) { if (!('onError' in importOptions)) importOptions.onError = function() {}; return new Promise((resolve, reject) => { - let progressState = { + const progressState = { loaded: 0, created: 0, updated: 0, @@ -245,19 +245,19 @@ function importEnex(parentFolderId, filePath, importOptions = null) { notesTagged: 0, }; - let stream = fs.createReadStream(filePath); + const stream = fs.createReadStream(filePath); - let options = {}; - let strict = true; - let saxStream = require('sax').createStream(strict, options); + const options = {}; + const strict = true; + const saxStream = require('sax').createStream(strict, options); - let nodes = []; // LIFO list of nodes so that we know in which node we are in the onText event + const nodes = []; // LIFO list of nodes so that we know in which node we are in the onText event let note = null; let noteAttributes = null; let noteResource = null; let noteResourceAttributes = null; let noteResourceRecognition = null; - let notes = []; + const notes = []; let processingNotes = false; stream.on('error', error => { @@ -282,7 +282,7 @@ function importEnex(parentFolderId, filePath, importOptions = null) { stream.pause(); while (notes.length) { - let note = notes.shift(); + const note = notes.shift(); const body = importOptions.outputFormat === 'html' ? await enexXmlToHtml(note.bodyXml, note.resources) : await enexXmlToMd(note.bodyXml, note.resources); @@ -332,7 +332,7 @@ function importEnex(parentFolderId, filePath, importOptions = null) { }); saxStream.on('text', function(text) { - let n = currentNodeName(); + const n = currentNodeName(); if (noteAttributes) { noteAttributes[n] = text; @@ -341,7 +341,7 @@ function importEnex(parentFolderId, filePath, importOptions = null) { } else if (noteResource) { if (n == 'data') { if (!noteResource.dataEncoding) { - let attr = currentNodeAttributes(); + const attr = currentNodeAttributes(); noteResource.dataEncoding = attr.encoding; } @@ -374,7 +374,7 @@ function importEnex(parentFolderId, filePath, importOptions = null) { }); saxStream.on('opentag', function(node) { - let n = node.name.toLowerCase(); + const n = node.name.toLowerCase(); nodes.push(node); if (n == 'note') { @@ -394,7 +394,7 @@ function importEnex(parentFolderId, filePath, importOptions = null) { }); saxStream.on('cdata', function(data) { - let n = currentNodeName(); + const n = currentNodeName(); if (noteResourceRecognition) { noteResourceRecognition.objID = extractRecognitionObjId(data); @@ -462,7 +462,7 @@ function importEnex(parentFolderId, filePath, importOptions = null) { saxStream.on('end', function() { // Wait till there is no more notes to process. - let iid = setInterval(() => { + const iid = setInterval(() => { processNotes().then(allDone => { if (allDone) { clearTimeout(iid); diff --git a/ReactNativeClient/lib/joplin-database.js b/ReactNativeClient/lib/joplin-database.js index 77d5cb515..4674ab931 100644 --- a/ReactNativeClient/lib/joplin-database.js +++ b/ReactNativeClient/lib/joplin-database.js @@ -136,8 +136,8 @@ class JoplinDatabase extends Database { } tableFieldNames(tableName) { - let tf = this.tableFields(tableName); - let output = []; + const tf = this.tableFields(tableName); + const output = []; for (let i = 0; i < tf.length; i++) { output.push(tf[i].name); } @@ -248,14 +248,14 @@ class JoplinDatabase extends Database { refreshTableFields() { this.logger().info('Initializing tables...'); - let queries = []; + const queries = []; queries.push(this.wrapQuery('DELETE FROM table_fields')); return this.selectAll('SELECT name FROM sqlite_master WHERE type="table"') .then(tableRows => { - let chain = []; + const chain = []; for (let i = 0; i < tableRows.length; i++) { - let tableName = tableRows[i].name; + const tableName = tableRows[i].name; if (tableName == 'android_metadata') continue; if (tableName == 'table_fields') continue; if (tableName == 'sqlite_sequence') continue; @@ -263,13 +263,13 @@ class JoplinDatabase extends Database { chain.push(() => { return this.selectAll(`PRAGMA table_info("${tableName}")`).then(pragmas => { for (let i = 0; i < pragmas.length; i++) { - let item = pragmas[i]; + const item = pragmas[i]; // In SQLite, if the default value is a string it has double quotes around it, so remove them here let defaultValue = item.dflt_value; if (typeof defaultValue == 'string' && defaultValue.length >= 2 && defaultValue[0] == '"' && defaultValue[defaultValue.length - 1] == '"') { defaultValue = defaultValue.substr(1, defaultValue.length - 2); } - let q = Database.insertQuery('table_fields', { + const q = Database.insertQuery('table_fields', { table_name: tableName, field_name: item.name, field_type: Database.enumId('fieldType', item.type), @@ -319,7 +319,7 @@ class JoplinDatabase extends Database { 'Unknown profile version. Most likely this is an old version of Joplin, while the profile was created by a newer version. Please upgrade Joplin at https://joplinapp.org and try again.\n' + `Joplin version: ${shim.appVersion()}\n` + `Profile version: ${fromVersion}\n` - + `Expected version: ${existingDatabaseVersions[existingDatabaseVersions.length-1]}`); + + `Expected version: ${existingDatabaseVersions[existingDatabaseVersions.length - 1]}`); } if (currentVersionIndex == existingDatabaseVersions.length - 1) return fromVersion; @@ -738,10 +738,10 @@ class JoplinDatabase extends Database { this.tableFields_ = {}; - let rows = await this.selectAll('SELECT * FROM table_fields'); + const rows = await this.selectAll('SELECT * FROM table_fields'); for (let i = 0; i < rows.length; i++) { - let row = rows[i]; + const row = rows[i]; if (!this.tableFields_[row.table_name]) this.tableFields_[row.table_name] = []; this.tableFields_[row.table_name].push({ name: row.field_name, diff --git a/ReactNativeClient/lib/joplin-renderer/MdToHtml.js b/ReactNativeClient/lib/joplin-renderer/MdToHtml.js index 69698966b..c9172be31 100644 --- a/ReactNativeClient/lib/joplin-renderer/MdToHtml.js +++ b/ReactNativeClient/lib/joplin-renderer/MdToHtml.js @@ -252,7 +252,7 @@ class MdToHtml { markdownIt.use(rules.code_inline(context, ruleOptions)); markdownIt.use(markdownItAnchor, { slugify: uslugify }); - for (let key in plugins) { + for (const key in plugins) { if (this.pluginEnabled(key)) markdownIt.use(plugins[key].module, plugins[key].options); } diff --git a/ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/fence.ts b/ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/fence.ts index 7662d71e1..f3a410089 100644 --- a/ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/fence.ts +++ b/ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/fence.ts @@ -1,3 +1,5 @@ +/* eslint prefer-const: 0*/ + // Note: this is copied from https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.js // Markdown-it assigns a special meaning to code returned from highlight() when it starts with PRE or not. // If it starts with PRE, the highlited code is returned as-is. If it does not, it is wrapped in

@@ -9,7 +11,7 @@
 function installRule(markdownIt:any) {
 	// @ts-ignore: Keep the function signature as-is despite unusued arguments
 	markdownIt.renderer.rules.fence = function(tokens:any[], idx:number, options:any, env:any, slf:any) {
-		var token = tokens[idx],
+		let token = tokens[idx],
 			info = token.info ? markdownIt.utils.unescapeAll(token.info).trim() : '',
 			langName = '',
 			highlighted, i, tmpAttrs, tmpToken;
diff --git a/ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/katex.js b/ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/katex.js
index adcdb963a..9471d60ae 100644
--- a/ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/katex.js
+++ b/ReactNativeClient/lib/joplin-renderer/MdToHtml/rules/katex.js
@@ -1,3 +1,5 @@
+/* eslint prefer-const: 0*/
+
 // Based on https://github.com/waylonflinn/markdown-it-katex
 
 'use strict';
@@ -15,7 +17,7 @@ katex = mhchemModule(katex);
 // Test if potential opening or closing delimieter
 // Assumes that there is a "$" at state.src[pos]
 function isValidDelim(state, pos) {
-	var prevChar,
+	let prevChar,
 		nextChar,
 		max = state.posMax,
 		can_open = true,
@@ -40,7 +42,7 @@ function isValidDelim(state, pos) {
 }
 
 function math_inline(state, silent) {
-	var start, match, token, res, pos;
+	let start, match, token, res, pos;
 
 	if (state.src[state.pos] !== '$') {
 		return false;
@@ -115,7 +117,7 @@ function math_inline(state, silent) {
 }
 
 function math_block(state, start, end, silent) {
-	var firstLine,
+	let firstLine,
 		lastLine,
 		next,
 		lastPos,
@@ -180,7 +182,7 @@ function math_block(state, start, end, silent) {
 	return true;
 }
 
-let cache_ = {};
+const cache_ = {};
 
 module.exports = function(context) {
 	// Keep macros that persist across Katex blocks to allow defining a macro
@@ -238,7 +240,7 @@ module.exports = function(context) {
 		options.trust = true;
 
 		// set KaTeX as the renderer for markdown-it-simplemath
-		var katexInline = function(latex) {
+		const katexInline = function(latex) {
 			options.displayMode = false;
 			try {
 				return `
${latex}
${renderToStringWithCache(latex, options)}
`; @@ -248,12 +250,12 @@ module.exports = function(context) { } }; - var inlineRenderer = function(tokens, idx) { + const inlineRenderer = function(tokens, idx) { addContextAssets(); return katexInline(tokens[idx].content); }; - var katexBlock = function(latex) { + const katexBlock = function(latex) { options.displayMode = true; try { return `
${latex}
${renderToStringWithCache(latex, options)}
`; @@ -263,7 +265,7 @@ module.exports = function(context) { } }; - var blockRenderer = function(tokens, idx) { + const blockRenderer = function(tokens, idx) { addContextAssets(); return `${katexBlock(tokens[idx].content)}\n`; }; diff --git a/ReactNativeClient/lib/joplin-renderer/MdToHtml/setupLinkify.js b/ReactNativeClient/lib/joplin-renderer/MdToHtml/setupLinkify.js index 5552f8f45..97e39059e 100644 --- a/ReactNativeClient/lib/joplin-renderer/MdToHtml/setupLinkify.js +++ b/ReactNativeClient/lib/joplin-renderer/MdToHtml/setupLinkify.js @@ -3,7 +3,7 @@ module.exports = function(markdownIt) { // file-URL links in html view markdownIt.linkify.add('file:', { validate: function(text, pos, self) { - var tail = text.slice(pos); + const tail = text.slice(pos); if (!self.re.file) { // matches all local file URI on Win/Unix/MacOS systems including reserved characters in some OS (i.e. no OS specific sanity check) self.re.file = new RegExp('^[\\/]{2,3}[\\S]+'); @@ -18,11 +18,11 @@ module.exports = function(markdownIt) { // enable file link URLs in MarkdownIt. Keeps other URL restrictions of MarkdownIt untouched. // Format [link name](file://...) markdownIt.validateLink = function(url) { - var BAD_PROTO_RE = /^(vbscript|javascript|data):/; - var GOOD_DATA_RE = /^data:image\/(gif|png|jpeg|webp);/; + const BAD_PROTO_RE = /^(vbscript|javascript|data):/; + const GOOD_DATA_RE = /^data:image\/(gif|png|jpeg|webp);/; // url should be normalized at this point, and existing entities are decoded - var str = url.trim().toLowerCase(); + const str = url.trim().toLowerCase(); return BAD_PROTO_RE.test(str) ? (GOOD_DATA_RE.test(str) ? true : false) : true; }; diff --git a/ReactNativeClient/lib/joplin-renderer/assetsToHeaders.js b/ReactNativeClient/lib/joplin-renderer/assetsToHeaders.js index 7f313745b..9b3988b38 100644 --- a/ReactNativeClient/lib/joplin-renderer/assetsToHeaders.js +++ b/ReactNativeClient/lib/joplin-renderer/assetsToHeaders.js @@ -15,8 +15,8 @@ function assetsToHeaders(pluginAssets, options = null) { } if (options.asHtml) { - let output = []; - for (let name in headers) { + const output = []; + for (const name in headers) { output.push(headers[name]); } return output.join(''); diff --git a/ReactNativeClient/lib/joplin-renderer/pathUtils.js b/ReactNativeClient/lib/joplin-renderer/pathUtils.js index ed085e296..371c46c6f 100644 --- a/ReactNativeClient/lib/joplin-renderer/pathUtils.js +++ b/ReactNativeClient/lib/joplin-renderer/pathUtils.js @@ -1,13 +1,13 @@ function dirname(path) { if (!path) throw new Error('Path is empty'); - let s = path.split(/\/|\\/); + const s = path.split(/\/|\\/); s.pop(); return s.join('/'); } function basename(path) { if (!path) throw new Error('Path is empty'); - let s = path.split(/\/|\\/); + const s = path.split(/\/|\\/); return s[s.length - 1]; } @@ -24,7 +24,7 @@ function filename(path, includeDir = false) { function fileExtension(path) { if (!path) throw new Error('Path is empty'); - let output = path.split('.'); + const output = path.split('.'); if (output.length <= 1) return ''; return output[output.length - 1]; } diff --git a/ReactNativeClient/lib/joplin-renderer/stringUtils.js b/ReactNativeClient/lib/joplin-renderer/stringUtils.js index 1ca72f030..941f721b6 100644 --- a/ReactNativeClient/lib/joplin-renderer/stringUtils.js +++ b/ReactNativeClient/lib/joplin-renderer/stringUtils.js @@ -38,7 +38,7 @@ function replaceRegexDiacritics(regexString) { let output = ''; for (let i = 0; i < regexString.length; i++) { - let c = regexString[i]; + const c = regexString[i]; const r = diacriticReplacements[c]; if (r) { output += r; diff --git a/ReactNativeClient/lib/locale.js b/ReactNativeClient/lib/locale.js index 7696eb5b1..98bdaa8e8 100644 --- a/ReactNativeClient/lib/locale.js +++ b/ReactNativeClient/lib/locale.js @@ -1,6 +1,6 @@ const { sprintf } = require('sprintf-js'); -let codeToLanguageE_ = {}; +const codeToLanguageE_ = {}; codeToLanguageE_['aa'] = 'Afar'; codeToLanguageE_['ab'] = 'Abkhazian'; codeToLanguageE_['af'] = 'Afrikaans'; @@ -144,7 +144,7 @@ codeToLanguageE_['za'] = 'Zhuang'; codeToLanguageE_['zh'] = 'Chinese'; codeToLanguageE_['zu'] = 'Zulu'; -let codeToLanguage_ = {}; +const codeToLanguage_ = {}; codeToLanguage_['an'] = 'Aragonés'; codeToLanguage_['da'] = 'Dansk'; codeToLanguage_['de'] = 'Deutsch'; @@ -172,7 +172,7 @@ codeToLanguage_['et'] = 'Eesti Keel'; codeToLanguage_['vi'] = 'Tiếng Việt'; codeToLanguage_['hu'] = 'Magyar'; -let codeToCountry_ = {}; +const codeToCountry_ = {}; codeToCountry_['BR'] = 'Brasil'; codeToCountry_['CR'] = 'Costa Rica'; codeToCountry_['CN'] = '中国'; @@ -182,7 +182,7 @@ codeToCountry_['US'] = 'US'; let supportedLocales_ = null; let localeStats_ = null; -let loadedLocales_ = {}; +const loadedLocales_ = {}; const defaultLocale_ = 'en_GB'; @@ -200,8 +200,8 @@ function localeStats() { function supportedLocales() { if (!supportedLocales_) supportedLocales_ = require('../locales/index.js').locales; - let output = []; - for (let n in supportedLocales_) { + const output = []; + for (const n in supportedLocales_) { if (!supportedLocales_.hasOwnProperty(n)) continue; output.push(n); } @@ -212,7 +212,7 @@ function supportedLocalesToLanguages(options = null) { if (!options) options = {}; const stats = localeStats(); const locales = supportedLocales(); - let output = {}; + const output = {}; for (let i = 0; i < locales.length; i++) { const locale = locales[i]; output[locale] = countryDisplayName(locale); @@ -307,7 +307,7 @@ function languageCode() { } function _(s, ...args) { - let strings = localeStrings(currentLocale_); + const strings = localeStrings(currentLocale_); let result = strings[s]; if (result === '' || result === undefined) result = s; try { diff --git a/ReactNativeClient/lib/logger.js b/ReactNativeClient/lib/logger.js index 1e8f5b7f6..72c12c9a1 100644 --- a/ReactNativeClient/lib/logger.js +++ b/ReactNativeClient/lib/logger.js @@ -33,8 +33,8 @@ class Logger { } addTarget(type, options = null) { - let target = { type: type }; - for (let n in options) { + const target = { type: type }; + for (const n in options) { if (!options.hasOwnProperty(n)) continue; target[n] = options[n]; } @@ -63,7 +63,7 @@ class Logger { } objectsToString(...object) { - let output = []; + const output = []; for (let i = 0; i < object.length; i++) { output.push(`"${this.objectToString(object[i])}"`); } @@ -71,7 +71,7 @@ class Logger { } static databaseCreateTableSql() { - let output = ` + const output = ` CREATE TABLE IF NOT EXISTS logs ( id INTEGER PRIMARY KEY, source TEXT, @@ -109,10 +109,10 @@ class Logger { if (!this.targets_.length) return; const timestamp = moment().format('YYYY-MM-DD HH:mm:ss'); - let line = `${timestamp}: `; + const line = `${timestamp}: `; for (let i = 0; i < this.targets_.length; i++) { - let target = this.targets_[i]; + const target = this.targets_[i]; if (this.targetLevel(target) < level) continue; @@ -125,16 +125,16 @@ class Logger { const items = [moment().format('HH:mm:ss')].concat(object); consoleObj[fn](...items); } else if (target.type == 'file') { - let serializedObject = this.objectsToString(...object); + const serializedObject = this.objectsToString(...object); try { Logger.fsDriver().appendFileSync(target.path, `${line + serializedObject}\n`); } catch (error) { console.error('Cannot write to log file:', error); } } else if (target.type == 'database') { - let msg = this.objectsToString(...object); + const msg = this.objectsToString(...object); - let queries = [ + const queries = [ { sql: 'INSERT INTO logs (`source`, `level`, `message`, `timestamp`) VALUES (?, ?, ?, ?)', params: [target.source, level, msg, time.unixMs()], @@ -192,7 +192,7 @@ class Logger { } static levelEnum() { - let output = {}; + const output = {}; const ids = this.levelIds(); for (let i = 0; i < ids.length; i++) { output[ids[i]] = this.levelIdToString(ids[i]); diff --git a/ReactNativeClient/lib/markdownUtils.js b/ReactNativeClient/lib/markdownUtils.js index 8f1110b7c..e4ae0ad63 100644 --- a/ReactNativeClient/lib/markdownUtils.js +++ b/ReactNativeClient/lib/markdownUtils.js @@ -65,7 +65,7 @@ const markdownUtils = { }, createMarkdownTable(headers, rows) { - let output = []; + const output = []; const headersMd = []; const lineMd = []; diff --git a/ReactNativeClient/lib/mime-utils.js b/ReactNativeClient/lib/mime-utils.js index 2fe62c335..de9429a2f 100644 --- a/ReactNativeClient/lib/mime-utils.js +++ b/ReactNativeClient/lib/mime-utils.js @@ -809,7 +809,7 @@ const mime = { fromDataUrl(dataUrl) { // Example: data:image/jpeg;base64,/9j/4AAQSkZJR..... const defaultMime = 'text/plain'; - let p = dataUrl.substr(0, dataUrl.indexOf(',')).split(';'); + const p = dataUrl.substr(0, dataUrl.indexOf(',')).split(';'); let s = p[0]; s = s.split(':'); if (s.length <= 1) return defaultMime; diff --git a/ReactNativeClient/lib/models/BaseItem.js b/ReactNativeClient/lib/models/BaseItem.js index 3306b7313..e2c830ab1 100644 --- a/ReactNativeClient/lib/models/BaseItem.js +++ b/ReactNativeClient/lib/models/BaseItem.js @@ -100,7 +100,7 @@ class BaseItem extends BaseModel { return this.itemClass(item.type_); } else { for (let i = 0; i < BaseItem.syncItemDefinitions_.length; i++) { - let d = BaseItem.syncItemDefinitions_[i]; + const d = BaseItem.syncItemDefinitions_[i]; if (Number(item) == d.type) return this.getClass(d.className); } throw new JoplinError(`Unknown type: ${item}`, 'unknownItemType'); @@ -110,8 +110,8 @@ class BaseItem extends BaseModel { // Returns the IDs of the items that have been synced at least once static async syncedItemIds(syncTarget) { if (!syncTarget) throw new Error('No syncTarget specified'); - let temp = await this.db().selectAll('SELECT item_id FROM sync_items WHERE sync_time > 0 AND sync_target = ?', [syncTarget]); - let output = []; + const temp = await this.db().selectAll('SELECT item_id FROM sync_items WHERE sync_time > 0 AND sync_target = ?', [syncTarget]); + const output = []; for (let i = 0; i < temp.length; i++) { output.push(temp[i].item_id); } @@ -124,8 +124,8 @@ class BaseItem extends BaseModel { } static pathToId(path) { - let p = path.split('/'); - let s = p[p.length - 1].split('.'); + const p = path.split('/'); + const s = p[p.length - 1].split('.'); let name = s[0]; if (!name) return name; name = name.split('-'); @@ -137,9 +137,9 @@ class BaseItem extends BaseModel { } static async loadItemById(id) { - let classes = this.syncItemClassNames(); + const classes = this.syncItemClassNames(); for (let i = 0; i < classes.length; i++) { - let item = await this.getClass(classes[i]).load(id); + const item = await this.getClass(classes[i]).load(id); if (item) return item; } return null; @@ -158,17 +158,17 @@ class BaseItem extends BaseModel { } static loadItemByField(itemType, field, value) { - let ItemClass = this.itemClass(itemType); + const ItemClass = this.itemClass(itemType); return ItemClass.loadByField(field, value); } static loadItem(itemType, id) { - let ItemClass = this.itemClass(itemType); + const ItemClass = this.itemClass(itemType); return ItemClass.load(id); } static deleteItem(itemType, id) { - let ItemClass = this.itemClass(itemType); + const ItemClass = this.itemClass(itemType); return ItemClass.delete(id); } @@ -195,8 +195,8 @@ class BaseItem extends BaseModel { if (trackDeleted) { const syncTargetIds = Setting.enumOptionValues('sync.target'); - let queries = []; - let now = time.unixMs(); + const queries = []; + const now = time.unixMs(); for (let i = 0; i < ids.length; i++) { if (conflictNoteIds.indexOf(ids[i]) >= 0) continue; @@ -227,7 +227,7 @@ class BaseItem extends BaseModel { } static async deletedItemCount(syncTarget) { - let r = await this.db().selectOne('SELECT count(*) as total FROM deleted_items WHERE sync_target = ?', [syncTarget]); + const r = await this.db().selectOne('SELECT count(*) as total FROM deleted_items WHERE sync_target = ?', [syncTarget]); return r['total']; } @@ -275,7 +275,7 @@ class BaseItem extends BaseModel { item = this.filter(item); - let output = {}; + const output = {}; if ('title' in item && shownKeys.indexOf('title') >= 0) { output.title = item.title; @@ -293,7 +293,7 @@ class BaseItem extends BaseModel { let value = null; if (typeof key === 'function') { - let r = await key(); + const r = await key(); key = r.key; value = r.value; } else { @@ -303,7 +303,7 @@ class BaseItem extends BaseModel { output.props.push(`${key}: ${value}`); } - let temp = []; + const temp = []; if (typeof output.title === 'string') temp.push(output.title); if (output.body) temp.push(output.body); @@ -324,7 +324,7 @@ class BaseItem extends BaseModel { static async serializeForSync(item) { const ItemClass = this.itemClass(item); - let shownKeys = ItemClass.fieldNames(); + const shownKeys = ItemClass.fieldNames(); shownKeys.push('type_'); const serialized = await ItemClass.serialize(item, shownKeys); @@ -384,10 +384,10 @@ class BaseItem extends BaseModel { } static async unserialize(content) { - let lines = content.split('\n'); + const lines = content.split('\n'); let output = {}; let state = 'readingProps'; - let body = []; + const body = []; for (let i = lines.length - 1; i >= 0; i--) { let line = lines[i]; @@ -400,10 +400,10 @@ class BaseItem extends BaseModel { continue; } - let p = line.indexOf(':'); + const p = line.indexOf(':'); if (p < 0) throw new Error(`Invalid property format: ${line}: ${content}`); - let key = line.substr(0, p).trim(); - let value = line.substr(p + 1).trim(); + const key = line.substr(0, p).trim(); + const value = line.substr(p + 1).trim(); output[key] = value; } else if (state == 'readingBody') { body.splice(0, 0, line); @@ -414,7 +414,7 @@ class BaseItem extends BaseModel { output.type_ = Number(output.type_); if (body.length) { - let title = body.splice(0, 2); + const title = body.splice(0, 2); output.title = title[0]; } @@ -423,7 +423,7 @@ class BaseItem extends BaseModel { const ItemClass = this.itemClass(output.type_); output = ItemClass.removeUnknownFields(output); - for (let n in output) { + for (const n in output) { if (!output.hasOwnProperty(n)) continue; output[n] = await this.unserialize_format(output.type_, n, output[n]); } @@ -522,7 +522,7 @@ class BaseItem extends BaseModel { for (let i = 0; i < classNames.length; i++) { const className = classNames[i]; const ItemClass = this.getClass(className); - let fieldNames = ItemClass.fieldNames('items'); + const fieldNames = ItemClass.fieldNames('items'); // // NEVER SYNCED: // 'SELECT * FROM [ITEMS] WHERE id NOT INT (SELECT item_id FROM sync_items WHERE sync_target = ?)' @@ -544,7 +544,7 @@ class BaseItem extends BaseModel { // data set it does. In that case it means the recent notes, those that are likely // to be modified again, will be synced first, thus avoiding potential conflicts. - let sql = sprintf(` + const sql = sprintf(` SELECT %s FROM %s items WHERE id NOT IN ( @@ -561,7 +561,7 @@ class BaseItem extends BaseModel { limit ); - let neverSyncedItem = await ItemClass.modelSelectAll(sql); + const neverSyncedItem = await ItemClass.modelSelectAll(sql); // Secondly get the items that have been synced under this sync target but that have been changed since then @@ -572,7 +572,7 @@ class BaseItem extends BaseModel { if (newLimit > 0) { fieldNames.push('sync_time'); - let sql = sprintf( + const sql = sprintf( ` SELECT %s FROM %s items JOIN sync_items s ON s.item_id = items.id @@ -613,7 +613,7 @@ class BaseItem extends BaseModel { static encryptableItemClassNames() { const temp = this.syncItemClassNames(); - let output = []; + const output = []; for (let i = 0; i < temp.length; i++) { if (temp[i] === 'MasterKey') continue; output.push(temp[i]); @@ -636,7 +636,7 @@ class BaseItem extends BaseModel { static async syncDisabledItems(syncTargetId) { const rows = await this.db().selectAll('SELECT * FROM sync_items WHERE sync_disabled = 1 AND sync_target = ?', [syncTargetId]); - let output = []; + const output = []; for (let i = 0; i < rows.length; i++) { const row = rows[i]; const item = await this.loadItem(row.item_type, row.item_id); @@ -687,7 +687,7 @@ class BaseItem extends BaseModel { static async deleteOrphanSyncItems() { const classNames = this.syncItemClassNames(); - let queries = []; + const queries = []; for (let i = 0; i < classNames.length; i++) { const className = classNames[i]; const ItemClass = this.getClass(className); diff --git a/ReactNativeClient/lib/models/Folder.js b/ReactNativeClient/lib/models/Folder.js index 975b89edc..9c8a23c32 100644 --- a/ReactNativeClient/lib/models/Folder.js +++ b/ReactNativeClient/lib/models/Folder.js @@ -35,9 +35,9 @@ class Folder extends BaseItem { return this.db() .selectAll('SELECT id FROM notes WHERE is_conflict = 0 AND parent_id = ?', [parentId]) .then(rows => { - let output = []; + const output = []; for (let i = 0; i < rows.length; i++) { - let row = rows[i]; + const row = rows[i]; output.push(row.id); } return output; @@ -50,12 +50,12 @@ class Folder extends BaseItem { } static async noteCount(parentId) { - let r = await this.db().selectOne('SELECT count(*) as total FROM notes WHERE is_conflict = 0 AND parent_id = ?', [parentId]); + const r = await this.db().selectOne('SELECT count(*) as total FROM notes WHERE is_conflict = 0 AND parent_id = ?', [parentId]); return r ? r.total : 0; } static markNotesAsConflict(parentId) { - let query = Database.updateQuery('notes', { is_conflict: 1 }, { parent_id: parentId }); + const query = Database.updateQuery('notes', { is_conflict: 1 }, { parent_id: parentId }); return this.db().exec(query); } @@ -63,16 +63,16 @@ class Folder extends BaseItem { if (!options) options = {}; if (!('deleteChildren' in options)) options.deleteChildren = true; - let folder = await Folder.load(folderId); + const folder = await Folder.load(folderId); if (!folder) return; // noop if (options.deleteChildren) { - let noteIds = await Folder.noteIds(folderId); + const noteIds = await Folder.noteIds(folderId); for (let i = 0; i < noteIds.length; i++) { await Note.delete(noteIds[i]); } - let subFolderIds = await Folder.subFolderIds(folderId); + const subFolderIds = await Folder.subFolderIds(folderId); for (let i = 0; i < subFolderIds.length; i++) { await Folder.delete(subFolderIds[i]); } @@ -124,7 +124,7 @@ class Folder extends BaseItem { noteCounts.forEach((noteCount) => { let parentId = noteCount.folder_id; do { - let folder = foldersById[parentId]; + const folder = foldersById[parentId]; if (!folder) break; // https://github.com/laurent22/joplin/issues/2079 folder.note_count = (folder.note_count || 0) + noteCount.note_count; parentId = folder.parent_id; @@ -172,7 +172,7 @@ class Folder extends BaseItem { applyChildTimeToParent(parent.id); }; - for (let folderId in folderIdToTime) { + for (const folderId in folderIdToTime) { if (!folderIdToTime.hasOwnProperty(folderId)) continue; applyChildTimeToParent(folderId); } @@ -193,9 +193,9 @@ class Folder extends BaseItem { } static async all(options = null) { - let output = await super.all(options); + const output = await super.all(options); if (options && options.includeConflictFolder) { - let conflictCount = await Note.conflictedCount(); + const conflictCount = await Note.conflictedCount(); if (conflictCount) output.push(this.conflictFolder()); } return output; @@ -305,7 +305,7 @@ class Folder extends BaseItem { } const rootFolders = []; - for (let folderId in idToFolders) { + for (const folderId in idToFolders) { if (!idToFolders.hasOwnProperty(folderId)) continue; const folder = idToFolders[folderId]; @@ -343,7 +343,7 @@ class Folder extends BaseItem { if (!targetFolderId) return true; while (true) { - let folder = await Folder.load(targetFolderId); + const folder = await Folder.load(targetFolderId); if (!folder.parent_id) break; if (folder.parent_id === folderId) return false; targetFolderId = folder.parent_id; diff --git a/ReactNativeClient/lib/models/Note.js b/ReactNativeClient/lib/models/Note.js index 14b8f49f6..f56114cc2 100644 --- a/ReactNativeClient/lib/models/Note.js +++ b/ReactNativeClient/lib/models/Note.js @@ -35,7 +35,7 @@ class Note extends BaseItem { static async unserializeForEdit(content) { content += `\n\ntype_: ${BaseModel.TYPE_NOTE}`; - let output = await super.unserialize(content); + const output = await super.unserialize(content); if (!output.title) output.title = ''; if (!output.body) output.body = ''; output.body = await this.replaceResourceExternalToInternalLinks(output.body); @@ -43,16 +43,16 @@ class Note extends BaseItem { } static async serializeAllProps(note) { - let fieldNames = this.fieldNames(); + const fieldNames = this.fieldNames(); fieldNames.push('type_'); lodash.pull(fieldNames, 'title', 'body'); return super.serialize(note, fieldNames); } static minimalSerializeForDisplay(note) { - let n = Object.assign({}, note); + const n = Object.assign({}, note); - let fieldNames = this.fieldNames(); + const fieldNames = this.fieldNames(); if (!n.is_conflict) lodash.pull(fieldNames, 'is_conflict'); if (!Number(n.latitude)) lodash.pull(fieldNames, 'latitude'); @@ -193,13 +193,13 @@ class Note extends BaseItem { } static new(parentId = '') { - let output = super.new(); + const output = super.new(); output.parent_id = parentId; return output; } static newTodo(parentId = '') { - let output = this.new(parentId); + const output = this.new(parentId); output.is_todo = true; return output; } @@ -269,13 +269,13 @@ class Note extends BaseItem { static async loadFolderNoteByField(folderId, field, value) { if (!folderId) throw new Error('folderId is undefined'); - let options = { + const options = { conditions: [`\`${field}\` = ?`], conditionsParams: [value], fields: '*', }; - let results = await this.previews(folderId, options); + const results = await this.previews(folderId, options); return results.length ? results[0] : null; } @@ -302,7 +302,7 @@ class Note extends BaseItem { } if (options.anywherePattern) { - let pattern = options.anywherePattern.replace(/\*/g, '%'); + const pattern = options.anywherePattern.replace(/\*/g, '%'); options.conditions.push('(title LIKE ? OR body LIKE ?)'); options.conditionsParams.push(pattern); options.conditionsParams.push(pattern); @@ -329,7 +329,7 @@ class Note extends BaseItem { let tempOptions = Object.assign({}, options); tempOptions.conditions = cond; - let uncompletedTodos = await this.search(tempOptions); + const uncompletedTodos = await this.search(tempOptions); cond = options.conditions.slice(); if (hasNotes && hasTodos) { @@ -341,7 +341,7 @@ class Note extends BaseItem { tempOptions = Object.assign({}, options); tempOptions.conditions = cond; if ('limit' in tempOptions) tempOptions.limit -= uncompletedTodos.length; - let theRest = await this.search(tempOptions); + const theRest = await this.search(tempOptions); return uncompletedTodos.concat(theRest); } @@ -381,7 +381,7 @@ class Note extends BaseItem { } static async conflictedCount() { - let r = await this.db().selectOne('SELECT count(*) as total FROM notes WHERE is_conflict = 1'); + const r = await this.db().selectOne('SELECT count(*) as total FROM notes WHERE is_conflict = 1'); return r && r.total ? r.total : 0; } @@ -393,7 +393,7 @@ class Note extends BaseItem { if (!Setting.value('trackLocation')) return; if (!Note.updateGeolocationEnabled_) return; - let startWait = time.unixMs(); + const startWait = time.unixMs(); while (true) { if (!this.geolocationUpdating_) break; this.logger().info('Waiting for geolocation update...'); @@ -428,7 +428,7 @@ class Note extends BaseItem { this.logger().info(`Updating lat/long of note ${noteId}`); - let note = await Note.load(noteId); + const note = await Note.load(noteId); if (!note) return; // Race condition - note has been deleted in the meantime note.longitude = geoData.coords.longitude; @@ -440,7 +440,7 @@ class Note extends BaseItem { static filter(note) { if (!note) return note; - let output = super.filter(note); + const output = super.filter(note); if ('longitude' in output) output.longitude = Number(!output.longitude ? 0 : output.longitude).toFixed(8); if ('latitude' in output) output.latitude = Number(!output.latitude ? 0 : output.latitude).toFixed(8); if ('altitude' in output) output.altitude = Number(!output.altitude ? 0 : output.altitude).toFixed(4); @@ -530,14 +530,14 @@ class Note extends BaseItem { const originalNote = await Note.load(noteId); if (!originalNote) throw new Error(`Unknown note: ${noteId}`); - let newNote = Object.assign({}, originalNote); + const newNote = Object.assign({}, originalNote); const fieldsToReset = ['id', 'created_time', 'updated_time', 'user_created_time', 'user_updated_time']; - for (let field of fieldsToReset) { + for (const field of fieldsToReset) { delete newNote[field]; } - for (let n in changes) { + for (const n in changes) { if (!changes.hasOwnProperty(n)) continue; newNote[n] = changes[n]; } @@ -557,7 +557,7 @@ class Note extends BaseItem { } static async save(o, options = null) { - let isNew = this.isNew(o, options); + const isNew = this.isNew(o, options); const isProvisional = options && !!options.provisional; if (isNew && !o.source) o.source = Setting.value('appName'); if (isNew && !o.source_application) o.source_application = Setting.value('appId'); diff --git a/ReactNativeClient/lib/models/NoteTag.js b/ReactNativeClient/lib/models/NoteTag.js index fc17b360d..0750ceabd 100644 --- a/ReactNativeClient/lib/models/NoteTag.js +++ b/ReactNativeClient/lib/models/NoteTag.js @@ -16,8 +16,8 @@ class NoteTag extends BaseItem { } static async tagIdsByNoteId(noteId) { - let rows = await this.db().selectAll('SELECT tag_id FROM note_tags WHERE note_id = ?', [noteId]); - let output = []; + const rows = await this.db().selectAll('SELECT tag_id FROM note_tags WHERE note_id = ?', [noteId]); + const output = []; for (let i = 0; i < rows.length; i++) { output.push(rows[i].tag_id); } diff --git a/ReactNativeClient/lib/models/Resource.js b/ReactNativeClient/lib/models/Resource.js index 38c506790..ad1ac1d17 100644 --- a/ReactNativeClient/lib/models/Resource.js +++ b/ReactNativeClient/lib/models/Resource.js @@ -45,7 +45,7 @@ class Resource extends BaseItem { } static needToBeFetched(resourceDownloadMode = null, limit = null) { - let sql = ['SELECT * FROM resources WHERE encryption_applied = 0 AND id IN (SELECT resource_id FROM resource_local_states WHERE fetch_status = ?)']; + const sql = ['SELECT * FROM resources WHERE encryption_applied = 0 AND id IN (SELECT resource_id FROM resource_local_states WHERE fetch_status = ?)']; if (resourceDownloadMode !== 'always') { sql.push('AND resources.id IN (SELECT resource_id FROM resources_to_download)'); } @@ -180,7 +180,7 @@ class Resource extends BaseItem { static markdownTag(resource) { let tagAlt = resource.alt ? resource.alt : resource.title; if (!tagAlt) tagAlt = ''; - let lines = []; + const lines = []; if (Resource.isSupportedImageMimeType(resource.mime)) { lines.push('!['); lines.push(markdownUtils.escapeLinkText(tagAlt)); diff --git a/ReactNativeClient/lib/models/Revision.js b/ReactNativeClient/lib/models/Revision.js index 6b980c018..a74b7980d 100644 --- a/ReactNativeClient/lib/models/Revision.js +++ b/ReactNativeClient/lib/models/Revision.js @@ -35,13 +35,13 @@ class Revision extends BaseItem { deleted: [], }; - for (let k in newObject) { + for (const k in newObject) { if (!newObject.hasOwnProperty(k)) continue; if (oldObject[k] === newObject[k]) continue; output.new[k] = newObject[k]; } - for (let k in oldObject) { + for (const k in oldObject) { if (!oldObject.hasOwnProperty(k)) continue; if (!(k in newObject)) output.deleted.push(k); } @@ -53,7 +53,7 @@ class Revision extends BaseItem { patch = JSON.parse(patch); const output = Object.assign({}, object); - for (let k in patch.new) { + for (const k in patch.new) { output[k] = patch.new[k]; } diff --git a/ReactNativeClient/lib/models/Setting.js b/ReactNativeClient/lib/models/Setting.js index 6fe53652a..4d40baebb 100644 --- a/ReactNativeClient/lib/models/Setting.js +++ b/ReactNativeClient/lib/models/Setting.js @@ -44,7 +44,7 @@ class Setting extends BaseModel { isEnum: true, label: () => _('Keyboard Mode'), options: () => { - let output = {}; + const output = {}; output['default'] = _('Default'); output['emacs'] = _('Emacs'); output['vim'] = _('Vim'); @@ -204,7 +204,7 @@ class Setting extends BaseModel { public: true, label: () => _('Date format'), options: () => { - let options = {}; + const options = {}; const now = new Date('2017-01-30T12:00:00').getTime(); options[Setting.DATE_FORMAT_1] = time.formatMsToLocal(now, Setting.DATE_FORMAT_1); options[Setting.DATE_FORMAT_2] = time.formatMsToLocal(now, Setting.DATE_FORMAT_2); @@ -223,7 +223,7 @@ class Setting extends BaseModel { public: true, label: () => _('Time format'), options: () => { - let options = {}; + const options = {}; const now = new Date('2017-01-30T20:30:00').getTime(); options[Setting.TIME_FORMAT_1] = time.formatMsToLocal(now, Setting.TIME_FORMAT_1); options[Setting.TIME_FORMAT_2] = time.formatMsToLocal(now, Setting.TIME_FORMAT_2); @@ -239,7 +239,7 @@ class Setting extends BaseModel { label: () => _('Theme'), section: 'appearance', options: () => { - let output = {}; + const output = {}; output[Setting.THEME_LIGHT] = _('Light'); output[Setting.THEME_DARK] = _('Dark'); if (platform !== mobilePlatform) { @@ -603,7 +603,7 @@ class Setting extends BaseModel { static settingMetadata(key) { const metadata = this.metadata(); if (!(key in metadata)) throw new Error(`Unknown key: ${key}`); - let output = Object.assign({}, metadata[key]); + const output = Object.assign({}, metadata[key]); output.key = key; return output; } @@ -622,14 +622,14 @@ class Setting extends BaseModel { if (!this.keys_) { const metadata = this.metadata(); this.keys_ = []; - for (let n in metadata) { + for (const n in metadata) { if (!metadata.hasOwnProperty(n)) continue; this.keys_.push(n); } } if (appType || publicOnly) { - let output = []; + const output = []; for (let i = 0; i < this.keys_.length; i++) { const md = this.settingMetadata(this.keys_[i]); if (publicOnly && !md.public) continue; @@ -653,7 +653,7 @@ class Setting extends BaseModel { this.cache_ = []; for (let i = 0; i < rows.length; i++) { - let c = rows[i]; + const c = rows[i]; if (!this.keyExists(c.key)) continue; c.value = this.formatValue(c.key, c.value); @@ -668,7 +668,7 @@ class Setting extends BaseModel { static toPlainObject() { const keys = this.keys(); - let keyToValues = {}; + const keyToValues = {}; for (let i = 0; i < keys.length; i++) { keyToValues[keys[i]] = this.value(keys[i]); } @@ -694,7 +694,7 @@ class Setting extends BaseModel { value = this.filterValue(key, value); for (let i = 0; i < this.cache_.length; i++) { - let c = this.cache_[i]; + const c = this.cache_[i]; if (c.key == key) { const md = this.settingMetadata(key); @@ -849,8 +849,8 @@ class Setting extends BaseModel { static enumOptionValues(key) { const options = this.enumOptions(key); - let output = []; - for (let n in options) { + const output = []; + for (const n in options) { if (!options.hasOwnProperty(n)) continue; output.push(n); } @@ -859,7 +859,7 @@ class Setting extends BaseModel { static enumOptionLabel(key, value) { const options = this.enumOptions(key); - for (let n in options) { + for (const n in options) { if (n == value) return options[n]; } return ''; @@ -875,8 +875,8 @@ class Setting extends BaseModel { static enumOptionsDoc(key, templateString = null) { if (templateString === null) templateString = '%s: %s'; const options = this.enumOptions(key); - let output = []; - for (let n in options) { + const output = []; + for (const n in options) { if (!options.hasOwnProperty(n)) continue; output.push(sprintf(templateString, n, options[n])); } @@ -895,8 +895,8 @@ class Setting extends BaseModel { static subValues(baseKey, settings, options = null) { const includeBaseKeyInName = !!options && !!options.includeBaseKeyInName; - let output = {}; - for (let key in settings) { + const output = {}; + for (const key in settings) { if (!settings.hasOwnProperty(key)) continue; if (key.indexOf(baseKey) === 0) { const subKey = includeBaseKeyInName ? key : key.substr(baseKey.length + 1); @@ -913,10 +913,10 @@ class Setting extends BaseModel { clearTimeout(this.saveTimeoutId_); this.saveTimeoutId_ = null; - let queries = []; + const queries = []; queries.push('DELETE FROM settings'); for (let i = 0; i < this.cache_.length; i++) { - let s = Object.assign({}, this.cache_[i]); + const s = Object.assign({}, this.cache_[i]); s.value = this.valueToString(s.key, s.value); queries.push(Database.insertQuery(this.tableName(), s)); } @@ -946,10 +946,10 @@ class Setting extends BaseModel { const metadata = this.metadata(); - let output = {}; - for (let key in metadata) { + const output = {}; + for (const key in metadata) { if (!metadata.hasOwnProperty(key)) continue; - let s = Object.assign({}, metadata[key]); + const s = Object.assign({}, metadata[key]); if (!s.public) continue; if (s.appTypes && s.appTypes.indexOf(appType) < 0) continue; s.value = this.value(key); @@ -967,7 +967,7 @@ class Setting extends BaseModel { } static groupMetadatasBySections(metadatas) { - let sections = []; + const sections = []; const generalSection = { name: 'general', metadatas: [] }; const nameToSections = {}; nameToSections['general'] = generalSection; diff --git a/ReactNativeClient/lib/models/Tag.js b/ReactNativeClient/lib/models/Tag.js index 3650faa85..2bb506fa3 100644 --- a/ReactNativeClient/lib/models/Tag.js +++ b/ReactNativeClient/lib/models/Tag.js @@ -14,8 +14,8 @@ class Tag extends BaseItem { } static async noteIds(tagId) { - let rows = await this.db().selectAll('SELECT note_id FROM note_tags WHERE tag_id = ?', [tagId]); - let output = []; + const rows = await this.db().selectAll('SELECT note_id FROM note_tags WHERE tag_id = ?', [tagId]); + const output = []; for (let i = 0; i < rows.length; i++) { output.push(rows[i].note_id); } @@ -25,7 +25,7 @@ class Tag extends BaseItem { static async notes(tagId, options = null) { if (options === null) options = {}; - let noteIds = await this.noteIds(tagId); + const noteIds = await this.noteIds(tagId); if (!noteIds.length) return []; return Note.previews( @@ -58,7 +58,7 @@ class Tag extends BaseItem { } static async addNote(tagId, noteId) { - let hasIt = await this.hasNote(tagId, noteId); + const hasIt = await this.hasNote(tagId, noteId); if (hasIt) return; const output = await NoteTag.save({ @@ -75,7 +75,7 @@ class Tag extends BaseItem { } static async removeNote(tagId, noteId) { - let noteTags = await NoteTag.modelSelectAll('SELECT id FROM note_tags WHERE tag_id = ? and note_id = ?', [tagId, noteId]); + const noteTags = await NoteTag.modelSelectAll('SELECT id FROM note_tags WHERE tag_id = ? and note_id = ?', [tagId, noteId]); for (let i = 0; i < noteTags.length; i++) { await NoteTag.delete(noteTags[i].id); } @@ -87,12 +87,12 @@ class Tag extends BaseItem { } static loadWithCount(tagId) { - let sql = 'SELECT * FROM tags_with_note_count WHERE id = ?'; + const sql = 'SELECT * FROM tags_with_note_count WHERE id = ?'; return this.modelSelectOne(sql, [tagId]); } static async hasNote(tagId, noteId) { - let r = await this.db().selectOne('SELECT note_id FROM note_tags WHERE tag_id = ? AND note_id = ? LIMIT 1', [tagId, noteId]); + const r = await this.db().selectOne('SELECT note_id FROM note_tags WHERE tag_id = ? AND note_id = ? LIMIT 1', [tagId, noteId]); return !!r; } diff --git a/ReactNativeClient/lib/net-utils.js b/ReactNativeClient/lib/net-utils.js index 26e22b2c3..1226eb4a7 100644 --- a/ReactNativeClient/lib/net-utils.js +++ b/ReactNativeClient/lib/net-utils.js @@ -3,12 +3,12 @@ const { shim } = require('lib/shim.js'); const netUtils = {}; netUtils.ip = async () => { - let response = await shim.fetch('https://api.ipify.org/?format=json'); + const response = await shim.fetch('https://api.ipify.org/?format=json'); if (!response.ok) { throw new Error(`Could not retrieve IP: ${await response.text()}`); } - let ip = await response.json(); + const ip = await response.json(); return ip.ip; }; @@ -21,7 +21,7 @@ netUtils.findAvailablePort = async (possiblePorts, extraRandomPortsToTry = 20) = let port = null; for (let i = 0; i < possiblePorts.length; i++) { - let inUse = await tcpPortUsed.check(possiblePorts[i]); + const inUse = await tcpPortUsed.check(possiblePorts[i]); if (!inUse) { port = possiblePorts[i]; break; diff --git a/ReactNativeClient/lib/onedrive-api-node-utils.js b/ReactNativeClient/lib/onedrive-api-node-utils.js index 8e768a9e9..e21b79864 100644 --- a/ReactNativeClient/lib/onedrive-api-node-utils.js +++ b/ReactNativeClient/lib/onedrive-api-node-utils.js @@ -44,11 +44,11 @@ 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}`); + const authCodeUrl = this.api().authCodeUrl(`http://localhost:${port}`); return new Promise((resolve, reject) => { this.oauthServer_ = http.createServer(); - let errorMessage = null; + const errorMessage = null; this.oauthServer_.on('request', (request, response) => { const url = urlParser.parse(request.url, true); diff --git a/ReactNativeClient/lib/onedrive-api.js b/ReactNativeClient/lib/onedrive-api.js index c0af9d29d..e2c77d280 100644 --- a/ReactNativeClient/lib/onedrive-api.js +++ b/ReactNativeClient/lib/onedrive-api.js @@ -33,7 +33,7 @@ class OneDriveApi { } dispatch(eventName, param) { - let ls = this.listeners_[eventName]; + const ls = this.listeners_[eventName]; for (let i = 0; i < ls.length; i++) { ls[i](param); } @@ -73,12 +73,12 @@ class OneDriveApi { } async appDirectory() { - let r = await this.execJson('GET', '/drive/special/approot'); + const r = await this.execJson('GET', '/drive/special/approot'); return `${r.parentReference.path}/${r.name}`; } authCodeUrl(redirectUri) { - let query = { + const query = { client_id: this.clientId_, scope: 'files.readwrite offline_access', response_type: 'code', @@ -88,7 +88,7 @@ class OneDriveApi { } async execTokenRequest(code, redirectUri) { - let body = new shim.FormData(); + const body = new shim.FormData(); body.append('client_id', this.clientId()); if (!this.isPublic()) body.append('client_secret', this.clientSecret()); body.append('code', code); @@ -120,8 +120,8 @@ class OneDriveApi { if (!errorResponse) return new Error('Undefined error'); if (errorResponse.error) { - let e = errorResponse.error; - let output = new Error(e.message); + const e = errorResponse.error; + const output = new Error(e.message); if (e.code) output.code = e.code; if (e.innerError) output.innerError = e.innerError; return output; @@ -183,7 +183,7 @@ class OneDriveApi { } if (!response.ok) { - let errorResponseText = await response.text(); + const errorResponseText = await response.text(); let errorResponse = null; try { errorResponse = JSON.parse(errorResponseText); // await response.json(); @@ -192,7 +192,7 @@ class OneDriveApi { throw error; } - let error = this.oneDriveErrorResponseToError(errorResponse); + const error = this.oneDriveErrorResponseToError(errorResponse); if (error.code == 'InvalidAuthenticationToken' || error.code == 'unauthenticated') { this.logger().info('Token expired: refreshing...'); @@ -246,10 +246,10 @@ class OneDriveApi { } async execJson(method, path, query, data) { - let response = await this.exec(method, path, query, data); - let errorResponseText = await response.text(); + const response = await this.exec(method, path, query, data); + const errorResponseText = await response.text(); try { - let output = JSON.parse(errorResponseText); // await response.json(); + const output = JSON.parse(errorResponseText); // await response.json(); return output; } catch (error) { error.message = `OneDriveApi::execJson: Cannot parse JSON: ${errorResponseText} ${error.message}`; @@ -259,8 +259,8 @@ class OneDriveApi { } async execText(method, path, query, data) { - let response = await this.exec(method, path, query, data); - let output = await response.text(); + const response = await this.exec(method, path, query, data); + const output = await response.text(); return output; } @@ -270,26 +270,26 @@ class OneDriveApi { throw new Error(_('Cannot refresh token: authentication data is missing. Starting the synchronisation again may fix the problem.')); } - let body = new shim.FormData(); + const body = new shim.FormData(); body.append('client_id', this.clientId()); if (!this.isPublic()) body.append('client_secret', this.clientSecret()); body.append('refresh_token', this.auth_.refresh_token); body.append('redirect_uri', 'http://localhost:1917'); body.append('grant_type', 'refresh_token'); - let options = { + const options = { method: 'POST', body: body, }; - let response = await shim.fetch(this.tokenBaseUrl(), options); + const response = await shim.fetch(this.tokenBaseUrl(), options); if (!response.ok) { this.setAuth(null); - let msg = await response.text(); + const msg = await response.text(); throw new Error(`${msg}: TOKEN: ${this.auth_}`); } - let auth = await response.json(); + const auth = await response.json(); this.setAuth(auth); } } diff --git a/ReactNativeClient/lib/parameters.js b/ReactNativeClient/lib/parameters.js index c5a68e543..69b376f42 100644 --- a/ReactNativeClient/lib/parameters.js +++ b/ReactNativeClient/lib/parameters.js @@ -34,7 +34,7 @@ parameters_.prod = { function parameters(env = null) { if (env === null) env = Setting.value('env'); - let output = parameters_[env]; + const output = parameters_[env]; if (Setting.value('isDemo')) { output.oneDrive = output.oneDriveDemo; } diff --git a/ReactNativeClient/lib/parseUri.js b/ReactNativeClient/lib/parseUri.js index 47a30194e..9c0e2bdf0 100644 --- a/ReactNativeClient/lib/parseUri.js +++ b/ReactNativeClient/lib/parseUri.js @@ -1,11 +1,12 @@ /* eslint no-useless-escape: 0*/ +/* eslint prefer-const: 0*/ // parseUri 1.2.2 // (c) Steven Levithan // MIT License function parseUri(str) { - var o = parseUri.options, + let o = parseUri.options, m = o.parser[o.strictMode ? 'strict' : 'loose'].exec(str), uri = {}, i = 14; diff --git a/ReactNativeClient/lib/path-utils.js b/ReactNativeClient/lib/path-utils.js index 23e30874d..5d6081056 100644 --- a/ReactNativeClient/lib/path-utils.js +++ b/ReactNativeClient/lib/path-utils.js @@ -4,14 +4,14 @@ const { _ } = require('lib/locale'); function dirname(path) { if (!path) throw new Error('Path is empty'); - let s = path.split(/\/|\\/); + const s = path.split(/\/|\\/); s.pop(); return s.join('/'); } function basename(path) { if (!path) throw new Error('Path is empty'); - let s = path.split(/\/|\\/); + const s = path.split(/\/|\\/); return s[s.length - 1]; } @@ -28,13 +28,13 @@ function filename(path, includeDir = false) { function fileExtension(path) { if (!path) throw new Error('Path is empty'); - let output = path.split('.'); + const output = path.split('.'); if (output.length <= 1) return ''; return output[output.length - 1]; } function isHidden(path) { - let b = basename(path); + const b = basename(path); if (!b.length) throw new Error(`Path empty or not a valid path: ${path}`); return b[0] === '.'; } @@ -49,7 +49,7 @@ function safeFilename(e, maxLength = null, allowSpaces = false) { if (maxLength === null) maxLength = 32; if (!e || !e.replace) return ''; const regex = allowSpaces ? /[^a-zA-Z0-9\-_\(\)\. ]/g : /[^a-zA-Z0-9\-_\(\)\.]/g; - let output = e.replace(regex, '_'); + const output = e.replace(regex, '_'); return output.substr(0, maxLength); } diff --git a/ReactNativeClient/lib/poor-man-intervals.js b/ReactNativeClient/lib/poor-man-intervals.js index 071999ddd..9175b2871 100644 --- a/ReactNativeClient/lib/poor-man-intervals.js +++ b/ReactNativeClient/lib/poor-man-intervals.js @@ -49,7 +49,7 @@ class PoorManIntervals { if (PoorManIntervals.lastUpdateTime_ + 1000 > time.unixMs()) return; for (let i = 0; i < PoorManIntervals.intervals_.length; i++) { - let interval = PoorManIntervals.intervals_[i]; + const interval = PoorManIntervals.intervals_[i]; const now = time.unixMs(); if (now - interval.lastIntervalTime >= interval.interval) { interval.lastIntervalTime = now; diff --git a/ReactNativeClient/lib/promise-utils.js b/ReactNativeClient/lib/promise-utils.js index 3b70ed696..5bd822181 100644 --- a/ReactNativeClient/lib/promise-utils.js +++ b/ReactNativeClient/lib/promise-utils.js @@ -3,7 +3,7 @@ function promiseChain(chain, defaultValue = null) { resolve(defaultValue); }); for (let i = 0; i < chain.length; i++) { - let f = chain[i]; + const f = chain[i]; output = output.then(f); } return output; diff --git a/ReactNativeClient/lib/reducer.js b/ReactNativeClient/lib/reducer.js index 8d81f0a33..dab6c9464 100644 --- a/ReactNativeClient/lib/reducer.js +++ b/ReactNativeClient/lib/reducer.js @@ -130,7 +130,7 @@ function folderSetCollapsed(state, action) { collapsedFolderIds.splice(idx, 1); } - let newState = Object.assign({}, state); + const newState = Object.assign({}, state); newState.collapsedFolderIds = collapsedFolderIds; return newState; } @@ -152,11 +152,11 @@ function handleItemDelete(state, action) { const isSelected = selectedItemKeys.includes(action.id); const items = state[listKey]; - let newItems = []; + const newItems = []; let newSelectedIndexes = []; for (let i = 0; i < items.length; i++) { - let item = items[i]; + const item = items[i]; if (isSelected) { // the selected item is deleted so select the following item // if multiple items are selected then just use the first one @@ -191,7 +191,7 @@ function handleItemDelete(state, action) { } } - let newState = Object.assign({}, state); + const newState = Object.assign({}, state); newState[listKey] = newItems; const newIds = []; @@ -216,12 +216,12 @@ function updateOneItem(state, action, keyName = '') { if (action.type === 'MASTERKEY_UPDATE_ONE') itemsKey = 'masterKeys'; } - let newItems = state[itemsKey].splice(0); - let item = action.item; + const newItems = state[itemsKey].splice(0); + const item = action.item; - var found = false; + let found = false; for (let i = 0; i < newItems.length; i++) { - let n = newItems[i]; + const n = newItems[i]; if (n.id == item.id) { newItems[i] = Object.assign(newItems[i], item); found = true; @@ -231,7 +231,7 @@ function updateOneItem(state, action, keyName = '') { if (!found) newItems.push(item); - let newState = Object.assign({}, state); + const newState = Object.assign({}, state); newState[itemsKey] = newItems; @@ -256,7 +256,7 @@ function changeSelectedFolder(state, action, options = null) { if (!options) options = {}; if (!('clearNoteHistory' in options)) options.clearNoteHistory = true; - let newState = Object.assign({}, state); + const newState = Object.assign({}, state); newState.selectedFolderId = 'folderId' in action ? action.folderId : action.id; if (!newState.selectedFolderId) { newState.notesParentType = defaultNotesParentType(state, 'Folder'); @@ -306,7 +306,7 @@ function changeSelectedNotes(state, action, options = null) { if (!noteIds.length) return state; // Nothing to unselect if (state.selectedNoteIds.length <= 1) return state; // Cannot unselect the last note - let newSelectedNoteIds = []; + const newSelectedNoteIds = []; for (let i = 0; i < newState.selectedNoteIds.length; i++) { const id = newState.selectedNoteIds[i]; if (noteIds.indexOf(id) >= 0) continue; @@ -334,7 +334,7 @@ function changeSelectedNotes(state, action, options = null) { function removeItemFromArray(array, property, value) { for (let i = 0; i !== array.length; ++i) { - let currentItem = array[i]; + const currentItem = array[i]; if (currentItem[property] === value) { array.splice(i, 1); break; @@ -366,7 +366,7 @@ const reducer = (state = defaultState, action) => { const selectRangeId2 = action.id; if (selectRangeId1 === selectRangeId2) return state; - let newSelectedNoteIds = state.selectedNoteIds.slice(); + const newSelectedNoteIds = state.selectedNoteIds.slice(); let selectionStarted = false; for (let i = 0; i < state.notes.length; i++) { const id = state.notes[i].id; @@ -445,7 +445,7 @@ const reducer = (state = defaultState, action) => { case 'SETTING_UPDATE_ONE': { newState = Object.assign({}, state); - let newSettings = Object.assign({}, state.settings); + const newSettings = Object.assign({}, state.settings); newSettings[action.key] = action.value; newState.settings = newSettings; } @@ -483,9 +483,9 @@ const reducer = (state = defaultState, action) => { let movedNotePreviousIndex = 0; let noteFolderHasChanged = false; let newNotes = state.notes.slice(); - var found = false; + let found = false; for (let i = 0; i < newNotes.length; i++) { - let n = newNotes[i]; + const n = newNotes[i]; if (n.id == modNote.id) { // Note is still in the same folder if (noteIsInFolder(modNote, n.parent_id)) { @@ -493,7 +493,7 @@ const reducer = (state = defaultState, action) => { // the object we already have. newNotes[i] = Object.assign({}, newNotes[i]); - for (let n in modNote) { + for (const n in modNote) { if (!modNote.hasOwnProperty(n)) continue; newNotes[i][n] = modNote[n]; } @@ -606,7 +606,7 @@ const reducer = (state = defaultState, action) => { case 'NOTE_TAG_REMOVE': { newState = updateOneItem(state, action, 'tags'); - let tagRemoved = action.item; + const tagRemoved = action.item; newState.selectedNoteTags = removeItemFromArray(newState.selectedNoteTags.splice(0), 'id', tagRemoved.id); } break; @@ -698,7 +698,7 @@ const reducer = (state = defaultState, action) => { case 'SEARCH_ADD': { newState = Object.assign({}, state); - let searches = newState.searches.slice(); + const searches = newState.searches.slice(); searches.push(action.search); newState.searches = searches; } @@ -707,7 +707,7 @@ const reducer = (state = defaultState, action) => { case 'SEARCH_UPDATE': { newState = Object.assign({}, state); - let searches = newState.searches.slice(); + const searches = newState.searches.slice(); let found = false; for (let i = 0; i < searches.length; i++) { if (searches[i].id === action.search.id) { @@ -773,7 +773,7 @@ const reducer = (state = defaultState, action) => { { newState = Object.assign({}, state); const decryptionWorker = Object.assign({}, newState.decryptionWorker); - for (var n in action) { + for (const n in action) { if (!action.hasOwnProperty(n) || n === 'type') continue; decryptionWorker[n] = action[n]; } diff --git a/ReactNativeClient/lib/services/DecryptionWorker.js b/ReactNativeClient/lib/services/DecryptionWorker.js index 4c1fbf4f7..53e60f27b 100644 --- a/ReactNativeClient/lib/services/DecryptionWorker.js +++ b/ReactNativeClient/lib/services/DecryptionWorker.js @@ -131,7 +131,7 @@ class DecryptionWorker { this.state_ = 'started'; - let excludedIds = []; + const excludedIds = []; this.dispatch({ type: 'ENCRYPTION_HAS_DISABLED_ITEMS', value: false }); this.dispatchReport({ state: 'started' }); diff --git a/ReactNativeClient/lib/services/EncryptionService.js b/ReactNativeClient/lib/services/EncryptionService.js index 834bd0b43..578b7d013 100644 --- a/ReactNativeClient/lib/services/EncryptionService.js +++ b/ReactNativeClient/lib/services/EncryptionService.js @@ -68,7 +68,7 @@ class EncryptionService { Setting.setValue('encryption.activeMasterKeyId', masterKey.id); if (password) { - let passwordCache = Setting.value('encryption.passwordCache'); + const passwordCache = Setting.value('encryption.passwordCache'); passwordCache[masterKey.id] = password; Setting.setValue('encryption.passwordCache', passwordCache); } @@ -101,7 +101,7 @@ class EncryptionService { this.logger().info(`Trying to load ${masterKeys.length} master keys...`); for (let i = 0; i < masterKeys.length; i++) { - let mk = masterKeys[i]; + const mk = masterKeys[i]; const password = passwords[mk.id]; if (this.isMasterKeyLoaded(mk.id)) continue; if (!password) continue; @@ -118,7 +118,7 @@ class EncryptionService { loadedMasterKeysCount() { let output = 0; - for (let n in this.loadedMasterKeys_) { + for (const n in this.loadedMasterKeys_) { if (!this.loadedMasterKeys_[n]) continue; output++; } @@ -161,7 +161,7 @@ class EncryptionService { } unloadAllMasterKeys() { - for (let id in this.loadedMasterKeys_) { + for (const id in this.loadedMasterKeys_) { if (!this.loadedMasterKeys_.hasOwnProperty(id)) continue; this.unloadMasterKey(this.loadedMasterKeys_[id]); } @@ -178,8 +178,8 @@ class EncryptionService { } loadedMasterKeyIds() { - let output = []; - for (let id in this.loadedMasterKeys_) { + const output = []; + for (const id in this.loadedMasterKeys_) { if (!this.loadedMasterKeys_.hasOwnProperty(id)) continue; output.push(id); } @@ -629,7 +629,7 @@ class EncryptionService { parseInt(reader.read(6), 16); // Read the size and move the reader pointer forward - let output = {}; + const output = {}; for (let i = 0; i < template.fields.length; i++) { const m = template.fields[i]; diff --git a/ReactNativeClient/lib/services/ExternalEditWatcher.js b/ReactNativeClient/lib/services/ExternalEditWatcher.js index ebbce96bf..173405f21 100644 --- a/ReactNativeClient/lib/services/ExternalEditWatcher.js +++ b/ReactNativeClient/lib/services/ExternalEditWatcher.js @@ -150,7 +150,7 @@ class ExternalEditWatcher { const output = []; const watchedPaths = this.watcher_.getWatched(); - for (let dirName in watchedPaths) { + for (const dirName in watchedPaths) { if (!watchedPaths.hasOwnProperty(dirName)) continue; for (let i = 0; i < watchedPaths[dirName].length; i++) { @@ -169,7 +169,7 @@ class ExternalEditWatcher { const watchedPaths = this.watcher_.getWatched(); - for (let dirName in watchedPaths) { + for (const dirName in watchedPaths) { if (!watchedPaths.hasOwnProperty(dirName)) continue; for (let i = 0; i < watchedPaths[dirName].length; i++) { @@ -216,7 +216,7 @@ class ExternalEditWatcher { const wrapError = error => { if (!error) return error; - let msg = error.message ? [error.message] : []; + const msg = error.message ? [error.message] : []; msg.push(`Command was: "${path}" ${args.join(' ')}`); error.message = msg.join('\n\n'); return error; diff --git a/ReactNativeClient/lib/services/InteropService.js b/ReactNativeClient/lib/services/InteropService.js index 2cf2ab220..86b23c515 100644 --- a/ReactNativeClient/lib/services/InteropService.js +++ b/ReactNativeClient/lib/services/InteropService.js @@ -277,7 +277,7 @@ class InteropService { }); }; - let exportedNoteIds = []; + const exportedNoteIds = []; let resourceIds = []; const folderIds = await Folder.allIds(); @@ -317,7 +317,7 @@ class InteropService { const noteTags = await NoteTag.all(); - let exportedTagIds = []; + const exportedTagIds = []; for (let i = 0; i < noteTags.length; i++) { const noteTag = noteTags[i]; diff --git a/ReactNativeClient/lib/services/InteropService_Exporter_Md.js b/ReactNativeClient/lib/services/InteropService_Exporter_Md.js index 3c8a9d8a2..370d696b3 100644 --- a/ReactNativeClient/lib/services/InteropService_Exporter_Md.js +++ b/ReactNativeClient/lib/services/InteropService_Exporter_Md.js @@ -34,7 +34,7 @@ class InteropService_Exporter_Md extends InteropService_Exporter_Base { async relaceLinkedItemIdsByRelativePaths_(item) { const relativePathToRoot = await this.makeDirPath_(item, '..'); - let newBody = await this.replaceResourceIdsByRelativePaths_(item.body, relativePathToRoot); + const newBody = await this.replaceResourceIdsByRelativePaths_(item.body, relativePathToRoot); return await this.replaceNoteIdsByRelativePaths_(newBody, relativePathToRoot); } @@ -42,7 +42,7 @@ class InteropService_Exporter_Md extends InteropService_Exporter_Base { const linkedResourceIds = await Note.linkedResourceIds(noteBody); const resourcePaths = this.context() && this.context().resourcePaths ? this.context().resourcePaths : {}; - let createRelativePath = function(resourcePath) { + const createRelativePath = function(resourcePath) { return `${relativePathToRoot}_resources/${basename(resourcePath)}`; }; return await this.replaceItemIdsByRelativePaths_(noteBody, linkedResourceIds, resourcePaths, createRelativePath); @@ -52,7 +52,7 @@ class InteropService_Exporter_Md extends InteropService_Exporter_Base { const linkedNoteIds = await Note.linkedNoteIds(noteBody); const notePaths = this.context() && this.context().notePaths ? this.context().notePaths : {}; - let createRelativePath = function(notePath) { + const createRelativePath = function(notePath) { return encodeURI(`${relativePathToRoot}${notePath}`.trim()); }; return await this.replaceItemIdsByRelativePaths_(noteBody, linkedNoteIds, notePaths, createRelativePath); @@ -63,7 +63,7 @@ class InteropService_Exporter_Md extends InteropService_Exporter_Base { for (let i = 0; i < linkedItemIds.length; i++) { const id = linkedItemIds[i]; - let itemPath = fn_createRelativePath(paths[id]); + const itemPath = fn_createRelativePath(paths[id]); newBody = newBody.replace(new RegExp(`:/${id}`, 'g'), itemPath); } @@ -114,9 +114,9 @@ class InteropService_Exporter_Md extends InteropService_Exporter_Base { } else if (item.type_ === BaseModel.TYPE_NOTE) { const notePaths = this.context() && this.context().notePaths ? this.context().notePaths : {}; - let noteFilePath = `${this.destDir_}/${notePaths[item.id]}`; + const noteFilePath = `${this.destDir_}/${notePaths[item.id]}`; - let noteBody = await this.relaceLinkedItemIdsByRelativePaths_(item); + const noteBody = await this.relaceLinkedItemIdsByRelativePaths_(item); const modNote = Object.assign({}, item, { body: noteBody }); const noteContent = await Note.serializeForEdit(modNote); await shim.fsDriver().mkdir(dirname(noteFilePath)); diff --git a/ReactNativeClient/lib/services/InteropService_Importer_Jex.js b/ReactNativeClient/lib/services/InteropService_Importer_Jex.js index 333d0ac9a..bca806bc1 100644 --- a/ReactNativeClient/lib/services/InteropService_Importer_Jex.js +++ b/ReactNativeClient/lib/services/InteropService_Importer_Jex.js @@ -15,9 +15,9 @@ class InteropService_Importer_Jex extends InteropService_Importer_Base { cwd: tempDir, }); } catch (error) { - let msg = [`Cannot untar file ${this.sourcePath_}`, error.message]; + const msg = [`Cannot untar file ${this.sourcePath_}`, error.message]; if (error.data) msg.push(JSON.stringify(error.data)); - let e = new Error(msg.join(': ')); + const e = new Error(msg.join(': ')); throw e; } diff --git a/ReactNativeClient/lib/services/InteropService_Importer_Raw.js b/ReactNativeClient/lib/services/InteropService_Importer_Raw.js index 5bb19047b..ceffdbaba 100644 --- a/ReactNativeClient/lib/services/InteropService_Importer_Raw.js +++ b/ReactNativeClient/lib/services/InteropService_Importer_Raw.js @@ -78,7 +78,7 @@ class InteropService_Importer_Raw extends InteropService_Importer_Base { if (fileExtension(stat.path).toLowerCase() !== 'md') continue; const content = await shim.fsDriver().readFile(`${this.sourcePath_}/${stat.path}`); - let item = await BaseItem.unserialize(content); + const item = await BaseItem.unserialize(content); const itemType = item.type_; const ItemClass = BaseItem.itemClass(item); diff --git a/ReactNativeClient/lib/services/KvStore.js b/ReactNativeClient/lib/services/KvStore.js index 9129cbf37..cd292f658 100644 --- a/ReactNativeClient/lib/services/KvStore.js +++ b/ReactNativeClient/lib/services/KvStore.js @@ -84,7 +84,7 @@ class KvStore extends BaseService { } async searchByPrefix(prefix) { - let results = await this.db().selectAll('SELECT `key`, `value`, `type` FROM key_values WHERE `key` LIKE ?', [`${prefix}%`]); + const results = await this.db().selectAll('SELECT `key`, `value`, `type` FROM key_values WHERE `key` LIKE ?', [`${prefix}%`]); return this.formatValues_(results); } diff --git a/ReactNativeClient/lib/services/NavService.js b/ReactNativeClient/lib/services/NavService.js index 472e1a3d9..417301fbf 100644 --- a/ReactNativeClient/lib/services/NavService.js +++ b/ReactNativeClient/lib/services/NavService.js @@ -1,7 +1,7 @@ class NavService { static async go(routeName) { if (this.handlers_.length) { - let r = await this.handlers_[this.handlers_.length - 1](); + const r = await this.handlers_[this.handlers_.length - 1](); if (r) return r; } diff --git a/ReactNativeClient/lib/services/RevisionService.js b/ReactNativeClient/lib/services/RevisionService.js index 1090f8d1f..21ad46c28 100644 --- a/ReactNativeClient/lib/services/RevisionService.js +++ b/ReactNativeClient/lib/services/RevisionService.js @@ -42,7 +42,7 @@ class RevisionService extends BaseService { noteMetadata_(note) { const excludedFields = ['type_', 'title', 'body', 'created_time', 'updated_time', 'encryption_applied', 'encryption_cipher_text', 'is_conflict']; const md = {}; - for (let k in note) { + for (const k in note) { if (excludedFields.indexOf(k) >= 0) continue; md[k] = note[k]; } diff --git a/ReactNativeClient/lib/services/SearchEngine.js b/ReactNativeClient/lib/services/SearchEngine.js index 9b71f8b71..40db001eb 100644 --- a/ReactNativeClient/lib/services/SearchEngine.js +++ b/ReactNativeClient/lib/services/SearchEngine.js @@ -316,7 +316,7 @@ class SearchEngine { let termCount = 0; const keys = []; - for (let col in terms) { + for (const col in terms) { if (!terms.hasOwnProperty(col)) continue; if (!terms[col].length) { @@ -356,7 +356,7 @@ class SearchEngine { if (!parsedQuery || !parsedQuery.termCount) return []; let output = []; - for (let col in parsedQuery.terms) { + for (const col in parsedQuery.terms) { if (!parsedQuery.terms.hasOwnProperty(col)) continue; output = output.concat(parsedQuery.terms[col]); } diff --git a/ReactNativeClient/lib/services/back-button.js b/ReactNativeClient/lib/services/back-button.js index e6009046b..789ee8621 100644 --- a/ReactNativeClient/lib/services/back-button.js +++ b/ReactNativeClient/lib/services/back-button.js @@ -11,7 +11,7 @@ class BackButtonService { static async back() { if (this.handlers_.length) { - let r = await this.handlers_[this.handlers_.length - 1](); + const r = await this.handlers_[this.handlers_.length - 1](); if (r) return r; } diff --git a/ReactNativeClient/lib/services/report.js b/ReactNativeClient/lib/services/report.js index 5501bd167..7f346846f 100644 --- a/ReactNativeClient/lib/services/report.js +++ b/ReactNativeClient/lib/services/report.js @@ -13,7 +13,7 @@ const { toTitleCase } = require('lib/string-utils.js'); class ReportService { csvEscapeCell(cell) { cell = this.csvValueToString(cell); - let output = cell.replace(/"/, '""'); + const output = cell.replace(/"/, '""'); if (this.csvCellRequiresQuotes(cell, ',')) { return `"${output}"`; } @@ -40,7 +40,7 @@ class ReportService { } csvCreate(rows) { - let output = []; + const output = []; for (let i = 0; i < rows.length; i++) { output.push(this.csvCreateLine(rows[i])); } @@ -52,7 +52,7 @@ class ReportService { if (!option.format) option.format = 'array'; const itemTypes = BaseItem.syncItemTypes(); - let output = []; + const output = []; output.push(['type', 'id', 'updated_time', 'sync_time', 'is_conflict']); for (let i = 0; i < itemTypes.length; i++) { const itemType = itemTypes[i]; @@ -61,7 +61,7 @@ class ReportService { for (let j = 0; j < items.length; j++) { const item = items[j]; - let row = [itemType, item.id, item.updated_time, item.sync_time]; + const row = [itemType, item.id, item.updated_time, item.sync_time]; row.push('is_conflict' in item ? item.is_conflict : ''); output.push(row); } @@ -71,7 +71,7 @@ class ReportService { } async syncStatus(syncTarget) { - let output = { + const output = { items: {}, total: {}, }; @@ -79,9 +79,9 @@ class ReportService { let itemCount = 0; let syncedCount = 0; for (let i = 0; i < BaseItem.syncItemDefinitions_.length; i++) { - let d = BaseItem.syncItemDefinitions_[i]; - let ItemClass = BaseItem.getClass(d.className); - let o = { + const d = BaseItem.syncItemDefinitions_[i]; + const ItemClass = BaseItem.getClass(d.className); + const o = { total: await ItemClass.count(), synced: await ItemClass.syncedCount(syncTarget), }; @@ -90,7 +90,7 @@ class ReportService { syncedCount += o.synced; } - let conflictedCount = await Note.conflictedCount(); + const conflictedCount = await Note.conflictedCount(); output.total = { total: itemCount - conflictedCount, @@ -111,8 +111,8 @@ class ReportService { } async status(syncTarget) { - let r = await this.syncStatus(syncTarget); - let sections = []; + const r = await this.syncStatus(syncTarget); + const sections = []; let section = null; const disabledItems = await BaseItem.syncDisabledItems(syncTarget); @@ -202,7 +202,7 @@ class ReportService { section = { title: _('Sync status (synced items / total items)'), body: [] }; - for (let n in r.items) { + for (const n in r.items) { if (!r.items.hasOwnProperty(n)) continue; section.body.push(_('%s: %d/%d', n, r.items[n].synced, r.items[n].total)); } diff --git a/ReactNativeClient/lib/services/rest/Api.js b/ReactNativeClient/lib/services/rest/Api.js index 82355022f..806fb3e95 100644 --- a/ReactNativeClient/lib/services/rest/Api.js +++ b/ReactNativeClient/lib/services/rest/Api.js @@ -74,7 +74,7 @@ class Api { const pathParts = path.split('/'); const callSuffix = pathParts.splice(0, 1)[0]; - let callName = `action_${callSuffix}`; + const callName = `action_${callSuffix}`; return { callName: callName, params: pathParts, @@ -121,7 +121,7 @@ class Api { let id = null; let link = null; - let params = parsedPath.params; + const params = parsedPath.params; if (params.length >= 1) { id = params[0]; @@ -389,7 +389,7 @@ class Api { const resourceIds = await Note.linkedResourceIds(note.body); const output = []; const loadOptions = this.defaultLoadOptions_(request); - for (let resourceId of resourceIds) { + for (const resourceId of resourceIds) { output.push(await Resource.load(resourceId, loadOptions)); } return output; @@ -456,7 +456,7 @@ class Api { if (!note) throw new ErrorNotFound(); - let updatedNote = await this.defaultAction_(BaseModel.TYPE_NOTE, request, id, link); + const updatedNote = await this.defaultAction_(BaseModel.TYPE_NOTE, request, id, link); const requestNote = JSON.parse(request.body); if (requestNote.tags || requestNote.tags === '') { @@ -670,7 +670,7 @@ class Api { } async createResourcesFromPaths_(urls) { - for (let url in urls) { + for (const url in urls) { if (!urls.hasOwnProperty(url)) continue; const urlInfo = urls[url]; try { @@ -684,7 +684,7 @@ class Api { } async removeTempFiles_(urls) { - for (let url in urls) { + for (const url in urls) { if (!urls.hasOwnProperty(url)) continue; const urlInfo = urls[url]; try { diff --git a/ReactNativeClient/lib/shim-init-node.js b/ReactNativeClient/lib/shim-init-node.js index 4b79368e5..123dc5217 100644 --- a/ReactNativeClient/lib/shim-init-node.js +++ b/ReactNativeClient/lib/shim-init-node.js @@ -153,7 +153,7 @@ function shimInit() { resource.file_extension = fileExt; - let targetPath = Resource.fullPath(resource); + const targetPath = Resource.fullPath(resource); if (resource.mime == 'image/jpeg' || resource.mime == 'image/jpg' || resource.mime == 'image/png') { await resizeImage_(filePath, targetPath, resource.mime); @@ -198,8 +198,8 @@ function shimInit() { if (!createFileURL) { newBody.push(Resource.markdownTag(resource)); } else { - let filename = escapeLinkText(basename(filePath)); // to get same filename as standard drag and drop - let fileURL = `[${filename}](${toFileProtocolPath(filePath)})`; + const filename = escapeLinkText(basename(filePath)); // to get same filename as standard drag and drop + const fileURL = `[${filename}](${toFileProtocolPath(filePath)})`; newBody.push(fileURL); } @@ -370,7 +370,7 @@ function shimInit() { shim.httpAgent = url => { if (shim.isLinux() && !shim.httpAgent) { - var AgentSettings = { + const AgentSettings = { keepAlive: true, maxSockets: 1, keepAliveMsecs: 5000, diff --git a/ReactNativeClient/lib/shim-init-react.js b/ReactNativeClient/lib/shim-init-react.js index 085640f8b..60d7e981b 100644 --- a/ReactNativeClient/lib/shim-init-react.js +++ b/ReactNativeClient/lib/shim-init-react.js @@ -29,8 +29,8 @@ function shimInit() { shim.randomBytes = async count => { const randomBytes = await generateSecureRandom(count); - let temp = []; - for (let n in randomBytes) { + const temp = []; + for (const n in randomBytes) { if (!randomBytes.hasOwnProperty(n)) continue; temp.push(randomBytes[n]); } @@ -53,11 +53,11 @@ function shimInit() { shim.fetchBlob = async function(url, options) { if (!options || !options.path) throw new Error('fetchBlob: target file path is missing'); - let headers = options.headers ? options.headers : {}; - let method = options.method ? options.method : 'GET'; + const headers = options.headers ? options.headers : {}; + const method = options.method ? options.method : 'GET'; const overwrite = 'overwrite' in options ? options.overwrite : true; - let dirs = RNFetchBlob.fs.dirs; + const dirs = RNFetchBlob.fs.dirs; let localFilePath = options.path; if (localFilePath.indexOf('/') !== 0) localFilePath = `${dirs.DocumentDir}/${localFilePath}`; @@ -80,7 +80,7 @@ function shimInit() { const response = await shim.fetchWithRetry(doFetchBlob, options); // Returns an object that's roughtly compatible with a standard Response object - let output = { + const output = { ok: response.respInfo.status < 400, path: response.data, text: response.text, @@ -102,7 +102,7 @@ function shimInit() { const method = options.method ? options.method : 'POST'; try { - let response = await RNFetchBlob.fetch(method, url, headers, RNFetchBlob.wrap(options.path)); + const response = await RNFetchBlob.fetch(method, url, headers, RNFetchBlob.wrap(options.path)); // Returns an object that's roughtly compatible with a standard Response object return { @@ -169,7 +169,7 @@ function shimInit() { resource.title = basename(filePath); resource.file_extension = ext; - let targetPath = Resource.fullPath(resource); + const targetPath = Resource.fullPath(resource); await shim.fsDriver().copy(filePath, targetPath); if (defaultProps) { diff --git a/ReactNativeClient/lib/shim.js b/ReactNativeClient/lib/shim.js index f3405dfbe..9912c5ad1 100644 --- a/ReactNativeClient/lib/shim.js +++ b/ReactNativeClient/lib/shim.js @@ -1,6 +1,6 @@ /* eslint @typescript-eslint/no-unused-vars: 0, no-unused-vars: ["error", { "argsIgnorePattern": ".*" }], */ -let shim = {}; +const shim = {}; shim.isNode = () => { if (typeof process === 'undefined') return false; diff --git a/ReactNativeClient/lib/string-utils-common.js b/ReactNativeClient/lib/string-utils-common.js index 1c94b64ff..cff1117d4 100644 --- a/ReactNativeClient/lib/string-utils-common.js +++ b/ReactNativeClient/lib/string-utils-common.js @@ -38,7 +38,7 @@ function replaceRegexDiacritics(regexString) { let output = ''; for (let i = 0; i < regexString.length; i++) { - let c = regexString[i]; + const c = regexString[i]; const r = diacriticReplacements[c]; if (r) { output += r; diff --git a/ReactNativeClient/lib/string-utils.js b/ReactNativeClient/lib/string-utils.js index c5dcd0891..509bc39a4 100644 --- a/ReactNativeClient/lib/string-utils.js +++ b/ReactNativeClient/lib/string-utils.js @@ -88,7 +88,7 @@ const defaultDiacriticsRemovalMap = [ ]; function removeDiacritics(str) { - for (var i = 0; i < defaultDiacriticsRemovalMap.length; i++) { + for (let i = 0; i < defaultDiacriticsRemovalMap.length; i++) { str = str.replace(defaultDiacriticsRemovalMap[i].letters, defaultDiacriticsRemovalMap[i].base); } @@ -124,7 +124,7 @@ function wrap(text, indent, width) { } function commandArgumentsToString(args) { - let output = []; + const output = []; for (let i = 0; i < args.length; i++) { let arg = args[i]; const quote = arg.indexOf('"') >= 0 ? '\'' : '"'; @@ -142,13 +142,13 @@ function splitCommandString(command, options = null) { options.handleEscape = true; } - let args = []; + const args = []; let state = 'start'; let current = ''; let quote = '"'; let escapeNext = false; for (let i = 0; i < command.length; i++) { - let c = command[i]; + const c = command[i]; if (state == 'quotes') { if (c != quote) { diff --git a/ReactNativeClient/lib/synchronizer.js b/ReactNativeClient/lib/synchronizer.js index 33e830da9..d336a0f94 100644 --- a/ReactNativeClient/lib/synchronizer.js +++ b/ReactNativeClient/lib/synchronizer.js @@ -90,7 +90,7 @@ class Synchronizer { } static reportToLines(report) { - let lines = []; + const lines = []; if (report.createLocal) lines.push(_('Created local items: %d.', report.createLocal)); if (report.updateLocal) lines.push(_('Updated local items: %d.', report.updateLocal)); if (report.createRemote) lines.push(_('Created remote items: %d.', report.createRemote)); @@ -107,7 +107,7 @@ class Synchronizer { } logSyncOperation(action, local = null, remote = null, message = null, actionCount = 1) { - let line = ['Sync']; + const line = ['Sync']; line.push(action); if (message) line.push(message); @@ -117,13 +117,13 @@ class Synchronizer { if (type) line.push(BaseItem.modelTypeToClassName(type)); if (local) { - let s = []; + const s = []; s.push(local.id); line.push(`(Local ${s.join(', ')})`); } if (remote) { - let s = []; + const s = []; s.push(remote.id ? remote.id : remote.path); line.push(`(Remote ${s.join(', ')})`); } @@ -140,7 +140,7 @@ class Synchronizer { async logSyncSummary(report) { this.logger().info('Operations completed: '); - for (let n in report) { + for (const n in report) { if (!report.hasOwnProperty(n)) continue; if (n == 'errors') continue; if (n == 'starting') continue; @@ -149,9 +149,9 @@ class Synchronizer { if (n == 'completedTime') continue; this.logger().info(`${n}: ${report[n] ? report[n] : '-'}`); } - let folderCount = await Folder.count(); - let noteCount = await Note.count(); - let resourceCount = await Resource.count(); + const folderCount = await Folder.count(); + const noteCount = await Note.count(); + const resourceCount = await Resource.count(); this.logger().info(`Total folders: ${folderCount}`); this.logger().info(`Total notes: ${noteCount}`); this.logger().info(`Total resources: ${resourceCount}`); @@ -159,7 +159,7 @@ class Synchronizer { if (report.errors && report.errors.length) { this.logger().warn('There was some errors:'); for (let i = 0; i < report.errors.length; i++) { - let e = report.errors[i]; + const e = report.errors[i]; this.logger().warn(e); } } @@ -275,7 +275,7 @@ class Synchronizer { if (!options) options = {}; if (this.state() != 'idle') { - let error = new Error(sprintf('Synchronisation is already in progress. State: %s', this.state())); + const error = new Error(sprintf('Synchronisation is already in progress. State: %s', this.state())); error.code = 'alreadyStarted'; throw error; } @@ -299,9 +299,9 @@ class Synchronizer { const masterKeysBefore = await MasterKey.count(); let hasAutoEnabledEncryption = false; - let synchronizationId = time.unixMs().toString(); + const synchronizationId = time.unixMs().toString(); - let outputContext = Object.assign({}, lastContext); + const outputContext = Object.assign({}, lastContext); this.dispatch({ type: 'SYNC_STARTED' }); @@ -335,7 +335,7 @@ class Synchronizer { // ======================================================================== if (syncSteps.indexOf('update_remote') >= 0) { - let donePaths = []; + const donePaths = []; const completeItemProcessing = path => { donePaths.push(path); @@ -344,15 +344,15 @@ class Synchronizer { while (true) { if (this.cancelling()) break; - let result = await BaseItem.itemsThatNeedSync(syncTargetId); - let locals = result.items; + const result = await BaseItem.itemsThatNeedSync(syncTargetId); + const locals = result.items; for (let i = 0; i < locals.length; i++) { if (this.cancelling()) break; let local = locals[i]; - let ItemClass = BaseItem.itemClass(local); - let path = BaseItem.systemPath(local); + const ItemClass = BaseItem.itemClass(local); + const path = BaseItem.systemPath(local); // Safety check to avoid infinite loops. // - In fact this error is possible if the item is marked for sync (via sync_time or force_sync) while synchronisation is in @@ -363,7 +363,7 @@ class Synchronizer { // (by setting an updated_time less than current time). if (donePaths.indexOf(path) >= 0) throw new JoplinError(sprintf('Processing a path that has already been done: %s. sync_time was not updated? Remote item has an updated_time in the future?', path), 'processingPathTwice'); - let remote = await this.api().stat(path); + const remote = await this.api().stat(path); let action = null; let reason = ''; @@ -434,7 +434,7 @@ class Synchronizer { local = result.resource; const localResourceContentPath = result.path; - if (local.size >= 10 * 1000* 1000) { + if (local.size >= 10 * 1000 * 1000) { this.logger().warn(`Uploading a large resource (resourceId: ${local.id}, size:${local.size} bytes) which may tie up the sync process.`); } @@ -520,7 +520,7 @@ class Synchronizer { // ------------------------------------------------------------------------------ if (mustHandleConflict) { - let conflictedNote = Object.assign({}, local); + const conflictedNote = Object.assign({}, local); delete conflictedNote.id; conflictedNote.is_conflict = 1; await Note.save(conflictedNote, { autoTimestamp: false, changeSource: ItemChange.SOURCE_SYNC }); @@ -557,12 +557,12 @@ class Synchronizer { // ======================================================================== if (syncSteps.indexOf('delete_remote') >= 0) { - let deletedItems = await BaseItem.deletedItems(syncTargetId); + const deletedItems = await BaseItem.deletedItems(syncTargetId); for (let i = 0; i < deletedItems.length; i++) { if (this.cancelling()) break; - let item = deletedItems[i]; - let path = BaseItem.systemPath(item.item_id); + const item = deletedItems[i]; + const path = BaseItem.systemPath(item.item_id); this.logSyncOperation('deleteRemote', null, { id: item.item_id }, 'local has been deleted'); await this.api().delete(path); @@ -592,14 +592,14 @@ class Synchronizer { let context = null; let newDeltaContext = null; - let localFoldersToDelete = []; + const localFoldersToDelete = []; let hasCancelled = false; if (lastContext.delta) context = lastContext.delta; while (true) { if (this.cancelling() || hasCancelled) break; - let listResult = await this.api().delta('', { + const listResult = await this.api().delta('', { context: context, // allItemIdsHandler() provides a way for drivers that don't have a delta API to @@ -616,7 +616,7 @@ class Synchronizer { logger: this.logger(), }); - let remotes = listResult.items; + const remotes = listResult.items; this.logSyncOperation('fetchingTotal', null, null, 'Fetching delta items from sync target', remotes.length); @@ -636,17 +636,17 @@ class Synchronizer { this.logSyncOperation('fetchingProcessed', null, null, 'Processing fetched item'); - let remote = remotes[i]; + const remote = remotes[i]; if (!BaseItem.isSystemPath(remote.path)) continue; // The delta API might return things like the .sync, .resource or the root folder const loadContent = async () => { - let task = await this.downloadQueue_.waitForResult(path); // await this.api().get(path); + const task = await this.downloadQueue_.waitForResult(path); // await this.api().get(path); if (task.error) throw task.error; if (!task.result) return null; return await BaseItem.unserialize(task.result); }; - let path = remote.path; + const path = remote.path; let action = null; let reason = ''; let local = await BaseItem.loadItemByPath(path); @@ -707,7 +707,7 @@ class Synchronizer { if (!content.user_updated_time) content.user_updated_time = content.updated_time; if (!content.user_created_time) content.user_created_time = content.created_time; - let options = { + const options = { autoTimestamp: false, nextQueries: BaseItem.updateSyncTimeQueries(syncTargetId, content, time.unixMs()), changeSource: ItemChange.SOURCE_SYNC, @@ -746,7 +746,7 @@ class Synchronizer { continue; } - let ItemClass = BaseItem.itemClass(local.type_); + const ItemClass = BaseItem.itemClass(local.type_); await ItemClass.delete(local.id, { trackDeleted: false, changeSource: ItemChange.SOURCE_SYNC }); } } diff --git a/ReactNativeClient/root.js b/ReactNativeClient/root.js index d848cb766..69b70655f 100644 --- a/ReactNativeClient/root.js +++ b/ReactNativeClient/root.js @@ -89,7 +89,7 @@ let storeDispatch = function() {}; const logReducerAction = function(action) { if (['SIDE_MENU_OPEN_PERCENT', 'SYNC_REPORT_UPDATE'].indexOf(action.type) >= 0) return; - let msg = [action.type]; + const msg = [action.type]; if (action.routeName) msg.push(action.routeName); // reg.logger().debug('Reducer action', msg.join(', ')); @@ -158,7 +158,7 @@ const generalMiddleware = store => next => async (action) => { return result; }; -let navHistory = []; +const navHistory = []; function historyCanGoBackTo(route) { if (route.routeName === 'Note') return false; @@ -233,7 +233,7 @@ const appReducer = (state = appDefaultState, action) => { // are loaded. Might be good enough since going back to different folders // is probably not a common workflow. for (let i = 0; i < navHistory.length; i++) { - let n = navHistory[i]; + const n = navHistory[i]; if (n.routeName == action.routeName) { navHistory[i] = Object.assign({}, action); } @@ -356,7 +356,7 @@ const appReducer = (state = appDefaultState, action) => { return reducer(newState, action); }; -let store = createStore(appReducer, applyMiddleware(generalMiddleware)); +const store = createStore(appReducer, applyMiddleware(generalMiddleware)); storeDispatch = store.dispatch; function resourceFetcher_downloadComplete(event) { @@ -403,7 +403,7 @@ async function initialize(dispatch) { dbLogger.setLevel(Logger.LEVEL_INFO); } - let db = new JoplinDatabase(new DatabaseDriverReactNative()); + const db = new JoplinDatabase(new DatabaseDriverReactNative()); db.setLogger(dbLogger); reg.setDb(db); @@ -516,7 +516,7 @@ async function initialize(dispatch) { items: masterKeys, }); - let folderId = Setting.value('activeFolderId'); + const folderId = Setting.value('activeFolderId'); let folder = await Folder.load(folderId); if (!folder) folder = await Folder.defaultFolder(); diff --git a/ReactNativeClient/tools/encodeAssets.js b/ReactNativeClient/tools/encodeAssets.js index ca5e5de60..57711fa05 100644 --- a/ReactNativeClient/tools/encodeAssets.js +++ b/ReactNativeClient/tools/encodeAssets.js @@ -5,12 +5,12 @@ const md5 = require('md5'); const rootDir = `${__dirname}/..`; const outputDir = `${rootDir}/pluginAssets`; -var walk = function(dir) { - var results = []; - var list = fs.readdirSync(dir); +const walk = function(dir) { + let results = []; + const list = fs.readdirSync(dir); list.forEach(function(file) { file = `${dir}/${file}`; - var stat = fs.statSync(file); + const stat = fs.statSync(file); if (stat && stat.isDirectory()) { results = results.concat(walk(file)); } else { diff --git a/Tools/build-release-stats.js b/Tools/build-release-stats.js index b7195c66c..9dd33207c 100644 --- a/Tools/build-release-stats.js +++ b/Tools/build-release-stats.js @@ -44,10 +44,10 @@ function createChangeLog(releases) { for (let i = 0; i < releases.length; i++) { const r = releases[i]; - let s = []; + const s = []; s.push(`## ${r.tag_name} - ${r.published_at}`); s.push(''); - let body = r.body.replace(/#(\d+)/g, '[#$1](https://github.com/laurent22/joplin/issues/$1)'); + const body = r.body.replace(/#(\d+)/g, '[#$1](https://github.com/laurent22/joplin/issues/$1)'); s.push(body); output.push(s.join('\n')); } diff --git a/Tools/build-translation.js b/Tools/build-translation.js index 466a707cd..4ea345481 100644 --- a/Tools/build-translation.js +++ b/Tools/build-translation.js @@ -27,9 +27,9 @@ function parsePoFile(filePath) { } function serializeTranslation(translation) { - let output = {}; + const output = {}; const translations = translation.translations['']; - for (let n in translations) { + for (const n in translations) { if (!translations.hasOwnProperty(n)) continue; if (n == '') continue; const t = translations[n]; @@ -64,7 +64,7 @@ function executablePath(file) { ]; for (const path of potentialPaths) { - let pathFile = path + file; + const pathFile = path + file; if (fs.existsSync(pathFile)) { return pathFile; } @@ -80,7 +80,7 @@ async function removePoHeaderDate(filePath) { } async function createPotFile(potFilePath, sources) { - let baseArgs = []; + const baseArgs = []; baseArgs.push('--from-code=utf-8'); baseArgs.push(`--output="${potFilePath}"`); baseArgs.push('--language=JavaScript'); @@ -91,7 +91,7 @@ async function createPotFile(potFilePath, sources) { baseArgs.push('--keyword=_n:1,2'); for (let i = 0; i < sources.length; i++) { - let args = baseArgs.slice(); + const args = baseArgs.slice(); if (i > 0) args.push('--join-existing'); args.push(sources[i]); let xgettextPath = 'xgettext'; @@ -114,7 +114,7 @@ async function mergePotToPo(potFilePath, poFilePath) { } function buildIndex(locales, stats) { - let output = []; + const output = []; output.push('var locales = {};'); output.push('var stats = {};'); @@ -223,7 +223,7 @@ function poFileUrl(locale) { } function translationStatusToMdTable(status) { - let output = []; + const output = []; output.push([' ', 'Language', 'Po File', 'Last translator', 'Percent done'].join(' | ')); output.push(['---', '---', '---', '---', '---'].join('|')); for (let i = 0; i < status.length; i++) { @@ -246,8 +246,8 @@ async function updateReadmeWithStats(stats) { async function main() { const argv = require('yargs').argv; - let potFilePath = `${cliLocalesDir}/joplin.pot`; - let jsonLocalesDir = `${cliDir}/build/locales`; + const potFilePath = `${cliLocalesDir}/joplin.pot`; + const jsonLocalesDir = `${cliDir}/build/locales`; const defaultLocale = 'en_GB'; const oldPotStatus = await translationStatus(false, potFilePath); @@ -284,9 +284,9 @@ async function main() { fs.mkdirpSync(jsonLocalesDir, 0o755); - let stats = []; + const stats = []; - let locales = availableLocales(defaultLocale); + const locales = availableLocales(defaultLocale); for (let i = 0; i < locales.length; i++) { const locale = locales[i]; diff --git a/Tools/build-welcome.js b/Tools/build-welcome.js index 0c9e3003b..76ff3ae04 100644 --- a/Tools/build-welcome.js +++ b/Tools/build-welcome.js @@ -130,7 +130,7 @@ async function main() { } const tags = []; - for (let n in tagIdsToTag) { + for (const n in tagIdsToTag) { if (!tagIdsToTag.hasOwnProperty(n)) continue; tags.push(tagIdsToTag[n]); } diff --git a/Tools/gulp/utils.js b/Tools/gulp/utils.js index 0ec5436e1..167ddeaf4 100644 --- a/Tools/gulp/utils.js +++ b/Tools/gulp/utils.js @@ -34,14 +34,14 @@ utils.execCommand = function(command) { utils.dirname = function(path) { if (!path) throw new Error('Path is empty'); - let s = path.split(/\/|\\/); + const s = path.split(/\/|\\/); s.pop(); return s.join('/'); }; utils.basename = function(path) { if (!path) throw new Error('Path is empty'); - let s = path.split(/\/|\\/); + const s = path.split(/\/|\\/); return s[s.length - 1]; }; @@ -63,7 +63,7 @@ utils.toSystemSlashes = function(path) { utils.fileExtension = function(path) { if (!path) throw new Error('Path is empty'); - let output = path.split('.'); + const output = path.split('.'); if (output.length <= 1) return ''; return output[output.length - 1]; }; diff --git a/Tools/release-android.js b/Tools/release-android.js index 1fcce69e0..85abb3b71 100644 --- a/Tools/release-android.js +++ b/Tools/release-android.js @@ -65,7 +65,7 @@ async function createRelease(name, tagName, version, rcSuffix) { console.info(`Creating release: ${suffix}`); if (name === '32bit') { - let filename = `${rnDir}/android/app/build.gradle`; + const filename = `${rnDir}/android/app/build.gradle`; let content = await fs.readFile(filename, 'utf8'); originalContents[filename] = content; content = content.replace(/abiFilters "armeabi-v7a", "x86", "arm64-v8a", "x86_64"/, 'abiFilters "armeabi-v7a", "x86"'); @@ -136,7 +136,7 @@ async function createRelease(name, tagName, version, rcSuffix) { await fs.copy('ReactNativeClient/android/app/build/outputs/apk/release/app-release.apk', `${releaseDir}/joplin-latest.apk`); } - for (let filename in originalContents) { + for (const filename in originalContents) { const content = originalContents[filename]; await fs.writeFile(filename, content); } diff --git a/Tools/release-clipper.js b/Tools/release-clipper.js index 678da9dbb..724ada171 100644 --- a/Tools/release-clipper.js +++ b/Tools/release-clipper.js @@ -22,8 +22,8 @@ async function copyToDist(distDir) { async function updateManifestVersionNumber(manifestPath) { const manifestText = await fs.readFile(manifestPath, 'utf-8'); - let manifest = JSON.parse(manifestText); - let v = manifest.version.split('.'); + const manifest = JSON.parse(manifestText); + const v = manifest.version.split('.'); const buildNumber = Number(v.pop()) + 1; v.push(buildNumber); manifest.version = v.join('.'); @@ -162,7 +162,7 @@ async function main() { }, }; - for (let distName in dists) { + for (const distName in dists) { const dist = dists[distName]; const distDir = `${clipperDir}/dist/${distName}`; await fs.remove(distDir); diff --git a/Tools/tool-utils.js b/Tools/tool-utils.js index 5acc2eb83..ec4cfc7da 100644 --- a/Tools/tool-utils.js +++ b/Tools/tool-utils.js @@ -22,7 +22,7 @@ toolUtils.execCommand = function(command) { }; toolUtils.execCommandWithPipes = function(executable, args) { - var spawn = require('child_process').spawn; + const spawn = require('child_process').spawn; return new Promise((resolve, reject) => { const child = spawn(executable, args, { stdio: 'inherit' }); diff --git a/Tools/update-readme-contributors.js b/Tools/update-readme-contributors.js index 2aea32c67..eb8441a3c 100644 --- a/Tools/update-readme-contributors.js +++ b/Tools/update-readme-contributors.js @@ -26,11 +26,11 @@ async function gitHubContributors(page) { } function contributorTable(contributors) { - let rows = []; + const rows = []; let row = []; rows.push(row); - let rowLength = 5; + const rowLength = 5; let contributorIndex = 0; while (contributorIndex < contributors.length) { const c = contributors[contributorIndex];