522 lines
14 KiB
JavaScript
Raw Normal View History

2019-08-26 20:21:43 +02:00
import ws from './ws.js';
import protectedSessionHolder from './protected_session_holder.js';
import utils from './utils.js';
import server from './server.js';
import treeCache from './tree_cache.js';
2019-10-20 10:00:18 +02:00
import toastService from "./toast.js";
2018-03-26 23:18:50 -04:00
import treeBuilder from "./tree_builder.js";
2018-12-12 20:39:56 +01:00
import hoistedNoteService from '../services/hoisted_note.js';
import optionsService from "../services/options.js";
import bundle from "./bundle.js";
2020-01-12 11:15:23 +01:00
import appContext from "./app_context.js";
/**
* Accepts notePath which might or might not be valid and returns an existing path as close to the original
* notePath as possible.
2019-10-20 13:09:00 +02:00
* @return {string|null}
*/
async function resolveNotePath(notePath) {
const runPath = await getRunPath(notePath);
2019-05-14 22:29:47 +02:00
return runPath ? runPath.join("/") : null;
}
/**
* 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.
2019-10-20 13:09:00 +02:00
*
* @return {string[]}
*/
async function getRunPath(notePath) {
utils.assertArguments(notePath);
notePath = notePath.split("-")[0].trim();
if (notePath.length === 0) {
return;
}
const path = notePath.split("/").reverse();
2018-05-26 16:16:34 -04:00
if (!path.includes("root")) {
path.push('root');
}
2017-11-19 08:47:22 -05:00
2018-12-12 20:39:56 +01:00
const hoistedNoteId = await hoistedNoteService.getHoistedNoteId();
const effectivePath = [];
let childNoteId = null;
let i = 0;
while (true) {
if (i >= path.length) {
break;
}
const parentNoteId = path[i++];
if (childNoteId !== null) {
const child = await treeCache.getNote(childNoteId);
2018-11-12 23:34:22 +01:00
if (!child) {
2019-05-14 22:29:47 +02:00
console.log("Can't find note " + childNoteId);
return;
2018-11-12 23:34:22 +01:00
}
const parents = await child.getParentNotes();
if (!parents) {
2019-08-26 20:21:43 +02:00
ws.logError("No parents found for " + childNoteId);
return;
}
2017-11-26 21:00:42 -05:00
if (!parents.some(p => p.noteId === parentNoteId)) {
console.debug(utils.now(), "Did not find parent " + parentNoteId + " for child " + childNoteId);
if (parents.length > 0) {
console.debug(utils.now(), "Available parents:", parents);
const someNotePath = await getSomeNotePath(parents[0]);
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);
}
effectivePath.push('root');
}
2017-11-19 08:47:22 -05:00
break;
}
else {
2019-08-26 20:21:43 +02:00
ws.logError("No parents, can't activate node.");
return;
}
2017-11-19 08:47:22 -05:00
}
}
2017-12-03 17:46:56 -05:00
2018-12-12 20:39:56 +01:00
effectivePath.push(parentNoteId);
childNoteId = parentNoteId;
if (parentNoteId === hoistedNoteId) {
break;
}
2017-11-19 08:47:22 -05:00
}
return effectivePath.reverse();
}
async function getSomeNotePath(note) {
utils.assertArguments(note);
const path = [];
let cur = note;
while (cur.noteId !== 'root') {
path.push(cur.noteId);
const parents = await cur.getParentNotes();
if (!parents.length) {
console.error(`Can't find parents for note ${cur.noteId}`);
2019-05-19 18:21:29 +02:00
return;
}
cur = parents[0];
}
2020-01-03 10:48:36 +01:00
path.push('root');
return path.reverse().join('/');
}
2017-11-04 19:28:49 -04:00
async function treeInitialized() {
2020-01-12 12:30:30 +01:00
if (appContext.getTabContexts().length > 0) {
// this is just tree reload - tabs are already in place
return;
}
const options = await optionsService.waitForOptions();
2019-05-10 21:43:40 +02:00
const openTabs = options.getJson('openTabs') || [];
2019-05-10 21:43:40 +02:00
// if there's notePath in the URL, make sure it's open and active
// (useful, among others, for opening clipped notes from clipper)
if (location.hash) {
const notePath = location.hash.substr(1);
2020-01-25 09:56:08 +01:00
const noteId = getNoteIdFromNotePath(notePath);
2019-11-17 10:22:26 +01:00
if (noteId && await treeCache.noteExists(noteId)) {
for (const tab of openTabs) {
tab.active = false;
}
2020-01-25 09:56:08 +01:00
const foundTab = openTabs.find(tab => noteId === getNoteIdFromNotePath(tab.notePath));
if (foundTab) {
foundTab.active = true;
}
else {
openTabs.push({
notePath: notePath,
active: true
});
}
}
}
let filteredTabs = [];
2019-05-10 21:43:40 +02:00
for (const openTab of openTabs) {
2020-01-25 09:56:08 +01:00
const noteId = getNoteIdFromNotePath(openTab.notePath);
2019-05-10 21:43:40 +02:00
if (await treeCache.noteExists(noteId)) {
// note doesn't exist so don't try to open tab for it
filteredTabs.push(openTab);
}
}
if (utils.isMobile()) {
// mobile frontend doesn't have tabs so show only the active tab
filteredTabs = filteredTabs.filter(tab => tab.active);
}
2019-05-10 21:43:40 +02:00
if (filteredTabs.length === 0) {
filteredTabs.push({
notePath: 'root',
active: true
});
}
2019-04-13 22:10:16 +02:00
2019-05-14 22:29:47 +02:00
if (!filteredTabs.find(tab => tab.active)) {
filteredTabs[0].active = true;
}
2019-05-10 21:43:40 +02:00
for (const tab of filteredTabs) {
2020-01-24 17:54:47 +01:00
const tabContext = appContext.openEmptyTab();
tabContext.setNote(tab.notePath);
if (tab.active) {
appContext.activateTab(tabContext.tabId);
}
}
2019-05-10 21:43:40 +02:00
// previous opening triggered task to save tab changes but these are bogus changes (this is init)
// so we'll cancel it
appContext.clearOpenTabsTask();
}
function isNotePathInAddress() {
2019-05-14 22:29:47 +02:00
const [notePath, tabId] = getHashValueFromAddress();
return notePath.startsWith("root")
// empty string is for empty/uninitialized tab
|| (notePath === '' && !!tabId);
}
function getHashValueFromAddress() {
2019-05-14 22:29:47 +02:00
const str = document.location.hash ? document.location.hash.substr(1) : ""; // strip initial #
return str.split("-");
}
async function createNewTopLevelNote() {
const hoistedNoteId = await hoistedNoteService.getHoistedNoteId();
2020-01-12 11:15:23 +01:00
const rootNode = appContext.getMainNoteTree().getNodesByNoteId(hoistedNoteId)[0];
await createNote(rootNode, hoistedNoteId, "into");
}
async function createNote(node, parentNoteId, target, extraOptions = {}) {
utils.assertArguments(node, parentNoteId, target);
extraOptions.activate = extraOptions.activate === undefined ? true : !!extraOptions.activate;
// 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 (!extraOptions.isProtected || !protectedSessionHolder.isProtectedSessionAvailable()) {
extraOptions.isProtected = false;
}
2020-01-12 12:30:30 +01:00
if (appContext.getActiveTabNoteType() !== 'text') {
extraOptions.saveSelection = false;
}
2020-02-02 11:14:44 +01:00
if (extraOptions.saveSelection && utils.isCKEditorInitialized()) {
[extraOptions.title, extraOptions.content] = parseSelectedHtml(window.cutToNote.getSelectedHtml());
}
const newNoteName = extraOptions.title || "new note";
2018-03-25 00:20:55 -04:00
2019-11-16 12:28:47 +01:00
const {note, branch} = await server.post(`notes/${parentNoteId}/children?target=${target}&targetBranchId=${node.data.branchId}`, {
title: newNoteName,
2019-11-16 17:00:22 +01:00
content: extraOptions.content || "",
isProtected: extraOptions.isProtected,
type: extraOptions.type
});
2018-03-25 00:20:55 -04:00
2020-02-02 11:14:44 +01:00
if (extraOptions.saveSelection && utils.isCKEditorInitialized()) {
// we remove the selection only after it was saved to server to make sure we don't lose anything
window.cutToNote.removeSelection();
}
2020-02-02 10:41:43 +01:00
noteDetailService.addDetailLoadedListener(note.noteId, () => appContext.trigger('focusAndSelectTitle'));
2018-10-31 18:21:58 +01:00
2019-10-26 09:51:08 +02:00
const noteEntity = await treeCache.getNote(note.noteId);
const branchEntity = treeCache.getBranch(branch.branchId);
let newNodeData = {
title: newNoteName,
2018-04-01 11:42:12 -04:00
noteId: branchEntity.noteId,
parentNoteId: parentNoteId,
2018-04-01 11:42:12 -04:00
refKey: branchEntity.noteId,
branchId: branchEntity.branchId,
isProtected: extraOptions.isProtected,
type: noteEntity.type,
2018-11-14 08:42:00 +01:00
extraClasses: await treeBuilder.getExtraClasses(noteEntity),
icon: await treeBuilder.getIcon(noteEntity),
folder: extraOptions.type === 'search',
2019-06-27 21:24:25 +02:00
lazy: true,
key: utils.randomString(12) // this should prevent some "duplicate key" errors
};
/** @var {FancytreeNode} */
let newNode;
if (target === 'after') {
newNode = node.appendSibling(newNodeData);
}
else if (target === 'into') {
if (!node.getChildren() && node.isFolder()) {
// folder is not loaded - load will bring up the note since it was already put into cache
await node.load(true);
await node.setExpanded();
}
else {
node.addChildren(newNodeData);
}
newNode = node.getLastChild();
const parentNoteEntity = await treeCache.getNote(node.data.noteId);
node.folder = true;
node.icon = await treeBuilder.getIcon(parentNoteEntity); // icon might change into folder
node.renderTitle();
}
else {
2019-10-20 10:00:18 +02:00
toastService.throwError("Unrecognized target: " + target);
}
if (extraOptions.activate) {
await newNode.setActive(true);
}
// need to refresh because original doesn't have methods like .getParent()
2020-01-12 11:15:23 +01:00
newNodeData = appContext.getMainNoteTree().getNodesByNoteId(branchEntity.noteId)[0];
// following for cycle will make sure that also clones of a parent are refreshed
2020-01-12 11:15:23 +01:00
for (const newParentNode of appContext.getMainNoteTree().getNodesByNoteId(parentNoteId)) {
if (newParentNode.key === newNodeData.getParent().key) {
// we've added a note into this one so no need to refresh
continue;
}
await newParentNode.load(true); // force reload to show up new note
2020-01-29 21:38:58 +01:00
await appContext.getMainNoteTree().updateNode(newParentNode);
}
2018-10-15 23:45:37 +02:00
return {note, branch};
}
/* If first element is heading, parse it out and use it as a new heading. */
function parseSelectedHtml(selectedHtml) {
const dom = $.parseHTML(selectedHtml);
if (dom.length > 0 && dom[0].tagName && dom[0].tagName.match(/h[1-6]/i)) {
const title = $(dom[0]).text();
2018-09-07 10:26:23 +02:00
// remove the title from content (only first occurence)
const content = selectedHtml.replace(dom[0].outerHTML, "");
return [title, content];
}
else {
return [null, selectedHtml];
}
}
async function sortAlphabetically(noteId) {
await server.put('notes/' + noteId + '/sort');
await reload();
}
2017-12-18 23:41:13 -05:00
2019-08-26 20:21:43 +02:00
ws.subscribeToMessages(message => {
if (message.type === 'refresh-tree') {
reload();
}
2019-06-23 13:25:00 +02:00
else if (message.type === 'open-note') {
2020-01-24 17:54:47 +01:00
appContext.activateOrOpenNote(message.noteId);
2019-06-23 13:25:00 +02:00
if (utils.isElectron()) {
const currentWindow = require("electron").remote.getCurrentWindow();
currentWindow.show();
}
}
});
$(window).on('hashchange', function() {
if (isNotePathInAddress()) {
2019-05-14 22:29:47 +02:00
const [notePath, tabId] = getHashValueFromAddress();
2020-01-12 12:30:30 +01:00
appContext.switchToTab(tabId, notePath);
}
});
2019-10-19 12:36:16 +02:00
async function duplicateNote(noteId, parentNoteId) {
const {note} = await server.post(`notes/${noteId}/duplicate/${parentNoteId}`);
2020-01-24 15:44:24 +01:00
await ws.waitForMaxKnownSyncId();
2019-10-19 12:36:16 +02:00
2020-02-02 20:02:08 +01:00
await appContext.activateOrOpenNote(note.noteId);
2019-10-19 12:36:16 +02:00
const origNote = await treeCache.getNote(noteId);
2019-10-20 10:00:18 +02:00
toastService.showMessage(`Note "${origNote.title}" has been duplicated`);
2019-10-19 12:36:16 +02:00
}
2020-01-25 09:56:08 +01:00
async function getParentProtectedStatus(node) {
return await hoistedNoteService.isRootNode(node) ? 0 : node.getParent().data.isProtected;
}
function getNoteIdFromNotePath(notePath) {
if (!notePath) {
return null;
}
const path = notePath.split("/");
const lastSegment = path[path.length - 1];
// path could have also tabId suffix
return lastSegment.split("-")[0];
}
function getNoteIdAndParentIdFromNotePath(notePath) {
let parentNoteId = 'root';
let noteId = '';
if (notePath) {
const path = notePath.split("/");
const lastSegment = path[path.length - 1];
// path could have also tabId suffix
noteId = lastSegment.split("-")[0];
if (path.length > 1) {
parentNoteId = path[path.length - 2];
}
}
return {
parentNoteId,
noteId
}
}
async function getNotePath(node) {
if (!node) {
console.error("Node is null");
return "";
}
const path = [];
while (node && !await hoistedNoteService.isRootNode(node)) {
if (node.data.noteId) {
path.push(node.data.noteId);
}
node = node.getParent();
}
if (node) { // null node can happen directly after unhoisting when tree is still hoisted but option has been changed already
path.push(node.data.noteId); // root or hoisted noteId
}
return path.reverse().join("/");
}
async function getNoteTitle(noteId, parentNoteId = null) {
utils.assertArguments(noteId);
const note = await treeCache.getNote(noteId);
if (!note) {
return "[not found]";
}
let {title} = note;
if (parentNoteId !== null) {
const branchId = note.parentToBranch[parentNoteId];
if (branchId) {
const branch = treeCache.getBranch(branchId);
if (branch && branch.prefix) {
title = branch.prefix + ' - ' + title;
}
}
}
return title;
}
async function getNotePathTitle(notePath) {
utils.assertArguments(notePath);
const titlePath = [];
if (notePath.startsWith('root/')) {
notePath = notePath.substr(5);
}
// special case when we want just root's title
if (notePath === 'root') {
return await getNoteTitle(notePath);
}
let parentNoteId = 'root';
for (const noteId of notePath.split('/')) {
titlePath.push(await getNoteTitle(noteId, parentNoteId));
parentNoteId = noteId;
}
return titlePath.join(' / ');
}
export default {
createNote,
sortAlphabetically,
treeInitialized,
2019-05-19 18:21:29 +02:00
resolveNotePath,
getSomeNotePath,
createNewTopLevelNote,
duplicateNote,
getRunPath,
2020-01-25 09:56:08 +01:00
getParentProtectedStatus,
getNotePath,
getNoteIdFromNotePath,
getNoteIdAndParentIdFromNotePath,
getNoteTitle,
getNotePathTitle
};