From 1b24276a4a2ab8e5b1814c8fe6ca222b9ab29de4 Mon Sep 17 00:00:00 2001 From: zadam Date: Wed, 21 Dec 2022 15:19:05 +0100 Subject: [PATCH] always use template strings instead of string concatenation --- src/anonymize.js | 2 +- src/app.js | 6 ++-- src/becca/becca_service.js | 2 +- src/becca/entities/abstract_entity.js | 2 +- src/becca/entities/branch.js | 2 +- src/becca/entities/note.js | 14 ++++---- src/becca/entities/note_revision.js | 4 +-- src/etapi/validators.js | 2 +- src/public/app/components/app_context.js | 2 +- src/public/app/components/component.js | 8 ++--- src/public/app/components/entrypoints.js | 8 ++--- src/public/app/components/tab_manager.js | 2 +- src/public/app/desktop.js | 2 +- src/public/app/entities/note_short.js | 4 +-- .../app/services/attribute_autocomplete.js | 2 +- src/public/app/services/attribute_parser.js | 4 +-- src/public/app/services/attribute_renderer.js | 16 +++++----- src/public/app/services/branches.js | 10 +++--- src/public/app/services/bundle.js | 2 +- src/public/app/services/clipboard.js | 6 ++-- src/public/app/services/css_class_manager.js | 2 +- src/public/app/services/date_notes.js | 10 +++--- src/public/app/services/froca.js | 8 ++--- .../app/services/frontend_script_api.js | 6 ++-- src/public/app/services/glob.js | 12 +++---- src/public/app/services/hoisted_note.js | 2 +- src/public/app/services/import.js | 6 ++-- src/public/app/services/library_loader.js | 4 +-- src/public/app/services/link.js | 8 ++--- src/public/app/services/note_autocomplete.js | 8 ++--- .../app/services/note_content_renderer.js | 8 ++--- src/public/app/services/note_list_renderer.js | 6 ++-- src/public/app/services/note_tooltip.js | 8 ++--- src/public/app/services/open.js | 12 +++---- src/public/app/services/protected_session.js | 6 ++-- src/public/app/services/render.js | 2 +- src/public/app/services/script_context.js | 2 +- src/public/app/services/search.js | 2 +- src/public/app/services/server.js | 8 ++--- src/public/app/services/shortcuts.js | 2 +- src/public/app/services/sync.js | 6 ++-- src/public/app/services/toast.js | 6 ++-- src/public/app/services/tree.js | 2 +- src/public/app/services/utils.js | 32 +++++++++---------- src/public/app/services/ws.js | 3 +- src/public/app/setup.js | 4 +-- .../attribute_widgets/attribute_detail.js | 10 +++--- .../attribute_widgets/attribute_editor.js | 4 +-- src/public/app/widgets/bookmark_switch.js | 2 +- src/public/app/widgets/buttons/calendar.js | 8 ++--- src/public/app/widgets/buttons/global_menu.js | 2 +- src/public/app/widgets/collapsible_widget.js | 2 +- src/public/app/widgets/dialogs/about.js | 2 +- .../app/widgets/dialogs/branch_prefix.js | 2 +- .../app/widgets/dialogs/bulk_actions.js | 2 +- src/public/app/widgets/dialogs/confirm.js | 4 +-- src/public/app/widgets/dialogs/export.js | 4 +-- .../app/widgets/dialogs/note_revisions.js | 8 ++--- src/public/app/widgets/dialogs/note_source.js | 6 ++-- .../app/widgets/dialogs/note_type_chooser.js | 2 +- .../app/widgets/dialogs/recent_changes.js | 2 +- src/public/app/widgets/find_in_html.js | 2 +- .../widgets/floating_buttons/code_buttons.js | 2 +- .../widgets/floating_buttons/zpetne_odkazy.js | 2 +- src/public/app/widgets/mermaid.js | 10 +++--- .../mobile_widgets/mobile_detail_menu.js | 2 +- src/public/app/widgets/note_detail.js | 16 +++++----- src/public/app/widgets/note_icon.js | 8 ++--- src/public/app/widgets/note_map.js | 10 +++--- src/public/app/widgets/note_tree.js | 14 ++++---- src/public/app/widgets/note_type.js | 2 +- src/public/app/widgets/quick_search.js | 4 +-- .../widgets/ribbon_widgets/edited_notes.js | 4 +-- .../widgets/ribbon_widgets/file_properties.js | 4 +-- .../ribbon_widgets/image_properties.js | 6 ++-- .../ribbon_widgets/note_info_widget.js | 4 +-- .../ribbon_widgets/promoted_attributes.js | 8 ++--- .../ribbon_widgets/search_definition.js | 2 +- .../widgets/ribbon_widgets/similar_notes.js | 2 +- .../widgets/search_options/search_string.js | 4 +-- src/public/app/widgets/shared_info.js | 4 +-- src/public/app/widgets/sync_status.js | 4 +-- src/public/app/widgets/tab_row.js | 12 +++---- .../app/widgets/type_widgets/editable_code.js | 2 +- .../app/widgets/type_widgets/editable_text.js | 4 +-- src/public/app/widgets/type_widgets/empty.js | 4 +-- src/public/app/widgets/type_widgets/file.js | 6 ++-- src/public/app/widgets/type_widgets/image.js | 4 +-- .../advanced/database_integrity_check.js | 2 +- .../type_widgets/options/appearance/fonts.js | 4 +-- .../type_widgets/options/appearance/theme.js | 2 +- .../widgets/type_widgets/options/backup.js | 2 +- .../widgets/type_widgets/options/shortcuts.js | 2 +- .../app/widgets/type_widgets/options/sync.js | 2 +- .../app/widgets/type_widgets/relation_map.js | 8 ++--- src/routes/api/autocomplete.js | 2 +- src/routes/api/clipper.js | 6 ++-- src/routes/api/database.js | 2 +- src/routes/api/image.js | 4 +-- src/routes/api/import.js | 2 +- src/routes/api/note_map.js | 6 ++-- src/routes/api/note_revisions.js | 7 ++-- src/routes/api/notes.js | 3 +- src/routes/api/sender.js | 4 +-- src/routes/api/sync.js | 2 +- src/routes/custom.js | 4 +-- src/services/anonymization.js | 2 +- src/services/asset_path.js | 2 +- src/services/attribute_formatter.js | 8 ++--- src/services/attributes.js | 2 +- src/services/backup.js | 2 +- src/services/bulk_actions.js | 4 +-- src/services/cloning.js | 2 +- src/services/consistency_checks.js | 6 ++-- src/services/data_dir.js | 14 ++++---- src/services/data_encryption.js | 2 +- src/services/date_notes.js | 2 +- src/services/date_utils.js | 8 ++--- src/services/events.js | 2 +- src/services/export/opml.js | 8 ++--- src/services/export/single.js | 8 ++--- src/services/export/zip.js | 31 +++++++++--------- src/services/handlers.js | 2 +- src/services/hidden_subtree.js | 8 +++-- src/services/image.js | 7 ++-- src/services/import/enex.js | 7 ++-- src/services/import/opml.js | 6 ++-- src/services/import/single.js | 2 +- src/services/import/zip.js | 12 +++---- src/services/log.js | 21 +++++------- src/services/migration.js | 16 +++++----- src/services/note_revisions.js | 2 +- src/services/notes.js | 10 +++--- src/services/options_init.js | 2 +- src/services/port.js | 2 +- src/services/request.js | 10 +++--- src/services/resource_dir.js | 4 +-- src/services/script.js | 10 +++--- .../expressions/note_content_fulltext.js | 2 +- src/services/search/services/parse.js | 6 ++-- src/services/search/services/search.js | 10 +++--- src/services/session_secret.js | 2 +- src/services/setup.js | 4 +-- src/services/special_notes.js | 8 ++--- src/services/sql.js | 16 +++++++--- src/services/sql_init.js | 6 ++-- src/services/sync.js | 11 ++++--- src/services/utils.js | 8 ++--- src/services/window.js | 4 +-- src/services/ws.js | 10 +++--- src/share/canvas_share.js | 2 +- src/share/content_renderer.js | 2 +- src/share/shaca/entities/note.js | 2 +- src/www | 8 ++--- 154 files changed, 433 insertions(+), 437 deletions(-) diff --git a/src/anonymize.js b/src/anonymize.js index 4599f3ac6..39cb44852 100644 --- a/src/anonymize.js +++ b/src/anonymize.js @@ -9,7 +9,7 @@ sqlInit.dbReady.then(async () => { const resp = await backupService.anonymize(); if (resp.success) { - console.log("Anonymized file has been saved to: " + resp.anonymizedFilePath); + console.log(`Anonymized file has been saved to: ${resp.anonymizedFilePath}`); process.exit(0); } else { diff --git a/src/app.js b/src/app.js index f1c8a4d65..c77189fef 100644 --- a/src/app.js +++ b/src/app.js @@ -66,12 +66,12 @@ const sessionParser = session({ name: 'trilium.sid', store: new FileStore({ ttl: 30 * 24 * 3600, - path: dataDir.TRILIUM_DATA_DIR + '/sessions' + path: `${dataDir.TRILIUM_DATA_DIR}/sessions` }) }); app.use(sessionParser); -app.use(favicon(__dirname + '/../images/app-icons/win/icon.ico')); +app.use(favicon(`${__dirname}/../images/app-icons/win/icon.ico`)); require('./routes/routes').register(app); @@ -91,7 +91,7 @@ app.use((err, req, res, next) => { // catch 404 and forward to error handler app.use((req, res, next) => { - const err = new Error('Router not found for request ' + req.url); + const err = new Error(`Router not found for request ${req.url}`); err.status = 404; next(err); }); diff --git a/src/becca/becca_service.js b/src/becca/becca_service.js index d666c502a..b96296bed 100644 --- a/src/becca/becca_service.js +++ b/src/becca/becca_service.js @@ -75,7 +75,7 @@ function getNoteTitle(childNoteId, parentNoteId) { const branch = parentNote ? becca.getBranchFromChildAndParent(childNote.noteId, parentNote.noteId) : null; - return ((branch && branch.prefix) ? `${branch.prefix} - ` : '') + title; + return `${(branch && branch.prefix) ? `${branch.prefix} - ` : ''}${title}`; } function getNoteTitleArrayForPath(notePathArray) { diff --git a/src/becca/entities/abstract_entity.js b/src/becca/entities/abstract_entity.js index ef634543e..8c1b7b755 100644 --- a/src/becca/entities/abstract_entity.js +++ b/src/becca/entities/abstract_entity.js @@ -31,7 +31,7 @@ class AbstractEntity { let contentToHash = ""; for (const propertyName of this.constructor.hashedProperties) { - contentToHash += "|" + this[propertyName]; + contentToHash += `|${this[propertyName]}`; } if (isDeleted) { diff --git a/src/becca/entities/branch.js b/src/becca/entities/branch.js index 2ed3ec070..263298e6c 100644 --- a/src/becca/entities/branch.js +++ b/src/becca/entities/branch.js @@ -185,7 +185,7 @@ class Branch extends AbstractEntity { // first delete children and then parent - this will show up better in recent changes - log.info("Deleting note " + note.noteId); + log.info(`Deleting note ${note.noteId}`); this.becca.notes[note.noteId].isBeingDeleted = true; diff --git a/src/becca/entities/note.js b/src/becca/entities/note.js index c71607dd5..2652d788a 100644 --- a/src/becca/entities/note.js +++ b/src/becca/entities/note.js @@ -211,7 +211,7 @@ class Note extends AbstractEntity { return undefined; } else { - throw new Error("Cannot find note content for noteId=" + this.noteId); + throw new Error(`Cannot find note content for noteId=${this.noteId}`); } } @@ -304,7 +304,7 @@ class Note extends AbstractEntity { sql.upsert("note_contents", "noteId", pojo); - const hash = utils.hash(this.noteId + "|" + pojo.content.toString()); + const hash = utils.hash(`${this.noteId}|${pojo.content.toString()}`); entityChangesService.addEntityChange({ entityName: 'note_contents', @@ -739,22 +739,22 @@ class Note extends AbstractEntity { */ getFlatText() { if (!this.flatTextCache) { - this.flatTextCache = this.noteId + ' ' + this.type + ' ' + this.mime + ' '; + this.flatTextCache = `${this.noteId} ${this.type} ${this.mime} `; for (const branch of this.parentBranches) { if (branch.prefix) { - this.flatTextCache += branch.prefix + ' '; + this.flatTextCache += `${branch.prefix} `; } } - this.flatTextCache += this.title + ' '; + this.flatTextCache += `${this.title} `; for (const attr of this.getAttributes()) { // it's best to use space as separator since spaces are filtered from the search string by the tokenization into words - this.flatTextCache += (attr.type === 'label' ? '#' : '~') + attr.name; + this.flatTextCache += `${attr.type === 'label' ? '#' : '~'}${attr.name}`; if (attr.value) { - this.flatTextCache += '=' + attr.value; + this.flatTextCache += `=${attr.value}`; } this.flatTextCache += ' '; diff --git a/src/becca/entities/note_revision.js b/src/becca/entities/note_revision.js index ae642cb09..209401af6 100644 --- a/src/becca/entities/note_revision.js +++ b/src/becca/entities/note_revision.js @@ -81,7 +81,7 @@ class NoteRevision extends AbstractEntity { return undefined; } else { - throw new Error("Cannot find note revision content for noteRevisionId=" + this.noteRevisionId); + throw new Error(`Cannot find note revision content for noteRevisionId=${this.noteRevisionId}`); } } @@ -124,7 +124,7 @@ class NoteRevision extends AbstractEntity { sql.upsert("note_revision_contents", "noteRevisionId", pojo); - const hash = utils.hash(this.noteRevisionId + "|" + pojo.content.toString()); + const hash = utils.hash(`${this.noteRevisionId}|${pojo.content.toString()}`); entityChangesService.addEntityChange({ entityName: 'note_revision_contents', diff --git a/src/etapi/validators.js b/src/etapi/validators.js index 797b61761..7b3ba852c 100644 --- a/src/etapi/validators.js +++ b/src/etapi/validators.js @@ -66,7 +66,7 @@ function isNoteType(obj) { const noteTypes = noteTypeService.getNoteTypeNames(); if (!noteTypes.includes(obj)) { - return `'${obj}' is not a valid note type, allowed types are: ` + noteTypes.join(", "); + return `'${obj}' is not a valid note type, allowed types are: ${noteTypes.join(", ")}`; } } diff --git a/src/public/app/components/app_context.js b/src/public/app/components/app_context.js index 97b44283d..6e46e56e9 100644 --- a/src/public/app/components/app_context.js +++ b/src/public/app/components/app_context.js @@ -96,7 +96,7 @@ class AppContext extends Component { /** @returns {Promise} */ triggerCommand(name, data = {}) { for (const executor of this.components) { - const fun = executor[name + "Command"]; + const fun = executor[`${name}Command`]; if (fun) { return executor.callMethod(fun, data); diff --git a/src/public/app/components/component.js b/src/public/app/components/component.js index ab9acefb5..a32cf2637 100644 --- a/src/public/app/components/component.js +++ b/src/public/app/components/component.js @@ -13,7 +13,7 @@ import utils from '../services/utils.js'; */ export default class Component { constructor() { - this.componentId = this.sanitizedClassName + '-' + utils.randomString(8); + this.componentId = `${this.sanitizedClassName}-${utils.randomString(8)}`; /** @type Component[] */ this.children = []; this.initialized = null; @@ -44,8 +44,8 @@ export default class Component { handleEvent(name, data) { try { const callMethodPromise = this.initialized - ? this.initialized.then(() => this.callMethod(this[name + 'Event'], data)) - : this.callMethod(this[name + 'Event'], data); + ? this.initialized.then(() => this.callMethod(this[`${name}Event`], data)) + : this.callMethod(this[`${name}Event`], data); const childrenPromise = this.handleEventInChildren(name, data); @@ -84,7 +84,7 @@ export default class Component { /** @returns {Promise} */ triggerCommand(name, data = {}) { - const fun = this[name + 'Command']; + const fun = this[`${name}Command`]; if (fun) { return this.callMethod(fun, data); diff --git a/src/public/app/components/entrypoints.js b/src/public/app/components/entrypoints.js index 92550b206..f82e2d361 100644 --- a/src/public/app/components/entrypoints.js +++ b/src/public/app/components/entrypoints.js @@ -150,7 +150,7 @@ export default class Entrypoints extends Component { ipcRenderer.send('create-extra-window', {notePath, hoistedNoteId}); } else { - const url = window.location.protocol + '//' + window.location.host + window.location.pathname + '?extra=1#' + notePath; + const url = `${window.location.protocol}//${window.location.host}${window.location.pathname}?extra=1#${notePath}`; window.open(url, '', 'width=1000,height=800'); } @@ -172,12 +172,12 @@ export default class Entrypoints extends Component { if (note.mime.endsWith("env=frontend")) { await bundleService.getAndExecuteBundle(note.noteId); } else if (note.mime.endsWith("env=backend")) { - await server.post('script/run/' + note.noteId); + await server.post(`script/run/${note.noteId}`); } else if (note.mime === 'text/x-sqlite;schema=trilium') { - const resp = await server.post("sql/execute/" + note.noteId); + const resp = await server.post(`sql/execute/${note.noteId}`); if (!resp.success) { - toastService.showError("Error occurred while executing SQL query: " + resp.message); + toastService.showError(`Error occurred while executing SQL query: ${resp.message}`); } await appContext.triggerEvent('sqlQueryResults', {ntxId: ntxId, results: resp.results}); diff --git a/src/public/app/components/tab_manager.js b/src/public/app/components/tab_manager.js index 3b9dd1c24..b79aaf778 100644 --- a/src/public/app/components/tab_manager.js +++ b/src/public/app/components/tab_manager.js @@ -126,7 +126,7 @@ export default class TabManager extends Component { if (window.history.length === 0 // first history entry || (activeNoteContext && activeNoteContext.notePath !== treeService.getHashValueFromAddress()[0])) { - const url = '#' + (activeNoteContext.notePath || "") + "-" + activeNoteContext.ntxId; + const url = `#${activeNoteContext.notePath || ""}-${activeNoteContext.ntxId}`; // using pushState instead of directly modifying document.location because it does not trigger hashchange window.history.pushState(null, "", url); diff --git a/src/public/app/desktop.js b/src/public/app/desktop.js index 21403bbb8..e83f4477e 100644 --- a/src/public/app/desktop.js +++ b/src/public/app/desktop.js @@ -112,7 +112,7 @@ if (utils.isElectron()) { if (hasText) { const shortenedSelection = params.selectionText.length > 15 - ? (params.selectionText.substr(0, 13) + "…") + ? (`${params.selectionText.substr(0, 13)}…`) : params.selectionText; items.push({ diff --git a/src/public/app/entities/note_short.js b/src/public/app/entities/note_short.js index af08e045f..3128d744e 100644 --- a/src/public/app/entities/note_short.js +++ b/src/public/app/entities/note_short.js @@ -119,7 +119,7 @@ class NoteShort { async getContent() { // we're not caching content since these objects are in froca and as such pretty long lived - const note = await server.get("notes/" + this.noteId); + const note = await server.get(`notes/${this.noteId}`); return note.content; } @@ -813,7 +813,7 @@ class NoteShort { return await bundleService.getAndExecuteBundle(this.noteId); } else if (env === "backend") { - return await server.post('script/run/' + this.noteId); + return await server.post(`script/run/${this.noteId}`); } else { throw new Error(`Unrecognized env type ${env} for note ${this.noteId}`); diff --git a/src/public/app/services/attribute_autocomplete.js b/src/public/app/services/attribute_autocomplete.js index 5d49c850a..6780ec7af 100644 --- a/src/public/app/services/attribute_autocomplete.js +++ b/src/public/app/services/attribute_autocomplete.js @@ -52,7 +52,7 @@ async function initLabelValueAutocomplete({ $el, open, nameCallback }) { return; } - const attributeValues = (await server.get('attributes/values/' + encodeURIComponent(attributeName))) + const attributeValues = (await server.get(`attributes/values/${encodeURIComponent(attributeName)}`)) .map(attribute => ({ value: attribute })); if (attributeValues.length === 0) { diff --git a/src/public/app/services/attribute_parser.js b/src/public/app/services/attribute_parser.js index d2fd1944e..6567dc401 100644 --- a/src/public/app/services/attribute_parser.js +++ b/src/public/app/services/attribute_parser.js @@ -125,9 +125,7 @@ function parse(tokens, str, allowEmptyRelations = false) { startIndex = Math.max(0, startIndex - 20); endIndex = Math.min(str.length, endIndex + 20); - return '"' + (startIndex !== 0 ? "..." : "") - + str.substr(startIndex, endIndex - startIndex) - + (endIndex !== str.length ? "..." : "") + '"'; + return `"${startIndex !== 0 ? "..." : ""}${str.substr(startIndex, endIndex - startIndex)}${endIndex !== str.length ? "..." : ""}"`; } for (let i = 0; i < tokens.length; i++) { diff --git a/src/public/app/services/attribute_renderer.js b/src/public/app/services/attribute_renderer.js index d8a68d8c5..d909bab2c 100644 --- a/src/public/app/services/attribute_renderer.js +++ b/src/public/app/services/attribute_renderer.js @@ -6,7 +6,7 @@ async function renderAttribute(attribute, renderIsInheritable) { const $attr = $(""); if (attribute.type === 'label') { - $attr.append(document.createTextNode('#' + attribute.name + isInheritable)); + $attr.append(document.createTextNode(`#${attribute.name}${isInheritable}`)); if (attribute.value) { $attr.append('='); @@ -19,11 +19,11 @@ async function renderAttribute(attribute, renderIsInheritable) { // when the relation has just been created then it might not have a value if (attribute.value) { - $attr.append(document.createTextNode('~' + attribute.name + isInheritable + "=")); + $attr.append(document.createTextNode(`~${attribute.name}${isInheritable}=`)); $attr.append(await createNoteLink(attribute.value)); } } else { - ws.logError("Unknown attr type: " + attribute.type); + ws.logError(`Unknown attr type: ${attribute.type}`); } return $attr; @@ -34,16 +34,16 @@ function formatValue(val) { return val; } else if (!val.includes('"')) { - return '"' + val + '"'; + return `"${val}"`; } else if (!val.includes("'")) { - return "'" + val + "'"; + return `'${val}'`; } else if (!val.includes("`")) { - return "`" + val + "`"; + return `\`${val}\``; } else { - return '"' + val.replace(/"/g, '\\"') + '"'; + return `"${val.replace(/"/g, '\\"')}"`; } } @@ -55,7 +55,7 @@ async function createNoteLink(noteId) { } return $("", { - href: '#root/' + noteId, + href: `#root/${noteId}`, class: 'reference-link', 'data-note-path': noteId }) diff --git a/src/public/app/services/branches.js b/src/public/app/services/branches.js index 86a9bce5f..b45be2e63 100644 --- a/src/public/app/services/branches.js +++ b/src/public/app/services/branches.js @@ -116,10 +116,10 @@ async function deleteNotes(branchIdsToDelete, forceDeleteAllClones = false) { const branch = froca.getBranch(branchIdToDelete); if (deleteAllClones) { - await server.remove(`notes/${branch.noteId}` + query); + await server.remove(`notes/${branch.noteId}${query}`); } else { - await server.remove(`branches/${branchIdToDelete}` + query); + await server.remove(`branches/${branchIdToDelete}${query}`); } } @@ -186,7 +186,7 @@ ws.subscribeToMessages(async message => { toastService.closePersistent(message.taskId); toastService.showError(message.message); } else if (message.type === 'taskProgressCount') { - toastService.showPersistent(makeToast(message.taskId, "Delete notes in progress: " + message.progressCount)); + toastService.showPersistent(makeToast(message.taskId, `Delete notes in progress: ${message.progressCount}`)); } else if (message.type === 'taskSucceeded') { const toast = makeToast(message.taskId, "Delete finished successfully."); toast.closeAfter = 5000; @@ -204,7 +204,7 @@ ws.subscribeToMessages(async message => { toastService.closePersistent(message.taskId); toastService.showError(message.message); } else if (message.type === 'taskProgressCount') { - toastService.showPersistent(makeToast(message.taskId, "Undeleting notes in progress: " + message.progressCount)); + toastService.showPersistent(makeToast(message.taskId, `Undeleting notes in progress: ${message.progressCount}`)); } else if (message.type === 'taskSucceeded') { const toast = makeToast(message.taskId, "Undeleting notes finished successfully."); toast.closeAfter = 5000; @@ -235,7 +235,7 @@ async function cloneNoteToNote(childNoteId, parentNoteId, prefix) { // beware that first arg is noteId and second is branchId! async function cloneNoteAfter(noteId, afterBranchId) { - const resp = await server.put('notes/' + noteId + '/clone-after/' + afterBranchId); + const resp = await server.put(`notes/${noteId}/clone-after/${afterBranchId}`); if (!resp.success) { toastService.showError(resp.message); diff --git a/src/public/app/services/bundle.js b/src/public/app/services/bundle.js index 5ef75dd63..09b20105f 100644 --- a/src/public/app/services/bundle.js +++ b/src/public/app/services/bundle.js @@ -5,7 +5,7 @@ import froca from "./froca.js"; import utils from "./utils.js"; async function getAndExecuteBundle(noteId, originEntity = null) { - const bundle = await server.get('script/bundle/' + noteId); + const bundle = await server.get(`script/bundle/${noteId}`); return await executeBundle(bundle, originEntity); } diff --git a/src/public/app/services/clipboard.js b/src/public/app/services/clipboard.js index 3ee16b68a..110c29f6a 100644 --- a/src/public/app/services/clipboard.js +++ b/src/public/app/services/clipboard.js @@ -30,7 +30,7 @@ async function pasteAfter(afterBranchId) { // copy will keep clipboardBranchIds and clipboardMode so it's possible to paste into multiple places } else { - toastService.throwError("Unrecognized clipboard mode=" + clipboardMode); + toastService.throwError(`Unrecognized clipboard mode=${clipboardMode}`); } } @@ -57,7 +57,7 @@ async function pasteInto(parentBranchId) { // copy will keep clipboardBranchIds and clipboardMode, so it's possible to paste into multiple places } else { - toastService.throwError("Unrecognized clipboard mode=" + clipboardMode); + toastService.throwError(`Unrecognized clipboard mode=${clipboardMode}`); } } @@ -71,7 +71,7 @@ async function copy(branchIds) { const links = []; for (const branch of froca.getBranches(clipboardBranchIds)) { - const $link = await linkService.createNoteLink(branch.parentNoteId + '/' + branch.noteId, { referenceLink: true }); + const $link = await linkService.createNoteLink(`${branch.parentNoteId}/${branch.noteId}`, { referenceLink: true }); links.push($link[0].outerHTML); } diff --git a/src/public/app/services/css_class_manager.js b/src/public/app/services/css_class_manager.js index cd0e9dfff..6b7c36677 100644 --- a/src/public/app/services/css_class_manager.js +++ b/src/public/app/services/css_class_manager.js @@ -11,7 +11,7 @@ function createClassForColor(color) { return ""; } - const className = 'color-' + normalizedColorName; + const className = `color-${normalizedColorName}`; if (!registeredClasses.has(className)) { $("head").append(``); diff --git a/src/public/app/services/date_notes.js b/src/public/app/services/date_notes.js index bfe83c3f6..160c30410 100644 --- a/src/public/app/services/date_notes.js +++ b/src/public/app/services/date_notes.js @@ -4,7 +4,7 @@ import ws from "./ws.js"; /** @returns {NoteShort} */ async function getInboxNote() { - const note = await server.get('special-notes/inbox/' + dayjs().format("YYYY-MM-DD"), "date-note"); + const note = await server.get(`special-notes/inbox/${dayjs().format("YYYY-MM-DD")}`, "date-note"); return await froca.getNote(note.noteId); } @@ -16,7 +16,7 @@ async function getTodayNote() { /** @returns {NoteShort} */ async function getDayNote(date) { - const note = await server.get('special-notes/days/' + date, "date-note"); + const note = await server.get(`special-notes/days/${date}`, "date-note"); await ws.waitForMaxKnownEntityChangeId(); @@ -25,7 +25,7 @@ async function getDayNote(date) { /** @returns {NoteShort} */ async function getWeekNote(date) { - const note = await server.get('special-notes/weeks/' + date, "date-note"); + const note = await server.get(`special-notes/weeks/${date}`, "date-note"); await ws.waitForMaxKnownEntityChangeId(); @@ -34,7 +34,7 @@ async function getWeekNote(date) { /** @returns {NoteShort} */ async function getMonthNote(month) { - const note = await server.get('special-notes/months/' + month, "date-note"); + const note = await server.get(`special-notes/months/${month}`, "date-note"); await ws.waitForMaxKnownEntityChangeId(); @@ -43,7 +43,7 @@ async function getMonthNote(month) { /** @returns {NoteShort} */ async function getYearNote(year) { - const note = await server.get('special-notes/years/' + year, "date-note"); + const note = await server.get(`special-notes/years/${year}`, "date-note"); await ws.waitForMaxKnownEntityChangeId(); diff --git a/src/public/app/services/froca.js b/src/public/app/services/froca.js index 2443ff888..2526c648b 100644 --- a/src/public/app/services/froca.js +++ b/src/public/app/services/froca.js @@ -41,7 +41,7 @@ class Froca { } async loadSubTree(subTreeNoteId) { - const resp = await server.get('tree?subTreeNoteId=' + subTreeNoteId); + const resp = await server.get(`tree?subTreeNoteId=${subTreeNoteId}`); this.addResp(resp); @@ -176,7 +176,7 @@ class Froca { return; } - const {searchResultNoteIds, highlightedTokens, error} = await server.get('search-note/' + note.noteId); + const {searchResultNoteIds, highlightedTokens, error} = await server.get(`search-note/${note.noteId}`); if (!Array.isArray(searchResultNoteIds)) { throw new Error(`Search note '${note.noteId}' failed: ${searchResultNoteIds}`); @@ -192,7 +192,7 @@ class Froca { searchResultNoteIds.forEach((resultNoteId, index) => branches.push({ // branchId should be repeatable since sometimes we reload some notes without rerendering the tree - branchId: "virt-" + note.noteId + '-' + resultNoteId, + branchId: `virt-${note.noteId}-${resultNoteId}`, noteId: resultNoteId, parentNoteId: note.noteId, notePosition: (index + 1) * 10, @@ -314,7 +314,7 @@ class Froca { */ async getNoteComplement(noteId) { if (!this.noteComplementPromises[noteId]) { - this.noteComplementPromises[noteId] = server.get('notes/' + noteId) + this.noteComplementPromises[noteId] = server.get(`notes/${noteId}`) .then(row => new NoteComplement(row)) .catch(e => console.error(`Cannot get note complement for note '${noteId}'`)); diff --git a/src/public/app/services/frontend_script_api.js b/src/public/app/services/frontend_script_api.js index 32f4af3b0..9cbceff34 100644 --- a/src/public/app/services/frontend_script_api.js +++ b/src/public/app/services/frontend_script_api.js @@ -137,7 +137,7 @@ function FrontendScriptApi(startNote, currentNote, originEntity = null, $contain return params.map(p => { if (typeof p === "function") { - return "!@#Function: " + p.toString(); + return `!@#Function: ${p.toString()}`; } else { return p; @@ -173,7 +173,7 @@ function FrontendScriptApi(startNote, currentNote, originEntity = null, $contain return ret.executionResult; } else { - throw new Error("server error: " + ret.error); + throw new Error(`server error: ${ret.error}`); } }; @@ -564,7 +564,7 @@ function FrontendScriptApi(startNote, currentNote, originEntity = null, $contain this.log = message => { const {noteId} = this.startNote; - message = utils.now() + ": " + message; + message = `${utils.now()}: ${message}`; console.log(`Script ${noteId}: ${message}`); diff --git a/src/public/app/services/glob.js b/src/public/app/services/glob.js index 94153fed9..f9f58d704 100644 --- a/src/public/app/services/glob.js +++ b/src/public/app/services/glob.js @@ -49,12 +49,12 @@ function setupGlobs() { message += 'No details available'; } else { message += [ - 'Message: ' + msg, - 'URL: ' + url, - 'Line: ' + lineNo, - 'Column: ' + columnNo, - 'Error object: ' + JSON.stringify(error), - 'Stack: ' + (error && error.stack) + `Message: ${msg}`, + `URL: ${url}`, + `Line: ${lineNo}`, + `Column: ${columnNo}`, + `Error object: ${JSON.stringify(error)}`, + `Stack: ${error && error.stack}` ].join(', '); } diff --git a/src/public/app/services/hoisted_note.js b/src/public/app/services/hoisted_note.js index dd8d63c35..11682de7c 100644 --- a/src/public/app/services/hoisted_note.js +++ b/src/public/app/services/hoisted_note.js @@ -44,7 +44,7 @@ async function checkNoteAccess(notePath, noteContext) { const resolvedNotePath = await treeService.resolveNotePath(notePath, noteContext.hoistedNoteId); if (!resolvedNotePath) { - console.log("Cannot activate " + notePath); + console.log(`Cannot activate ${notePath}`); return false; } diff --git a/src/public/app/services/import.js b/src/public/app/services/import.js index 83211b0bf..dfc91c0df 100644 --- a/src/public/app/services/import.js +++ b/src/public/app/services/import.js @@ -26,14 +26,14 @@ export async function uploadFiles(parentNoteId, files, options) { } ({noteId} = await $.ajax({ - url: baseApiUrl + 'notes/' + parentNoteId + '/import', + url: `${baseApiUrl}notes/${parentNoteId}/import`, headers: await server.getHeaders(), data: formData, dataType: 'json', type: 'POST', timeout: 60 * 60 * 1000, error: function(xhr) { - toastService.showError("Import failed: " + xhr.responseText); + toastService.showError(`Import failed: ${xhr.responseText}`); }, contentType: false, // NEEDED, DON'T REMOVE THIS processData: false, // NEEDED, DON'T REMOVE THIS @@ -59,7 +59,7 @@ ws.subscribeToMessages(async message => { toastService.closePersistent(message.taskId); toastService.showError(message.message); } else if (message.type === 'taskProgressCount') { - toastService.showPersistent(makeToast(message.taskId, "Import in progress: " + message.progressCount)); + toastService.showPersistent(makeToast(message.taskId, `Import in progress: ${message.progressCount}`)); } else if (message.type === 'taskSucceeded') { const toast = makeToast(message.taskId, "Import finished successfully."); toast.closeAfter = 5000; diff --git a/src/public/app/services/library_loader.js b/src/public/app/services/library_loader.js index eeac0fb44..6398f294a 100644 --- a/src/public/app/services/library_loader.js +++ b/src/public/app/services/library_loader.js @@ -86,7 +86,7 @@ async function requireLibrary(library) { const loadedScriptPromises = {}; async function requireScript(url) { - url = window.glob.assetPath + "/" + url; + url = `${window.glob.assetPath}/${url}`; if (!loadedScriptPromises[url]) { loadedScriptPromises[url] = $.ajax({ @@ -106,7 +106,7 @@ async function requireCss(url, prependAssetPath = true) { if (!cssLinks.some(l => l.endsWith(url))) { if (prependAssetPath) { - url = window.glob.assetPath + "/" + url; + url = `${window.glob.assetPath}/${url}`; } $('head').append($('').attr('href', url)); diff --git a/src/public/app/services/link.js b/src/public/app/services/link.js index d5b8988d5..88a587249 100644 --- a/src/public/app/services/link.js +++ b/src/public/app/services/link.js @@ -20,7 +20,7 @@ async function createNoteLink(notePath, options = {}) { if (!notePath.startsWith("root")) { // all note paths should start with "root/" (except for "root" itself) // used e.g. to find internal links - notePath = "root/" + notePath; + notePath = `root/${notePath}`; } let noteTitle = options.title; @@ -41,12 +41,12 @@ async function createNoteLink(notePath, options = {}) { const note = await froca.getNote(noteId); $container - .append($("").addClass("bx " + note.getIcon())) + .append($("").addClass(`bx ${note.getIcon()}`)) .append(" "); } const $noteLink = $("", { - href: '#' + notePath, + href: `#${notePath}`, text: noteTitle }).attr('data-action', 'note') .attr('data-note-path', notePath); @@ -70,7 +70,7 @@ async function createNoteLink(notePath, options = {}) { const parentNotePath = resolvedNotePathSegments.join("/").trim(); if (parentNotePath) { - $container.append($("").text(" (" + await treeService.getNotePathTitle(parentNotePath) + ")")); + $container.append($("").text(` (${await treeService.getNotePathTitle(parentNotePath)})`)); } } } diff --git a/src/public/app/services/note_autocomplete.js b/src/public/app/services/note_autocomplete.js index a0dd30fa9..157c24261 100644 --- a/src/public/app/services/note_autocomplete.js +++ b/src/public/app/services/note_autocomplete.js @@ -17,9 +17,9 @@ async function autocompleteSourceForCKEditor(queryText) { return { action: row.action, noteTitle: row.noteTitle, - id: '@' + row.notePathTitle, + id: `@${row.notePathTitle}`, name: row.notePathTitle, - link: '#' + row.notePath, + link: `#${row.notePath}`, notePath: row.notePath, highlightedNotePathTitle: row.highlightedNotePathTitle } @@ -33,9 +33,7 @@ async function autocompleteSourceForCKEditor(queryText) { async function autocompleteSource(term, cb, options = {}) { const activeNoteId = appContext.tabManager.getActiveContextNoteId(); - let results = await server.get('autocomplete' - + '?query=' + encodeURIComponent(term) - + '&activeNoteId=' + activeNoteId); + let results = await server.get(`autocomplete?query=${encodeURIComponent(term)}&activeNoteId=${activeNoteId}`); if (term.trim().length >= 1 && options.allowCreatingNotes) { results = [ diff --git a/src/public/app/services/note_content_renderer.js b/src/public/app/services/note_content_renderer.js index f1dfd1f42..0a509af31 100644 --- a/src/public/app/services/note_content_renderer.js +++ b/src/public/app/services/note_content_renderer.js @@ -37,7 +37,7 @@ async function getRenderedContent(note, options = {}) { } } else if (type === 'code') { - const fullNote = await server.get('notes/' + note.noteId); + const fullNote = await server.get(`notes/${note.noteId}`); $renderedContent.append($("
").text(trim(fullNote.content, options.trim)));
     }
@@ -64,13 +64,13 @@ async function getRenderedContent(note, options = {}) {
 
         if (type === 'pdf') {
             const $pdfPreview = $('');
-            $pdfPreview.attr("src", openService.getUrlForDownload("api/notes/" + note.noteId + "/open"));
+            $pdfPreview.attr("src", openService.getUrlForDownload(`api/notes/${note.noteId}/open`));
 
             $content.append($pdfPreview);
         }
         else if (type === 'audio') {
             const $audioPreview = $('')
-                .attr("src", openService.getUrlForStreaming("api/notes/" + note.noteId + "/open-partial"))
+                .attr("src", openService.getUrlForStreaming(`api/notes/${note.noteId}/open-partial`))
                 .attr("type", note.mime)
                 .css("width", "100%");
 
@@ -78,7 +78,7 @@ async function getRenderedContent(note, options = {}) {
         }
         else if (type === 'video') {
             const $videoPreview = $('')
-                .attr("src", openService.getUrlForDownload("api/notes/" + note.noteId + "/open-partial"))
+                .attr("src", openService.getUrlForDownload(`api/notes/${note.noteId}/open-partial`))
                 .attr("type", note.mime)
                 .css("width", "100%");
 
diff --git a/src/public/app/services/note_list_renderer.js b/src/public/app/services/note_list_renderer.js
index 1180fa2ec..2f36b191f 100644
--- a/src/public/app/services/note_list_renderer.js
+++ b/src/public/app/services/note_list_renderer.js
@@ -178,7 +178,7 @@ class NoteListRenderer {
             this.viewType = parentNote.type === 'search' ? 'list' : 'grid';
         }
 
-        this.$noteList.addClass(this.viewType + '-view');
+        this.$noteList.addClass(`${this.viewType}-view`);
 
         this.showNotePath = showNotePath;
     }
@@ -267,7 +267,7 @@ class NoteListRenderer {
         const {$renderedAttributes} = await attributeRenderer.renderNormalAttributes(note);
         const notePath = this.parentNote.type === 'search'
             ? note.noteId // for search note parent we want to display non-search path
-            : this.parentNote.noteId + '/' + note.noteId;
+            : `${this.parentNote.noteId}/${note.noteId}`;
 
         const $card = $('
') .attr('data-note-id', note.noteId) @@ -345,7 +345,7 @@ class NoteListRenderer { } $content.append($renderedContent); - $content.addClass("type-" + type); + $content.addClass(`type-${type}`); } catch (e) { console.log(`Caught error while rendering note ${note.noteId} of type ${note.type}: ${e.message}, stack: ${e.stack}`); diff --git a/src/public/app/services/note_tooltip.js b/src/public/app/services/note_tooltip.js index 74c4d20ad..b83296cd8 100644 --- a/src/public/app/services/note_tooltip.js +++ b/src/public/app/services/note_tooltip.js @@ -50,7 +50,7 @@ async function mouseEnterHandler() { return; } - const html = '
' + content + '
'; + const html = `
${content}
`; // we need to check if we're still hovering over the element // since the operation to get tooltip content was async, it is possible that @@ -89,7 +89,7 @@ async function renderTooltip(note) { return; } - let content = '
' + (await treeService.getNoteTitleWithPathAsSuffix(someNotePath)).prop('outerHTML') + '
'; + let content = `
${(await treeService.getNoteTitleWithPathAsSuffix(someNotePath)).prop('outerHTML')}
`; const {$renderedAttributes} = await attributeRenderer.renderNormalAttributes(note); @@ -98,9 +98,7 @@ async function renderTooltip(note) { trim: true }); - content = content - + '
' + $renderedAttributes[0].outerHTML + '
' - + $renderedContent[0].outerHTML; + content = `${content}
${$renderedAttributes[0].outerHTML}
${$renderedContent[0].outerHTML}`; return content; } diff --git a/src/public/app/services/open.js b/src/public/app/services/open.js index ed2493cbb..dba42db89 100644 --- a/src/public/app/services/open.js +++ b/src/public/app/services/open.js @@ -2,10 +2,10 @@ import utils from "./utils.js"; import server from "./server.js"; function getFileUrl(noteId) { - return getUrlForDownload("api/notes/" + noteId + "/download"); + return getUrlForDownload(`api/notes/${noteId}/download`); } function getOpenFileUrl(noteId) { - return getUrlForDownload("api/notes/" + noteId + "/open"); + return getUrlForDownload(`api/notes/${noteId}/open`); } function download(url) { @@ -19,14 +19,14 @@ function download(url) { } function downloadFileNote(noteId) { - const url = getFileUrl(noteId) + '?' + Date.now(); // don't use cache + const url = `${getFileUrl(noteId)}?${Date.now()}`; // don't use cache download(url); } async function openNoteExternally(noteId, mime) { if (utils.isElectron()) { - const resp = await server.post("notes/" + noteId + "/save-to-tmp-dir"); + const resp = await server.post(`notes/${noteId}/save-to-tmp-dir`); const electron = utils.dynamicRequire('electron'); const res = await electron.shell.openPath(resp.tmpFilePath); @@ -59,7 +59,7 @@ function downloadNoteRevision(noteId, noteRevisionId) { function getUrlForDownload(url) { if (utils.isElectron()) { // electron needs absolute URL so we extract current host, port, protocol - return getHost() + '/' + url; + return `${getHost()}/${url}`; } else { // web server can be deployed on subdomain so we need to use relative path @@ -69,7 +69,7 @@ function getUrlForDownload(url) { function getHost() { const url = new URL(window.location.href); - return url.protocol + "//" + url.hostname + ":" + url.port; + return `${url.protocol}//${url.hostname}:${url.port}`; } export default { diff --git a/src/public/app/services/protected_session.js b/src/public/app/services/protected_session.js index ac0d6e18d..dd6692d43 100644 --- a/src/public/app/services/protected_session.js +++ b/src/public/app/services/protected_session.js @@ -88,7 +88,7 @@ async function protectNote(noteId, protect, includingSubtree) { function makeToast(message, protectingLabel, text) { return { id: message.taskId, - title: protectingLabel + " status", + title: `${protectingLabel} status`, message: text, icon: message.data.protect ? "check-shield" : "shield" }; @@ -105,9 +105,9 @@ ws.subscribeToMessages(async message => { toastService.closePersistent(message.taskId); toastService.showError(message.message); } else if (message.type === 'taskProgressCount') { - toastService.showPersistent(makeToast(message, protectingLabel,protectingLabel + " in progress: " + message.progressCount)); + toastService.showPersistent(makeToast(message, protectingLabel,`${protectingLabel} in progress: ${message.progressCount}`)); } else if (message.type === 'taskSucceeded') { - const toast = makeToast(message, protectingLabel, protectingLabel + " finished successfully."); + const toast = makeToast(message, protectingLabel, `${protectingLabel} finished successfully.`); toast.closeAfter = 3000; toastService.showPersistent(toast); diff --git a/src/public/app/services/render.js b/src/public/app/services/render.js index 565d954be..c7b3f0b2c 100644 --- a/src/public/app/services/render.js +++ b/src/public/app/services/render.js @@ -10,7 +10,7 @@ async function render(note, $el) { $el.empty().toggle(renderNoteIds.length > 0); for (const renderNoteId of renderNoteIds) { - const bundle = await server.get('script/bundle/' + renderNoteId); + const bundle = await server.get(`script/bundle/${renderNoteId}`); const $scriptContainer = $('
'); $el.append($scriptContainer); diff --git a/src/public/app/services/script_context.js b/src/public/app/services/script_context.js index 712ff7ad3..f47380704 100644 --- a/src/public/app/services/script_context.js +++ b/src/public/app/services/script_context.js @@ -20,7 +20,7 @@ async function ScriptContext(startNoteId, allNoteIds, originEntity = null, $cont const note = candidates.find(c => c.title === moduleName); if (!note) { - throw new Error("Could not find module note " + moduleName); + throw new Error(`Could not find module note ${moduleName}`); } return modules[note.noteId].exports; diff --git a/src/public/app/services/search.js b/src/public/app/services/search.js index 2a9849431..9a6cd61fc 100644 --- a/src/public/app/services/search.js +++ b/src/public/app/services/search.js @@ -2,7 +2,7 @@ import server from "./server.js"; import froca from "./froca.js"; async function searchForNoteIds(searchString) { - return await server.get('search/' + encodeURIComponent(searchString)); + return await server.get(`search/${encodeURIComponent(searchString)}`); } async function searchForNotes(searchString) { diff --git a/src/public/app/services/server.js b/src/public/app/services/server.js index 811b73d6d..783fe598b 100644 --- a/src/public/app/services/server.js +++ b/src/public/app/services/server.js @@ -72,14 +72,14 @@ async function call(method, url, data, headers = {}) { reqRejects[requestId] = reject; if (REQUEST_LOGGING_ENABLED) { - console.log(utils.now(), "Request #" + requestId + " to " + method + " " + url); + console.log(utils.now(), `Request #${requestId} to ${method} ${url}`); } ipc.send('server-request', { requestId: requestId, headers: headers, method: method, - url: "/" + baseApiUrl + url, + url: `/${baseApiUrl}${url}`, data: data }); }); @@ -117,7 +117,7 @@ async function reportError(method, url, statusCode, response) { toastService.showError(response.message); throw new ValidationError(response); } else { - const message = "Error when calling " + method + " " + url + ": " + statusCode + " - " + response; + const message = `Error when calling ${method} ${url}: ${statusCode} - ${response}`; toastService.showError(message); toastService.throwError(message); } @@ -169,7 +169,7 @@ if (utils.isElectron()) { ipc.on('server-response', async (event, arg) => { if (REQUEST_LOGGING_ENABLED) { - console.log(utils.now(), "Response #" + arg.requestId + ": " + arg.statusCode); + console.log(utils.now(), `Response #${arg.requestId}: ${arg.statusCode}`); } if (arg.statusCode >= 200 && arg.statusCode < 300) { diff --git a/src/public/app/services/shortcuts.js b/src/public/app/services/shortcuts.js index 7e6ea56a8..083a5d0e5 100644 --- a/src/public/app/services/shortcuts.js +++ b/src/public/app/services/shortcuts.js @@ -15,7 +15,7 @@ function bindElShortcut($el, keyboardShortcut, handler, namespace = null) { let eventName = 'keydown'; if (namespace) { - eventName += "." + namespace; + eventName += `.${namespace}`; // if there's a namespace then we replace the existing event handler with the new one $el.off(eventName); diff --git a/src/public/app/services/sync.js b/src/public/app/services/sync.js index c904f1d37..1f1f8cc17 100644 --- a/src/public/app/services/sync.js +++ b/src/public/app/services/sync.js @@ -9,17 +9,17 @@ async function syncNow(ignoreNotConfigured = false) { } else { if (result.message.length > 200) { - result.message = result.message.substr(0, 200) + "..."; + result.message = `${result.message.substr(0, 200)}...`; } if (!ignoreNotConfigured || result.errorCode !== 'NOT_CONFIGURED') { - toastService.showError("Sync failed: " + result.message); + toastService.showError(`Sync failed: ${result.message}`); } } } async function forceNoteSync(noteId) { - await server.post('sync/force-note-sync/' + noteId); + await server.post(`sync/force-note-sync/${noteId}`); toastService.showMessage("Note added to sync queue."); } diff --git a/src/public/app/services/toast.js b/src/public/app/services/toast.js index ff2871044..dd7d05c48 100644 --- a/src/public/app/services/toast.js +++ b/src/public/app/services/toast.js @@ -16,7 +16,7 @@ function toast(options) { $toast.find('.toast-body').text(options.message); if (options.id) { - $toast.attr("id", "toast-" + options.id); + $toast.attr("id", `toast-${options.id}`); } $("#toast-container").append($toast); @@ -34,7 +34,7 @@ function toast(options) { } function showPersistent(options) { - let $toast = $("#toast-" + options.id); + let $toast = $(`#toast-${options.id}`); if ($toast.length > 0) { $toast.find('.toast-body').html(options.message); @@ -51,7 +51,7 @@ function showPersistent(options) { } function closePersistent(id) { - $("#toast-" + id).remove(); + $(`#toast-${id}`).remove(); } function showMessage(message, delay = 2000) { diff --git a/src/public/app/services/tree.js b/src/public/app/services/tree.js index eb6f4645c..ba7c5593a 100644 --- a/src/public/app/services/tree.js +++ b/src/public/app/services/tree.js @@ -292,7 +292,7 @@ async function getNoteTitleWithPathAsSuffix(notePath) { if (path.length > 0) { $titleWithPath - .append($('').text(' (' + path.join(' / ') + ')')); + .append($('').text(` (${path.join(' / ')})`)); } return $titleWithPath; diff --git a/src/public/app/services/utils.js b/src/public/app/services/utils.js index d8805c14e..ffec05edf 100644 --- a/src/public/app/services/utils.js +++ b/src/public/app/services/utils.js @@ -1,6 +1,6 @@ function reloadFrontendApp(reason) { if (reason) { - logInfo("Frontend app reload: " + reason); + logInfo(`Frontend app reload: ${reason}`); } window.location.reload(true); @@ -11,20 +11,20 @@ function parseDate(str) { return new Date(Date.parse(str)); } catch (e) { - throw new Error("Can't parse date from " + str + ": " + e.stack); + throw new Error(`Can't parse date from ${str}: ${e.stack}`); } } function padNum(num) { - return (num <= 9 ? "0" : "") + num; + return `${num <= 9 ? "0" : ""}${num}`; } function formatTime(date) { - return padNum(date.getHours()) + ":" + padNum(date.getMinutes()); + return `${padNum(date.getHours())}:${padNum(date.getMinutes())}`; } function formatTimeWithSeconds(date) { - return padNum(date.getHours()) + ":" + padNum(date.getMinutes()) + ":" + padNum(date.getSeconds()); + return `${padNum(date.getHours())}:${padNum(date.getMinutes())}:${padNum(date.getSeconds())}`; } // this is producing local time! @@ -37,11 +37,11 @@ function formatDate(date) { // this is producing local time! function formatDateISO(date) { - return date.getFullYear() + "-" + padNum(date.getMonth() + 1) + "-" + padNum(date.getDate()); + return `${date.getFullYear()}-${padNum(date.getMonth() + 1)}-${padNum(date.getDate())}`; } function formatDateTime(date) { - return formatDate(date) + " " + formatTime(date); + return `${formatDate(date)} ${formatTime(date)}`; } function localNowDateTime() { @@ -101,14 +101,14 @@ async function stopWatch(what, func) { } function formatValueWithWhitespace(val) { - return /[^\w_-]/.test(val) ? '"' + val + '"' : val; + return /[^\w_-]/.test(val) ? `"${val}"` : val; } function formatLabel(label) { - let str = "#" + formatValueWithWhitespace(label.name); + let str = `#${formatValueWithWhitespace(label.name)}`; if (label.value !== "") { - str += "=" + formatValueWithWhitespace(label.value); + str += `=${formatValueWithWhitespace(label.value)}`; } return str; @@ -154,22 +154,22 @@ function isDesktop() { function setCookie(name, value) { const date = new Date(Date.now() + 10 * 365 * 24 * 60 * 60 * 1000); - const expires = "; expires=" + date.toUTCString(); + const expires = `; expires=${date.toUTCString()}`; - document.cookie = name + "=" + (value || "") + expires + ";"; + document.cookie = `${name}=${value || ""}${expires};`; } function setSessionCookie(name, value) { - document.cookie = name + "=" + (value || "") + "; SameSite=Strict"; + document.cookie = `${name}=${value || ""}; SameSite=Strict`; } function getCookie(name) { - const valueMatch = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)'); + const valueMatch = document.cookie.match(`(^|;) ?${name}=([^;]*)(;|$)`); return valueMatch ? valueMatch[2] : null; } function getNoteTypeClass(type) { - return "type-" + type; + return `type-${type}`; } function getMimeTypeClass(mime) { @@ -184,7 +184,7 @@ function getMimeTypeClass(mime) { mime = mime.substr(0, semicolonIdx); } - return 'mime-' + mime.toLowerCase().replace(/[\W_]+/g,"-"); + return `mime-${mime.toLowerCase().replace(/[\W_]+/g, "-")}`; } function closeActiveDialog() { diff --git a/src/public/app/services/ws.js b/src/public/app/services/ws.js index 4ae29c014..265274ce2 100644 --- a/src/public/app/services/ws.js +++ b/src/public/app/services/ws.js @@ -195,8 +195,7 @@ async function consumeFrontendUpdateData() { function connectWebSocket() { const loc = window.location; - const webSocketUri = (loc.protocol === "https:" ? "wss:" : "ws:") - + "//" + loc.host + loc.pathname; + const webSocketUri = `${loc.protocol === "https:" ? "wss:" : "ws:"}//${loc.host}${loc.pathname}`; // use wss for secure messaging const ws = new WebSocket(webSocketUri); diff --git a/src/public/app/setup.js b/src/public/app/setup.js index 12d300b4f..c40d0fb8e 100644 --- a/src/public/app/setup.js +++ b/src/public/app/setup.js @@ -8,7 +8,7 @@ function SetupModel() { setInterval(checkOutstandingSyncs, 1000); } - const serverAddress = location.protocol + '//' + location.host; + const serverAddress = `${location.protocol}//${location.host}`; $("#current-host").html(serverAddress); @@ -74,7 +74,7 @@ function SetupModel() { hideAlert(); } else { - showAlert('Sync setup failed: ' + resp.error); + showAlert(`Sync setup failed: ${resp.error}`); } }; } diff --git a/src/public/app/widgets/attribute_widgets/attribute_detail.js b/src/public/app/widgets/attribute_widgets/attribute_detail.js index c94faea91..b38791ca5 100644 --- a/src/public/app/widgets/attribute_widgets/attribute_detail.js +++ b/src/public/app/widgets/attribute_widgets/attribute_detail.js @@ -628,9 +628,9 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget { } if (this.attrType === 'label-definition') { - attrName = 'label:' + attrName; + attrName = `label:${attrName}`; } else if (this.attrType === 'relation-definition') { - attrName = 'relation:' + attrName; + attrName = `relation:${attrName}`; } this.attribute.name = attrName; @@ -662,12 +662,12 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget { props.push(this.$inputLabelType.val()); if (this.$inputLabelType.val() === 'number' && this.$inputNumberPrecision.val() !== '') { - props.push('precision=' + this.$inputNumberPrecision.val()); + props.push(`precision=${this.$inputNumberPrecision.val()}`); } } else if (this.attrType === 'relation-definition' && this.$inputInverseRelation.val().trim().length > 0) { const inverseRelationName = this.$inputInverseRelation.val(); - props.push("inverse=" + utils.filterAttributeName(inverseRelationName)); + props.push(`inverse=${utils.filterAttributeName(inverseRelationName)}`); } this.$rowNumberPrecision.toggle( @@ -683,7 +683,7 @@ export default class AttributeDetailWidget extends NoteContextAwareWidget { createNoteLink(noteId) { return $("", { - href: '#' + noteId, + href: `#${noteId}`, class: 'reference-link', 'data-note-path': noteId }); diff --git a/src/public/app/widgets/attribute_widgets/attribute_editor.js b/src/public/app/widgets/attribute_widgets/attribute_editor.js index d3bf0522b..ec8a9595d 100644 --- a/src/public/app/widgets/attribute_widgets/attribute_editor.js +++ b/src/public/app/widgets/attribute_widgets/attribute_editor.js @@ -99,7 +99,7 @@ const mentionSetup = { return names.map(name => { return { - id: '#' + name, + id: `#${name}`, name: name } }); @@ -114,7 +114,7 @@ const mentionSetup = { return names.map(name => { return { - id: '~' + name, + id: `~${name}`, name: name } }); diff --git a/src/public/app/widgets/bookmark_switch.js b/src/public/app/widgets/bookmark_switch.js index 8755b0504..6f6f2a007 100644 --- a/src/public/app/widgets/bookmark_switch.js +++ b/src/public/app/widgets/bookmark_switch.js @@ -20,7 +20,7 @@ export default class BookmarkSwitchWidget extends SwitchWidget { } async toggle(state) { - const resp = await server.put(`notes/${this.noteId}/toggle-in-parent/lbBookmarks/` + !!state); + const resp = await server.put(`notes/${this.noteId}/toggle-in-parent/lbBookmarks/${!!state}`); if (!resp.success) { toastService.showError(resp.message); diff --git a/src/public/app/widgets/buttons/calendar.js b/src/public/app/widgets/buttons/calendar.js index 2f9056b95..f58b973d6 100644 --- a/src/public/app/widgets/buttons/calendar.js +++ b/src/public/app/widgets/buttons/calendar.js @@ -78,7 +78,7 @@ export default class CalendarWidget extends RightDropdownButtonWidget { init(activeDate) { // attaching time fixes local timezone handling - this.activeDate = activeDate ? new Date(activeDate + "T12:00:00") : null; + this.activeDate = activeDate ? new Date(`${activeDate}T12:00:00`) : null; this.todaysDate = new Date(); this.date = new Date((this.activeDate || this.todaysDate).getTime()); this.date.setDate(1); @@ -97,7 +97,7 @@ export default class CalendarWidget extends RightDropdownButtonWidget { if (day === 0) { $newDay.css("marginLeft", (6 * 14.28) + '%'); } else { - $newDay.css("marginLeft", ((day - 1) * 14.28) + '%'); + $newDay.css("marginLeft", `${(day - 1) * 14.28}%`); } } @@ -132,7 +132,7 @@ export default class CalendarWidget extends RightDropdownButtonWidget { async createMonth() { const month = utils.formatDateISO(this.date).substr(0, 7); - const dateNotesForMonth = await server.get('special-notes/notes-for-month/' + month); + const dateNotesForMonth = await server.get(`special-notes/notes-for-month/${month}`); this.$month.empty(); @@ -153,7 +153,7 @@ export default class CalendarWidget extends RightDropdownButtonWidget { this.date.setDate(1); this.date.setMonth(this.date.getMonth() - 1); - this.$label.html(this.monthsAsString(this.date.getMonth()) + ' ' + this.date.getFullYear()); + this.$label.html(`${this.monthsAsString(this.date.getMonth())} ${this.date.getFullYear()}`); } monthsAsString(monthIndex) { diff --git a/src/public/app/widgets/buttons/global_menu.js b/src/public/app/widgets/buttons/global_menu.js index 01b08bfb3..c268216a2 100644 --- a/src/public/app/widgets/buttons/global_menu.js +++ b/src/public/app/widgets/buttons/global_menu.js @@ -281,7 +281,7 @@ export default class GlobalMenuWidget extends BasicWidget { const zoomFactor = utils.dynamicRequire('electron').webFrame.getZoomFactor(); const zoomPercent = Math.round(zoomFactor * 100); - this.$zoomState.text(zoomPercent + "%"); + this.$zoomState.text(`${zoomPercent}%`); } async updateVersionStatus() { diff --git a/src/public/app/widgets/collapsible_widget.js b/src/public/app/widgets/collapsible_widget.js index 0d108f27e..97f28c317 100644 --- a/src/public/app/widgets/collapsible_widget.js +++ b/src/public/app/widgets/collapsible_widget.js @@ -20,7 +20,7 @@ export default class CollapsibleWidget extends NoteContextAwareWidget { doRender() { this.$widget = $(WIDGET_TPL); this.contentSized(); - this.$widget.find('[data-target]').attr('data-target', "#" + this.componentId); + this.$widget.find('[data-target]').attr('data-target', `#${this.componentId}`); this.$bodyWrapper = this.$widget.find('.body-wrapper'); this.$bodyWrapper.attr('id', this.componentId); // for toggle to work we need id diff --git a/src/public/app/widgets/dialogs/about.js b/src/public/app/widgets/dialogs/about.js index 8ab9482e9..5d2df1145 100644 --- a/src/public/app/widgets/dialogs/about.js +++ b/src/public/app/widgets/dialogs/about.js @@ -70,7 +70,7 @@ export default class AboutDialog extends BasicWidget { this.$syncVersion.text(appInfo.syncVersion); this.$buildDate.text(appInfo.buildDate); this.$buildRevision.text(appInfo.buildRevision); - this.$buildRevision.attr('href', 'https://github.com/zadam/trilium/commit/' + appInfo.buildRevision); + this.$buildRevision.attr('href', `https://github.com/zadam/trilium/commit/${appInfo.buildRevision}`); this.$dataDirectory.text(appInfo.dataDirectory); } diff --git a/src/public/app/widgets/dialogs/branch_prefix.js b/src/public/app/widgets/dialogs/branch_prefix.js index ec07bc116..fff6d9900 100644 --- a/src/public/app/widgets/dialogs/branch_prefix.js +++ b/src/public/app/widgets/dialogs/branch_prefix.js @@ -82,7 +82,7 @@ export default class BranchPrefixDialog extends BasicWidget { const noteTitle = await treeService.getNoteTitle(noteId); - this.$noteTitle.text(" - " + noteTitle); + this.$noteTitle.text(` - ${noteTitle}`); } async editBranchPrefixEvent() { diff --git a/src/public/app/widgets/dialogs/bulk_actions.js b/src/public/app/widgets/dialogs/bulk_actions.js index 29f648443..60315ae02 100644 --- a/src/public/app/widgets/dialogs/bulk_actions.js +++ b/src/public/app/widgets/dialogs/bulk_actions.js @@ -130,7 +130,7 @@ export default class BulkActionsDialog extends BasicWidget { for (const actionGroup of bulkActionService.ACTION_GROUPS) { const $actionGroupList = $(""); const $actionGroup = $("") - .append($("").text(actionGroup.title + ": ")) + .append($("").text(`${actionGroup.title}: `)) .append($actionGroupList); for (const action of actionGroup.actions) { diff --git a/src/public/app/widgets/dialogs/confirm.js b/src/public/app/widgets/dialogs/confirm.js index 398dd172c..64d6465c1 100644 --- a/src/public/app/widgets/dialogs/confirm.js +++ b/src/public/app/widgets/dialogs/confirm.js @@ -96,7 +96,7 @@ export default class ConfirmDialog extends BasicWidget { .append( $("") .attr("type", "checkbox") - .addClass("form-check-input " + DELETE_NOTE_BUTTON_CLASS) + .addClass(`form-check-input ${DELETE_NOTE_BUTTON_CLASS}`) ) .append("Also delete the note") )); @@ -111,7 +111,7 @@ export default class ConfirmDialog extends BasicWidget { doResolve(ret) { this.resolve({ confirmed: ret, - isDeleteNoteChecked: this.$widget.find("." + DELETE_NOTE_BUTTON_CLASS + ":checked").length > 0 + isDeleteNoteChecked: this.$widget.find(`.${DELETE_NOTE_BUTTON_CLASS}:checked`).length > 0 }); this.resolve = null; diff --git a/src/public/app/widgets/dialogs/export.js b/src/public/app/widgets/dialogs/export.js index 075182300..5a13f2746 100644 --- a/src/public/app/widgets/dialogs/export.js +++ b/src/public/app/widgets/dialogs/export.js @@ -203,7 +203,7 @@ export default class ExportDialog extends BasicWidget { this.$singleType.prop("checked", true).trigger('change'); } else { - throw new Error("Unrecognized type " + defaultType); + throw new Error(`Unrecognized type ${defaultType}`); } this.$widget.find(".opml-v2").prop("checked", true); // setting default @@ -242,7 +242,7 @@ ws.subscribeToMessages(async message => { toastService.showError(message.message); } else if (message.type === 'taskProgressCount') { - toastService.showPersistent(makeToast(message.taskId, "Export in progress: " + message.progressCount)); + toastService.showPersistent(makeToast(message.taskId, `Export in progress: ${message.progressCount}`)); } else if (message.type === 'taskSucceeded') { const toast = makeToast(message.taskId, "Export finished successfully."); diff --git a/src/public/app/widgets/dialogs/note_revisions.js b/src/public/app/widgets/dialogs/note_revisions.js index 8d71e4f1e..c936c45be 100644 --- a/src/public/app/widgets/dialogs/note_revisions.js +++ b/src/public/app/widgets/dialogs/note_revisions.js @@ -147,9 +147,9 @@ export default class NoteRevisionsDialog extends BasicWidget { for (const item of this.revisionItems) { this.$list.append( $('') - .text(item.dateLastEdited.substr(0, 16) + ` (${item.contentLength} bytes)`) + .text(`${item.dateLastEdited.substr(0, 16)} (${item.contentLength} bytes)`) .attr('data-note-revision-id', item.noteRevisionId) - .attr('title', 'This revision was last edited on ' + item.dateLastEdited) + .attr('title', `This revision was last edited on ${item.dateLastEdited}`) ); } @@ -241,7 +241,7 @@ export default class NoteRevisionsDialog extends BasicWidget { this.$content.html($("") // reason why we put this inline as base64 is that we do not want to let user to copy this // as a URL to be used in a note. Instead if they copy and paste it into a note, it will be a uploaded as a new note - .attr("src", `data:${note.mime};base64,` + fullNoteRevision.content) + .attr("src", `data:${note.mime};base64,${fullNoteRevision.content}`) .css("max-width", "100%") .css("max-height", "100%")); } @@ -253,7 +253,7 @@ export default class NoteRevisionsDialog extends BasicWidget { )) .append($("").append( $("").text("File size:"), - $("").text(revisionItem.contentLength + " bytes") + $("").text(`${revisionItem.contentLength} bytes`) )); if (fullNoteRevision.content) { diff --git a/src/public/app/widgets/dialogs/note_source.js b/src/public/app/widgets/dialogs/note_source.js index c44e59d9b..085210922 100644 --- a/src/public/app/widgets/dialogs/note_source.js +++ b/src/public/app/widgets/dialogs/note_source.js @@ -54,13 +54,15 @@ export default class NoteSourceDialog extends BasicWidget { let textNode; for (let i = 0; i < node.children.length; i++) { - textNode = document.createTextNode('\n' + indentBefore); + textNode = document.createTextNode(` +${indentBefore}`); node.insertBefore(textNode, node.children[i]); this.formatNode(node.children[i], level); if (node.lastElementChild === node.children[i]) { - textNode = document.createTextNode('\n' + indentAfter); + textNode = document.createTextNode(` +${indentAfter}`); node.appendChild(textNode); } } diff --git a/src/public/app/widgets/dialogs/note_type_chooser.js b/src/public/app/widgets/dialogs/note_type_chooser.js index 2031af579..a3d703493 100644 --- a/src/public/app/widgets/dialogs/note_type_chooser.js +++ b/src/public/app/widgets/dialogs/note_type_chooser.js @@ -110,7 +110,7 @@ export default class NoteTypeChooserDialog extends BasicWidget { .attr("data-note-type", noteType.type) .attr("data-template-note-id", noteType.templateNoteId) .append($("").addClass(noteType.uiIcon)) - .append(" " + noteType.title) + .append(` ${noteType.title}`) ); } } diff --git a/src/public/app/widgets/dialogs/recent_changes.js b/src/public/app/widgets/dialogs/recent_changes.js index b6320d76b..f0e82a7cc 100644 --- a/src/public/app/widgets/dialogs/recent_changes.js +++ b/src/public/app/widgets/dialogs/recent_changes.js @@ -57,7 +57,7 @@ export default class RecentChangesDialog extends BasicWidget { this.ancestorNoteId = hoistedNoteService.getHoistedNoteId(); } - const recentChangesRows = await server.get('recent-changes/' + this.ancestorNoteId); + const recentChangesRows = await server.get(`recent-changes/${this.ancestorNoteId}`); // preload all notes into cache await froca.getNotes(recentChangesRows.map(r => r.noteId), true); diff --git a/src/public/app/widgets/find_in_html.js b/src/public/app/widgets/find_in_html.js index 48ca2cb9a..2feb3d5fe 100644 --- a/src/public/app/widgets/find_in_html.js +++ b/src/public/app/widgets/find_in_html.js @@ -37,7 +37,7 @@ export default class FindInHtml { separateWordSearch: false, caseSensitive: matchCase, done: async () => { - this.$results = $content.find("." + FIND_RESULT_CSS_CLASSNAME); + this.$results = $content.find(`.${FIND_RESULT_CSS_CLASSNAME}`); this.currentIndex = 0; await this.jumpTo(); diff --git a/src/public/app/widgets/floating_buttons/code_buttons.js b/src/public/app/widgets/floating_buttons/code_buttons.js index 25474539e..0f15e12bf 100644 --- a/src/public/app/widgets/floating_buttons/code_buttons.js +++ b/src/public/app/widgets/floating_buttons/code_buttons.js @@ -58,7 +58,7 @@ export default class CodeButtonsWidget extends NoteContextAwareWidget { await appContext.tabManager.getActiveContext().setNote(notePath); - toastService.showMessage("SQL Console note has been saved into " + await treeService.getNotePathTitle(notePath)); + toastService.showMessage(`SQL Console note has been saved into ${await treeService.getNotePathTitle(notePath)}`); }); keyboardActionService.updateDisplayedShortcuts(this.$widget); diff --git a/src/public/app/widgets/floating_buttons/zpetne_odkazy.js b/src/public/app/widgets/floating_buttons/zpetne_odkazy.js index d3f115f97..ec896cca5 100644 --- a/src/public/app/widgets/floating_buttons/zpetne_odkazy.js +++ b/src/public/app/widgets/floating_buttons/zpetne_odkazy.js @@ -133,7 +133,7 @@ export default class BacklinksWidget extends NoteContextAwareWidget { })); if (backlink.relationName) { - $item.append($("

").text("relation: " + backlink.relationName)); + $item.append($("

").text(`relation: ${backlink.relationName}`)); } else { $item.append(...backlink.excerpts); diff --git a/src/public/app/widgets/mermaid.js b/src/public/app/widgets/mermaid.js index 82c3c35fa..ad8e94eb8 100644 --- a/src/public/app/widgets/mermaid.js +++ b/src/public/app/widgets/mermaid.js @@ -78,9 +78,9 @@ export default class MermaidWidget extends NoteContextAwareWidget { await wheelZoomLoaded; - this.$display.attr("id", 'mermaid-render-' + idCounter); + this.$display.attr("id", `mermaid-render-${idCounter}`); - WZoom.create('#mermaid-render-' + idCounter, { + WZoom.create(`#mermaid-render-${idCounter}`, { type: 'html', maxScale: 10, speed: 20, @@ -101,7 +101,7 @@ export default class MermaidWidget extends NoteContextAwareWidget { const noteComplement = await froca.getNoteComplement(this.noteId); const content = noteComplement.content || ""; - mermaid.mermaidAPI.render('mermaid-graph-' + idCounter, content, res); + mermaid.mermaidAPI.render(`mermaid-graph-${idCounter}`, content, res); }); } @@ -118,12 +118,12 @@ export default class MermaidWidget extends NoteContextAwareWidget { const renderedSvg = await this.renderSvg(); - this.download(this.note.title + ".svg", renderedSvg); + this.download(`${this.note.title}.svg`, renderedSvg); } download(filename, text) { const element = document.createElement('a'); - element.setAttribute('href', 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(text)); + element.setAttribute('href', `data:image/svg+xml;charset=utf-8,${encodeURIComponent(text)}`); element.setAttribute('download', filename); element.style.display = 'none'; diff --git a/src/public/app/widgets/mobile_widgets/mobile_detail_menu.js b/src/public/app/widgets/mobile_widgets/mobile_detail_menu.js index 88b31cba5..84430c7d1 100644 --- a/src/public/app/widgets/mobile_widgets/mobile_detail_menu.js +++ b/src/public/app/widgets/mobile_widgets/mobile_detail_menu.js @@ -40,7 +40,7 @@ class MobileDetailMenuWidget extends BasicWidget { } } else { - throw new Error("Unrecognized command " + command); + throw new Error(`Unrecognized command ${command}`); } } }); diff --git a/src/public/app/widgets/note_detail.js b/src/public/app/widgets/note_detail.js index 590bbb21b..274e82fa9 100644 --- a/src/public/app/widgets/note_detail.js +++ b/src/public/app/widgets/note_detail.js @@ -170,7 +170,7 @@ export default class NoteDetailWidget extends NoteContextAwareWidget { getTypeWidget() { if (!this.typeWidgets[this.type]) { - throw new Error("Could not find typeWidget for type: " + this.type); + throw new Error(`Could not find typeWidget for type: ${this.type}`); } return this.typeWidgets[this.type]; @@ -268,13 +268,13 @@ export default class NoteDetailWidget extends NoteContextAwareWidget { `, importCSS: false, loadCSS: [ - assetPath + "/libraries/codemirror/codemirror.css", - assetPath + "/libraries/ckeditor/ckeditor-content.css", - assetPath + "/libraries/bootstrap/css/bootstrap.min.css", - assetPath + "/libraries/katex/katex.min.css", - assetPath + "/stylesheets/print.css", - assetPath + "/stylesheets/relation_map.css", - assetPath + "/stylesheets/ckeditor-theme.css" + `${assetPath}/libraries/codemirror/codemirror.css`, + `${assetPath}/libraries/ckeditor/ckeditor-content.css`, + `${assetPath}/libraries/bootstrap/css/bootstrap.min.css`, + `${assetPath}/libraries/katex/katex.min.css`, + `${assetPath}/stylesheets/print.css`, + `${assetPath}/stylesheets/relation_map.css`, + `${assetPath}/stylesheets/ckeditor-theme.css` ], debug: true }); diff --git a/src/public/app/widgets/note_icon.js b/src/public/app/widgets/note_icon.js index 9be439efa..20bdeed79 100644 --- a/src/public/app/widgets/note_icon.js +++ b/src/public/app/widgets/note_icon.js @@ -119,7 +119,7 @@ export default class NoteIconWidget extends NoteContextAwareWidget { } async refreshWithNote(note) { - this.$icon.removeClass().addClass(note.getIcon() + " note-icon"); + this.$icon.removeClass().addClass(`${note.getIcon()} note-icon`); } async entitiesReloadedEvent({loadResults}) { @@ -193,13 +193,13 @@ export default class NoteIconWidget extends NoteContextAwareWidget { getIconClass(icon) { if (icon.type_of_icon === 'LOGO') { - return "bx bxl-" + icon.name; + return `bx bxl-${icon.name}`; } else if (icon.type_of_icon === 'SOLID') { - return "bx bxs-" + icon.name; + return `bx bxs-${icon.name}`; } else { - return "bx bx-" + icon.name; + return `bx bx-${icon.name}`; } } } diff --git a/src/public/app/widgets/note_map.js b/src/public/app/widgets/note_map.js index 78af3ba75..acacedae3 100644 --- a/src/public/app/widgets/note_map.js +++ b/src/public/app/widgets/note_map.js @@ -163,7 +163,7 @@ export default class NoteMapWidget extends NoteContextAwareWidget { generateColorFromString(str) { if (this.themeStyle === "dark") { - str = "0" + str; // magic lightening modifier + str = `0${str}`; // magic lightening modifier } let hash = 0; @@ -175,7 +175,7 @@ export default class NoteMapWidget extends NoteContextAwareWidget { for (let i = 0; i < 3; i++) { const value = (hash >> (i * 8)) & 0xFF; - color += ('00' + value.toString(16)).substr(-2); + color += (`00${value.toString(16)}`).substr(-2); } return color; } @@ -209,14 +209,14 @@ export default class NoteMapWidget extends NoteContextAwareWidget { } ctx.fillStyle = this.css.textColor; - ctx.font = size + 'px ' + this.css.fontFamily; + ctx.font = `${size}px ${this.css.fontFamily}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; let title = node.name; if (title.length > 15) { - title = title.substr(0, 15) + "..."; + title = `${title.substr(0, 15)}...`; } ctx.fillText(title, x, y + Math.round(size * 1.5)); @@ -227,7 +227,7 @@ export default class NoteMapWidget extends NoteContextAwareWidget { return; } - ctx.font = '3px ' + this.css.fontFamily; + ctx.font = `3px ${this.css.fontFamily}`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillStyle = this.css.mutedTextColor; diff --git a/src/public/app/widgets/note_tree.js b/src/public/app/widgets/note_tree.js index 1f48844d6..0e2e24e6f 100644 --- a/src/public/app/widgets/note_tree.js +++ b/src/public/app/widgets/note_tree.js @@ -273,19 +273,19 @@ export default class NoteTreeWidget extends NoteContextAwareWidget { } get hideArchivedNotes() { - return options.is("hideArchivedNotes_" + this.treeName); + return options.is(`hideArchivedNotes_${this.treeName}`); } async setHideArchivedNotes(val) { - await options.save("hideArchivedNotes_" + this.treeName, val.toString()); + await options.save(`hideArchivedNotes_${this.treeName}`, val.toString()); } get hideIncludedImages() { - return options.is("hideIncludedImages_" + this.treeName); + return options.is(`hideIncludedImages_${this.treeName}`); } async setHideIncludedImages(val) { - await options.save("hideIncludedImages_" + this.treeName, val.toString()); + await options.save(`hideIncludedImages_${this.treeName}`, val.toString()); } get autoCollapseNoteTree() { @@ -484,7 +484,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget { } else if (data.hitMode === "over") { branchService.moveToParentNote(selectedBranchIds, node.data.branchId); } else { - throw new Error("Unknown hitMode=" + data.hitMode); + throw new Error(`Unknown hitMode=${data.hitMode}`); } } } @@ -676,7 +676,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget { return; } - const title = (branch.prefix ? (branch.prefix + " - ") : "") + note.title; + const title = `${branch.prefix ? (`${branch.prefix} - `) : ""}${note.title}`; node.data.isProtected = note.isProtected; node.data.noteType = note.type; @@ -703,7 +703,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget { throw new Error(`Branch "${branch.branchId}" has no child note "${branch.noteId}"`); } - const title = (branch.prefix ? (branch.prefix + " - ") : "") + note.title; + const title = `${branch.prefix ? (`${branch.prefix} - `) : ""}${note.title}`; const isFolder = note.isFolder(); diff --git a/src/public/app/widgets/note_type.js b/src/public/app/widgets/note_type.js index 779ada63b..708375d61 100644 --- a/src/public/app/widgets/note_type.js +++ b/src/public/app/widgets/note_type.js @@ -139,7 +139,7 @@ export default class NoteTypeWidget extends NoteContextAwareWidget { return; } - await server.put('notes/' + this.noteId + '/type', { type, mime }); + await server.put(`notes/${this.noteId}/type`, { type, mime }); } async confirmChangeIfContent() { diff --git a/src/public/app/widgets/quick_search.js b/src/public/app/widgets/quick_search.js index 5b7370263..a3d5a402f 100644 --- a/src/public/app/widgets/quick_search.js +++ b/src/public/app/widgets/quick_search.js @@ -98,12 +98,12 @@ export default class QuickSearchWidget extends BasicWidget { this.$dropdownMenu.empty(); this.$dropdownMenu.append(' Searching ...'); - const {searchResultNoteIds, error} = await server.get('quick-search/' + encodeURIComponent(searchString)); + const {searchResultNoteIds, error} = await server.get(`quick-search/${encodeURIComponent(searchString)}`); if (error) { this.$searchString.tooltip({ trigger: 'manual', - title: "Search error: " + error, + title: `Search error: ${error}`, placement: 'right' }); diff --git a/src/public/app/widgets/ribbon_widgets/edited_notes.js b/src/public/app/widgets/ribbon_widgets/edited_notes.js index 2b86e1d95..a68450a47 100644 --- a/src/public/app/widgets/ribbon_widgets/edited_notes.js +++ b/src/public/app/widgets/ribbon_widgets/edited_notes.js @@ -48,7 +48,7 @@ export default class EditedNotesWidget extends CollapsibleWidget { } async refreshWithNote(note) { - let editedNotes = await server.get('edited-notes/' + note.getLabelValue("dateNote")); + let editedNotes = await server.get(`edited-notes/${note.getLabelValue("dateNote")}`); editedNotes = editedNotes.filter(n => n.noteId !== note.noteId); @@ -69,7 +69,7 @@ export default class EditedNotesWidget extends CollapsibleWidget { const $item = $(''); if (editedNote.isDeleted) { - const title = editedNote.title + " (deleted)"; + const title = `${editedNote.title} (deleted)`; $item.append( $("") .text(title) diff --git a/src/public/app/widgets/ribbon_widgets/file_properties.js b/src/public/app/widgets/ribbon_widgets/file_properties.js index 536fa7af7..454c73f1d 100644 --- a/src/public/app/widgets/ribbon_widgets/file_properties.js +++ b/src/public/app/widgets/ribbon_widgets/file_properties.js @@ -104,7 +104,7 @@ export default class FilePropertiesWidget extends NoteContextAwareWidget { formData.append('upload', fileToUpload); const result = await $.ajax({ - url: baseApiUrl + 'notes/' + this.noteId + '/file', + url: `${baseApiUrl}notes/${this.noteId}/file`, headers: await server.getHeaders(), data: formData, type: 'PUT', @@ -136,7 +136,7 @@ export default class FilePropertiesWidget extends NoteContextAwareWidget { const noteComplement = await this.noteContext.getNoteComplement(); - this.$fileSize.text(noteComplement.contentLength + " bytes"); + this.$fileSize.text(`${noteComplement.contentLength} bytes`); // open doesn't work for protected notes since it works through browser which isn't in protected session this.$openButton.toggle(!note.isProtected); diff --git a/src/public/app/widgets/ribbon_widgets/image_properties.js b/src/public/app/widgets/ribbon_widgets/image_properties.js index f59f45787..9cf31bf65 100644 --- a/src/public/app/widgets/ribbon_widgets/image_properties.js +++ b/src/public/app/widgets/ribbon_widgets/image_properties.js @@ -88,7 +88,7 @@ export default class ImagePropertiesWidget extends NoteContextAwareWidget { formData.append('upload', fileToUpload); const result = await $.ajax({ - url: baseApiUrl + 'images/' + this.noteId, + url: `${baseApiUrl}images/${this.noteId}`, headers: await server.getHeaders(), data: formData, type: 'PUT', @@ -105,7 +105,7 @@ export default class ImagePropertiesWidget extends NoteContextAwareWidget { this.refresh(); } else { - toastService.showError("Upload of a new image revision failed: " + result.message); + toastService.showError(`Upload of a new image revision failed: ${result.message}`); } }); } @@ -119,7 +119,7 @@ export default class ImagePropertiesWidget extends NoteContextAwareWidget { const noteComplement = await this.noteContext.getNoteComplement(); this.$fileName.text(attributeMap.originalFileName || "?"); - this.$fileSize.text(noteComplement.contentLength + " bytes"); + this.$fileSize.text(`${noteComplement.contentLength} bytes`); this.$fileType.text(note.mime); } } diff --git a/src/public/app/widgets/ribbon_widgets/note_info_widget.js b/src/public/app/widgets/ribbon_widgets/note_info_widget.js index 18927f8ed..28459da5d 100644 --- a/src/public/app/widgets/ribbon_widgets/note_info_widget.js +++ b/src/public/app/widgets/ribbon_widgets/note_info_widget.js @@ -110,7 +110,7 @@ export default class NoteInfoWidget extends NoteContextAwareWidget { const subTreeResp = await server.get(`stats/subtree-size/${this.noteId}`); if (subTreeResp.subTreeNoteCount > 1) { - this.$subTreeSize.text("(subtree size: " + this.formatSize(subTreeResp.subTreeSize) + ` in ${subTreeResp.subTreeNoteCount} notes)`); + this.$subTreeSize.text(`(subtree size: ${this.formatSize(subTreeResp.subTreeSize)} in ${subTreeResp.subTreeNoteCount} notes)`); } else { this.$subTreeSize.text(""); @@ -133,7 +133,7 @@ export default class NoteInfoWidget extends NoteContextAwareWidget { this.$type.text(note.type); if (note.mime) { - this.$mime.text('(' + note.mime + ')'); + this.$mime.text(`(${note.mime})`); } else { this.$mime.empty(); diff --git a/src/public/app/widgets/ribbon_widgets/promoted_attributes.js b/src/public/app/widgets/ribbon_widgets/promoted_attributes.js index 6c6e58495..ac5286795 100644 --- a/src/public/app/widgets/ribbon_widgets/promoted_attributes.js +++ b/src/public/app/widgets/ribbon_widgets/promoted_attributes.js @@ -139,7 +139,7 @@ export default class PromotedAttributesWidget extends NoteContextAwareWidget { $input.prop("type", "text"); // no need to await for this, can be done asynchronously - server.get('attributes/values/' + encodeURIComponent(valueAttr.name)).then(attributeValues => { + server.get(`attributes/values/${encodeURIComponent(valueAttr.name)}`).then(attributeValues => { if (attributeValues.length === 0) { return; } @@ -207,7 +207,7 @@ export default class PromotedAttributesWidget extends NoteContextAwareWidget { .append($openButton)); } else { - ws.logError("Unknown labelType=" + definitionAttr.labelType); + ws.logError(`Unknown labelType=${definitionAttr.labelType}`); } } else if (valueAttr.type === 'relation') { @@ -225,7 +225,7 @@ export default class PromotedAttributesWidget extends NoteContextAwareWidget { $input.setSelectedNotePath(valueAttr.value); } else { - ws.logError("Unknown attribute type=" + valueAttr.type); + ws.logError(`Unknown attribute type=${valueAttr.type}`); return; } @@ -253,7 +253,7 @@ export default class PromotedAttributesWidget extends NoteContextAwareWidget { const attributeId = $input.attr("data-attribute-id"); if (attributeId) { - await server.remove("notes/" + this.noteId + "/attributes/" + attributeId, this.componentId); + await server.remove(`notes/${this.noteId}/attributes/${attributeId}`, this.componentId); } // if it's the last one the create new empty form immediately diff --git a/src/public/app/widgets/ribbon_widgets/search_definition.js b/src/public/app/widgets/ribbon_widgets/search_definition.js index 1cc8da73a..a370e1715 100644 --- a/src/public/app/widgets/ribbon_widgets/search_definition.js +++ b/src/public/app/widgets/ribbon_widgets/search_definition.js @@ -244,7 +244,7 @@ export default class SearchDefinitionWidget extends NoteContextAwareWidget { await appContext.tabManager.getActiveContext().setNote(notePath); - toastService.showMessage("Search note has been saved into " + await treeService.getNotePathTitle(notePath)); + toastService.showMessage(`Search note has been saved into ${await treeService.getNotePathTitle(notePath)}`); }); } diff --git a/src/public/app/widgets/ribbon_widgets/similar_notes.js b/src/public/app/widgets/ribbon_widgets/similar_notes.js index 55f0abd2d..8a34d2d1b 100644 --- a/src/public/app/widgets/ribbon_widgets/similar_notes.js +++ b/src/public/app/widgets/ribbon_widgets/similar_notes.js @@ -64,7 +64,7 @@ export default class SimilarNotesWidget extends NoteContextAwareWidget { // remember which title was when we found the similar notes this.title = this.note.title; - const similarNotes = await server.get('similar-notes/' + this.noteId); + const similarNotes = await server.get(`similar-notes/${this.noteId}`); if (similarNotes.length === 0) { this.$similarNotesWrapper.empty().append("No similar notes found."); diff --git a/src/public/app/widgets/search_options/search_string.js b/src/public/app/widgets/search_options/search_string.js index b89510f04..89bc3304e 100644 --- a/src/public/app/widgets/search_options/search_string.js +++ b/src/public/app/widgets/search_options/search_string.js @@ -61,7 +61,7 @@ export default class SearchString extends AbstractSearchOption { if (this.note.title.startsWith('Search: ')) { await server.put(`notes/${this.note.noteId}/title`, { - title: 'Search: ' + (searchString.length < 30 ? searchString : `${searchString.substr(0, 30)}…`) + title: `Search: ${searchString.length < 30 ? searchString : `${searchString.substr(0, 30)}…`}` }); } }, 1000); @@ -74,7 +74,7 @@ export default class SearchString extends AbstractSearchOption { showSearchErrorEvent({error}) { this.$searchString.tooltip({ trigger: 'manual', - title: "Search error: " + error, + title: `Search error: ${error}`, placement: 'bottom' }); diff --git a/src/public/app/widgets/shared_info.js b/src/public/app/widgets/shared_info.js index db9ed6835..8267bd733 100644 --- a/src/public/app/widgets/shared_info.js +++ b/src/public/app/widgets/shared_info.js @@ -35,11 +35,11 @@ export default class SharedInfoWidget extends NoteContextAwareWidget { const shareId = this.getShareId(note); if (syncServerHost) { - link = syncServerHost + "/share/" + shareId; + link = `${syncServerHost}/share/${shareId}`; this.$sharedText.text("This note is shared publicly on"); } else { - link = location.protocol + '//' + location.host + location.pathname + "share/" + shareId; + link = `${location.protocol}//${location.host}${location.pathname}share/${shareId}`; this.$sharedText.text("This note is shared locally on"); } diff --git a/src/public/app/widgets/sync_status.js b/src/public/app/widgets/sync_status.js index 5b52c447c..d4e5187cc 100644 --- a/src/public/app/widgets/sync_status.js +++ b/src/public/app/widgets/sync_status.js @@ -105,7 +105,7 @@ export default class SyncStatusWidget extends BasicWidget { this.$widget.show(); this.$widget.find('.sync-status-icon').hide(); - this.$widget.find('.sync-status-' + className).show(); + this.$widget.find(`.sync-status-${className}`).show(); } processMessage(message) { @@ -134,7 +134,7 @@ export default class SyncStatusWidget extends BasicWidget { if (['unknown', 'in-progress'].includes(this.syncState)) { this.showIcon(this.syncState); } else { - this.showIcon(this.syncState + '-' + (this.allChangesPushed ? 'no-changes' : 'with-changes')); + this.showIcon(`${this.syncState}-${this.allChangesPushed ? 'no-changes' : 'with-changes'}`); } } } diff --git a/src/public/app/widgets/tab_row.js b/src/public/app/widgets/tab_row.js index 17fdb7305..a401157fc 100644 --- a/src/public/app/widgets/tab_row.js +++ b/src/public/app/widgets/tab_row.js @@ -12,11 +12,11 @@ import attributeService from "../services/attributes.js"; * https://draggabilly.desandro.com * MIT license */ -(function(e,i){e.jQueryBridget=i(e,e.jQuery)})(window,function t(e,r){"use strict";var s=Array.prototype.slice;var i=e.console;var f=typeof i=="undefined"?function(){}:function(t){i.error(t)};function n(h,o,d){d=d||r||e.jQuery;if(!d){return}if(!o.prototype.option){o.prototype.option=function(t){if(!d.isPlainObject(t)){return}this.options=d.extend(true,this.options,t)}}d.fn[h]=function(t){if(typeof t=="string"){var e=s.call(arguments,1);return i(this,t,e)}n(this,t);return this};function i(t,r,s){var a;var u="$()."+h+'("'+r+'")';t.each(function(t,e){var i=d.data(e,h);if(!i){f(h+" not initialized. Cannot call methods, i.e. "+u);return}var n=i[r];if(!n||r.charAt(0)=="_"){f(u+" is not a valid method");return}var o=n.apply(i,s);a=a===undefined?o:a});return a!==undefined?a:t}function n(t,n){t.each(function(t,e){var i=d.data(e,h);if(i){i.option(n);i._init()}else{i=new o(e,n);d.data(e,h,i)}})}a(d)}function a(t){if(!t||t&&t.bridget){return}t.bridget=n}a(r||e.jQuery);return n}); -(function(t,e){"use strict";t.getSize=e()})(window,function t(){"use strict";function m(t){var e=parseFloat(t);var i=t.indexOf("%")==-1&&!isNaN(e);return i&&e}function e(){}var i=typeof console=="undefined"?e:function(t){console.error(t)};var y=["paddingLeft","paddingRight","paddingTop","paddingBottom","marginLeft","marginRight","marginTop","marginBottom","borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth"];var b=y.length;function E(){var t={width:0,height:0,innerWidth:0,innerHeight:0,outerWidth:0,outerHeight:0};for(var e=0;e

') - .append($("
").addClass(workspaceNote.getIcon() + " workspace-icon")) + .append($("
").addClass(`${workspaceNote.getIcon()} workspace-icon`)) .append($("
").text(workspaceNote.title)) - .attr("title", "Enter workspace " + workspaceNote.title) + .attr("title", `Enter workspace ${workspaceNote.title}`) .on('click', () => this.triggerCommand('hoistNote', {noteId: workspaceNote.noteId})) ); } diff --git a/src/public/app/widgets/type_widgets/file.js b/src/public/app/widgets/type_widgets/file.js index f6d3409ae..0fd78bd35 100644 --- a/src/public/app/widgets/type_widgets/file.js +++ b/src/public/app/widgets/type_widgets/file.js @@ -65,19 +65,19 @@ export default class FileTypeWidget extends TypeWidget { this.$previewContent.text(noteComplement.content); } else if (note.mime === 'application/pdf') { - this.$pdfPreview.show().attr("src", openService.getUrlForDownload("api/notes/" + this.noteId + "/open")); + this.$pdfPreview.show().attr("src", openService.getUrlForDownload(`api/notes/${this.noteId}/open`)); } else if (note.mime.startsWith('video/')) { this.$videoPreview .show() - .attr("src", openService.getUrlForDownload("api/notes/" + this.noteId + "/open-partial")) + .attr("src", openService.getUrlForDownload(`api/notes/${this.noteId}/open-partial`)) .attr("type", this.note.mime) .css("width", this.$widget.width()); } else if (note.mime.startsWith('audio/')) { this.$audioPreview .show() - .attr("src", openService.getUrlForDownload("api/notes/" + this.noteId + "/open-partial")) + .attr("src", openService.getUrlForDownload(`api/notes/${this.noteId}/open-partial`)) .attr("type", this.note.mime) .css("width", this.$widget.width()); } diff --git a/src/public/app/widgets/type_widgets/image.js b/src/public/app/widgets/type_widgets/image.js index 4ef6628d8..8974b8e61 100644 --- a/src/public/app/widgets/type_widgets/image.js +++ b/src/public/app/widgets/type_widgets/image.js @@ -45,10 +45,10 @@ class ImageTypeWidget extends TypeWidget { this.$widget = $(TPL); this.$imageWrapper = this.$widget.find('.note-detail-image-wrapper'); this.$imageView = this.$widget.find('.note-detail-image-view') - .attr("id", "image-view-" + utils.randomString(10)); + .attr("id", `image-view-${utils.randomString(10)}`); libraryLoader.requireLibrary(libraryLoader.WHEEL_ZOOM).then(() => { - WZoom.create('#' + this.$imageView.attr("id"), { + WZoom.create(`#${this.$imageView.attr("id")}`, { maxScale: 10, speed: 20, zoomOnClick: false diff --git a/src/public/app/widgets/type_widgets/options/advanced/database_integrity_check.js b/src/public/app/widgets/type_widgets/options/advanced/database_integrity_check.js index 5fc1264b9..6e734379b 100644 --- a/src/public/app/widgets/type_widgets/options/advanced/database_integrity_check.js +++ b/src/public/app/widgets/type_widgets/options/advanced/database_integrity_check.js @@ -24,7 +24,7 @@ export default class DatabaseIntegrityCheckOptions extends OptionsWidget { toastService.showMessage("Integrity check succeeded - no problems found."); } else { - toastService.showMessage("Integrity check failed: " + JSON.stringify(results, null, 2), 15000); + toastService.showMessage(`Integrity check failed: ${JSON.stringify(results, null, 2)}`, 15000); } }); } diff --git a/src/public/app/widgets/type_widgets/options/appearance/fonts.js b/src/public/app/widgets/type_widgets/options/appearance/fonts.js index 964ff09fb..d208ccb65 100644 --- a/src/public/app/widgets/type_widgets/options/appearance/fonts.js +++ b/src/public/app/widgets/type_widgets/options/appearance/fonts.js @@ -167,8 +167,8 @@ export default class FontsOptions extends OptionsWidget { ]; for (const optionName of optionsToSave) { - this['$' + optionName].on('change', () => - this.updateOption(optionName, this['$' + optionName].val())); + this[`$${optionName}`].on('change', () => + this.updateOption(optionName, this[`$${optionName}`].val())); } } diff --git a/src/public/app/widgets/type_widgets/options/appearance/theme.js b/src/public/app/widgets/type_widgets/options/appearance/theme.js index 15c850858..91b0cbb7f 100644 --- a/src/public/app/widgets/type_widgets/options/appearance/theme.js +++ b/src/public/app/widgets/type_widgets/options/appearance/theme.js @@ -28,7 +28,7 @@ export default class ThemeOptions extends OptionsWidget { this.$themeSelect.on('change', async () => { const newTheme = this.$themeSelect.val(); - await server.put('options/theme/' + newTheme); + await server.put(`options/theme/${newTheme}`); utils.reloadFrontendApp("theme change"); }); diff --git a/src/public/app/widgets/type_widgets/options/backup.js b/src/public/app/widgets/type_widgets/options/backup.js index 674801055..d5430d30b 100644 --- a/src/public/app/widgets/type_widgets/options/backup.js +++ b/src/public/app/widgets/type_widgets/options/backup.js @@ -48,7 +48,7 @@ export default class BackupOptions extends OptionsWidget { this.$backupDatabaseButton.on('click', async () => { const {backupFile} = await server.post('database/backup-database'); - toastService.showMessage("Database has been backed up to " + backupFile, 10000); + toastService.showMessage(`Database has been backed up to ${backupFile}`, 10000); }); this.$dailyBackupEnabled = this.$widget.find(".daily-backup-enabled"); diff --git a/src/public/app/widgets/type_widgets/options/shortcuts.js b/src/public/app/widgets/type_widgets/options/shortcuts.js index f3393fdca..a2c89437b 100644 --- a/src/public/app/widgets/type_widgets/options/shortcuts.js +++ b/src/public/app/widgets/type_widgets/options/shortcuts.js @@ -106,7 +106,7 @@ export default class KeyboardShortcutsOptions extends OptionsWidget { .map(shortcut => shortcut.replace("+Comma", "+,")) .filter(shortcut => !!shortcut); - const optionName = 'keyboardShortcuts' + actionName.substr(0, 1).toUpperCase() + actionName.substr(1); + const optionName = `keyboardShortcuts${actionName.substr(0, 1).toUpperCase()}${actionName.substr(1)}`; this.updateOption(optionName, JSON.stringify(shortcuts)); }); diff --git a/src/public/app/widgets/type_widgets/options/sync.js b/src/public/app/widgets/type_widgets/options/sync.js index e7ac9b8cc..ade20b129 100644 --- a/src/public/app/widgets/type_widgets/options/sync.js +++ b/src/public/app/widgets/type_widgets/options/sync.js @@ -59,7 +59,7 @@ export default class SyncOptions extends OptionsWidget { toastService.showMessage(result.message); } else { - toastService.showError("Sync server handshake failed, error: " + result.message); + toastService.showError(`Sync server handshake failed, error: ${result.message}`); } }); } diff --git a/src/public/app/widgets/type_widgets/relation_map.js b/src/public/app/widgets/type_widgets/relation_map.js index c3e1a1402..870c5c85e 100644 --- a/src/public/app/widgets/type_widgets/relation_map.js +++ b/src/public/app/widgets/type_widgets/relation_map.js @@ -209,7 +209,7 @@ export default class RelationMapTypeWidget extends TypeWidget { } noteIdToId(noteId) { - return "rel-map-note-" + noteId; + return `rel-map-note-${noteId}`; } idToNoteId(id) { @@ -484,8 +484,8 @@ export default class RelationMapTypeWidget extends TypeWidget { .prop("id", this.noteIdToId(noteId)) .append($("").addClass("title").append($link)) .append($("
").addClass("endpoint").attr("title", "Start dragging relations from here and drop them on another note.")) - .css("left", x + "px") - .css("top", y + "px"); + .css("left", `${x}px`) + .css("top", `${y}px`); this.jsPlumbInstance.getContainer().appendChild($noteBox[0]); @@ -537,7 +537,7 @@ export default class RelationMapTypeWidget extends TypeWidget { const matches = transform.match(matrixRegex); if (!matches) { - throw new Error("Cannot match transform: " + transform); + throw new Error(`Cannot match transform: ${transform}`); } return matches[1]; diff --git a/src/routes/api/autocomplete.js b/src/routes/api/autocomplete.js index 5f5448f6e..31da671b3 100644 --- a/src/routes/api/autocomplete.js +++ b/src/routes/api/autocomplete.js @@ -38,7 +38,7 @@ function getRecentNotes(activeNoteId) { const hoistedNoteId = cls.getHoistedNoteId(); if (hoistedNoteId !== 'root') { extraCondition = `AND recent_notes.notePath LIKE ?`; - params.push('%' + hoistedNoteId + '%'); + params.push(`%${hoistedNoteId}%`); } const recentNotes = becca.getRecentNotesFromQuery(` diff --git a/src/routes/api/clipper.js b/src/routes/api/clipper.js index ac3bb416f..fc3fcbdc4 100644 --- a/src/routes/api/clipper.js +++ b/src/routes/api/clipper.js @@ -68,7 +68,7 @@ function addClipping(req) { const existingContent = clippingNote.getContent(); - clippingNote.setContent(existingContent + (existingContent.trim() ? "
" : "") + rewrittenContent); + clippingNote.setContent(`${existingContent}${existingContent.trim() ? "
" : ""}${rewrittenContent}`); return { noteId: clippingNote.noteId @@ -79,7 +79,7 @@ function createNote(req) { let {title, content, pageUrl, images, clipType} = req.body; if (!title || !title.trim()) { - title = "Clipped note from " + pageUrl; + title = `Clipped note from ${pageUrl}`; } const clipperInbox = getClipperInboxNote(); @@ -123,7 +123,7 @@ function processContent(images, note, content) { ? dataUrl.substr(0, Math.min(100, dataUrl.length)) : "null"; - log.info("Image could not be recognized as data URL: " + excerpt); + log.info(`Image could not be recognized as data URL: ${excerpt}`); continue; } diff --git a/src/routes/api/database.js b/src/routes/api/database.js index 0f008b56c..27658f39d 100644 --- a/src/routes/api/database.js +++ b/src/routes/api/database.js @@ -25,7 +25,7 @@ function vacuumDatabase() { function checkIntegrity() { const results = sql.getRows("PRAGMA integrity_check"); - log.info("Integrity check result: " + JSON.stringify(results)); + log.info(`Integrity check result: ${JSON.stringify(results)}`); return { results diff --git a/src/routes/api/image.js b/src/routes/api/image.js index aa6151ce6..adf3a6441 100644 --- a/src/routes/api/image.js +++ b/src/routes/api/image.js @@ -18,7 +18,7 @@ function returnImage(req, res) { } else if (image.isDeleted || image.data === null) { res.set('Content-Type', 'image/png'); - return res.send(fs.readFileSync(RESOURCE_DIR + '/db/image-deleted.png')); + return res.send(fs.readFileSync(`${RESOURCE_DIR}/db/image-deleted.png`)); } /** @@ -81,7 +81,7 @@ function updateImage(req) { if (!["image/png", "image/jpeg", "image/gif", "image/webp", "image/svg+xml"].includes(file.mimetype)) { return { uploaded: false, - message: "Unknown image type: " + file.mimetype + message: `Unknown image type: ${file.mimetype}` }; } diff --git a/src/routes/api/import.js b/src/routes/api/import.js index f62f37b7c..7edcb0ff1 100644 --- a/src/routes/api/import.js +++ b/src/routes/api/import.js @@ -63,7 +63,7 @@ async function importToBranch(req) { } } catch (e) { - const message = "Import failed with following error: '" + e.message + "'. More details might be in the logs."; + const message = `Import failed with following error: '${e.message}'. More details might be in the logs.`; taskContext.reportError(message); log.error(message + e.stack); diff --git a/src/routes/api/note_map.js b/src/routes/api/note_map.js index 027900958..36072e04a 100644 --- a/src/routes/api/note_map.js +++ b/src/routes/api/note_map.js @@ -138,7 +138,7 @@ function getLinkMap(req) { } }) .map(rel => ({ - id: rel.noteId + "-" + rel.name + "-" + rel.value, + id: `${rel.noteId}-${rel.name}-${rel.value}`, sourceNoteId: rel.noteId, targetNoteId: rel.value, name: rel.name @@ -267,7 +267,7 @@ function findExcerpts(sourceNote, referencedNoteId) { if (prevText.length + excerptLength > EXCERPT_CHAR_LIMIT) { const prefix = prevText.substr(prevText.length - (EXCERPT_CHAR_LIMIT - excerptLength)); - const textNode = document.createTextNode("…" + prefix); + const textNode = document.createTextNode(`…${prefix}`); excerptEls.unshift(textNode); break; @@ -287,7 +287,7 @@ function findExcerpts(sourceNote, referencedNoteId) { if (nextText.length + excerptLength > EXCERPT_CHAR_LIMIT) { const suffix = nextText.substr(nextText.length - (EXCERPT_CHAR_LIMIT - excerptLength)); - const textNode = document.createTextNode(suffix + "…"); + const textNode = document.createTextNode(`${suffix}…`); excerptEls.push(textNode); break; diff --git a/src/routes/api/note_revisions.js b/src/routes/api/note_revisions.js index be301e621..d81c6afa2 100644 --- a/src/routes/api/note_revisions.js +++ b/src/routes/api/note_revisions.js @@ -52,11 +52,10 @@ function getRevisionFilename(noteRevision) { .replace(/[^0-9_]/g, ''); if (extension) { - filename = filename.substr(0, filename.length - extension.length) - + '-' + date + extension; + filename = `${filename.substr(0, filename.length - extension.length)}-${date}${extension}`; } else { - filename += '-' + date; + filename += `-${date}`; } return filename; @@ -123,7 +122,7 @@ function getEditedNotesOnDate(req) { WHERE note_revisions.dateLastEdited LIKE :date ) ORDER BY isDeleted - LIMIT 50`, {date: req.params.date + '%'}); + LIMIT 50`, {date: `${req.params.date}%`}); let notes = becca.getNotes(noteIds, true); diff --git a/src/routes/api/notes.js b/src/routes/api/notes.js index ba112b034..4268b7d4d 100644 --- a/src/routes/api/notes.js +++ b/src/routes/api/notes.js @@ -25,8 +25,7 @@ function getNote(req) { pojo.content = note.getContent(); if (note.type === 'file' && pojo.content.length > 10000) { - pojo.content = pojo.content.substr(0, 10000) - + `\r\n\r\n... and ${pojo.content.length - 10000} more characters.`; + pojo.content = `${pojo.content.substr(0, 10000)}\r\n\r\n... and ${pojo.content.length - 10000} more characters.`; } } diff --git a/src/routes/api/sender.js b/src/routes/api/sender.js index bb51ec22b..fc0368758 100644 --- a/src/routes/api/sender.js +++ b/src/routes/api/sender.js @@ -10,10 +10,10 @@ function uploadImage(req) { const file = req.file; if (!["image/png", "image/jpeg", "image/gif", "image/webp", "image/svg+xml"].includes(file.mimetype)) { - return [400, "Unknown image type: " + file.mimetype]; + return [400, `Unknown image type: ${file.mimetype}`]; } - const originalName = "Sender image." + imageType(file.buffer).ext; + const originalName = `Sender image.${imageType(file.buffer).ext}`; const parentNote = dateNoteService.getDayNote(req.headers['x-local-date']); diff --git a/src/routes/api/sync.js b/src/routes/api/sync.js index 7d62ca895..c035ca94f 100644 --- a/src/routes/api/sync.js +++ b/src/routes/api/sync.js @@ -114,7 +114,7 @@ function forceNoteSync(req) { entityChangesService.moveEntityChangeToTop('note_revision_contents', noteRevisionId); } - log.info("Forcing note sync for " + noteId); + log.info(`Forcing note sync for ${noteId}`); // not awaiting for the job to finish (will probably take a long time) syncService.sync(); diff --git a/src/routes/custom.js b/src/routes/custom.js index 7a6ee9c46..077c730cd 100644 --- a/src/routes/custom.js +++ b/src/routes/custom.js @@ -26,7 +26,7 @@ function handleRequest(req, res) { match = path.match(regex); } catch (e) { - log.error(`Testing path for label ${attr.attributeId}, regex=${attr.value} failed with error ` + e.stack); + log.error(`Testing path for label ${attr.attributeId}, regex=${attr.value} failed with error ${e.stack}`); continue; } @@ -58,7 +58,7 @@ function handleRequest(req, res) { fileUploadService.downloadNoteFile(attr.noteId, res); } else { - throw new Error("Unrecognized attribute name " + attr.name); + throw new Error(`Unrecognized attribute name ${attr.name}`); } return; // only first handler is executed diff --git a/src/services/anonymization.js b/src/services/anonymization.js index 998a8ce86..09fe37739 100644 --- a/src/services/anonymization.js +++ b/src/services/anonymization.js @@ -9,7 +9,7 @@ function getFullAnonymizationScript() { // we want to delete all non-builtin attributes because they can contain sensitive names and values // on the other hand builtin/system attrs should not contain any sensitive info const builtinAttrNames = BUILTIN_ATTRIBUTES - .map(attr => "'" + attr.name + "'").join(', '); + .map(attr => `'${attr.name}'`).join(', '); const anonymizeScript = ` UPDATE etapi_tokens SET tokenHash = 'API token hash value'; diff --git a/src/services/asset_path.js b/src/services/asset_path.js index 5b6535f4d..a32ebc553 100644 --- a/src/services/asset_path.js +++ b/src/services/asset_path.js @@ -1,3 +1,3 @@ const packageJson = require('../../package.json'); -module.exports = "assets/v" + packageJson.version; +module.exports = `assets/v${packageJson.version}`; diff --git a/src/services/attribute_formatter.js b/src/services/attribute_formatter.js index f02e9f731..8891a7813 100644 --- a/src/services/attribute_formatter.js +++ b/src/services/attribute_formatter.js @@ -32,16 +32,16 @@ function formatValue(val) { return val; } else if (!val.includes('"')) { - return '"' + val + '"'; + return `"${val}"`; } else if (!val.includes("'")) { - return "'" + val + "'"; + return `'${val}'`; } else if (!val.includes("`")) { - return "`" + val + "`"; + return `\`${val}\``; } else { - return '"' + val.replace(/"/g, '\\"') + '"'; + return `"${val.replace(/"/g, '\\"')}"`; } } diff --git a/src/services/attributes.js b/src/services/attributes.js index 5c6d309a0..406bfbcca 100644 --- a/src/services/attributes.js +++ b/src/services/attributes.js @@ -87,7 +87,7 @@ function getAttributeNames(type, nameLike) { FROM attributes WHERE isDeleted = 0 AND type = ? - AND name LIKE ?`, [type, '%' + nameLike + '%']); + AND name LIKE ?`, [type, `%${nameLike}%`]); for (const attr of BUILTIN_ATTRIBUTES) { if (attr.type === type && attr.name.toLowerCase().includes(nameLike) && !names.includes(attr.name)) { diff --git a/src/services/backup.js b/src/services/backup.js index 1adf9d530..c7908524f 100644 --- a/src/services/backup.js +++ b/src/services/backup.js @@ -47,7 +47,7 @@ async function backupNow(name) { await sql.copyDatabase(backupFile); - log.info("Created backup at " + backupFile); + log.info(`Created backup at ${backupFile}`); return backupFile; }); diff --git a/src/services/bulk_actions.js b/src/services/bulk_actions.js index 72a0f8d1e..eaa57a1fb 100644 --- a/src/services/bulk_actions.js +++ b/src/services/bulk_actions.js @@ -13,7 +13,7 @@ const ACTION_HANDLERS = { note.addRelation(action.relationName, action.targetNoteId); }, deleteNote: (action, note) => { - const deleteId = 'searchbulkaction-' + utils.randomString(10); + const deleteId = `searchbulkaction-${utils.randomString(10)}`; note.deleteNote(deleteId); }, @@ -34,7 +34,7 @@ const ACTION_HANDLERS = { // "officially" injected value: // - note - const newTitle = eval('`' + action.newTitle + '`'); + const newTitle = eval(`\`${action.newTitle}\``); if (note.title !== newTitle) { note.title = newTitle; diff --git a/src/services/cloning.js b/src/services/cloning.js index 4f89fb8fe..bb905f5b6 100644 --- a/src/services/cloning.js +++ b/src/services/cloning.js @@ -40,7 +40,7 @@ function cloneNoteToNote(noteId, parentNoteId, prefix) { return { success: true, branchId: branch.branchId, - notePath: beccaService.getNotePath(parentNoteId).path + "/" + noteId + notePath: `${beccaService.getNotePath(parentNoteId).path}/${noteId}` }; } diff --git a/src/services/consistency_checks.js b/src/services/consistency_checks.js index 2d7230879..8a2a75f36 100644 --- a/src/services/consistency_checks.js +++ b/src/services/consistency_checks.js @@ -694,7 +694,7 @@ class ConsistencyChecks { const tables = [ "notes", "note_revisions", "branches", "attributes", "etapi_tokens" ]; - log.info("Table counts: " + tables.map(tableName => getTableRowCount(tableName)).join(", ")); + log.info(`Table counts: ${tables.map(tableName => getTableRowCount(tableName)).join(", ")}`); } async runChecks() { @@ -736,11 +736,11 @@ function getBlankContent(isProtected, type, mime) { } function logFix(message) { - log.info("Consistency issue fixed: " + message); + log.info(`Consistency issue fixed: ${message}`); } function logError(message) { - log.info("Consistency error: " + message); + log.info(`Consistency error: ${message}`); } function runPeriodicChecks() { diff --git a/src/services/data_dir.js b/src/services/data_dir.js index ea2f4b464..ab2bdd333 100644 --- a/src/services/data_dir.js +++ b/src/services/data_dir.js @@ -19,10 +19,10 @@ function getAppDataDir() { appDataDir = process.env.APPDATA; } else if (os.platform() === 'linux') { - appDataDir = os.homedir() + '/.local/share'; + appDataDir = `${os.homedir()}/.local/share`; } else if (os.platform() === 'darwin') { - appDataDir = os.homedir() + '/Library/Application Support'; + appDataDir = `${os.homedir()}/Library/Application Support`; } if (!fs.existsSync(appDataDir)) { @@ -60,11 +60,11 @@ function getTriliumDataDir() { } const TRILIUM_DATA_DIR = getTriliumDataDir(); -const DOCUMENT_PATH = TRILIUM_DATA_DIR + path.sep + "document.db"; -const BACKUP_DIR = TRILIUM_DATA_DIR + path.sep + "backup"; -const LOG_DIR = TRILIUM_DATA_DIR + path.sep + "log"; -const ANONYMIZED_DB_DIR = TRILIUM_DATA_DIR + path.sep + "anonymized-db"; -const CONFIG_INI_PATH = TRILIUM_DATA_DIR + '/config.ini'; +const DOCUMENT_PATH = `${TRILIUM_DATA_DIR + path.sep}document.db`; +const BACKUP_DIR = `${TRILIUM_DATA_DIR + path.sep}backup`; +const LOG_DIR = `${TRILIUM_DATA_DIR + path.sep}log`; +const ANONYMIZED_DB_DIR = `${TRILIUM_DATA_DIR + path.sep}anonymized-db`; +const CONFIG_INI_PATH = `${TRILIUM_DATA_DIR}/config.ini`; module.exports = { TRILIUM_DATA_DIR, diff --git a/src/services/data_encryption.js b/src/services/data_encryption.js index c372036de..3218bb285 100644 --- a/src/services/data_encryption.js +++ b/src/services/data_encryption.js @@ -108,7 +108,7 @@ function decryptString(dataKey, cipherText) { const str = buffer.toString('utf-8'); if (str === 'false') { - log.error("Could not decrypt string. Buffer: " + buffer); + log.error(`Could not decrypt string. Buffer: ${buffer}`); throw new Error("Could not decrypt string."); } diff --git a/src/services/date_notes.js b/src/services/date_notes.js index 3aed9de51..1f6484096 100644 --- a/src/services/date_notes.js +++ b/src/services/date_notes.js @@ -201,7 +201,7 @@ function getStartOfTheWeek(date, startOfTheWeek) { diff = date.getDate() - day; } else { - throw new Error("Unrecognized start of the week " + startOfTheWeek); + throw new Error(`Unrecognized start of the week ${startOfTheWeek}`); } return new Date(date.setDate(diff)); diff --git a/src/services/date_utils.js b/src/services/date_utils.js index b01804ad5..14a7fa702 100644 --- a/src/services/date_utils.js +++ b/src/services/date_utils.js @@ -22,7 +22,7 @@ function localNowDate() { else { const date = new Date(); - return date.getFullYear() + "-" + pad(date.getMonth() + 1) + "-" + pad(date.getDate()); + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`; } } @@ -47,21 +47,21 @@ function parseDateTime(str) { return new Date(Date.parse(str)); } catch (e) { - throw new Error("Can't parse date from " + str + ": " + e.stack); + throw new Error(`Can't parse date from ${str}: ${e.stack}`); } } function parseDate(str) { const datePart = str.substr(0, 10); - return parseDateTime(datePart + "T12:00:00.000Z"); + return parseDateTime(`${datePart}T12:00:00.000Z`); } function parseLocalDate(str) { const datePart = str.substr(0, 10); // not specifying the timezone and specifying the time means Date.parse() will use the local timezone - return parseDateTime(datePart + " 12:00:00.000"); + return parseDateTime(`${datePart} 12:00:00.000`); } function getDateTimeForFile() { diff --git a/src/services/events.js b/src/services/events.js index a9dd44496..f188ffe71 100644 --- a/src/services/events.js +++ b/src/services/events.js @@ -49,7 +49,7 @@ function emit(eventType, data) { listener(data); } catch (e) { - log.error("Listener threw error: " + e.stack); + log.error(`Listener threw error: ${e.stack}`); // we won't stop execution because of listener } } diff --git a/src/services/export/opml.js b/src/services/export/opml.js index 8c4265ab6..4fce57515 100644 --- a/src/services/export/opml.js +++ b/src/services/export/opml.js @@ -5,7 +5,7 @@ const becca = require("../../becca/becca"); function exportToOpml(taskContext, branch, version, res) { if (!['1.0', '2.0'].includes(version)) { - throw new Error("Unrecognized OPML version " + version); + throw new Error(`Unrecognized OPML version ${version}`); } const opmlVersion = parseInt(version); @@ -20,7 +20,7 @@ function exportToOpml(taskContext, branch, version, res) { return; } - const title = (branch.prefix ? (branch.prefix + ' - ') : '') + note.title; + const title = `${branch.prefix ? (`${branch.prefix} - `) : ''}${note.title}`; if (opmlVersion === 1) { const preparedTitle = escapeXmlAttribute(title); @@ -35,7 +35,7 @@ function exportToOpml(taskContext, branch, version, res) { res.write(`\n`); } else { - throw new Error("Unrecognized OPML version " + opmlVersion); + throw new Error(`Unrecognized OPML version ${opmlVersion}`); } taskContext.increaseProgressCount(); @@ -48,7 +48,7 @@ function exportToOpml(taskContext, branch, version, res) { } - const filename = (branch.prefix ? (branch.prefix + ' - ') : '') + note.title + ".opml"; + const filename = `${branch.prefix ? (`${branch.prefix} - `) : ''}${note.title}.opml`; res.setHeader('Content-Disposition', utils.getContentDisposition(filename)); res.setHeader('Content-Type', 'text/x-opml'); diff --git a/src/services/export/single.js b/src/services/export/single.js index 838631444..6158731cf 100644 --- a/src/services/export/single.js +++ b/src/services/export/single.js @@ -13,7 +13,7 @@ function exportSingleNote(taskContext, branch, format, res) { } if (format !== 'html' && format !== 'markdown') { - return [400, 'Unrecognized format ' + format]; + return [400, `Unrecognized format ${format}`]; } let payload, extension, mime; @@ -23,7 +23,7 @@ function exportSingleNote(taskContext, branch, format, res) { if (note.type === 'text') { if (format === 'html') { if (!content.toLowerCase().includes("'; + content = `${content}`; } payload = html.prettyPrint(content, {indent_size: 2}); @@ -47,10 +47,10 @@ function exportSingleNote(taskContext, branch, format, res) { mime = 'application/json'; } - const filename = note.title + "." + extension; + const filename = `${note.title}.${extension}`; res.setHeader('Content-Disposition', utils.getContentDisposition(filename)); - res.setHeader('Content-Type', mime + '; charset=UTF-8'); + res.setHeader('Content-Type', `${mime}; charset=UTF-8`); res.send(payload); diff --git a/src/services/export/zip.js b/src/services/export/zip.js index b1336e32a..281a3b2d2 100644 --- a/src/services/export/zip.js +++ b/src/services/export/zip.js @@ -37,11 +37,11 @@ function exportToZip(taskContext, branch, format, res) { do { index = existingFileNames[lcFileName]++; - newName = index + "_" + lcFileName; + newName = `${index}_${lcFileName}`; } while (newName in existingFileNames); - return index + "_" + fileName; + return `${index}_${fileName}`; } else { existingFileNames[lcFileName] = 1; @@ -84,8 +84,8 @@ function exportToZip(taskContext, branch, format, res) { } // if the note is already named with extension (e.g. "jquery"), then it's silly to append exact same extension again - if (newExtension && existingExtension !== "." + newExtension.toLowerCase()) { - fileName += "." + newExtension; + if (newExtension && existingExtension !== `.${newExtension.toLowerCase()}`) { + fileName += `.${newExtension}`; } return getUniqueFilename(existingFileNames, fileName); @@ -99,7 +99,7 @@ function exportToZip(taskContext, branch, format, res) { } const title = note.getTitleOrProtected(); - const completeTitle = branch.prefix ? (branch.prefix + ' - ' + title) : title; + const completeTitle = branch.prefix ? (`${branch.prefix} - ${title}`) : title; let baseFileName = sanitize(completeTitle); if (baseFileName.length > 200) { // actual limit is 256 bytes(!) but let's be conservative @@ -109,7 +109,7 @@ function exportToZip(taskContext, branch, format, res) { const notePath = parentMeta.notePath.concat([note.noteId]); if (note.noteId in noteIdToMeta) { - const fileName = getUniqueFilename(existingFileNames, baseFileName + ".clone." + (format === 'html' ? 'html' : 'md')); + const fileName = getUniqueFilename(existingFileNames, `${baseFileName}.clone.${format === 'html' ? 'html' : 'md'}`); return { isClone: true, @@ -202,7 +202,7 @@ function exportToZip(taskContext, branch, format, res) { for (let i = 0; i < targetPath.length - 1; i++) { const meta = noteIdToMeta[targetPath[i]]; - url += encodeURIComponent(meta.dirFileName) + '/'; + url += `${encodeURIComponent(meta.dirFileName)}/`; } const meta = noteIdToMeta[targetPath[targetPath.length - 1]]; @@ -238,7 +238,7 @@ function exportToZip(taskContext, branch, format, res) { if (noteMeta.format === 'html') { if (!content.substr(0, 100).toLowerCase().includes(" element will make sure external links are openable - https://github.com/zadam/trilium/issues/1289#issuecomment-704066809 content = ` @@ -263,7 +263,8 @@ ${content} let markdownContent = mdService.toMarkdown(content); if (markdownContent.trim().length > 0 && !markdownContent.startsWith("# ")) { - markdownContent = '# ' + title + "\r\n" + markdownContent; + markdownContent = `# ${title}\r +${markdownContent}`; } return markdownContent; @@ -307,10 +308,10 @@ ${content} const directoryPath = filePathPrefix + noteMeta.dirFileName; // create directory - archive.append('', { name: directoryPath + '/', date: dateUtils.parseDateTime(note.utcDateModified) }); + archive.append('', { name: `${directoryPath}/`, date: dateUtils.parseDateTime(note.utcDateModified) }); for (const childMeta of noteMeta.children) { - saveNote(childMeta, directoryPath + '/'); + saveNote(childMeta, `${directoryPath}/`); } } } @@ -319,7 +320,7 @@ ${content} function saveNavigationInner(meta) { let html = '
  • '; - const escapedTitle = utils.escapeHtml((meta.prefix ? `${meta.prefix} - ` : '') + meta.title); + const escapedTitle = utils.escapeHtml(`${meta.prefix ? `${meta.prefix} - ` : ''}${meta.title}`); if (meta.dataFileName) { const targetUrl = getTargetUrl(meta.noteId, rootMeta); @@ -340,7 +341,7 @@ ${content} html += '' } - return html + '
  • '; + return `${html}`; } const fullHtml = ` @@ -390,7 +391,7 @@ ${content} } function saveCss(rootMeta, cssMeta) { - const cssContent = fs.readFileSync(RESOURCE_DIR + '/libraries/ckeditor/ckeditor-content.css'); + const cssContent = fs.readFileSync(`${RESOURCE_DIR}/libraries/ckeditor/ckeditor-content.css`); archive.append(cssContent, { name: cssMeta.dataFileName }); } @@ -452,7 +453,7 @@ ${content} } const note = branch.getNote(); - const zipFileName = (branch.prefix ? `${branch.prefix} - ` : "") + note.getTitleOrProtected() + ".zip"; + const zipFileName = `${branch.prefix ? `${branch.prefix} - ` : ""}${note.getTitleOrProtected()}.zip`; res.setHeader('Content-Disposition', utils.getContentDisposition(zipFileName)); res.setHeader('Content-Type', 'application/zip'); diff --git a/src/services/handlers.js b/src/services/handlers.js index 57cf0ba3c..80d4ce39a 100644 --- a/src/services/handlers.js +++ b/src/services/handlers.js @@ -123,7 +123,7 @@ eventService.subscribe(eventService.CHILD_NOTE_CREATED, ({ parentNote, childNote function processInverseRelations(entityName, entity, handler) { if (entityName === 'attributes' && entity.type === 'relation') { const note = entity.getNote(); - const relDefinitions = note.getLabels('relation:' + entity.name); + const relDefinitions = note.getLabels(`relation:${entity.name}`); for (const relDefinition of relDefinitions) { const definition = relDefinition.getDefinition(); diff --git a/src/services/hidden_subtree.js b/src/services/hidden_subtree.js index aef470556..02f75448b 100644 --- a/src/services/hidden_subtree.js +++ b/src/services/hidden_subtree.js @@ -228,16 +228,20 @@ function checkHiddenSubtree() { function checkHiddenSubtreeRecursively(parentNoteId, item) { if (!item.id || !item.type || !item.title) { - throw new Error(`Item does not contain mandatory properties: ` + JSON.stringify(item)); + throw new Error(`Item does not contain mandatory properties: ${JSON.stringify(item)}`); } + // if (item.id.charAt(0) !== '_') { + // throw new Error("ID has to start with underscore"); + // } + let note = becca.notes[item.id]; let branch = becca.branches[item.id]; const attrs = [...(item.attributes || [])]; if (item.icon) { - attrs.push({ type: 'label', name: 'iconClass', value: 'bx ' + item.icon }); + attrs.push({ type: 'label', name: 'iconClass', value: `bx ${item.icon}` }); } if (!note) { diff --git a/src/services/image.js b/src/services/image.js index d2d405096..8a2ef4ba0 100644 --- a/src/services/image.js +++ b/src/services/image.js @@ -61,7 +61,7 @@ function getImageType(buffer) { function getImageMimeFromExtension(ext) { ext = ext.toLowerCase(); - return 'image/' + (ext === 'svg' ? 'svg+xml' : ext); + return `image/${ext === 'svg' ? 'svg+xml' : ext}`; } function updateImage(noteId, uploadBuffer, originalName) { @@ -114,7 +114,7 @@ function saveImage(parentNoteId, uploadBuffer, originalName, shrinkImageSwitch, note.mime = getImageMimeFromExtension(imageFormat.ext); if (!originalName.includes(".")) { - originalName += "." + imageFormat.ext; + originalName += `.${imageFormat.ext}`; note.setLabel('originalFileName', originalName); note.title = sanitizeFilename(originalName); @@ -146,7 +146,8 @@ async function shrinkImage(buffer, originalName) { finalImageBuffer = await resize(buffer, jpegQuality); } catch (e) { - log.error("Failed to resize image '" + originalName + "'\nStack: " + e.stack); + log.error(`Failed to resize image '${originalName}' +Stack: ${e.stack}`); finalImageBuffer = buffer; } diff --git a/src/services/import/enex.js b/src/services/import/enex.js index 710283b09..df1456709 100644 --- a/src/services/import/enex.js +++ b/src/services/import/enex.js @@ -13,8 +13,7 @@ const attributeService = require("../attributes"); // date format is e.g. 20181121T193703Z function parseDate(text) { // insert - and : to make it ISO format - text = text.substr(0, 4) + "-" + text.substr(4, 2) + "-" + text.substr(6, 2) - + " " + text.substr(9, 2) + ":" + text.substr(11, 2) + ":" + text.substr(13, 2) + ".000Z"; + text = `${text.substr(0, 4)}-${text.substr(4, 2)}-${text.substr(6, 2)} ${text.substr(9, 2)}:${text.substr(11, 2)}:${text.substr(13, 2)}.000Z`; return text; } @@ -101,7 +100,7 @@ function importEnex(taskContext, file, parentNote) { saxStream.on("error", e => { // unhandled errors will throw, since this is a proper node // event emitter. - log.error("error when parsing ENEX file: " + e); + log.error(`error when parsing ENEX file: ${e}`); // clear the error this._parser.error = null; this._parser.resume(); @@ -311,7 +310,7 @@ function importEnex(taskContext, file, parentNote) { content += imageLink; } } catch (e) { - log.error("error when saving image from ENEX file: " + e); + log.error(`error when saving image from ENEX file: ${e}`); createFileNote(); } } else { diff --git a/src/services/import/opml.js b/src/services/import/opml.js index 90a8b544d..bdc464825 100644 --- a/src/services/import/opml.js +++ b/src/services/import/opml.js @@ -25,7 +25,7 @@ async function importOpml(taskContext, fileBuffer, parentNote) { }); if (!['1.0', '1.1', '2.0'].includes(xml.opml.$.version)) { - return [400, 'Unsupported OPML version ' + xml.opml.$.version + ', 1.0, 1.1 or 2.0 expected instead.']; + return [400, `Unsupported OPML version ${xml.opml.$.version}, 1.0, 1.1 or 2.0 expected instead.`]; } const opmlVersion = parseInt(xml.opml.$.version); @@ -48,7 +48,7 @@ async function importOpml(taskContext, fileBuffer, parentNote) { content = outline.$._note; // _note is already HTML } else { - throw new Error("Unrecognized OPML version " + opmlVersion); + throw new Error(`Unrecognized OPML version ${opmlVersion}`); } content = htmlSanitizer.sanitize(content || ""); @@ -88,7 +88,7 @@ function toHtml(text) { return ''; } - return '

    ' + text.replace(/(?:\r\n|\r|\n)/g, '

    ') + '

    '; + return `

    ${text.replace(/(?:\r\n|\r|\n)/g, '

    ')}

    `; } module.exports = { diff --git a/src/services/import/single.js b/src/services/import/single.js index b693d82fb..d0c351740 100644 --- a/src/services/import/single.js +++ b/src/services/import/single.js @@ -111,7 +111,7 @@ function convertTextToHtml(text) { text = text.replace(/
    \s*
    /g, "

    "); // 4: Wrap in Paragraph Tags - text = "

    " + text + "

    "; + text = `

    ${text}

    `; return text; } diff --git a/src/services/import/zip.js b/src/services/import/zip.js index a2f859a3f..41bfbffdb 100644 --- a/src/services/import/zip.js +++ b/src/services/import/zip.js @@ -135,15 +135,15 @@ async function importZip(taskContext, fileBuffer, importRootNote) { if (attr.type === 'label-definition') { attr.type = 'label'; - attr.name = 'label:' + attr.name; + attr.name = `label:${attr.name}`; } else if (attr.type === 'relation-definition') { attr.type = 'label'; - attr.name = 'relation:' + attr.name; + attr.name = `relation:${attr.name}`; } if (!attributeService.isAttributeType(attr.type)) { - log.error("Unrecognized attribute type " + attr.type); + log.error(`Unrecognized attribute type ${attr.type}`); continue; } @@ -157,7 +157,7 @@ async function importZip(taskContext, fileBuffer, importRootNote) { } if (taskContext.data.safeImport && attributeService.isAttributeDangerous(attr.type, attr.name)) { - attr.name = 'disabled:' + attr.name; + attr.name = `disabled:${attr.name}`; } if (taskContext.data.safeImport) { @@ -223,7 +223,7 @@ async function importZip(taskContext, fileBuffer, importRootNote) { absUrl = ''; } - absUrl += (absUrl.length > 0 ? '/' : '') + url; + absUrl += `${absUrl.length > 0 ? '/' : ''}${url}`; const {noteMeta} = getMeta(absUrl); const targetNoteId = getNoteId(noteMeta, absUrl); @@ -526,7 +526,7 @@ async function importZip(taskContext, fileBuffer, importRootNote) { new Attribute(attr).save(); } else { - log.info("Relation not imported since target note doesn't exist: " + JSON.stringify(attr)); + log.info(`Relation not imported since target note doesn't exist: ${JSON.stringify(attr)}`); } } diff --git a/src/services/log.js b/src/services/log.js index 0fcd98122..a141eae14 100644 --- a/src/services/log.js +++ b/src/services/log.js @@ -30,7 +30,7 @@ function getTodaysMidnight() { function initLogFile() { todaysMidnight = getTodaysMidnight(); - const path = dataDir.LOG_DIR + '/trilium-' + formatDate() + '.log'; + const path = `${dataDir.LOG_DIR}/trilium-${formatDate()}.log`; if (logFile) { logFile.end(); @@ -60,7 +60,7 @@ function log(str) { millisSinceMidnight = checkDate(millisSinceMidnight); - logFile.write(formatTime(millisSinceMidnight) + ' ' + str + NEW_LINE); + logFile.write(`${formatTime(millisSinceMidnight)} ${str}${NEW_LINE}`); console.log(str); } @@ -70,7 +70,7 @@ function info(message) { } function error(message) { - log("ERROR: " + message); + log(`ERROR: ${message}`); } const requestBlacklist = [ "/libraries", "/app", "/images", "/stylesheets", "/api/recent-notes" ]; @@ -93,15 +93,15 @@ function request(req, res, timeMs, responseLength = "?") { function pad(num) { num = Math.floor(num); - return num < 10 ? ("0" + num) : num.toString(); + return num < 10 ? (`0${num}`) : num.toString(); } function padMilli(num) { if (num < 10) { - return "00" + num; + return `00${num}`; } else if (num < 100) { - return "0" + num; + return `0${num}`; } else { return num.toString(); @@ -109,16 +109,11 @@ function padMilli(num) { } function formatTime(millisSinceMidnight) { - return pad(millisSinceMidnight / HOUR) - + ":" + pad((millisSinceMidnight % HOUR) / MINUTE) - + ":" + pad((millisSinceMidnight % MINUTE) / SECOND) - + "." + padMilli(millisSinceMidnight % SECOND); + return `${pad(millisSinceMidnight / HOUR)}:${pad((millisSinceMidnight % HOUR) / MINUTE)}:${pad((millisSinceMidnight % MINUTE) / SECOND)}.${padMilli(millisSinceMidnight % SECOND)}`; } function formatDate() { - return pad(todaysMidnight.getFullYear()) - + "-" + pad(todaysMidnight.getMonth() + 1) - + "-" + pad(todaysMidnight.getDate()); + return `${pad(todaysMidnight.getFullYear())}-${pad(todaysMidnight.getMonth() + 1)}-${pad(todaysMidnight.getDate())}`; } module.exports = { diff --git a/src/services/migration.js b/src/services/migration.js index 423c87cf1..adcd4981c 100644 --- a/src/services/migration.js +++ b/src/services/migration.js @@ -9,18 +9,18 @@ const appInfo = require('./app_info'); function executeMigration(mig) { sql.transactional(() => { if (mig.type === 'sql') { - const migrationSql = fs.readFileSync(resourceDir.MIGRATIONS_DIR + "/" + mig.file).toString('utf8'); + const migrationSql = fs.readFileSync(`${resourceDir.MIGRATIONS_DIR}/${mig.file}`).toString('utf8'); - console.log("Migration with SQL script: " + migrationSql); + console.log(`Migration with SQL script: ${migrationSql}`); sql.executeScript(migrationSql); } else if (mig.type === 'js') { console.log("Migration with JS module"); - const migrationModule = require(resourceDir.MIGRATIONS_DIR + "/" + mig.file); + const migrationModule = require(`${resourceDir.MIGRATIONS_DIR}/${mig.file}`); migrationModule(); } else { - throw new Error("Unknown migration type " + mig.type); + throw new Error(`Unknown migration type ${mig.type}`); } }); } @@ -66,16 +66,16 @@ async function migrate() { for (const mig of migrations) { try { - log.info("Attempting migration to version " + mig.dbVersion); + log.info(`Attempting migration to version ${mig.dbVersion}`); executeMigration(mig); sql.execute(`UPDATE options SET value = ? WHERE name = ?`, [mig.dbVersion.toString(), "dbVersion"]); - log.info("Migration to version " + mig.dbVersion + " has been successful."); + log.info(`Migration to version ${mig.dbVersion} has been successful.`); } catch (e) { - log.error("error during migration to version " + mig.dbVersion + ": " + e.stack); + log.error(`error during migration to version ${mig.dbVersion}: ${e.stack}`); log.error("migration failed, crashing hard"); // this is not very user friendly :-/ utils.crash(); @@ -93,7 +93,7 @@ function isDbUpToDate() { const upToDate = dbVersion >= appInfo.dbVersion; if (!upToDate) { - log.info("App db version is " + appInfo.dbVersion + ", while db version is " + dbVersion + ". Migration needed."); + log.info(`App db version is ${appInfo.dbVersion}, while db version is ${dbVersion}. Migration needed.`); } return upToDate; diff --git a/src/services/note_revisions.js b/src/services/note_revisions.js index dcaf1cd79..832150b50 100644 --- a/src/services/note_revisions.js +++ b/src/services/note_revisions.js @@ -27,7 +27,7 @@ function protectNoteRevisions(note) { revision.save(); } catch (e) { - log.error("Could not un/protect note revision ID = " + revision.noteRevisionId); + log.error(`Could not un/protect note revision ID = ${revision.noteRevisionId}`); throw e; } diff --git a/src/services/notes.js b/src/services/notes.js index 4d501e244..09e1165f9 100644 --- a/src/services/notes.js +++ b/src/services/notes.js @@ -79,7 +79,7 @@ function getNewNoteTitle(parentNote) { // - now // - parentNote - title = eval('`' + titleTemplate + '`'); + title = eval(`\`${titleTemplate}\``); } catch (e) { log.error(`Title template of note '${parentNote.noteId}' failed with: ${e.message}`); } @@ -288,7 +288,7 @@ function protectNote(note, protect) { noteRevisionService.protectNoteRevisions(note); } catch (e) { - log.error("Could not un/protect note ID = " + note.noteId); + log.error(`Could not un/protect note ID = ${note.noteId}`); throw e; } @@ -402,9 +402,7 @@ function downloadImages(noteId, content) { const sanitizedTitle = note.title.replace(/[^a-z0-9-.]/gi, ""); - content = content.substr(0, imageMatch.index) - + ` diff --git a/src/services/options_init.js b/src/services/options_init.js index c7d23e14b..fd66718f8 100644 --- a/src/services/options_init.js +++ b/src/services/options_init.js @@ -118,7 +118,7 @@ function getKeyboardDefaultOptions() { return keyboardActions.DEFAULT_KEYBOARD_ACTIONS .filter(ka => !!ka.actionName) .map(ka => ({ - name: "keyboardShortcuts" + ka.actionName.charAt(0).toUpperCase() + ka.actionName.slice(1), + name: `keyboardShortcuts${ka.actionName.charAt(0).toUpperCase()}${ka.actionName.slice(1)}`, value: JSON.stringify(ka.defaultShortcuts), isSynced: false })); diff --git a/src/services/port.js b/src/services/port.js index b730755c0..559385644 100644 --- a/src/services/port.js +++ b/src/services/port.js @@ -21,7 +21,7 @@ if (process.env.TRILIUM_PORT) { } else if (utils.isElectron()) { port = env.isDev() ? 37740 : 37840; } else { - port = parseAndValidate(config['Network']['port'] || '3000', "Network.port in " + dataDir.CONFIG_INI_PATH); + port = parseAndValidate(config['Network']['port'] || '3000', `Network.port in ${dataDir.CONFIG_INI_PATH}`); } module.exports = port; diff --git a/src/services/request.js b/src/services/request.js index 30e7d9e09..28d1edbf0 100644 --- a/src/services/request.js +++ b/src/services/request.js @@ -38,7 +38,7 @@ function exec(opts) { }; if (opts.auth) { - headers['trilium-cred'] = Buffer.from("dummy:" + opts.auth.password).toString('base64'); + headers['trilium-cred'] = Buffer.from(`dummy:${opts.auth.password}`).toString('base64'); } const request = client.request({ @@ -59,7 +59,7 @@ function exec(opts) { request.on('response', response => { if (![200, 201, 204].includes(response.statusCode)) { - reject(generateError(opts, response.statusCode + ' ' + response.statusMessage)); + reject(generateError(opts, `${response.statusCode} ${response.statusMessage}`)); } if (opts.cookieJar && response.headers['set-cookie']) { @@ -77,7 +77,7 @@ function exec(opts) { resolve(jsonObj); } catch (e) { - log.error("Failed to deserialize sync response: " + responseStr); + log.error(`Failed to deserialize sync response: ${responseStr}`); reject(generateError(opts, e.message)); } @@ -134,7 +134,7 @@ function getImage(imageUrl) { request.on('response', response => { if (![200, 201, 204].includes(response.statusCode)) { - reject(generateError(opts, response.statusCode + ' ' + response.statusMessage)); + reject(generateError(opts, `${response.statusCode} ${response.statusMessage}`)); } const chunks = [] @@ -160,7 +160,7 @@ function getProxyAgent(opts) { if (protocol === 'http:' || protocol === 'https:') { const protoNoColon = protocol.substr(0, protocol.length - 1); - const AgentClass = require(protoNoColon + '-proxy-agent'); + const AgentClass = require(`${protoNoColon}-proxy-agent`); return new AgentClass(opts.proxy); } diff --git a/src/services/resource_dir.js b/src/services/resource_dir.js index 28009aba7..ba05b70e7 100644 --- a/src/services/resource_dir.js +++ b/src/services/resource_dir.js @@ -9,14 +9,14 @@ const ELECTRON_APP_ROOT_DIR = path.resolve(RESOURCE_DIR, "../.."); const DB_INIT_DIR = path.resolve(RESOURCE_DIR, "db"); if (!fs.existsSync(DB_INIT_DIR)) { - log.error("Could not find DB initialization directory: " + DB_INIT_DIR); + log.error(`Could not find DB initialization directory: ${DB_INIT_DIR}`); process.exit(1); } const MIGRATIONS_DIR = path.resolve(DB_INIT_DIR, "migrations"); if (!fs.existsSync(MIGRATIONS_DIR)) { - log.error("Could not find migration directory: " + MIGRATIONS_DIR); + log.error(`Could not find migration directory: ${MIGRATIONS_DIR}`); process.exit(1); } diff --git a/src/services/script.js b/src/services/script.js index a9b4ea241..812854bbe 100644 --- a/src/services/script.js +++ b/src/services/script.js @@ -36,7 +36,9 @@ function executeBundle(bundle, apiParams = {}) { cls.set('bundleNoteId', bundle.note.noteId); // last \r\n is necessary if script contains line comment on its last line - const script = "function() {\r\n" + bundle.script + "\r\n}"; + const script = `function() {\r +${bundle.script}\r +}`; const ctx = new ScriptContext(bundle.allNotes, apiParams); try { @@ -166,15 +168,13 @@ function getScriptBundle(note, root = true, scriptEnv = null, includedNoteIds = if (note.isJavaScript()) { bundle.script += ` apiContext.modules['${note.noteId}'] = { exports: {} }; -${root ? 'return ' : ''}${isFrontend ? 'await' : ''} ((${isFrontend ? 'async' : ''} function(exports, module, require, api` + (modules.length > 0 ? ', ' : '') + - modules.map(child => sanitizeVariableName(child.title)).join(', ') + `) { +${root ? 'return ' : ''}${isFrontend ? 'await' : ''} ((${isFrontend ? 'async' : ''} function(exports, module, require, api${modules.length > 0 ? ', ' : ''}${modules.map(child => sanitizeVariableName(child.title)).join(', ')}) { try { ${backendOverrideContent || note.getContent()}; } catch (e) { throw new Error("Load of script note \\"${note.title}\\" (${note.noteId}) failed with: " + e.message); } for (const exportKey in exports) module.exports[exportKey] = exports[exportKey]; return module.exports; -}).call({}, {}, apiContext.modules['${note.noteId}'], apiContext.require(${JSON.stringify(moduleNoteIds)}), apiContext.apis['${note.noteId}']` + (modules.length > 0 ? ', ' : '') + - modules.map(mod => `apiContext.modules['${mod.noteId}'].exports`).join(', ') + `)); +}).call({}, {}, apiContext.modules['${note.noteId}'], apiContext.require(${JSON.stringify(moduleNoteIds)}), apiContext.apis['${note.noteId}']${modules.length > 0 ? ', ' : ''}${modules.map(mod => `apiContext.modules['${mod.noteId}'].exports`).join(', ')})); `; } else if (note.isHtml()) { diff --git a/src/services/search/expressions/note_content_fulltext.js b/src/services/search/expressions/note_content_fulltext.js index ae8946aab..d2837340b 100644 --- a/src/services/search/expressions/note_content_fulltext.js +++ b/src/services/search/expressions/note_content_fulltext.js @@ -32,7 +32,7 @@ class NoteContentFulltextExp extends Expression { execute(inputNoteSet, executionContext, searchContext) { if (!ALLOWED_OPERATORS.includes(this.operator)) { - searchContext.addError(`Note content can be searched only with operators: ` + ALLOWED_OPERATORS.join(", ") + `, operator ${this.operator} given.`); + searchContext.addError(`Note content can be searched only with operators: ${ALLOWED_OPERATORS.join(", ")}, operator ${this.operator} given.`); return inputNoteSet; } diff --git a/src/services/search/services/parse.js b/src/services/search/services/parse.js index eb3ba5a2d..0b121f959 100644 --- a/src/services/search/services/parse.js +++ b/src/services/search/services/parse.js @@ -76,9 +76,7 @@ function getExpression(tokens, searchContext, level = 0) { startIndex = Math.max(0, startIndex - 20); endIndex = Math.min(searchContext.originalQuery.length, endIndex + 20); - return '"' + (startIndex !== 0 ? "..." : "") - + searchContext.originalQuery.substr(startIndex, endIndex - startIndex) - + (endIndex !== searchContext.originalQuery.length ? "..." : "") + '"'; + return `"${startIndex !== 0 ? "..." : ""}${searchContext.originalQuery.substr(startIndex, endIndex - startIndex)}${endIndex !== searchContext.originalQuery.length ? "..." : ""}"`; } function resolveConstantOperand() { @@ -128,7 +126,7 @@ function getExpression(tokens, searchContext, level = 0) { format = "YYYY"; } else { - throw new Error("Unrecognized keyword: " + operand.token); + throw new Error(`Unrecognized keyword: ${operand.token}`); } return date.format(format); diff --git a/src/services/search/services/search.js b/src/services/search/services/search.js index f8ddd9bd6..c5038466b 100644 --- a/src/services/search/services/search.js +++ b/src/services/search/services/search.js @@ -224,7 +224,7 @@ function parseQueryToExpression(query, searchContext) { expression }; - log.info("Search debug: " + JSON.stringify(searchContext.debugInfo, null, 4)); + log.info(`Search debug: ${JSON.stringify(searchContext.debugInfo, null, 4)}`); } return expression; @@ -357,15 +357,15 @@ function highlightSearchResults(searchResults, highlightedTokens) { function formatAttribute(attr) { if (attr.type === 'relation') { - return '~' + utils.escapeHtml(attr.name) + "=…"; + return `~${utils.escapeHtml(attr.name)}=…`; } else if (attr.type === 'label') { - let label = '#' + utils.escapeHtml(attr.name); + let label = `#${utils.escapeHtml(attr.name)}`; if (attr.value) { - const val = /[^\w_-]/.test(attr.value) ? '"' + attr.value + '"' : attr.value; + const val = /[^\w_-]/.test(attr.value) ? `"${attr.value}"` : attr.value; - label += '=' + utils.escapeHtml(val); + label += `=${utils.escapeHtml(val)}`; } return label; diff --git a/src/services/session_secret.js b/src/services/session_secret.js index a589c70c9..f7ff8ef03 100644 --- a/src/services/session_secret.js +++ b/src/services/session_secret.js @@ -5,7 +5,7 @@ const crypto = require('crypto'); const dataDir = require('./data_dir'); const log = require('./log'); -const sessionSecretPath = dataDir.TRILIUM_DATA_DIR + "/session_secret.txt"; +const sessionSecretPath = `${dataDir.TRILIUM_DATA_DIR}/session_secret.txt`; let sessionSecret; diff --git a/src/services/setup.js b/src/services/setup.js index eb176bebe..6119c1bc3 100644 --- a/src/services/setup.js +++ b/src/services/setup.js @@ -69,7 +69,7 @@ async function setupSyncFromSyncServer(syncServerHost, syncProxy, password) { // response is expected to contain documentId and documentSecret options const resp = await request.exec({ method: 'get', - url: syncServerHost + '/api/setup/sync-seed', + url: `${syncServerHost}/api/setup/sync-seed`, auth: { password }, proxy: syncProxy, timeout: 30000 // seed request should not take long @@ -93,7 +93,7 @@ async function setupSyncFromSyncServer(syncServerHost, syncProxy, password) { return { result: 'success' }; } catch (e) { - log.error("Sync failed: " + e.message); + log.error(`Sync failed: ${e.message}`); return { result: 'failure', diff --git a/src/services/special_notes.js b/src/services/special_notes.js index f359903d6..e7880d816 100644 --- a/src/services/special_notes.js +++ b/src/services/special_notes.js @@ -71,7 +71,7 @@ function saveSqlConsole(sqlConsoleNoteId) { function createSearchNote(searchString, ancestorNoteId) { const {note} = noteService.createNewNote({ parentNoteId: getMonthlyParentNoteId('search'), - title: 'Search: ' + searchString, + title: `Search: ${searchString}`, content: "", type: 'search', mime: 'application/json' @@ -232,7 +232,7 @@ function resetLauncher(noteId) { * could mess up the layout - e.g. the sync status being below. */ function createOrUpdateScriptLauncherFromApi(opts) { - const launcherId = opts.id || ("tb" + opts.title.replace(/[^[a-z0-9]/gi, "")); + const launcherId = opts.id || (`tb${opts.title.replace(/[^[a-z0-9]/gi, "")}`); if (!opts.title) { throw new Error("Title is mandatory property to create or update a launcher."); @@ -244,7 +244,7 @@ function createOrUpdateScriptLauncherFromApi(opts) { || createScriptLauncher('lbVisibleLaunchers', launcherId); launcherNote.title = opts.title; - launcherNote.setContent("(" + opts.action + ")()"); + launcherNote.setContent(`(${opts.action})()`); launcherNote.setLabel('scriptInLauncherContent'); // there's no target note, the script is in the launcher's content launcherNote.mime = 'application/javascript;env=frontend'; launcherNote.save(); @@ -256,7 +256,7 @@ function createOrUpdateScriptLauncherFromApi(opts) { } if (opts.icon) { - launcherNote.setLabel('iconClass', "bx bx-" + opts.icon); + launcherNote.setLabel('iconClass', `bx bx-${opts.icon}`); } else { launcherNote.removeLabel('iconClass'); } diff --git a/src/services/sql.js b/src/services/sql.js index 06159abda..40043d5ef 100644 --- a/src/services/sql.js +++ b/src/services/sql.js @@ -28,14 +28,20 @@ const LOG_ALL_QUERIES = false; function insert(tableName, rec, replace = false) { const keys = Object.keys(rec); if (keys.length === 0) { - log.error("Can't insert empty object into table " + tableName); + log.error(`Can't insert empty object into table ${tableName}`); return; } const columns = keys.join(", "); const questionMarks = keys.map(p => "?").join(", "); - const query = "INSERT " + (replace ? "OR REPLACE" : "") + " INTO " + tableName + "(" + columns + ") VALUES (" + questionMarks + ")"; + const query = `INSERT + ${replace ? "OR REPLACE" : ""} INTO + ${tableName} + ( + ${columns} + ) + VALUES (${questionMarks})`; const res = execute(query, Object.values(rec)); @@ -49,13 +55,13 @@ function replace(tableName, rec) { function upsert(tableName, primaryKey, rec) { const keys = Object.keys(rec); if (keys.length === 0) { - log.error("Can't upsert empty object into table " + tableName); + log.error(`Can't upsert empty object into table ${tableName}`); return; } const columns = keys.join(", "); - const questionMarks = keys.map(colName => "@" + colName).join(", "); + const questionMarks = keys.map(colName => `@${colName}`).join(", "); const updateMarks = keys.map(colName => `${colName} = @${colName}`).join(", "); @@ -272,7 +278,7 @@ function fillParamList(paramIds, truncate = true) { } // doing it manually to avoid this showing up on the sloq query list - const s = stmt(`INSERT INTO param_list VALUES ` + paramIds.map(paramId => `(?)`).join(','), paramIds); + const s = stmt(`INSERT INTO param_list VALUES ${paramIds.map(paramId => `(?)`).join(',')}`, paramIds); s.run(paramIds); } diff --git a/src/services/sql_init.js b/src/services/sql_init.js index 182391ac9..98c78317d 100644 --- a/src/services/sql_init.js +++ b/src/services/sql_init.js @@ -50,8 +50,8 @@ async function createInitialDatabase() { throw new Error("DB is already initialized"); } - const schema = fs.readFileSync(resourceDir.DB_INIT_DIR + '/schema.sql', 'UTF-8'); - const demoFile = fs.readFileSync(resourceDir.DB_INIT_DIR + '/demo.zip'); + const schema = fs.readFileSync(`${resourceDir.DB_INIT_DIR}/schema.sql`, 'UTF-8'); + const demoFile = fs.readFileSync(`${resourceDir.DB_INIT_DIR}/demo.zip`); let rootNote; @@ -127,7 +127,7 @@ function createDatabaseForSync(options, syncServerHost = '', syncProxy = '') { throw new Error("DB is already initialized"); } - const schema = fs.readFileSync(resourceDir.DB_INIT_DIR + '/schema.sql', 'UTF-8'); + const schema = fs.readFileSync(`${resourceDir.DB_INIT_DIR}/schema.sql`, 'UTF-8'); sql.transactional(() => { sql.executeScript(schema); diff --git a/src/services/sync.js b/src/services/sync.js index b616a886f..ddb0dedf4 100644 --- a/src/services/sync.js +++ b/src/services/sync.js @@ -72,7 +72,8 @@ async function sync() { }; } else { - log.info("sync failed: " + e.message + "\nstack: " + e.stack); + log.info(`sync failed: ${e.message} +stack: ${e.stack}`); ws.syncFailed(); @@ -221,7 +222,7 @@ async function pushChanges(syncContext) { ws.syncPushInProgress(); - log.info(`Sync ${logMarkerId}: Pushing ${entityChangesRecords.length} sync changes in ` + (Date.now() - startDate.getTime()) + "ms"); + log.info(`Sync ${logMarkerId}: Pushing ${entityChangesRecords.length} sync changes in ${Date.now() - startDate.getTime()}ms`); lastSyncedPush = entityChangesRecords[entityChangesRecords.length - 1].entityChange.id; @@ -311,7 +312,7 @@ function getEntityChangeRow(entityName, entityId) { const primaryKey = entityConstructor.getEntityFromEntityName(entityName).primaryKeyName; if (!primaryKey) { - throw new Error("Unknown entity " + entityName); + throw new Error(`Unknown entity ${entityName}`); } const entity = sql.getRow(`SELECT * FROM ${entityName} WHERE ${primaryKey} = ?`, [entityId]); @@ -367,7 +368,7 @@ function setLastSyncedPull(entityChangeId) { const lastSyncedPullOption = becca.getOption('lastSyncedPull'); if (lastSyncedPullOption) { // might be null in initial sync when becca is not loaded - lastSyncedPullOption.value = entityChangeId + ''; + lastSyncedPullOption.value = `${entityChangeId}`; } // this way we avoid updating entity_changes which otherwise means that we've never pushed all entity_changes @@ -388,7 +389,7 @@ function setLastSyncedPush(entityChangeId) { const lastSyncedPushOption = becca.getOption('lastSyncedPush'); if (lastSyncedPushOption) { // might be null in initial sync when becca is not loaded - lastSyncedPushOption.value = entityChangeId + ''; + lastSyncedPushOption.value = `${entityChangeId}`; } // this way we avoid updating entity_changes which otherwise means that we've never pushed all entity_changes diff --git a/src/services/utils.js b/src/services/utils.js index af0e66f8e..8164f48e4 100644 --- a/src/services/utils.js +++ b/src/services/utils.js @@ -191,9 +191,9 @@ function formatDownloadTitle(filename, type, mime) { filename = sanitize(filename); if (type === 'text') { - return filename + '.html'; + return `${filename}.html`; } else if (['relationMap', 'canvas', 'search'].includes(type)) { - return filename + '.json'; + return `${filename}.json`; } else { if (!mime) { return filename; @@ -208,7 +208,7 @@ function formatDownloadTitle(filename, type, mime) { } for (const ext of extensions) { - if (filenameLc.endsWith('.' + ext)) { + if (filenameLc.endsWith(`.${ext}`)) { return filename; } } @@ -221,7 +221,7 @@ function formatDownloadTitle(filename, type, mime) { return filename; } - return filename + '.' + extensions[0]; + return `${filename}.${extensions[0]}`; } } diff --git a/src/services/window.js b/src/services/window.js index 6ccf16a5d..3990c7f70 100644 --- a/src/services/window.js +++ b/src/services/window.js @@ -77,7 +77,7 @@ async function createMainWindow(app) { mainWindowState.manage(mainWindow); mainWindow.setMenuBarVisibility(false); - mainWindow.loadURL('http://127.0.0.1:' + port); + mainWindow.loadURL(`http://127.0.0.1:${port}`); mainWindow.on('closed', () => mainWindow = null); configureWebContents(mainWindow.webContents, spellcheckEnabled); @@ -143,7 +143,7 @@ async function createSetupWindow() { }); setupWindow.setMenuBarVisibility(false); - setupWindow.loadURL('http://127.0.0.1:' + port); + setupWindow.loadURL(`http://127.0.0.1:${port}`); setupWindow.on('closed', () => setupWindow = null); } diff --git a/src/services/ws.js b/src/services/ws.js index 4a6d8ce90..3a7f9e062 100644 --- a/src/services/ws.js +++ b/src/services/ws.js @@ -39,10 +39,11 @@ function init(httpServer, sessionParser) { const message = JSON.parse(messageJson); if (message.type === 'log-error') { - log.info('JS Error: ' + message.error + '\r\nStack: ' + message.stack); + log.info(`JS Error: ${message.error}\r +Stack: ${message.stack}`); } else if (message.type === 'log-info') { - log.info('JS Info: ' + message.info); + log.info(`JS Info: ${message.info}`); } else if (message.type === 'ping') { await syncMutexService.doExclusively(() => sendPing(ws)); @@ -73,7 +74,7 @@ function sendMessageToAllClients(message) { if (webSocketServer) { if (message.type !== 'sync-failed' && message.type !== 'api-log-messages') { - log.info("Sending message to all clients: " + jsonStr); + log.info(`Sending message to all clients: ${jsonStr}`); } webSocketServer.clients.forEach(function each(client) { @@ -174,8 +175,7 @@ function sendPing(client, entityChangeIds = []) { fillInAdditionalProperties(entityChange); } catch (e) { - log.error("Could not fill additional properties for entity change " + JSON.stringify(entityChange) - + " because of error: " + e.message + ": " + e.stack); + log.error(`Could not fill additional properties for entity change ${JSON.stringify(entityChange)} because of error: ${e.message}: ${e.stack}`); } } diff --git a/src/share/canvas_share.js b/src/share/canvas_share.js index d781ba44c..a7759527a 100644 --- a/src/share/canvas_share.js +++ b/src/share/canvas_share.js @@ -5,7 +5,7 @@ * const {elements, appState, files} = window.triliumExcalidraw; */ -document.getElementById("excalidraw-app").style.height = appState.height+"px"; +document.getElementById("excalidraw-app").style.height = `${appState.height}px`; const App = () => { const excalidrawRef = React.useRef(null); diff --git a/src/share/content_renderer.js b/src/share/content_renderer.js index bd2a5734e..9b9aef442 100644 --- a/src/share/content_renderer.js +++ b/src/share/content_renderer.js @@ -69,7 +69,7 @@ function renderText(result, note) { if (linkedNote) { linkEl.setAttribute("href", linkedNote.shareId); - linkEl.classList.add("type-" + linkedNote.type); + linkEl.classList.add(`type-${linkedNote.type}`); } else { linkEl.removeAttribute("href"); } diff --git a/src/share/shaca/entities/note.js b/src/share/shaca/entities/note.js index f7de68771..0c7a5261a 100644 --- a/src/share/shaca/entities/note.js +++ b/src/share/shaca/entities/note.js @@ -99,7 +99,7 @@ class Note extends AbstractEntity { return undefined; } else { - throw new Error("Cannot find note content for noteId=" + this.noteId); + throw new Error(`Cannot find note content for noteId=${this.noteId}`); } } diff --git a/src/www b/src/www index 4652c785c..bc41ca063 100644 --- a/src/www +++ b/src/www @@ -64,7 +64,7 @@ async function startTrilium() { app.set('trust proxy', config['Network']['trustedReverseProxy']) } } - log.info('Trusted reverse proxy: ' + app.get('trust proxy')) + log.info(`Trusted reverse proxy: ${app.get('trust proxy')}`) if (config['Network']['https']) { if (!config['Network']['keyPath'] || !config['Network']['keyPath'].trim().length) { @@ -82,12 +82,12 @@ async function startTrilium() { httpServer = https.createServer(options, app); - log.info("App HTTPS server starting up at port " + port); + log.info(`App HTTPS server starting up at port ${port}`); } else { httpServer = http.createServer(app); - log.info("App HTTP server starting up at port " + port); + log.info(`App HTTP server starting up at port ${port}`); } log.info(JSON.stringify(appInfo, null, 2)); @@ -124,7 +124,7 @@ async function startTrilium() { } ) - httpServer.on('listening', () => log.info('Listening on port ' + httpServer.address().port)); + httpServer.on('listening', () => log.info(`Listening on port ${httpServer.address().port}`)); ws.init(httpServer, sessionParser);