Notes/src/services/tree.ts

272 lines
9.2 KiB
TypeScript
Raw Normal View History

2018-01-13 18:02:41 -05:00
"use strict";
import sql from "./sql.js";
import log from "./log.js";
import BBranch from "../becca/entities/bbranch.js";
import entityChangesService from "./entity_changes.js";
import becca from "../becca/becca.js";
import type BNote from "../becca/entities/bnote.js";
2024-02-18 11:47:32 +02:00
interface ValidationResponse {
branch: BBranch | null;
success: boolean;
message?: string;
}
function validateParentChild(parentNoteId: string, childNoteId: string, branchId: string | null = null): ValidationResponse {
2025-01-09 18:07:02 +02:00
if (["root", "_hidden", "_share", "_lbRoot", "_lbAvailableLaunchers", "_lbVisibleLaunchers"].includes(childNoteId)) {
return { branch: null, success: false, message: `Cannot change this note's location.` };
}
2025-01-09 18:07:02 +02:00
if (parentNoteId === "none") {
// this shouldn't happen
return { branch: null, success: false, message: `Cannot move anything into 'none' parent.` };
}
const existingBranch = becca.getBranchFromChildAndParent(childNoteId, parentNoteId);
2018-01-13 18:02:41 -05:00
if (existingBranch && existingBranch.branchId !== branchId) {
2021-12-23 20:54:48 +01:00
const parentNote = becca.getNote(parentNoteId);
const childNote = becca.getNote(childNoteId);
2018-03-30 12:57:22 -04:00
return {
branch: existingBranch,
2018-01-13 18:02:41 -05:00
success: false,
2024-02-18 11:47:32 +02:00
message: `Note "${childNote?.title}" note already exists in the "${parentNote?.title}".`
2018-03-30 12:57:22 -04:00
};
2018-01-13 18:02:41 -05:00
}
2023-04-14 16:49:06 +02:00
if (wouldAddingBranchCreateCycle(parentNoteId, childNoteId)) {
2018-03-30 12:57:22 -04:00
return {
branch: null,
2018-01-13 18:02:41 -05:00
success: false,
2025-01-09 18:07:02 +02:00
message: "Moving/cloning note here would create cycle."
2018-03-30 12:57:22 -04:00
};
2018-01-13 18:02:41 -05:00
}
2025-01-09 18:07:02 +02:00
if (parentNoteId !== "_lbBookmarks" && becca.getNote(parentNoteId)?.type === "launcher") {
2022-08-08 23:13:31 +02:00
return {
branch: null,
2022-08-08 23:13:31 +02:00
success: false,
2025-01-09 18:07:02 +02:00
message: "Launcher note cannot have any children."
2022-08-08 23:13:31 +02:00
};
}
return { branch: null, success: true };
2018-01-13 18:02:41 -05:00
}
/**
* Tree cycle can be created when cloning or when moving existing clone. This method should detect both cases.
*/
2024-02-18 11:47:32 +02:00
function wouldAddingBranchCreateCycle(parentNoteId: string, childNoteId: string) {
if (parentNoteId === childNoteId) {
return true;
}
2023-04-14 16:49:06 +02:00
const childNote = becca.getNote(childNoteId);
const parentNote = becca.getNote(parentNoteId);
2018-01-13 18:02:41 -05:00
2023-04-14 16:49:06 +02:00
if (!childNote || !parentNote) {
return false;
2018-01-13 18:02:41 -05:00
}
2023-04-14 16:49:06 +02:00
// we'll load the whole subtree - because the cycle can start in one of the notes in the subtree
const childSubtreeNoteIds = new Set(childNote.getSubtreeNoteIds());
const parentAncestorNoteIds = parentNote.getAncestorNoteIds();
2018-01-13 18:02:41 -05:00
2025-01-09 18:07:02 +02:00
return parentAncestorNoteIds.some((parentAncestorNoteId) => childSubtreeNoteIds.has(parentAncestorNoteId));
2018-01-13 18:02:41 -05:00
}
2025-01-09 18:07:02 +02:00
function sortNotes(parentNoteId: string, customSortBy: string = "title", reverse = false, foldersFirst = false, sortNatural = false, _sortLocale?: string | null) {
if (!customSortBy) {
2025-01-09 18:07:02 +02:00
customSortBy = "title";
}
2024-02-18 11:47:32 +02:00
// sortLocale can not be empty string or null value, default value must be set to undefined.
2025-01-09 18:07:02 +02:00
const sortLocale = _sortLocale || undefined;
2020-06-20 12:31:38 +02:00
sql.transactional(() => {
2024-02-18 11:47:32 +02:00
const note = becca.getNote(parentNoteId);
if (!note) {
throw new Error("Unable to find note");
}
2024-02-18 11:47:32 +02:00
const notes = note.getChildNotes();
2025-01-09 18:07:02 +02:00
const normalize = (obj: any) => (obj && typeof obj === "string" ? obj.toLowerCase() : obj);
notes.sort((a, b) => {
if (foldersFirst) {
const aHasChildren = a.hasChildren();
const bHasChildren = b.hasChildren();
if ((aHasChildren && !bHasChildren) || (!aHasChildren && bHasChildren)) {
2023-06-30 11:18:34 +02:00
// exactly one note of the two is a directory, so the sorting will be done based on this status
return aHasChildren ? -1 : 1;
}
}
2024-02-18 11:47:32 +02:00
function fetchValue(note: BNote, key: string) {
let rawValue;
2025-01-09 18:07:02 +02:00
if (key === "title") {
const branch = note.getParentBranches().find((branch) => branch.parentNoteId === parentNoteId);
const prefix = branch?.prefix;
rawValue = prefix ? `${prefix} - ${note.title}` : note.title;
} else {
2025-01-09 18:07:02 +02:00
rawValue = ["dateCreated", "dateModified"].includes(key) ? (note as any)[key] : note.getLabelValue(key);
}
return normalize(rawValue);
}
2024-02-18 11:47:32 +02:00
function compare(a: string, b: string) {
if (!sortNatural) {
// alphabetical sort
return b === null || b === undefined || a < b ? -1 : 1;
} else {
// natural sort
2025-01-09 18:07:02 +02:00
return a.localeCompare(b, sortLocale, { numeric: true, sensitivity: "base" });
}
}
2025-01-09 18:07:02 +02:00
const topAEl = fetchValue(a, "top");
const topBEl = fetchValue(b, "top");
if (topAEl !== topBEl) {
// since "top" should not be reversible, we'll reverse it once more to nullify this effect
return compare(topAEl, topBEl) * (reverse ? -1 : 1);
}
2025-01-09 18:07:02 +02:00
const bottomAEl = fetchValue(a, "bottom");
const bottomBEl = fetchValue(b, "bottom");
if (bottomAEl !== bottomBEl) {
// since "bottom" should not be reversible, we'll reverse it once more to nullify this effect
return compare(bottomBEl, bottomAEl) * (reverse ? -1 : 1);
}
const customAEl = fetchValue(a, customSortBy);
const customBEl = fetchValue(b, customSortBy);
if (customAEl !== customBEl) {
return compare(customAEl, customBEl);
}
2025-01-09 18:07:02 +02:00
const titleAEl = fetchValue(a, "title");
const titleBEl = fetchValue(b, "title");
return compare(titleAEl, titleBEl);
});
2021-02-28 23:40:15 +01:00
if (reverse) {
notes.reverse();
}
2019-10-19 12:36:16 +02:00
let position = 10;
let someBranchUpdated = false;
for (const note of notes) {
2025-01-09 18:07:02 +02:00
const branch = note.getParentBranches().find((b) => b.parentNoteId === parentNoteId);
if (!branch) {
continue;
}
2025-01-09 18:07:02 +02:00
if (branch.noteId === "_hidden") {
2022-11-26 14:57:39 +01:00
position = 999_999_999;
}
if (branch.notePosition !== position) {
2025-01-09 18:07:02 +02:00
sql.execute("UPDATE branches SET notePosition = ? WHERE branchId = ?", [position, branch.branchId]);
branch.notePosition = position;
someBranchUpdated = true;
}
2019-10-19 12:36:16 +02:00
position += 10;
}
if (someBranchUpdated) {
2023-07-29 23:25:02 +02:00
entityChangesService.putNoteReorderingEntityChange(parentNoteId);
}
});
}
2024-02-18 11:47:32 +02:00
function sortNotesIfNeeded(parentNoteId: string) {
const parentNote = becca.getNote(parentNoteId);
if (!parentNote) {
return;
}
2021-02-28 23:40:15 +01:00
2025-01-09 18:07:02 +02:00
const sortedLabel = parentNote.getLabel("sorted");
2021-02-28 23:40:15 +01:00
2025-01-09 18:07:02 +02:00
if (!sortedLabel || sortedLabel.value === "off") {
return;
}
2021-02-28 23:40:15 +01:00
2025-01-09 18:07:02 +02:00
const sortReversed = parentNote.getLabelValue("sortDirection")?.toLowerCase() === "desc";
const sortFoldersFirst = parentNote.isLabelTruthy("sortFoldersFirst");
const sortNatural = parentNote.isLabelTruthy("sortNatural");
const sortLocale = parentNote.getLabelValue("sortLocale");
sortNotes(parentNoteId, sortedLabel.value, sortReversed, sortFoldersFirst, sortNatural, sortLocale);
2021-02-28 23:40:15 +01:00
}
2019-11-10 19:29:51 +01:00
/**
2023-01-05 23:38:41 +01:00
* @deprecated this will be removed in the future
2019-11-10 19:29:51 +01:00
*/
2024-02-18 11:47:32 +02:00
function setNoteToParent(noteId: string, prefix: string, parentNoteId: string) {
2021-05-02 11:23:58 +02:00
const parentNote = becca.getNote(parentNoteId);
if (parentNoteId && !parentNote) {
// null parentNoteId is a valid value
throw new Error(`Cannot move note to deleted / missing parent note '${parentNoteId}'`);
}
// case where there might be more such branches is ignored. It's expected there should be just one
2024-02-18 11:47:32 +02:00
const branchId = sql.getValue<string>("SELECT branchId FROM branches WHERE isDeleted = 0 AND noteId = ? AND prefix = ?", [noteId, prefix]);
2021-05-11 22:00:16 +02:00
const branch = becca.getBranch(branchId);
if (branch) {
if (!parentNoteId) {
2023-06-05 09:23:42 +02:00
log.info(`Removing note '${noteId}' from parent '${parentNoteId}'`);
2022-01-31 22:09:39 +01:00
branch.markAsDeleted();
2025-01-09 18:07:02 +02:00
} else {
2022-01-31 22:09:39 +01:00
const newBranch = branch.createClone(parentNoteId);
newBranch.save();
branch.markAsDeleted();
}
2025-01-09 18:07:02 +02:00
} else if (parentNoteId) {
2021-05-02 11:23:58 +02:00
const note = becca.getNote(noteId);
2024-02-18 11:47:32 +02:00
if (!note) {
throw new Error(`Cannot find note '${noteId}.`);
}
if (note.isDeleted) {
2023-05-04 22:16:18 +02:00
throw new Error(`Cannot create a branch for '${noteId}' which is deleted.`);
}
2025-01-09 18:07:02 +02:00
const branchId = sql.getValue<string>("SELECT branchId FROM branches WHERE isDeleted = 0 AND noteId = ? AND parentNoteId = ?", [noteId, parentNoteId]);
2021-05-11 22:00:16 +02:00
const branch = becca.getBranch(branchId);
2019-11-10 19:29:51 +01:00
if (branch) {
branch.prefix = prefix;
2020-06-20 12:31:38 +02:00
branch.save();
2025-01-09 18:07:02 +02:00
} else {
new BBranch({
2019-11-10 19:29:51 +01:00
noteId: noteId,
parentNoteId: parentNoteId,
prefix: prefix
}).save();
}
}
}
export default {
2018-01-13 18:02:41 -05:00
validateParentChild,
2021-02-28 23:40:15 +01:00
sortNotes,
sortNotesIfNeeded,
setNoteToParent
2020-05-16 23:12:29 +02:00
};