Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
many small issues found by intellij analysis
zadamf50a9c250a10
diff --git a/package-lock.json b/package-lock.jsonindex 2c8d1c985e..e27ec78a53 100644--- a/package-lock.json+++ b/package-lock.json@@ -71,6 +71,7 @@"turndown": "7.1.1","unescape": "1.0.1","ws": "8.12.0",+ "xml2js": "^0.4.23","yauzl": "2.10.0"},"bin": {diff --git a/package.json b/package.jsonindex 0808b715d6..2cdd0995d2 100644--- a/package.json+++ b/package.json@@ -88,6 +88,7 @@"turndown": "7.1.1","unescape": "1.0.1","ws": "8.12.0",+ "xml2js": "0.4.23","yauzl": "2.10.0"},"devDependencies": {diff --git a/src/anonymize.js b/src/anonymize.jsindex 39cb44852e..0fa00cda18 100644--- a/src/anonymize.js+++ b/src/anonymize.js@@ -1,12 +1,12 @@-const backupService = require('./services/backup');+const anonymizationService = require('./services/anonymization');const sqlInit = require('./services/sql_init');-require('./entities/entity_constructor');+require('./becca/entity_constructor');sqlInit.dbReady.then(async () => {try {console.log("Starting anonymization...");- const resp = await backupService.anonymize();+ const resp = await anonymizationService.createAnonymizedCopy('full');if (resp.success) {console.log(`Anonymized file has been saved to: ${resp.anonymizedFilePath}`);diff --git a/src/becca/becca.js b/src/becca/becca.jsindex bb7e14208a..05a42de264 100644--- a/src/becca/becca.js+++ b/src/becca/becca.js@@ -121,17 +121,17 @@ class Becca {return row ? new BNoteRevision(row) : null;}- /** @returns {Option|null} */+ /** @returns {BOption|null} */getOption(name) {return this.options[name];}- /** @returns {EtapiToken[]} */+ /** @returns {BEtapiToken[]} */getEtapiTokens() {return Object.values(this.etapiTokens);}- /** @returns {EtapiToken|null} */+ /** @returns {BEtapiToken|null} */getEtapiToken(etapiTokenId) {return this.etapiTokens[etapiTokenId];}@@ -168,7 +168,7 @@ class Becca {const rows = sql.getRows(query, params);const BNoteRevision = require("./entities/bnote_revision"); // avoiding circular dependency problems- return rows.map(row => new NoteRevision(row));+ return rows.map(row => new BNoteRevision(row));}/** Should be called when the set of all non-skeleton notes changes (added/removed) */diff --git a/src/becca/entities/bbranch.js b/src/becca/entities/bbranch.jsindex a114308c93..18b19588cb 100644--- a/src/becca/entities/bbranch.js+++ b/src/becca/entities/bbranch.js@@ -53,7 +53,7 @@ class BBranch extends AbstractBeccaEntity {this.noteId = noteId;/** @type {string} */this.parentNoteId = parentNoteId;- /** @type {string} */+ /** @type {string|null} */this.prefix = prefix;/** @type {int} */this.notePosition = notePosition;diff --git a/src/becca/entities/bnote.js b/src/becca/entities/bnote.jsindex e1ac3e7015..f1d0fe3433 100644--- a/src/becca/entities/bnote.js+++ b/src/becca/entities/bnote.js@@ -195,9 +195,9 @@ class BNote extends AbstractBeccaEntity {/** Note content has quite special handling - it's not a separate entity, but a lazily loaded- * part of Note entity with it's own sync. Reasons behind this hybrid design has been:+ * part of Note entity with its own sync. Reasons behind this hybrid design has been:*- * - content can be quite large and it's not necessary to load it / fill memory for any note access even if we don't need a content, especially for bulk operations like search+ * - content can be quite large, and it's not necessary to load it / fill memory for any note access even if we don't need a content, especially for bulk operations like search* - changes in the note metadata or title should not trigger note content sync (so we keep separate utcDateModified and entity changes records)* - but to the user note content and title changes are one and the same - single dateModified (so all changes must go through Note and content is not a separate entity)*/diff --git a/src/becca/similarity.js b/src/becca/similarity.jsindex b946beb099..dadfb1ce57 100644--- a/src/becca/similarity.js+++ b/src/becca/similarity.js@@ -261,7 +261,7 @@ async function findSimilarNotes(noteId) {let counter = 0;- // when the title is very long then weight of each individual word should be lower+ // when the title is very long then weight of each individual word should be lowered// also pretty important in e.g. long URLs in label valuesconst lengthPenalization = 1 / Math.pow(text.length, 0.3);@@ -448,7 +448,7 @@ async function findSimilarNotes(noteId) {}/**- * Point of this is to break up long running sync process to avoid blocking+ * Point of this is to break up long-running sync process to avoid blocking* see https://snyk.io/blog/nodejs-how-even-quick-async-functions-can-block-the-event-loop-starve-io/*/function setImmediatePromise() {diff --git a/src/public/app/components/app_context.js b/src/public/app/components/app_context.jsindex f8b1e6d7a6..32670f5a30 100644--- a/src/public/app/components/app_context.js+++ b/src/public/app/components/app_context.js@@ -89,7 +89,7 @@ class AppContext extends Component {}/** @returns {Promise<void>} */- triggerEvent(name, data) {+ triggerEvent(name, data = {}) {return this.handleEvent(name, data);}diff --git a/src/public/app/components/component.js b/src/public/app/components/component.jsindex 076d038a45..0f614bcbf7 100644--- a/src/public/app/components/component.js+++ b/src/public/app/components/component.js@@ -4,11 +4,11 @@ import utils from '../services/utils.js';* Abstract class for all components in the Trilium's frontend.** Contains also event implementation with following properties:- * - event / command distribution is synchronous which among others mean that events are well ordered - event+ * - event / command distribution is synchronous which among others mean that events are well-ordered - event* which was sent out first will also be processed first by the component* - execution of the event / command is asynchronous - each component executes the event on its own without regard for* other components.- * - although the execution is async, we are collecting all the promises and therefore it is possible to wait until the+ * - although the execution is async, we are collecting all the promises, and therefore it is possible to wait until the* event / command is executed in all components - by simply awaiting the `triggerEvent()`.*/export default class Component {@@ -62,12 +62,12 @@ export default class Component {}/** @returns {Promise<void>} */- triggerEvent(name, data) {+ triggerEvent(name, data = {}) {return this.parent.triggerEvent(name, data);}/** @returns {Promise<void>} */- handleEventInChildren(name, data) {+ handleEventInChildren(name, data = {}) {const promises = [];for (const child of this.children) {diff --git a/src/public/app/components/note_context.js b/src/public/app/components/note_context.jsindex 29bf013cc7..2b9c5b11dd 100644--- a/src/public/app/components/note_context.js+++ b/src/public/app/components/note_context.js@@ -9,9 +9,6 @@ import hoistedNoteService from "../services/hoisted_note.js";import options from "../services/options.js";class NoteContext extends Component {- /**- * @param {string|null} ntxId- */constructor(ntxId = null, hoistedNoteId = 'root', mainNtxId = null) {super();diff --git a/src/public/app/entities/fnote.js b/src/public/app/entities/fnote.jsindex a3319b10dd..3e0da6cdb9 100644--- a/src/public/app/entities/fnote.js+++ b/src/public/app/entities/fnote.js@@ -113,7 +113,7 @@ class FNote {}async getContent() {- // we're not caching content since these objects are in froca and as such pretty long lived+ // we're not caching content since these objects are in froca and as such pretty long-livedconst note = await server.get(`notes/${this.noteId}`);return note.content;diff --git a/src/public/app/menus/context_menu.js b/src/public/app/menus/context_menu.jsindex 67434025b2..ba42cc345d 100644--- a/src/public/app/menus/context_menu.js+++ b/src/public/app/menus/context_menu.js@@ -24,7 +24,7 @@ class ContextMenu {positionMenu() {// code below tries to detect when dropdown would overflow from page- // in such case we'll position it above click coordinates so it will fit into client+ // in such case we'll position it above click coordinates, so it will fit into clientconst CONTEXT_MENU_PADDING = 5; // How many pixels to pad context menu from edge of screenconst CONTEXT_MENU_OFFSET = 0; // How many pixels to offset context menu by relative to cursor, see #3157diff --git a/src/public/app/menus/launcher_context_menu.js b/src/public/app/menus/launcher_context_menu.jsindex 00b2f17e81..179a2a1be6 100644--- a/src/public/app/menus/launcher_context_menu.js+++ b/src/public/app/menus/launcher_context_menu.js@@ -19,7 +19,7 @@ export default class LauncherContextMenu {x: e.pageX,y: e.pageY,items: await this.getMenuItems(),- selectMenuItemHandler: (item, e) => this.selectMenuItemHandler(item, e)+ selectMenuItemHandler: (item, e) => this.selectMenuItemHandler(item)})}diff --git a/src/public/app/menus/tree_context_menu.js b/src/public/app/menus/tree_context_menu.jsindex 52300b9623..5b792da722 100644--- a/src/public/app/menus/tree_context_menu.js+++ b/src/public/app/menus/tree_context_menu.js@@ -21,7 +21,7 @@ export default class TreeContextMenu {x: e.pageX,y: e.pageY,items: await this.getMenuItems(),- selectMenuItemHandler: (item, e) => this.selectMenuItemHandler(item, e)+ selectMenuItemHandler: (item, e) => this.selectMenuItemHandler(item)})}diff --git a/src/public/app/services/attribute_parser.js b/src/public/app/services/attribute_parser.jsindex 6567dc4011..3b89bce8dc 100644--- a/src/public/app/services/attribute_parser.js+++ b/src/public/app/services/attribute_parser.js@@ -67,7 +67,7 @@ function lex(str) {finishWord(i - 1);}else {- // it's a quote but within other kind of quotes so it's valid as a literal character+ // it's a quote but within other kind of quotes, so it's valid as a literal charactercurrentWord += chr;}continue;diff --git a/src/public/app/services/attributes.js b/src/public/app/services/attributes.jsindex 26dedf4674..97847855ee 100644--- a/src/public/app/services/attributes.js+++ b/src/public/app/services/attributes.js@@ -36,7 +36,7 @@ function isAffecting(attrRow, affectedNote) {const attrNote = froca.notes[attrRow.noteId];if (!attrNote) {- // the note (owner of the attribute) is not even loaded into the cache so it should not affect anything else+ // the note (owner of the attribute) is not even loaded into the cache, so it should not affect anything elsereturn false;}diff --git a/src/public/app/services/clipboard.js b/src/public/app/services/clipboard.jsindex 110c29f6af..1caf46cdd8 100644--- a/src/public/app/services/clipboard.js+++ b/src/public/app/services/clipboard.js@@ -27,7 +27,7 @@ async function pasteAfter(afterBranchId) {await branchService.cloneNoteAfter(clipboardNote.noteId, afterBranchId);}- // copy will keep clipboardBranchIds and clipboardMode so it's possible to paste into multiple places+ // copy will keep clipboardBranchIds and clipboardMode, so it's possible to paste into multiple places}else {toastService.throwError(`Unrecognized clipboard mode=${clipboardMode}`);diff --git a/src/public/app/services/debounce.js b/src/public/app/services/debounce.jsindex e737bcd767..62415da292 100644--- a/src/public/app/services/debounce.js+++ b/src/public/app/services/debounce.js@@ -7,20 +7,20 @@** @source underscore.js* @see http://unscriptable.com/2009/03/20/debouncing-javascript-methods/- * @param {Function} function to wrap- * @param {Number} timeout in ms (`100`)- * @param {Boolean} whether to execute at the beginning (`false`)+ * @param {Function} func to wrap+ * @param {Number} waitMs in ms (`100`)+ * @param {Boolean} immediate whether to execute at the beginning (`false`)* @api public*/-function debounce(func, wait_ms, immediate){+function debounce(func, waitMs, immediate) {var timeout, args, context, timestamp, result;- if (null == wait_ms) wait_ms = 100;+ if (null == waitMs) waitMs = 100;function later() {var last = Date.now() - timestamp;- if (last < wait_ms && last >= 0) {- timeout = setTimeout(later, wait_ms - last);+ if (last < waitMs && last >= 0) {+ timeout = setTimeout(later, waitMs - last);} else {timeout = null;if (!immediate) {@@ -28,14 +28,14 @@ function debounce(func, wait_ms, immediate){context = args = null;}}- };+ }var debounced = function(){context = this;args = arguments;timestamp = Date.now();var callNow = immediate && !timeout;- if (!timeout) timeout = setTimeout(later, wait_ms);+ if (!timeout) timeout = setTimeout(later, waitMs);if (callNow) {result = func.apply(context, args);context = args = null;@@ -62,7 +62,7 @@ function debounce(func, wait_ms, immediate){};return debounced;-};+}// Adds compatibility for ES modulesdebounce.debounce = debounce;diff --git a/src/public/app/services/froca_updater.js b/src/public/app/services/froca_updater.jsindex b28f80f3f3..5a0a224ff3 100644--- a/src/public/app/services/froca_updater.js+++ b/src/public/app/services/froca_updater.js@@ -85,7 +85,7 @@ function processNoteChange(loadResults, ec) {const note = froca.notes[ec.entityId];if (!note) {- // if this note has not been requested before then it's not part of froca's cached subset and+ // if this note has not been requested before then it's not part of froca's cached subset, and// we're not interested in itreturn;}diff --git a/src/public/app/services/frontend_script_api.js b/src/public/app/services/frontend_script_api.jsindex 7923396f02..91bd49fc0a 100644--- a/src/public/app/services/frontend_script_api.js+++ b/src/public/app/services/frontend_script_api.js@@ -175,7 +175,7 @@ function FrontendScriptApi(startNote, currentNote, originEntity = null, $contain** @method* @param {string} script - script to be executed on the backend- * @param {Array.<?>} params - list of parameters to the anonymous function to be send to backend+ * @param {Array.<?>} params - list of parameters to the anonymous function to be sent to backend* @returns {Promise<*>} return value of the executed function on the backend*/this.runOnBackend = async (script, params = []) => {diff --git a/src/public/app/services/note_create.js b/src/public/app/services/note_create.jsindex f246abae18..e5c593c206 100644--- a/src/public/app/services/note_create.js+++ b/src/public/app/services/note_create.js@@ -1,5 +1,4 @@import appContext from "../components/app_context.js";-import utils from "./utils.js";import protectedSessionHolder from "./protected_session_holder.js";import server from "./server.js";import ws from "./ws.js";@@ -15,7 +14,7 @@ async function createNote(parentNotePath, options = {}) {}, options);// if isProtected isn't available (user didn't enter password yet), then note is created as unencrypted- // but this is quite weird since user doesn't see WHERE the note is being created so it shouldn't occur often+ // but this is quite weird since user doesn't see WHERE the note is being created, so it shouldn't occur oftenif (!options.isProtected || !protectedSessionHolder.isProtectedSessionAvailable()) {options.isProtected = false;}diff --git a/src/public/app/services/open.js b/src/public/app/services/open.jsindex dba42db898..2d0ef6091e 100644--- a/src/public/app/services/open.js+++ b/src/public/app/services/open.js@@ -58,11 +58,11 @@ function downloadNoteRevision(noteId, noteRevisionId) {*/function getUrlForDownload(url) {if (utils.isElectron()) {- // electron needs absolute URL so we extract current host, port, protocol+ // electron needs absolute URL, so we extract current host, port, protocolreturn `${getHost()}/${url}`;}else {- // web server can be deployed on subdomain so we need to use relative path+ // web server can be deployed on subdomain, so we need to use relative pathreturn url;}}diff --git a/src/public/app/services/spaced_update.js b/src/public/app/services/spaced_update.jsindex 300edc13da..1bd7b56496 100644--- a/src/public/app/services/spaced_update.js+++ b/src/public/app/services/spaced_update.js@@ -47,7 +47,7 @@ export default class SpacedUpdate {this.changed = false;}else {- // update not triggered but changes are still pending so we need to schedule another check+ // update not triggered but changes are still pending, so we need to schedule another checkthis.scheduleUpdate();}}diff --git a/src/public/app/services/tree.js b/src/public/app/services/tree.jsindex b405b2572b..cc0112d49b 100644--- a/src/public/app/services/tree.js+++ b/src/public/app/services/tree.js@@ -1,6 +1,5 @@import ws from './ws.js';import utils from './utils.js';-import server from './server.js';import froca from './froca.js';import hoistedNoteService from '../services/hoisted_note.js';import appContext from "../components/app_context.js";diff --git a/src/public/app/services/utils.js b/src/public/app/services/utils.jsindex ffec05edf9..49edcf5ec4 100644--- a/src/public/app/services/utils.js+++ b/src/public/app/services/utils.js@@ -3,7 +3,7 @@ function reloadFrontendApp(reason) {logInfo(`Frontend app reload: ${reason}`);}- window.location.reload(true);+ window.location.reload();}function parseDate(str) {@@ -314,7 +314,7 @@ function initHelpDropdown($el) {const $dropdownMenu = $el.find('.help-dropdown .dropdown-menu');$dropdownMenu.on('click', e => e.stopPropagation());- // previous propagation stop will also block help buttons from being opened so we need to re-init for this element+ // previous propagation stop will also block help buttons from being opened, so we need to re-init for this elementinitHelpButtons($dropdownMenu);}diff --git a/src/public/app/widgets/attribute_widgets/attribute_editor.js b/src/public/app/widgets/attribute_widgets/attribute_editor.jsindex ec8a9595d7..217717f059 100644--- a/src/public/app/widgets/attribute_widgets/attribute_editor.js+++ b/src/public/app/widgets/attribute_widgets/attribute_editor.js@@ -346,6 +346,7 @@ export default class AttributeEditorWidget extends NoteContextAwareWidget {this.$editor.on("click", e => this.handleEditorClick(e));+ /** @property {BalloonEditor} */this.textEditor = await BalloonEditor.create(this.$editor[0], editorConfig);this.textEditor.model.document.on('change:data', () => this.dataChanged());this.textEditor.editing.view.document.on('enter', (event, data) => {diff --git a/src/public/app/widgets/containers/split_note_container.js b/src/public/app/widgets/containers/split_note_container.jsindex 4a031f2711..66356164d2 100644--- a/src/public/app/widgets/containers/split_note_container.js+++ b/src/public/app/widgets/containers/split_note_container.js@@ -112,7 +112,7 @@ export default class SplitNoteContainer extends FlexContainer {/*** widget.hasBeenAlreadyShown is intended for lazy loading of cached tabs - initial note switches of new tabs- * are not executed, we're waiting for the first tab activation and then we update the tab. After this initial+ * are not executed, we're waiting for the first tab activation, and then we update the tab. After this initial* activation further note switches are always propagated to the tabs.*/handleEventInChildren(name, data) {diff --git a/src/public/app/widgets/dialogs/add_link.js b/src/public/app/widgets/dialogs/add_link.jsindex 76d1181e9a..cc233c7ec3 100644--- a/src/public/app/widgets/dialogs/add_link.js+++ b/src/public/app/widgets/dialogs/add_link.js@@ -99,7 +99,7 @@ export default class AddLinkDialog extends BasicWidget {this.$addLinkTitleSettings.find('input[type=radio]').on('change', e => this.updateTitleSettingsVisibility(e));- // with selection hyper link is implied+ // with selection hyperlink is impliedif (this.textTypeWidget.hasSelection()) {this.$addLinkTitleSettings.find("input[value='hyper-link']").prop("checked", true);}diff --git a/src/public/app/widgets/dialogs/backend_log.js b/src/public/app/widgets/dialogs/backend_log.jsindex dab76ac575..9f308028a4 100644--- a/src/public/app/widgets/dialogs/backend_log.js+++ b/src/public/app/widgets/dialogs/backend_log.js@@ -1,5 +1,4 @@import server from "../../services/server.js";-import utils from "../../services/utils.js";import BasicWidget from "../basic_widget.js";const TPL = `diff --git a/src/public/app/widgets/dialogs/help.js b/src/public/app/widgets/dialogs/help.jsindex ad48073fa8..b15ca841b7 100644--- a/src/public/app/widgets/dialogs/help.js+++ b/src/public/app/widgets/dialogs/help.js@@ -1,4 +1,3 @@-import utils from "../../services/utils.js";import BasicWidget from "../basic_widget.js";const TPL = `diff --git a/src/public/app/widgets/dialogs/include_note.js b/src/public/app/widgets/dialogs/include_note.jsindex 5778c4909e..28e8fea2ae 100644--- a/src/public/app/widgets/dialogs/include_note.js+++ b/src/public/app/widgets/dialogs/include_note.js@@ -98,7 +98,7 @@ export default class IncludeNoteDialog extends BasicWidget {const boxSize = $("input[name='include-note-box-size']:checked").val();if (note.type === 'image') {- // there's no benefit to use insert note functionlity for images+ // there's no benefit to use insert note functionlity for images,// so we'll just add an IMG tagthis.textTypeWidget.addImage(noteId);}diff --git a/src/public/app/widgets/dialogs/info.js b/src/public/app/widgets/dialogs/info.jsindex 266dc74025..113cc8732b 100644--- a/src/public/app/widgets/dialogs/info.js+++ b/src/public/app/widgets/dialogs/info.js@@ -27,7 +27,7 @@ export default class InfoDialog extends BasicWidget {super();this.resolve = null;- this.$originallyFocused = null; // element focused before the dialog was opened so we can return to it afterwards+ this.$originallyFocused = null; // element focused before the dialog was opened, so we can return to it afterwards}doRender() {diff --git a/src/public/app/widgets/dialogs/note_revisions.js b/src/public/app/widgets/dialogs/note_revisions.jsindex c936c45beb..17d578c2db 100644--- a/src/public/app/widgets/dialogs/note_revisions.js+++ b/src/public/app/widgets/dialogs/note_revisions.js@@ -239,8 +239,8 @@ export default class NoteRevisionsDialog extends BasicWidget {}else if (revisionItem.type === 'image') {this.$content.html($("<img>")- // 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+ // reason why we put this inline as base64 is that we do not want to let user copy this+ // as a URL to be used in a note. Instead, if they copy and paste it into a note, it will be an uploaded as a new note.attr("src", `data:${note.mime};base64,${fullNoteRevision.content}`).css("max-width", "100%").css("max-height", "100%"));diff --git a/src/public/app/widgets/find_in_code.js b/src/public/app/widgets/find_in_code.jsindex 1c244bd1d5..54784b7543 100644--- a/src/public/app/widgets/find_in_code.js+++ b/src/public/app/widgets/find_in_code.js@@ -69,8 +69,8 @@ export default class FindInCode {let curChar = 0;let curMatch = null;findResult = [];- // All those markText take several seconds on eg this ~500-line- // script, batch them inside an operation so they become+ // All those markText take several seconds on e.g. this ~500-line+ // script, batch them inside an operation, so they become// unnoticeable. Alternatively, an overlay could be used, see// https://codemirror.net/addon/search/match-highlighter.js ?codeEditor.operation(() => {diff --git a/src/public/app/widgets/find_in_text.js b/src/public/app/widgets/find_in_text.jsindex 97ebaea365..b45d4a9903 100644--- a/src/public/app/widgets/find_in_text.js+++ b/src/public/app/widgets/find_in_text.js@@ -14,9 +14,9 @@ export default class FindInText {const selection = textEditor.model.document.selection;const range = selection.getFirstRange();+ // FIXMEfor (const item of range.getItems()) {- // Fill in the findbox with the current selection if- // any+ // Fill in the findbox with the current selection if anyreturn item.data;}}diff --git a/src/public/app/widgets/note_tree.js b/src/public/app/widgets/note_tree.jsindex 72999f2d82..8e9fcdf049 100644--- a/src/public/app/widgets/note_tree.js+++ b/src/public/app/widgets/note_tree.js@@ -19,7 +19,6 @@ import options from "../services/options.js";import protectedSessionHolder from "../services/protected_session_holder.js";import dialogService from "../services/dialog.js";import shortcutService from "../services/shortcuts.js";-import LauncherContextMenu from "../menus/launcher_context_menu.js";const TPL = `<div class="tree-wrapper">@@ -915,7 +914,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {if (expand) {await parentNode.setExpanded(true, {noAnimation: true});- // although previous line should set the expanded status, it seems to happen asynchronously+ // although previous line should set the expanded status, it seems to happen asynchronously,// so we need to make sure it is set properly before calling updateNode which uses this flagconst branch = froca.getBranch(parentNode.data.branchId);branch.isExpanded = true;@@ -925,7 +924,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {let foundChildNode = this.findChildNode(parentNode, childNoteId);- if (!foundChildNode) { // note might be recently created so we'll force reload and try again+ if (!foundChildNode) { // note might be recently created, so we'll force reload and try againawait parentNode.load(true);foundChildNode = this.findChildNode(parentNode, childNoteId);@@ -933,7 +932,7 @@ export default class NoteTreeWidget extends NoteContextAwareWidget {if (!foundChildNode) {if (logErrors) {// besides real errors this can be also caused by hiding of e.g. included images- // these are real notes with real notePath, user can display them in a detail+ // these are real notes with real notePath, user can display them in a detail,// but they don't have a node in the treeconst childNote = await froca.getNote(childNoteId);diff --git a/src/public/app/widgets/quick_search.js b/src/public/app/widgets/quick_search.jsindex a3d5a402fb..a3156df389 100644--- a/src/public/app/widgets/quick_search.js+++ b/src/public/app/widgets/quick_search.js@@ -54,7 +54,7 @@ export default class QuickSearchWidget extends BasicWidget {if(utils.isMobile()) {this.$searchString.keydown(e =>{- if(e.which==13) {+ if(e.which === 13) {if (this.$dropdownMenu.is(":visible")) {this.search(); // just update already visible dropdown} else {@@ -128,7 +128,7 @@ export default class QuickSearchWidget extends BasicWidget {this.$dropdownToggle.dropdown("hide");if (!e.target || e.target.nodeName !== 'A') {- // click on the link is handled by link handling but we want the whole item clickable+ // click on the link is handled by link handling, but we want the whole item clickableappContext.tabManager.getActiveContext().setNote(note.noteId);}});diff --git a/src/public/app/widgets/sql_table_schemas.js b/src/public/app/widgets/sql_table_schemas.jsindex 5eac92c0e8..8a986fe04b 100644--- a/src/public/app/widgets/sql_table_schemas.js+++ b/src/public/app/widgets/sql_table_schemas.js@@ -1,9 +1,5 @@import NoteContextAwareWidget from "./note_context_aware_widget.js";-import treeService from "../services/tree.js";-import linkService from "../services/link.js";-import hoistedNoteService from "../services/hoisted_note.js";import server from "../services/server.js";-import toastService from "../services/toast.js";const TPL = `<div class="sql-table-schemas-widget">diff --git a/src/public/app/widgets/toc.js b/src/public/app/widgets/toc.jsindex 133d66065f..4f9e974291 100644--- a/src/public/app/widgets/toc.js+++ b/src/public/app/widgets/toc.js@@ -2,8 +2,8 @@* Table of contents widget* (c) Antonio Tejada 2022*- * By design there's no support for non-sensical or malformed constructs:- * - headings inside elements (eg Trilium allows headings inside tables, but+ * By design there's no support for nonsensical or malformed constructs:+ * - headings inside elements (e.g. Trilium allows headings inside tables, but* not inside lists)* - nested headings when using raw HTML <H2><H3></H3></H2>* - malformed headings when using raw HTML <H2></H3></H2><H3>@@ -52,7 +52,7 @@ const TPL = `<div class="toc-widget">* @param {Element} parent Parent node to find a headingIndex'th in.* @param {uint} headingIndex Index for the heading* @returns {Element|null} Heading node with the given index, null couldn't be- * found (ie malformed like nested headings, etc)+ * found (ie malformed like nested headings, etc.)*/function findHeadingNodeByIndex(parent, headingIndex) {let headingNode = null;@@ -61,7 +61,7 @@ function findHeadingNodeByIndex(parent, headingIndex) {// Headings appear as flattened top level children in the CKEditor// document named as "heading" plus the level, eg "heading2",- // "heading3", "heading2", etc and not nested wrt the heading level. If+ // "heading3", "heading2", etc. and not nested wrt the heading level. If// a heading node is found, decrement the headingIndex until zero is// reachedif (child.name.startsWith("heading")) {diff --git a/src/public/app/widgets/type_widgets/canvas.js b/src/public/app/widgets/type_widgets/canvas.jsindex 74238ff51d..5dd8f8f0cb 100644--- a/src/public/app/widgets/type_widgets/canvas.js+++ b/src/public/app/widgets/type_widgets/canvas.js@@ -144,7 +144,7 @@ export default class ExcalidrawTypeWidget extends TypeWidget {/*** called to populate the widget container with the note content*- * @param {note} note+ * @param {FNote} note*/async doRefresh(note) {// see if note changed, since we do not get a new class for a new note@@ -219,7 +219,7 @@ export default class ExcalidrawTypeWidget extends TypeWidget {collaborators: []};- // files are expected in an array when loading. they are stored as an key-index object+ // files are expected in an array when loading. they are stored as a key-index object// see example for loading here:// https://github.com/excalidraw/excalidraw/blob/c5a7723185f6ca05e0ceb0b0d45c4e3fbcb81b2a/src/packages/excalidraw/example/App.js#L68const fileArray = [];diff --git a/src/public/app/widgets/type_widgets/editable_text.js b/src/public/app/widgets/type_widgets/editable_text.jsindex 67003dc689..74f593d331 100644--- a/src/public/app/widgets/type_widgets/editable_text.js+++ b/src/public/app/widgets/type_widgets/editable_text.js@@ -122,13 +122,13 @@ export default class EditableTextTypeWidget extends AbstractTextTypeWidget {this.watchdog = new EditorWatchdog(BalloonEditor, {// An average number of milliseconds between the last editor errors (defaults to 5000).// When the period of time between errors is lower than that and the crashNumberLimit- // is also reached, the watchdog changes its state to crashedPermanently and it stops+ // is also reached, the watchdog changes its state to crashedPermanently, and it stops// restarting the editor. This prevents an infinite restart loop.minimumNonErrorTimePeriod: 5000,// A threshold specifying the number of errors (defaults to 3).// After this limit is reached and the time between last errors// is shorter than minimumNonErrorTimePeriod, the watchdog changes- // its state to crashedPermanently and it stops restarting the editor.+ // its state to crashedPermanently, and it stops restarting the editor.// This prevents an infinite restart loop.crashNumberLimit: 3,// A minimum number of milliseconds between saving the editor data internally (defaults to 5000).diff --git a/src/public/app/widgets/type_widgets/image.js b/src/public/app/widgets/type_widgets/image.jsindex 8974b8e612..deffe5c7a2 100644--- a/src/public/app/widgets/type_widgets/image.js+++ b/src/public/app/widgets/type_widgets/image.js@@ -56,7 +56,7 @@ class ImageTypeWidget extends TypeWidget {});if (utils.isElectron()) {- // for browser we want to let the native menu+ // for browser, we want to let the native menuthis.$imageView.on('contextmenu', e => {e.preventDefault();diff --git a/src/public/app/widgets/type_widgets/options/options_widget.js b/src/public/app/widgets/type_widgets/options/options_widget.jsindex ad0bf97a20..442237880b 100644--- a/src/public/app/widgets/type_widgets/options/options_widget.js+++ b/src/public/app/widgets/type_widgets/options/options_widget.js@@ -1,7 +1,6 @@import server from "../../../services/server.js";import toastService from "../../../services/toast.js";import NoteContextAwareWidget from "../../note_context_aware_widget.js";-import attributeService from "../../../services/attributes.js";export default class OptionsWidget extends NoteContextAwareWidget {constructor() {diff --git a/src/routes/api/fonts.js b/src/routes/api/fonts.jsindex 99f7b27489..3764c4a681 100644--- a/src/routes/api/fonts.js+++ b/src/routes/api/fonts.js@@ -11,10 +11,10 @@ function getFontCss(req, res) {const optionsMap = optionService.getOptionsMap();- const mainFontFamilyOverridden = optionsMap.mainFontFamily != 'theme';- const treeFontFamilyOverridden = optionsMap.treeFontFamily != 'theme';- const detailFontFamilyOverridden = optionsMap.detailFontFamily != 'theme';- const monospaceFontFamilyOverridden = optionsMap.monospaceFontFamily != 'theme';+ const mainFontFamilyOverridden = optionsMap.mainFontFamily !== 'theme';+ const treeFontFamilyOverridden = optionsMap.treeFontFamily !== 'theme';+ const detailFontFamilyOverridden = optionsMap.detailFontFamily !== 'theme';+ const monospaceFontFamilyOverridden = optionsMap.monospaceFontFamily !== 'theme';// using body to be more specific than themes' :rootlet style = 'body {';diff --git a/src/routes/api/note_map.js b/src/routes/api/note_map.jsindex 68bc811181..b8487e6ce1 100644--- a/src/routes/api/note_map.js+++ b/src/routes/api/note_map.js@@ -30,6 +30,11 @@ function buildDescendantCountMap() {return noteIdToCountMap;}+/**+ * @param {BNote} note+ * @param {int} depth+ * @returns {string[]} noteIds+ */function getNeighbors(note, depth) {if (depth === 0) {return [];@@ -157,7 +162,7 @@ function getLinkMap(req) {function getTreeMap(req) {const mapRootNote = becca.getNote(req.params.noteId);- // if the map root itself has ignore (journal typically) then there wouldn't be anything to display so+ // if the map root itself has ignore (journal typically) then there wouldn't be anything to display, so// we'll just ignore itconst ignoreExcludeFromNoteMap = mapRootNote.hasLabel('excludeFromNoteMap');const subtree = mapRootNote.getSubtree({@@ -259,6 +264,7 @@ function findExcerpts(sourceNote, referencedNoteId) {centerEl = centerEl.parentElement;}+ /** @var {HTMLElement[]} */const excerptEls = [centerEl];let excerptLength = centerEl.textContent.length;let left = centerEl;diff --git a/src/routes/api/sync.js b/src/routes/api/sync.jsindex c035ca94f6..e2947f096c 100644--- a/src/routes/api/sync.js+++ b/src/routes/api/sync.js@@ -21,7 +21,7 @@ async function testSync() {await syncService.login();- // login was successful so we'll kick off sync now+ // login was successful, so we'll kick off sync now// this is important in case when sync server has been just initializedsyncService.sync();diff --git a/src/services/attributes.js b/src/services/attributes.jsindex 3de60ef82b..d123829d53 100644--- a/src/services/attributes.js+++ b/src/services/attributes.js@@ -10,8 +10,8 @@ const BUILTIN_ATTRIBUTES = require("./builtin_attributes");const ATTRIBUTE_TYPES = [ 'label', 'relation' ];/** @returns {BNote[]} */-function getNotesWithLabel(name, value) {- const query = formatAttrForSearch({type: 'label', name, value}, true);+function getNotesWithLabel(name, value = undefined) {+ const query = formatAttrForSearch({type: 'label', name, value}, value !== undefined);return searchService.searchNotes(query, {includeArchivedNotes: true,ignoreHoistedNote: truediff --git a/src/services/consistency_checks.js b/src/services/consistency_checks.jsindex 66f3bdf69c..97c6f4a131 100644--- a/src/services/consistency_checks.js+++ b/src/services/consistency_checks.js@@ -336,7 +336,7 @@ class ConsistencyChecks {({noteId, isProtected, type, mime}) => {if (this.autoFix) {// it might be possible that the note_content is not available only because of the interrupted- // sync and it will come later. It's therefore important to guarantee that this artifical+ // sync, and it will come later. It's therefore important to guarantee that this artifical// record won't overwrite the real one coming from the sync.const fakeDate = "2000-01-01 00:00:00Z";diff --git a/src/services/date_utils.js b/src/services/date_utils.jsindex 14a7fa7026..5c9a4a8354 100644--- a/src/services/date_utils.js+++ b/src/services/date_utils.js@@ -5,7 +5,7 @@ function utcNowDateTime() {return utcDateTimeStr(new Date());}-// CLS date time is important in web deployments - server often runs in different time zone than user is located in+// CLS date time is important in web deployments - server often runs in different time zone than user is located in,// so we'd prefer client timezone to be used to record local dates. For this reason requests from client contain// "trilium-local-now-datetime" header which is then stored in CLSfunction localNowDateTime() {diff --git a/src/services/export/zip.js b/src/services/export/zip.jsindex 4f9c16f9db..3db3cf5f45 100644--- a/src/services/export/zip.js+++ b/src/services/export/zip.js@@ -21,6 +21,8 @@ const ValidationError = require("../../errors/validation_error");* @param {TaskContext} taskContext* @param {BBranch} branch* @param {string} format - 'html' or 'markdown'+ * @param {object} res - express response+ * @param {boolean} setHeaders*/async function exportToZip(taskContext, branch, format, res, setHeaders = true) {if (!['html', 'markdown'].includes(format)) {diff --git a/src/services/import/enex.js b/src/services/import/enex.jsindex 5f9489189b..b982d642ab 100644--- a/src/services/import/enex.js+++ b/src/services/import/enex.js@@ -207,7 +207,7 @@ function importEnex(taskContext, file, parentNote) {});function updateDates(noteId, utcDateCreated, utcDateModified) {- // it's difficult to force custom dateCreated and dateModified to Note entity so we do it post-creation with SQL+ // it's difficult to force custom dateCreated and dateModified to Note entity, so we do it post-creation with SQLsql.execute(`UPDATE notesSET dateCreated = ?,diff --git a/src/services/notes.js b/src/services/notes.jsindex 817f0e0f00..1785d989fe 100644--- a/src/services/notes.js+++ b/src/services/notes.js@@ -544,7 +544,7 @@ function saveLinks(note, content) {existingLinks.push(newLink);}- // else the link exists so we don't need to do anything+ // else the link exists, so we don't need to do anything}// marking links as deleted if they are not present on the page anymorediff --git a/src/services/request.js b/src/services/request.jsindex 28d1edbf03..78370ad7da 100644--- a/src/services/request.js+++ b/src/services/request.js@@ -11,7 +11,7 @@ const syncOptions = require('./sync_options');function exec(opts) {const client = getClient(opts);- // hack for cases where electron.net does not work but we don't want to set proxy+ // hack for cases where electron.net does not work, but we don't want to set proxyif (opts.proxy === 'noproxy') {opts.proxy = null;}diff --git a/src/services/script.js b/src/services/script.jsindex 812854bbe7..0d95dff8a7 100644--- a/src/services/script.js+++ b/src/services/script.js@@ -66,8 +66,8 @@ function executeScript(script, params, startNoteId, currentNoteId, originEntityNconst currentNote = becca.getNote(currentNoteId);const originEntity = becca.getEntity(originEntityName, originEntityId);- // we're just executing an excerpt of the original frontend script in the backend context so we must- // override normal note's content and it's mime type / script environment+ // we're just executing an excerpt of the original frontend script in the backend context, so we must+ // override normal note's content, and it's mime type / script environmentconst backendOverrideContent = `return (${script}\r\n)(${getParams(params)})`;const bundle = getScriptBundle(currentNote, true, null, [], backendOverrideContent);diff --git a/src/services/search/expressions/note_flat_text.js b/src/services/search/expressions/note_flat_text.jsindex c66df49a78..67aae1b836 100644--- a/src/services/search/expressions/note_flat_text.js+++ b/src/services/search/expressions/note_flat_text.js@@ -17,6 +17,11 @@ class NoteFlatTextExp extends Expression {const beccaService = require('../../../becca/becca_service');const resultNoteSet = new NoteSet();+ /**+ * @param {BNote} note+ * @param {string[]} tokens+ * @param {string[]} path+ */function searchDownThePath(note, tokens, path) {if (tokens.length === 0) {const retPath = beccaService.getSomePath(note, path);diff --git a/src/services/search/services/search.js b/src/services/search/services/search.jsindex e193483927..59fa5fd384 100644--- a/src/services/search/services/search.js+++ b/src/services/search/services/search.js@@ -230,6 +230,7 @@ function parseQueryToExpression(query, searchContext) {/*** @param {string} query+ * @param {object} params - see SearchContext* @returns {BNote[]}*/function searchNotes(query, params = {}) {@@ -299,7 +300,7 @@ function highlightSearchResults(searchResults, highlightedTokens) {// < and > are used for marking <small> and </small>highlightedTokens = highlightedTokens.map(token => token.replace('/[<\{\}]/g', ''));- // sort by the longest so we first highlight longest matches+ // sort by the longest, so we first highlight the longest matcheshighlightedTokens.sort((a, b) => a.length > b.length ? -1 : 1);for (const result of searchResults) {diff --git a/src/services/spaced_update.js b/src/services/spaced_update.jsindex d038a09dba..1257c4e2c7 100644--- a/src/services/spaced_update.js+++ b/src/services/spaced_update.js@@ -47,7 +47,7 @@ class SpacedUpdate {this.changed = false;}else {- // update not triggered but changes are still pending so we need to schedule another check+ // update not triggered but changes are still pending, so we need to schedule another checkthis.scheduleUpdate();}}diff --git a/src/services/sync.js b/src/services/sync.jsindex ddb0dedf44..80adc235f7 100644--- a/src/services/sync.js+++ b/src/services/sync.js@@ -116,7 +116,7 @@ async function doLogin() {const lastSyncedPull = getLastSyncedPull();- // this is important in a scenario where we setup the sync by manually copying the document+ // this is important in a scenario where we set up the sync by manually copying the document// lastSyncedPull then could be pretty off for the newly cloned clientif (lastSyncedPull > resp.maxEntityChangeId) {log.info(`Lowering last synced pull from ${lastSyncedPull} to ${resp.maxEntityChangeId}`);diff --git a/src/services/sync_options.js b/src/services/sync_options.jsindex 28ec9cca39..af3c4e25e0 100644--- a/src/services/sync_options.js+++ b/src/services/sync_options.js@@ -21,7 +21,7 @@ module.exports = {isSyncSetup: () => {const syncServerHost = get('syncServerHost');- // special value "disabled" is here to support use case where document is configured with sync server+ // special value "disabled" is here to support use case where document is configured with sync server,// and we need to override it with config from config.inireturn !!syncServerHost && syncServerHost !== 'disabled';},diff --git a/src/services/tree.js b/src/services/tree.jsindex 6eeb5ce30a..a0feb07a02 100644--- a/src/services/tree.js+++ b/src/services/tree.js@@ -85,7 +85,7 @@ function getExistingBranch(parentNoteId, childNoteId) {function checkTreeCycle(parentNoteId, childNoteId) {const subtreeNoteIds = [];- // we'll load the whole sub tree - because the cycle can start in one of the notes in the sub tree+ // we'll load the whole subtree - because the cycle can start in one of the notes in the subtreeloadSubtreeNoteIds(childNoteId, subtreeNoteIds);function checkTreeCycleInner(parentNoteId) {diff --git a/src/services/utils.js b/src/services/utils.jsindex f243e28333..a50f443efb 100644--- a/src/services/utils.js+++ b/src/services/utils.js@@ -29,6 +29,9 @@ function toBase64(plainText) {return Buffer.from(plainText).toString('base64');}+/**+ * @returns {Buffer}+ */function fromBase64(encodedText) {return Buffer.from(encodedText, 'base64');}diff --git a/src/services/window.js b/src/services/window.jsindex 3990c7f70f..a9180d5199 100644--- a/src/services/window.js+++ b/src/services/window.js@@ -48,7 +48,7 @@ async function createMainWindow(app) {const windowStateKeeper = require('electron-window-state'); // should not be statically importedconst mainWindowState = windowStateKeeper({- // default window width & height so it's usable on 1600 * 900 display (including some extra panels etc.)+ // default window width & height, so it's usable on 1600 * 900 display (including some extra panels etc.)defaultWidth: 1200,defaultHeight: 800});diff --git a/src/share/canvas_share.js b/src/share/canvas_share.jsindex a7759527ae..77d5561b23 100644--- a/src/share/canvas_share.js+++ b/src/share/canvas_share.js@@ -1,7 +1,7 @@/*** this is used as a "standalone js" file and required by a shared note directly via script-tags- *- * data input comes via window variable as follow+ *+ * data input comes via window variable as follows* const {elements, appState, files} = window.triliumExcalidraw;*/@@ -15,9 +15,9 @@ const App = () => {height: appState.height,});const [viewModeEnabled, setViewModeEnabled] = React.useState(false);-+// ensure that assets are loaded from trilium-+/*** resizing*/@@ -35,9 +35,9 @@ const App = () => {};setDimensions(dimensions);};-+window.addEventListener("resize", onResize);-+return () => window.removeEventListener("resize", onResize);}, [excalidrawWrapperRef]);@@ -49,7 +49,7 @@ const App = () => {{className: "excalidraw-wrapper",ref: excalidrawWrapperRef- },+ },React.createElement(ExcalidrawLib.Excalidraw, {ref: excalidrawRef,width: dimensions.width,@@ -82,10 +82,10 @@ const App = () => {className: "excalidraw Stack",},React.createElement(- "button",+ "button",{onClick: () => setViewModeEnabled(!viewModeEnabled)- },+ },viewModeEnabled ? " Enter simple view mode " : " Enter extended view mode "),""diff --git a/src/tools/generate_document.js b/src/tools/generate_document.jsindex 62af2f97a4..85c6ad1bfc 100644--- a/src/tools/generate_document.js+++ b/src/tools/generate_document.js@@ -3,13 +3,12 @@* will create 1000 new notes and some clones into a current document.db*/-require('../entities/entity_constructor');+require('../becca/entity_constructor');const sqlInit = require('../services/sql_init');const noteService = require('../services/notes');const attributeService = require('../services/attributes');const cls = require('../services/cls');const cloningService = require('../services/cloning');-const noteRevisionService = require('../services/note_revisions');const loremIpsum = require('lorem-ipsum').loremIpsum;const noteCount = parseInt(process.argv[2]);@@ -47,7 +46,7 @@ async function start() {format: 'html'});- const {note} = await noteService.createNewNote({+ const {note} = noteService.createNewNote({parentNoteId: getRandomNoteId(),title,content,@@ -83,7 +82,7 @@ async function start() {isInheritable: Math.random() > 0.1 // 10% are inheritable});- noteRevisionService.createNoteRevision(await becca.getNote(getRandomNoteId()));+ note.saveNoteRevision();notes.push(note.noteId);}