trilium/public/javascripts/note_tree.js

674 lines
20 KiB
JavaScript
Raw Normal View History

"use strict";
2017-11-05 07:28:49 +08:00
const noteTree = (function() {
const treeEl = $("#tree");
const parentListEl = $("#parent-list");
2017-12-17 10:35:44 +08:00
const parentListListEl = $("#parent-list-list");
let startNotePath = null;
2017-11-24 09:12:39 +08:00
let notesTreeMap = {};
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 getNoteTreeId(parentNoteId, childNoteId) {
const key = parentNoteId + "-" + childNoteId;
// this can return undefined and client code should deal with it somehow
return parentChildToNoteTreeId[key];
}
function getNoteTitle(noteId, parentNoteId = null) {
let title = noteIdToTitle[noteId];
2017-11-20 01:06:48 +08:00
if (!title) {
throwError("Can't find title for noteId='" + noteId + "'");
2017-11-20 01:06:48 +08:00
}
if (parentNoteId !== null) {
const noteTreeId = getNoteTreeId(parentNoteId, noteId);
if (noteTreeId) {
const noteTree = notesTreeMap[noteTreeId];
if (noteTree.prefix) {
title = noteTree.prefix + ' - ' + title;
}
}
}
2017-11-20 01:06:48 +08:00
return title;
}
2017-11-24 09:12:39 +08:00
// 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 getCurrentNotePath() {
const node = getCurrentNode();
return treeUtils.getNotePath(node);
}
function getCurrentNoteId() {
const node = getCurrentNode();
return node ? node.data.note_id : null;
}
function getCurrentClones() {
const noteId = getCurrentNoteId();
if (noteId) {
2017-11-28 23:17:30 +08:00
return getNodesByNoteId(noteId);
2017-11-24 09:12:39 +08:00
}
else {
return [];
}
}
2017-11-28 23:17:30 +08:00
function getNodesByNoteTreeId(noteTreeId) {
const noteTree = notesTreeMap[noteTreeId];
return getNodesByNoteId(noteTree.note_id).filter(node => node.data.note_tree_id === noteTreeId);
}
function getNodesByNoteId(noteId) {
2017-12-13 11:26:40 +08:00
const list = getTree().getNodesByRef(noteId);
return list ? list : []; // if no nodes with this refKey are found, fancy tree returns null
2017-11-24 09:12:39 +08:00
}
2017-11-28 23:17:30 +08:00
function setPrefix(noteTreeId, prefix) {
notesTreeMap[noteTreeId].prefix = prefix;
getNodesByNoteTreeId(noteTreeId).map(node => {
node.data.prefix = prefix;
treeUtils.setNodeTitleWithPrefix(node);
});
}
function removeParentChildRelation(parentNoteId, childNoteId) {
const key = parentNoteId + "-" + childNoteId;
delete parentChildToNoteTreeId[key];
parentToChildren[parentNoteId] = parentToChildren[parentNoteId].filter(noteId => noteId !== childNoteId);
childToParents[childNoteId] = childToParents[childNoteId].filter(noteId => noteId !== parentNoteId);
}
function setParentChildRelation(noteTreeId, parentNoteId, childNoteId) {
const key = parentNoteId + "-" + childNoteId;
parentChildToNoteTreeId[key] = noteTreeId;
if (!parentToChildren[parentNoteId]) {
parentToChildren[parentNoteId] = [];
}
parentToChildren[parentNoteId].push(childNoteId);
if (!childToParents[childNoteId]) {
childToParents[childNoteId] = [];
}
childToParents[childNoteId].push(parentNoteId);
}
function prepareNoteTree(notes) {
2017-11-19 21:47:22 +08:00
parentToChildren = {};
childToParents = {};
2017-11-24 09:12:39 +08:00
notesTreeMap = {};
for (const note of notes) {
2017-11-24 09:12:39 +08:00
notesTreeMap[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
setParentChildRelation(note.note_tree_id, note.note_pid, note.note_id);
}
return prepareNoteTreeInner('root');
2017-11-18 10:31:54 +08:00
}
2017-11-24 09:12:39 +08:00
function getExtraClasses(note) {
let extraClasses = '';
if (note.is_protected) {
extraClasses += ",protected";
}
if (childToParents[note.note_id].length > 1) {
extraClasses += ",multiple-parents";
}
if (extraClasses.startsWith(",")) {
extraClasses = extraClasses.substr(1);
}
return extraClasses;
}
function prepareNoteTreeInner(parentNoteId) {
const childNoteIds = parentToChildren[parentNoteId];
2017-11-20 05:43:49 +08:00
if (!childNoteIds) {
2017-12-02 11:28:22 +08:00
messaging.logError("No children for " + parentNoteId + ". This shouldn't happen.");
2017-11-20 05:43:49 +08:00
return;
}
2017-11-18 10:31:54 +08:00
const noteList = [];
2017-11-24 09:12:39 +08:00
for (const noteId of childNoteIds) {
const noteTreeId = getNoteTreeId(parentNoteId, noteId);
const noteTree = notesTreeMap[noteTreeId];
const node = {
note_id: noteTree.note_id,
note_pid: noteTree.note_pid,
note_tree_id: noteTree.note_tree_id,
is_protected: noteTree.is_protected,
2017-11-27 11:40:14 +08:00
prefix: noteTree.prefix,
2017-11-27 11:34:25 +08:00
title: (noteTree.prefix ? (noteTree.prefix + " - ") : "") + noteIdToTitle[noteTree.note_id],
2017-11-24 09:12:39 +08:00
extraClasses: getExtraClasses(noteTree),
refKey: noteTree.note_id,
expanded: noteTree.is_expanded
};
if (parentToChildren[noteId] && parentToChildren[noteId].length > 0) {
node.folder = true;
2017-11-18 10:31:54 +08:00
if (node.expanded) {
2017-11-24 09:12:39 +08:00
node.children = prepareNoteTreeInner(noteId);
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) {
2017-12-04 06:46:56 +08:00
const runPath = getRunPath(notePath);
const noteId = treeUtils.getNoteIdFromNotePath(notePath);
let parentNoteId = 'root';
console.log("Run path: ", runPath);
2017-12-04 06:46:56 +08:00
for (const childNoteId of runPath) {
const node = getNodesByNoteId(childNoteId).find(node => node.data.note_pid === parentNoteId);
if (childNoteId === noteId) {
await node.setActive();
}
else {
await node.setExpanded();
}
parentNoteId = childNoteId;
}
}
/**
* 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.
*/
function getRunPath(notePath) {
2017-11-19 21:47:22 +08:00
const path = notePath.split("/").reverse();
2017-12-04 06:46:56 +08:00
path.push('root');
2017-11-19 21:47:22 +08:00
const effectivePath = [];
let childNoteId = null;
let i = 0;
while (true) {
if (i >= path.length) {
break;
}
const parentNoteId = path[i++];
if (childNoteId !== null) {
const parents = childToParents[childNoteId];
2017-11-27 10:00:42 +08:00
if (!parents) {
2017-12-02 11:28:22 +08:00
messaging.logError("No parents found for " + childNoteId);
2017-11-27 10:00:42 +08:00
return;
}
if (!parents.includes(parentNoteId)) {
console.log("Did not find parent " + parentNoteId + " for child " + childNoteId);
if (parents.length > 0) {
const pathToRoot = getSomeNotePath(parents[0]).split("/").reverse();
for (const noteId of pathToRoot) {
effectivePath.push(noteId);
}
break;
}
else {
2017-12-02 11:28:22 +08:00
messaging.logError("No parents, can't activate node.");
return;
}
}
}
2017-11-19 21:47:22 +08:00
2017-12-04 06:46:56 +08:00
if (parentNoteId === 'root') {
break;
2017-11-19 21:47:22 +08:00
}
else {
2017-12-04 06:46:56 +08:00
effectivePath.push(parentNoteId);
childNoteId = parentNoteId;
2017-11-19 21:47:22 +08:00
}
}
2017-12-04 06:46:56 +08:00
return effectivePath.reverse();
2017-11-19 21:47:22 +08:00
}
function showParentList(noteId, node) {
const parents = childToParents[noteId];
if (!parents) {
throwError("Can't find parents for noteId=" + noteId);
}
if (parents.length <= 1) {
parentListEl.hide();
}
else {
parentListEl.show();
2017-12-17 10:35:44 +08:00
parentListListEl.empty();
for (const parentNoteId of parents) {
const parentNotePath = getSomeNotePath(parentNoteId);
// this is to avoid having root notes leading '/'
const notePath = parentNotePath ? (parentNotePath + '/' + noteId) : 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);
}
2017-12-17 10:35:44 +08:00
parentListListEl.append($("<li/>").append(item));
}
}
}
function getNotePathTitle(notePath) {
const titlePath = [];
let parentNoteId = 'root';
for (const noteId of notePath.split('/')) {
titlePath.push(getNoteTitle(noteId, parentNoteId));
parentNoteId = noteId;
}
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('/');
}
async function setExpandedToServer(noteTreeId, isExpanded) {
const expandedNum = isExpanded ? 1 : 0;
2017-11-05 07:28:49 +08:00
await server.put('notes/' + noteTreeId + '/expanded/' + expandedNum);
2017-11-05 07:28:49 +08:00
}
function setCurrentNotePathToHash(node) {
const currentNotePath = treeUtils.getNotePath(node);
const currentNoteTreeId = node.data.note_tree_id;
document.location.hash = currentNotePath;
recentNotes.addRecentNote(currentNoteTreeId, currentNotePath);
}
function initFancyTree(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
},
"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) {
treeChanges.moveBeforeNode(node, beforeNode);
2017-11-05 07:28:49 +08:00
}
},
"shift+down": node => {
let afterNode = node.getNextSibling();
if (afterNode !== null) {
treeChanges.moveAfterNode(node, afterNode);
2017-11-05 07:28:49 +08:00
}
},
"shift+left": node => {
2017-11-29 04:17:11 +08:00
treeChanges.moveNodeUpInHierarchy(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
}
},
"f2": node => {
2017-11-28 23:17:30 +08:00
editTreePrefix.showDialog(node);
2017-11-05 07:28:49 +08:00
}
};
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);
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) => {
const noteId = treeUtils.getNoteIdFromNotePath(startNotePath);
if (noteIdToTitle[noteId] === undefined) {
// note doesn't exist so don't try to activate it
startNotePath = null;
}
if (startNotePath) {
activateNode(startNotePath);
2017-11-19 21:47:22 +08:00
}
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
2017-11-29 00:36:32 +08:00
case 67:
if (event.ctrlKey) { // Ctrl-C
contextMenu.copy(node);
return false;
}
break;
2017-11-05 07:28:49 +08:00
case 86:
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:
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 server.get('tree').then(resp => {
startNotePath = resp.start_note_path;
2017-11-05 07:28:49 +08:00
if (document.location.hash) {
startNotePath = document.location.hash.substr(1); // strip initial #
2017-11-05 07:28:49 +08:00
}
return prepareNoteTree(resp.notes);
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 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, parentNoteId);
2017-11-20 08:39:39 +08:00
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 setNoteTitle(noteId, title) {
noteIdToTitle[noteId] = title;
getNodesByNoteId(noteId).map(clone => treeUtils.setNodeTitleWithPrefix(clone));
}
async function createNewTopLevelNote() {
const rootNode = treeEl.fancytree("getRootNode");
await createNote(rootNode, "root", "into");
}
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 server.post('notes/' + parentNoteId + '/children', {
note_title: newNoteName,
target: target,
target_note_tree_id: node.data.note_tree_id,
is_protected: isProtected
});
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" : ""
};
setParentChildRelation(result.note_tree_id, parentNoteId, result.note_id);
notesTreeMap[result.note_tree_id] = result;
noteIdToTitle[result.note_id] = newNoteName;
noteEditor.newNoteCreated();
if (target === 'after') {
node.appendSibling(newNode).setActive(true);
}
else {
node.addChildren(newNode).setActive(true);
node.folder = true;
node.renderTitle();
}
showMessage("Created!");
}
$(document).bind('keydown', 'ctrl+insert', () => {
const node = getCurrentNode();
createNote(node, node.data.note_id, 'into', node.data.is_protected);
});
$(document).bind('keydown', 'ctrl+.', scrollToCurrentNote);
2017-11-05 07:28:49 +08:00
return {
reload,
2017-11-05 07:28:49 +08:00
collapseTree,
scrollToCurrentNote,
setCurrentNoteTreeBasedOnProtectedStatus,
getCurrentNode,
2017-11-20 01:06:48 +08:00
activateNode,
getCurrentNotePath,
getNoteTitle,
2017-11-20 08:39:39 +08:00
setCurrentNotePathToHash,
getAutocompleteItems,
setNoteTitle,
createNewTopLevelNote,
2017-11-28 23:17:30 +08:00
createNote,
setPrefix,
getNotePathTitle,
removeParentChildRelation,
setParentChildRelation
2017-11-05 07:28:49 +08:00
};
})();