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
convert more note details to new style
zadamff41904d72b1
diff --git a/src/public/javascripts/services/note_detail.js b/src/public/javascripts/services/note_detail.jsindex bfec007158..933370a55b 100644--- a/src/public/javascripts/services/note_detail.js+++ b/src/public/javascripts/services/note_detail.js@@ -121,12 +121,12 @@ async function loadNoteDetail(noteId, newTab = false) {let ctx;if (noteContexts.length === 0 || newTab) {- const tabContent = $("#note-tab-content-template").clone();+ const $tabContent = $(".note-tab-content-template").clone();- tabContent.removeAttr('id');- tabContent.attr('data-note-id', noteId);+ $tabContent.removeClass('note-tab-content-template');+ $tabContent.attr('data-note-id', noteId);- $noteTabContentsContainer.append(tabContent);+ $noteTabContentsContainer.append($tabContent);// if it's a new tab explicitly by user then it's in backgroundctx = new NoteContext(loadedNote, newTab);diff --git a/src/public/javascripts/services/note_detail_code.js b/src/public/javascripts/services/note_detail_code.jsindex 77269a0f18..a785440b79 100644--- a/src/public/javascripts/services/note_detail_code.js+++ b/src/public/javascripts/services/note_detail_code.js@@ -5,109 +5,112 @@ import server from "./server.js";import noteDetailService from "./note_detail.js";import utils from "./utils.js";-let codeEditor = null;--const $component = $('#note-detail-code');-const $executeScriptButton = $("#execute-script-button");--async function show() {- await libraryLoader.requireLibrary(libraryLoader.CODE_MIRROR);-- if (!codeEditor) {- CodeMirror.keyMap.default["Shift-Tab"] = "indentLess";- CodeMirror.keyMap.default["Tab"] = "indentMore";-- // these conflict with backward/forward navigation shortcuts- delete CodeMirror.keyMap.default["Alt-Left"];- delete CodeMirror.keyMap.default["Alt-Right"];-- CodeMirror.modeURL = 'libraries/codemirror/mode/%N/%N.js';-- codeEditor = CodeMirror($component[0], {- value: "",- viewportMargin: Infinity,- indentUnit: 4,- matchBrackets: true,- matchTags: {bothTags: true},- highlightSelectionMatches: {showToken: /\w/, annotateScrollbar: false},- lint: true,- gutters: ["CodeMirror-lint-markers"],- lineNumbers: true,- tabindex: 100,- // we linewrap partly also because without it horizontal scrollbar displays only when you scroll- // all the way to the bottom of the note. With line wrap there's no horizontal scrollbar so no problem- lineWrapping: true- });-- onNoteChange(noteDetailService.noteChanged);- }-- $component.show();-- const activeNote = noteDetailService.getActiveNote();+class NoteDetailCode {- // this needs to happen after the element is shown, otherwise the editor won't be refreshed- // CodeMirror breaks pretty badly on null so even though it shouldn't happen (guarded by consistency check)- // we provide fallback- codeEditor.setValue(activeNote.content || "");+ /**+ * @param {NoteContext} ctx+ */+ constructor(ctx) {+ this.ctx = ctx;+ this.codeEditor = null;+ this.$component = ctx.$noteTabContent.find('.note-detail-code');+ this.$executeScriptButton = ctx.$noteTabContent.find(".execute-script-button");- const info = CodeMirror.findModeByMIME(activeNote.mime);+ utils.bindShortcut("ctrl+return", this.executeCurrentNote);- if (info) {- codeEditor.setOption("mode", info.mime);- CodeMirror.autoLoadMode(codeEditor, info.mode);+ this.$executeScriptButton.click(this.executeCurrentNote);}- codeEditor.refresh();-}+ async show() {+ await libraryLoader.requireLibrary(libraryLoader.CODE_MIRROR);++ if (!this.codeEditor) {+ CodeMirror.keyMap.default["Shift-Tab"] = "indentLess";+ CodeMirror.keyMap.default["Tab"] = "indentMore";++ // these conflict with backward/forward navigation shortcuts+ delete CodeMirror.keyMap.default["Alt-Left"];+ delete CodeMirror.keyMap.default["Alt-Right"];++ CodeMirror.modeURL = 'libraries/codemirror/mode/%N/%N.js';++ this.codeEditor = CodeMirror(this.$component[0], {+ value: "",+ viewportMargin: Infinity,+ indentUnit: 4,+ matchBrackets: true,+ matchTags: {bothTags: true},+ highlightSelectionMatches: {showToken: /\w/, annotateScrollbar: false},+ lint: true,+ gutters: ["CodeMirror-lint-markers"],+ lineNumbers: true,+ tabindex: 100,+ // we linewrap partly also because without it horizontal scrollbar displays only when you scroll+ // all the way to the bottom of the note. With line wrap there's no horizontal scrollbar so no problem+ lineWrapping: true+ });++ this.onNoteChange(noteDetailService.noteChanged);+ }-function getContent() {- return codeEditor.getValue();-}+ this.$component.show();-function focus() {- codeEditor.focus();-}+ // this needs to happen after the element is shown, otherwise the editor won't be refreshed+ // CodeMirror breaks pretty badly on null so even though it shouldn't happen (guarded by consistency check)+ // we provide fallback+ this.codeEditor.setValue(this.ctx.note.content || "");-async function executeCurrentNote() {- // ctrl+enter is also used elsewhere so make sure we're running only when appropriate- if (noteDetailService.getActiveNoteType() !== 'code') {- return;- }+ const info = CodeMirror.findModeByMIME(this.ctx.note.mime);- // make sure note is saved so we load latest changes- await noteDetailService.saveNotesIfChanged();+ if (info) {+ this.codeEditor.setOption("mode", info.mime);+ CodeMirror.autoLoadMode(this.codeEditor, info.mode);+ }- const activeNote = noteDetailService.getActiveNote();+ this.codeEditor.refresh();+ }- if (activeNote.mime.endsWith("env=frontend")) {- await bundleService.getAndExecuteBundle(noteDetailService.getActiveNoteId());+ getContent() {+ return this.codeEditor.getValue();}- if (activeNote.mime.endsWith("env=backend")) {- await server.post('script/run/' + noteDetailService.getActiveNoteId());+ focus() {+ this.codeEditor.focus();}- infoService.showMessage("Note executed");-}+ async executeCurrentNote() {+ // ctrl+enter is also used elsewhere so make sure we're running only when appropriate+ if (this.ctx.note.type !== 'code') {+ return;+ }-function onNoteChange(func) {- codeEditor.on('change', func);-}+ // make sure note is saved so we load latest changes+ await noteDetailService.saveNotesIfChanged();++ if (this.ctx.note.mime.endsWith("env=frontend")) {+ await bundleService.getAndExecuteBundle(this.ctx.note.noteId);+ }-utils.bindShortcut("ctrl+return", executeCurrentNote);+ if (this.ctx.note.mime.endsWith("env=backend")) {+ await server.post('script/run/' + this.ctx.note.noteId);+ }-$executeScriptButton.click(executeCurrentNote);+ infoService.showMessage("Note executed");+ }-export default {- show,- getContent,- focus,- onNoteChange,- cleanup: () => {- if (codeEditor) {- codeEditor.setValue('');+ onNoteChange(func) {+ this.codeEditor.on('change', func);+ }++ cleanup() {+ if (this.codeEditor) {+ this.codeEditor.setValue('');}- },- scrollToTop: () => $component.scrollTop(0)+ }++ scrollToTop() {+ this.$component.scrollTop(0);+ }}++export default NoteDetailCode;\ No newline at end of filediff --git a/src/public/javascripts/services/note_detail_relation_map.js b/src/public/javascripts/services/note_detail_relation_map.jsindex ee3c1ddff8..1450779e8e 100644--- a/src/public/javascripts/services/note_detail_relation_map.js+++ b/src/public/javascripts/services/note_detail_relation_map.js@@ -10,19 +10,6 @@ import promptDialog from "../dialogs/prompt.js";import infoDialog from "../dialogs/info.js";import confirmDialog from "../dialogs/confirm.js";-const $component = $("#note-detail-relation-map");-const $relationMapContainer = $("#relation-map-container");-const $createChildNote = $("#relation-map-create-child-note");-const $zoomInButton = $("#relation-map-zoom-in");-const $zoomOutButton = $("#relation-map-zoom-out");-const $resetPanZoomButton = $("#relation-map-reset-pan-zoom");--let mapData;-let jsPlumbInstance;-// outside of mapData because they are not persisted in the note content-let relations;-let pzInstance;-const uniDirectionalOverlays = [[ "Arrow", {location: 1,@@ -77,504 +64,532 @@ const linkOverlays = [} ]];-function loadMapData() {- const activeNote = noteDetailService.getActiveNote();- mapData = {- notes: [],- // it is important to have this exact value here so that initial transform is same as this- // which will guarantee note won't be saved on first conversion to relation map note type- // this keeps the principle that note type change doesn't destroy note content unless user- // does some actual change- transform: {- x: 0,- y: 0,- scale: 1- }- };+let containerCounter = 1;++class NoteDetailRelationMap {+ /**+ * @param {NoteContext} ctx+ */+ constructor(ctx) {+ this.ctx = ctx;+ this.$component = ctx.$noteTabContent.find(".note-detail-relation-map");+ this.$relationMapContainer = ctx.$noteTabContent.find(".relation-map-container");+ this.$createChildNote = ctx.$noteTabContent.find(".relation-map-create-child-note");+ this.$zoomInButton = ctx.$noteTabContent.find(".relation-map-zoom-in");+ this.$zoomOutButton = ctx.$noteTabContent.find(".relation-map-zoom-out");+ this.$resetPanZoomButton = ctx.$noteTabContent.find(".relation-map-reset-pan-zoom");++ this.mapData = null;+ this.jsPlumbInstance = null;+ // outside of mapData because they are not persisted in the note content+ this.relations = null;+ this.pzInstance = null;++ this.$relationMapContainer.attr("id", "relation-map-container-" + (containerCounter++));+ this.$relationMapContainer.on("contextmenu", ".note-box", e => {+ contextMenuWidget.initContextMenu(e, {+ getContextMenuItems: () => {+ return [+ {title: "Remove note", cmd: "remove", uiIcon: "trash"},+ {title: "Edit title", cmd: "edit-title", uiIcon: "pencil"},+ ];+ },+ selectContextMenuItem: (event, cmd) => this.noteContextMenuHandler(event, cmd)+ });- if (activeNote.content) {- try {- mapData = JSON.parse(activeNote.content);- } catch (e) {- console.log("Could not parse content: ", e);- }- }-}+ return false;+ });-function noteIdToId(noteId) {- return "rel-map-note-" + noteId;-}+ this.clipboard = null;-function idToNoteId(id) {- return id.substr(13);-}+ this.$createChildNote.click(async () => {+ const title = await promptDialog.ask({ message: "Enter title of new note", defaultValue: "new note" });-async function show() {- $component.show();+ if (!title.trim()) {+ return;+ }- await libraryLoader.requireLibrary(libraryLoader.RELATION_MAP);+ const {note} = await server.post(`notes/${this.ctx.note.noteId}/children`, {+ title,+ target: 'into'+ });++ infoService.showMessage("Click on canvas to place new note");++ // reloading tree so that the new note appears there+ // no need to wait for it to finish+ treeService.reload();- loadMapData();+ this.clipboard = { noteId: note.noteId, title };+ });- jsPlumb.ready(() => {- initJsPlumbInstance();+ this.$resetPanZoomButton.click(() => {+ // reset to initial pan & zoom state+ this.pzInstance.zoomTo(0, 0, 1 / getZoom());+ this.pzInstance.moveTo(0, 0);+ });- initPanZoom();+ this.$component.on("drop", this.dropNoteOntoRelationMapHandler);+ this.$component.on("dragover", ev => ev.preventDefault());+ }- loadNotesAndRelations();- });+ async noteContextMenuHandler(event, cmd) {+ const $noteBox = $(event.originalTarget).closest(".note-box");+ const $title = $noteBox.find(".title a");+ const noteId = this.idToNoteId($noteBox.prop("id"));-}+ if (cmd === "remove") {+ if (!await confirmDialog.confirmDeleteNoteBoxWithNote($title.text())) {+ return;+ }-function clearMap() {- // delete all endpoints and connections- // this is done at this point (after async operations) to reduce flicker to the minimum- jsPlumbInstance.deleteEveryEndpoint();+ this.jsPlumbInstance.remove(this.noteIdToId(noteId));- // without this we still end up with note boxes remaining in the canvas- $relationMapContainer.empty();-}+ if (confirmDialog.isDeleteNoteChecked()) {+ await server.remove("notes/" + noteId);-async function loadNotesAndRelations() {- const noteIds = mapData.notes.map(note => note.noteId);- const data = await server.post("notes/relation-map", {noteIds});+ // to force it to disappear from the tree+ treeService.reload();+ }- relations = [];+ this.mapData.notes = this.mapData.notes.filter(note => note.noteId !== noteId);- for (const relation of data.relations) {- const match = relations.find(rel =>- rel.name === data.inverseRelations[relation.name]- && ((rel.sourceNoteId === relation.sourceNoteId && rel.targetNoteId === relation.targetNoteId)- || (rel.sourceNoteId === relation.targetNoteId && rel.targetNoteId === relation.sourceNoteId)));+ this.relations = this.relations.filter(relation => relation.sourceNoteId !== noteId && relation.targetNoteId !== noteId);- if (match) {- match.type = relation.type = relation.name === data.inverseRelations[relation.name] ? 'biDirectional' : 'inverse';- relation.render = false; // don't render second relation- } else {- relation.type = 'uniDirectional';- relation.render = true;+ this.saveData();}+ else if (cmd === "edit-title") {+ const title = await promptDialog.ask({+ message: "Enter new note title:",+ defaultValue: $title.text()+ });- relations.push(relation);- }-- mapData.notes = mapData.notes.filter(note => note.noteId in data.noteTitles);+ if (!title) {+ return;+ }- jsPlumbInstance.batch(async function () {- clearMap();+ await server.put(`notes/${noteId}/change-title`, { title });- for (const note of mapData.notes) {- const title = data.noteTitles[note.noteId];+ treeService.setNoteTitle(noteId, title);- await createNoteBox(note.noteId, title, note.x, note.y);+ $title.text(title);}+ }- for (const relation of relations) {- if (!relation.render) {- continue;+ loadMapData() {+ this.mapData = {+ notes: [],+ // it is important to have this exact value here so that initial transform is same as this+ // which will guarantee note won't be saved on first conversion to relation map note type+ // this keeps the principle that note type change doesn't destroy note content unless user+ // does some actual change+ transform: {+ x: 0,+ y: 0,+ scale: 1}+ };- const connection = jsPlumbInstance.connect({- source: noteIdToId(relation.sourceNoteId),- target: noteIdToId(relation.targetNoteId),- type: relation.type- });+ if (this.ctx.note.content) {+ try {+ this.mapData = JSON.parse(this.ctx.note.content);+ } catch (e) {+ console.log("Could not parse content: ", e);+ }+ }+ }- connection.id = relation.attributeId;+ noteIdToId(noteId) {+ return "rel-map-note-" + noteId;+ }- if (relation.type === 'inverse') {- connection.getOverlay("label-source").setLabel(relation.name);- connection.getOverlay("label-target").setLabel(data.inverseRelations[relation.name]);- }- else {- connection.getOverlay("label").setLabel(relation.name);- }+ idToNoteId(id) {+ return id.substr(13);+ }- connection.canvas.setAttribute("data-connection-id", connection.id);- }+ async show() {+ this.$component.show();- for (const link of data.links) {- jsPlumbInstance.connect({- source: noteIdToId(link.sourceNoteId),- target: noteIdToId(link.targetNoteId),- type: 'link'- });- }- });-}+ await libraryLoader.requireLibrary(libraryLoader.RELATION_MAP);++ this.loadMapData();++ jsPlumb.ready(() => {+ this.initJsPlumbInstance();++ this.initPanZoom();++ this.loadNotesAndRelations();+ });-function initPanZoom() {- if (pzInstance) {- return;}- pzInstance = panzoom($relationMapContainer[0], {- maxZoom: 2,- minZoom: 0.3,- smoothScroll: false,- onMouseDown: function(event) {- if (clipboard) {- let {x, y} = getMousePosition(event);+ clearMap() {+ // delete all endpoints and connections+ // this is done at this point (after async operations) to reduce flicker to the minimum+ this.jsPlumbInstance.deleteEveryEndpoint();- // modifying position so that cursor is on the top-center of the box- x -= 80;- y -= 15;+ // without this we still end up with note boxes remaining in the canvas+ this.$relationMapContainer.empty();+ }- createNoteBox(clipboard.noteId, clipboard.title, x, y);+ async loadNotesAndRelations() {+ const noteIds = this.mapData.notes.map(note => note.noteId);+ const data = await server.post("notes/relation-map", {noteIds});- mapData.notes.push({ noteId: clipboard.noteId, x, y });+ this.relations = [];- saveData();+ for (const relation of data.relations) {+ const match = this.relations.find(rel =>+ rel.name === data.inverseRelations[relation.name]+ && ((rel.sourceNoteId === relation.sourceNoteId && rel.targetNoteId === relation.targetNoteId)+ || (rel.sourceNoteId === relation.targetNoteId && rel.targetNoteId === relation.sourceNoteId)));- clipboard = null;+ if (match) {+ match.type = relation.type = relation.name === data.inverseRelations[relation.name] ? 'biDirectional' : 'inverse';+ relation.render = false; // don't render second relation+ } else {+ relation.type = 'uniDirectional';+ relation.render = true;}- return true;- },- filterKey: function(e, dx, dy, dz) {- // if ALT is pressed then panzoom should bubble the event up- // this is to preserve ALT-LEFT, ALT-RIGHT navigation working- return e.altKey;+ this.relations.push(relation);}- });- pzInstance.on('transform', () => { // gets triggered on any transform change- jsPlumbInstance.setZoom(getZoom());+ this.mapData.notes = this.mapData.notes.filter(note => note.noteId in data.noteTitles);- saveCurrentTransform();- });+ this.jsPlumbInstance.batch(async () => {+ this.clearMap();- if (mapData.transform) {- pzInstance.zoomTo(0, 0, mapData.transform.scale);+ for (const note of this.mapData.notes) {+ const title = data.noteTitles[note.noteId];- pzInstance.moveTo(mapData.transform.x, mapData.transform.y);- }- else {- // set to initial coordinates- pzInstance.moveTo(0, 0);- }+ await this.createNoteBox(note.noteId, title, note.x, note.y);+ }- $zoomInButton.click(() => pzInstance.zoomTo(0, 0, 1.2));- $zoomOutButton.click(() => pzInstance.zoomTo(0, 0, 0.8));-}+ for (const relation of this.relations) {+ if (!relation.render) {+ continue;+ }-function saveCurrentTransform() {- const newTransform = pzInstance.getTransform();+ const connection = this.jsPlumbInstance.connect({+ source: this.noteIdToId(relation.sourceNoteId),+ target: this.noteIdToId(relation.targetNoteId),+ type: relation.type+ });- if (JSON.stringify(newTransform) !== JSON.stringify(mapData.transform)) {- // clone transform object- mapData.transform = JSON.parse(JSON.stringify(newTransform));+ connection.id = relation.attributeId;- saveData();- }-}+ if (relation.type === 'inverse') {+ connection.getOverlay("label-source").setLabel(relation.name);+ connection.getOverlay("label-target").setLabel(data.inverseRelations[relation.name]);+ }+ else {+ connection.getOverlay("label").setLabel(relation.name);+ }-function cleanup() {- if (jsPlumbInstance) {- clearMap();- }+ connection.canvas.setAttribute("data-connection-id", connection.id);+ }- if (pzInstance) {- pzInstance.dispose();- pzInstance = null;+ for (const link of data.links) {+ this.jsPlumbInstance.connect({+ source: this.noteIdToId(link.sourceNoteId),+ target: this.noteIdToId(link.targetNoteId),+ type: 'link'+ });+ }+ });}-}-function initJsPlumbInstance () {- if (jsPlumbInstance) {- cleanup();+ initPanZoom() {+ if (this.pzInstance) {+ return;+ }- return;- }+ this.pzInstance = panzoom(this.$relationMapContainer[0], {+ maxZoom: 2,+ minZoom: 0.3,+ smoothScroll: false,+ onMouseDown: function(event) {+ if (this.clipboard) {+ let {x, y} = this.getMousePosition(event);- jsPlumbInstance = jsPlumb.getInstance({- Endpoint: ["Dot", {radius: 2}],- Connector: "StateMachine",- ConnectionOverlays: uniDirectionalOverlays,- HoverPaintStyle: { stroke: "#777", strokeWidth: 1 },- Container: "relation-map-container"- });+ // modifying position so that cursor is on the top-center of the box+ x -= 80;+ y -= 15;- jsPlumbInstance.registerConnectionType("uniDirectional", { anchor:"Continuous", connector:"StateMachine", overlays: uniDirectionalOverlays });+ this.createNoteBox(this.clipboard.noteId, this.clipboard.title, x, y);- jsPlumbInstance.registerConnectionType("biDirectional", { anchor:"Continuous", connector:"StateMachine", overlays: biDirectionalOverlays });+ this.mapData.notes.push({ noteId: this.clipboard.noteId, x, y });- jsPlumbInstance.registerConnectionType("inverse", { anchor:"Continuous", connector:"StateMachine", overlays: inverseRelationsOverlays });+ this.saveData();- jsPlumbInstance.registerConnectionType("link", { anchor:"Continuous", connector:"StateMachine", overlays: linkOverlays });+ this.clipboard = null;+ }- jsPlumbInstance.bind("connection", connectionCreatedHandler);+ return true;+ },+ filterKey: function(e, dx, dy, dz) {+ // if ALT is pressed then panzoom should bubble the event up+ // this is to preserve ALT-LEFT, ALT-RIGHT navigation working+ return e.altKey;+ }+ });- // so that canvas is not panned when clicking/dragging note box- $relationMapContainer.on('mousedown touchstart', '.note-box, .connection-label', e => e.stopPropagation());-}+ this.pzInstance.on('transform', () => { // gets triggered on any transform change+ this.jsPlumbInstance.setZoom(this.getZoom());-function connectionContextMenuHandler(connection, event) {- event.preventDefault();- event.stopPropagation();+ this.saveCurrentTransform();+ });- const items = [ {title: "Remove relation", cmd: "remove", uiIcon: "trash"} ];+ if (this.mapData.transform) {+ this.pzInstance.zoomTo(0, 0, this.mapData.transform.scale);- contextMenuWidget.initContextMenu(event, items, async (event, cmd) => {- if (cmd === 'remove') {- if (!await confirmDialog.confirm("Are you sure you want to remove the relation?")) {- return;- }+ this.pzInstance.moveTo(this.mapData.transform.x, this.mapData.transform.y);+ }+ else {+ // set to initial coordinates+ this.pzInstance.moveTo(0, 0);+ }- const relation = relations.find(rel => rel.attributeId === connection.id);+ this.$zoomInButton.click(() => this.pzInstance.zoomTo(0, 0, 1.2));+ this.$zoomOutButton.click(() => this.pzInstance.zoomTo(0, 0, 0.8));+ }- await server.remove(`notes/${relation.sourceNoteId}/relations/${relation.name}/to/${relation.targetNoteId}`);+ saveCurrentTransform() {+ const newTransform = this.pzInstance.getTransform();- jsPlumbInstance.deleteConnection(connection);+ if (JSON.stringify(newTransform) !== JSON.stringify(this.mapData.transform)) {+ // clone transform object+ this.mapData.transform = JSON.parse(JSON.stringify(newTransform));- relations = relations.filter(relation => relation.attributeId !== connection.id);+ this.saveData();}- });-}--async function connectionCreatedHandler(info, originalEvent) {- const connection = info.connection;+ }- connection.bind("contextmenu", (obj, event) => {- if (connection.getType().includes("link")) {- // don't create context menu if it's a link since there's nothing to do with link from relation map- // (don't open browser menu either)- event.preventDefault();+ cleanup() {+ if (this.jsPlumbInstance) {+ this.clearMap();}- else {- connectionContextMenuHandler(connection, event);- }- });- // if there's no event, then this has been triggered programatically- if (!originalEvent) {- return;+ if (this.pzInstance) {+ this.pzInstance.dispose();+ this.pzInstance = null;+ }}- const name = await promptDialog.ask({- message: "Specify new relation name:",- shown: ({ $answer }) =>- attributeAutocompleteService.initAttributeNameAutocomplete({- $el: $answer,- attributeType: "relation",- open: true- })- });+ initJsPlumbInstance () {+ if (this.jsPlumbInstance) {+ this.cleanup();++ return;+ }- if (!name || !name.trim()) {- jsPlumbInstance.deleteConnection(connection);+ this.jsPlumbInstance = jsPlumb.getInstance({+ Endpoint: ["Dot", {radius: 2}],+ Connector: "StateMachine",+ ConnectionOverlays: uniDirectionalOverlays,+ HoverPaintStyle: { stroke: "#777", strokeWidth: 1 },+ Container: this.$relationMapContainer.attr("id")+ });- return;- }+ this.jsPlumbInstance.registerConnectionType("uniDirectional", { anchor:"Continuous", connector:"StateMachine", overlays: uniDirectionalOverlays });- const targetNoteId = idToNoteId(connection.target.id);- const sourceNoteId = idToNoteId(connection.source.id);+ this.jsPlumbInstance.registerConnectionType("biDirectional", { anchor:"Continuous", connector:"StateMachine", overlays: biDirectionalOverlays });- const relationExists = relations.some(rel =>- rel.targetNoteId === targetNoteId- && rel.sourceNoteId === sourceNoteId- && rel.name === name);+ this.jsPlumbInstance.registerConnectionType("inverse", { anchor:"Continuous", connector:"StateMachine", overlays: inverseRelationsOverlays });- if (relationExists) {- await infoDialog.info("Connection '" + name + "' between these notes already exists.");+ this.jsPlumbInstance.registerConnectionType("link", { anchor:"Continuous", connector:"StateMachine", overlays: linkOverlays });- jsPlumbInstance.deleteConnection(connection);+ this.jsPlumbInstance.bind("connection", (info, originalEvent) => this.connectionCreatedHandler(info, originalEvent));- return;+ // so that canvas is not panned when clicking/dragging note box+ this.$relationMapContainer.on('mousedown touchstart', '.note-box, .connection-label', e => e.stopPropagation());}- await server.put(`notes/${sourceNoteId}/relations/${name}/to/${targetNoteId}`);+ async connectionCreatedHandler(info, originalEvent) {+ const connection = info.connection;- await refresh();-}+ connection.bind("contextmenu", (obj, event) => {+ if (connection.getType().includes("link")) {+ // don't create context menu if it's a link since there's nothing to do with link from relation map+ // (don't open browser menu either)+ event.preventDefault();+ }+ else {+ event.preventDefault();+ event.stopPropagation();-$relationMapContainer.on("contextmenu", ".note-box", e => {- const items = [- {title: "Remove note", cmd: "remove", uiIcon: "trash"},- {title: "Edit title", cmd: "edit-title", uiIcon: "pencil"},- ];+ contextMenuWidget.initContextMenu(event, {+ getContextMenuItems: () => {+ return [ {title: "Remove relation", cmd: "remove", uiIcon: "trash"} ];+ },+ selectContextMenuItem: async (event, cmd) => {+ if (cmd === 'remove') {+ if (!await confirmDialog.confirm("Are you sure you want to remove the relation?")) {+ return;+ }- contextMenuWidget.initContextMenu(e, items, noteContextMenuHandler);+ const relation = this.relations.find(rel => rel.attributeId === connection.id);- return false;-});+ await server.remove(`notes/${relation.sourceNoteId}/relations/${relation.name}/to/${relation.targetNoteId}`);-async function noteContextMenuHandler(event, cmd) {- const $noteBox = $(event.originalTarget).closest(".note-box");- const $title = $noteBox.find(".title a");- const noteId = idToNoteId($noteBox.prop("id"));+ this.jsPlumbInstance.deleteConnection(connection);- if (cmd === "remove") {- if (!await confirmDialog.confirmDeleteNoteBoxWithNote($title.text())) {+ this.relations = this.relations.filter(relation => relation.attributeId !== connection.id);+ }+ }+ });+ }+ });++ // if there's no event, then this has been triggered programatically+ if (!originalEvent) {return;}- jsPlumbInstance.remove(noteIdToId(noteId));+ const name = await promptDialog.ask({+ message: "Specify new relation name:",+ shown: ({ $answer }) =>+ attributeAutocompleteService.initAttributeNameAutocomplete({+ $el: $answer,+ attributeType: "relation",+ open: true+ })+ });- if (confirmDialog.isDeleteNoteChecked()) {- await server.remove("notes/" + noteId);+ if (!name || !name.trim()) {+ this.jsPlumbInstance.deleteConnection(connection);- // to force it to disappear from the tree- treeService.reload();+ return;}- mapData.notes = mapData.notes.filter(note => note.noteId !== noteId);+ const targetNoteId = this.idToNoteId(connection.target.id);+ const sourceNoteId = this.idToNoteId(connection.source.id);- relations = relations.filter(relation => relation.sourceNoteId !== noteId && relation.targetNoteId !== noteId);+ const relationExists = this.relations.some(rel =>+ rel.targetNoteId === targetNoteId+ && rel.sourceNoteId === sourceNoteId+ && rel.name === name);- saveData();- }- else if (cmd === "edit-title") {- const title = await promptDialog.ask({- message: "Enter new note title:",- defaultValue: $title.text()- });+ if (relationExists) {+ await infoDialog.info("Connection '" + name + "' between these notes already exists.");++ this.jsPlumbInstance.deleteConnection(connection);- if (!title) {return;}- await server.put(`notes/${noteId}/change-title`, { title });+ await server.put(`notes/${sourceNoteId}/relations/${name}/to/${targetNoteId}`);- treeService.setNoteTitle(noteId, title);+ await this.refresh();+ }- $title.text(title);+ saveData() {+ this.ctx.noteChanged();}-}-function saveData() {- noteDetailService.noteChanged();-}+ async createNoteBox(noteId, title, x, y) {+ const $noteBox = $("<div>")+ .addClass("note-box")+ .prop("id", this.noteIdToId(noteId))+ .append($("<span>").addClass("title").html(await linkService.createNoteLink(noteId, title)))+ .append($("<div>").addClass("endpoint").attr("title", "Start dragging relations from here and drop them on another note."))+ .css("left", x + "px")+ .css("top", y + "px");-async function createNoteBox(noteId, title, x, y) {- const $noteBox = $("<div>")- .addClass("note-box")- .prop("id", noteIdToId(noteId))- .append($("<span>").addClass("title").html(await linkService.createNoteLink(noteId, title)))- .append($("<div>").addClass("endpoint").attr("title", "Start dragging relations from here and drop them on another note."))- .css("left", x + "px")- .css("top", y + "px");+ this.jsPlumbInstance.getContainer().appendChild($noteBox[0]);- jsPlumbInstance.getContainer().appendChild($noteBox[0]);+ this.jsPlumbInstance.draggable($noteBox[0], {+ start: params => {},+ drag: params => {},+ stop: params => {+ const noteId = this.idToNoteId(params.el.id);- jsPlumbInstance.draggable($noteBox[0], {- start: params => {},- drag: params => {},- stop: params => {- const noteId = idToNoteId(params.el.id);+ const note = this.mapData.notes.find(note => note.noteId === noteId);- const note = mapData.notes.find(note => note.noteId === noteId);+ if (!note) {+ console.error(`Note ${noteId} not found!`);+ return;+ }- if (!note) {- console.error(`Note ${noteId} not found!`);- return;- }+ [note.x, note.y] = params.finalPos;- [note.x, note.y] = params.finalPos;+ this.saveData();+ }+ });- saveData();- }- });-- jsPlumbInstance.makeSource($noteBox[0], {- filter: ".endpoint",- anchor: "Continuous",- connectorStyle: { stroke: "#000", strokeWidth: 1 },- connectionType: "basic",- extract:{- "action": "the-action"- }- });+ this.jsPlumbInstance.makeSource($noteBox[0], {+ filter: ".endpoint",+ anchor: "Continuous",+ connectorStyle: { stroke: "#000", strokeWidth: 1 },+ connectionType: "basic",+ extract:{+ "action": "the-action"+ }+ });- jsPlumbInstance.makeTarget($noteBox[0], {- dropOptions: { hoverClass: "dragHover" },- anchor: "Continuous",- allowLoopback: true- });-}+ this.jsPlumbInstance.makeTarget($noteBox[0], {+ dropOptions: { hoverClass: "dragHover" },+ anchor: "Continuous",+ allowLoopback: true+ });+ }-async function refresh() {- await loadNotesAndRelations();-}+ async refresh() {+ await this.loadNotesAndRelations();+ }-let clipboard = null;+ getZoom() {+ const matrixRegex = /matrix\((-?\d*\.?\d+),\s*0,\s*0,\s*-?\d*\.?\d+,\s*-?\d*\.?\d+,\s*-?\d*\.?\d+\)/;-$createChildNote.click(async () => {- const title = await promptDialog.ask({ message: "Enter title of new note", defaultValue: "new note" });+ const matches = this.$relationMapContainer.css('transform').match(matrixRegex);- if (!title.trim()) {- return;+ return matches[1];}- const {note} = await server.post(`notes/${noteDetailService.getActiveNoteId()}/children`, {- title,- target: 'into'- });+ async dropNoteOntoRelationMapHandler(ev) {+ ev.preventDefault();- infoService.showMessage("Click on canvas to place new note");+ const note = JSON.parse(ev.originalEvent.dataTransfer.getData("text"));- // reloading tree so that the new note appears there- // no need to wait for it to finish- treeService.reload();+ let {x, y} = this.getMousePosition(ev);- clipboard = { noteId: note.noteId, title };-});+ const exists = this.mapData.notes.some(n => n.noteId === note.noteId);-function getZoom() {- const matrixRegex = /matrix\((-?\d*\.?\d+),\s*0,\s*0,\s*-?\d*\.?\d+,\s*-?\d*\.?\d+,\s*-?\d*\.?\d+\)/;+ if (exists) {+ await infoDialog.info(`Note "${note.title}" is already placed into the diagram`);- const matches = $relationMapContainer.css('transform').match(matrixRegex);-- return matches[1];-}+ return;+ }-async function dropNoteOntoRelationMapHandler(ev) {- ev.preventDefault();+ this.mapData.notes.push({noteId: note.noteId, x, y});- const note = JSON.parse(ev.originalEvent.dataTransfer.getData("text"));+ this.saveData();- let {x, y} = getMousePosition(ev);+ await this.refresh();+ }- const exists = mapData.notes.some(n => n.noteId === note.noteId);+ getMousePosition(evt) {+ const rect = this.$relationMapContainer[0].getBoundingClientRect();- if (exists) {- await infoDialog.info(`Note "${note.title}" is already placed into the diagram`);+ const zoom = this.getZoom();- return;+ return {+ x: (evt.clientX - rect.left) / zoom,+ y: (evt.clientY - rect.top) / zoom+ };}- mapData.notes.push({noteId: note.noteId, x, y});-- saveData();-- await refresh();-}+ getContent() {+ return JSON.stringify(this.mapData);+ }-function getMousePosition(evt) {- const rect = $relationMapContainer[0].getBoundingClientRect();+ focus() {}- const zoom = getZoom();+ onNoteChange() {}- return {- x: (evt.clientX - rect.left) / zoom,- y: (evt.clientY - rect.top) / zoom- };+ scrollToTop() {}}-$resetPanZoomButton.click(() => {- // reset to initial pan & zoom state- pzInstance.zoomTo(0, 0, 1 / getZoom());- pzInstance.moveTo(0, 0);-});--$component.on("drop", dropNoteOntoRelationMapHandler);-$component.on("dragover", ev => ev.preventDefault());--export default {- show,- getContent: () => JSON.stringify(mapData),- focus: () => null,- onNoteChange: () => null,- cleanup,- scrollToTop: () => null-}\ No newline at end of file+export default NoteDetailRelationMap;\ No newline at end of filediff --git a/src/public/javascripts/services/note_detail_render.js b/src/public/javascripts/services/note_detail_render.jsindex e37d4f4ef8..f99c2627c1 100644--- a/src/public/javascripts/services/note_detail_render.js+++ b/src/public/javascripts/services/note_detail_render.js@@ -3,40 +3,55 @@ import server from "./server.js";import noteDetailService from "./note_detail.js";import attributeService from "./attributes.js";-const $component = $('#note-detail-render');-const $noteDetailRenderHelp = $('#note-detail-render-help');-const $noteDetailRenderContent = $('#note-detail-render-content');-const $renderButton = $('#render-button');+class NoteDetailRender {+ /**+ * @param {NoteContext} ctx+ */+ constructor(ctx) {+ this.ctx = ctx;+ this.$component = ctx.$noteTabContent.find('.note-detail-render');+ this.$noteDetailRenderHelp = ctx.$noteTabContent.find('.note-detail-render-help');+ this.$noteDetailRenderContent = ctx.$noteTabContent.find('.note-detail-render-content');+ this.$renderButton = ctx.$noteTabContent.find('.render-button');++ this.$renderButton.click(this.show);+ }-async function render() {- const attributes = await attributeService.getAttributes();- const renderNotes = attributes.filter(attr =>- attr.type === 'relation'- && attr.name === 'renderNote'- && !!attr.value);+ async show() {+ const attributes = await attributeService.getAttributes();+ const renderNotes = attributes.filter(attr =>+ attr.type === 'relation'+ && attr.name === 'renderNote'+ && !!attr.value);- $component.show();+ this.$component.show();- $noteDetailRenderContent.empty();- $noteDetailRenderContent.toggle(renderNotes.length > 0);- $noteDetailRenderHelp.toggle(renderNotes.length === 0);+ this.$noteDetailRenderContent.empty();+ this.$noteDetailRenderContent.toggle(renderNotes.length > 0);+ this.$noteDetailRenderHelp.toggle(renderNotes.length === 0);- for (const renderNote of renderNotes) {- const bundle = await server.get('script/bundle/' + renderNote.value);+ for (const renderNote of renderNotes) {+ const bundle = await server.get('script/bundle/' + renderNote.value);- $noteDetailRenderContent.append(bundle.html);+ this.$noteDetailRenderContent.append(bundle.html);- await bundleService.executeBundle(bundle, noteDetailService.getActiveNote());+ await bundleService.executeBundle(bundle, noteDetailService.getActiveNote());+ }}-}-$renderButton.click(render);+ getContent() {}++ focus() {}++ onNoteChange() {}++ cleanup() {+ this.$noteDetailRenderContent.empty();+ }++ scrollToTop() {+ this.$component.scrollTop(0);+ }+}-export default {- show: render,- getContent: () => "",- focus: () => null,- onNoteChange: () => null,- cleanup: () => $noteDetailRenderContent.empty(),- scrollToTop: () => $component.scrollTop(0)-}\ No newline at end of file+export default NoteDetailRender;\ No newline at end of filediff --git a/src/public/javascripts/services/note_detail_search.js b/src/public/javascripts/services/note_detail_search.jsindex c8130ca547..1e5d3274fd 100644--- a/src/public/javascripts/services/note_detail_search.js+++ b/src/public/javascripts/services/note_detail_search.js@@ -1,46 +1,55 @@import noteDetailService from "./note_detail.js";import searchNotesService from "./search_notes.js";-const $searchString = $("#search-string");-const $component = $('#note-detail-search');-const $refreshButton = $('#note-detail-search-refresh-results-button');-const $help = $("#note-detail-search-help");+class NoteDetailSearch {+ /**+ * @param {NoteContext} ctx+ */+ constructor(ctx) {+ this.ctx = ctx;+ this.$searchString = ctx.$noteTabContent.find(".search-string");+ this.$component = ctx.$noteTabContent.find('.note-detail-search');+ this.$help = ctx.$noteTabContent.find(".note-detail-search-help");+ this.$refreshButton = ctx.$noteTabContent.find('.note-detail-search-refresh-results-button');++ this.$refreshButton.click(async () => {+ await noteDetailService.saveNotesIfChanged();++ await searchNotesService.refreshSearch();+ });+ }++ show() {+ this.$help.html(searchNotesService.getHelpText());-function show() {- $help.html(searchNotesService.getHelpText());+ this.$component.show();- $component.show();+ try {+ const json = JSON.parse(this.ctx.note.content);- try {- const json = JSON.parse(noteDetailService.getActiveNote().content);+ this.$searchString.val(json.searchString);+ }+ catch (e) {+ console.log(e);+ this.$searchString.val('');+ }- $searchString.val(json.searchString);+ this.$searchString.on('input', noteDetailService.noteChanged);}- catch (e) {- console.log(e);- $searchString.val('');++ getContent() {+ return JSON.stringify({+ searchString: this.$searchString.val()+ });}- $searchString.on('input', noteDetailService.noteChanged);-}+ focus() {}-function getContent() {- return JSON.stringify({- searchString: $searchString.val()- });-}+ onNoteChange() {}-$refreshButton.click(async () => {- await noteDetailService.saveNotesIfChanged();+ cleanup() {}- await searchNotesService.refreshSearch();-});+ scrollToTop() {}+}-export default {- getContent,- show,- focus: () => null,- onNoteChange: () => null,- cleanup: () => null,- scrollToTop: () => null-}\ No newline at end of file+export default NoteDetailSearch;\ No newline at end of filediff --git a/src/public/javascripts/services/note_detail_text.js b/src/public/javascripts/services/note_detail_text.jsindex 16c21632d8..40ae432ebe 100644--- a/src/public/javascripts/services/note_detail_text.js+++ b/src/public/javascripts/services/note_detail_text.js@@ -53,7 +53,7 @@ class NoteDetailText {this.$component.show();-// this.textEditor.setData(this.ctx.note.content);+ this.textEditor.setData(this.ctx.note.content);}getContent() {diff --git a/src/public/stylesheets/style.css b/src/public/stylesheets/style.cssindex cc56ce8915..1895e8d3e0 100644--- a/src/public/stylesheets/style.css+++ b/src/public/stylesheets/style.css@@ -103,8 +103,8 @@ ul.fancytree-container {display: none;}-#note-tab-content-template {- display: none;+.note-tab-content-template {+ display: none !important;}.note-tab-content {diff --git a/src/views/tabs.ejs b/src/views/tabs.ejsindex 5a80d24b4c..ecb302c98d 100644--- a/src/views/tabs.ejs+++ b/src/views/tabs.ejs@@ -3,7 +3,7 @@</div><div id="note-tab-container">- <div id="note-tab-content-template" class="note-tab-content">+ <div class="note-tab-content note-tab-content-template"><% include title.ejs %><div class="note-detail-script-area"></div>