trilium/public/javascripts/note_tree.js

696 lines
20 KiB
JavaScript
Raw Normal View History

"use strict";
2017-11-05 07:28:49 +08:00
const noteTree = (function() {
const noteDetailEl = $('#note-detail');
const treeEl = $("#tree");
const parentListEl = $("#parent-list");
let startNoteTreeId = null;
2017-11-05 07:28:49 +08:00
let treeLoadTime = null;
2017-11-18 10:31:54 +08:00
let notesMap = {};
2017-11-19 21:47:22 +08:00
let parentToChildren = {};
let childToParents = {};
let parentChildToNoteTreeId = {};
2017-11-20 01:06:48 +08:00
let noteIdToTitle = {};
function getNoteTreeIdFromKey(key) {
const node = treeUtils.getNodeByKey(key);
return node.note_tree_id;
}
2017-11-05 07:28:49 +08:00
function getTreeLoadTime() {
return treeLoadTime;
}
function getNoteTreeId(parentNoteId, childNoteId) {
const key = parentNoteId + "-" + childNoteId;
const noteTreeId = parentChildToNoteTreeId[key];
if (!noteTreeId) {
2017-11-20 01:06:48 +08:00
console.trace();
throw new Error("Can't find note tree id for parent=" + parentNoteId + ", child=" + childNoteId);
}
return noteTreeId;
}
2017-11-20 01:06:48 +08:00
function getNoteTitle(notePath) {
const noteId = treeUtils.getNoteIdFromNotePath(notePath);
const title = noteIdToTitle[noteId];
if (!title) {
throw new Error("Can't find title for noteId='" + noteId + "'");
2017-11-20 01:06:48 +08:00
}
return title;
}
function prepareNoteTree(notes) {
2017-11-19 21:47:22 +08:00
parentToChildren = {};
childToParents = {};
notesMap = {};
for (const note of notes) {
notesMap[note.note_tree_id] = note;
2017-11-20 01:06:48 +08:00
noteIdToTitle[note.note_id] = note.note_title;
delete note.note_title; // this should not be used. Use noteIdToTitle instead
const key = note.note_pid + "-" + note.note_id;
parentChildToNoteTreeId[key] = note.note_tree_id;
if (!parentToChildren[note.note_pid]) {
parentToChildren[note.note_pid] = [];
}
parentToChildren[note.note_pid].push(note.note_id);
2017-11-19 21:47:22 +08:00
if (!childToParents[note.note_id]) {
childToParents[note.note_id] = [];
2017-11-19 21:47:22 +08:00
}
childToParents[note.note_id].push(note.note_pid);
}
return prepareNoteTreeInner('root');
2017-11-18 10:31:54 +08:00
}
function prepareNoteTreeInner(parentNoteId) {
const childNoteIds = parentToChildren[parentNoteId];
2017-11-20 05:43:49 +08:00
if (!childNoteIds) {
console.log("No children for " + noteId + ". This shouldn't happen.");
return;
}
2017-11-18 10:31:54 +08:00
const noteList = [];
for (const childNoteId of childNoteIds) {
const noteTreeId = getNoteTreeId(parentNoteId, childNoteId);
const note = notesMap[noteTreeId];
const node = {};
2017-11-18 10:31:54 +08:00
node.note_id = note.note_id;
node.note_pid = note.note_pid;
node.note_tree_id = note.note_tree_id;
node.is_protected = note.is_protected;
node.title = noteIdToTitle[note.note_id];
2017-11-05 07:28:49 +08:00
node.extraClasses = "";
if (node.is_protected) {
node.extraClasses += ",protected";
}
if (childToParents[childNoteId].length > 1) {
node.extraClasses += ",multiple-parents";
}
if (node.extraClasses.startsWith(",")) {
node.extraClasses = node.extraClasses.substr(1);
2017-11-05 07:28:49 +08:00
}
node.refKey = note.note_id;
node.expanded = note.is_expanded;
2017-11-05 07:28:49 +08:00
if (parentToChildren[note.note_id] && parentToChildren[note.note_id].length > 0) {
node.folder = true;
2017-11-18 10:31:54 +08:00
if (node.expanded) {
node.children = prepareNoteTreeInner(note.note_id);
2017-11-18 10:31:54 +08:00
}
else {
node.lazy = true;
2017-11-18 10:31:54 +08:00
}
2017-11-05 07:28:49 +08:00
}
2017-11-18 10:31:54 +08:00
noteList.push(node);
2017-11-05 07:28:49 +08:00
}
2017-11-18 10:31:54 +08:00
return noteList;
2017-11-05 07:28:49 +08:00
}
2017-11-19 21:47:22 +08:00
async function activateNode(notePath) {
const path = notePath.split("/").reverse();
const effectivePath = [];
let childNoteId = null;
let i = 0;
while (true) {
const parentNoteId = i < path.length ? path[i] : null;
i++;
if (childNoteId !== null) {
const parents = childToParents[childNoteId];
if (parentNoteId === null || !parents.includes(parentNoteId)) {
console.log("Did not find parent " + parentNoteId + " for child " + childNoteId);
if (parents.length > 0) {
if (parents[0] === 'root') {
console.log("Reached root.");
break;
}
childNoteId = parents[0];
effectivePath.push(childNoteId);
console.log("Choosing parent " + childNoteId + " instead.");
continue;
}
else {
console.log("No parents, can't activate node.");
return;
}
}
}
2017-11-19 21:47:22 +08:00
effectivePath.push(parentNoteId);
childNoteId = parentNoteId;
2017-11-19 21:47:22 +08:00
}
const noteId = treeUtils.getNoteIdFromNotePath(notePath);
2017-11-19 21:47:22 +08:00
const runPath = effectivePath.reverse();
let parentNoteId = 'root';
2017-11-19 21:47:22 +08:00
for (const childNoteId of runPath) {
const node = getNodes(childNoteId).find(node => node.data.note_pid === parentNoteId);
2017-11-19 21:47:22 +08:00
if (childNoteId === noteId) {
await node.setActive();
2017-11-19 21:47:22 +08:00
}
else {
await node.setExpanded();
2017-11-19 21:47:22 +08:00
}
parentNoteId = childNoteId;
2017-11-19 21:47:22 +08:00
}
}
function getNodes(noteId) {
return getTree().getNodesByRef(noteId);
}
function showParentList(noteId, node) {
const parents = childToParents[noteId];
if (!parents) {
throw new Error("Can't find parents for noteId=" + noteId);
}
if (parents.length <= 1) {
parentListEl.hide();
}
else {
parentListEl.show();
parentListEl.empty();
const list = $("<ul/>");
for (const parentNoteId of parents) {
const notePath = getSomeNotePath(parentNoteId) + '/' + noteId;
const title = getNotePathTitle(notePath);
let item;
if (node.getParent().data.note_id === parentNoteId) {
item = $("<span/>").attr("title", "Current note").append(title);
}
else {
item = link.createNoteLink(notePath, title);
}
list.append($("<li/>").append(item));
}
parentListEl.append(list);
}
}
function getNotePathTitle(notePath) {
const titlePath = [];
for (const path of notePath.split('/')) {
titlePath.push(getNoteTitle(path));
}
return titlePath.join(' / ');
}
function getSomeNotePath(noteId) {
const path = [];
let cur = noteId;
while (cur !== 'root') {
path.push(cur);
cur = childToParents[cur][0];
}
return path.reverse().join('/');
}
function setExpandedToServer(noteTreeId, isExpanded) {
const expandedNum = isExpanded ? 1 : 0;
2017-11-05 07:28:49 +08:00
$.ajax({
url: baseApiUrl + 'notes/' + noteTreeId + '/expanded/' + expandedNum,
2017-11-05 07:28:49 +08:00
type: 'PUT',
contentType: "application/json",
success: result => {}
});
}
function setCurrentNotePathToHash(node) {
const currentNotePath = treeUtils.getNotePath(node);
document.location.hash = currentNotePath;
recentNotes.addRecentNote(currentNotePath);
}
function initFancyTree(noteTree) {
console.log(noteTree);
2017-11-05 07:28:49 +08:00
const keybindings = {
"insert": node => {
const parentNoteId = node.data.note_pid;
2017-11-15 12:01:23 +08:00
const isProtected = treeUtils.getParentProtectedStatus(node);
2017-11-05 07:28:49 +08:00
createNote(node, parentNoteId, 'after', isProtected);
2017-11-05 07:28:49 +08:00
},
"ctrl+insert": node => {
createNote(node, node.data.note_id, 'into', node.data.is_protected);
2017-11-05 07:28:49 +08:00
},
"del": node => {
2017-11-05 10:10:41 +08:00
treeChanges.deleteNode(node);
2017-11-05 07:28:49 +08:00
},
"shift+up": node => {
const beforeNode = node.getPrevSibling();
if (beforeNode !== null) {
2017-11-05 10:10:41 +08:00
treeChanges.moveBeforeNode(node, beforeNode);
2017-11-05 07:28:49 +08:00
}
},
"shift+down": node => {
let afterNode = node.getNextSibling();
if (afterNode !== null) {
2017-11-05 10:10:41 +08:00
treeChanges.moveAfterNode(node, afterNode);
2017-11-05 07:28:49 +08:00
}
},
"shift+left": node => {
2017-11-05 10:10:41 +08:00
treeChanges.moveNodeUp(node);
2017-11-05 07:28:49 +08:00
},
"shift+right": node => {
let toNode = node.getPrevSibling();
if (toNode !== null) {
2017-11-05 10:10:41 +08:00
treeChanges.moveToNode(node, toNode);
2017-11-05 07:28:49 +08:00
}
},
"return": node => {
// doesn't work :-/
noteDetailEl.summernote('focus');
}
};
treeEl.fancytree({
autoScroll: true,
extensions: ["hotkeys", "filter", "dnd", "clones"],
source: noteTree,
2017-11-05 07:28:49 +08:00
scrollParent: $("#tree"),
activate: (event, data) => {
const node = data.node.data;
setCurrentNotePathToHash(data.node);
noteEditor.switchToNote(node.note_id);
showParentList(node.note_id, data.node);
return false;
2017-11-05 07:28:49 +08:00
},
expand: (event, data) => {
2017-11-23 09:29:22 +08:00
setExpandedToServer(data.node.data.note_tree_id, true);
2017-11-05 07:28:49 +08:00
},
collapse: (event, data) => {
2017-11-23 09:29:22 +08:00
setExpandedToServer(data.node.data.note_tree_id, false);
2017-11-05 07:28:49 +08:00
},
init: (event, data) => {
2017-11-19 21:47:22 +08:00
if (startNoteTreeId) {
activateNode(startNoteTreeId);
}
2017-11-20 05:35:35 +08:00
else {
showAppIfHidden();
}
2017-11-05 07:28:49 +08:00
},
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,
keydown: (event, data) => {
const node = data.node;
// Eat keyboard events, when a menu is open
if ($(".contextMenu:visible").length > 0)
return false;
switch (event.which) {
// Open context menu on [Space] key (simulate right click)
case 32: // [Space]
$(node.span).trigger("mousedown", {
preventDefault: true,
button: 2
})
.trigger("mouseup", {
preventDefault: true,
pageX: node.span.offsetLeft,
pageY: node.span.offsetTop,
button: 2
});
return false;
// Handle Ctrl-C, -X and -V
// case 67:
// if (event.ctrlKey) { // Ctrl-C
// copyPaste("copy", node);
// return false;
// }
// break;
case 86:
console.log("CTRL-V");
if (event.ctrlKey) { // Ctrl-V
2017-11-05 07:33:39 +08:00
contextMenu.pasteAfter(node);
2017-11-05 07:28:49 +08:00
return false;
}
break;
case 88:
console.log("CTRL-X");
if (event.ctrlKey) { // Ctrl-X
2017-11-05 07:33:39 +08:00
contextMenu.cut(node);
2017-11-05 07:28:49 +08:00
return false;
}
break;
}
2017-11-18 10:31:54 +08:00
},
lazyLoad: function(event, data){
const node = data.node.data;
2017-11-18 10:31:54 +08:00
2017-11-20 05:43:49 +08:00
data.result = prepareNoteTreeInner(node.note_id);
},
clones: {
highlightActiveClones: true
2017-11-05 07:28:49 +08:00
}
});
2017-11-05 07:33:39 +08:00
treeEl.contextmenu(contextMenu.contextMenuSettings);
2017-11-05 07:28:49 +08:00
}
function getTree() {
return treeEl.fancytree('getTree');
}
async function reload() {
const notes = await loadTree();
// this will also reload the note content
await getTree().reload(notes);
}
2017-11-05 07:28:49 +08:00
function loadTree() {
return $.get(baseApiUrl + 'tree').then(resp => {
startNoteTreeId = resp.start_note_tree_id;
2017-11-05 07:28:49 +08:00
treeLoadTime = resp.tree_load_time;
if (document.location.hash) {
startNoteTreeId = document.location.hash.substr(1); // strip initial #
2017-11-05 07:28:49 +08:00
}
return prepareNoteTree(resp.notes, resp.notes_parent);
2017-11-05 07:28:49 +08:00
});
}
$(() => loadTree().then(noteTree => initFancyTree(noteTree)));
2017-11-05 07:28:49 +08:00
function collapseTree() {
treeEl.fancytree("getRootNode").visit(node => {
node.setExpanded(false);
});
}
$(document).bind('keydown', 'alt+c', collapseTree);
function scrollToCurrentNote() {
const node = noteTree.getCurrentNode();
2017-11-05 07:28:49 +08:00
if (node) {
node.makeVisible({scrollIntoView: true});
node.setFocus();
}
}
function showSearch() {
$("#search-box").show();
$("input[name=search]").focus();
}
function toggleSearch() {
if ($("#search-box:hidden").length) {
showSearch();
}
else {
resetSearch();
$("#search-box").hide();
}
}
function resetSearch() {
$("input[name=search]").val("");
const tree = getTree();
2017-11-05 07:28:49 +08:00
tree.clearFilter();
}
// note that if you want to access data like note_id or is_protected, you need to go into "data" property
function getCurrentNode() {
return treeEl.fancytree("getActiveNode");
}
function getCurrentNoteTreeId() {
const node = getCurrentNode();
return node.data.note_tree_id;
}
2017-11-20 01:06:48 +08:00
function getCurrentNotePath() {
const node = getCurrentNode();
return treeUtils.getNotePath(node);
}
function getCurrentNoteId() {
const node = getCurrentNode();
return node ? node.data.note_id : null;
}
function setCurrentNoteTreeBasedOnProtectedStatus() {
2017-11-23 09:29:22 +08:00
getCurrentClones().map(node => node.toggleClass("protected", !!node.data.is_protected));
}
2017-11-20 08:39:39 +08:00
function getAutocompleteItems(parentNoteId, notePath, titlePath) {
if (!parentNoteId) {
parentNoteId = 'root';
}
if (!parentToChildren[parentNoteId]) {
return [];
}
if (!notePath) {
notePath = '';
}
if (!titlePath) {
titlePath = '';
}
const autocompleteItems = [];
for (const childNoteId of parentToChildren[parentNoteId]) {
const childNotePath = (notePath ? (notePath + '/') : '') + childNoteId;
const childTitlePath = (titlePath ? (titlePath + ' / ') : '') + getNoteTitle(childNoteId);
autocompleteItems.push({
2017-11-20 09:36:13 +08:00
value: childTitlePath + ' (' + childNotePath + ')',
2017-11-20 08:39:39 +08:00
label: childTitlePath
});
const childItems = getAutocompleteItems(childNoteId, childNotePath, childTitlePath);
for (const childItem of childItems) {
autocompleteItems.push(childItem);
}
}
return autocompleteItems;
}
function getCurrentClones() {
const noteId = getCurrentNoteId();
if (noteId) {
return getNodes(noteId);
}
else {
return [];
}
}
function setCurrentNoteTitle(title) {
const currentNoteId = getCurrentNoteId();
if (currentNoteId) {
noteIdToTitle[currentNoteId] = title;
getCurrentClones().map(clone => clone.setTitle(title));
}
}
function createNewTopLevelNote() {
let rootNode = treeEl.fancytree("getRootNode");
createNote(rootNode, "root", "into");
}
let newNoteCreated = false;
function isNewNoteCreated() {
return newNoteCreated;
}
function switchOffNewNoteCreated() {
newNoteCreated = false;
}
async function createNote(node, parentNoteId, target, 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 newNoteName = "new note";
const result = await $.ajax({
url: baseApiUrl + 'notes/' + parentNoteId + '/children' ,
type: 'POST',
data: JSON.stringify({
note_title: newNoteName,
target: target,
target_note_tree_id: node.data.note_tree_id,
is_protected: isProtected
}),
contentType: "application/json"
});
const newNode = {
title: newNoteName,
note_id: result.note_id,
note_pid: parentNoteId,
refKey: result.note_id,
note_tree_id: result.note_tree_id,
is_protected: isProtected,
extraClasses: isProtected ? "protected" : ""
};
parentToChildren[parentNoteId].push(result.note_id);
parentToChildren[result.note_id] = [];
childToParents[result.note_id] = [ parentNoteId ];
noteIdToTitle[result.note_id] = newNoteName;
newNoteCreated = true;
if (target === 'after') {
node.appendSibling(newNode).setActive(true);
}
else {
node.addChildren(newNode).setActive(true);
node.folder = true;
node.renderTitle();
}
showMessage("Created!");
}
2017-11-05 07:28:49 +08:00
$("button#reset-search-button").click(resetSearch);
$("input[name=search]").keyup(e => {
const searchString = $("input[name=search]").val();
if (e && e.which === $.ui.keyCode.ESCAPE || $.trim(searchString) === "") {
$("button#reset-search-button").click();
return;
}
if (e && e.which === $.ui.keyCode.ENTER) {
$.get(baseApiUrl + 'notes?search=' + searchString).then(resp => {
console.log("search: ", resp);
// Pass a string to perform case insensitive matching
getTree().filterBranches(node => {
2017-11-05 07:28:49 +08:00
return resp.includes(node.data.note_id);
});
});
}
}).focus();
$(document).bind('keydown', 'alt+s', showSearch);
return {
getTreeLoadTime,
reload,
2017-11-05 07:28:49 +08:00
collapseTree,
scrollToCurrentNote,
2017-11-05 07:49:26 +08:00
toggleSearch,
getNoteTreeIdFromKey,
setCurrentNoteTreeBasedOnProtectedStatus,
getCurrentNode,
getCurrentNoteTreeId,
2017-11-20 01:06:48 +08:00
activateNode,
getCurrentNotePath,
getNoteTitle,
2017-11-20 08:39:39 +08:00
setCurrentNotePathToHash,
getAutocompleteItems,
setCurrentNoteTitle,
createNewTopLevelNote,
createNote,
isNewNoteCreated,
switchOffNewNoteCreated
2017-11-05 07:28:49 +08:00
};
})();