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
using ES6 modules for whole frontend SPA app
azivnera699210a298a
diff --git a/src/public/javascripts/bootstrap.js b/src/public/javascripts/bootstrap.jsindex d858b0f12d..9ddabb9996 100644--- a/src/public/javascripts/bootstrap.js+++ b/src/public/javascripts/bootstrap.js@@ -1,9 +1,38 @@-import searchTree from './search_tree.js';+import addLink from './dialogs/add_link.js';+import editTreePrefix from './dialogs/edit_tree_prefix.js';+import eventLog from './dialogs/event_log.js';+import jumpToNote from './dialogs/jump_to_note.js';+import labelsDialog from './dialogs/labels.js';+import noteHistory from './dialogs/note_history.js';+import noteSource from './dialogs/note_source.js';+import recentChanges from './dialogs/recent_changes.js';+import recentNotes from './dialogs/recent_notes.js';+import settings from './dialogs/settings.js';+import sqlConsole from './dialogs/sql_console.js';+import cloning from './cloning.js';+import contextMenu from './context_menu.js';+import dragAndDropSetup from './drag_and_drop.js';+import exportService from './export.js';+import link from './link.js';+import messaging from './messaging.js';+import noteEditor from './note_editor.js';+import noteType from './note_type.js';+import protected_session from './protected_session.js';+import ScriptApi from './script_api.js';+import ScriptContext from './script_context.js';+import sync from './sync.js';+import treeChanges from './tree_changes.js';+import treeUtils from './tree_utils.js';+import utils from './utils.js';++import searchTreeService from './search_tree.js';+import './init.js';+import treeService from './note_tree.js';const $toggleSearchButton = $("#toggle-search-button");-$toggleSearchButton.click(searchTree.toggleSearch);-bindShortcut('ctrl+s', searchTree.toggleSearch);+$toggleSearchButton.click(searchTreeService.toggleSearch);+bindShortcut('ctrl+s', searchTreeService.toggleSearch);function bindShortcut(keyboardShortcut, handler) {$(document).bind('keydown', keyboardShortcut, e => {diff --git a/src/public/javascripts/cloning.js b/src/public/javascripts/cloning.jsindex 7dd7e395a8..bb578a888f 100644--- a/src/public/javascripts/cloning.js+++ b/src/public/javascripts/cloning.js@@ -1,33 +1,33 @@"use strict";-const cloning = (function() {- async function cloneNoteTo(childNoteId, parentNoteId, prefix) {- const resp = await server.put('notes/' + childNoteId + '/clone-to/' + parentNoteId, {- prefix: prefix- });-- if (!resp.success) {- alert(resp.message);- return;- }-- await treeService.reload();+import treeService from './note_tree.js';++async function cloneNoteTo(childNoteId, parentNoteId, prefix) {+ const resp = await server.put('notes/' + childNoteId + '/clone-to/' + parentNoteId, {+ prefix: prefix+ });++ if (!resp.success) {+ alert(resp.message);+ return;}- // 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);+ await treeService.reload();+}- if (!resp.success) {- alert(resp.message);- return;- }+// 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);- await treeService.reload();+ if (!resp.success) {+ alert(resp.message);+ return;}- return {- cloneNoteAfter,- cloneNoteTo- };-})();\ No newline at end of file+ await treeService.reload();+}++export default {+ cloneNoteAfter,+ cloneNoteTo+};\ No newline at end of filediff --git a/src/public/javascripts/context_menu.js b/src/public/javascripts/context_menu.jsindex 55fe98edbc..0631a104f1 100644--- a/src/public/javascripts/context_menu.js+++ b/src/public/javascripts/context_menu.js@@ -1,181 +1,188 @@"use strict";-const contextMenu = (function() {- const $tree = $("#tree");+import treeService from './note_tree.js';+import cloning from './cloning.js';+import exportService from './export.js';+import messaging from './messaging.js';+import protected_session from './protected_session.js';+import treeChanges from './tree_changes.js';+import treeUtils from './tree_utils.js';+import utils from './utils.js';- let clipboardIds = [];- let clipboardMode = null;+const $tree = $("#tree");- async function pasteAfter(node) {- if (clipboardMode === 'cut') {- const nodes = clipboardIds.map(nodeKey => treeUtils.getNodeByKey(nodeKey));+let clipboardIds = [];+let clipboardMode = null;- await treeChanges.moveAfterNode(nodes, node);+async function pasteAfter(node) {+ if (clipboardMode === 'cut') {+ const nodes = clipboardIds.map(nodeKey => treeUtils.getNodeByKey(nodeKey));- clipboardIds = [];- clipboardMode = null;- }- else if (clipboardMode === 'copy') {- for (const noteId of clipboardIds) {- await cloning.cloneNoteAfter(noteId, node.data.branchId);- }+ await treeChanges.moveAfterNode(nodes, node);- // copy will keep clipboardIds and clipboardMode so it's possible to paste into multiple places- }- else if (clipboardIds.length === 0) {- // just do nothing- }- else {- utils.throwError("Unrecognized clipboard mode=" + clipboardMode);+ clipboardIds = [];+ clipboardMode = null;+ }+ else if (clipboardMode === 'copy') {+ for (const noteId of clipboardIds) {+ await cloning.cloneNoteAfter(noteId, node.data.branchId);}++ // copy will keep clipboardIds and clipboardMode so it's possible to paste into multiple places+ }+ else if (clipboardIds.length === 0) {+ // just do nothing}+ else {+ utils.throwError("Unrecognized clipboard mode=" + clipboardMode);+ }+}- async function pasteInto(node) {- if (clipboardMode === 'cut') {- const nodes = clipboardIds.map(nodeKey => treeUtils.getNodeByKey(nodeKey));+async function pasteInto(node) {+ if (clipboardMode === 'cut') {+ const nodes = clipboardIds.map(nodeKey => treeUtils.getNodeByKey(nodeKey));- await treeChanges.moveToNode(nodes, node);+ await treeChanges.moveToNode(nodes, node);- clipboardIds = [];- clipboardMode = null;+ clipboardIds = [];+ clipboardMode = null;+ }+ else if (clipboardMode === 'copy') {+ for (const noteId of clipboardIds) {+ await cloning.cloneNoteTo(noteId, node.data.noteId);+ }+ // copy will keep clipboardIds and clipboardMode so it's possible to paste into multiple places+ }+ else if (clipboardIds.length === 0) {+ // just do nothing+ }+ else {+ utils.throwError("Unrecognized clipboard mode=" + mode);+ }+}++function copy(nodes) {+ clipboardIds = nodes.map(node => node.data.noteId);+ clipboardMode = 'copy';++ utils.showMessage("Note(s) have been copied into clipboard.");+}++function cut(nodes) {+ clipboardIds = nodes.map(node => node.key);+ clipboardMode = 'cut';++ utils.showMessage("Note(s) have been cut into clipboard.");+}++const contextMenuSettings = {+ delegate: "span.fancytree-title",+ autoFocus: true,+ menu: [+ {title: "Insert note here <kbd>Ctrl+O</kbd>", cmd: "insertNoteHere", uiIcon: "ui-icon-plus"},+ {title: "Insert child note <kbd>Ctrl+P</kbd>", cmd: "insertChildNote", uiIcon: "ui-icon-plus"},+ {title: "Delete <kbd>Ctrl+Del</kbd>", cmd: "delete", uiIcon: "ui-icon-trash"},+ {title: "----"},+ {title: "Edit tree prefix <kbd>F2</kbd>", cmd: "editTreePrefix", uiIcon: "ui-icon-pencil"},+ {title: "----"},+ {title: "Protect sub-tree", cmd: "protectSubTree", uiIcon: "ui-icon-locked"},+ {title: "Unprotect sub-tree", cmd: "unprotectSubTree", uiIcon: "ui-icon-unlocked"},+ {title: "----"},+ {title: "Copy / clone <kbd>Ctrl+C</kbd>", cmd: "copy", uiIcon: "ui-icon-copy"},+ {title: "Cut <kbd>Ctrl+X</kbd>", cmd: "cut", uiIcon: "ui-icon-scissors"},+ {title: "Paste into <kbd>Ctrl+V</kbd>", cmd: "pasteInto", uiIcon: "ui-icon-clipboard"},+ {title: "Paste after", cmd: "pasteAfter", uiIcon: "ui-icon-clipboard"},+ {title: "----"},+ {title: "Export sub-tree", cmd: "exportSubTree", uiIcon: " ui-icon-arrowthick-1-ne"},+ {title: "Import sub-tree into", cmd: "importSubTree", uiIcon: "ui-icon-arrowthick-1-sw"},+ {title: "----"},+ {title: "Collapse sub-tree <kbd>Alt+-</kbd>", cmd: "collapseSubTree", uiIcon: "ui-icon-minus"},+ {title: "Force note sync", cmd: "forceNoteSync", uiIcon: "ui-icon-refresh"},+ {title: "Sort alphabetically <kbd>Alt+S</kbd>", cmd: "sortAlphabetically", uiIcon: " ui-icon-arrowthick-2-n-s"}++ ],+ beforeOpen: (event, ui) => {+ const node = $.ui.fancytree.getNode(ui.target);+ const branch = treeService.getBranch(node.data.branchId);+ const note = treeService.getNote(node.data.noteId);+ const parentNote = treeService.getNote(branch.parentNoteId);++ // Modify menu entries depending on node status+ $tree.contextmenu("enableEntry", "pasteAfter", clipboardIds.length > 0 && (!parentNote || parentNote.type !== 'search'));+ $tree.contextmenu("enableEntry", "pasteInto", clipboardIds.length > 0 && note.type !== 'search');+ $tree.contextmenu("enableEntry", "insertNoteHere", !parentNote || parentNote.type !== 'search');+ $tree.contextmenu("enableEntry", "insertChildNote", note.type !== 'search');+ $tree.contextmenu("enableEntry", "importSubTree", note.type !== 'search');+ $tree.contextmenu("enableEntry", "exportSubTree", note.type !== 'search');++ // Activate node on right-click+ node.setActive();+ // Disable tree keyboard handling+ ui.menu.prevKeyboard = node.tree.options.keyboard;+ node.tree.options.keyboard = false;+ },+ close: (event, ui) => {},+ select: (event, ui) => {+ const node = $.ui.fancytree.getNode(ui.target);++ if (ui.cmd === "insertNoteHere") {+ const parentNoteId = node.data.parentNoteId;+ const isProtected = treeUtils.getParentProtectedStatus(node);++ treeService.createNote(node, parentNoteId, 'after', isProtected);+ }+ else if (ui.cmd === "insertChildNote") {+ treeService.createNote(node, node.data.noteId, 'into');+ }+ else if (ui.cmd === "editTreePrefix") {+ editTreePrefix.showDialog(node);+ }+ else if (ui.cmd === "protectSubTree") {+ protected_session.protectSubTree(node.data.noteId, true);+ }+ else if (ui.cmd === "unprotectSubTree") {+ protected_session.protectSubTree(node.data.noteId, false);}- else if (clipboardMode === 'copy') {- for (const noteId of clipboardIds) {- await cloning.cloneNoteTo(noteId, node.data.noteId);- }- // copy will keep clipboardIds and clipboardMode so it's possible to paste into multiple places+ else if (ui.cmd === "copy") {+ copy(treeService.getSelectedNodes());}- else if (clipboardIds.length === 0) {- // just do nothing+ else if (ui.cmd === "cut") {+ cut(treeService.getSelectedNodes());+ }+ else if (ui.cmd === "pasteAfter") {+ pasteAfter(node);+ }+ else if (ui.cmd === "pasteInto") {+ pasteInto(node);+ }+ else if (ui.cmd === "delete") {+ treeChanges.deleteNodes(treeService.getSelectedNodes(true));+ }+ else if (ui.cmd === "exportSubTree") {+ exportService.exportSubTree(node.data.noteId);+ }+ else if (ui.cmd === "importSubTree") {+ exportService.importSubTree(node.data.noteId);+ }+ else if (ui.cmd === "collapseSubTree") {+ treeService.collapseTree(node);+ }+ else if (ui.cmd === "forceNoteSync") {+ syncService.forceNoteSync(node.data.noteId);+ }+ else if (ui.cmd === "sortAlphabetically") {+ treeService.sortAlphabetically(node.data.noteId);}else {- utils.throwError("Unrecognized clipboard mode=" + mode);+ messaging.logError("Unknown command: " + ui.cmd);}}-- function copy(nodes) {- clipboardIds = nodes.map(node => node.data.noteId);- clipboardMode = 'copy';-- utils.showMessage("Note(s) have been copied into clipboard.");- }-- function cut(nodes) {- clipboardIds = nodes.map(node => node.key);- clipboardMode = 'cut';-- utils.showMessage("Note(s) have been cut into clipboard.");- }-- const contextMenuSettings = {- delegate: "span.fancytree-title",- autoFocus: true,- menu: [- {title: "Insert note here <kbd>Ctrl+O</kbd>", cmd: "insertNoteHere", uiIcon: "ui-icon-plus"},- {title: "Insert child note <kbd>Ctrl+P</kbd>", cmd: "insertChildNote", uiIcon: "ui-icon-plus"},- {title: "Delete <kbd>Ctrl+Del</kbd>", cmd: "delete", uiIcon: "ui-icon-trash"},- {title: "----"},- {title: "Edit tree prefix <kbd>F2</kbd>", cmd: "editTreePrefix", uiIcon: "ui-icon-pencil"},- {title: "----"},- {title: "Protect sub-tree", cmd: "protectSubTree", uiIcon: "ui-icon-locked"},- {title: "Unprotect sub-tree", cmd: "unprotectSubTree", uiIcon: "ui-icon-unlocked"},- {title: "----"},- {title: "Copy / clone <kbd>Ctrl+C</kbd>", cmd: "copy", uiIcon: "ui-icon-copy"},- {title: "Cut <kbd>Ctrl+X</kbd>", cmd: "cut", uiIcon: "ui-icon-scissors"},- {title: "Paste into <kbd>Ctrl+V</kbd>", cmd: "pasteInto", uiIcon: "ui-icon-clipboard"},- {title: "Paste after", cmd: "pasteAfter", uiIcon: "ui-icon-clipboard"},- {title: "----"},- {title: "Export sub-tree", cmd: "exportSubTree", uiIcon: " ui-icon-arrowthick-1-ne"},- {title: "Import sub-tree into", cmd: "importSubTree", uiIcon: "ui-icon-arrowthick-1-sw"},- {title: "----"},- {title: "Collapse sub-tree <kbd>Alt+-</kbd>", cmd: "collapseSubTree", uiIcon: "ui-icon-minus"},- {title: "Force note sync", cmd: "forceNoteSync", uiIcon: "ui-icon-refresh"},- {title: "Sort alphabetically <kbd>Alt+S</kbd>", cmd: "sortAlphabetically", uiIcon: " ui-icon-arrowthick-2-n-s"}-- ],- beforeOpen: (event, ui) => {- const node = $.ui.fancytree.getNode(ui.target);- const branch = treeService.getBranch(node.data.branchId);- const note = treeService.getNote(node.data.noteId);- const parentNote = treeService.getNote(branch.parentNoteId);-- // Modify menu entries depending on node status- $tree.contextmenu("enableEntry", "pasteAfter", clipboardIds.length > 0 && (!parentNote || parentNote.type !== 'search'));- $tree.contextmenu("enableEntry", "pasteInto", clipboardIds.length > 0 && note.type !== 'search');- $tree.contextmenu("enableEntry", "insertNoteHere", !parentNote || parentNote.type !== 'search');- $tree.contextmenu("enableEntry", "insertChildNote", note.type !== 'search');- $tree.contextmenu("enableEntry", "importSubTree", note.type !== 'search');- $tree.contextmenu("enableEntry", "exportSubTree", note.type !== 'search');-- // Activate node on right-click- node.setActive();- // Disable tree keyboard handling- ui.menu.prevKeyboard = node.tree.options.keyboard;- node.tree.options.keyboard = false;- },- close: (event, ui) => {},- select: (event, ui) => {- const node = $.ui.fancytree.getNode(ui.target);-- if (ui.cmd === "insertNoteHere") {- const parentNoteId = node.data.parentNoteId;- const isProtected = treeUtils.getParentProtectedStatus(node);-- treeService.createNote(node, parentNoteId, 'after', isProtected);- }- else if (ui.cmd === "insertChildNote") {- treeService.createNote(node, node.data.noteId, 'into');- }- else if (ui.cmd === "editTreePrefix") {- editTreePrefix.showDialog(node);- }- else if (ui.cmd === "protectSubTree") {- protected_session.protectSubTree(node.data.noteId, true);- }- else if (ui.cmd === "unprotectSubTree") {- protected_session.protectSubTree(node.data.noteId, false);- }- else if (ui.cmd === "copy") {- copy(treeService.getSelectedNodes());- }- else if (ui.cmd === "cut") {- cut(treeService.getSelectedNodes());- }- else if (ui.cmd === "pasteAfter") {- pasteAfter(node);- }- else if (ui.cmd === "pasteInto") {- pasteInto(node);- }- else if (ui.cmd === "delete") {- treeChanges.deleteNodes(treeService.getSelectedNodes(true));- }- else if (ui.cmd === "exportSubTree") {- exportService.exportSubTree(node.data.noteId);- }- else if (ui.cmd === "importSubTree") {- exportService.importSubTree(node.data.noteId);- }- else if (ui.cmd === "collapseSubTree") {- treeService.collapseTree(node);- }- else if (ui.cmd === "forceNoteSync") {- syncService.forceNoteSync(node.data.noteId);- }- else if (ui.cmd === "sortAlphabetically") {- treeService.sortAlphabetically(node.data.noteId);- }- else {- messaging.logError("Unknown command: " + ui.cmd);- }- }- };-- return {- pasteAfter,- pasteInto,- cut,- copy,- contextMenuSettings- }-})();\ No newline at end of file+};++export default {+ pasteAfter,+ pasteInto,+ cut,+ copy,+ contextMenuSettings+};\ No newline at end of filediff --git a/src/public/javascripts/dialogs/add_link.js b/src/public/javascripts/dialogs/add_link.jsindex f0f06d7f23..e357471c22 100644--- a/src/public/javascripts/dialogs/add_link.js+++ b/src/public/javascripts/dialogs/add_link.js@@ -1,137 +1,141 @@"use strict";-const addLink = (function() {- const $dialog = $("#add-link-dialog");- const $form = $("#add-link-form");- const $autoComplete = $("#note-autocomplete");- const $linkTitle = $("#link-title");- const $clonePrefix = $("#clone-prefix");- const $linkTitleFormGroup = $("#add-link-title-form-group");- const $prefixFormGroup = $("#add-link-prefix-form-group");- const $linkTypes = $("input[name='add-link-type']");- const $linkTypeHtml = $linkTypes.filter('input[value="html"]');-- function setLinkType(linkType) {- $linkTypes.each(function () {- $(this).prop('checked', $(this).val() === linkType);- });-- linkTypeChanged();- }+import treeService from '../note_tree.js';+import cloning from '../cloning.js';+import link from '../link.js';+import noteEditor from '../note_editor.js';+import treeUtils from '../tree_utils.js';++const $dialog = $("#add-link-dialog");+const $form = $("#add-link-form");+const $autoComplete = $("#note-autocomplete");+const $linkTitle = $("#link-title");+const $clonePrefix = $("#clone-prefix");+const $linkTitleFormGroup = $("#add-link-title-form-group");+const $prefixFormGroup = $("#add-link-prefix-form-group");+const $linkTypes = $("input[name='add-link-type']");+const $linkTypeHtml = $linkTypes.filter('input[value="html"]');++function setLinkType(linkType) {+ $linkTypes.each(function () {+ $(this).prop('checked', $(this).val() === linkType);+ });- async function showDialog() {- glob.activeDialog = $dialog;+ linkTypeChanged();+}- if (noteEditor.getCurrentNoteType() === 'text') {- $linkTypeHtml.prop('disabled', false);+async function showDialog() {+ glob.activeDialog = $dialog;- setLinkType('html');- }- else {- $linkTypeHtml.prop('disabled', true);+ if (noteEditor.getCurrentNoteType() === 'text') {+ $linkTypeHtml.prop('disabled', false);- setLinkType('selected-to-current');- }+ setLinkType('html');+ }+ else {+ $linkTypeHtml.prop('disabled', true);- $dialog.dialog({- modal: true,- width: 700- });+ setLinkType('selected-to-current');+ }- $autoComplete.val('').focus();- $clonePrefix.val('');- $linkTitle.val('');+ $dialog.dialog({+ modal: true,+ width: 700+ });- function setDefaultLinkTitle(noteId) {- const noteTitle = treeService.getNoteTitle(noteId);+ $autoComplete.val('').focus();+ $clonePrefix.val('');+ $linkTitle.val('');- $linkTitle.val(noteTitle);- }+ function setDefaultLinkTitle(noteId) {+ const noteTitle = treeService.getNoteTitle(noteId);++ $linkTitle.val(noteTitle);+ }- $autoComplete.autocomplete({- source: await treeService.getAutocompleteItems(),- minLength: 0,- change: () => {- const val = $autoComplete.val();- const notePath = link.getNodePathFromLabel(val);- if (!notePath) {- return;- }-- const noteId = treeUtils.getNoteIdFromNotePath(notePath);-- if (noteId) {- setDefaultLinkTitle(noteId);- }- },- // this is called when user goes through autocomplete list with keyboard- // at this point the item isn't selected yet so we use supplied ui.item to see WHERE the cursor is- focus: (event, ui) => {- const notePath = link.getNodePathFromLabel(ui.item.value);- const noteId = treeUtils.getNoteIdFromNotePath(notePath);+ $autoComplete.autocomplete({+ source: await treeService.getAutocompleteItems(),+ minLength: 0,+ change: () => {+ const val = $autoComplete.val();+ const notePath = link.getNodePathFromLabel(val);+ if (!notePath) {+ return;+ }++ const noteId = treeUtils.getNoteIdFromNotePath(notePath);+ if (noteId) {setDefaultLinkTitle(noteId);}- });- }+ },+ // this is called when user goes through autocomplete list with keyboard+ // at this point the item isn't selected yet so we use supplied ui.item to see WHERE the cursor is+ focus: (event, ui) => {+ const notePath = link.getNodePathFromLabel(ui.item.value);+ const noteId = treeUtils.getNoteIdFromNotePath(notePath);++ setDefaultLinkTitle(noteId);+ }+ });+}- $form.submit(() => {- const value = $autoComplete.val();+$form.submit(() => {+ const value = $autoComplete.val();- const notePath = link.getNodePathFromLabel(value);- const noteId = treeUtils.getNoteIdFromNotePath(notePath);+ const notePath = link.getNodePathFromLabel(value);+ const noteId = treeUtils.getNoteIdFromNotePath(notePath);- if (notePath) {- const linkType = $("input[name='add-link-type']:checked").val();+ if (notePath) {+ const linkType = $("input[name='add-link-type']:checked").val();- if (linkType === 'html') {- const linkTitle = $linkTitle.val();+ if (linkType === 'html') {+ const linkTitle = $linkTitle.val();- $dialog.dialog("close");+ $dialog.dialog("close");- link.addLinkToEditor(linkTitle, '#' + notePath);- }- else if (linkType === 'selected-to-current') {- const prefix = $clonePrefix.val();+ link.addLinkToEditor(linkTitle, '#' + notePath);+ }+ else if (linkType === 'selected-to-current') {+ const prefix = $clonePrefix.val();- cloning.cloneNoteTo(noteId, noteEditor.getCurrentNoteId(), prefix);+ cloning.cloneNoteTo(noteId, noteEditor.getCurrentNoteId(), prefix);- $dialog.dialog("close");- }- else if (linkType === 'current-to-selected') {- const prefix = $clonePrefix.val();+ $dialog.dialog("close");+ }+ else if (linkType === 'current-to-selected') {+ const prefix = $clonePrefix.val();- cloning.cloneNoteTo(noteEditor.getCurrentNoteId(), noteId, prefix);+ cloning.cloneNoteTo(noteEditor.getCurrentNoteId(), noteId, prefix);- $dialog.dialog("close");- }+ $dialog.dialog("close");}+ }- return false;- });+ return false;+});- function linkTypeChanged() {- const value = $linkTypes.filter(":checked").val();+function linkTypeChanged() {+ const value = $linkTypes.filter(":checked").val();- if (value === 'html') {- $linkTitleFormGroup.show();- $prefixFormGroup.hide();- }- else {- $linkTitleFormGroup.hide();- $prefixFormGroup.show();- }+ if (value === 'html') {+ $linkTitleFormGroup.show();+ $prefixFormGroup.hide();+ }+ else {+ $linkTitleFormGroup.hide();+ $prefixFormGroup.show();}+}- $linkTypes.change(linkTypeChanged);+$linkTypes.change(linkTypeChanged);- $(document).bind('keydown', 'ctrl+l', e => {- showDialog();+$(document).bind('keydown', 'ctrl+l', e => {+ showDialog();- e.preventDefault();- });+ e.preventDefault();+});- return {- showDialog- };-})();\ No newline at end of file+export default {+ showDialog+};\ No newline at end of filediff --git a/src/public/javascripts/dialogs/edit_tree_prefix.js b/src/public/javascripts/dialogs/edit_tree_prefix.jsindex bcc15ef447..45dbdcbeed 100644--- a/src/public/javascripts/dialogs/edit_tree_prefix.js+++ b/src/public/javascripts/dialogs/edit_tree_prefix.js@@ -1,46 +1,46 @@"use strict";-const editTreePrefix = (function() {- const $dialog = $("#edit-tree-prefix-dialog");- const $form = $("#edit-tree-prefix-form");- const $treePrefixInput = $("#tree-prefix-input");- const $noteTitle = $('#tree-prefix-note-title');+import treeService from '../note_tree.js';- let branchId;+const $dialog = $("#edit-tree-prefix-dialog");+const $form = $("#edit-tree-prefix-form");+const $treePrefixInput = $("#tree-prefix-input");+const $noteTitle = $('#tree-prefix-note-title');- async function showDialog() {- glob.activeDialog = $dialog;+let branchId;- await $dialog.dialog({- modal: true,- width: 500- });+async function showDialog() {+ glob.activeDialog = $dialog;- const currentNode = treeService.getCurrentNode();+ await $dialog.dialog({+ modal: true,+ width: 500+ });- branchId = currentNode.data.branchId;- const nt = treeService.getBranch(branchId);+ const currentNode = treeService.getCurrentNode();- $treePrefixInput.val(nt.prefix).focus();+ branchId = currentNode.data.branchId;+ const nt = treeService.getBranch(branchId);- const noteTitle = treeService.getNoteTitle(currentNode.data.noteId);+ $treePrefixInput.val(nt.prefix).focus();- $noteTitle.html(noteTitle);- }+ const noteTitle = treeService.getNoteTitle(currentNode.data.noteId);- $form.submit(() => {- const prefix = $treePrefixInput.val();+ $noteTitle.html(noteTitle);+}- server.put('tree/' + branchId + '/set-prefix', {- prefix: prefix- }).then(() => treeService.setPrefix(branchId, prefix));+$form.submit(() => {+ const prefix = $treePrefixInput.val();- $dialog.dialog("close");+ server.put('tree/' + branchId + '/set-prefix', {+ prefix: prefix+ }).then(() => treeService.setPrefix(branchId, prefix));- return false;- });+ $dialog.dialog("close");++ return false;+});- return {- showDialog- };-})();\ No newline at end of file+export default {+ showDialog+};\ No newline at end of filediff --git a/src/public/javascripts/dialogs/event_log.js b/src/public/javascripts/dialogs/event_log.jsindex affa63dc79..b89cafe52d 100644--- a/src/public/javascripts/dialogs/event_log.js+++ b/src/public/javascripts/dialogs/event_log.js@@ -1,38 +1,39 @@"use strict";-const eventLog = (function() {- const $dialog = $("#event-log-dialog");- const $list = $("#event-log-list");+import link from '../link.js';+import utils from '../utils.js';- async function showDialog() {- glob.activeDialog = $dialog;+const $dialog = $("#event-log-dialog");+const $list = $("#event-log-list");- $dialog.dialog({- modal: true,- width: 800,- height: 700- });+async function showDialog() {+ glob.activeDialog = $dialog;- const result = await server.get('event-log');+ $dialog.dialog({+ modal: true,+ width: 800,+ height: 700+ });- $list.html('');+ const result = await server.get('event-log');- for (const event of result) {- const dateTime = utils.formatDateTime(utils.parseDate(event.dateAdded));+ $list.html('');- if (event.noteId) {- const noteLink = link.createNoteLink(event.noteId).prop('outerHTML');+ for (const event of result) {+ const dateTime = utils.formatDateTime(utils.parseDate(event.dateAdded));- event.comment = event.comment.replace('<note>', noteLink);- }+ if (event.noteId) {+ const noteLink = link.createNoteLink(event.noteId).prop('outerHTML');- const eventEl = $('<li>').html(dateTime + " - " + event.comment);-- $list.append(eventEl);+ event.comment = event.comment.replace('<note>', noteLink);}++ const eventEl = $('<li>').html(dateTime + " - " + event.comment);++ $list.append(eventEl);}+}- return {- showDialog- };-})();\ No newline at end of file+export default {+ showDialog+};diff --git a/src/public/javascripts/dialogs/jump_to_note.js b/src/public/javascripts/dialogs/jump_to_note.jsindex c6b33c01a8..f1dae16cf5 100644--- a/src/public/javascripts/dialogs/jump_to_note.js+++ b/src/public/javascripts/dialogs/jump_to_note.js@@ -1,59 +1,61 @@"use strict";-const jumpToNote = (function() {- const $showDialogButton = $("#jump-to-note-button");- const $dialog = $("#jump-to-note-dialog");- const $autoComplete = $("#jump-to-note-autocomplete");- const $form = $("#jump-to-note-form");-- async function showDialog() {- glob.activeDialog = $dialog;-- $autoComplete.val('');-- $dialog.dialog({- modal: true,- width: 800- });-- await $autoComplete.autocomplete({- source: await utils.stopWatch("building autocomplete", treeService.getAutocompleteItems),- minLength: 0- });- }+import treeService from '../note_tree.js';+import link from '../link.js';+import utils from '../utils.js';- function getSelectedNotePath() {- const val = $autoComplete.val();- return link.getNodePathFromLabel(val);- }+const $showDialogButton = $("#jump-to-note-button");+const $dialog = $("#jump-to-note-dialog");+const $autoComplete = $("#jump-to-note-autocomplete");+const $form = $("#jump-to-note-form");++async function showDialog() {+ glob.activeDialog = $dialog;- function goToNote() {- const notePath = getSelectedNotePath();+ $autoComplete.val('');- if (notePath) {- treeService.activateNode(notePath);+ $dialog.dialog({+ modal: true,+ width: 800+ });++ await $autoComplete.autocomplete({+ source: await utils.stopWatch("building autocomplete", treeService.getAutocompleteItems),+ minLength: 0+ });+}- $dialog.dialog('close');- }+function getSelectedNotePath() {+ const val = $autoComplete.val();+ return link.getNodePathFromLabel(val);+}++function goToNote() {+ const notePath = getSelectedNotePath();++ if (notePath) {+ treeService.activateNode(notePath);++ $dialog.dialog('close');}+}- $(document).bind('keydown', 'ctrl+j', e => {- showDialog();+$(document).bind('keydown', 'ctrl+j', e => {+ showDialog();- e.preventDefault();- });+ e.preventDefault();+});- $form.submit(() => {- const action = $dialog.find("button:focus").val();+$form.submit(() => {+ const action = $dialog.find("button:focus").val();- goToNote();+ goToNote();- return false;- });+ return false;+});- $showDialogButton.click(showDialog);+$showDialogButton.click(showDialog);- return {- showDialog- };-})();\ No newline at end of file+export default {+ showDialog+};\ No newline at end of filediff --git a/src/public/javascripts/dialogs/labels.js b/src/public/javascripts/dialogs/labels.jsindex 1ffd9c91f8..b63dd90fd0 100644--- a/src/public/javascripts/dialogs/labels.js+++ b/src/public/javascripts/dialogs/labels.js@@ -1,227 +1,228 @@"use strict";-const labelsDialog = (function() {- const $showDialogButton = $(".show-labels-button");- const $dialog = $("#labels-dialog");- const $saveLabelsButton = $("#save-labels-button");- const $labelsBody = $('#labels-table tbody');+import noteEditor from '../note_editor.js';+import utils from '../utils.js';- const labelsModel = new LabelsModel();- let labelNames = [];+const $showDialogButton = $(".show-labels-button");+const $dialog = $("#labels-dialog");+const $saveLabelsButton = $("#save-labels-button");+const $labelsBody = $('#labels-table tbody');- function LabelsModel() {- const self = this;+const labelsModel = new LabelsModel();+let labelNames = [];- this.labels = ko.observableArray();+function LabelsModel() {+ const self = this;- this.loadLabels = async function() {- const noteId = noteEditor.getCurrentNoteId();+ this.labels = ko.observableArray();- const labels = await server.get('notes/' + noteId + '/labels');+ this.loadLabels = async function() {+ const noteId = noteEditor.getCurrentNoteId();- self.labels(labels.map(ko.observable));+ const labels = await server.get('notes/' + noteId + '/labels');- addLastEmptyRow();+ self.labels(labels.map(ko.observable));- labelNames = await server.get('labels/names');+ addLastEmptyRow();- // label might not be rendered immediatelly so could not focus- setTimeout(() => $(".label-name:last").focus(), 100);+ labelNames = await server.get('labels/names');- $labelsBody.sortable({- handle: '.handle',- containment: $labelsBody,- update: function() {- let position = 0;+ // label might not be rendered immediatelly so could not focus+ setTimeout(() => $(".label-name:last").focus(), 100);- // we need to update positions by searching in the DOM, because order of the- // labels in the viewmodel (self.labels()) stays the same- $labelsBody.find('input[name="position"]').each(function() {- const attr = self.getTargetLabel(this);+ $labelsBody.sortable({+ handle: '.handle',+ containment: $labelsBody,+ update: function() {+ let position = 0;- attr().position = position++;- });- }- });- };+ // we need to update positions by searching in the DOM, because order of the+ // labels in the viewmodel (self.labels()) stays the same+ $labelsBody.find('input[name="position"]').each(function() {+ const attr = self.getTargetLabel(this);- this.deleteLabel = function(data, event) {- const attr = self.getTargetLabel(event.target);- const attrData = attr();+ attr().position = position++;+ });+ }+ });+ };- if (attrData) {- attrData.isDeleted = 1;+ this.deleteLabel = function(data, event) {+ const attr = self.getTargetLabel(event.target);+ const attrData = attr();- attr(attrData);+ if (attrData) {+ attrData.isDeleted = 1;- addLastEmptyRow();- }- };+ attr(attrData);- function isValid() {- for (let attrs = self.labels(), i = 0; i < attrs.length; i++) {- if (self.isEmptyName(i)) {- return false;- }- }+ addLastEmptyRow();+ }+ };- return true;+ function isValid() {+ for (let attrs = self.labels(), i = 0; i < attrs.length; i++) {+ if (self.isEmptyName(i)) {+ return false;+ }}- this.save = async function() {- // we need to defocus from input (in case of enter-triggered save) because value is updated- // on blur event (because of conflict with jQuery UI Autocomplete). Without this, input would- // stay in focus, blur wouldn't be triggered and change wouldn't be updated in the viewmodel.- $saveLabelsButton.focus();+ return true;+ }- if (!isValid()) {- alert("Please fix all validation errors and try saving again.");- return;- }+ this.save = async function() {+ // we need to defocus from input (in case of enter-triggered save) because value is updated+ // on blur event (because of conflict with jQuery UI Autocomplete). Without this, input would+ // stay in focus, blur wouldn't be triggered and change wouldn't be updated in the viewmodel.+ $saveLabelsButton.focus();- const noteId = noteEditor.getCurrentNoteId();+ if (!isValid()) {+ alert("Please fix all validation errors and try saving again.");+ return;+ }- const labelsToSave = self.labels()- .map(attr => attr())- .filter(attr => attr.labelId !== "" || attr.name !== "");+ const noteId = noteEditor.getCurrentNoteId();- const labels = await server.put('notes/' + noteId + '/labels', labelsToSave);+ const labelsToSave = self.labels()+ .map(attr => attr())+ .filter(attr => attr.labelId !== "" || attr.name !== "");- self.labels(labels.map(ko.observable));+ const labels = await server.put('notes/' + noteId + '/labels', labelsToSave);- addLastEmptyRow();+ self.labels(labels.map(ko.observable));- utils.showMessage("Labels have been saved.");+ addLastEmptyRow();- noteEditor.loadLabelList();- };+ utils.showMessage("Labels have been saved.");- function addLastEmptyRow() {- const attrs = self.labels().filter(attr => attr().isDeleted === 0);- const last = attrs.length === 0 ? null : attrs[attrs.length - 1]();+ noteEditor.loadLabelList();+ };- if (!last || last.name.trim() !== "" || last.value !== "") {- self.labels.push(ko.observable({- labelId: '',- name: '',- value: '',- isDeleted: 0,- position: 0- }));- }+ function addLastEmptyRow() {+ const attrs = self.labels().filter(attr => attr().isDeleted === 0);+ const last = attrs.length === 0 ? null : attrs[attrs.length - 1]();++ if (!last || last.name.trim() !== "" || last.value !== "") {+ self.labels.push(ko.observable({+ labelId: '',+ name: '',+ value: '',+ isDeleted: 0,+ position: 0+ }));}+ }- this.labelChanged = function (data, event) {- addLastEmptyRow();+ this.labelChanged = function (data, event) {+ addLastEmptyRow();- const attr = self.getTargetLabel(event.target);+ const attr = self.getTargetLabel(event.target);- attr.valueHasMutated();- };+ attr.valueHasMutated();+ };- this.isNotUnique = function(index) {- const cur = self.labels()[index]();+ this.isNotUnique = function(index) {+ const cur = self.labels()[index]();- if (cur.name.trim() === "") {- return false;- }+ if (cur.name.trim() === "") {+ return false;+ }- for (let attrs = self.labels(), i = 0; i < attrs.length; i++) {- const attr = attrs[i]();+ for (let attrs = self.labels(), i = 0; i < attrs.length; i++) {+ const attr = attrs[i]();- if (index !== i && cur.name === attr.name) {- return true;- }+ if (index !== i && cur.name === attr.name) {+ return true;}+ }- return false;- };+ return false;+ };- this.isEmptyName = function(index) {- const cur = self.labels()[index]();+ this.isEmptyName = function(index) {+ const cur = self.labels()[index]();- return cur.name.trim() === "" && (cur.labelId !== "" || cur.value !== "");- };+ return cur.name.trim() === "" && (cur.labelId !== "" || cur.value !== "");+ };- this.getTargetLabel = function(target) {- const context = ko.contextFor(target);- const index = context.$index();+ this.getTargetLabel = function(target) {+ const context = ko.contextFor(target);+ const index = context.$index();- return self.labels()[index];- }+ return self.labels()[index];}+}- async function showDialog() {- glob.activeDialog = $dialog;+async function showDialog() {+ glob.activeDialog = $dialog;- await labelsModel.loadLabels();+ await labelsModel.loadLabels();- $dialog.dialog({- modal: true,- width: 800,- height: 500- });- }+ $dialog.dialog({+ modal: true,+ width: 800,+ height: 500+ });+}- $(document).bind('keydown', 'alt+a', e => {- showDialog();+$(document).bind('keydown', 'alt+a', e => {+ showDialog();- e.preventDefault();- });+ e.preventDefault();+});- ko.applyBindings(labelsModel, document.getElementById('labels-dialog'));-- $(document).on('focus', '.label-name', function (e) {- if (!$(this).hasClass("ui-autocomplete-input")) {- $(this).autocomplete({- // shouldn't be required and autocomplete should just accept array of strings, but that fails- // because we have overriden filter() function in init.js- source: labelNames.map(attr => {- return {- label: attr,- value: attr- }- }),- minLength: 0- });- }+ko.applyBindings(labelsModel, document.getElementById('labels-dialog'));- $(this).autocomplete("search", $(this).val());- });+$(document).on('focus', '.label-name', function (e) {+ if (!$(this).hasClass("ui-autocomplete-input")) {+ $(this).autocomplete({+ // shouldn't be required and autocomplete should just accept array of strings, but that fails+ // because we have overriden filter() function in init.js+ source: labelNames.map(attr => {+ return {+ label: attr,+ value: attr+ }+ }),+ minLength: 0+ });+ }- $(document).on('focus', '.label-value', async function (e) {- if (!$(this).hasClass("ui-autocomplete-input")) {- const labelName = $(this).parent().parent().find('.label-name').val();+ $(this).autocomplete("search", $(this).val());+});- if (labelName.trim() === "") {- return;- }+$(document).on('focus', '.label-value', async function (e) {+ if (!$(this).hasClass("ui-autocomplete-input")) {+ const labelName = $(this).parent().parent().find('.label-name').val();- const labelValues = await server.get('labels/values/' + encodeURIComponent(labelName));+ if (labelName.trim() === "") {+ return;+ }- if (labelValues.length === 0) {- return;- }+ const labelValues = await server.get('labels/values/' + encodeURIComponent(labelName));- $(this).autocomplete({- // shouldn't be required and autocomplete should just accept array of strings, but that fails- // because we have overriden filter() function in init.js- source: labelValues.map(attr => {- return {- label: attr,- value: attr- }- }),- minLength: 0- });+ if (labelValues.length === 0) {+ return;}- $(this).autocomplete("search", $(this).val());- });+ $(this).autocomplete({+ // shouldn't be required and autocomplete should just accept array of strings, but that fails+ // because we have overriden filter() function in init.js+ source: labelValues.map(attr => {+ return {+ label: attr,+ value: attr+ }+ }),+ minLength: 0+ });+ }- $showDialogButton.click(showDialog);+ $(this).autocomplete("search", $(this).val());+});- return {- showDialog- };-})();\ No newline at end of file+$showDialogButton.click(showDialog);++export default {+ showDialog+};\ No newline at end of filediff --git a/src/public/javascripts/dialogs/note_history.js b/src/public/javascripts/dialogs/note_history.jsindex 3c04679aab..7819fd643a 100644--- a/src/public/javascripts/dialogs/note_history.js+++ b/src/public/javascripts/dialogs/note_history.js@@ -1,81 +1,82 @@"use strict";-const noteHistory = (function() {- const $showDialogButton = $("#show-history-button");- const $dialog = $("#note-history-dialog");- const $list = $("#note-history-list");- const $content = $("#note-history-content");- const $title = $("#note-history-title");+import noteEditor from '../note_editor.js';+import utils from '../utils.js';- let historyItems = [];+const $showDialogButton = $("#show-history-button");+const $dialog = $("#note-history-dialog");+const $list = $("#note-history-list");+const $content = $("#note-history-content");+const $title = $("#note-history-title");- async function showCurrentNoteHistory() {- await showNoteHistoryDialog(noteEditor.getCurrentNoteId());- }+let historyItems = [];- async function showNoteHistoryDialog(noteId, noteRevisionId) {- glob.activeDialog = $dialog;+async function showCurrentNoteHistory() {+ await showNoteHistoryDialog(noteEditor.getCurrentNoteId());+}- $dialog.dialog({- modal: true,- width: 800,- height: 700- });+async function showNoteHistoryDialog(noteId, noteRevisionId) {+ glob.activeDialog = $dialog;- $list.empty();- $content.empty();+ $dialog.dialog({+ modal: true,+ width: 800,+ height: 700+ });- historyItems = await server.get('notes-history/' + noteId);+ $list.empty();+ $content.empty();- for (const item of historyItems) {- const dateModified = utils.parseDate(item.dateModifiedFrom);+ historyItems = await server.get('notes-history/' + noteId);- $list.append($('<option>', {- value: item.noteRevisionId,- text: utils.formatDateTime(dateModified)- }));- }+ for (const item of historyItems) {+ const dateModified = utils.parseDate(item.dateModifiedFrom);- if (historyItems.length > 0) {- if (!noteRevisionId) {- noteRevisionId = $list.find("option:first").val();- }+ $list.append($('<option>', {+ value: item.noteRevisionId,+ text: utils.formatDateTime(dateModified)+ }));+ }- $list.val(noteRevisionId).trigger('change');- }- else {- $title.text("No history for this note yet...");+ if (historyItems.length > 0) {+ if (!noteRevisionId) {+ noteRevisionId = $list.find("option:first").val();}++ $list.val(noteRevisionId).trigger('change');+ }+ else {+ $title.text("No history for this note yet...");}+}- $(document).bind('keydown', 'alt+h', e => {- showCurrentNoteHistory();+$(document).bind('keydown', 'alt+h', e => {+ showCurrentNoteHistory();- e.preventDefault();- });+ e.preventDefault();+});- $list.on('change', () => {- const optVal = $list.find(":selected").val();+$list.on('change', () => {+ const optVal = $list.find(":selected").val();- const historyItem = historyItems.find(r => r.noteRevisionId === optVal);+ const historyItem = historyItems.find(r => r.noteRevisionId === optVal);- $title.html(historyItem.title);- $content.html(historyItem.content);- });+ $title.html(historyItem.title);+ $content.html(historyItem.content);+});- $(document).on('click', "a[action='note-history']", event => {- const linkEl = $(event.target);- const noteId = linkEl.attr('note-path');- const noteRevisionId = linkEl.attr('note-history-id');+$(document).on('click', "a[action='note-history']", event => {+ const linkEl = $(event.target);+ const noteId = linkEl.attr('note-path');+ const noteRevisionId = linkEl.attr('note-history-id');- showNoteHistoryDialog(noteId, noteRevisionId);+ showNoteHistoryDialog(noteId, noteRevisionId);- return false;- });+ return false;+});- $showDialogButton.click(showCurrentNoteHistory);+$showDialogButton.click(showCurrentNoteHistory);- return {- showCurrentNoteHistory- };-})();\ No newline at end of file+export default {+ showCurrentNoteHistory+};\ No newline at end of filediff --git a/src/public/javascripts/dialogs/note_source.js b/src/public/javascripts/dialogs/note_source.jsindex c8a05e0f62..327f7c54d5 100644--- a/src/public/javascripts/dialogs/note_source.js+++ b/src/public/javascripts/dialogs/note_source.js@@ -1,60 +1,60 @@"use strict";-const noteSource = (function() {- const $showDialogButton = $("#show-source-button");- const $dialog = $("#note-source-dialog");- const $noteSource = $("#note-source");+import noteEditor from '../note_editor.js';- function showDialog() {- glob.activeDialog = $dialog;+const $showDialogButton = $("#show-source-button");+const $dialog = $("#note-source-dialog");+const $noteSource = $("#note-source");- $dialog.dialog({- modal: true,- width: 800,- height: 500- });+function showDialog() {+ glob.activeDialog = $dialog;- const noteText = noteEditor.getCurrentNote().detail.content;+ $dialog.dialog({+ modal: true,+ width: 800,+ height: 500+ });- $noteSource.text(formatHtml(noteText));- }+ const noteText = noteEditor.getCurrentNote().detail.content;- function formatHtml(str) {- const div = document.createElement('div');- div.innerHTML = str.trim();+ $noteSource.text(formatHtml(noteText));+}- return formatNode(div, 0).innerHTML.trim();- }+function formatHtml(str) {+ const div = document.createElement('div');+ div.innerHTML = str.trim();- function formatNode(node, level) {- const indentBefore = new Array(level++ + 1).join(' ');- const indentAfter = new Array(level - 1).join(' ');- let textNode;+ return formatNode(div, 0).innerHTML.trim();+}- for (let i = 0; i < node.children.length; i++) {- textNode = document.createTextNode('\n' + indentBefore);- node.insertBefore(textNode, node.children[i]);+function formatNode(node, level) {+ const indentBefore = new Array(level++ + 1).join(' ');+ const indentAfter = new Array(level - 1).join(' ');+ let textNode;- formatNode(node.children[i], level);+ for (let i = 0; i < node.children.length; i++) {+ textNode = document.createTextNode('\n' + indentBefore);+ node.insertBefore(textNode, node.children[i]);- if (node.lastElementChild === node.children[i]) {- textNode = document.createTextNode('\n' + indentAfter);- node.appendChild(textNode);- }- }+ formatNode(node.children[i], level);- return node;+ if (node.lastElementChild === node.children[i]) {+ textNode = document.createTextNode('\n' + indentAfter);+ node.appendChild(textNode);+ }}- $(document).bind('keydown', 'ctrl+u', e => {- showDialog();+ return node;+}- e.preventDefault();- });+$(document).bind('keydown', 'ctrl+u', e => {+ showDialog();++ e.preventDefault();+});- $showDialogButton.click(showDialog);+$showDialogButton.click(showDialog);- return {- showDialog- };-})();\ No newline at end of file+export default {+ showDialog+};\ No newline at end of filediff --git a/src/public/javascripts/dialogs/recent_changes.js b/src/public/javascripts/dialogs/recent_changes.jsindex d08c893639..5e4d590231 100644--- a/src/public/javascripts/dialogs/recent_changes.js+++ b/src/public/javascripts/dialogs/recent_changes.js@@ -1,92 +1,93 @@"use strict";-const recentChanges = (function() {- const $showDialogButton = $("#recent-changes-button");- const $dialog = $("#recent-changes-dialog");+import link from '../link.js';+import utils from '../utils.js';- async function showDialog() {- glob.activeDialog = $dialog;+const $showDialogButton = $("#recent-changes-button");+const $dialog = $("#recent-changes-dialog");- $dialog.dialog({- modal: true,- width: 800,- height: 700- });+async function showDialog() {+ glob.activeDialog = $dialog;- const result = await server.get('recent-changes/');+ $dialog.dialog({+ modal: true,+ width: 800,+ height: 700+ });- $dialog.html('');+ const result = await server.get('recent-changes/');- const groupedByDate = groupByDate(result);+ $dialog.html('');- for (const [dateDay, dayChanges] of groupedByDate) {- const changesListEl = $('<ul>');+ const groupedByDate = groupByDate(result);- const dayEl = $('<div>').append($('<b>').html(utils.formatDate(dateDay))).append(changesListEl);+ for (const [dateDay, dayChanges] of groupedByDate) {+ const changesListEl = $('<ul>');- for (const change of dayChanges) {- const formattedTime = utils.formatTime(utils.parseDate(change.dateModifiedTo));+ const dayEl = $('<div>').append($('<b>').html(utils.formatDate(dateDay))).append(changesListEl);- const revLink = $("<a>", {- href: 'javascript:',- text: 'rev'- }).attr('action', 'note-history')- .attr('note-path', change.noteId)- .attr('note-history-id', change.noteRevisionId);+ for (const change of dayChanges) {+ const formattedTime = utils.formatTime(utils.parseDate(change.dateModifiedTo));- let noteLink;+ const revLink = $("<a>", {+ href: 'javascript:',+ text: 'rev'+ }).attr('action', 'note-history')+ .attr('note-path', change.noteId)+ .attr('note-history-id', change.noteRevisionId);- if (change.current_isDeleted) {- noteLink = change.current_title;- }- else {- noteLink = link.createNoteLink(change.noteId, change.title);- }+ let noteLink;- changesListEl.append($('<li>')- .append(formattedTime + ' - ')- .append(noteLink)- .append(' (').append(revLink).append(')'));- }-- $dialog.append(dayEl);- }- }-- function groupByDate(result) {- const groupedByDate = new Map();- const dayCache = {};-- for (const row of result) {- let dateDay = utils.parseDate(row.dateModifiedTo);- dateDay.setHours(0);- dateDay.setMinutes(0);- dateDay.setSeconds(0);- dateDay.setMilliseconds(0);-- // this stupidity is to make sure that we always use the same day object because Map uses only- // reference equality- if (dayCache[dateDay]) {- dateDay = dayCache[dateDay];+ if (change.current_isDeleted) {+ noteLink = change.current_title;}else {- dayCache[dateDay] = dateDay;+ noteLink = link.createNoteLink(change.noteId, change.title);}- if (!groupedByDate.has(dateDay)) {- groupedByDate.set(dateDay, []);- }+ changesListEl.append($('<li>')+ .append(formattedTime + ' - ')+ .append(noteLink)+ .append(' (').append(revLink).append(')'));+ }++ $dialog.append(dayEl);+ }+}++function groupByDate(result) {+ const groupedByDate = new Map();+ const dayCache = {};++ for (const row of result) {+ let dateDay = utils.parseDate(row.dateModifiedTo);+ dateDay.setHours(0);+ dateDay.setMinutes(0);+ dateDay.setSeconds(0);+ dateDay.setMilliseconds(0);++ // this stupidity is to make sure that we always use the same day object because Map uses only+ // reference equality+ if (dayCache[dateDay]) {+ dateDay = dayCache[dateDay];+ }+ else {+ dayCache[dateDay] = dateDay;+ }- groupedByDate.get(dateDay).push(row);+ if (!groupedByDate.has(dateDay)) {+ groupedByDate.set(dateDay, []);}- return groupedByDate;++ groupedByDate.get(dateDay).push(row);}+ return groupedByDate;+}- $(document).bind('keydown', 'alt+r', showDialog);+$(document).bind('keydown', 'alt+r', showDialog);- $showDialogButton.click(showDialog);+$showDialogButton.click(showDialog);- return {- showDialog- };-})();\ No newline at end of file+export default {+ showDialog+};\ No newline at end of filediff --git a/src/public/javascripts/dialogs/recent_notes.js b/src/public/javascripts/dialogs/recent_notes.jsindex a7d3d2a5a4..eff86cec21 100644--- a/src/public/javascripts/dialogs/recent_notes.js+++ b/src/public/javascripts/dialogs/recent_notes.js@@ -1,105 +1,107 @@"use strict";-const recentNotes = (function() {- const $showDialogButton = $("#recent-notes-button");- const $dialog = $("#recent-notes-dialog");- const $searchInput = $('#recent-notes-search-input');+import treeService from '../note_tree.js';+import server from '../server.js';+import messaging from '../messaging.js';++const $showDialogButton = $("#recent-notes-button");+const $dialog = $("#recent-notes-dialog");+const $searchInput = $('#recent-notes-search-input');++// list of recent note paths+let list = [];++async function reload() {+ const result = await server.get('recent-notes');++ list = result.map(r => r.notePath);+}++function addRecentNote(branchId, notePath) {+ setTimeout(async () => {+ // we include the note into recent list only if the user stayed on the note at least 5 seconds+ if (notePath && notePath === treeService.getCurrentNotePath()) {+ const result = await server.put('recent-notes/' + branchId + '/' + encodeURIComponent(notePath));++ list = result.map(r => r.notePath);+ }+ }, 1500);+}++function showDialog() {+ glob.activeDialog = $dialog;++ $dialog.dialog({+ modal: true,+ width: 800,+ height: 100,+ position: { my: "center top+100", at: "top", of: window }+ });- // list of recent note paths- let list = [];+ $searchInput.val('');- async function reload() {- const result = await server.get('recent-notes');+ // remove the current note+ const recNotes = list.filter(note => note !== treeService.getCurrentNotePath());- list = result.map(r => r.notePath);- }+ $searchInput.autocomplete({+ source: recNotes.map(notePath => {+ let noteTitle;- function addRecentNote(branchId, notePath) {- setTimeout(async () => {- // we include the note into recent list only if the user stayed on the note at least 5 seconds- if (notePath && notePath === treeService.getCurrentNotePath()) {- const result = await server.put('recent-notes/' + branchId + '/' + encodeURIComponent(notePath));+ try {+ noteTitle = treeService.getNotePathTitle(notePath);+ }+ catch (e) {+ noteTitle = "[error - can't find note title]";- list = result.map(r => r.notePath);+ messaging.logError("Could not find title for notePath=" + notePath + ", stack=" + e.stack);}- }, 1500);- }-- function showDialog() {- glob.activeDialog = $dialog;-- $dialog.dialog({- modal: true,- width: 800,- height: 100,- position: { my: "center top+100", at: "top", of: window }- });-- $searchInput.val('');-- // remove the current note- const recNotes = list.filter(note => note !== treeService.getCurrentNotePath());-- $searchInput.autocomplete({- source: recNotes.map(notePath => {- let noteTitle;-- try {- noteTitle = treeService.getNotePathTitle(notePath);- }- catch (e) {- noteTitle = "[error - can't find note title]";-- messaging.logError("Could not find title for notePath=" + notePath + ", stack=" + e.stack);- }-- return {- label: noteTitle,- value: notePath- }- }),- minLength: 0,- autoFocus: true,- select: function (event, ui) {- treeService.activateNode(ui.item.value);+ return {+ label: noteTitle,+ value: notePath+ }+ }),+ minLength: 0,+ autoFocus: true,+ select: function (event, ui) {+ treeService.activateNode(ui.item.value);++ $searchInput.autocomplete('destroy');+ $dialog.dialog('close');+ },+ focus: function (event, ui) {+ event.preventDefault();+ },+ close: function (event, ui) {+ if (event.keyCode === 27) { // escape closes dialog$searchInput.autocomplete('destroy');$dialog.dialog('close');- },- focus: function (event, ui) {- event.preventDefault();- },- close: function (event, ui) {- if (event.keyCode === 27) { // escape closes dialog- $searchInput.autocomplete('destroy');- $dialog.dialog('close');- }- else {- // keep autocomplete open- // we're kind of abusing autocomplete to work in a way which it's not designed for- $searchInput.autocomplete("search", "");- }- },- create: () => $searchInput.autocomplete("search", ""),- classes: {- "ui-autocomplete": "recent-notes-autocomplete"}- });- }+ else {+ // keep autocomplete open+ // we're kind of abusing autocomplete to work in a way which it's not designed for+ $searchInput.autocomplete("search", "");+ }+ },+ create: () => $searchInput.autocomplete("search", ""),+ classes: {+ "ui-autocomplete": "recent-notes-autocomplete"+ }+ });+}- reload();+reload();- $(document).bind('keydown', 'ctrl+e', e => {- showDialog();+$(document).bind('keydown', 'ctrl+e', e => {+ showDialog();- e.preventDefault();- });+ e.preventDefault();+});- $showDialogButton.click(showDialog);+$showDialogButton.click(showDialog);- return {- showDialog,- addRecentNote,- reload- };-})();\ No newline at end of file+export default {+ showDialog,+ addRecentNote,+ reload+};\ No newline at end of filediff --git a/src/public/javascripts/dialogs/settings.js b/src/public/javascripts/dialogs/settings.jsindex 05b634e361..9f3253b1a6 100644--- a/src/public/javascripts/dialogs/settings.js+++ b/src/public/javascripts/dialogs/settings.js@@ -1,54 +1,56 @@"use strict";-const settings = (function() {- const $showDialogButton = $("#settings-button");- const $dialog = $("#settings-dialog");- const $tabs = $("#settings-tabs");+import protected_session from '../protected_session.js';+import utils from '../utils.js';+import server from '../server.js';- const settingModules = [];+const $showDialogButton = $("#settings-button");+const $dialog = $("#settings-dialog");+const $tabs = $("#settings-tabs");- function addModule(module) {- settingModules.push(module);- }+const settingModules = [];- async function showDialog() {- glob.activeDialog = $dialog;+function addModule(module) {+ settingModules.push(module);+}- const settings = await server.get('settings');+async function showDialog() {+ glob.activeDialog = $dialog;- $dialog.dialog({- modal: true,- width: 900- });+ const settings = await server.get('settings');- $tabs.tabs();+ $dialog.dialog({+ modal: true,+ width: 900+ });- for (const module of settingModules) {- if (module.settingsLoaded) {- module.settingsLoaded(settings);- }+ $tabs.tabs();++ for (const module of settingModules) {+ if (module.settingsLoaded) {+ module.settingsLoaded(settings);}}+}- async function saveSettings(settingName, settingValue) {- await server.post('settings', {- name: settingName,- value: settingValue- });+async function saveSettings(settingName, settingValue) {+ await server.post('settings', {+ name: settingName,+ value: settingValue+ });- utils.showMessage("Settings change have been saved.");- }+ utils.showMessage("Settings change have been saved.");+}- $showDialogButton.click(showDialog);+$showDialogButton.click(showDialog);- return {- showDialog,- saveSettings,- addModule- };-})();+export default {+ showDialog,+ saveSettings,+ addModule+};-settings.addModule((function() {+addModule((function() {const $form = $("#change-password-form");const $oldPassword = $("#old-password");const $newPassword1 = $("#new-password1");@@ -94,7 +96,7 @@ settings.addModule((function() {};})());-settings.addModule((function() {+addModule((function() {const $form = $("#protected-session-timeout-form");const $protectedSessionTimeout = $("#protected-session-timeout-in-seconds");const settingName = 'protected_session_timeout';@@ -118,7 +120,7 @@ settings.addModule((function() {};})());-settings.addModule((function () {+addModule((function () {const $form = $("#history-snapshot-time-interval-form");const $timeInterval = $("#history-snapshot-time-interval-in-seconds");const settingName = 'history_snapshot_time_interval';@@ -138,7 +140,7 @@ settings.addModule((function () {};})());-settings.addModule((async function () {+addModule((async function () {const $appVersion = $("#app-version");const $dbVersion = $("#db-version");const $buildDate = $("#build-date");@@ -155,7 +157,7 @@ settings.addModule((async function () {return {};})());-settings.addModule((async function () {+addModule((async function () {const $forceFullSyncButton = $("#force-full-sync-button");const $fillSyncRowsButton = $("#fill-sync-rows-button");const $anonymizeButton = $("#anonymize-button");diff --git a/src/public/javascripts/dialogs/sql_console.js b/src/public/javascripts/dialogs/sql_console.jsindex 44306fae9d..77cdd2d35d 100644--- a/src/public/javascripts/dialogs/sql_console.js+++ b/src/public/javascripts/dialogs/sql_console.js@@ -1,106 +1,106 @@"use strict";-const sqlConsole = (function() {- const $dialog = $("#sql-console-dialog");- const $query = $('#sql-console-query');- const $executeButton = $('#sql-console-execute');- const $resultHead = $('#sql-console-results thead');- const $resultBody = $('#sql-console-results tbody');-- let codeEditor;-- function showDialog() {- glob.activeDialog = $dialog;-- $dialog.dialog({- modal: true,- width: $(window).width(),- height: $(window).height(),- open: function() {- initEditor();- }- });- }+import utils from '../utils.js';- async function initEditor() {- if (!codeEditor) {- await utils.requireLibrary(utils.CODE_MIRROR);+const $dialog = $("#sql-console-dialog");+const $query = $('#sql-console-query');+const $executeButton = $('#sql-console-execute');+const $resultHead = $('#sql-console-results thead');+const $resultBody = $('#sql-console-results tbody');- CodeMirror.keyMap.default["Shift-Tab"] = "indentLess";- CodeMirror.keyMap.default["Tab"] = "indentMore";+let codeEditor;- // removing Escape binding so that Escape will propagate to the dialog (which will close on escape)- delete CodeMirror.keyMap.basic["Esc"];+function showDialog() {+ glob.activeDialog = $dialog;- CodeMirror.modeURL = 'libraries/codemirror/mode/%N/%N.js';+ $dialog.dialog({+ modal: true,+ width: $(window).width(),+ height: $(window).height(),+ open: function() {+ initEditor();+ }+ });+}- codeEditor = CodeMirror($query[0], {- value: "",- viewportMargin: Infinity,- indentUnit: 4,- highlightSelectionMatches: {showToken: /\w/, annotateScrollbar: false}- });+async function initEditor() {+ if (!codeEditor) {+ await utils.requireLibrary(utils.CODE_MIRROR);- codeEditor.setOption("mode", "text/x-sqlite");- CodeMirror.autoLoadMode(codeEditor, "sql");- }+ CodeMirror.keyMap.default["Shift-Tab"] = "indentLess";+ CodeMirror.keyMap.default["Tab"] = "indentMore";++ // removing Escape binding so that Escape will propagate to the dialog (which will close on escape)+ delete CodeMirror.keyMap.basic["Esc"];++ CodeMirror.modeURL = 'libraries/codemirror/mode/%N/%N.js';++ codeEditor = CodeMirror($query[0], {+ value: "",+ viewportMargin: Infinity,+ indentUnit: 4,+ highlightSelectionMatches: {showToken: /\w/, annotateScrollbar: false}+ });- codeEditor.focus();+ codeEditor.setOption("mode", "text/x-sqlite");+ CodeMirror.autoLoadMode(codeEditor, "sql");}- async function execute(e) {- // stop from propagating upwards (dangerous especially with ctrl+enter executable javascript notes)- e.preventDefault();- e.stopPropagation();+ codeEditor.focus();+}- const sqlQuery = codeEditor.getValue();+async function execute(e) {+ // stop from propagating upwards (dangerous especially with ctrl+enter executable javascript notes)+ e.preventDefault();+ e.stopPropagation();- const result = await server.post("sql/execute", {- query: sqlQuery- });+ const sqlQuery = codeEditor.getValue();- if (!result.success) {- utils.showError(result.error);- return;- }- else {- utils.showMessage("Query was executed successfully.");- }+ const result = await server.post("sql/execute", {+ query: sqlQuery+ });- const rows = result.rows;+ if (!result.success) {+ utils.showError(result.error);+ return;+ }+ else {+ utils.showMessage("Query was executed successfully.");+ }- $resultHead.empty();- $resultBody.empty();+ const rows = result.rows;- if (rows.length > 0) {- const result = rows[0];- const rowEl = $("<tr>");+ $resultHead.empty();+ $resultBody.empty();- for (const key in result) {- rowEl.append($("<th>").html(key));- }+ if (rows.length > 0) {+ const result = rows[0];+ const rowEl = $("<tr>");- $resultHead.append(rowEl);+ for (const key in result) {+ rowEl.append($("<th>").html(key));}- for (const result of rows) {- const rowEl = $("<tr>");+ $resultHead.append(rowEl);+ }- for (const key in result) {- rowEl.append($("<td>").html(result[key]));- }+ for (const result of rows) {+ const rowEl = $("<tr>");- $resultBody.append(rowEl);+ for (const key in result) {+ rowEl.append($("<td>").html(result[key]));}++ $resultBody.append(rowEl);}+}- $(document).bind('keydown', 'alt+o', showDialog);+$(document).bind('keydown', 'alt+o', showDialog);- $query.bind('keydown', 'ctrl+return', execute);+$query.bind('keydown', 'ctrl+return', execute);- $executeButton.click(execute);+$executeButton.click(execute);- return {- showDialog- };-})();\ No newline at end of file+export default {+ showDialog+};\ No newline at end of filediff --git a/src/public/javascripts/drag_and_drop.js b/src/public/javascripts/drag_and_drop.jsindex e27eb019af..252bc01602 100644--- a/src/public/javascripts/drag_and_drop.js+++ b/src/public/javascripts/drag_and_drop.js@@ -1,5 +1,8 @@"use strict";+import treeService from './note_tree.js';+import treeChanges from './tree_changes.js';+const dragAndDropSetup = {autoExpandMS: 600,draggable: { // modify default jQuery draggable options@@ -65,3 +68,5 @@ const dragAndDropSetup = {}}};++export default dragAndDropSetup;\ No newline at end of filediff --git a/src/public/javascripts/export.js b/src/public/javascripts/export.jsindex 5cd62052b7..9c105b58a9 100644--- a/src/public/javascripts/export.js+++ b/src/public/javascripts/export.js@@ -1,39 +1,41 @@"use strict";-const exportService = (function () {- function exportSubTree(noteId) {- const url = utils.getHost() + "/api/export/" + noteId + "?protectedSessionId="- + encodeURIComponent(protected_session.getProtectedSessionId());+import treeService from './note_tree.js';+import protected_session from './protected_session.js';+import utils from './utils.js';- utils.download(url);- }+function exportSubTree(noteId) {+ const url = utils.getHost() + "/api/export/" + noteId + "?protectedSessionId="+ + encodeURIComponent(protected_session.getProtectedSessionId());- let importNoteId;+ utils.download(url);+}- function importSubTree(noteId) {- importNoteId = noteId;+let importNoteId;- $("#import-upload").trigger('click');- }+function importSubTree(noteId) {+ importNoteId = noteId;- $("#import-upload").change(async function() {- const formData = new FormData();- formData.append('upload', this.files[0]);+ $("#import-upload").trigger('click');+}- await $.ajax({- url: baseApiUrl + 'import/' + importNoteId,- headers: server.getHeaders(),- data: formData,- type: 'POST',- contentType: false, // NEEDED, DON'T OMIT THIS- processData: false, // NEEDED, DON'T OMIT THIS- });+$("#import-upload").change(async function() {+ const formData = new FormData();+ formData.append('upload', this.files[0]);- await treeService.reload();+ await $.ajax({+ url: baseApiUrl + 'import/' + importNoteId,+ headers: server.getHeaders(),+ data: formData,+ type: 'POST',+ contentType: false, // NEEDED, DON'T OMIT THIS+ processData: false, // NEEDED, DON'T OMIT THIS});- return {- exportSubTree,- importSubTree- };-})();\ No newline at end of file+ await treeService.reload();+});++export default {+ exportSubTree,+ importSubTree+};\ No newline at end of filediff --git a/src/public/javascripts/init.js b/src/public/javascripts/init.jsindex 2c3b7ad6c3..4c1054e964 100644--- a/src/public/javascripts/init.js+++ b/src/public/javascripts/init.js@@ -1,252 +1,258 @@"use strict";-const initService = (function() {- // hot keys are active also inside inputs and content editables- jQuery.hotkeys.options.filterInputAcceptingElements = false;- jQuery.hotkeys.options.filterContentEditable = false;- jQuery.hotkeys.options.filterTextInputs = false;+import treeService from './note_tree.js';+import link from './link.js';+import messaging from './messaging.js';+import noteEditor from './note_editor.js';+import treeUtils from './tree_utils.js';+import utils from './utils.js';+import server from './server.js';- $(document).bind('keydown', 'alt+m', e => {- $(".hide-toggle").toggleClass("suppressed");+// hot keys are active also inside inputs and content editables+jQuery.hotkeys.options.filterInputAcceptingElements = false;+jQuery.hotkeys.options.filterContentEditable = false;+jQuery.hotkeys.options.filterTextInputs = false;- e.preventDefault();- });+$(document).bind('keydown', 'alt+m', e => {+ $(".hide-toggle").toggleClass("suppressed");- // hide (toggle) everything except for the note content for distraction free writing- $(document).bind('keydown', 'alt+t', e => {- const date = new Date();- const dateString = utils.formatDateTime(date);+ e.preventDefault();+});- link.addTextToEditor(dateString);+// hide (toggle) everything except for the note content for distraction free writing+$(document).bind('keydown', 'alt+t', e => {+ const date = new Date();+ const dateString = utils.formatDateTime(date);- e.preventDefault();- });+ link.addTextToEditor(dateString);- $(document).bind('keydown', 'f5', () => {- utils.reloadApp();+ e.preventDefault();+});- return false;- });+$(document).bind('keydown', 'f5', () => {+ utils.reloadApp();- $(document).bind('keydown', 'ctrl+r', () => {- utils.reloadApp();+ return false;+});- return false;- });+$(document).bind('keydown', 'ctrl+r', () => {+ utils.reloadApp();- $(document).bind('keydown', 'ctrl+shift+i', () => {- if (utils.isElectron()) {- require('electron').remote.getCurrentWindow().toggleDevTools();+ return false;+});- return false;- }- });+$(document).bind('keydown', 'ctrl+shift+i', () => {+ if (utils.isElectron()) {+ require('electron').remote.getCurrentWindow().toggleDevTools();- $(document).bind('keydown', 'ctrl+f', () => {- if (utils.isElectron()) {- const searchInPage = require('electron-in-page-search').default;- const remote = require('electron').remote;+ return false;+ }+});- const inPageSearch = searchInPage(remote.getCurrentWebContents());+$(document).bind('keydown', 'ctrl+f', () => {+ if (utils.isElectron()) {+ const searchInPage = require('electron-in-page-search').default;+ const remote = require('electron').remote;- inPageSearch.openSearchWindow();+ const inPageSearch = searchInPage(remote.getCurrentWebContents());- return false;- }- });+ inPageSearch.openSearchWindow();- $(document).bind('keydown', "ctrl+shift+up", () => {- const node = treeService.getCurrentNode();- node.navigate($.ui.keyCode.UP, true);+ return false;+ }+});- $("#note-detail").focus();+$(document).bind('keydown', "ctrl+shift+up", () => {+ const node = treeService.getCurrentNode();+ node.navigate($.ui.keyCode.UP, true);- return false;- });+ $("#note-detail").focus();- $(document).bind('keydown', "ctrl+shift+down", () => {- const node = treeService.getCurrentNode();- node.navigate($.ui.keyCode.DOWN, true);+ return false;+});- $("#note-detail").focus();+$(document).bind('keydown', "ctrl+shift+down", () => {+ const node = treeService.getCurrentNode();+ node.navigate($.ui.keyCode.DOWN, true);- return false;- });+ $("#note-detail").focus();- $(document).bind('keydown', 'ctrl+-', () => {- if (utils.isElectron()) {- const webFrame = require('electron').webFrame;+ return false;+});- if (webFrame.getZoomFactor() > 0.2) {- webFrame.setZoomFactor(webFrame.getZoomFactor() - 0.1);- }+$(document).bind('keydown', 'ctrl+-', () => {+ if (utils.isElectron()) {+ const webFrame = require('electron').webFrame;- return false;+ if (webFrame.getZoomFactor() > 0.2) {+ webFrame.setZoomFactor(webFrame.getZoomFactor() - 0.1);}- });- $(document).bind('keydown', 'ctrl+=', () => {- if (utils.isElectron()) {- const webFrame = require('electron').webFrame;+ return false;+ }+});- webFrame.setZoomFactor(webFrame.getZoomFactor() + 0.1);+$(document).bind('keydown', 'ctrl+=', () => {+ if (utils.isElectron()) {+ const webFrame = require('electron').webFrame;- return false;- }- });+ webFrame.setZoomFactor(webFrame.getZoomFactor() + 0.1);- $("#note-title").bind('keydown', 'return', () => $("#note-detail").focus());+ return false;+ }+});- $(window).on('beforeunload', () => {- // this makes sure that when user e.g. reloads the page or navigates away from the page, the note's content is saved- // this sends the request asynchronously and doesn't wait for result- noteEditor.saveNoteIfChanged();- });+$("#note-title").bind('keydown', 'return', () => $("#note-detail").focus());- // Overrides the default autocomplete filter function to search for matched on atleast 1 word in each of the input term's words- $.ui.autocomplete.filter = (array, terms) => {- if (!terms) {- return array;- }+$(window).on('beforeunload', () => {+ // this makes sure that when user e.g. reloads the page or navigates away from the page, the note's content is saved+ // this sends the request asynchronously and doesn't wait for result+ noteEditor.saveNoteIfChanged();+});- const startDate = new Date();+// Overrides the default autocomplete filter function to search for matched on atleast 1 word in each of the input term's words+$.ui.autocomplete.filter = (array, terms) => {+ if (!terms) {+ return array;+ }- const results = [];- const tokens = terms.toLowerCase().split(" ");+ const startDate = new Date();- for (const item of array) {- const lcLabel = item.label.toLowerCase();+ const results = [];+ const tokens = terms.toLowerCase().split(" ");- const found = tokens.every(token => lcLabel.indexOf(token) !== -1);- if (!found) {- continue;- }+ for (const item of array) {+ const lcLabel = item.label.toLowerCase();- // this is not completely correct and might cause minor problems with note with names containing this " / "- const lastSegmentIndex = lcLabel.lastIndexOf(" / ");+ const found = tokens.every(token => lcLabel.indexOf(token) !== -1);+ if (!found) {+ continue;+ }++ // this is not completely correct and might cause minor problems with note with names containing this " / "+ const lastSegmentIndex = lcLabel.lastIndexOf(" / ");- if (lastSegmentIndex !== -1) {- const lastSegment = lcLabel.substr(lastSegmentIndex + 3);+ if (lastSegmentIndex !== -1) {+ const lastSegment = lcLabel.substr(lastSegmentIndex + 3);- // at least some token needs to be in the last segment (leaf note), otherwise this- // particular note is not that interesting (query is satisfied by parent note)- const foundInLastSegment = tokens.some(token => lastSegment.indexOf(token) !== -1);+ // at least some token needs to be in the last segment (leaf note), otherwise this+ // particular note is not that interesting (query is satisfied by parent note)+ const foundInLastSegment = tokens.some(token => lastSegment.indexOf(token) !== -1);- if (!foundInLastSegment) {- continue;- }+ if (!foundInLastSegment) {+ continue;}+ }- results.push(item);+ results.push(item);- if (results.length > 100) {- break;- }+ if (results.length > 100) {+ break;}+ }- console.log("Search took " + (new Date().getTime() - startDate.getTime()) + "ms");+ console.log("Search took " + (new Date().getTime() - startDate.getTime()) + "ms");- return results;- };+ return results;+};- $(document).tooltip({- items: "#note-detail a",- content: function(callback) {- const notePath = link.getNotePathFromLink($(this).attr("href"));+$(document).tooltip({+ items: "#note-detail a",+ content: function(callback) {+ const notePath = link.getNotePathFromLink($(this).attr("href"));- if (notePath !== null) {- const noteId = treeUtils.getNoteIdFromNotePath(notePath);+ if (notePath !== null) {+ const noteId = treeUtils.getNoteIdFromNotePath(notePath);- noteEditor.loadNote(noteId).then(note => callback(note.detail.content));- }- },- close: function(event, ui)- {- ui.tooltip.hover(function()- {- $(this).stop(true).fadeTo(400, 1);- },- function()+ noteEditor.loadNote(noteId).then(note => callback(note.detail.content));+ }+ },+ close: function(event, ui)+ {+ ui.tooltip.hover(function()+ {+ $(this).stop(true).fadeTo(400, 1);+ },+ function()+ {+ $(this).fadeOut('400', function(){- $(this).fadeOut('400', function()- {- $(this).remove();- });+ $(this).remove();});- }- });+ });+ }+});- window.onerror = function (msg, url, lineNo, columnNo, error) {- const string = msg.toLowerCase();+window.onerror = function (msg, url, lineNo, columnNo, error) {+ const string = msg.toLowerCase();- let message = "Uncaught error: ";+ let message = "Uncaught error: ";- if (string.indexOf("script error") > -1){- message += 'No details available';- }- else {- message += [- 'Message: ' + msg,- 'URL: ' + url,- 'Line: ' + lineNo,- 'Column: ' + columnNo,- 'Error object: ' + JSON.stringify(error)- ].join(' - ');- }+ if (string.indexOf("script error") > -1){+ message += 'No details available';+ }+ else {+ message += [+ 'Message: ' + msg,+ 'URL: ' + url,+ 'Line: ' + lineNo,+ 'Column: ' + columnNo,+ 'Error object: ' + JSON.stringify(error)+ ].join(' - ');+ }- messaging.logError(message);+ messaging.logError(message);- return false;- };+ return false;+};- $("#logout-button").toggle(!utils.isElectron());+$("#logout-button").toggle(!utils.isElectron());- $(document).ready(() => {- server.get("script/startup").then(scriptBundles => {- for (const bundle of scriptBundles) {- utils.executeBundle(bundle);- }- });+$(document).ready(() => {+ server.get("script/startup").then(scriptBundles => {+ for (const bundle of scriptBundles) {+ utils.executeBundle(bundle);+ }});+});- if (utils.isElectron()) {- require('electron').ipcRenderer.on('create-day-sub-note', async function(event, parentNoteId) {- // this might occur when day note had to be created- if (!await treeService.noteExists(parentNoteId)) {- await treeService.reload();- }+if (utils.isElectron()) {+ require('electron').ipcRenderer.on('create-day-sub-note', async function(event, parentNoteId) {+ // this might occur when day note had to be created+ if (!await treeService.noteExists(parentNoteId)) {+ await treeService.reload();+ }- await treeService.activateNode(parentNoteId);+ await treeService.activateNode(parentNoteId);- setTimeout(() => {- const node = treeService.getCurrentNode();+ setTimeout(() => {+ const node = treeService.getCurrentNode();- treeService.createNote(node, node.data.noteId, 'into', node.data.isProtected);- }, 500);- });- }+ treeService.createNote(node, node.data.noteId, 'into', node.data.isProtected);+ }, 500);+ });+}- function uploadAttachment() {- $("#attachment-upload").trigger('click');- }+function uploadAttachment() {+ $("#attachment-upload").trigger('click');+}- $("#upload-attachment-button").click(uploadAttachment);+$("#upload-attachment-button").click(uploadAttachment);- $("#attachment-upload").change(async function() {- const formData = new FormData();- formData.append('upload', this.files[0]);+$("#attachment-upload").change(async function() {+ const formData = new FormData();+ formData.append('upload', this.files[0]);- const resp = await $.ajax({- url: baseApiUrl + 'attachments/upload/' + noteEditor.getCurrentNoteId(),- headers: server.getHeaders(),- data: formData,- type: 'POST',- contentType: false, // NEEDED, DON'T OMIT THIS- processData: false, // NEEDED, DON'T OMIT THIS- });+ const resp = await $.ajax({+ url: baseApiUrl + 'attachments/upload/' + noteEditor.getCurrentNoteId(),+ headers: server.getHeaders(),+ data: formData,+ type: 'POST',+ contentType: false, // NEEDED, DON'T OMIT THIS+ processData: false, // NEEDED, DON'T OMIT THIS+ });- await treeService.reload();+ await treeService.reload();- await treeService.activateNode(resp.noteId);- });-})();+ await treeService.activateNode(resp.noteId);+});diff --git a/src/public/javascripts/link.js b/src/public/javascripts/link.jsindex 25b2961def..c06c855494 100644--- a/src/public/javascripts/link.js+++ b/src/public/javascripts/link.js@@ -1,103 +1,105 @@"use strict";-const link = (function() {- function getNotePathFromLink(url) {- const notePathMatch = /#([A-Za-z0-9/]+)$/.exec(url);+import treeService from './note_tree.js';+import noteEditor from './note_editor.js';+import treeUtils from './tree_utils.js';- if (notePathMatch === null) {- return null;- }- else {- return notePathMatch[1];- }- }-- function getNodePathFromLabel(label) {- const notePathMatch = / \(([A-Za-z0-9/]+)\)/.exec(label);-- if (notePathMatch !== null) {- return notePathMatch[1];- }+function getNotePathFromLink(url) {+ const notePathMatch = /#([A-Za-z0-9/]+)$/.exec(url);+ if (notePathMatch === null) {return null;}+ else {+ return notePathMatch[1];+ }+}- function createNoteLink(notePath, noteTitle) {- if (!noteTitle) {- const noteId = treeUtils.getNoteIdFromNotePath(notePath);+function getNodePathFromLabel(label) {+ const notePathMatch = / \(([A-Za-z0-9/]+)\)/.exec(label);- noteTitle = treeService.getNoteTitle(noteId);- }+ if (notePathMatch !== null) {+ return notePathMatch[1];+ }- const noteLink = $("<a>", {- href: 'javascript:',- text: noteTitle- }).attr('action', 'note')- .attr('note-path', notePath);+ return null;+}- return noteLink;- }+function createNoteLink(notePath, noteTitle) {+ if (!noteTitle) {+ const noteId = treeUtils.getNoteIdFromNotePath(notePath);- function goToLink(e) {- e.preventDefault();+ noteTitle = treeService.getNoteTitle(noteId);+ }- const $link = $(e.target);- let notePath = $link.attr("note-path");+ const noteLink = $("<a>", {+ href: 'javascript:',+ text: noteTitle+ }).attr('action', 'note')+ .attr('note-path', notePath);- if (!notePath) {- const address = $link.attr("note-path") ? $link.attr("note-path") : $link.attr('href');+ return noteLink;+}- if (!address) {- return;- }+function goToLink(e) {+ e.preventDefault();- if (address.startsWith('http')) {- window.open(address, '_blank');+ const $link = $(e.target);+ let notePath = $link.attr("note-path");- return;- }+ if (!notePath) {+ const address = $link.attr("note-path") ? $link.attr("note-path") : $link.attr('href');- notePath = getNotePathFromLink(address);+ if (!address) {+ return;}- treeService.activateNode(notePath);+ if (address.startsWith('http')) {+ window.open(address, '_blank');- // this is quite ugly hack, but it seems like we can't close the tooltip otherwise- $("[role='tooltip']").remove();-- if (glob.activeDialog) {- try {- glob.activeDialog.dialog('close');- }- catch (e) {}+ return;}- }- function addLinkToEditor(linkTitle, linkHref) {- const editor = noteEditor.getEditor();- const doc = editor.document;-- doc.enqueueChanges(() => editor.data.insertLink(linkTitle, linkHref), doc.selection);+ notePath = getNotePathFromLink(address);}- function addTextToEditor(text) {- const editor = noteEditor.getEditor();- const doc = editor.document;+ treeService.activateNode(notePath);- doc.enqueueChanges(() => editor.data.insertText(text), doc.selection);- }+ // this is quite ugly hack, but it seems like we can't close the tooltip otherwise+ $("[role='tooltip']").remove();- // when click on link popup, in case of internal link, just go the the referenced note instead of default behavior- // of opening the link in new window/tab- $(document).on('click', "a[action='note']", goToLink);- $(document).on('click', 'div.popover-content a, div.ui-tooltip-content a', goToLink);- $(document).on('dblclick', '#note-detail a', goToLink);-- return {- getNodePathFromLabel,- getNotePathFromLink,- createNoteLink,- addLinkToEditor,- addTextToEditor- };-})();\ No newline at end of file+ if (glob.activeDialog) {+ try {+ glob.activeDialog.dialog('close');+ }+ catch (e) {}+ }+}++function addLinkToEditor(linkTitle, linkHref) {+ const editor = noteEditor.getEditor();+ const doc = editor.document;++ doc.enqueueChanges(() => editor.data.insertLink(linkTitle, linkHref), doc.selection);+}++function addTextToEditor(text) {+ const editor = noteEditor.getEditor();+ const doc = editor.document;++ doc.enqueueChanges(() => editor.data.insertText(text), doc.selection);+}++// when click on link popup, in case of internal link, just go the the referenced note instead of default behavior+// of opening the link in new window/tab+$(document).on('click', "a[action='note']", goToLink);+$(document).on('click', 'div.popover-content a, div.ui-tooltip-content a', goToLink);+$(document).on('dblclick', '#note-detail a', goToLink);++export default {+ getNodePathFromLabel,+ getNotePathFromLink,+ createNoteLink,+ addLinkToEditor,+ addTextToEditor+};\ No newline at end of filediff --git a/src/public/javascripts/messaging.js b/src/public/javascripts/messaging.jsindex 61d6cbca46..3bc626c101 100644--- a/src/public/javascripts/messaging.js+++ b/src/public/javascripts/messaging.js@@ -1,115 +1,118 @@"use strict";-const messaging = (function() {- const $changesToPushCount = $("#changes-to-push-count");-- function logError(message) {- console.log(utils.now(), message); // needs to be separate from .trace()- console.trace();-- if (ws && ws.readyState === 1) {- ws.send(JSON.stringify({- type: 'log-error',- error: message- }));- }- }-- function messageHandler(event) {- const message = JSON.parse(event.data);+import treeService from './note_tree.js';+import noteEditor from './note_editor.js';+import sync from './sync.js';+import utils from './utils.js';- if (message.type === 'sync') {- lastPingTs = new Date().getTime();+const $changesToPushCount = $("#changes-to-push-count");- if (message.data.length > 0) {- console.log(utils.now(), "Sync data: ", message.data);+function logError(message) {+ console.log(utils.now(), message); // needs to be separate from .trace()+ console.trace();- lastSyncId = message.data[message.data.length - 1].id;- }+ if (ws && ws.readyState === 1) {+ ws.send(JSON.stringify({+ type: 'log-error',+ error: message+ }));+ }+}- const syncData = message.data.filter(sync => sync.sourceId !== glob.sourceId);+function messageHandler(event) {+ const message = JSON.parse(event.data);- if (syncData.some(sync => sync.entityName === 'branches')- || syncData.some(sync => sync.entityName === 'notes')) {+ if (message.type === 'sync') {+ lastPingTs = new Date().getTime();- console.log(utils.now(), "Reloading tree because of background changes");+ if (message.data.length > 0) {+ console.log(utils.now(), "Sync data: ", message.data);- treeService.reload();- }+ lastSyncId = message.data[message.data.length - 1].id;+ }- if (syncData.some(sync => sync.entityName === 'notes' && sync.entityId === noteEditor.getCurrentNoteId())) {- utils.showMessage('Reloading note because of background changes');+ const syncData = message.data.filter(sync => sync.sourceId !== glob.sourceId);- noteEditor.reload();- }+ if (syncData.some(sync => sync.entityName === 'branches')+ || syncData.some(sync => sync.entityName === 'notes')) {- if (syncData.some(sync => sync.entityName === 'recent_notes')) {- console.log(utils.now(), "Reloading recent notes because of background changes");+ console.log(utils.now(), "Reloading tree because of background changes");- recentNotes.reload();- }+ treeService.reload();+ }- // we don't detect image changes here since images themselves are immutable and references should be- // updated in note detail as well+ if (syncData.some(sync => sync.entityName === 'notes' && sync.entityId === noteEditor.getCurrentNoteId())) {+ utils.showMessage('Reloading note because of background changes');- $changesToPushCount.html(message.changesToPushCount);- }- else if (message.type === 'sync-hash-check-failed') {- utils.utils.showError("Sync check failed!", 60000);+ noteEditor.reload();}- else if (message.type === 'consistency-checks-failed') {- utils.showError("Consistency checks failed! See logs for details.", 50 * 60000);- }- }- function connectWebSocket() {- const protocol = document.location.protocol === 'https:' ? 'wss' : 'ws';+ if (syncData.some(sync => sync.entityName === 'recent_notes')) {+ console.log(utils.now(), "Reloading recent notes because of background changes");- // use wss for secure messaging- const ws = new WebSocket(protocol + "://" + location.host);- ws.onopen = event => console.log(utils.now(), "Connected to server with WebSocket");- ws.onmessage = messageHandler;- ws.onclose = function(){- // Try to reconnect in 5 seconds- setTimeout(() => connectWebSocket(), 5000);- };+ recentNotes.reload();+ }++ // we don't detect image changes here since images themselves are immutable and references should be+ // updated in note detail as well- return ws;+ $changesToPushCount.html(message.changesToPushCount);+ }+ else if (message.type === 'sync-hash-check-failed') {+ utils.utils.showError("Sync check failed!", 60000);}+ else if (message.type === 'consistency-checks-failed') {+ utils.showError("Consistency checks failed! See logs for details.", 50 * 60000);+ }+}++function connectWebSocket() {+ const protocol = document.location.protocol === 'https:' ? 'wss' : 'ws';++ // use wss for secure messaging+ const ws = new WebSocket(protocol + "://" + location.host);+ ws.onopen = event => console.log(utils.now(), "Connected to server with WebSocket");+ ws.onmessage = messageHandler;+ ws.onclose = function(){+ // Try to reconnect in 5 seconds+ setTimeout(() => connectWebSocket(), 5000);+ };- const ws = connectWebSocket();-- let lastSyncId = glob.maxSyncIdAtLoad;- let lastPingTs = new Date().getTime();- let connectionBrokenNotification = null;-- setInterval(async () => {- if (new Date().getTime() - lastPingTs > 30000) {- if (!connectionBrokenNotification) {- connectionBrokenNotification = $.notify({- // options- message: "Lost connection to server"- },{- // settings- type: 'danger',- delay: 100000000 // keep it until we explicitly close it- });- }+ return ws;+}++const ws = connectWebSocket();++let lastSyncId = glob.maxSyncIdAtLoad;+let lastPingTs = new Date().getTime();+let connectionBrokenNotification = null;++setInterval(async () => {+ if (new Date().getTime() - lastPingTs > 30000) {+ if (!connectionBrokenNotification) {+ connectionBrokenNotification = $.notify({+ // options+ message: "Lost connection to server"+ },{+ // settings+ type: 'danger',+ delay: 100000000 // keep it until we explicitly close it+ });}- else if (connectionBrokenNotification) {- await connectionBrokenNotification.close();- connectionBrokenNotification = null;+ }+ else if (connectionBrokenNotification) {+ await connectionBrokenNotification.close();+ connectionBrokenNotification = null;- utils.showMessage("Re-connected to server");- }+ utils.showMessage("Re-connected to server");+ }- ws.send(JSON.stringify({- type: 'ping',- lastSyncId: lastSyncId- }));- }, 1000);+ ws.send(JSON.stringify({+ type: 'ping',+ lastSyncId: lastSyncId+ }));+}, 1000);- return {- logError- };-})();\ No newline at end of file+export default {+ logError+};\ No newline at end of filediff --git a/src/public/javascripts/note_editor.js b/src/public/javascripts/note_editor.jsindex 6e86c19ece..e2f1e06688 100644--- a/src/public/javascripts/note_editor.js+++ b/src/public/javascripts/note_editor.js@@ -1,400 +1,404 @@"use strict";-const noteEditor = (function() {- const $noteTitle = $("#note-title");-- const $noteDetail = $('#note-detail');- const $noteDetailCode = $('#note-detail-code');- const $noteDetailSearch = $('#note-detail-search');- const $noteDetailRender = $('#note-detail-render');- const $noteDetailAttachment = $('#note-detail-attachment');-- const $protectButton = $("#protect-button");- const $unprotectButton = $("#unprotect-button");- const $noteDetailWrapper = $("#note-detail-wrapper");- const $noteIdDisplay = $("#note-id-display");- const $labelList = $("#label-list");- const $labelListInner = $("#label-list-inner");- const $attachmentFileName = $("#attachment-filename");- const $attachmentFileType = $("#attachment-filetype");- const $attachmentFileSize = $("#attachment-filesize");- const $attachmentDownload = $("#attachment-download");- const $attachmentOpen = $("#attachment-open");- const $searchString = $("#search-string");-- const $executeScriptButton = $("#execute-script-button");+import treeService from './note_tree.js';+import noteType from './note_type.js';+import protected_session from './protected_session.js';+import utils from './utils.js';+import server from './server.js';++const $noteTitle = $("#note-title");++const $noteDetail = $('#note-detail');+const $noteDetailCode = $('#note-detail-code');+const $noteDetailSearch = $('#note-detail-search');+const $noteDetailRender = $('#note-detail-render');+const $noteDetailAttachment = $('#note-detail-attachment');++const $protectButton = $("#protect-button");+const $unprotectButton = $("#unprotect-button");+const $noteDetailWrapper = $("#note-detail-wrapper");+const $noteIdDisplay = $("#note-id-display");+const $labelList = $("#label-list");+const $labelListInner = $("#label-list-inner");+const $attachmentFileName = $("#attachment-filename");+const $attachmentFileType = $("#attachment-filetype");+const $attachmentFileSize = $("#attachment-filesize");+const $attachmentDownload = $("#attachment-download");+const $attachmentOpen = $("#attachment-open");+const $searchString = $("#search-string");++const $executeScriptButton = $("#execute-script-button");++let editor = null;+let codeEditor = null;++let currentNote = null;++let noteChangeDisabled = false;++let isNoteChanged = false;++function getCurrentNote() {+ return currentNote;+}++function getCurrentNoteId() {+ return currentNote ? currentNote.detail.noteId : null;+}++function noteChanged() {+ if (noteChangeDisabled) {+ return;+ }- let editor = null;- let codeEditor = null;+ isNoteChanged = true;+}- let currentNote = null;+async function reload() {+ // no saving here- let noteChangeDisabled = false;+ await loadNoteToEditor(getCurrentNoteId());+}- let isNoteChanged = false;+async function switchToNote(noteId) {+ if (getCurrentNoteId() !== noteId) {+ await saveNoteIfChanged();- function getCurrentNote() {- return currentNote;+ await loadNoteToEditor(noteId);}+}- function getCurrentNoteId() {- return currentNote ? currentNote.detail.noteId : null;+async function saveNoteIfChanged() {+ if (!isNoteChanged) {+ return;}- function noteChanged() {- if (noteChangeDisabled) {- return;- }+ const note = getCurrentNote();- isNoteChanged = true;- }+ updateNoteFromInputs(note);- async function reload() {- // no saving here+ await saveNoteToServer(note);- await loadNoteToEditor(getCurrentNoteId());+ if (note.detail.isProtected) {+ protected_session.touchProtectedSession();}+}- async function switchToNote(noteId) {- if (getCurrentNoteId() !== noteId) {- await saveNoteIfChanged();+function updateNoteFromInputs(note) {+ if (note.detail.type === 'text') {+ let content = editor.getData();- await loadNoteToEditor(noteId);+ // if content is only tags/whitespace (typically <p> </p>), then just make it empty+ // this is important when setting new note to code+ if (jQuery(content).text().trim() === '' && !content.includes("<img")) {+ content = '';}++ note.detail.content = content;+ }+ else if (note.detail.type === 'code') {+ note.detail.content = codeEditor.getValue();+ }+ else if (note.detail.type === 'search') {+ note.detail.content = JSON.stringify({+ searchString: $searchString.val()+ });+ }+ else if (note.detail.type === 'render' || note.detail.type === 'file') {+ // nothing+ }+ else {+ utils.throwError("Unrecognized type: " + note.detail.type);}- async function saveNoteIfChanged() {- if (!isNoteChanged) {- return;- }+ const title = $noteTitle.val();- const note = noteEditor.getCurrentNote();+ note.detail.title = title;- updateNoteFromInputs(note);+ treeService.setNoteTitle(note.detail.noteId, title);+}- await saveNoteToServer(note);+async function saveNoteToServer(note) {+ await server.put('notes/' + note.detail.noteId, note);- if (note.detail.isProtected) {- protected_session.touchProtectedSession();- }- }+ isNoteChanged = false;- function updateNoteFromInputs(note) {- if (note.detail.type === 'text') {- let content = editor.getData();+ utils.showMessage("Saved!");+}- // if content is only tags/whitespace (typically <p> </p>), then just make it empty- // this is important when setting new note to code- if (jQuery(content).text().trim() === '' && !content.includes("<img")) {- content = '';- }+function setNoteBackgroundIfProtected(note) {+ const isProtected = !!note.detail.isProtected;- note.detail.content = content;- }- else if (note.detail.type === 'code') {- note.detail.content = codeEditor.getValue();- }- else if (note.detail.type === 'search') {- note.detail.content = JSON.stringify({- searchString: $searchString.val()- });- }- else if (note.detail.type === 'render' || note.detail.type === 'file') {- // nothing- }- else {- utils.throwError("Unrecognized type: " + note.detail.type);- }-- const title = $noteTitle.val();-- note.detail.title = title;-- treeService.setNoteTitle(note.detail.noteId, title);- }+ $noteDetailWrapper.toggleClass("protected", isProtected);+ $protectButton.toggle(!isProtected);+ $unprotectButton.toggle(isProtected);+}- async function saveNoteToServer(note) {- await server.put('notes/' + note.detail.noteId, note);+let isNewNoteCreated = false;- isNoteChanged = false;+function newNoteCreated() {+ isNewNoteCreated = true;+}- utils.showMessage("Saved!");- }+async function setContent(content) {+ if (currentNote.detail.type === 'text') {+ if (!editor) {+ await utils.requireLibrary(utils.CKEDITOR);- function setNoteBackgroundIfProtected(note) {- const isProtected = !!note.detail.isProtected;+ editor = await BalloonEditor.create($noteDetail[0], {});- $noteDetailWrapper.toggleClass("protected", isProtected);- $protectButton.toggle(!isProtected);- $unprotectButton.toggle(isProtected);- }+ editor.document.on('change', noteChanged);+ }- let isNewNoteCreated = false;+ // temporary workaround for https://github.com/ckeditor/ckeditor5-enter/issues/49+ editor.setData(content ? content : "<p></p>");- function newNoteCreated() {- isNewNoteCreated = true;+ $noteDetail.show();}+ else if (currentNote.detail.type === 'code') {+ if (!codeEditor) {+ await utils.requireLibrary(utils.CODE_MIRROR);++ CodeMirror.keyMap.default["Shift-Tab"] = "indentLess";+ CodeMirror.keyMap.default["Tab"] = "indentMore";++ CodeMirror.modeURL = 'libraries/codemirror/mode/%N/%N.js';++ codeEditor = CodeMirror($("#note-detail-code")[0], {+ value: "",+ viewportMargin: Infinity,+ indentUnit: 4,+ matchBrackets: true,+ matchTags: { bothTags: true },+ highlightSelectionMatches: { showToken: /\w/, annotateScrollbar: false },+ lint: true,+ gutters: ["CodeMirror-lint-markers"],+ lineNumbers: true+ });- async function setContent(content) {- if (currentNote.detail.type === 'text') {- if (!editor) {- await utils.requireLibrary(utils.CKEDITOR);+ codeEditor.on('change', noteChanged);+ }- editor = await BalloonEditor.create($noteDetail[0], {});+ $noteDetailCode.show();- editor.document.on('change', noteChanged);- }+ // this needs to happen after the element is shown, otherwise the editor won't be refresheds+ codeEditor.setValue(content);- // temporary workaround for https://github.com/ckeditor/ckeditor5-enter/issues/49- editor.setData(content ? content : "<p></p>");+ const info = CodeMirror.findModeByMIME(currentNote.detail.mime);- $noteDetail.show();+ if (info) {+ codeEditor.setOption("mode", info.mime);+ CodeMirror.autoLoadMode(codeEditor, info.mode);}- else if (currentNote.detail.type === 'code') {- if (!codeEditor) {- await utils.requireLibrary(utils.CODE_MIRROR);-- CodeMirror.keyMap.default["Shift-Tab"] = "indentLess";- CodeMirror.keyMap.default["Tab"] = "indentMore";-- CodeMirror.modeURL = 'libraries/codemirror/mode/%N/%N.js';- codeEditor = CodeMirror($("#note-detail-code")[0], {- value: "",- viewportMargin: Infinity,- indentUnit: 4,- matchBrackets: true,- matchTags: { bothTags: true },- highlightSelectionMatches: { showToken: /\w/, annotateScrollbar: false },- lint: true,- gutters: ["CodeMirror-lint-markers"],- lineNumbers: true- });+ codeEditor.refresh();+ }+ else if (currentNote.detail.type === 'search') {+ $noteDetailSearch.show();- codeEditor.on('change', noteChanged);- }+ try {+ const json = JSON.parse(content);- $noteDetailCode.show();+ $searchString.val(json.searchString);+ }+ catch (e) {+ console.log(e);+ $searchString.val('');+ }- // this needs to happen after the element is shown, otherwise the editor won't be refresheds- codeEditor.setValue(content);+ $searchString.on('input', noteChanged);+ }+}- const info = CodeMirror.findModeByMIME(currentNote.detail.mime);+async function loadNoteToEditor(noteId) {+ currentNote = await loadNote(noteId);- if (info) {- codeEditor.setOption("mode", info.mime);- CodeMirror.autoLoadMode(codeEditor, info.mode);- }+ if (isNewNoteCreated) {+ isNewNoteCreated = false;- codeEditor.refresh();- }- else if (currentNote.detail.type === 'search') {- $noteDetailSearch.show();+ $noteTitle.focus().select();+ }- try {- const json = JSON.parse(content);+ $noteIdDisplay.html(noteId);- $searchString.val(json.searchString);- }- catch (e) {- console.log(e);- $searchString.val('');- }+ await protected_session.ensureProtectedSession(currentNote.detail.isProtected, false);- $searchString.on('input', noteChanged);- }+ if (currentNote.detail.isProtected) {+ protected_session.touchProtectedSession();}- async function loadNoteToEditor(noteId) {- currentNote = await loadNote(noteId);+ // this might be important if we focused on protected note when not in protected note and we got a dialog+ // to login, but we chose instead to come to another node - at that point the dialog is still visible and this will close it.+ protected_session.ensureDialogIsClosed();- if (isNewNoteCreated) {- isNewNoteCreated = false;+ $noteDetailWrapper.show();- $noteTitle.focus().select();- }+ noteChangeDisabled = true;- $noteIdDisplay.html(noteId);+ $noteTitle.val(currentNote.detail.title);- await protected_session.ensureProtectedSession(currentNote.detail.isProtected, false);+ noteType.setNoteType(currentNote.detail.type);+ noteType.setNoteMime(currentNote.detail.mime);- if (currentNote.detail.isProtected) {- protected_session.touchProtectedSession();- }+ $noteDetail.hide();+ $noteDetailSearch.hide();+ $noteDetailCode.hide();+ $noteDetailRender.html('').hide();+ $noteDetailAttachment.hide();- // this might be important if we focused on protected note when not in protected note and we got a dialog- // to login, but we chose instead to come to another node - at that point the dialog is still visible and this will close it.- protected_session.ensureDialogIsClosed();+ if (currentNote.detail.type === 'render') {+ $noteDetailRender.show();- $noteDetailWrapper.show();+ const bundle = await server.get('script/bundle/' + getCurrentNoteId());- noteChangeDisabled = true;+ $noteDetailRender.html(bundle.html);- $noteTitle.val(currentNote.detail.title);+ utils.executeBundle(bundle);+ }+ else if (currentNote.detail.type === 'file') {+ $noteDetailAttachment.show();- noteType.setNoteType(currentNote.detail.type);- noteType.setNoteMime(currentNote.detail.mime);+ $attachmentFileName.text(currentNote.labels.original_file_name);+ $attachmentFileSize.text(currentNote.labels.file_size + " bytes");+ $attachmentFileType.text(currentNote.detail.mime);+ }+ else {+ await setContent(currentNote.detail.content);+ }- $noteDetail.hide();- $noteDetailSearch.hide();- $noteDetailCode.hide();- $noteDetailRender.html('').hide();- $noteDetailAttachment.hide();+ noteChangeDisabled = false;- if (currentNote.detail.type === 'render') {- $noteDetailRender.show();+ setNoteBackgroundIfProtected(currentNote);+ treeService.setBranchBackgroundBasedOnProtectedStatus(noteId);- const bundle = await server.get('script/bundle/' + getCurrentNoteId());+ // after loading new note make sure editor is scrolled to the top+ $noteDetailWrapper.scrollTop(0);- $noteDetailRender.html(bundle.html);+ loadLabelList();+}- utils.executeBundle(bundle);- }- else if (currentNote.detail.type === 'file') {- $noteDetailAttachment.show();+async function loadLabelList() {+ const noteId = getCurrentNoteId();- $attachmentFileName.text(currentNote.labels.original_file_name);- $attachmentFileSize.text(currentNote.labels.file_size + " bytes");- $attachmentFileType.text(currentNote.detail.mime);- }- else {- await setContent(currentNote.detail.content);- }-- noteChangeDisabled = false;+ const labels = await server.get('notes/' + noteId + '/labels');- setNoteBackgroundIfProtected(currentNote);- treeService.setBranchBackgroundBasedOnProtectedStatus(noteId);+ $labelListInner.html('');- // after loading new note make sure editor is scrolled to the top- $noteDetailWrapper.scrollTop(0);+ if (labels.length > 0) {+ for (const attr of labels) {+ $labelListInner.append(utils.formatLabel(attr) + " ");+ }- loadLabelList();+ $labelList.show();}+ else {+ $labelList.hide();+ }+}- async function loadLabelList() {- const noteId = getCurrentNoteId();-- const labels = await server.get('notes/' + noteId + '/labels');+async function loadNote(noteId) {+ return await server.get('notes/' + noteId);+}- $labelListInner.html('');+function getEditor() {+ return editor;+}- if (labels.length > 0) {- for (const attr of labels) {- $labelListInner.append(utils.formatLabel(attr) + " ");- }+function focus() {+ const note = getCurrentNote();- $labelList.show();- }- else {- $labelList.hide();- }+ if (note.detail.type === 'text') {+ $noteDetail.focus();}-- async function loadNote(noteId) {- return await server.get('notes/' + noteId);+ else if (note.detail.type === 'code') {+ codeEditor.focus();}-- function getEditor() {- return editor;+ else if (note.detail.type === 'render' || note.detail.type === 'file' || note.detail.type === 'search') {+ // do nothing}-- function focus() {- const note = getCurrentNote();-- if (note.detail.type === 'text') {- $noteDetail.focus();- }- else if (note.detail.type === 'code') {- codeEditor.focus();- }- else if (note.detail.type === 'render' || note.detail.type === 'file' || note.detail.type === 'search') {- // do nothing- }- else {- utils.throwError('Unrecognized type: ' + note.detail.type);- }+ else {+ utils.throwError('Unrecognized type: ' + note.detail.type);}+}- function getCurrentNoteType() {- const currentNote = getCurrentNote();-- return currentNote ? currentNote.detail.type : null;- }+function getCurrentNoteType() {+ const currentNote = getCurrentNote();- async function executeCurrentNote() {- if (getCurrentNoteType() === 'code') {- // make sure note is saved so we load latest changes- await saveNoteIfChanged();+ return currentNote ? currentNote.detail.type : null;+}- if (currentNote.detail.mime.endsWith("env=frontend")) {- const bundle = await server.get('script/bundle/' + getCurrentNoteId());+async function executeCurrentNote() {+ if (getCurrentNoteType() === 'code') {+ // make sure note is saved so we load latest changes+ await saveNoteIfChanged();- utils.executeBundle(bundle);- }+ if (currentNote.detail.mime.endsWith("env=frontend")) {+ const bundle = await server.get('script/bundle/' + getCurrentNoteId());- if (currentNote.detail.mime.endsWith("env=backend")) {- await server.post('script/run/' + getCurrentNoteId());- }+ utils.executeBundle(bundle);+ }- utils.showMessage("Note executed");+ if (currentNote.detail.mime.endsWith("env=backend")) {+ await server.post('script/run/' + getCurrentNoteId());}++ utils.showMessage("Note executed");}+}- $attachmentDownload.click(() => utils.download(getAttachmentUrl()));+$attachmentDownload.click(() => utils.download(getAttachmentUrl()));- $attachmentOpen.click(() => {- if (utils.isElectron()) {- const open = require("open");+$attachmentOpen.click(() => {+ if (utils.isElectron()) {+ const open = require("open");- open(getAttachmentUrl());- }- else {- window.location.href = getAttachmentUrl();- }- });-- function getAttachmentUrl() {- // electron needs absolute URL so we extract current host, port, protocol- return utils.getHost() + "/api/attachments/download/" + getCurrentNoteId()- + "?protectedSessionId=" + encodeURIComponent(protected_session.getProtectedSessionId());+ open(getAttachmentUrl());+ }+ else {+ window.location.href = getAttachmentUrl();}+});- $(document).ready(() => {- $noteTitle.on('input', () => {- noteChanged();+function getAttachmentUrl() {+ // electron needs absolute URL so we extract current host, port, protocol+ return utils.getHost() + "/api/attachments/download/" + getCurrentNoteId()+ + "?protectedSessionId=" + encodeURIComponent(protected_session.getProtectedSessionId());+}- const title = $noteTitle.val();+$(document).ready(() => {+ $noteTitle.on('input', () => {+ noteChanged();- treeService.setNoteTitle(getCurrentNoteId(), title);- });+ const title = $noteTitle.val();- // so that tab jumps from note title (which has tabindex 1)- $noteDetail.attr("tabindex", 2);+ treeService.setNoteTitle(getCurrentNoteId(), title);});- $(document).bind('keydown', "ctrl+return", executeCurrentNote);-- $executeScriptButton.click(executeCurrentNote());-- setInterval(saveNoteIfChanged, 5000);-- return {- reload,- switchToNote,- saveNoteIfChanged,- updateNoteFromInputs,- saveNoteToServer,- setNoteBackgroundIfProtected,- loadNote,- getCurrentNote,- getCurrentNoteType,- getCurrentNoteId,- newNoteCreated,- getEditor,- focus,- executeCurrentNote,- loadLabelList,- setContent- };-})();\ No newline at end of file+ // so that tab jumps from note title (which has tabindex 1)+ $noteDetail.attr("tabindex", 2);+});++$(document).bind('keydown', "ctrl+return", executeCurrentNote);++$executeScriptButton.click(executeCurrentNote());++setInterval(saveNoteIfChanged, 5000);++export default {+ reload,+ switchToNote,+ saveNoteIfChanged,+ updateNoteFromInputs,+ saveNoteToServer,+ setNoteBackgroundIfProtected,+ loadNote,+ getCurrentNote,+ getCurrentNoteType,+ getCurrentNoteId,+ newNoteCreated,+ getEditor,+ focus,+ executeCurrentNote,+ loadLabelList,+ setContent+};\ No newline at end of filediff --git a/src/public/javascripts/note_tree.js b/src/public/javascripts/note_tree.jsindex 3f8b670205..1fd0cb8fd1 100644--- a/src/public/javascripts/note_tree.js+++ b/src/public/javascripts/note_tree.js@@ -1,5 +1,17 @@"use strict";+import contextMenu from './context_menu.js';+import dragAndDropSetup from './drag_and_drop.js';+import link from './link.js';+import messaging from './messaging.js';+import noteEditor from './note_editor.js';+import protected_session from './protected_session.js';+import treeChanges from './tree_changes.js';+import treeUtils from './tree_utils.js';+import utils from './utils.js';+import server from './server.js';+import recentNotes from './dialogs/recent_notes.js';+class TreeCache {constructor(noteRows, branchRows) {this.parents = [];@@ -126,925 +138,923 @@ class Branch {}}-const treeService = (function() {- let treeCache;-- const $tree = $("#tree");- const $parentList = $("#parent-list");- const $parentListList = $("#parent-list-inner");- const $createTopLevelNoteButton = $("#create-top-level-note-button");- const $collapseTreeButton = $("#collapse-tree-button");- const $scrollToCurrentNoteButton = $("#scroll-to-current-note-button");+let treeCache;- let instanceName = null; // should have better place+const $tree = $("#tree");+const $parentList = $("#parent-list");+const $parentListList = $("#parent-list-inner");+const $createTopLevelNoteButton = $("#create-top-level-note-button");+const $collapseTreeButton = $("#collapse-tree-button");+const $scrollToCurrentNoteButton = $("#scroll-to-current-note-button");- let startNotePath = null;+let instanceName = null; // should have better place- function getNote(noteId) {- const note = treeCache.getNote(noteId);+let startNotePath = null;- if (!note) {- utils.throwError("Can't find title for noteId='" + noteId + "'");- }+function getNote(noteId) {+ const note = treeCache.getNote(noteId);- return note;+ if (!note) {+ utils.throwError("Can't find title for noteId='" + noteId + "'");}- function getNoteTitle(noteId, parentNoteId = null) {- utils.assertArguments(noteId);-- let title = treeCache.getNote(noteId).title;+ return note;+}- if (parentNoteId !== null) {- const branch = treeCache.getBranchByChildParent(noteId, parentNoteId);+function getNoteTitle(noteId, parentNoteId = null) {+ utils.assertArguments(noteId);- if (branch && branch.prefix) {- title = branch.prefix + ' - ' + title;- }- }+ let title = treeCache.getNote(noteId).title;- return title;- }+ if (parentNoteId !== null) {+ const branch = treeCache.getBranchByChildParent(noteId, parentNoteId);- // note that if you want to access data like noteId or isProtected, you need to go into "data" property- function getCurrentNode() {- return $tree.fancytree("getActiveNode");+ if (branch && branch.prefix) {+ title = branch.prefix + ' - ' + title;+ }}- function getCurrentNotePath() {- const node = getCurrentNode();+ return title;+}- return treeUtils.getNotePath(node);- }+// note that if you want to access data like noteId or isProtected, you need to go into "data" property+function getCurrentNode() {+ return $tree.fancytree("getActiveNode");+}- function getNodesByBranchId(branchId) {- utils.assertArguments(branchId);+function getCurrentNotePath() {+ const node = getCurrentNode();- const branch = treeCache.getBranch(branchId);+ return treeUtils.getNotePath(node);+}- return getNodesByNoteId(branch.noteId).filter(node => node.data.branchId === branchId);- }+function getNodesByBranchId(branchId) {+ utils.assertArguments(branchId);- function getNodesByNoteId(noteId) {- utils.assertArguments(noteId);+ const branch = treeCache.getBranch(branchId);- const list = getTree().getNodesByRef(noteId);- return list ? list : []; // if no nodes with this refKey are found, fancy tree returns null- }+ return getNodesByNoteId(branch.noteId).filter(node => node.data.branchId === branchId);+}- function setPrefix(branchId, prefix) {- utils.assertArguments(branchId);+function getNodesByNoteId(noteId) {+ utils.assertArguments(noteId);- treeCache.getBranch(branchId).prefix = prefix;+ const list = getTree().getNodesByRef(noteId);+ return list ? list : []; // if no nodes with this refKey are found, fancy tree returns null+}- getNodesByBranchId(branchId).map(node => setNodeTitleWithPrefix(node));- }+function setPrefix(branchId, prefix) {+ utils.assertArguments(branchId);- function setNodeTitleWithPrefix(node) {- const noteTitle = getNoteTitle(node.data.noteId);- const branch = treeCache.getBranch(node.data.branchId);+ treeCache.getBranch(branchId).prefix = prefix;- const prefix = branch.prefix;+ getNodesByBranchId(branchId).map(node => setNodeTitleWithPrefix(node));+}- const title = (prefix ? (prefix + " - ") : "") + noteTitle;+function setNodeTitleWithPrefix(node) {+ const noteTitle = getNoteTitle(node.data.noteId);+ const branch = treeCache.getBranch(node.data.branchId);- node.setTitle(utils.escapeHtml(title));- }+ const prefix = branch.prefix;- function removeParentChildRelation(parentNoteId, childNoteId) {- utils.assertArguments(parentNoteId, childNoteId);+ const title = (prefix ? (prefix + " - ") : "") + noteTitle;- treeCache.parents[childNoteId] = treeCache.parents[childNoteId].filter(p => p.noteId !== parentNoteId);- treeCache.children[parentNoteId] = treeCache.children[parentNoteId].filter(ch => ch.noteId !== childNoteId);+ node.setTitle(utils.escapeHtml(title));+}- delete treeCache.childParentToBranch[childNoteId + '-' + parentNoteId];- }+function removeParentChildRelation(parentNoteId, childNoteId) {+ utils.assertArguments(parentNoteId, childNoteId);- function setParentChildRelation(branchId, parentNoteId, childNoteId) {- treeCache.parents[childNoteId] = treeCache.parents[childNoteId] || [];- treeCache.parents[childNoteId].push(treeCache.getNote(parentNoteId));+ treeCache.parents[childNoteId] = treeCache.parents[childNoteId].filter(p => p.noteId !== parentNoteId);+ treeCache.children[parentNoteId] = treeCache.children[parentNoteId].filter(ch => ch.noteId !== childNoteId);- treeCache.children[parentNoteId] = treeCache.children[parentNoteId] || [];- treeCache.children[parentNoteId].push(treeCache.getNote(childNoteId));+ delete treeCache.childParentToBranch[childNoteId + '-' + parentNoteId];+}- treeCache.childParentToBranch[childNoteId + '-' + parentNoteId] = treeCache.getBranch(branchId);- }+function setParentChildRelation(branchId, parentNoteId, childNoteId) {+ treeCache.parents[childNoteId] = treeCache.parents[childNoteId] || [];+ treeCache.parents[childNoteId].push(treeCache.getNote(parentNoteId));- async function prepareBranch(noteRows, branchRows) {- utils.assertArguments(noteRows);+ treeCache.children[parentNoteId] = treeCache.children[parentNoteId] || [];+ treeCache.children[parentNoteId].push(treeCache.getNote(childNoteId));- treeCache = new TreeCache(noteRows, branchRows);+ treeCache.childParentToBranch[childNoteId + '-' + parentNoteId] = treeCache.getBranch(branchId);+}- return await prepareBranchInner(treeCache.getNote('root'));- }+async function prepareBranch(noteRows, branchRows) {+ utils.assertArguments(noteRows);- async function getExtraClasses(note) {- utils.assertArguments(note);+ treeCache = new TreeCache(noteRows, branchRows);- const extraClasses = [];+ return await prepareBranchInner(treeCache.getNote('root'));+}- if (note.isProtected) {- extraClasses.push("protected");- }+async function getExtraClasses(note) {+ utils.assertArguments(note);- if ((await note.getParentNotes()).length > 1) {- extraClasses.push("multiple-parents");- }+ const extraClasses = [];- extraClasses.push(note.type);+ if (note.isProtected) {+ extraClasses.push("protected");+ }- return extraClasses.join(" ");+ if ((await note.getParentNotes()).length > 1) {+ extraClasses.push("multiple-parents");}- async function prepareBranchInner(parentNote) {- utils.assertArguments(parentNote);+ extraClasses.push(note.type);- const childBranches = await parentNote.getChildBranches();+ return extraClasses.join(" ");+}- if (!childBranches) {- messaging.logError(`No children for ${parentNote}. This shouldn't happen.`);- return;- }+async function prepareBranchInner(parentNote) {+ utils.assertArguments(parentNote);- const noteList = [];+ const childBranches = await parentNote.getChildBranches();- for (const branch of childBranches) {- const note = await branch.getNote();- const title = (branch.prefix ? (branch.prefix + " - ") : "") + note.title;+ if (!childBranches) {+ messaging.logError(`No children for ${parentNote}. This shouldn't happen.`);+ return;+ }- const node = {- noteId: note.noteId,- parentNoteId: branch.parentNoteId,- branchId: branch.branchId,- isProtected: note.isProtected,- title: utils.escapeHtml(title),- extraClasses: await getExtraClasses(note),- refKey: note.noteId,- expanded: note.type !== 'search' && branch.isExpanded- };+ const noteList = [];++ for (const branch of childBranches) {+ const note = await branch.getNote();+ const title = (branch.prefix ? (branch.prefix + " - ") : "") + note.title;++ const node = {+ noteId: note.noteId,+ parentNoteId: branch.parentNoteId,+ branchId: branch.branchId,+ isProtected: note.isProtected,+ title: utils.escapeHtml(title),+ extraClasses: await getExtraClasses(note),+ refKey: note.noteId,+ expanded: note.type !== 'search' && branch.isExpanded+ };- const hasChildren = (await note.getChildNotes()).length > 0;+ const hasChildren = (await note.getChildNotes()).length > 0;- if (hasChildren || note.type === 'search') {- node.folder = true;+ if (hasChildren || note.type === 'search') {+ node.folder = true;- if (node.expanded && note.type !== 'search') {- node.children = await prepareBranchInner(note);- }- else {- node.lazy = true;- }+ if (node.expanded && note.type !== 'search') {+ node.children = await prepareBranchInner(note);+ }+ else {+ node.lazy = true;}-- noteList.push(node);}- return noteList;+ noteList.push(node);}- async function expandToNote(notePath, expandOpts) {- utils.assertArguments(notePath);+ return noteList;+}- const runPath = await getRunPath(notePath);+async function expandToNote(notePath, expandOpts) {+ utils.assertArguments(notePath);- const noteId = treeUtils.getNoteIdFromNotePath(notePath);+ const runPath = await getRunPath(notePath);- let parentNoteId = 'root';+ const noteId = treeUtils.getNoteIdFromNotePath(notePath);- for (const childNoteId of runPath) {- const node = getNodesByNoteId(childNoteId).find(node => node.data.parentNoteId === parentNoteId);+ let parentNoteId = 'root';- if (childNoteId === noteId) {- return node;- }- else {- await node.setExpanded(true, expandOpts);- }+ for (const childNoteId of runPath) {+ const node = getNodesByNoteId(childNoteId).find(node => node.data.parentNoteId === parentNoteId);- parentNoteId = childNoteId;+ if (childNoteId === noteId) {+ return node;}+ else {+ await node.setExpanded(true, expandOpts);+ }++ parentNoteId = childNoteId;}+}- async function activateNode(notePath) {- utils.assertArguments(notePath);+async function activateNode(notePath) {+ utils.assertArguments(notePath);- const node = await expandToNote(notePath);+ const node = await expandToNote(notePath);- await node.setActive();+ await node.setActive();- clearSelectedNodes();- }+ clearSelectedNodes();+}- /**- * Accepts notePath and tries to resolve it. Part of the path might not be valid because of note moving (which causes- * path change) or other corruption, in that case this will try to get some other valid path to the correct note.- */- async function getRunPath(notePath) {- utils.assertArguments(notePath);+/**+ * Accepts notePath and tries to resolve it. Part of the path might not be valid because of note moving (which causes+ * path change) or other corruption, in that case this will try to get some other valid path to the correct note.+ */+async function getRunPath(notePath) {+ utils.assertArguments(notePath);- const path = notePath.split("/").reverse();- path.push('root');+ const path = notePath.split("/").reverse();+ path.push('root');- const effectivePath = [];- let childNoteId = null;- let i = 0;+ const effectivePath = [];+ let childNoteId = null;+ let i = 0;- while (true) {- if (i >= path.length) {- break;- }+ while (true) {+ if (i >= path.length) {+ break;+ }- const parentNoteId = path[i++];+ const parentNoteId = path[i++];- if (childNoteId !== null) {- const child = treeCache.getNote(childNoteId);- const parents = await child.getParentNotes();+ if (childNoteId !== null) {+ const child = treeCache.getNote(childNoteId);+ const parents = await child.getParentNotes();- if (!parents) {- messaging.logError("No parents found for " + childNoteId);- return;- }+ if (!parents) {+ messaging.logError("No parents found for " + childNoteId);+ return;+ }- if (!parents.some(p => p.noteId === parentNoteId)) {- console.log(utils.now(), "Did not find parent " + parentNoteId + " for child " + childNoteId);+ if (!parents.some(p => p.noteId === parentNoteId)) {+ console.log(utils.now(), "Did not find parent " + parentNoteId + " for child " + childNoteId);- if (parents.length > 0) {- console.log(utils.now(), "Available parents:", parents);+ if (parents.length > 0) {+ console.log(utils.now(), "Available parents:", parents);- const someNotePath = await getSomeNotePath(parents[0]);+ const someNotePath = await getSomeNotePath(parents[0]);- if (someNotePath) { // in case it's root the path may be empty- const pathToRoot = someNotePath.split("/").reverse();+ if (someNotePath) { // in case it's root the path may be empty+ const pathToRoot = someNotePath.split("/").reverse();- for (const noteId of pathToRoot) {- effectivePath.push(noteId);- }+ for (const noteId of pathToRoot) {+ effectivePath.push(noteId);}-- break;}- else {- messaging.logError("No parents, can't activate node.");- return;- }- }- }- if (parentNoteId === 'root') {- break;- }- else {- effectivePath.push(parentNoteId);- childNoteId = parentNoteId;+ break;+ }+ else {+ messaging.logError("No parents, can't activate node.");+ return;+ }}}- return effectivePath.reverse();+ if (parentNoteId === 'root') {+ break;+ }+ else {+ effectivePath.push(parentNoteId);+ childNoteId = parentNoteId;+ }}- async function showParentList(noteId, node) {- utils.assertArguments(noteId, node);+ return effectivePath.reverse();+}- const note = treeCache.getNote(noteId);- const parents = await note.getParentNotes();+async function showParentList(noteId, node) {+ utils.assertArguments(noteId, node);- if (!parents.length) {- utils.throwError("Can't find parents for noteId=" + noteId);- }+ const note = treeCache.getNote(noteId);+ const parents = await note.getParentNotes();- if (parents.length <= 1) {- $parentList.hide();- }- else {- $parentList.show();- $parentListList.empty();+ if (!parents.length) {+ utils.throwError("Can't find parents for noteId=" + noteId);+ }- for (const parentNote of parents) {- const parentNotePath = await getSomeNotePath(parentNote);- // this is to avoid having root notes leading '/'- const notePath = parentNotePath ? (parentNotePath + '/' + noteId) : noteId;- const title = getNotePathTitle(notePath);+ if (parents.length <= 1) {+ $parentList.hide();+ }+ else {+ $parentList.show();+ $parentListList.empty();- let item;+ for (const parentNote of parents) {+ const parentNotePath = await getSomeNotePath(parentNote);+ // this is to avoid having root notes leading '/'+ const notePath = parentNotePath ? (parentNotePath + '/' + noteId) : noteId;+ const title = getNotePathTitle(notePath);- if (node.getParent().data.noteId === parentNote.noteId) {- item = $("<span/>").attr("title", "Current note").append(title);- }- else {- item = link.createNoteLink(notePath, title);- }+ let item;- $parentListList.append($("<li/>").append(item));+ if (node.getParent().data.noteId === parentNote.noteId) {+ item = $("<span/>").attr("title", "Current note").append(title);}+ else {+ item = link.createNoteLink(notePath, title);+ }++ $parentListList.append($("<li/>").append(item));}}+}- function getNotePathTitle(notePath) {- utils.assertArguments(notePath);-- const titlePath = [];+function getNotePathTitle(notePath) {+ utils.assertArguments(notePath);- let parentNoteId = 'root';+ const titlePath = [];- for (const noteId of notePath.split('/')) {- titlePath.push(getNoteTitle(noteId, parentNoteId));+ let parentNoteId = 'root';- parentNoteId = noteId;- }+ for (const noteId of notePath.split('/')) {+ titlePath.push(getNoteTitle(noteId, parentNoteId));- return titlePath.join(' / ');+ parentNoteId = noteId;}- async function getSomeNotePath(note) {- utils.assertArguments(note);+ return titlePath.join(' / ');+}- const path = [];+async function getSomeNotePath(note) {+ utils.assertArguments(note);- let cur = note;+ const path = [];- while (cur.noteId !== 'root') {- path.push(cur.noteId);+ let cur = note;- const parents = await cur.getParentNotes();+ while (cur.noteId !== 'root') {+ path.push(cur.noteId);- if (!parents.length) {- utils.throwError("Can't find parents for " + cur);- }+ const parents = await cur.getParentNotes();- cur = parents[0];+ if (!parents.length) {+ utils.throwError("Can't find parents for " + cur);}- return path.reverse().join('/');+ cur = parents[0];}- async function setExpandedToServer(branchId, isExpanded) {- utils.assertArguments(branchId);-- const expandedNum = isExpanded ? 1 : 0;+ return path.reverse().join('/');+}- await server.put('tree/' + branchId + '/expanded/' + expandedNum);- }+async function setExpandedToServer(branchId, isExpanded) {+ utils.assertArguments(branchId);- function setCurrentNotePathToHash(node) {- utils.assertArguments(node);+ const expandedNum = isExpanded ? 1 : 0;- const currentNotePath = treeUtils.getNotePath(node);- const currentBranchId = node.data.branchId;+ await server.put('tree/' + branchId + '/expanded/' + expandedNum);+}- document.location.hash = currentNotePath;+function setCurrentNotePathToHash(node) {+ utils.assertArguments(node);- recentNotes.addRecentNote(currentBranchId, currentNotePath);- }+ const currentNotePath = treeUtils.getNotePath(node);+ const currentBranchId = node.data.branchId;- function getSelectedNodes(stopOnParents = false) {- return getTree().getSelectedNodes(stopOnParents);- }+ document.location.hash = currentNotePath;- function clearSelectedNodes() {- for (const selectedNode of getSelectedNodes()) {- selectedNode.setSelected(false);- }+ recentNotes.addRecentNote(currentBranchId, currentNotePath);+}- const currentNode = getCurrentNode();+function getSelectedNodes(stopOnParents = false) {+ return getTree().getSelectedNodes(stopOnParents);+}- if (currentNode) {- currentNode.setSelected(true);- }+function clearSelectedNodes() {+ for (const selectedNode of getSelectedNodes()) {+ selectedNode.setSelected(false);}- function initFancyTree(branch) {- utils.assertArguments(branch);+ const currentNode = getCurrentNode();- const keybindings = {- "del": node => {- treeChanges.deleteNodes(getSelectedNodes(true));- },- "ctrl+up": node => {- const beforeNode = node.getPrevSibling();+ if (currentNode) {+ currentNode.setSelected(true);+ }+}- if (beforeNode !== null) {- treeChanges.moveBeforeNode([node], beforeNode);- }+function initFancyTree(branch) {+ utils.assertArguments(branch);- return false;- },- "ctrl+down": node => {- let afterNode = node.getNextSibling();- if (afterNode !== null) {- treeChanges.moveAfterNode([node], afterNode);- }-- return false;- },- "ctrl+left": node => {- treeChanges.moveNodeUpInHierarchy(node);+ const keybindings = {+ "del": node => {+ treeChanges.deleteNodes(getSelectedNodes(true));+ },+ "ctrl+up": node => {+ const beforeNode = node.getPrevSibling();- return false;- },- "ctrl+right": node => {- let toNode = node.getPrevSibling();+ if (beforeNode !== null) {+ treeChanges.moveBeforeNode([node], beforeNode);+ }- if (toNode !== null) {- treeChanges.moveToNode([node], toNode);- }+ return false;+ },+ "ctrl+down": node => {+ let afterNode = node.getNextSibling();+ if (afterNode !== null) {+ treeChanges.moveAfterNode([node], afterNode);+ }- return false;- },- "shift+up": node => {- node.navigate($.ui.keyCode.UP, true).then(() => {- const currentNode = getCurrentNode();+ return false;+ },+ "ctrl+left": node => {+ treeChanges.moveNodeUpInHierarchy(node);- if (currentNode.isSelected()) {- node.setSelected(false);- }+ return false;+ },+ "ctrl+right": node => {+ let toNode = node.getPrevSibling();- currentNode.setSelected(true);- });+ if (toNode !== null) {+ treeChanges.moveToNode([node], toNode);+ }- return false;- },- "shift+down": node => {- node.navigate($.ui.keyCode.DOWN, true).then(() => {- const currentNode = getCurrentNode();+ return false;+ },+ "shift+up": node => {+ node.navigate($.ui.keyCode.UP, true).then(() => {+ const currentNode = getCurrentNode();- if (currentNode.isSelected()) {- node.setSelected(false);- }+ if (currentNode.isSelected()) {+ node.setSelected(false);+ }- currentNode.setSelected(true);- });+ currentNode.setSelected(true);+ });- return false;- },- "f2": node => {- editTreePrefix.showDialog(node);- },- "alt+-": node => {- collapseTree(node);- },- "alt+s": node => {- sortAlphabetically(node.data.noteId);+ return false;+ },+ "shift+down": node => {+ node.navigate($.ui.keyCode.DOWN, true).then(() => {+ const currentNode = getCurrentNode();- return false;- },- "ctrl+a": node => {- for (const child of node.getParent().getChildren()) {- child.setSelected(true);+ if (currentNode.isSelected()) {+ node.setSelected(false);}- return false;- },- "ctrl+c": () => {- contextMenu.copy(getSelectedNodes());-- return false;- },- "ctrl+x": () => {- contextMenu.cut(getSelectedNodes());+ currentNode.setSelected(true);+ });- return false;- },- "ctrl+v": node => {- contextMenu.pasteInto(node);+ return false;+ },+ "f2": node => {+ editTreePrefix.showDialog(node);+ },+ "alt+-": node => {+ collapseTree(node);+ },+ "alt+s": node => {+ sortAlphabetically(node.data.noteId);++ return false;+ },+ "ctrl+a": node => {+ for (const child of node.getParent().getChildren()) {+ child.setSelected(true);+ }- return false;- },- "return": node => {- noteEditor.focus();+ return false;+ },+ "ctrl+c": () => {+ contextMenu.copy(getSelectedNodes());++ return false;+ },+ "ctrl+x": () => {+ contextMenu.cut(getSelectedNodes());++ return false;+ },+ "ctrl+v": node => {+ contextMenu.pasteInto(node);++ return false;+ },+ "return": node => {+ noteEditor.focus();++ return false;+ },+ "backspace": node => {+ if (!utils.isTopLevelNode(node)) {+ node.getParent().setActive().then(() => clearSelectedNodes());+ }+ },+ // code below shouldn't be necessary normally, however there's some problem with interaction with context menu plugin+ // after opening context menu, standard shortcuts don't work, but they are detected here+ // so we essentially takeover the standard handling with our implementation.+ "left": node => {+ node.navigate($.ui.keyCode.LEFT, true).then(() => clearSelectedNodes());++ return false;+ },+ "right": node => {+ node.navigate($.ui.keyCode.RIGHT, true).then(() => clearSelectedNodes());++ return false;+ },+ "up": node => {+ node.navigate($.ui.keyCode.UP, true).then(() => clearSelectedNodes());++ return false;+ },+ "down": node => {+ node.navigate($.ui.keyCode.DOWN, true).then(() => clearSelectedNodes());++ return false;+ }+ };- return false;- },- "backspace": node => {- if (!utils.isTopLevelNode(node)) {- node.getParent().setActive().then(() => clearSelectedNodes());+ $tree.fancytree({+ autoScroll: true,+ keyboard: false, // we takover keyboard handling in the hotkeys plugin+ extensions: ["hotkeys", "filter", "dnd", "clones"],+ source: branch,+ scrollParent: $("#tree"),+ click: (event, data) => {+ const targetType = data.targetType;+ const node = data.node;++ if (targetType === 'title' || targetType === 'icon') {+ if (!event.ctrlKey) {+ node.setActive();+ node.setSelected(true);++ clearSelectedNodes();+ }+ else {+ node.setSelected(!node.isSelected());}- },- // code below shouldn't be necessary normally, however there's some problem with interaction with context menu plugin- // after opening context menu, standard shortcuts don't work, but they are detected here- // so we essentially takeover the standard handling with our implementation.- "left": node => {- node.navigate($.ui.keyCode.LEFT, true).then(() => clearSelectedNodes());-- return false;- },- "right": node => {- node.navigate($.ui.keyCode.RIGHT, true).then(() => clearSelectedNodes());return false;- },- "up": node => {- node.navigate($.ui.keyCode.UP, true).then(() => clearSelectedNodes());+ }+ },+ activate: (event, data) => {+ const node = data.node.data;++ setCurrentNotePathToHash(data.node);++ noteEditor.switchToNote(node.noteId);++ showParentList(node.noteId, data.node);+ },+ expand: (event, data) => {+ setExpandedToServer(data.node.data.branchId, true);+ },+ collapse: (event, data) => {+ setExpandedToServer(data.node.data.branchId, false);+ },+ init: (event, data) => {+ const noteId = treeUtils.getNoteIdFromNotePath(startNotePath);++ if (treeCache.getNote(noteId) === undefined) {+ // note doesn't exist so don't try to activate it+ startNotePath = null;+ }- return false;- },- "down": node => {- node.navigate($.ui.keyCode.DOWN, true).then(() => clearSelectedNodes());+ if (startNotePath) {+ activateNode(startNotePath);- return false;+ // looks like this this doesn't work when triggered immediatelly after activating node+ // so waiting a second helps+ setTimeout(scrollToCurrentNote, 1000);}- };+ },+ hotkeys: {+ keydown: keybindings+ },+ filter: {+ autoApply: true, // Re-apply last filter if lazy data is loaded+ autoExpand: true, // Expand all branches that contain matches while filtered+ counter: false, // Show a badge with number of matching child nodes near parent icons+ fuzzy: false, // Match single characters in order, e.g. 'fb' will match 'FooBar'+ hideExpandedCounter: true, // Hide counter badge if parent is expanded+ hideExpanders: false, // Hide expanders if all child nodes are hidden by filter+ highlight: true, // Highlight matches by wrapping inside <mark> tags+ leavesOnly: false, // Match end nodes only+ nodata: true, // Display a 'no data' status node if result is empty+ mode: "hide" // Grayout unmatched nodes (pass "hide" to remove unmatched node instead)+ },+ dnd: dragAndDropSetup,+ lazyLoad: function(event, data){+ const noteId = data.node.data.noteId;+ const note = getNote(noteId);++ if (note.type === 'search') {+ data.result = loadSearchNote(noteId);+ }+ else {+ data.result = prepareBranchInner(note);+ }+ },+ clones: {+ highlightActiveClones: true+ }+ });- $tree.fancytree({- autoScroll: true,- keyboard: false, // we takover keyboard handling in the hotkeys plugin- extensions: ["hotkeys", "filter", "dnd", "clones"],- source: branch,- scrollParent: $("#tree"),- click: (event, data) => {- const targetType = data.targetType;- const node = data.node;-- if (targetType === 'title' || targetType === 'icon') {- if (!event.ctrlKey) {- node.setActive();- node.setSelected(true);-- clearSelectedNodes();- }- else {- node.setSelected(!node.isSelected());- }+ $tree.contextmenu(contextMenu.contextMenuSettings);+}- return false;- }- },- activate: (event, data) => {- const node = data.node.data;-- setCurrentNotePathToHash(data.node);-- noteEditor.switchToNote(node.noteId);-- showParentList(node.noteId, data.node);- },- expand: (event, data) => {- setExpandedToServer(data.node.data.branchId, true);- },- collapse: (event, data) => {- setExpandedToServer(data.node.data.branchId, false);- },- init: (event, data) => {- const noteId = treeUtils.getNoteIdFromNotePath(startNotePath);-- if (treeCache.getNote(noteId) === undefined) {- // note doesn't exist so don't try to activate it- startNotePath = null;- }+async function loadSearchNote(searchNoteId) {+ const note = await server.get('notes/' + searchNoteId);- if (startNotePath) {- activateNode(startNotePath);+ const json = JSON.parse(note.detail.content);- // looks like this this doesn't work when triggered immediatelly after activating node- // so waiting a second helps- setTimeout(scrollToCurrentNote, 1000);- }- },- hotkeys: {- keydown: keybindings- },- filter: {- autoApply: true, // Re-apply last filter if lazy data is loaded- autoExpand: true, // Expand all branches that contain matches while filtered- counter: false, // Show a badge with number of matching child nodes near parent icons- fuzzy: false, // Match single characters in order, e.g. 'fb' will match 'FooBar'- hideExpandedCounter: true, // Hide counter badge if parent is expanded- hideExpanders: false, // Hide expanders if all child nodes are hidden by filter- highlight: true, // Highlight matches by wrapping inside <mark> tags- leavesOnly: false, // Match end nodes only- nodata: true, // Display a 'no data' status node if result is empty- mode: "hide" // Grayout unmatched nodes (pass "hide" to remove unmatched node instead)- },- dnd: dragAndDropSetup,- lazyLoad: function(event, data){- const noteId = data.node.data.noteId;- const note = getNote(noteId);-- if (note.type === 'search') {- data.result = loadSearchNote(noteId);- }- else {- data.result = prepareBranchInner(note);- }- },- clones: {- highlightActiveClones: true- }- });+ const noteIds = await server.get('search/' + encodeURIComponent(json.searchString));- $tree.contextmenu(contextMenu.contextMenuSettings);+ for (const noteId of noteIds) {+ const branchId = "virt" + utils.randomString(10);++ treeCache.addBranch({+ branchId: branchId,+ noteId: noteId,+ parentNoteId: searchNoteId,+ prefix: '',+ virtual: true+ });}- async function loadSearchNote(searchNoteId) {- const note = await server.get('notes/' + searchNoteId);+ return await prepareBranchInner(treeCache.getNote(searchNoteId));+}- const json = JSON.parse(note.detail.content);+function getTree() {+ return $tree.fancytree('getTree');+}- const noteIds = await server.get('search/' + encodeURIComponent(json.searchString));+async function reload() {+ const notes = await loadTree();- for (const noteId of noteIds) {- const branchId = "virt" + utils.randomString(10);+ // this will also reload the note content+ await getTree().reload(notes);+}- treeCache.addBranch({- branchId: branchId,- noteId: noteId,- parentNoteId: searchNoteId,- prefix: '',- virtual: true- });- }+function getNotePathFromAddress() {+ return document.location.hash.substr(1); // strip initial #+}- return await prepareBranchInner(treeCache.getNote(searchNoteId));- }+async function loadTree() {+ const resp = await server.get('tree');+ startNotePath = resp.start_note_path;+ instanceName = resp.instanceName;- function getTree() {- return $tree.fancytree('getTree');+ if (document.location.hash) {+ startNotePath = getNotePathFromAddress();}- async function reload() {- const notes = await loadTree();+ return await prepareBranch(resp.notes, resp.branches);+}- // this will also reload the note content- await getTree().reload(notes);- }+$(() => loadTree().then(branch => initFancyTree(branch)));- function getNotePathFromAddress() {- return document.location.hash.substr(1); // strip initial #+function collapseTree(node = null) {+ if (!node) {+ node = $tree.fancytree("getRootNode");}- async function loadTree() {- const resp = await server.get('tree');- startNotePath = resp.start_note_path;- instanceName = resp.instanceName;+ node.setExpanded(false);- if (document.location.hash) {- startNotePath = getNotePathFromAddress();- }-- return await prepareBranch(resp.notes, resp.branches);- }+ node.visit(node => node.setExpanded(false));+}- $(() => loadTree().then(branch => initFancyTree(branch)));+$(document).bind('keydown', 'alt+c', () => collapseTree()); // don't use shortened form since collapseTree() accepts argument- function collapseTree(node = null) {- if (!node) {- node = $tree.fancytree("getRootNode");- }+function scrollToCurrentNote() {+ const node = getCurrentNode();- node.setExpanded(false);+ if (node) {+ node.makeVisible({scrollIntoView: true});- node.visit(node => node.setExpanded(false));+ node.setFocus();}+}- $(document).bind('keydown', 'alt+c', () => collapseTree()); // don't use shortened form since collapseTree() accepts argument+function setBranchBackgroundBasedOnProtectedStatus(noteId) {+ getNodesByNoteId(noteId).map(node => node.toggleClass("protected", !!node.data.isProtected));+}- function scrollToCurrentNote() {- const node = getCurrentNode();+function setProtected(noteId, isProtected) {+ getNodesByNoteId(noteId).map(node => node.data.isProtected = isProtected);- if (node) {- node.makeVisible({scrollIntoView: true});+ setBranchBackgroundBasedOnProtectedStatus(noteId);+}- node.setFocus();- }+async function getAutocompleteItems(parentNoteId, notePath, titlePath) {+ if (!parentNoteId) {+ parentNoteId = 'root';}- function setBranchBackgroundBasedOnProtectedStatus(noteId) {- getNodesByNoteId(noteId).map(node => node.toggleClass("protected", !!node.data.isProtected));- }+ const parentNote = treeCache.getNote(parentNoteId);+ const childNotes = await parentNote.getChildNotes();- function setProtected(noteId, isProtected) {- getNodesByNoteId(noteId).map(node => node.data.isProtected = isProtected);+ if (!childNotes.length) {+ return [];+ }- setBranchBackgroundBasedOnProtectedStatus(noteId);+ if (!notePath) {+ notePath = '';}- async function getAutocompleteItems(parentNoteId, notePath, titlePath) {- if (!parentNoteId) {- parentNoteId = 'root';- }+ if (!titlePath) {+ titlePath = '';+ }- const parentNote = treeCache.getNote(parentNoteId);- const childNotes = await parentNote.getChildNotes();+ // https://github.com/zadam/trilium/issues/46+ // unfortunately not easy to implement because we don't have an easy access to note's isProtected property- if (!childNotes.length) {- return [];- }+ const autocompleteItems = [];- if (!notePath) {- notePath = '';+ for (const childNote of childNotes) {+ if (childNote.hideInAutocomplete) {+ continue;}- if (!titlePath) {- titlePath = '';- }+ const childNotePath = (notePath ? (notePath + '/') : '') + childNote.noteId;+ const childTitlePath = (titlePath ? (titlePath + ' / ') : '') + getNoteTitle(childNote.noteId, parentNoteId);- // https://github.com/zadam/trilium/issues/46- // unfortunately not easy to implement because we don't have an easy access to note's isProtected property-- const autocompleteItems = [];-- for (const childNote of childNotes) {- if (childNote.hideInAutocomplete) {- continue;- }-- const childNotePath = (notePath ? (notePath + '/') : '') + childNote.noteId;- const childTitlePath = (titlePath ? (titlePath + ' / ') : '') + getNoteTitle(childNote.noteId, parentNoteId);-- autocompleteItems.push({- value: childTitlePath + ' (' + childNotePath + ')',- label: childTitlePath- });+ autocompleteItems.push({+ value: childTitlePath + ' (' + childNotePath + ')',+ label: childTitlePath+ });- const childItems = await getAutocompleteItems(childNote.noteId, childNotePath, childTitlePath);+ const childItems = await getAutocompleteItems(childNote.noteId, childNotePath, childTitlePath);- for (const childItem of childItems) {- autocompleteItems.push(childItem);- }+ for (const childItem of childItems) {+ autocompleteItems.push(childItem);}-- return autocompleteItems;}- function setNoteTitle(noteId, title) {- utils.assertArguments(noteId);-- getNote(noteId).title = title;+ return autocompleteItems;+}- getNodesByNoteId(noteId).map(clone => setNodeTitleWithPrefix(clone));- }+function setNoteTitle(noteId, title) {+ utils.assertArguments(noteId);- async function createNewTopLevelNote() {- const rootNode = $tree.fancytree("getRootNode");+ getNote(noteId).title = title;- await createNote(rootNode, "root", "into");- }+ getNodesByNoteId(noteId).map(clone => setNodeTitleWithPrefix(clone));+}- async function createNote(node, parentNoteId, target, isProtected) {- utils.assertArguments(node, parentNoteId, target);+async function createNewTopLevelNote() {+ const rootNode = $tree.fancytree("getRootNode");- // 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- if (!isProtected || !protected_session.isProtectedSessionAvailable()) {- isProtected = false;- }+ await createNote(rootNode, "root", "into");+}- const newNoteName = "new note";+async function createNote(node, parentNoteId, target, isProtected) {+ utils.assertArguments(node, parentNoteId, target);- const result = await server.post('notes/' + parentNoteId + '/children', {- title: newNoteName,- target: target,- target_branchId: node.data.branchId,- isProtected: isProtected- });+ // 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+ if (!isProtected || !protected_session.isProtectedSessionAvailable()) {+ isProtected = false;+ }- const note = new NoteShort(treeCache, {- noteId: result.noteId,- title: result.title,- isProtected: result.isProtected,- type: result.type,- mime: result.mime- });+ const newNoteName = "new note";- const branch = new Branch(treeCache, result);+ const result = await server.post('notes/' + parentNoteId + '/children', {+ title: newNoteName,+ target: target,+ target_branchId: node.data.branchId,+ isProtected: isProtected+ });- treeCache.add(note, branch);+ const note = new NoteShort(treeCache, {+ noteId: result.noteId,+ title: result.title,+ isProtected: result.isProtected,+ type: result.type,+ mime: result.mime+ });- noteEditor.newNoteCreated();+ const branch = new Branch(treeCache, result);- const newNode = {- title: newNoteName,- noteId: result.noteId,- parentNoteId: parentNoteId,- refKey: result.noteId,- branchId: result.branchId,- isProtected: isProtected,- extraClasses: await getExtraClasses(note)- };+ treeCache.add(note, branch);- if (target === 'after') {- await node.appendSibling(newNode).setActive(true);- }- else if (target === 'into') {- if (!node.getChildren() && node.isFolder()) {- await node.setExpanded();- }- else {- node.addChildren(newNode);- }+ noteEditor.newNoteCreated();- await node.getLastChild().setActive(true);+ const newNode = {+ title: newNoteName,+ noteId: result.noteId,+ parentNoteId: parentNoteId,+ refKey: result.noteId,+ branchId: result.branchId,+ isProtected: isProtected,+ extraClasses: await getExtraClasses(note)+ };- node.folder = true;- node.renderTitle();+ if (target === 'after') {+ await node.appendSibling(newNode).setActive(true);+ }+ else if (target === 'into') {+ if (!node.getChildren() && node.isFolder()) {+ await node.setExpanded();}else {- utils.throwError("Unrecognized target: " + target);+ node.addChildren(newNode);}- clearSelectedNodes(); // to unmark previously active node+ await node.getLastChild().setActive(true);- utils.showMessage("Created!");+ node.folder = true;+ node.renderTitle();}-- async function sortAlphabetically(noteId) {- await server.put('notes/' + noteId + '/sort');-- await reload();+ else {+ utils.throwError("Unrecognized target: " + target);}- async function noteExists(noteId) {- return !!treeCache.getNote(noteId);- }+ clearSelectedNodes(); // to unmark previously active node- function getInstanceName() {- return instanceName;- }+ utils.showMessage("Created!");+}- function getBranch(branchId) {- return branchMap[branchId];- }+async function sortAlphabetically(noteId) {+ await server.put('notes/' + noteId + '/sort');- $(document).bind('keydown', 'ctrl+o', e => {- const node = getCurrentNode();- const parentNoteId = node.data.parentNoteId;- const isProtected = treeUtils.getParentProtectedStatus(node);+ await reload();+}- createNote(node, parentNoteId, 'after', isProtected);+async function noteExists(noteId) {+ return !!treeCache.getNote(noteId);+}- e.preventDefault();- });+function getInstanceName() {+ return instanceName;+}- $(document).bind('keydown', 'ctrl+p', e => {- const node = getCurrentNode();+function getBranch(branchId) {+ return branchMap[branchId];+}- createNote(node, node.data.noteId, 'into', node.data.isProtected);+$(document).bind('keydown', 'ctrl+o', e => {+ const node = getCurrentNode();+ const parentNoteId = node.data.parentNoteId;+ const isProtected = treeUtils.getParentProtectedStatus(node);- e.preventDefault();- });+ createNote(node, parentNoteId, 'after', isProtected);- $(document).bind('keydown', 'ctrl+del', e => {- const node = getCurrentNode();+ e.preventDefault();+});- treeChanges.deleteNodes([node]);+$(document).bind('keydown', 'ctrl+p', e => {+ const node = getCurrentNode();- e.preventDefault();- });+ createNote(node, node.data.noteId, 'into', node.data.isProtected);- $(document).bind('keydown', 'ctrl+.', scrollToCurrentNote);+ e.preventDefault();+});- $(window).bind('hashchange', function() {- const notePath = getNotePathFromAddress();+$(document).bind('keydown', 'ctrl+del', e => {+ const node = getCurrentNode();- if (getCurrentNotePath() !== notePath) {- console.log("Switching to " + notePath + " because of hash change");+ treeChanges.deleteNodes([node]);- activateNode(notePath);- }- });+ e.preventDefault();+});- if (utils.isElectron()) {- $(document).bind('keydown', 'alt+left', e => {- window.history.back();+$(document).bind('keydown', 'ctrl+.', scrollToCurrentNote);- e.preventDefault();- });+$(window).bind('hashchange', function() {+ const notePath = getNotePathFromAddress();- $(document).bind('keydown', 'alt+right', e => {- window.history.forward();+ if (getCurrentNotePath() !== notePath) {+ console.log("Switching to " + notePath + " because of hash change");- e.preventDefault();- });+ activateNode(notePath);}+});- $createTopLevelNoteButton.click(createNewTopLevelNote);- $collapseTreeButton.click(collapseTree);- $scrollToCurrentNoteButton.click(scrollToCurrentNote);-- return {- reload,- collapseTree,- scrollToCurrentNote,- setBranchBackgroundBasedOnProtectedStatus,- setProtected,- getCurrentNode,- expandToNote,- activateNode,- getCurrentNotePath,- getNoteTitle,- setCurrentNotePathToHash,- getAutocompleteItems,- setNoteTitle,- createNewTopLevelNote,- createNote,- setPrefix,- getNotePathTitle,- removeParentChildRelation,- setParentChildRelation,- getSelectedNodes,- sortAlphabetically,- noteExists,- getInstanceName,- getBranch,- getNote- };-})();\ No newline at end of file+if (utils.isElectron()) {+ $(document).bind('keydown', 'alt+left', e => {+ window.history.back();++ e.preventDefault();+ });++ $(document).bind('keydown', 'alt+right', e => {+ window.history.forward();++ e.preventDefault();+ });+}++$createTopLevelNoteButton.click(createNewTopLevelNote);+$collapseTreeButton.click(collapseTree);+$scrollToCurrentNoteButton.click(scrollToCurrentNote);++export default {+ reload,+ collapseTree,+ scrollToCurrentNote,+ setBranchBackgroundBasedOnProtectedStatus,+ setProtected,+ getCurrentNode,+ expandToNote,+ activateNode,+ getCurrentNotePath,+ getNoteTitle,+ setCurrentNotePathToHash,+ getAutocompleteItems,+ setNoteTitle,+ createNewTopLevelNote,+ createNote,+ setPrefix,+ getNotePathTitle,+ removeParentChildRelation,+ setParentChildRelation,+ getSelectedNodes,+ sortAlphabetically,+ noteExists,+ getInstanceName,+ getBranch,+ getNote+};\ No newline at end of filediff --git a/src/public/javascripts/note_type.js b/src/public/javascripts/note_type.jsindex 9403da589e..980d7f7bb1 100644--- a/src/public/javascripts/note_type.js+++ b/src/public/javascripts/note_type.js@@ -1,145 +1,147 @@"use strict";-const noteType = (function() {- const $executeScriptButton = $("#execute-script-button");- const noteTypeModel = new NoteTypeModel();-- function NoteTypeModel() {- const self = this;-- this.type = ko.observable('text');- this.mime = ko.observable('');-- this.codeMimeTypes = ko.observableArray([- { mime: 'text/x-csrc', title: 'C' },- { mime: 'text/x-c++src', title: 'C++' },- { mime: 'text/x-csharp', title: 'C#' },- { mime: 'text/x-clojure', title: 'Clojure' },- { mime: 'text/css', title: 'CSS' },- { mime: 'text/x-dockerfile', title: 'Dockerfile' },- { mime: 'text/x-erlang', title: 'Erlang' },- { mime: 'text/x-feature', title: 'Gherkin' },- { mime: 'text/x-go', title: 'Go' },- { mime: 'text/x-groovy', title: 'Groovy' },- { mime: 'text/x-haskell', title: 'Haskell' },- { mime: 'text/html', title: 'HTML' },- { mime: 'message/http', title: 'HTTP' },- { mime: 'text/x-java', title: 'Java' },- { mime: 'application/javascript;env=frontend', title: 'JavaScript frontend' },- { mime: 'application/javascript;env=backend', title: 'JavaScript backend' },- { mime: 'application/json', title: 'JSON' },- { mime: 'text/x-kotlin', title: 'Kotlin' },- { mime: 'text/x-lua', title: 'Lua' },- { mime: 'text/x-markdown', title: 'Markdown' },- { mime: 'text/x-objectivec', title: 'Objective C' },- { mime: 'text/x-pascal', title: 'Pascal' },- { mime: 'text/x-perl', title: 'Perl' },- { mime: 'text/x-php', title: 'PHP' },- { mime: 'text/x-python', title: 'Python' },- { mime: 'text/x-ruby', title: 'Ruby' },- { mime: 'text/x-rustsrc', title: 'Rust' },- { mime: 'text/x-scala', title: 'Scala' },- { mime: 'text/x-sh', title: 'Shell' },- { mime: 'text/x-sql', title: 'SQL' },- { mime: 'text/x-swift', title: 'Swift' },- { mime: 'text/xml', title: 'XML' },- { mime: 'text/x-yaml', title: 'YAML' }- ]);-- this.typeString = function() {- const type = self.type();- const mime = self.mime();-- if (type === 'text') {- return 'Text';- }- else if (type === 'code') {- if (!mime) {- return 'Code';- }- else {- const found = self.codeMimeTypes().find(x => x.mime === mime);-- return found ? found.title : mime;- }- }- else if (type === 'render') {- return 'Render HTML note';- }- else if (type === 'file') {- return 'Attachment';- }- else if (type === 'search') {- // ignore and do nothing, "type" will be hidden since it's not possible to switch to and from search+import treeService from './note_tree.js';+import noteEditor from './note_editor.js';+import utils from './utils.js';++const $executeScriptButton = $("#execute-script-button");+const noteTypeModel = new NoteTypeModel();++function NoteTypeModel() {+ const self = this;++ this.type = ko.observable('text');+ this.mime = ko.observable('');++ this.codeMimeTypes = ko.observableArray([+ { mime: 'text/x-csrc', title: 'C' },+ { mime: 'text/x-c++src', title: 'C++' },+ { mime: 'text/x-csharp', title: 'C#' },+ { mime: 'text/x-clojure', title: 'Clojure' },+ { mime: 'text/css', title: 'CSS' },+ { mime: 'text/x-dockerfile', title: 'Dockerfile' },+ { mime: 'text/x-erlang', title: 'Erlang' },+ { mime: 'text/x-feature', title: 'Gherkin' },+ { mime: 'text/x-go', title: 'Go' },+ { mime: 'text/x-groovy', title: 'Groovy' },+ { mime: 'text/x-haskell', title: 'Haskell' },+ { mime: 'text/html', title: 'HTML' },+ { mime: 'message/http', title: 'HTTP' },+ { mime: 'text/x-java', title: 'Java' },+ { mime: 'application/javascript;env=frontend', title: 'JavaScript frontend' },+ { mime: 'application/javascript;env=backend', title: 'JavaScript backend' },+ { mime: 'application/json', title: 'JSON' },+ { mime: 'text/x-kotlin', title: 'Kotlin' },+ { mime: 'text/x-lua', title: 'Lua' },+ { mime: 'text/x-markdown', title: 'Markdown' },+ { mime: 'text/x-objectivec', title: 'Objective C' },+ { mime: 'text/x-pascal', title: 'Pascal' },+ { mime: 'text/x-perl', title: 'Perl' },+ { mime: 'text/x-php', title: 'PHP' },+ { mime: 'text/x-python', title: 'Python' },+ { mime: 'text/x-ruby', title: 'Ruby' },+ { mime: 'text/x-rustsrc', title: 'Rust' },+ { mime: 'text/x-scala', title: 'Scala' },+ { mime: 'text/x-sh', title: 'Shell' },+ { mime: 'text/x-sql', title: 'SQL' },+ { mime: 'text/x-swift', title: 'Swift' },+ { mime: 'text/xml', title: 'XML' },+ { mime: 'text/x-yaml', title: 'YAML' }+ ]);++ this.typeString = function() {+ const type = self.type();+ const mime = self.mime();++ if (type === 'text') {+ return 'Text';+ }+ else if (type === 'code') {+ if (!mime) {+ return 'Code';}else {- utils.throwError('Unrecognized type: ' + type);+ const found = self.codeMimeTypes().find(x => x.mime === mime);++ return found ? found.title : mime;}- };+ }+ else if (type === 'render') {+ return 'Render HTML note';+ }+ else if (type === 'file') {+ return 'Attachment';+ }+ else if (type === 'search') {+ // ignore and do nothing, "type" will be hidden since it's not possible to switch to and from search+ }+ else {+ utils.throwError('Unrecognized type: ' + type);+ }+ };- this.isDisabled = function() {- return self.type() === "file";- };+ this.isDisabled = function() {+ return self.type() === "file";+ };- async function save() {- const note = noteEditor.getCurrentNote();+ async function save() {+ const note = noteEditor.getCurrentNote();- await server.put('notes/' + note.detail.noteId- + '/type/' + encodeURIComponent(self.type())- + '/mime/' + encodeURIComponent(self.mime()));+ await server.put('notes/' + note.detail.noteId+ + '/type/' + encodeURIComponent(self.type())+ + '/mime/' + encodeURIComponent(self.mime()));- await noteEditor.reload();+ await noteEditor.reload();- // for the note icon to be updated in the tree- await treeService.reload();+ // for the note icon to be updated in the tree+ await treeService.reload();- self.updateExecuteScriptButtonVisibility();- }+ self.updateExecuteScriptButtonVisibility();+ }- this.selectText = function() {- self.type('text');- self.mime('');+ this.selectText = function() {+ self.type('text');+ self.mime('');- save();- };+ save();+ };- this.selectRender = function() {- self.type('render');- self.mime('');+ this.selectRender = function() {+ self.type('render');+ self.mime('');- save();- };+ save();+ };- this.selectCode = function() {- self.type('code');- self.mime('');+ this.selectCode = function() {+ self.type('code');+ self.mime('');- save();- };+ save();+ };- this.selectCodeMime = function(el) {- self.type('code');- self.mime(el.mime);+ this.selectCodeMime = function(el) {+ self.type('code');+ self.mime(el.mime);- save();- };+ save();+ };- this.updateExecuteScriptButtonVisibility = function() {- $executeScriptButton.toggle(self.mime().startsWith('application/javascript'));- }+ this.updateExecuteScriptButtonVisibility = function() {+ $executeScriptButton.toggle(self.mime().startsWith('application/javascript'));}+}- ko.applyBindings(noteTypeModel, document.getElementById('note-type'));+ko.applyBindings(noteTypeModel, document.getElementById('note-type'));- return {- getNoteType: () => noteTypeModel.type(),- setNoteType: type => noteTypeModel.type(type),+export default {+ getNoteType: () => noteTypeModel.type(),+ setNoteType: type => noteTypeModel.type(type),- getNoteMime: () => noteTypeModel.mime(),- setNoteMime: mime => {- noteTypeModel.mime(mime);+ getNoteMime: () => noteTypeModel.mime(),+ setNoteMime: mime => {+ noteTypeModel.mime(mime);- noteTypeModel.updateExecuteScriptButtonVisibility();- }- };-})();\ No newline at end of file+ noteTypeModel.updateExecuteScriptButtonVisibility();+ }+};\ No newline at end of filediff --git a/src/public/javascripts/protected_session.js b/src/public/javascripts/protected_session.jsindex 7402d114fe..9f66e53f48 100644--- a/src/public/javascripts/protected_session.js+++ b/src/public/javascripts/protected_session.js@@ -1,189 +1,192 @@"use strict";-const protected_session = (function() {- const $dialog = $("#protected-session-password-dialog");- const $passwordForm = $("#protected-session-password-form");- const $password = $("#protected-session-password");- const $noteDetailWrapper = $("#note-detail-wrapper");- const $protectButton = $("#protect-button");- const $unprotectButton = $("#unprotect-button");-- let protectedSessionDeferred = null;- let lastProtectedSessionOperationDate = null;- let protectedSessionTimeout = null;- let protectedSessionId = null;-- $(document).ready(() => {- server.get('settings/all').then(settings => protectedSessionTimeout = settings.protected_session_timeout);- });+import treeService from './note_tree.js';+import noteEditor from './note_editor.js';+import utils from './utils.js';+import server from './server.js';++const $dialog = $("#protected-session-password-dialog");+const $passwordForm = $("#protected-session-password-form");+const $password = $("#protected-session-password");+const $noteDetailWrapper = $("#note-detail-wrapper");+const $protectButton = $("#protect-button");+const $unprotectButton = $("#unprotect-button");++let protectedSessionDeferred = null;+let lastProtectedSessionOperationDate = null;+let protectedSessionTimeout = null;+let protectedSessionId = null;++$(document).ready(() => {+ server.get('settings/all').then(settings => protectedSessionTimeout = settings.protected_session_timeout);+});++function setProtectedSessionTimeout(encSessTimeout) {+ protectedSessionTimeout = encSessTimeout;+}++function ensureProtectedSession(requireProtectedSession, modal) {+ const dfd = $.Deferred();++ if (requireProtectedSession && !isProtectedSessionAvailable()) {+ protectedSessionDeferred = dfd;++ if (treeService.getCurrentNode().data.isProtected) {+ $noteDetailWrapper.hide();+ }- function setProtectedSessionTimeout(encSessTimeout) {- protectedSessionTimeout = encSessTimeout;+ $dialog.dialog({+ modal: modal,+ width: 400,+ open: () => {+ if (!modal) {+ // dialog steals focus for itself, which is not what we want for non-modal (viewing)+ treeService.getCurrentNode().setFocus();+ }+ }+ });+ }+ else {+ dfd.resolve();}- function ensureProtectedSession(requireProtectedSession, modal) {- const dfd = $.Deferred();-- if (requireProtectedSession && !isProtectedSessionAvailable()) {- protectedSessionDeferred = dfd;+ return dfd.promise();+}- if (treeService.getCurrentNode().data.isProtected) {- $noteDetailWrapper.hide();- }+async function setupProtectedSession() {+ const password = $password.val();+ $password.val("");- $dialog.dialog({- modal: modal,- width: 400,- open: () => {- if (!modal) {- // dialog steals focus for itself, which is not what we want for non-modal (viewing)- treeService.getCurrentNode().setFocus();- }- }- });- }- else {- dfd.resolve();- }+ const response = await enterProtectedSession(password);- return dfd.promise();+ if (!response.success) {+ utils.showError("Wrong password.");+ return;}- async function setupProtectedSession() {- const password = $password.val();- $password.val("");-- const response = await enterProtectedSession(password);+ protectedSessionId = response.protectedSessionId;- if (!response.success) {- utils.showError("Wrong password.");- return;- }-- protectedSessionId = response.protectedSessionId;+ $dialog.dialog("close");- $dialog.dialog("close");+ noteEditor.reload();+ treeService.reload();- noteEditor.reload();- treeService.reload();+ if (protectedSessionDeferred !== null) {+ ensureDialogIsClosed($dialog, $password);- if (protectedSessionDeferred !== null) {- ensureDialogIsClosed($dialog, $password);+ $noteDetailWrapper.show();- $noteDetailWrapper.show();+ protectedSessionDeferred.resolve();- protectedSessionDeferred.resolve();-- protectedSessionDeferred = null;- }+ protectedSessionDeferred = null;}+}- function ensureDialogIsClosed() {- // this may fal if the dialog has not been previously opened- try {- $dialog.dialog('close');- }- catch (e) {}-- $password.val('');+function ensureDialogIsClosed() {+ // this may fal if the dialog has not been previously opened+ try {+ $dialog.dialog('close');}+ catch (e) {}- async function enterProtectedSession(password) {- return await server.post('login/protected', {- password: password- });- }+ $password.val('');+}- function getProtectedSessionId() {- return protectedSessionId;- }+async function enterProtectedSession(password) {+ return await server.post('login/protected', {+ password: password+ });+}- function resetProtectedSession() {- protectedSessionId = null;+function getProtectedSessionId() {+ return protectedSessionId;+}- // most secure solution - guarantees nothing remained in memory- // since this expires because user doesn't use the app, it shouldn't be disruptive- utils.reloadApp();- }+function resetProtectedSession() {+ protectedSessionId = null;- function isProtectedSessionAvailable() {- return protectedSessionId !== null;- }+ // most secure solution - guarantees nothing remained in memory+ // since this expires because user doesn't use the app, it shouldn't be disruptive+ utils.reloadApp();+}- async function protectNoteAndSendToServer() {- await ensureProtectedSession(true, true);+function isProtectedSessionAvailable() {+ return protectedSessionId !== null;+}- const note = noteEditor.getCurrentNote();+async function protectNoteAndSendToServer() {+ await ensureProtectedSession(true, true);- noteEditor.updateNoteFromInputs(note);+ const note = noteEditor.getCurrentNote();- note.detail.isProtected = true;+ noteEditor.updateNoteFromInputs(note);- await noteEditor.saveNoteToServer(note);+ note.detail.isProtected = true;- treeService.setProtected(note.detail.noteId, note.detail.isProtected);+ await noteEditor.saveNoteToServer(note);- noteEditor.setNoteBackgroundIfProtected(note);- }+ treeService.setProtected(note.detail.noteId, note.detail.isProtected);- async function unprotectNoteAndSendToServer() {- await ensureProtectedSession(true, true);+ noteEditor.setNoteBackgroundIfProtected(note);+}- const note = noteEditor.getCurrentNote();+async function unprotectNoteAndSendToServer() {+ await ensureProtectedSession(true, true);- noteEditor.updateNoteFromInputs(note);+ const note = noteEditor.getCurrentNote();- note.detail.isProtected = false;+ noteEditor.updateNoteFromInputs(note);- await noteEditor.saveNoteToServer(note);+ note.detail.isProtected = false;- treeService.setProtected(note.detail.noteId, note.detail.isProtected);+ await noteEditor.saveNoteToServer(note);- noteEditor.setNoteBackgroundIfProtected(note);- }+ treeService.setProtected(note.detail.noteId, note.detail.isProtected);- function touchProtectedSession() {- if (isProtectedSessionAvailable()) {- lastProtectedSessionOperationDate = new Date();- }+ noteEditor.setNoteBackgroundIfProtected(note);+}++function touchProtectedSession() {+ if (isProtectedSessionAvailable()) {+ lastProtectedSessionOperationDate = new Date();}+}- async function protectSubTree(noteId, protect) {- await ensureProtectedSession(true, true);+async function protectSubTree(noteId, protect) {+ await ensureProtectedSession(true, true);- await server.put('notes/' + noteId + "/protect-sub-tree/" + (protect ? 1 : 0));+ await server.put('notes/' + noteId + "/protect-sub-tree/" + (protect ? 1 : 0));- utils.showMessage("Request to un/protect sub tree has finished successfully");+ utils.showMessage("Request to un/protect sub tree has finished successfully");- treeService.reload();- noteEditor.reload();- }+ treeService.reload();+ noteEditor.reload();+}- $passwordForm.submit(() => {- setupProtectedSession();+$passwordForm.submit(() => {+ setupProtectedSession();- return false;- });+ return false;+});- setInterval(() => {- if (lastProtectedSessionOperationDate !== null && new Date().getTime() - lastProtectedSessionOperationDate.getTime() > protectedSessionTimeout * 1000) {- resetProtectedSession();- }- }, 5000);-- $protectButton.click(protectNoteAndSendToServer);- $unprotectButton.click(unprotectNoteAndSendToServer);-- return {- setProtectedSessionTimeout,- ensureProtectedSession,- resetProtectedSession,- isProtectedSessionAvailable,- protectNoteAndSendToServer,- unprotectNoteAndSendToServer,- getProtectedSessionId,- touchProtectedSession,- protectSubTree,- ensureDialogIsClosed- };-})();\ No newline at end of file+setInterval(() => {+ if (lastProtectedSessionOperationDate !== null && new Date().getTime() - lastProtectedSessionOperationDate.getTime() > protectedSessionTimeout * 1000) {+ resetProtectedSession();+ }+}, 5000);++$protectButton.click(protectNoteAndSendToServer);+$unprotectButton.click(unprotectNoteAndSendToServer);++export default {+ setProtectedSessionTimeout,+ ensureProtectedSession,+ resetProtectedSession,+ isProtectedSessionAvailable,+ protectNoteAndSendToServer,+ unprotectNoteAndSendToServer,+ getProtectedSessionId,+ touchProtectedSession,+ protectSubTree,+ ensureDialogIsClosed+};\ No newline at end of filediff --git a/src/public/javascripts/script_api.js b/src/public/javascripts/script_api.jsindex 8038e795c9..7cb1f31329 100644--- a/src/public/javascripts/script_api.js+++ b/src/public/javascripts/script_api.js@@ -1,3 +1,5 @@+import treeService from './note_tree.js';+function ScriptApi(startNote, currentNote) {const $pluginButtons = $("#plugin-buttons");@@ -51,4 +53,6 @@ function ScriptApi(startNote, currentNote) {getInstanceName: treeService.getInstanceName,runOnServer}-}\ No newline at end of file+}++export default ScriptApi;\ No newline at end of filediff --git a/src/public/javascripts/script_context.js b/src/public/javascripts/script_context.jsindex bf8ee68efa..0b77b037f2 100644--- a/src/public/javascripts/script_context.js+++ b/src/public/javascripts/script_context.js@@ -1,3 +1,8 @@+"use strict";++import ScriptApi from './script_api.js';+import utils from './utils.js';+function ScriptContext(startNote, allNotes) {const modules = {};@@ -18,4 +23,6 @@ function ScriptContext(startNote, allNotes) {}}};-}\ No newline at end of file+}++export default ScriptContext;\ No newline at end of filediff --git a/src/public/javascripts/search_tree.js b/src/public/javascripts/search_tree.jsindex bc28dfb36e..906250b734 100644--- a/src/public/javascripts/search_tree.js+++ b/src/public/javascripts/search_tree.js@@ -1,5 +1,7 @@"use strict";+import treeService from './note_tree.js';+const $tree = $("#tree");const $searchInput = $("input[name='search-text']");const $resetSearchButton = $("#reset-search-button");diff --git a/src/public/javascripts/server.js b/src/public/javascripts/server.jsindex fbd8693e26..eed75110b9 100644--- a/src/public/javascripts/server.js+++ b/src/public/javascripts/server.js@@ -1,101 +1,104 @@-const server = (function() {- function getHeaders() {- let protectedSessionId = null;-- try { // this is because protected session might not be declared in some cases - like when it's included in migration page- protectedSessionId = protected_session.getProtectedSessionId();- }- catch(e) {}-- // headers need to be lowercase because node.js automatically converts them to lower case- // so hypothetical protectedSessionId becomes protectedsessionid on the backend- return {- protected_session_id: protectedSessionId,- source_id: glob.sourceId- };- }+"use strict";- async function get(url) {- return await call('GET', url);- }+import protected_session from './protected_session.js';+import utils from './utils.js';- async function post(url, data) {- return await call('POST', url, data);- }+function getHeaders() {+ let protectedSessionId = null;- async function put(url, data) {- return await call('PUT', url, data);+ try { // this is because protected session might not be declared in some cases - like when it's included in migration page+ protectedSessionId = protected_session.getProtectedSessionId();}+ catch(e) {}- async function remove(url) {- return await call('DELETE', url);- }+ // headers need to be lowercase because node.js automatically converts them to lower case+ // so hypothetical protectedSessionId becomes protectedsessionid on the backend+ return {+ protected_session_id: protectedSessionId,+ source_id: glob.sourceId+ };+}- let i = 1;- const reqResolves = {};+async function get(url) {+ return await call('GET', url);+}- async function call(method, url, data) {- if (utils.isElectron()) {- const ipc = require('electron').ipcRenderer;- const requestId = i++;+async function post(url, data) {+ return await call('POST', url, data);+}- return new Promise((resolve, reject) => {- reqResolves[requestId] = resolve;+async function put(url, data) {+ return await call('PUT', url, data);+}- console.log(utils.now(), "Request #" + requestId + " to " + method + " " + url);+async function remove(url) {+ return await call('DELETE', url);+}- ipc.send('server-request', {- requestId: requestId,- headers: getHeaders(),- method: method,- url: "/" + baseApiUrl + url,- data: data- });- });- }- else {- return await ajax(url, method, data);- }- }+let i = 1;+const reqResolves = {};+async function call(method, url, data) {if (utils.isElectron()) {const ipc = require('electron').ipcRenderer;+ const requestId = i++;- ipc.on('server-response', (event, arg) => {- console.log(utils.now(), "Response #" + arg.requestId + ": " + arg.statusCode);+ return new Promise((resolve, reject) => {+ reqResolves[requestId] = resolve;- reqResolves[arg.requestId](arg.body);+ console.log(utils.now(), "Request #" + requestId + " to " + method + " " + url);- delete reqResolves[arg.requestId];+ ipc.send('server-request', {+ requestId: requestId,+ headers: getHeaders(),+ method: method,+ url: "/" + baseApiUrl + url,+ data: data+ });});}-- async function ajax(url, method, data) {- const options = {- url: baseApiUrl + url,- type: method,- headers: getHeaders()- };-- if (data) {- options.data = JSON.stringify(data);- options.contentType = "application/json";- }-- return await $.ajax(options).catch(e => {- const message = "Error when calling " + method + " " + url + ": " + e.status + " - " + e.statusText;- utils.showError(message);- utils.throwError(message);- });+ else {+ return await ajax(url, method, data);}+}- return {- get,- post,- put,- remove,- ajax,- // don't remove, used from CKEditor image upload!- getHeaders+if (utils.isElectron()) {+ const ipc = require('electron').ipcRenderer;++ ipc.on('server-response', (event, arg) => {+ console.log(utils.now(), "Response #" + arg.requestId + ": " + arg.statusCode);++ reqResolves[arg.requestId](arg.body);++ delete reqResolves[arg.requestId];+ });+}++async function ajax(url, method, data) {+ const options = {+ url: baseApiUrl + url,+ type: method,+ headers: getHeaders()+ };++ if (data) {+ options.data = JSON.stringify(data);+ options.contentType = "application/json";}-})();\ No newline at end of file++ return await $.ajax(options).catch(e => {+ const message = "Error when calling " + method + " " + url + ": " + e.status + " - " + e.statusText;+ utils.showError(message);+ utils.throwError(message);+ });+}++export default {+ get,+ post,+ put,+ remove,+ ajax,+ // don't remove, used from CKEditor image upload!+ getHeaders+};\ No newline at end of filediff --git a/src/public/javascripts/sync.js b/src/public/javascripts/sync.jsindex 43cf217b5c..faa431c74d 100644--- a/src/public/javascripts/sync.js+++ b/src/public/javascripts/sync.js@@ -1,31 +1,31 @@"use strict";-const syncService = (function() {- async function syncNow() {- const result = await server.post('sync/now');+import utils from './utils.js';- if (result.success) {- utils.showMessage("Sync finished successfully.");- }- else {- if (result.message.length > 50) {- result.message = result.message.substr(0, 50);- }+async function syncNow() {+ const result = await server.post('sync/now');- utils.showError("Sync failed: " + result.message);+ if (result.success) {+ utils.showMessage("Sync finished successfully.");+ }+ else {+ if (result.message.length > 50) {+ result.message = result.message.substr(0, 50);}++ utils.showError("Sync failed: " + result.message);}+}- $("#sync-now-button").click(syncNow);+$("#sync-now-button").click(syncNow);- async function forceNoteSync(noteId) {- const result = await server.post('sync/force-note-sync/' + noteId);+async function forceNoteSync(noteId) {+ const result = await server.post('sync/force-note-sync/' + noteId);- utils.showMessage("Note added to sync queue.");- }+ utils.showMessage("Note added to sync queue.");+}- return {- syncNow,- forceNoteSync- };-})();\ No newline at end of file+export default {+ syncNow,+ forceNoteSync+};\ No newline at end of filediff --git a/src/public/javascripts/tree_changes.js b/src/public/javascripts/tree_changes.jsindex c478b1c847..6238ca3ed8 100644--- a/src/public/javascripts/tree_changes.js+++ b/src/public/javascripts/tree_changes.js@@ -1,132 +1,133 @@"use strict";-const treeChanges = (function() {- async function moveBeforeNode(nodesToMove, beforeNode) {- for (const nodeToMove of nodesToMove) {- const resp = await server.put('tree/' + nodeToMove.data.branchId + '/move-before/' + beforeNode.data.branchId);+import treeService from './note_tree.js';+import utils from './utils.js';- if (!resp.success) {- alert(resp.message);- return;- }+async function moveBeforeNode(nodesToMove, beforeNode) {+ for (const nodeToMove of nodesToMove) {+ const resp = await server.put('tree/' + nodeToMove.data.branchId + '/move-before/' + beforeNode.data.branchId);- changeNode(nodeToMove, node => node.moveTo(beforeNode, 'before'));+ if (!resp.success) {+ alert(resp.message);+ return;}- }- async function moveAfterNode(nodesToMove, afterNode) {- nodesToMove.reverse(); // need to reverse to keep the note order+ changeNode(nodeToMove, node => node.moveTo(beforeNode, 'before'));+ }+}- for (const nodeToMove of nodesToMove) {- const resp = await server.put('tree/' + nodeToMove.data.branchId + '/move-after/' + afterNode.data.branchId);+async function moveAfterNode(nodesToMove, afterNode) {+ nodesToMove.reverse(); // need to reverse to keep the note order- if (!resp.success) {- alert(resp.message);- return;- }+ for (const nodeToMove of nodesToMove) {+ const resp = await server.put('tree/' + nodeToMove.data.branchId + '/move-after/' + afterNode.data.branchId);- changeNode(nodeToMove, node => node.moveTo(afterNode, 'after'));+ if (!resp.success) {+ alert(resp.message);+ return;}++ changeNode(nodeToMove, node => node.moveTo(afterNode, 'after'));}+}- async function moveToNode(nodesToMove, toNode) {- for (const nodeToMove of nodesToMove) {- const resp = await server.put('tree/' + nodeToMove.data.branchId + '/move-to/' + toNode.data.noteId);+async function moveToNode(nodesToMove, toNode) {+ for (const nodeToMove of nodesToMove) {+ const resp = await server.put('tree/' + nodeToMove.data.branchId + '/move-to/' + toNode.data.noteId);- if (!resp.success) {- alert(resp.message);- return;- }+ if (!resp.success) {+ alert(resp.message);+ return;+ }- changeNode(nodeToMove, node => {- // first expand which will force lazy load and only then move the node- // if this is not expanded before moving, then lazy load won't happen because it already contains node- // this doesn't work if this isn't a folder yet, that's why we expand second time below- toNode.setExpanded(true);+ changeNode(nodeToMove, node => {+ // first expand which will force lazy load and only then move the node+ // if this is not expanded before moving, then lazy load won't happen because it already contains node+ // this doesn't work if this isn't a folder yet, that's why we expand second time below+ toNode.setExpanded(true);- node.moveTo(toNode);+ node.moveTo(toNode);- toNode.folder = true;- toNode.renderTitle();+ toNode.folder = true;+ toNode.renderTitle();- // this expands the note in case it become the folder only after the move- toNode.setExpanded(true);- });- }+ // this expands the note in case it become the folder only after the move+ toNode.setExpanded(true);+ });}+}- async function deleteNodes(nodes) {- if (nodes.length === 0 || !confirm('Are you sure you want to delete select note(s) and all the sub-notes?')) {- return;- }-- for (const node of nodes) {- await server.remove('tree/' + node.data.branchId);- }-- // following code assumes that nodes contain only top-most selected nodes - getSelectedNodes has been- // called with stopOnParent=true- let next = nodes[nodes.length - 1].getNextSibling();+async function deleteNodes(nodes) {+ if (nodes.length === 0 || !confirm('Are you sure you want to delete select note(s) and all the sub-notes?')) {+ return;+ }- if (!next) {- next = nodes[0].getPrevSibling();- }+ for (const node of nodes) {+ await server.remove('tree/' + node.data.branchId);+ }- if (!next && !utils.isTopLevelNode(nodes[0])) {- next = nodes[0].getParent();- }+ // following code assumes that nodes contain only top-most selected nodes - getSelectedNodes has been+ // called with stopOnParent=true+ let next = nodes[nodes.length - 1].getNextSibling();- if (next) {- // activate next element after this one is deleted so we don't lose focus- next.setActive();+ if (!next) {+ next = nodes[0].getPrevSibling();+ }- treeService.setCurrentNotePathToHash(next);- }+ if (!next && !utils.isTopLevelNode(nodes[0])) {+ next = nodes[0].getParent();+ }- treeService.reload();+ if (next) {+ // activate next element after this one is deleted so we don't lose focus+ next.setActive();- utils.showMessage("Note(s) has been deleted.");+ treeService.setCurrentNotePathToHash(next);}- async function moveNodeUpInHierarchy(node) {- if (utils.isTopLevelNode(node)) {- return;- }+ treeService.reload();- const resp = await server.put('tree/' + node.data.branchId + '/move-after/' + node.getParent().data.branchId);+ utils.showMessage("Note(s) has been deleted.");+}- if (!resp.success) {- alert(resp.message);- return;- }+async function moveNodeUpInHierarchy(node) {+ if (utils.isTopLevelNode(node)) {+ return;+ }- if (!utils.isTopLevelNode(node) && node.getParent().getChildren().length <= 1) {- node.getParent().folder = false;- node.getParent().renderTitle();- }+ const resp = await server.put('tree/' + node.data.branchId + '/move-after/' + node.getParent().data.branchId);- changeNode(node, node => node.moveTo(node.getParent(), 'after'));+ if (!resp.success) {+ alert(resp.message);+ return;}- function changeNode(node, func) {- utils.assertArguments(node.data.parentNoteId, node.data.noteId);+ if (!utils.isTopLevelNode(node) && node.getParent().getChildren().length <= 1) {+ node.getParent().folder = false;+ node.getParent().renderTitle();+ }- treeService.removeParentChildRelation(node.data.parentNoteId, node.data.noteId);+ changeNode(node, node => node.moveTo(node.getParent(), 'after'));+}- func(node);+function changeNode(node, func) {+ utils.assertArguments(node.data.parentNoteId, node.data.noteId);- node.data.parentNoteId = utils.isTopLevelNode(node) ? 'root' : node.getParent().data.noteId;+ treeService.removeParentChildRelation(node.data.parentNoteId, node.data.noteId);- treeService.setParentChildRelation(node.data.branchId, node.data.parentNoteId, node.data.noteId);+ func(node);- treeService.setCurrentNotePathToHash(node);- }+ node.data.parentNoteId = utils.isTopLevelNode(node) ? 'root' : node.getParent().data.noteId;++ treeService.setParentChildRelation(node.data.branchId, node.data.parentNoteId, node.data.noteId);++ treeService.setCurrentNotePathToHash(node);+}- return {- moveBeforeNode,- moveAfterNode,- moveToNode,- deleteNodes,- moveNodeUpInHierarchy- };-})();\ No newline at end of file+export default {+ moveBeforeNode,+ moveAfterNode,+ moveToNode,+ deleteNodes,+ moveNodeUpInHierarchy+};\ No newline at end of filediff --git a/src/public/javascripts/tree_utils.js b/src/public/javascripts/tree_utils.jsindex a431dede5b..bd15439eda 100644--- a/src/public/javascripts/tree_utils.js+++ b/src/public/javascripts/tree_utils.js@@ -1,40 +1,40 @@"use strict";-const treeUtils = (function() {- const $tree = $("#tree");+import utils from './utils.js';- function getParentProtectedStatus(node) {- return utils.isTopLevelNode(node) ? 0 : node.getParent().data.isProtected;- }+const $tree = $("#tree");- function getNodeByKey(key) {- return $tree.fancytree('getNodeByKey', key);- }+function getParentProtectedStatus(node) {+ return utils.isTopLevelNode(node) ? 0 : node.getParent().data.isProtected;+}- function getNoteIdFromNotePath(notePath) {- const path = notePath.split("/");+function getNodeByKey(key) {+ return $tree.fancytree('getNodeByKey', key);+}- return path[path.length - 1];- }+function getNoteIdFromNotePath(notePath) {+ const path = notePath.split("/");- function getNotePath(node) {- const path = [];+ return path[path.length - 1];+}- while (node && !utils.isRootNode(node)) {- if (node.data.noteId) {- path.push(node.data.noteId);- }+function getNotePath(node) {+ const path = [];- node = node.getParent();+ while (node && !utils.isRootNode(node)) {+ if (node.data.noteId) {+ path.push(node.data.noteId);}- return path.reverse().join("/");+ node = node.getParent();}- return {- getParentProtectedStatus,- getNodeByKey,- getNotePath,- getNoteIdFromNotePath,- };-})();\ No newline at end of file+ return path.reverse().join("/");+}++export default {+ getParentProtectedStatus,+ getNodeByKey,+ getNotePath,+ getNoteIdFromNotePath,+};\ No newline at end of filediff --git a/src/public/javascripts/utils.js b/src/public/javascripts/utils.jsindex 512f417133..5ec6c7a764 100644--- a/src/public/javascripts/utils.js+++ b/src/public/javascripts/utils.js@@ -1,270 +1,272 @@"use strict";-const utils = (function() {- function reloadApp() {- window.location.reload(true);+import link from './link.js';+import messaging from './messaging.js';+import ScriptContext from './script_context.js';++function reloadApp() {+ window.location.reload(true);+}++function showMessage(message) {+ console.log(now(), "message: ", message);++ $.notify({+ // options+ message: message+ }, {+ // settings+ type: 'success',+ delay: 3000+ });+}++function showError(message, delay = 10000) {+ console.log(now(), "error: ", message);++ $.notify({+ // options+ message: message+ }, {+ // settings+ type: 'danger',+ delay: delay+ });+}++function throwError(message) {+ messaging.logError(message);++ throw new Error(message);+}++function parseDate(str) {+ try {+ return new Date(Date.parse(str));}-- function showMessage(message) {- console.log(now(), "message: ", message);-- $.notify({- // options- message: message- }, {- // settings- type: 'success',- delay: 3000- });+ catch (e) {+ throw new Error("Can't parse date from " + str + ": " + e.stack);}+}- function showError(message, delay = 10000) {- console.log(now(), "error: ", message);-- $.notify({- // options- message: message- }, {- // settings- type: 'danger',- delay: delay- });- }+function padNum(num) {+ return (num <= 9 ? "0" : "") + num;+}- function throwError(message) {- messaging.logError(message);+function formatTime(date) {+ return padNum(date.getHours()) + ":" + padNum(date.getMinutes());+}- throw new Error(message);- }-- function parseDate(str) {- try {- return new Date(Date.parse(str));- }- catch (e) {- throw new Error("Can't parse date from " + str + ": " + e.stack);- }- }+function formatTimeWithSeconds(date) {+ return padNum(date.getHours()) + ":" + padNum(date.getMinutes()) + ":" + padNum(date.getSeconds());+}- function padNum(num) {- return (num <= 9 ? "0" : "") + num;- }+function formatDate(date) {+ return padNum(date.getDate()) + ". " + padNum(date.getMonth() + 1) + ". " + date.getFullYear();+}- function formatTime(date) {- return padNum(date.getHours()) + ":" + padNum(date.getMinutes());- }+function formatDateISO(date) {+ return date.getFullYear() + "-" + padNum(date.getMonth() + 1) + "-" + padNum(date.getDate());+}- function formatTimeWithSeconds(date) {- return padNum(date.getHours()) + ":" + padNum(date.getMinutes()) + ":" + padNum(date.getSeconds());- }+function formatDateTime(date) {+ return formatDate(date) + " " + formatTime(date);+}- function formatDate(date) {- return padNum(date.getDate()) + ". " + padNum(date.getMonth() + 1) + ". " + date.getFullYear();- }-- function formatDateISO(date) {- return date.getFullYear() + "-" + padNum(date.getMonth() + 1) + "-" + padNum(date.getDate());- }-- function formatDateTime(date) {- return formatDate(date) + " " + formatTime(date);- }-- function now() {- return formatTimeWithSeconds(new Date());- }-- function isElectron() {- return window && window.process && window.process.type;- }+function now() {+ return formatTimeWithSeconds(new Date());+}- function assertArguments() {- for (const i in arguments) {- if (!arguments[i]) {- throwError(`Argument idx#${i} should not be falsy: ${arguments[i]}`);- }- }- }+function isElectron() {+ return window && window.process && window.process.type;+}- function assert(expr, message) {- if (!expr) {- throwError(message);+function assertArguments() {+ for (const i in arguments) {+ if (!arguments[i]) {+ throwError(`Argument idx#${i} should not be falsy: ${arguments[i]}`);}}+}- function isTopLevelNode(node) {- return isRootNode(node.getParent());+function assert(expr, message) {+ if (!expr) {+ throwError(message);}+}- function isRootNode(node) {- return node.key === "root_1";- }+function isTopLevelNode(node) {+ return isRootNode(node.getParent());+}- function escapeHtml(str) {- return $('<div/>').text(str).html();- }+function isRootNode(node) {+ return node.key === "root_1";+}- async function stopWatch(what, func) {- const start = new Date();+function escapeHtml(str) {+ return $('<div/>').text(str).html();+}- const ret = await func();+async function stopWatch(what, func) {+ const start = new Date();- const tookMs = new Date().getTime() - start.getTime();+ const ret = await func();- console.log(`${what} took ${tookMs}ms`);+ const tookMs = new Date().getTime() - start.getTime();- return ret;- }+ console.log(`${what} took ${tookMs}ms`);- async function executeBundle(bundle) {- const apiContext = ScriptContext(bundle.note, bundle.allNotes);+ return ret;+}- return await (function () {- return eval(`const apiContext = this; (async function() { ${bundle.script}\r\n})()`);- }.call(apiContext));- }+async function executeBundle(bundle) {+ const apiContext = ScriptContext(bundle.note, bundle.allNotes);- function formatValueWithWhitespace(val) {- return /[^\w_-]/.test(val) ? '"' + val + '"' : val;- }+ return await (function () {+ return eval(`const apiContext = this; (async function() { ${bundle.script}\r\n})()`);+ }.call(apiContext));+}- function formatLabel(attr) {- let str = "@" + formatValueWithWhitespace(attr.name);+function formatValueWithWhitespace(val) {+ return /[^\w_-]/.test(val) ? '"' + val + '"' : val;+}- if (attr.value !== "") {- str += "=" + formatValueWithWhitespace(attr.value);- }+function formatLabel(attr) {+ let str = "@" + formatValueWithWhitespace(attr.name);- return str;+ if (attr.value !== "") {+ str += "=" + formatValueWithWhitespace(attr.value);}- const CKEDITOR = {"js": ["libraries/ckeditor/ckeditor.js"]};-- const CODE_MIRROR = {- js: [- "libraries/codemirror/codemirror.js",- "libraries/codemirror/addon/mode/loadmode.js",- "libraries/codemirror/addon/fold/xml-fold.js",- "libraries/codemirror/addon/edit/matchbrackets.js",- "libraries/codemirror/addon/edit/matchtags.js",- "libraries/codemirror/addon/search/match-highlighter.js",- "libraries/codemirror/mode/meta.js",- "libraries/codemirror/addon/lint/lint.js",- "libraries/codemirror/addon/lint/eslint.js"- ],- css: [- "libraries/codemirror/codemirror.css",- "libraries/codemirror/addon/lint/lint.css"- ]- };-- const ESLINT = {js: ["libraries/eslint.js"]};-- async function requireLibrary(library) {- if (library.css) {- library.css.map(cssUrl => requireCss(cssUrl));- }+ return str;+}++const CKEDITOR = {"js": ["libraries/ckeditor/ckeditor.js"]};++const CODE_MIRROR = {+ js: [+ "libraries/codemirror/codemirror.js",+ "libraries/codemirror/addon/mode/loadmode.js",+ "libraries/codemirror/addon/fold/xml-fold.js",+ "libraries/codemirror/addon/edit/matchbrackets.js",+ "libraries/codemirror/addon/edit/matchtags.js",+ "libraries/codemirror/addon/search/match-highlighter.js",+ "libraries/codemirror/mode/meta.js",+ "libraries/codemirror/addon/lint/lint.js",+ "libraries/codemirror/addon/lint/eslint.js"+ ],+ css: [+ "libraries/codemirror/codemirror.css",+ "libraries/codemirror/addon/lint/lint.css"+ ]+};++const ESLINT = {js: ["libraries/eslint.js"]};++async function requireLibrary(library) {+ if (library.css) {+ library.css.map(cssUrl => requireCss(cssUrl));+ }- if (library.js) {- for (const scriptUrl of library.js) {- await requireScript(scriptUrl);- }+ if (library.js) {+ for (const scriptUrl of library.js) {+ await requireScript(scriptUrl);}}+}- const dynamicallyLoadedScripts = [];+const dynamicallyLoadedScripts = [];- async function requireScript(url) {- if (!dynamicallyLoadedScripts.includes(url)) {- dynamicallyLoadedScripts.push(url);+async function requireScript(url) {+ if (!dynamicallyLoadedScripts.includes(url)) {+ dynamicallyLoadedScripts.push(url);- return await $.ajax({- url: url,- dataType: "script",- cache: true- })- }+ return await $.ajax({+ url: url,+ dataType: "script",+ cache: true+ })}+}- async function requireCss(url) {- const css = Array- .from(document.querySelectorAll('link'))- .map(scr => scr.href);+async function requireCss(url) {+ const css = Array+ .from(document.querySelectorAll('link'))+ .map(scr => scr.href);- if (!css.includes(url)) {- $('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', url));- }+ if (!css.includes(url)) {+ $('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', url));}+}- function getHost() {- const url = new URL(window.location.href);- return url.protocol + "//" + url.hostname + ":" + url.port;- }+function getHost() {+ const url = new URL(window.location.href);+ return url.protocol + "//" + url.hostname + ":" + url.port;+}- function download(url) {- if (isElectron()) {- const remote = require('electron').remote;+function download(url) {+ if (isElectron()) {+ const remote = require('electron').remote;- remote.getCurrentWebContents().downloadURL(url);- }- else {- window.location.href = url;- }+ remote.getCurrentWebContents().downloadURL(url);}+ else {+ window.location.href = url;+ }+}- function toObject(array, fn) {- const obj = {};-- for (const item of array) {- const ret = fn(item);+function toObject(array, fn) {+ const obj = {};- obj[ret[0]] = ret[1];- }+ for (const item of array) {+ const ret = fn(item);- return obj;+ obj[ret[0]] = ret[1];}- function randomString(len) {- let text = "";- const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";+ return obj;+}- for (let i = 0; i < len; i++) {- text += possible.charAt(Math.floor(Math.random() * possible.length));- }+function randomString(len) {+ let text = "";+ const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";- return text;+ for (let i = 0; i < len; i++) {+ text += possible.charAt(Math.floor(Math.random() * possible.length));}- return {- reloadApp,- showMessage,- showError,- throwError,- parseDate,- padNum,- formatTime,- formatTimeWithSeconds,- formatDate,- formatDateISO,- formatDateTime,- now,- isElectron,- assertArguments,- assert,- isTopLevelNode,- isRootNode,- escapeHtml,- stopWatch,- executeBundle,- formatValueWithWhitespace,- formatLabel,- requireLibrary,- CKEDITOR,- CODE_MIRROR,- ESLINT,- getHost,- download,- toObject,- randomString- };-})();\ No newline at end of file+ return text;+}++export default {+ reloadApp,+ showMessage,+ showError,+ throwError,+ parseDate,+ padNum,+ formatTime,+ formatTimeWithSeconds,+ formatDate,+ formatDateISO,+ formatDateTime,+ now,+ isElectron,+ assertArguments,+ assert,+ isTopLevelNode,+ isRootNode,+ escapeHtml,+ stopWatch,+ executeBundle,+ formatValueWithWhitespace,+ formatLabel,+ requireLibrary,+ CKEDITOR,+ CODE_MIRROR,+ ESLINT,+ getHost,+ download,+ toObject,+ randomString+};\ No newline at end of filediff --git a/src/views/index.ejs b/src/views/index.ejsindex f07375e320..50fa5ffcdd 100644--- a/src/views/index.ejs+++ b/src/views/index.ejs@@ -521,43 +521,6 @@<script src="/javascripts/bootstrap.js" type="module"></script>- <script src="/javascripts/utils.js"></script>- <script src="/javascripts/init.js"></script>- <script src="/javascripts/server.js"></script>-- <!-- Tree scripts -->- <script src="/javascripts/note_tree.js"></script>- <script src="/javascripts/tree_changes.js"></script>- <script src="/javascripts/cloning.js"></script>- <script src="/javascripts/tree_utils.js"></script>- <script src="/javascripts/drag_and_drop.js"></script>- <script src="/javascripts/context_menu.js"></script>- <script src="/javascripts/export.js"></script>-- <!-- Note detail -->- <script src="/javascripts/note_editor.js"></script>- <script src="/javascripts/protected_session.js"></script>- <script src="/javascripts/note_type.js"></script>-- <!-- dialogs -->- <script src="/javascripts/dialogs/recent_notes.js"></script>- <script src="/javascripts/dialogs/add_link.js"></script>- <script src="/javascripts/dialogs/jump_to_note.js"></script>- <script src="/javascripts/dialogs/settings.js"></script>- <script src="/javascripts/dialogs/note_history.js"></script>- <script src="/javascripts/dialogs/recent_changes.js"></script>- <script src="/javascripts/dialogs/event_log.js"></script>- <script src="/javascripts/dialogs/edit_tree_prefix.js"></script>- <script src="/javascripts/dialogs/sql_console.js"></script>- <script src="/javascripts/dialogs/note_source.js"></script>- <script src="/javascripts/dialogs/labels.js"></script>-- <script src="/javascripts/link.js"></script>- <script src="/javascripts/sync.js"></script>- <script src="/javascripts/messaging.js"></script>- <script src="/javascripts/script_context.js"></script>- <script src="/javascripts/script_api.js"></script>-<script type="text/javascript">// we hide container initally because otherwise it is rendered first without CSS and then flickers into// final form which is pretty ugly.