Skip to content

Build your personal knowledge base with Trilium Notes

Merge remote-tracking branch 'origin/main' into standalone

Elian Doran6180949de2d4
diff --cc apps/build-docs/package.json
index 13ca18a9da,197c885dc3..029ace4cd9
--- a/apps/build-docs/package.json
+++ b/apps/build-docs/package.json
@@@ -14,13 -14,9 +14,13 @@@
"keywords": [],
"author": "Elian Doran <[email protected]>",
"license": "AGPL-3.0-only",
- "packageManager": "[email protected]",
+ "packageManager": "[email protected]",
+ "dependencies": {
+ "@triliumnext/core": "workspace:*",
+ "@triliumnext/server": "workspace:*"
+ },
"devDependencies": {
- "@redocly/cli": "2.30.0",
+ "@redocly/cli": "2.30.4",
"archiver": "7.0.1",
"fs-extra": "11.3.4",
"js-yaml": "4.1.1",
diff --cc apps/client-standalone/package.json
index b3aa60e2ac,0000000000..950d247c6e
mode 100644,000000..100644
--- a/apps/client-standalone/package.json
+++ b/apps/client-standalone/package.json
@@@ -1,94 -1,0 +1,94 @@@
+{
+ "name": "@triliumnext/client-standalone",
+ "version": "0.102.2",
+ "description": "Standalone client for TriliumNext with SQLite WASM backend",
+ "private": true,
+ "license": "AGPL-3.0-only",
+ "scripts": {
+ "build": "cross-env NODE_OPTIONS=--max-old-space-size=4096 vite build",
+ "dev": "vite dev",
+ "test": "vitest",
+ "start-prod": "pnpm build && pnpm vite preview --port 8888",
+ "coverage": "vitest --coverage",
+ "e2e": "playwright test",
+ "start-prod-no-dir": "pnpm build && pnpm vite preview --host 127.0.0.1"
+ },
+ "dependencies": {
+ "@excalidraw/excalidraw": "0.18.0",
+ "@fullcalendar/core": "6.1.20",
+ "@fullcalendar/daygrid": "6.1.20",
+ "@fullcalendar/interaction": "6.1.20",
+ "@fullcalendar/list": "6.1.20",
+ "@fullcalendar/multimonth": "6.1.20",
+ "@fullcalendar/timegrid": "6.1.20",
+ "@maplibre/maplibre-gl-leaflet": "0.1.3",
+ "@mermaid-js/layout-elk": "0.2.1",
+ "@mind-elixir/node-menu": "5.0.1",
+ "@popperjs/core": "2.11.8",
+ "@preact/signals": "2.9.0",
+ "@sqlite.org/sqlite-wasm": "3.51.1-build2",
+ "@triliumnext/ckeditor5": "workspace:*",
+ "@triliumnext/codemirror": "workspace:*",
+ "@triliumnext/commons": "workspace:*",
+ "@triliumnext/core": "workspace:*",
+ "@triliumnext/highlightjs": "workspace:*",
+ "@triliumnext/share-theme": "workspace:*",
+ "@triliumnext/split.js": "workspace:*",
+ "@zumer/snapdom": "2.8.0",
+ "autocomplete.js": "0.38.1",
+ "bootstrap": "5.3.8",
+ "boxicons": "2.1.4",
+ "clsx": "2.1.1",
+ "color": "5.0.3",
+ "debounce": "3.0.0",
+ "draggabilly": "3.0.0",
+ "fflate": "0.8.2",
+ "force-graph": "1.51.4",
+ "globals": "17.4.0",
- "i18next": "26.0.5",
++ "i18next": "26.0.8",
+ "i18next-http-backend": "3.0.4",
+ "aes-js": "3.1.2",
+ "jquery": "4.0.0",
+ "jquery.fancytree": "2.38.5",
+ "js-md5": "0.8.3",
+ "js-sha1": "0.7.0",
+ "js-sha256": "0.11.1",
+ "js-sha512": "0.9.0",
+ "scrypt-js": "3.0.1",
+ "jsplumb": "2.15.6",
+ "katex": "0.16.45",
+ "knockout": "3.5.1",
+ "leaflet": "1.9.4",
+ "leaflet-gpx": "2.2.0",
+ "mark.js": "8.11.1",
+ "marked": "18.0.1",
+ "mermaid": "11.14.0",
+ "mind-elixir": "5.10.0",
+ "normalize.css": "8.0.1",
+ "panzoom": "9.4.4",
+ "preact": "10.29.1",
+ "react-i18next": "17.0.4",
+ "react-window": "2.2.7",
+ "reveal.js": "6.0.1",
+ "svg-pan-zoom": "3.6.2",
+ "tabulator-tables": "6.4.0",
+ "vanilla-js-wheel-zoom": "9.0.4"
+ },
+ "devDependencies": {
+ "@types/aes-js": "3.1.4",
+ "@ckeditor/ckeditor5-inspector": "5.0.0",
+ "@preact/preset-vite": "2.10.2",
+ "@types/bootstrap": "5.2.10",
+ "@types/jquery": "4.0.0",
+ "@types/leaflet": "1.9.21",
+ "@types/leaflet-gpx": "1.3.8",
+ "@types/mark.js": "8.11.12",
+ "@types/reveal.js": "5.2.2",
+ "@types/tabulator-tables": "6.3.1",
+ "copy-webpack-plugin": "14.0.0",
+ "cross-env": "7.0.3",
+ "happy-dom": "20.9.0",
+ "script-loader": "0.7.2",
+ "vite-plugin-static-copy": "4.0.1"
+ }
+}
diff --cc apps/client-standalone/src/lightweight/zip_provider.ts
index f5e435c5c5,0000000000..b0826b3a72
mode 100644,000000..100644
--- a/apps/client-standalone/src/lightweight/zip_provider.ts
+++ b/apps/client-standalone/src/lightweight/zip_provider.ts
@@@ -1,101 -1,0 +1,107 @@@
+import type { FileStream, ZipArchive, ZipEntry, ZipProvider } from "@triliumnext/core/src/services/zip_provider.js";
+import { strToU8, unzip, zipSync } from "fflate";
+
+type ZipOutput = {
+ send?: (body: unknown) => unknown;
+ write?: (chunk: Uint8Array | string) => unknown;
+ end?: (chunk?: Uint8Array | string) => unknown;
+};
+
+class BrowserZipArchive implements ZipArchive {
+ readonly #entries: Record<string, Uint8Array> = {};
+ #destination: ZipOutput | null = null;
+
+ append(content: string | Uint8Array, options: { name: string }) {
+ this.#entries[options.name] = typeof content === "string" ? strToU8(content) : content;
+ }
+
+ pipe(destination: unknown) {
+ this.#destination = destination as ZipOutput;
+ }
+
+ async finalize(): Promise<void> {
+ if (!this.#destination) {
+ throw new Error("ZIP output destination not set.");
+ }
+
+ const content = zipSync(this.#entries, { level: 9 });
+
+ if (typeof this.#destination.send === "function") {
+ this.#destination.send(content);
+ return;
+ }
+
+ if (typeof this.#destination.end === "function") {
+ if (typeof this.#destination.write === "function") {
+ this.#destination.write(content);
+ this.#destination.end();
+ } else {
+ this.#destination.end(content);
+ }
+ return;
+ }
+
+ throw new Error("Unsupported ZIP output destination.");
+ }
+}
+
+export default class BrowserZipProvider implements ZipProvider {
++ async detectFilenameEncoding(_buffer: Uint8Array): Promise<string> {
++ // fflate handles filename decoding internally; no additional detection needed.
++ return "utf-8";
++ }
++
+ createZipArchive(): ZipArchive {
+ return new BrowserZipArchive();
+ }
+
+ createFileStream(_filePath: string): FileStream {
+ throw new Error("File stream creation is not supported in the browser.");
+ }
+
+ readZipFile(
+ buffer: Uint8Array,
- processEntry: (entry: ZipEntry, readContent: () => Promise<Uint8Array>) => Promise<void>
++ processEntry: (entry: ZipEntry, readContent: () => Promise<Uint8Array>) => Promise<void>,
++ _filenameEncoding?: string
+ ): Promise<void> {
+ return new Promise<void>((res, rej) => {
+ unzip(buffer, async (err, files) => {
+ if (err) { rej(err); return; }
+
+ try {
+ for (const [fileName, data] of Object.entries(files)) {
+ await processEntry(
+ { fileName: decodeZipFileName(fileName) },
+ () => Promise.resolve(data)
+ );
+ }
+ res();
+ } catch (e) {
+ rej(e);
+ }
+ });
+ });
+ }
+}
+
+const utf8Decoder = new TextDecoder("utf-8", { fatal: true });
+
+/**
+ * fflate decodes ZIP entry filenames as CP437/Latin-1 unless the language
+ * encoding flag (general purpose bit 11) is set, but many real-world archives
+ * (e.g. those produced by macOS / Linux unzip / Python's zipfile) write UTF-8
+ * filenames without setting that flag. Recover the original UTF-8 bytes from
+ * fflate's per-byte string and re-decode them; if the result isn't valid
+ * UTF-8 we fall back to the as-decoded name.
+ */
+function decodeZipFileName(name: string): string {
+ const bytes = new Uint8Array(name.length);
+ for (let i = 0; i < name.length; i++) {
+ bytes[i] = name.charCodeAt(i) & 0xff;
+ }
+ try {
+ return utf8Decoder.decode(bytes);
+ } catch {
+ return name;
+ }
+}
diff --cc apps/client/package.json
index 2dca4079dd,c4ebb4cfd9..6d3da2ca3c
--- a/apps/client/package.json
+++ b/apps/client/package.json
@@@ -89,7 -89,7 +89,7 @@@
"happy-dom": "20.9.0",
"lightningcss": "1.32.0",
"script-loader": "0.7.2",
- "stylelint": "17.9.0",
+ "stylelint": "17.11.0",
"vite-plugin-static-copy": "4.1.0"
}
-}
+}
diff --cc apps/client/src/components/main_tree_executors.ts
index f4637a3702,f9bdf51945..bfff930bbd
--- a/apps/client/src/components/main_tree_executors.ts
+++ b/apps/client/src/components/main_tree_executors.ts
@@@ -1,12 -1,7 +1,12 @@@
- import appContext, { type CommandListenerData, type EventData } from "./app_context.js";
-import appContext, { type EventData } from "./app_context.js";
+import branchService from "../services/branches.js";
+import clipboard from "../services/clipboard.js";
+import froca from "../services/froca.js";
+import hoistedNoteService from "../services/hoisted_note.js";
import noteCreateService from "../services/note_create.js";
- import protectedSessionHolder from "../services/protected_session_holder.js";
+import protectedSessionService from "../services/protected_session.js";
++import protectedSessionHolder from "../services/protected_session_holder.js";
import treeService from "../services/tree.js";
-import hoistedNoteService from "../services/hoisted_note.js";
++import appContext, { type CommandListenerData, type EventData } from "./app_context.js";
import Component from "./component.js";
/**
@@@ -84,95 -75,12 +84,99 @@@ export default class MainTreeExecutors
await noteCreateService.createNote(parentNotePath, {
target: "after",
targetBranchId: node.data.branchId,
-- isProtected: isProtected,
++ isProtected,
saveSelection: false
});
}
+ async deleteNotesCommand({ selectedOrActiveBranchIds }: CommandListenerData<"deleteNotes">) {
+ const branchIds = selectedOrActiveBranchIds.filter((branchId) => !branchId.startsWith("virt-")); // search results can't be deleted
+
+ if (!branchIds.length) {
+ return;
+ }
+
+ await branchService.deleteNotes(branchIds);
+
+ this.tree?.clearSelectedNodes();
+ }
+
+ async editBranchPrefixCommand({ node, selectedOrActiveBranchIds }: CommandListenerData<"editBranchPrefix">) {
+ const branchIds = selectedOrActiveBranchIds.filter((branchId) => !branchId.startsWith("virt-"));
+
+ if (!branchIds.length) {
+ return;
+ }
+
+ appContext.triggerEvent("editBranchPrefix", {
+ selectedOrActiveBranchIds: branchIds,
+ node
+ });
+ }
+
+ copyNotesToClipboardCommand({ selectedOrActiveBranchIds }: CommandListenerData<"copyNotesToClipboard">) {
+ clipboard.copy(selectedOrActiveBranchIds);
+ }
+
+ cutNotesToClipboardCommand({ selectedOrActiveBranchIds }: CommandListenerData<"cutNotesToClipboard">) {
+ clipboard.cut(selectedOrActiveBranchIds);
+ }
+
+ pasteNotesFromClipboardCommand({ node, branchId }: CommandListenerData<"pasteNotesFromClipboard">) {
+ const targetBranchId = branchId ?? node?.data.branchId;
+ if (!targetBranchId) return;
+ clipboard.pasteInto(targetBranchId);
+ }
+
+ pasteNotesAfterFromClipboardCommand({ node, branchId }: CommandListenerData<"pasteNotesAfterFromClipboard">) {
+ const targetBranchId = branchId ?? node?.data.branchId;
+ if (!targetBranchId) return;
+ clipboard.pasteAfter(targetBranchId);
+ }
+
+ async exportNoteCommand({ node, notePath }: CommandListenerData<"exportNote">) {
+ const path = notePath ?? (node ? treeService.getNotePath(node) : undefined);
+ if (!path) return;
+
+ this.triggerCommand("showExportDialog", { notePath: path, defaultType: "subtree" });
+ }
+
+ async importIntoNoteCommand({ node, noteId }: CommandListenerData<"importIntoNote">) {
+ const targetNoteId = noteId ?? node?.data.noteId;
+ if (!targetNoteId) return;
+ this.triggerCommand("showImportDialog", { noteId: targetNoteId });
+ }
+
+ protectSubtreeCommand({ node, noteId }: CommandListenerData<"protectSubtree">) {
+ const targetNoteId = noteId ?? node?.data.noteId;
+ if (!targetNoteId) return;
+ protectedSessionService.protectNote(targetNoteId, true, true);
+ }
+
+ unprotectSubtreeCommand({ node, noteId }: CommandListenerData<"unprotectSubtree">) {
+ const targetNoteId = noteId ?? node?.data.noteId;
+ if (!targetNoteId) return;
+ protectedSessionService.protectNote(targetNoteId, false, true);
+ }
+
+ async duplicateSubtreeCommand({ selectedOrActiveBranchIds }: CommandListenerData<"duplicateSubtree">) {
+ for (const branchId of selectedOrActiveBranchIds) {
+ const branch = froca.getBranch(branchId);
+ if (!branch) continue;
+ const note = await froca.getNote(branch.noteId);
+ if (!note) continue;
+ if (note.isProtected && !protectedSessionHolder.isProtectedSessionAvailable()) continue;
+ noteCreateService.duplicateSubtree(branch.noteId, branch.parentNoteId);
+ }
+ }
+
+ async recentChangesInSubtreeCommand({ node, noteId }: CommandListenerData<"recentChangesInSubtree">) {
+ const ancestorNoteId = noteId ?? node?.data.noteId;
+ if (!ancestorNoteId) return;
+ this.triggerCommand("showRecentChanges", { ancestorNoteId });
+ }
++
+ async toggleArchivedNotesCommand(){
+ await this.tree?.toggleArchivedNotes();
+ }
}
diff --cc apps/server/package.json
index a4732f0547,979f6200cf..b940a32e7e
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@@ -38,9 -37,9 +38,9 @@@
"ai": "6.0.168",
"better-sqlite3": "12.9.0",
"html-to-text": "9.0.5",
+ "i18next-fs-backend": "2.6.3",
- "i18next": "26.0.5",
++ "i18next": "26.0.8",
"js-yaml": "4.1.1",
- "node-html-parser": "7.1.0",
- "sucrase": "3.35.1",
"unpdf": "1.6.0"
},
"devDependencies": {
diff --cc apps/server/src/zip_provider.ts
index 2ebe7b23cd,0000000000..3598029951
mode 100644,000000..100644
--- a/apps/server/src/zip_provider.ts
+++ b/apps/server/src/zip_provider.ts
@@@ -1,92 -1,0 +1,140 @@@
+import type { FileStream, ZipArchive, ZipEntry, ZipProvider } from "@triliumnext/core/src/services/zip_provider.js";
+import archiver, { type Archiver } from "archiver";
+import fs from "fs";
+import type { Stream } from "stream";
+import * as yauzl from "yauzl";
+
+class NodejsZipArchive implements ZipArchive {
+ readonly #archive: Archiver;
+
+ constructor() {
+ this.#archive = archiver("zip", {
+ zlib: { level: 9 }
+ });
+ }
+
+ append(content: string | Uint8Array, options: { name: string; date?: Date }) {
+ this.#archive.append(typeof content === "string" ? content : Buffer.from(content), options);
+ }
+
+ pipe(destination: unknown) {
+ this.#archive.pipe(destination as NodeJS.WritableStream);
+ }
+
+ finalize(): Promise<void> {
+ return this.#archive.finalize();
+ }
+}
+
+function streamToBuffer(stream: Stream): Promise<Buffer> {
+ const chunks: Uint8Array[] = [];
+ stream.on("data", (chunk: Uint8Array) => chunks.push(chunk));
+ return new Promise((res, rej) => {
+ stream.on("end", () => res(Buffer.concat(chunks)));
+ stream.on("error", rej);
+ });
+}
+
+export default class NodejsZipProvider implements ZipProvider {
++ detectFilenameEncoding(buffer: Uint8Array): Promise<string> {
++ return new Promise<string>((res, rej) => {
++ yauzl.fromBuffer(Buffer.from(buffer), { lazyEntries: true, validateEntrySizes: false, decodeStrings: false }, (err, zipfile) => {
++ if (err) return rej(err);
++ if (!zipfile) return rej(new Error("Unable to read zip file."));
++
++ const samples: Buffer[] = [];
++ zipfile.readEntry();
++ zipfile.on("entry", (entry: yauzl.Entry) => {
++ const isUtf8Flagged = !!(entry.generalPurposeBitFlag & 0x800);
++ if (!isUtf8Flagged && Buffer.isBuffer(entry.fileName)) {
++ samples.push(entry.fileName as Buffer);
++ }
++ zipfile.readEntry();
++ });
++ zipfile.on("end", async () => {
++ if (samples.length === 0) {
++ return res("utf-8");
++ }
++ const combined = Buffer.concat(samples);
++ try {
++ const chardet = await import("chardet");
++ const detected = chardet.default.detect(combined);
++ res(detected || "utf-8");
++ } catch {
++ res("utf-8");
++ }
++ });
++ zipfile.on("error", rej);
++ });
++ });
++ }
++
+ createZipArchive(): ZipArchive {
+ return new NodejsZipArchive();
+ }
+
+ createFileStream(filePath: string): FileStream {
+ const stream = fs.createWriteStream(filePath);
+ return {
+ destination: stream,
+ waitForFinish: () => new Promise((resolve, reject) => {
+ stream.on("finish", resolve);
+ stream.on("error", reject);
+ })
+ };
+ }
+
+ readZipFile(
+ buffer: Uint8Array,
- processEntry: (entry: ZipEntry, readContent: () => Promise<Uint8Array>) => Promise<void>
++ processEntry: (entry: ZipEntry, readContent: () => Promise<Uint8Array>) => Promise<void>,
++ filenameEncoding?: string
+ ): Promise<void> {
+ return new Promise<void>((res, rej) => {
+ yauzl.fromBuffer(Buffer.from(buffer), { lazyEntries: true, validateEntrySizes: false, decodeStrings: false }, (err, zipfile) => {
+ if (err) { rej(err); return; }
+ if (!zipfile) { rej(new Error("Unable to read zip file.")); return; }
+
+ zipfile.readEntry();
+ zipfile.on("entry", async (entry: yauzl.Entry) => {
+ try {
+ // yauzl with decodeStrings: false returns fileName as a Buffer.
- // We decode as UTF-8 to handle ZIP files that use UTF-8 filenames
- // without setting the general purpose bit flag 11 (language encoding flag).
- const fileName = Buffer.isBuffer(entry.fileName)
- ? (entry.fileName as Buffer).toString("utf-8")
- : entry.fileName;
++ // Use the detected encoding for non-UTF-8-flagged entries,
++ // falling back to UTF-8.
++ let fileName: string;
++ if (Buffer.isBuffer(entry.fileName)) {
++ const isUtf8Flagged = !!(entry.generalPurposeBitFlag & 0x800);
++ const encoding = isUtf8Flagged ? "utf-8" : (filenameEncoding || "utf-8");
++ fileName = decodeBuffer(entry.fileName as Buffer, encoding);
++ } else {
++ fileName = entry.fileName;
++ }
+
+ const readContent = () => new Promise<Uint8Array>((res, rej) => {
+ zipfile.openReadStream(entry, (err, readStream) => {
+ if (err) { rej(err); return; }
+ if (!readStream) { rej(new Error("Unable to read content.")); return; }
+ streamToBuffer(readStream).then(res, rej);
+ });
+ });
+
+ await processEntry({ fileName }, readContent);
+ } catch (e) {
+ rej(e);
+ }
+ zipfile.readEntry();
+ });
+ zipfile.on("end", res);
+ zipfile.on("error", rej);
+ });
+ });
+ }
+}
++
++function decodeBuffer(buf: Buffer, encoding: string): string {
++ try {
++ return new TextDecoder(encoding).decode(buf);
++ } catch {
++ // Fallback if the encoding label isn't supported by TextDecoder
++ return buf.toString("utf-8");
++ }
++}
diff --cc packages/trilium-core/package.json
index b8c771d417,0000000000..1d1ae1c443
mode 100644,000000..100644
--- a/packages/trilium-core/package.json
+++ b/packages/trilium-core/package.json
@@@ -1,30 -1,0 +1,30 @@@
+{
+ "name": "@triliumnext/core",
+ "version": "0.102.2",
+ "description": "",
+ "main": "src/index.ts",
+ "scripts": {
+ "test": "echo \"Note: Core tests are run either through apps/server or apps/client-standalone, since they have different runtime environments.\""
+ },
+ "dependencies": {
+ "@braintree/sanitize-url": "7.1.1",
+ "@triliumnext/commons": "workspace:*",
+ "@triliumnext/turndown-plugin-gfm": "workspace:*",
+ "async-mutex": "0.5.0",
+ "chardet": "2.1.1",
+ "escape-html": "1.0.3",
- "i18next": "26.0.5",
++ "i18next": "26.0.8",
+ "mime-types": "3.0.2",
+ "node-html-parser": "7.1.0",
+ "sanitize-filename": "1.6.4",
+ "sanitize-html": "2.17.2",
+ "strip-bom": "5.0.0",
+ "sucrase": "3.35.1",
+ "unescape": "1.0.1"
+ },
+ "devDependencies": {
+ "@types/escape-html": "1.0.4",
+ "@types/mime-types": "3.0.1",
+ "@types/sanitize-html": "2.16.1"
+ }
+}
diff --cc packages/trilium-core/src/becca/entities/bnote.ts
index 9ba1c96e64,0000000000..46f860328a
mode 100644,000000..100644
--- a/packages/trilium-core/src/becca/entities/bnote.ts
+++ b/packages/trilium-core/src/becca/entities/bnote.ts
@@@ -1,1788 -1,0 +1,1798 @@@
+import type { AttachmentRow, AttributeType, CloneResponse, NoteRow, NoteType, RevisionRow, RevisionSource } from "@triliumnext/commons";
+import { dayjs, getNoteIcon } from "@triliumnext/commons";
+
+import cloningService from "../../services/cloning.js";
+import dateUtils from "../../services/utils/date.js";
+import eraseService from "../../services/erase.js";
+import eventService from "../../services/events.js";
+import handlers from "../../services/handlers.js";
+import noteService from "../../services/notes.js";
+import optionService from "../../services/options.js";
+import protectedSessionService from "../../services/protected_session.js";
+import searchService from "../../services/search/services/search.js";
+import TaskContext from "../../services/task_context.js";
+import type { NotePojo } from "../becca-interface.js";
+import AbstractBeccaEntity from "./abstract_becca_entity.js";
+import BAttachment from "./battachment.js";
+import BAttribute from "./battribute.js";
+import type BBranch from "./bbranch.js";
+import BRevision from "./brevision.js";
+import { getLog } from "../../services/log.js";
+import { getSql } from "../../services/sql/index.js";
+import { formatDownloadTitle, isStringNote, normalize, randomString, replaceAll } from "../../services/utils/index.js";
- import scriptService from "../../services/script.js";
+
+const LABEL = "label";
+const RELATION = "relation";
+
+interface NotePathRecord {
+ isArchived: boolean;
+ isInHoistedSubTree: boolean;
+ notePath: string[];
+ isHidden: boolean;
+}
+
+interface ContentOpts {
+ /** will also save this BNote entity */
+ forceSave?: boolean;
+ /** override frontend heuristics on when to reload, instruct to reload */
+ forceFrontendReload?: boolean;
+}
+
+interface Relationship {
+ parentNoteId: string;
+ childNoteId: string;
+}
+
+interface ConvertOpts {
+ /** if true, the action is not triggered by user, but e.g. by migration, and only perfect candidates will be migrated */
+ autoConversion?: boolean;
+}
+
+/**
+ * Trilium's main entity, which can represent text note, image, code note, file attachment etc.
+ */
+class BNote extends AbstractBeccaEntity<BNote> {
+ static get entityName() {
+ return "notes";
+ }
+ static get primaryKeyName() {
+ return "noteId";
+ }
+ static get hashedProperties() {
+ return ["noteId", "title", "isProtected", "type", "mime", "blobId"];
+ }
+
+ noteId!: string;
+ title!: string;
+ type!: NoteType;
+ mime!: string;
+ /** set during the deletion operation, before it is completed (removed from becca completely). */
+ isBeingDeleted!: boolean;
+ isDecrypted!: boolean;
+
+ ownedAttributes!: BAttribute[];
+ parentBranches!: BBranch[];
+ parents!: BNote[];
+ children!: BNote[];
+ targetRelations!: BAttribute[];
+
+ __flatTextCache!: string | null;
+
+ private __attributeCache!: BAttribute[] | null;
+ private __inheritableAttributeCache!: BAttribute[] | null;
+ private __ancestorCache!: BNote[] | null;
+
+ // following attributes are filled during searching in the database
+ /** size of the content in bytes */
+ contentSize!: number | null;
+ /** size of the note content, attachment contents in bytes */
+ contentAndAttachmentsSize!: number | null;
+ /** size of the note content, attachment contents and revision contents in bytes */
+ contentAndAttachmentsAndRevisionsSize!: number | null;
+ /** number of note revisions for this note */
+ revisionCount!: number | null;
+
+ constructor(row?: Partial<NoteRow>) {
+ super();
+
+ if (!row) {
+ return;
+ }
+
+ this.updateFromRow(row);
+ this.init();
+ }
+
+ updateFromRow(row: Partial<NoteRow>) {
+ this.update([row.noteId, row.title, row.type, row.mime, row.isProtected, row.blobId, row.dateCreated, row.dateModified, row.utcDateCreated, row.utcDateModified]);
+ }
+
+ update([noteId, title, type, mime, isProtected, blobId, dateCreated, dateModified, utcDateCreated, utcDateModified]: any) {
+ // ------ Database persisted attributes ------
+
+ this.noteId = noteId;
+ this.title = title;
+ this.type = type;
+ this.mime = mime;
+ this.isProtected = !!isProtected;
+ this.blobId = blobId;
+ this.dateCreated = dateCreated || dateUtils.localNowDateTime();
+ this.dateModified = dateModified;
+ this.utcDateCreated = utcDateCreated || dateUtils.utcNowDateTime();
+ this.utcDateModified = utcDateModified;
+ this.isBeingDeleted = false;
+
+ // ------ Derived attributes ------
+
+ this.isDecrypted = !this.noteId || !this.isProtected;
+
+ this.decrypt();
+
+ this.__flatTextCache = null;
+
+ return this;
+ }
+
+ override init() {
+ this.parentBranches = [];
+ this.parents = [];
+ this.children = [];
+ this.ownedAttributes = [];
+ this.__attributeCache = null;
+ this.__inheritableAttributeCache = null;
+ this.targetRelations = [];
+
+ this.becca.addNote(this.noteId, this);
+ this.__ancestorCache = null;
+
+ this.contentSize = null;
+ this.contentAndAttachmentsSize = null;
+ this.contentAndAttachmentsAndRevisionsSize = null;
+ this.revisionCount = null;
+ }
+
+ isContentAvailable() {
+ return (
+ !this.noteId || // new note which was not encrypted yet
+ !this.isProtected ||
+ protectedSessionService.isProtectedSessionAvailable()
+ );
+ }
+
+ getTitleOrProtected() {
+ return this.isContentAvailable() ? this.title : "[protected]";
+ }
+
+ getParentBranches() {
+ return this.parentBranches;
+ }
+
+ /**
+ * Returns <i>strong</i> (as opposed to <i>weak</i>) parent branches. See isWeak for details.
+ */
+ getStrongParentBranches() {
+ return this.getParentBranches().filter((branch) => !branch.isWeak);
+ }
+
+ /**
+ * @deprecated use getParentBranches() instead
+ */
+ getBranches() {
+ return this.parentBranches;
+ }
+
+ getParentNotes() {
+ return this.parents;
+ }
+
+ getChildNotes() {
+ return this.children;
+ }
+
+ hasChildren() {
+ return this.children && this.children.length > 0;
+ }
+
+ getChildBranches(): BBranch[] {
+ return this.children.map((childNote) => this.becca.getBranchFromChildAndParent(childNote.noteId, this.noteId)) as BBranch[];
+ }
+
+ /**
+ * Note content has quite special handling - it's not a separate entity, but a lazily loaded
+ * part of Note entity with its own sync. Reasons behind this hybrid design has been:
+ *
+ * - content can be quite large, and it's not necessary to load it / fill memory for any note access even if we don't need a content, especially for bulk operations like search
+ * - changes in the note metadata or title should not trigger note content sync (so we keep separate utcDateModified and entity changes records)
+ * - but to the user note content and title changes are one and the same - single dateModified (so all changes must go through Note and content is not a separate entity)
+ */
+ getContent() {
+ return this._getContent();
+ }
+
+ /**
+ * @throws Error in case of invalid JSON
+ */
+ getJsonContent(): any | null {
+ const content = this.getContent();
+
+ if (typeof content !== "string" || !content || !content.trim()) {
+ return null;
+ }
+
+ return JSON.parse(content);
+ }
+
+ /** @returns valid object or null if the content cannot be parsed as JSON */
+ getJsonContentSafely() {
+ try {
+ return this.getJsonContent();
+ } catch (e) {
+ return null;
+ }
+ }
+
+ setContent(content: Uint8Array | string, opts: ContentOpts = {}) {
+ this._setContent(content, opts);
+
+ eventService.emit(eventService.NOTE_CONTENT_CHANGE, { entity: this });
+ }
+
+ setJsonContent(content: {}) {
+ this.setContent(JSON.stringify(content, null, "\t"));
+ }
+
+ get dateCreatedObj() {
+ return this.dateCreated === null ? null : dayjs(this.dateCreated);
+ }
+
+ get utcDateCreatedObj() {
+ return this.utcDateCreated === null ? null : dayjs.utc(this.utcDateCreated);
+ }
+
+ get dateModifiedObj() {
+ return this.dateModified === null ? null : dayjs(this.dateModified);
+ }
+
+ get utcDateModifiedObj() {
+ return this.utcDateModified === null ? null : dayjs.utc(this.utcDateModified);
+ }
+
+ /** @returns true if this note is the root of the note tree. Root note has "root" noteId */
+ isRoot() {
+ return this.noteId === "root";
+ }
+
+ /** @returns true if this note is of application/json content type */
+ isJson() {
+ return this.mime === "application/json";
+ }
+
+ /** @returns true if this note is JavaScript (code or attachment) */
+ isJavaScript() {
+ return (
+ (this.type === "code" || this.type === "file" || this.type === "launcher") &&
+ (this.mime.startsWith("application/javascript") || this.mime === "application/x-javascript" || this.mime === "text/javascript")
+ );
+ }
+
+ isJsx() {
+ return (this.type === "code" && this.mime === "text/jsx");
+ }
+
+ /** @returns true if this note is HTML */
+ isHtml() {
+ return ["code", "file", "render"].includes(this.type) && this.mime === "text/html";
+ }
+
++ /** @returns true if this note is a Markdown code note */
++ isMarkdown() {
++ return this.type === "code" && (this.mime === "text/markdown" || this.mime === "text/x-markdown" || this.mime === "text/x-gfm");
++ }
++
+ /** @returns true if this note is an image */
+ isImage() {
+ return this.type === "image" || (this.type === "file" && this.mime?.startsWith("image/"));
+ }
+
+ /** @deprecated use hasStringContent() instead */
+ isStringNote() {
+ return this.hasStringContent();
+ }
+
+ /** @returns true if the note has string content (not binary) */
+ override hasStringContent() {
+ return isStringNote(this.type, this.mime);
+ }
+
+ /** @returns JS script environment - either "frontend" or "backend" */
+ getScriptEnv() {
+ if (this.isHtml() || (this.isJavaScript() && this.mime.endsWith("env=frontend")) || this.isJsx()) {
+ return "frontend";
+ }
+
+ if (this.type === "render") {
+ return "frontend";
+ }
+
+ if (this.isJavaScript() && this.mime.endsWith("env=backend")) {
+ return "backend";
+ }
+
+ return null;
+ }
+
+ /**
+ * Executes this note as a script. The note must be of type "Code: JS backend".
+ *
+ * @returns the return value of the executed script
+ */
+ executeScript() {
++ // Lazy require to avoid circular dependency (script.ts imports BNote as a type).
++ // eslint-disable-next-line @typescript-eslint/no-require-imports
++ const scriptService = require("../../services/script.js").default;
+ return scriptService.executeNote(this, { originEntity: this });
+ }
+
+ /**
+ * Beware that the method must not create a copy of the array, but actually returns its internal array
+ * (for performance reasons)
+ *
+ * @param type - (optional) attribute type to filter
+ * @param name - (optional) attribute name to filter
+ * @returns all note's attributes, including inherited ones
+ */
+ getAttributes(type?: string, name?: string): BAttribute[] {
+ this.__validateTypeName(type, name);
+ this.__ensureAttributeCacheIsAvailable();
+
+ if (!this.__attributeCache) {
+ throw new Error("Attribute cache not available.");
+ }
+
+ if (type && name) {
+ return this.__attributeCache.filter((attr) => attr.name === name && attr.type === type);
+ } else if (type) {
+ return this.__attributeCache.filter((attr) => attr.type === type);
+ } else if (name) {
+ return this.__attributeCache.filter((attr) => attr.name === name);
+ }
+ return this.__attributeCache;
+ }
+
+ private __ensureAttributeCacheIsAvailable() {
+ if (!this.__attributeCache) {
+ this.__getAttributes([]);
+ }
+ }
+
+ private __getAttributes(path: string[]) {
+ if (path.includes(this.noteId)) {
+ return [];
+ }
+
+ if (!this.__attributeCache) {
+ const parentAttributes = this.ownedAttributes.slice();
+ const newPath = [...path, this.noteId];
+
+ // inheritable attrs on root are typically not intended to be applied to hidden subtree #3537
+ if (this.noteId !== "root" && this.noteId !== "_hidden") {
+ for (const parentNote of this.parents) {
+ parentAttributes.push(...parentNote.__getInheritableAttributes(newPath));
+ }
+ }
+
+ const templateAttributes: BAttribute[] = [];
+
+ for (const ownedAttr of parentAttributes) {
+ // parentAttributes so we process also inherited templates
+ if (ownedAttr.type === "relation" && ["template", "inherit"].includes(ownedAttr.name)) {
+ const templateNote = this.becca.notes[ownedAttr.value];
+
+ if (templateNote) {
+ templateAttributes.push(
+ ...templateNote
+ .__getAttributes(newPath)
+ // template attr is used as a marker for templates, but it's not meant to be inherited
+ .filter((attr) => !(attr.type === "label" && (attr.name === "template" || attr.name === "workspacetemplate")))
+ );
+ }
+ }
+ }
+
+ this.__attributeCache = [];
+
+ const addedAttributeIds = new Set();
+
+ for (const attr of parentAttributes.concat(templateAttributes)) {
+ if (!addedAttributeIds.has(attr.attributeId)) {
+ addedAttributeIds.add(attr.attributeId);
+
+ this.__attributeCache.push(attr);
+ }
+ }
+
+ this.__inheritableAttributeCache = [];
+
+ for (const attr of this.__attributeCache) {
+ if (attr.isInheritable) {
+ this.__inheritableAttributeCache.push(attr);
+ }
+ }
+ }
+
+ return this.__attributeCache;
+ }
+
+ private __getInheritableAttributes(path: string[]): BAttribute[] {
+ if (path.includes(this.noteId)) {
+ return [];
+ }
+
+ if (!this.__inheritableAttributeCache) {
+ this.__getAttributes(path); // will refresh also this.__inheritableAttributeCache
+ }
+
+ return this.__inheritableAttributeCache || [];
+ }
+
+ __validateTypeName(type?: string | null, name?: string | null) {
+ if (type && type !== "label" && type !== "relation") {
+ throw new Error(`Unrecognized attribute type '${type}'. Only 'label' and 'relation' are possible values.`);
+ }
+
+ if (name) {
+ const firstLetter = name.charAt(0);
+ if (firstLetter === "#" || firstLetter === "~") {
+ throw new Error(`Detect '#' or '~' in the attribute's name. In the API, attribute names should be set without these characters.`);
+ }
+ }
+ }
+
+ hasAttribute(type: string, name: string, value: string | null = null): boolean {
+ return !!this.getAttributes().find((attr) => attr.name === name && (value === undefined || value === null || attr.value === value) && attr.type === type);
+ }
+
+ getAttributeCaseInsensitive(type: string, name: string, value?: string | null) {
+ name = name.toLowerCase();
+ value = value ? value.toLowerCase() : null;
+
+ return this.getAttributes().find((attr) => attr.name.toLowerCase() === name && (!value || attr.value.toLowerCase() === value) && attr.type === type);
+ }
+
+ getRelationTarget(name: string) {
+ const relation = this.getAttributes().find((attr) => attr.name === name && attr.type === "relation");
+
+ return relation ? relation.targetNote : null;
+ }
+
+ /**
+ * @param name - label name
+ * @param value - label value
+ * @returns true if label exists (including inherited)
+ */
+ hasLabel(name: string, value?: string): boolean {
+ return this.hasAttribute(LABEL, name, value);
+ }
+
+ /**
+ * @param name - label name
+ * @returns true if label exists (including inherited) and does not have "false" value.
+ */
+ isLabelTruthy(name: string): boolean {
+ const label = this.getLabel(name);
+
+ if (!label) {
+ return false;
+ }
+
+ return label && label.value !== "false";
+ }
+
+ /**
+ * @param name - label name
+ * @param value - label value
+ * @returns true if label exists (excluding inherited)
+ */
+ hasOwnedLabel(name: string, value?: string): boolean {
+ return this.hasOwnedAttribute(LABEL, name, value);
+ }
+
+ /**
+ * @param name - relation name
+ * @param value - relation value
+ * @returns true if relation exists (including inherited)
+ */
+ hasRelation(name: string, value?: string): boolean {
+ return this.hasAttribute(RELATION, name, value);
+ }
+
+ /**
+ * @param name - relation name
+ * @param value - relation value
+ * @returns true if relation exists (excluding inherited)
+ */
+ hasOwnedRelation(name: string, value?: string): boolean {
+ return this.hasOwnedAttribute(RELATION, name, value);
+ }
+
+ /**
+ * @param name - label name
+ * @returns label if it exists, null otherwise
+ */
+ getLabel(name: string): BAttribute | null {
+ return this.getAttribute(LABEL, name);
+ }
+
+ /**
+ * @param name - label name
+ * @returns label if it exists, null otherwise
+ */
+ getOwnedLabel(name: string): BAttribute | null {
+ return this.getOwnedAttribute(LABEL, name);
+ }
+
+ /**
+ * @param name - relation name
+ * @returns relation if it exists, null otherwise
+ */
+ getRelation(name: string): BAttribute | null {
+ return this.getAttribute(RELATION, name);
+ }
+
+ /**
+ * @param name - relation name
+ * @returns relation if it exists, null otherwise
+ */
+ getOwnedRelation(name: string): BAttribute | null {
+ return this.getOwnedAttribute(RELATION, name);
+ }
+
+ /**
+ * @param name - label name
+ * @returns label value if label exists, null otherwise
+ */
+ getLabelValue(name: string): string | null {
+ return this.getAttributeValue(LABEL, name);
+ }
+
+ /**
+ * @param name - label name
+ * @returns label value if label exists, null otherwise
+ */
+ getOwnedLabelValue(name: string): string | null {
+ return this.getOwnedAttributeValue(LABEL, name);
+ }
+
+ /**
+ * @param name - relation name
+ * @returns relation value if relation exists, null otherwise
+ */
+ getRelationValue(name: string): string | null {
+ return this.getAttributeValue(RELATION, name);
+ }
+
+ /**
+ * @param name - relation name
+ * @returns relation value if relation exists, null otherwise
+ */
+ getOwnedRelationValue(name: string): string | null {
+ return this.getOwnedAttributeValue(RELATION, name);
+ }
+
+ /**
+ * @param attribute type (label, relation, etc.)
+ * @param name - attribute name
+ * @param value - attribute value
+ * @returns true if note has an attribute with given type and name (excluding inherited)
+ */
+ hasOwnedAttribute(type: string, name: string, value?: string): boolean {
+ return !!this.getOwnedAttribute(type, name, value);
+ }
+
+ /**
+ * @param type - attribute type (label, relation, etc.)
+ * @param name - attribute name
+ * @returns attribute of the given type and name. If there are more such attributes, first is returned.
+ * Returns null if there's no such attribute belonging to this note.
+ */
+ getAttribute(type: string, name: string): BAttribute | null {
+ const attributes = this.getAttributes();
+
+ return attributes.find((attr) => attr.name === name && attr.type === type) || null;
+ }
+
+ /**
+ * @param type - attribute type (label, relation, etc.)
+ * @param name - attribute name
+ * @returns attribute value of given type and name or null if no such attribute exists.
+ */
+ getAttributeValue(type: string, name: string): string | null {
+ const attr = this.getAttribute(type, name);
+
+ return attr ? attr.value : null;
+ }
+
+ /**
+ * @param type - attribute type (label, relation, etc.)
+ * @param name - attribute name
+ * @returns attribute value of given type and name or null if no such attribute exists.
+ */
+ getOwnedAttributeValue(type: string, name: string): string | null {
+ const attr = this.getOwnedAttribute(type, name);
+
+ return attr ? attr.value : null;
+ }
+
+ /**
+ * @param name - label name to filter
+ * @returns all note's labels (attributes with type label), including inherited ones
+ */
+ getLabels(name?: string): BAttribute[] {
+ return this.getAttributes(LABEL, name);
+ }
+
+ /**
+ * @param name - label name to filter
+ * @returns all note's label values, including inherited ones
+ */
+ getLabelValues(name: string): string[] {
+ return this.getLabels(name).map((l) => l.value);
+ }
+
+ /**
+ * @param name - label name to filter
+ * @returns all note's labels (attributes with type label), excluding inherited ones
+ */
+ getOwnedLabels(name: string): BAttribute[] {
+ return this.getOwnedAttributes(LABEL, name);
+ }
+
+ /**
+ * @param name - label name to filter
+ * @returns all note's label values, excluding inherited ones
+ */
+ getOwnedLabelValues(name: string): string[] {
+ return this.getOwnedAttributes(LABEL, name).map((l) => l.value);
+ }
+
+ /**
+ * @param name - relation name to filter
+ * @returns all note's relations (attributes with type relation), including inherited ones
+ */
+ getRelations(name?: string): BAttribute[] {
+ return this.getAttributes(RELATION, name);
+ }
+
+ /**
+ * @param name - relation name to filter
+ * @returns all note's relations (attributes with type relation), excluding inherited ones
+ */
+ getOwnedRelations(name?: string | null): BAttribute[] {
+ return this.getOwnedAttributes(RELATION, name);
+ }
+
+ /**
+ * Beware that the method must not create a copy of the array, but actually returns its internal array
+ * (for performance reasons)
+ *
+ * @param type - (optional) attribute type to filter
+ * @param name - (optional) attribute name to filter
+ * @param value - (optional) attribute value to filter
+ * @returns note's "owned" attributes - excluding inherited ones
+ */
+ getOwnedAttributes(type: string | null = null, name: string | null = null, value: string | null = null) {
+ this.__validateTypeName(type, name);
+
+ if (type && name && value !== undefined && value !== null) {
+ return this.ownedAttributes.filter((attr) => attr.name === name && attr.value === value && attr.type === type);
+ } else if (type && name) {
+ return this.ownedAttributes.filter((attr) => attr.name === name && attr.type === type);
+ } else if (type) {
+ return this.ownedAttributes.filter((attr) => attr.type === type);
+ } else if (name) {
+ return this.ownedAttributes.filter((attr) => attr.name === name);
+ }
+ return this.ownedAttributes;
+ }
+
+ /**
+ * @returns attribute belonging to this specific note (excludes inherited attributes)
+ *
+ * This method can be significantly faster than the getAttribute()
+ */
+ getOwnedAttribute(type: string, name: string, value: string | null = null) {
+ const attrs = this.getOwnedAttributes(type, name, value);
+
+ return attrs.length > 0 ? attrs[0] : null;
+ }
+
+ get isArchived() {
+ return this.hasAttribute("label", "archived");
+ }
+
+ areAllNotePathsArchived() {
+ // there's a slight difference between note being itself archived and all its note paths being archived
+ // - note is archived when it itself has an archived label or inherits it
+ // - note does not have or inherit archived label, but each note path contains a note with (non-inheritable)
+ // archived label
+
+ const bestNotePathRecord = this.getSortedNotePathRecords()[0];
+
+ if (!bestNotePathRecord) {
+ throw new Error(`No note path available for note '${this.noteId}'`);
+ }
+
+ return bestNotePathRecord.isArchived;
+ }
+
+ hasInheritableArchivedLabel() {
+ for (const attr of this.getAttributes()) {
+ if (attr.name === "archived" && attr.type === LABEL && attr.isInheritable) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ // will sort the parents so that the non-archived are first and archived at the end
+ // this is done so that the non-archived paths are always explored as first when looking for note path
+ sortParents() {
+ this.parentBranches.sort((a, b) => {
+ if (a.parentNote?.isArchived) {
+ return 1;
+ } else if (a.parentNote?.isHiddenCompletely()) {
+ return 1;
+ }
+ return 0;
+ });
+
+ this.parents = this.parentBranches.map((branch) => branch.parentNote).filter((note) => !!note) as BNote[];
+ }
+
+ sortChildren() {
+ if (this.children.length === 0) {
+ return;
+ }
+
+ const becca = this.becca;
+
+ this.children.sort((a, b) => {
+ const aBranch = becca.getBranchFromChildAndParent(a.noteId, this.noteId);
+ const bBranch = becca.getBranchFromChildAndParent(b.noteId, this.noteId);
+
+ return (aBranch?.notePosition || 0) - (bBranch?.notePosition || 0) || 0;
+ });
+ }
+
+ /**
+ * This is used for:
+ * - fast searching
+ * - note similarity evaluation
+ *
+ * @returns - returns flattened textual representation of note, prefixes and attributes
+ */
+ getFlatText() {
+ if (!this.__flatTextCache) {
+ this.__flatTextCache = `${this.noteId} ${this.type} ${this.mime} `;
+
+ for (const branch of this.parentBranches) {
+ if (branch.prefix) {
+ this.__flatTextCache += `${branch.prefix} `;
+ }
+ }
+
+ this.__flatTextCache += `${this.title} `;
+
+ for (const attr of this.getAttributes()) {
+ // it's best to use space as separator since spaces are filtered from the search string by the tokenization into words
+ this.__flatTextCache += `${attr.type === "label" ? "#" : "~"}${attr.name}`;
+
+ if (attr.value) {
+ this.__flatTextCache += `=${attr.value}`;
+ }
+
+ this.__flatTextCache += " ";
+ }
+
+ this.__flatTextCache = normalize(this.__flatTextCache);
+ }
+
+ return this.__flatTextCache as string;
+ }
+
+ invalidateThisCache() {
+ this.__flatTextCache = null;
+
+ this.__attributeCache = null;
+ this.__inheritableAttributeCache = null;
+ this.__ancestorCache = null;
++
++ // Mark only this note's flat text as dirty for incremental index update
++ this.becca.dirtyNoteFlatText(this.noteId);
+ }
+
+ invalidateSubTree(path: string[] = []) {
+ if (path.includes(this.noteId)) {
+ return;
+ }
+
+ this.invalidateThisCache();
+
+ if (this.children.length || this.targetRelations.length) {
+ path = [...path, this.noteId];
+ }
+
+ for (const childNote of this.children) {
+ childNote.invalidateSubTree(path);
+ }
+
+ for (const targetRelation of this.targetRelations) {
+ if (targetRelation.name === "template" || targetRelation.name === "inherit") {
+ const note = targetRelation.note;
+
+ if (note) {
+ note.invalidateSubTree(path);
+ }
+ }
+ }
+ }
+
+ getRelationDefinitions() {
+ return this.getLabels().filter((l) => l.name.startsWith("relation:"));
+ }
+
+ getLabelDefinitions() {
+ return this.getLabels().filter((l) => l.name.startsWith("relation:"));
+ }
+
+ isInherited() {
+ return !!this.targetRelations.find((rel) => rel.name === "template" || rel.name === "inherit");
+ }
+
+ getSubtreeNotesIncludingTemplated(): BNote[] {
+ const set = new Set<BNote>();
+
+ function inner(note: BNote) {
+ // _hidden is not counted as subtree for the purpose of inheritance
+ if (set.has(note) || note.noteId === "_hidden") {
+ return;
+ }
+
+ set.add(note);
+
+ for (const childNote of note.children) {
+ inner(childNote);
+ }
+
+ for (const targetRelation of note.targetRelations) {
+ if (targetRelation.name === "template" || targetRelation.name === "inherit") {
+ const targetNote = targetRelation.note;
+
+ if (targetNote) {
+ inner(targetNote);
+ }
+ }
+ }
+ }
+
+ inner(this);
+
+ return Array.from(set);
+ }
+
+ getSearchResultNotes(): BNote[] {
+ if (this.type !== "search") {
+ return [];
+ }
+
+ try {
+ const result = searchService.searchFromNote(this);
+ const becca = this.becca;
+ return result.searchResultNoteIds.map((resultNoteId) => becca.notes[resultNoteId]).filter((note) => !!note);
+ } catch (e: any) {
+ getLog().error(`Could not resolve search note ${this.noteId}: ${e.message}`);
+ return [];
+ }
+ }
+
+ getSubtree({ includeArchived = true, includeHidden = false, resolveSearch = false } = {}): {
+ notes: BNote[];
+ relationships: Relationship[];
+ } {
+ const noteSet = new Set<BNote>();
+ const relationships: Relationship[] = []; // list of tuples parentNoteId -> childNoteId
+
+ function resolveSearchNote(searchNote: BNote) {
+ try {
+ for (const resultNote of searchNote.getSearchResultNotes()) {
+ addSubtreeNotesInner(resultNote, searchNote);
+ }
+ } catch (e: any) {
+ getLog().error(`Could not resolve search note ${searchNote?.noteId}: ${e.message}`);
+ }
+ }
+
+ function addSubtreeNotesInner(note: BNote, parentNote: BNote | null = null) {
+ if (note.noteId === "_hidden" && !includeHidden) {
+ return;
+ }
+
+ if (parentNote) {
+ // this needs to happen first before noteSet check to include all clone relationships
+ relationships.push({
+ parentNoteId: parentNote.noteId,
+ childNoteId: note.noteId
+ });
+ }
+
+ if (noteSet.has(note)) {
+ return;
+ }
+
+ if (!includeArchived && note.isArchived) {
+ return;
+ }
+
+ noteSet.add(note);
+
+ if (note.type === "search") {
+ if (resolveSearch) {
+ resolveSearchNote(note);
+ }
+ } else {
+ for (const childNote of note.children) {
+ addSubtreeNotesInner(childNote, note);
+ }
+ }
+ }
+
+ addSubtreeNotesInner(this);
+
+ return {
+ notes: Array.from(noteSet),
+ relationships
+ };
+ }
+
+ /** @returns includes the subtree root note as well */
+ getSubtreeNoteIds({ includeArchived = true, includeHidden = false, resolveSearch = false } = {}) {
+ return this.getSubtree({ includeArchived, includeHidden, resolveSearch }).notes.map((note) => note.noteId);
+ }
+
+ /** @deprecated use getSubtreeNoteIds() instead */
+ getDescendantNoteIds() {
+ return this.getSubtreeNoteIds();
+ }
+
+ get parentCount() {
+ return this.parents.length;
+ }
+
+ get childrenCount() {
+ return this.children.length;
+ }
+
+ get labelCount() {
+ return this.getAttributes().filter((attr) => attr.type === "label").length;
+ }
+
+ get ownedLabelCount() {
+ return this.ownedAttributes.filter((attr) => attr.type === "label").length;
+ }
+
+ get relationCount() {
+ return this.getAttributes().filter((attr) => attr.type === "relation" && !attr.isAutoLink()).length;
+ }
+
+ get relationCountIncludingLinks() {
+ return this.getAttributes().filter((attr) => attr.type === "relation").length;
+ }
+
+ get ownedRelationCount() {
+ return this.ownedAttributes.filter((attr) => attr.type === "relation" && !attr.isAutoLink()).length;
+ }
+
+ get ownedRelationCountIncludingLinks() {
+ return this.ownedAttributes.filter((attr) => attr.type === "relation").length;
+ }
+
+ get targetRelationCount() {
+ return this.targetRelations.filter((attr) => !attr.isAutoLink()).length;
+ }
+
+ get targetRelationCountIncludingLinks() {
+ return this.targetRelations.length;
+ }
+
+ get attributeCount() {
+ return this.getAttributes().length;
+ }
+
+ get ownedAttributeCount() {
+ return this.getOwnedAttributes().length;
+ }
+
+ getAncestors() {
+ if (!this.__ancestorCache) {
+ const noteIds = new Set();
+ this.__ancestorCache = [];
+
+ for (const parent of this.parents) {
+ if (noteIds.has(parent.noteId)) {
+ continue;
+ }
+
+ this.__ancestorCache.push(parent);
+ noteIds.add(parent.noteId);
+
+ for (const ancestorNote of parent.getAncestors()) {
+ if (!noteIds.has(ancestorNote.noteId)) {
+ this.__ancestorCache.push(ancestorNote);
+ noteIds.add(ancestorNote.noteId);
+ }
+ }
+ }
+ }
+
+ return this.__ancestorCache;
+ }
+
+ getAncestorNoteIds(): string[] {
+ return this.getAncestors().map((note) => note.noteId);
+ }
+
+ hasAncestor(ancestorNoteId: string): boolean {
+ for (const ancestorNote of this.getAncestors()) {
+ if (ancestorNote.noteId === ancestorNoteId) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ isInHiddenSubtree() {
+ return this.noteId === "_hidden" || this.hasAncestor("_hidden");
+ }
+
+ getTargetRelations() {
+ return this.targetRelations;
+ }
+
+ /** @returns returns only notes which are templated, does not include their subtrees
+ * in effect returns notes which are influenced by note's non-inheritable attributes */
+ getInheritingNotes(): BNote[] {
+ const arr: BNote[] = [this];
+
+ for (const targetRelation of this.targetRelations) {
+ if (targetRelation.name === "template" || targetRelation.name === "inherit") {
+ const note = targetRelation.note;
+
+ if (note) {
+ arr.push(note);
+ }
+ }
+ }
+
+ return arr;
+ }
+
+ getDistanceToAncestor(ancestorNoteId: string) {
+ if (this.noteId === ancestorNoteId) {
+ return 0;
+ }
+
+ let minDistance = 999999;
+
+ for (const parent of this.parents) {
+ minDistance = Math.min(minDistance, parent.getDistanceToAncestor(ancestorNoteId) + 1);
+ }
+
+ return minDistance;
+ }
+
+ getRevisions(): BRevision[] {
+ return getSql().getRows<RevisionRow>("SELECT * FROM revisions WHERE noteId = ? ORDER BY revisions.utcDateCreated ASC", [this.noteId]).map((row) => new BRevision(row));
+ }
+
+ getAttachments() {
+ const query = /*sql*/`\
+ SELECT attachments.*, LENGTH(blobs.content) AS contentLength
+ FROM attachments
+ JOIN blobs USING (blobId)
+ WHERE ownerId = ? AND isDeleted = 0
+ ORDER BY position`;
+
+ return getSql().getRows<AttachmentRow>(query, [this.noteId]).map((row) => new BAttachment(row));
+ }
+
+ getAttachmentById(attachmentId: string) {
+ const query = /*sql*/`\
+ SELECT attachments.*, LENGTH(blobs.content) AS contentLength
+ FROM attachments
+ JOIN blobs USING (blobId)
+ WHERE ownerId = ? AND attachmentId = ? AND isDeleted = 0`;
+
+ return getSql().getRows<AttachmentRow>(query, [this.noteId, attachmentId]).map((row) => new BAttachment(row))[0];
+ }
+
+ getAttachmentsByRole(role: string): BAttachment[] {
+ return getSql()
+ .getRows<AttachmentRow>(
+ `
+ SELECT attachments.*
+ FROM attachments
+ WHERE ownerId = ?
+ AND role = ?
+ AND isDeleted = 0
+ ORDER BY position`,
+ [this.noteId, role]
+ )
+ .map((row) => new BAttachment(row));
+ }
+
+ getAttachmentByTitle(title: string): BAttachment | undefined {
+ // cannot use SQL to filter by title since it can be encrypted
+ return this.getAttachments().filter((attachment) => attachment.title === title)[0];
+ }
+
+ /**
+ * Gives all possible note paths leading to this note. Paths containing search note are ignored (could form cycles)
+ *
+ * @returns array of notePaths (each represented by array of noteIds constituting the particular note path)
+ */
+ getAllNotePaths(): string[][] {
+ if (this.noteId === "root") {
+ return [["root"]];
+ }
+
+ const parentNotes = this.getParentNotes();
+
+ const notePaths =
+ parentNotes.length === 1
+ ? parentNotes[0].getAllNotePaths() // optimization for the most common case
+ : parentNotes.flatMap((parentNote) => parentNote.getAllNotePaths());
+
+ for (const notePath of notePaths) {
+ notePath.push(this.noteId);
+ }
+
+ return notePaths;
+ }
+
+ getSortedNotePathRecords(hoistedNoteId: string = "root"): NotePathRecord[] {
+ const isHoistedRoot = hoistedNoteId === "root";
+
+ const notePaths = this.getAllNotePaths().map((path) => ({
+ notePath: path,
+ isInHoistedSubTree: isHoistedRoot || path.includes(hoistedNoteId),
+ isArchived: path.some((noteId) => this.becca.notes[noteId].isArchived),
+ isHidden: path.includes("_hidden")
+ }));
+
+ notePaths.sort((a, b) => {
+ if (a.isInHoistedSubTree !== b.isInHoistedSubTree) {
+ return a.isInHoistedSubTree ? -1 : 1;
+ } else if (a.isArchived !== b.isArchived) {
+ return a.isArchived ? 1 : -1;
+ } else if (a.isHidden !== b.isHidden) {
+ return a.isHidden ? 1 : -1;
+ }
+ return a.notePath.length - b.notePath.length;
+ });
+
+ return notePaths;
+ }
+
+ /**
+ * Returns a note path considered to be the "best"
+ *
+ * @return array of noteIds constituting the particular note path
+ */
+ getBestNotePath(hoistedNoteId: string = "root"): string[] {
+ return this.getSortedNotePathRecords(hoistedNoteId)[0]?.notePath;
+ }
+
+ /**
+ * Returns a note path considered to be the "best"
+ *
+ * @return serialized note path (e.g. 'root/a1h315/js725h')
+ */
+ getBestNotePathString(hoistedNoteId: string = "root"): string {
+ const notePath = this.getBestNotePath(hoistedNoteId);
+
+ return notePath?.join("/");
+ }
+
+ /**
+ * @return boolean - true if there's no non-hidden path, note is not cloned to the visible tree
+ */
+ isHiddenCompletely() {
+ if (this.noteId === "root") {
+ return false;
+ }
+
+ for (const parentNote of this.parents) {
+ if (parentNote.noteId === "root") {
+ return false;
+ } else if (parentNote.noteId === "_hidden") {
+ continue;
+ } else if (!parentNote.isHiddenCompletely()) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * @returns true if ancestorNoteId occurs in at least one of the note's paths
+ */
+ isDescendantOfNote(ancestorNoteId: string): boolean {
+ const notePaths = this.getAllNotePaths();
+
+ return notePaths.some((path) => path.includes(ancestorNoteId));
+ }
+
+ /**
+ * Update's given attribute's value or creates it if it doesn't exist
+ *
+ * @param type - attribute type (label, relation, etc.)
+ * @param name - attribute name
+ * @param value - attribute value (optional)
+ */
+ setAttribute(type: AttributeType, name: string, value?: string) {
+ const attributes = this.getOwnedAttributes();
+ const attr = attributes.find((attr) => attr.type === type && attr.name === name);
+
+ value = value?.toString() || "";
+
+ if (attr) {
+ if (attr.value !== value) {
+ attr.value = value;
+ attr.save();
+ }
+ } else {
+ new BAttribute({
+ noteId: this.noteId,
+ type,
+ name,
+ value
+ }).save();
+ }
+ }
+
+ /**
+ * Removes given attribute name-value pair if it exists.
+ *
+ * @param type - attribute type (label, relation, etc.)
+ * @param name - attribute name
+ * @param value - attribute value (optional)
+ */
+ removeAttribute(type: string, name: string, value?: string) {
+ const attributes = this.getOwnedAttributes();
+
+ for (const attribute of attributes) {
+ if (attribute.type === type && attribute.name === name && (value === undefined || value === attribute.value)) {
+ attribute.markAsDeleted();
+ }
+ }
+ }
+
+ /**
+ * Adds a new attribute to this note. The attribute is saved and returned.
+ * See addLabel, addRelation for more specific methods.
+ *
+ * @param type - attribute type (label / relation)
+ * @param name - name of the attribute, not including the leading ~/#
+ * @param value - value of the attribute - text for labels, target note ID for relations; optional.
+ */
+ addAttribute(type: AttributeType, name: string, value: string = "", isInheritable: boolean = false, position: number | null = null): BAttribute {
+ return new BAttribute({
+ noteId: this.noteId,
+ type,
+ name,
+ value,
+ isInheritable,
+ position
+ }).save();
+ }
+
+ /**
+ * Adds a new label to this note. The label attribute is saved and returned.
+ *
+ * @param name - name of the label, not including the leading #
+ * @param value - text value of the label; optional
+ */
+ addLabel(name: string, value: string = "", isInheritable: boolean = false): BAttribute {
+ return this.addAttribute(LABEL, name, value, isInheritable);
+ }
+
+ /**
+ * Adds a new relation to this note. The relation attribute is saved and
+ * returned.
+ *
+ * @param name - name of the relation, not including the leading ~
+ */
+ addRelation(name: string, targetNoteId: string, isInheritable: boolean = false): BAttribute {
+ return this.addAttribute(RELATION, name, targetNoteId, isInheritable);
+ }
+
+ /**
+ * Based on enabled, the attribute is either set or removed.
+ *
+ * @param type - attribute type ('relation', 'label' etc.)
+ * @param enabled - toggle On or Off
+ * @param name - attribute name
+ * @param value - attribute value (optional)
+ */
+ toggleAttribute(type: AttributeType, enabled: boolean, name: string, value?: string) {
+ if (enabled) {
+ this.setAttribute(type, name, value);
+ } else {
+ this.removeAttribute(type, name, value);
+ }
+ }
+
+ /**
+ * Based on enabled, label is either set or removed.
+ *
+ * @param enabled - toggle On or Off
+ * @param name - label name
+ * @param value - label value (optional)
+ */
+ toggleLabel(enabled: boolean, name: string, value?: string) {
+ return this.toggleAttribute(LABEL, enabled, name, value);
+ }
+
+ /**
+ * Based on enabled, relation is either set or removed.
+ *
+ * @param enabled - toggle On or Off
+ * @param name - relation name
+ * @param value - relation value (noteId)
+ */
+ toggleRelation(enabled: boolean, name: string, value?: string) {
+ return this.toggleAttribute(RELATION, enabled, name, value);
+ }
+
+ /**
+ * Update's given label's value or creates it if it doesn't exist
+ *
+ * @param name - label name
+ * @param value label value
+ */
+ setLabel(name: string, value?: string) {
+ return this.setAttribute(LABEL, name, value);
+ }
+
+ /**
+ * Update's given relation's value or creates it if it doesn't exist
+ *
+ * @param name - relation name
+ * @param value - relation value (noteId)
+ */
+ setRelation(name: string, value?: string) {
+ return this.setAttribute(RELATION, name, value);
+ }
+
+ /**
+ * Remove label name-value pair, if it exists.
+ *
+ * @param name - label name
+ * @param value - label value
+ */
+ removeLabel(name: string, value?: string) {
+ return this.removeAttribute(LABEL, name, value);
+ }
+
+ /**
+ * Remove the relation name-value pair, if it exists.
+ *
+ * @param name - relation name
+ * @param value - relation value (noteId)
+ */
+ removeRelation(name: string, value?: string) {
+ return this.removeAttribute(RELATION, name, value);
+ }
+
+ searchNotesInSubtree(searchString: string) {
+ return searchService.searchNotes(searchString) as BNote[];
+ }
+
+ searchNoteInSubtree(searchString: string) {
+ return this.searchNotesInSubtree(searchString)[0];
+ }
+
+ cloneTo(parentNoteId: string): CloneResponse {
+ const branch = this.becca.getNote(parentNoteId)?.getParentBranches()[0];
+ if (!branch?.branchId) {
+ return {
+ success: false,
+ message: "Unable to find the branch ID to clone."
+ };
+ }
+
+ return cloningService.cloneNoteToBranch(this.noteId, branch.branchId);
+ }
+
+ isEligibleForConversionToAttachment(opts: ConvertOpts = { autoConversion: false }) {
+ if (this.type !== "image" || !this.isContentAvailable() || this.hasChildren() || this.getParentBranches().length !== 1) {
+ return false;
+ }
+
+ const targetRelations = this.getTargetRelations().filter((relation) => relation.name === "imageLink");
+
+ if (opts.autoConversion && targetRelations.length === 0) {
+ return false;
+ } else if (targetRelations.length > 1) {
+ return false;
+ }
+
+ const parentNote = this.getParentNotes()[0]; // at this point note can have only one parent
+ const referencingNote = targetRelations[0]?.getNote();
+
+ if (referencingNote && parentNote !== referencingNote) {
+ return false;
+ } else if (parentNote.type !== "text" || !parentNote.isContentAvailable()) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Some notes are eligible for conversion into an attachment of its parent, note must have these properties:
+ * - it has exactly one target relation
+ * - it has a relation from its parent note
+ * - it has no children
+ * - it has no clones
+ * - the parent is of type text
+ * - both notes are either unprotected or user is in protected session
+ *
+ * Currently, works only for image notes.
+ *
+ * In the future, this functionality might get more generic and some of the requirements relaxed.
+ *
+ * @returns null if note is not eligible for conversion
+ */
+ convertToParentAttachment(opts: ConvertOpts = { autoConversion: false }): BAttachment | null {
+ if (!this.isEligibleForConversionToAttachment(opts)) {
+ return null;
+ }
+
+ const content = this.getContent();
+
+ const parentNote = this.getParentNotes()[0];
+ const attachment = parentNote.saveAttachment({
+ role: "image",
+ mime: this.mime,
+ title: this.title,
+ content
+ });
+
+ const parentContent = parentNote.getContent();
+
+ const oldNoteUrl = `api/images/${this.noteId}/`;
+ const newAttachmentUrl = `api/attachments/${attachment.attachmentId}/image/`;
+
+ if (typeof parentContent !== "string") {
+ throw new Error("Unable to convert image note into attachment because parent note does not have a string content.");
+ }
+
+ const fixedContent = replaceAll(parentContent, oldNoteUrl, newAttachmentUrl);
+
+ parentNote.setContent(fixedContent);
+
+ noteService.asyncPostProcessContent(parentNote, fixedContent); // to mark an unused attachment for deletion
+
+ this.deleteNote();
+
+ return attachment;
+ }
+
+ /**
+ * (Soft) delete a note and all its descendants.
+ *
+ * @param deleteId - optional delete identified
+ */
+ deleteNote(deleteId: string | null = null, taskContext: TaskContext<"deleteNotes"> | null = null) {
+ if (this.isDeleted) {
+ return;
+ }
+
+ if (!deleteId) {
+ deleteId = randomString(10);
+ }
+
+ if (!taskContext) {
+ taskContext = new TaskContext("no-progress-reporting", "deleteNotes", null);
+ }
+
+ // needs to be run before branches and attributes are deleted and thus attached relations disappear
+ handlers.runAttachedRelations(this, "runOnNoteDeletion", this);
+ taskContext.noteDeletionHandlerTriggered = true;
+
+ for (const branch of this.getParentBranches()) {
+ branch.deleteBranch(deleteId ?? undefined, taskContext);
+ }
+ }
+
+ decrypt() {
+ if (this.isProtected && !this.isDecrypted && protectedSessionService.isProtectedSessionAvailable()) {
+ try {
+ this.title = protectedSessionService.decryptString(this.title) || "";
+ this.__flatTextCache = null;
+
+ this.isDecrypted = true;
+ } catch (e: any) {
+ getLog().error(`Could not decrypt note ${this.noteId}: ${e.message} ${e.stack}`);
+ }
+ }
+ }
+
+ isLaunchBarConfig() {
+ return this.type === "launcher"
+ || ["_lbRoot", "_lbAvailableLaunchers", "_lbVisibleLaunchers"].includes(this.noteId)
+ || ["_lbMobileRoot", "_lbMobileAvailableLaunchers", "_lbMobileVisibleLaunchers"].includes(this.noteId);
+ }
+
+ isOptions() {
+ return this.noteId.startsWith("_options");
+ }
+
+ override get isDeleted() {
+ // isBeingDeleted is relevant only in the transition period when the deletion process has begun, but not yet
+ // finished (note is still in becca)
+ return !(this.noteId in this.becca.notes) || this.isBeingDeleted;
+ }
+
+ saveRevision(opts: { description?: string; source?: RevisionSource } = {}): BRevision {
+ return getSql().transactional(() => {
+ let noteContent = this.getContent();
+
+ const revision = new BRevision(
+ {
+ noteId: this.noteId,
+ // title and text should be decrypted now
+ title: this.title,
+ description: opts.description || "",
+ source: opts.source || "auto",
+ type: this.type,
+ mime: this.mime,
+ isProtected: this.isProtected,
+ utcDateLastEdited: this.utcDateModified,
+ utcDateCreated: dateUtils.utcNowDateTime(),
+ utcDateModified: dateUtils.utcNowDateTime(),
+ dateLastEdited: this.dateModified,
+ dateCreated: dateUtils.localNowDateTime()
+ },
+ true
+ );
+
+ revision.save(); // to generate revisionId, which is then used to save attachments
+
+ for (const noteAttachment of this.getAttachments()) {
+ const revisionAttachment = noteAttachment.copy();
+
+ if (!revision.revisionId) {
+ throw new Error("Revision ID is missing.");
+ }
+
+ revisionAttachment.ownerId = revision.revisionId;
+ revisionAttachment.setContent(noteAttachment.getContent(), { forceSave: true });
+
+ if (this.type === "text" && typeof noteContent === "string") {
+ // content is rewritten to point to the revision attachments
+ noteContent = noteContent.replaceAll(`attachments/${noteAttachment.attachmentId}`, `attachments/${revisionAttachment.attachmentId}`);
+
+ noteContent = noteContent.replaceAll(
+ new RegExp(`href="[^"]*attachmentId=${noteAttachment.attachmentId}[^"]*"`, "gi"),
+ `href="api/attachments/${revisionAttachment.attachmentId}/download"`
+ );
+ }
+ }
+
+ revision.setContent(noteContent);
+
+ this.eraseExcessRevisionSnapshots();
+ return revision;
+ });
+ }
+
+ // Limit the number of Snapshots to revisionSnapshotNumberLimit
+ // Delete older Snapshots that exceed the limit
+ eraseExcessRevisionSnapshots() {
+ // lable has a higher priority
+ let revisionSnapshotNumberLimit = parseInt(this.getLabelValue("versioningLimit") ?? "");
+ if (!Number.isInteger(revisionSnapshotNumberLimit)) {
+ revisionSnapshotNumberLimit = parseInt(optionService.getOption("revisionSnapshotNumberLimit"));
+ }
+ if (revisionSnapshotNumberLimit >= 0) {
+ const revisions = this.getRevisions();
+ if (revisions.length - revisionSnapshotNumberLimit > 0) {
+ const revisionIds = revisions
+ .slice(0, revisions.length - revisionSnapshotNumberLimit)
+ .map((revision) => revision.revisionId)
+ .filter((id): id is string => id !== undefined);
+ eraseService.eraseRevisions(revisionIds);
+ }
+ }
+ }
+
+ /**
+ * @param matchBy - choose by which property we detect if to update an existing attachment.
+ * Supported values are either 'attachmentId' (default) or 'title'
+ */
+ saveAttachment({ attachmentId, role, mime, title, content, position }: Omit<AttachmentRow, "ownerId">, matchBy: "attachmentId" | "title" | undefined = "attachmentId") {
+ if (!["attachmentId", "title"].includes(matchBy)) {
+ throw new Error(`Unsupported value '${matchBy}' for matchBy param, has to be either 'attachmentId' or 'title'.`);
+ }
+
+ let attachment;
+
+ if (matchBy === "title" && title) {
+ attachment = this.getAttachmentByTitle(title);
+ } else if (matchBy === "attachmentId" && attachmentId) {
+ attachment = this.becca.getAttachmentOrThrow(attachmentId);
+ }
+
+ attachment =
+ attachment ||
+ new BAttachment({
+ ownerId: this.noteId,
+ title,
+ role,
+ mime,
+ isProtected: this.isProtected,
+ position
+ });
+
+ content = content || "";
+ attachment.setContent(content, { forceSave: true });
+
+ return attachment;
+ }
+
+ getFileName() {
+ return formatDownloadTitle(this.title, this.type, this.mime);
+ }
+
+ override beforeSaving() {
+ super.beforeSaving();
+
+ this.becca.addNote(this.noteId, this);
+
+ this.dateModified = dateUtils.localNowDateTime();
+ this.utcDateModified = dateUtils.utcNowDateTime();
+ }
+
+ getPojo(): NotePojo {
+ return {
+ noteId: this.noteId,
+ title: this.title,
+ isProtected: this.isProtected,
+ type: this.type,
+ mime: this.mime,
+ blobId: this.blobId,
+ isDeleted: false,
+ dateCreated: this.dateCreated,
+ dateModified: this.dateModified,
+ utcDateCreated: this.utcDateCreated,
+ utcDateModified: this.utcDateModified
+ };
+ }
+
+ override getPojoToSave() {
+ const pojo = this.getPojo();
+
+ if (pojo.isProtected) {
+ if (this.isDecrypted && pojo.title) {
+ pojo.title = protectedSessionService.encrypt(pojo.title) || undefined;
+ } else {
+ // updating protected note outside of protected session means we will keep original ciphertexts
+ delete pojo.title;
+ }
+ }
+
+ return pojo;
+ }
+
+ getIcon() {
+ const iconClassLabels = this.getLabels("iconClass");
+ const icon = getNoteIcon({
+ noteId: this.noteId,
+ type: this.type,
+ mime: this.mime,
+ iconClass: iconClassLabels.length > 0 ? iconClassLabels[0].value : undefined,
+ workspaceIconClass: undefined,
+ isFolder: this.isFolder.bind(this)
+ });
+
+ return `tn-icon ${icon}`;
+ }
+
+ // TODO: Deduplicate with fnote
+ isFolder() {
+ return this.type === "search" || this.getFilteredChildBranches().length > 0;
+ }
+
+ // TODO: Deduplicate with fnote
+ getFilteredChildBranches() {
+ const childBranches = this.getChildBranches();
+
+ if (!childBranches) {
+ console.error(`No children for '${this.noteId}'. This shouldn't happen.`);
+ return [];
+ }
+
+ // we're not checking hideArchivedNotes since that would mean we need to lazy load the child notes
+ // which would seriously slow down everything.
+ // we check this flag only once user chooses to expand the parent. This has the negative consequence that
+ // note may appear as a folder but not contain any children when all of them are archived
+
+ return childBranches;
+ }
+
+ get encodedTitle() {
+ return encodeURIComponent(this.title);
+ }
+
+ getVisibleChildBranches() {
+ return this.getChildBranches().filter((branch) => {
+ const note = branch.getNote();
+ return !note.isLabelTruthy("shareHiddenFromTree") && !note.noteId.startsWith("_");
+ });
+ }
+
+ getVisibleChildNotes() {
+ return this.getVisibleChildBranches().map((branch) => branch.getNote());
+ }
+
+ hasVisibleChildren() {
+ return this.getVisibleChildNotes().length > 0;
+ }
+
+ get shareId() {
+ return this.noteId;
+ }
+
+ /**
+ * Return an attribute by it's attributeId. Requires the attribute cache to be available.
+ * @param attributeId - the id of the attribute owned by this note
+ * @returns - the BAttribute with the given id or undefined if not found.
+ */
+ getAttributeById(attributeId : string): BAttribute | undefined {
+ this.__ensureAttributeCacheIsAvailable();
+
+ if (!this.__attributeCache) {
+ throw new Error("Attribute cache not available.");
+ }
+
+ return this.__attributeCache.find((attr) => attr.attributeId === attributeId);
+ }
+
+ /**
+ * Sets an attribute's value by it's attributeId.
+ * @param attributeId - the id of the attribute owned by this note
+ * @param value - the new value to replace
+ */
+ setAttributeValueById(attributeId : string, value? : string) {
+ const attributes = this.getOwnedAttributes();
+ const attr = attributes.find((attr) => attr.attributeId === attributeId);
+
+ value = value?.toString() || "";
+
+ if (attr) {
+ if (attr.value !== value) {
+ attr.value = value;
+ attr.save();
+ }
+ } else {
+ throw new Error(`Attribute with id ${attributeId} not found.`);
+ }
+ }
+}
+
+export default BNote;
diff --cc packages/trilium-core/src/routes/api/special_notes.ts
index 7f17ca7f5f,69f9ec3dac..40bfea5e19
--- a/packages/trilium-core/src/routes/api/special_notes.ts
+++ b/packages/trilium-core/src/routes/api/special_notes.ts
@@@ -49,11 -49,10 +49,11 @@@ function getDayNotesForMonth(req: Reque
AND attr.isDeleted = 0
AND attr.type = 'label'
AND attr.name = 'dateNote'
- AND attr.value LIKE '${month}%'`;
+ AND attr.value LIKE ? || '%'`;
+ const sql = getSql();
if (calendarRoot) {
- const rows = sql.getRows<{ date: string; noteId: string }>(query);
+ const rows = sql.getRows<{ date: string; noteId: string }>(query, [month]);
const result: Record<string, string> = {};
for (const { date, noteId } of rows) {
const note = becca.getNote(noteId);
diff --cc packages/trilium-core/src/services/backend_script_api.ts
index e233cb2c99,f72d70b889..dd9cb78c5b
--- a/packages/trilium-core/src/services/backend_script_api.ts
+++ b/packages/trilium-core/src/services/backend_script_api.ts
@@@ -558,11 -562,9 +559,11 @@@ function BackendScriptApi(this: Api, cu
this.logMessages = {};
this.logSpacedUpdates = {};
+ const logInstance = getLog();
+ const sql = getSql();
- this.log = (rawMessage) => {
- const message = formatLogMessage(rawMessage);
+ this.log = (...rawMessages) => {
- const message = formatLogMessage(...rawMessages);
- log.info(message);
++ const message = formatLogMessage(rawMessages);
+ logInstance.info(message);
if (!this.startNote) {
return;
diff --cc packages/trilium-core/src/services/export/rewrite_links.spec.ts
index 0000000000,712029f3dd..712029f3dd
mode 000000,100644..100644
--- a/packages/trilium-core/src/services/export/rewrite_links.spec.ts
+++ b/packages/trilium-core/src/services/export/rewrite_links.spec.ts
diff --cc packages/trilium-core/src/services/export/rewrite_links.ts
index 0000000000,31f65e962f..baa97b1f70
mode 000000,100644..100644
--- a/packages/trilium-core/src/services/export/rewrite_links.ts
+++ b/packages/trilium-core/src/services/export/rewrite_links.ts
@@@ -1,0 -1,65 +1,65 @@@
-import type NoteMeta from "../meta/note_meta.js";
++import { NoteMeta } from "../../meta";
+
+ const MARKDOWN_MIMES = new Set(["text/x-markdown", "text/markdown", "text/x-gfm"]);
+
+ export function isMarkdownCodeNote(mime: string | undefined): boolean {
+ return !!mime && MARKDOWN_MIMES.has(mime);
+ }
+
+ /**
+ * Rewrites Trilium-internal links in markdown content to use relative file paths
+ * suitable for export. This handles code notes with markdown MIME type, where
+ * the content is already in markdown format (unlike text notes which store HTML).
+ *
+ * Counterpart to `rewriteLinks` in `zip.ts` which handles HTML-style patterns.
+ */
+ export function rewriteMarkdownContentLinks(
+ content: string,
+ noteMeta: NoteMeta,
+ getNoteTargetUrl: (targetNoteId: string, sourceMeta: NoteMeta) => string | null
+ ): string {
+ // Attachment images: ![alt](api/attachments/{id}/image/{filename})
+ content = content.replace(
+ /!\[([^\]]*)\]\([^)]*?api\/attachments\/([a-zA-Z0-9_]+)\/image\/[^)]*\)/g,
+ (match, alt, attachmentId) => {
+ const url = findAttachmentUrl(noteMeta, attachmentId);
+ return url ? `![${alt}](${url})` : match;
+ }
+ );
+
+ // Image notes: ![alt](api/images/{id}/{filename})
+ content = content.replace(
+ /!\[([^\]]*)\]\([^)]*?api\/images\/([a-zA-Z0-9_]+)\/[^)]*\)/g,
+ (match, alt, noteId) => {
+ const url = getNoteTargetUrl(noteId, noteMeta);
+ return url ? `![${alt}](${url})` : match;
+ }
+ );
+
+ // Attachment download links: [text](#root/...?attachmentId={id})
+ // Must be matched before internal note links to avoid partial matches.
+ content = content.replace(
+ /\[([^\]]*)\]\([^)]*#root[^)]*attachmentId=([a-zA-Z0-9_]+)[^)]*\)/g,
+ (match, text, attachmentId) => {
+ const url = findAttachmentUrl(noteMeta, attachmentId);
+ return url ? `[${text}](${url})` : match;
+ }
+ );
+
+ // Internal note links: [text](#root/.../noteId)
+ content = content.replace(
+ /\[([^\]]*)\]\(#root[a-zA-Z0-9_\/]*\/([a-zA-Z0-9_]+)[^)]*\)/g,
+ (match, text, noteId) => {
+ const url = getNoteTargetUrl(noteId, noteMeta);
+ return url ? `[${text}](${url})` : match;
+ }
+ );
+
+ return content;
+ }
+
+ function findAttachmentUrl(noteMeta: NoteMeta, attachmentId: string): string | undefined {
+ return (noteMeta.attachments || [])
+ .find((a) => a.attachmentId === attachmentId)
+ ?.dataFileName;
+ }
diff --cc packages/trilium-core/src/services/export/zip.ts
index 8aa4914750,60412233ed..ff46b9bcab
--- a/packages/trilium-core/src/services/export/zip.ts
+++ b/packages/trilium-core/src/services/export/zip.ts
@@@ -5,24 -11,32 +5,25 @@@ import packageInfo from "../../../packa
import becca from "../../becca/becca.js";
import BBranch from "../../becca/entities/bbranch.js";
import type BNote from "../../becca/entities/bnote.js";
-import ValidationError from "../../errors/validation_error.js";
-import dateUtils from "../date_utils.js";
-import log from "../log.js";
-import type AttachmentMeta from "../meta/attachment_meta.js";
-import type AttributeMeta from "../meta/attribute_meta.js";
-import type NoteMeta from "../meta/note_meta.js";
-import type { NoteMetaFile } from "../meta/note_meta.js";
+import dateUtils from "../utils/date.js";
+import { getLog } from "../log.js";
import protectedSessionService from "../protected_session.js";
import TaskContext from "../task_context.js";
-import { getContentDisposition, waitForStreamToFinish } from "../utils.js";
-import { AdvancedExportOptions, type ExportFormat, ZipExportProviderData } from "./zip/abstract_provider.js";
-import HtmlExportProvider from "./zip/html.js";
-import MarkdownExportProvider from "./zip/markdown.js";
-import ShareThemeExportProvider from "./zip/share_theme.js";
+import { getZipProvider } from "../zip_provider.js";
+import { getContentDisposition } from "../utils/index"
+import { AdvancedExportOptions, ZipExportProviderData } from "./zip/abstract_provider.js";
+import { getZipExportProviderFactory } from "./zip_export_provider_factory.js";
+import { AttachmentMeta, AttributeMeta, ExportFormat, NoteMeta, NoteMetaFile } from "../../meta";
+import { ValidationError } from "../../errors";
+import { extname } from "../utils/path";
+ import { rewriteMarkdownContentLinks, isMarkdownCodeNote } from "./rewrite_links.js";
-async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch, format: ExportFormat, res: Response | fs.WriteStream, setHeaders = true, zipExportOptions?: AdvancedExportOptions) {
- if (!["html", "markdown", "share"].includes(format)) {
- throw new ValidationError(`Only 'html', 'markdown' and 'share' allowed as export format, '${format}' given`);
- }
-
- const archive = archiver("zip", {
- zlib: { level: 9 } // Sets the compression level.
- });
+// eslint-disable-next-line @typescript-eslint/no-explicit-any
+async function exportToZip(taskContext: TaskContext<"export">, branch: BBranch, format: ExportFormat, res: Record<string, any>, setHeaders = true, zipExportOptions?: AdvancedExportOptions) {
+ const archive = getZipProvider().createZipArchive();
const rewriteFn = (zipExportOptions?.customRewriteLinks ? zipExportOptions?.customRewriteLinks(rewriteLinks, getNoteTargetUrl) : rewriteLinks);
- const provider = buildProvider();
+ const provider = await buildProvider();
+ const log = getLog();
const noteIdToMeta: Record<string, NoteMeta> = {};
@@@ -402,9 -430,9 +410,8 @@@
} else if (attr.value === "root" || attr.value?.startsWith("_")) {
// relations to "named" noteIds can be preserved
return true;
- }
+ }
return false;
-
-
});
}
diff --cc packages/trilium-core/src/services/import/samples/gbk-support.zip
index 0000000000,6dd9ff7b74..6dd9ff7b74
mode 000000,100644..100644
Binary files differ
diff --cc packages/trilium-core/src/services/import/zip.spec.ts
index 208daf0180,4a922ee11d..2a5741dd2c
--- a/packages/trilium-core/src/services/import/zip.spec.ts
+++ b/packages/trilium-core/src/services/import/zip.spec.ts
@@@ -1,7 -1,10 +1,9 @@@
import { beforeAll, describe, expect, it, vi } from "vitest";
+ import archiver from "archiver";
import fs from "fs";
-import path from "path";
import { fileURLToPath } from "url";
import { dirname } from "path";
+ import { PassThrough } from "stream";
import zip, { removeTriliumTags } from "./zip.js";
import becca from "../../becca/becca.js";
import BNote from "../../becca/entities/bnote.js";
@@@ -12,7 -15,11 +14,11 @@@ import { getContext } from "../context.
const scriptDir = dirname(fileURLToPath(import.meta.url));
async function testImport(fileName: string) {
- const mdxSample = fs.readFileSync(`${scriptDir}/samples/${fileName}`);
- const mdxSample = fs.readFileSync(path.join(scriptDir, "samples", fileName));
- return testImportBuffer(mdxSample);
++ const buffer = fs.readFileSync(`${scriptDir}/samples/${fileName}`);
++ return testImportBuffer(buffer);
+ }
+
+ async function testImportBuffer(buffer: Buffer) {
const taskContext = TaskContext.getInstance("import-mdx", "importNotes", {
textImportedAsText: true
});
diff --cc packages/trilium-core/src/services/import/zip.ts
index 837ccf7bc4,42e72aeb80..8bd6a0e3a8
--- a/packages/trilium-core/src/services/import/zip.ts
+++ b/packages/trilium-core/src/services/import/zip.ts
@@@ -17,8 -23,7 +17,9 @@@ import type TaskContext from "../task_c
import treeService from "../tree.js";
import markdownService from "./markdown.js";
import mimeService from "./mime.js";
+import { AttributeMeta, NoteMeta } from "../../meta.js";
+ import { isMarkdownCodeNote } from "../export/rewrite_links.js";
+import { sanitizeHtml } from "../sanitizer.js";
interface MetaFile {
files: NoteMeta[];
@@@ -414,7 -425,63 +420,63 @@@ async function importZip(taskContext: T
return content;
}
+ /**
+ * Rewrites relative file paths in markdown code notes back to Trilium internal
+ * URLs (counterpart to `rewriteMarkdownContentLinks` in the export).
+ */
+ function processMarkdownCodeNoteContent(content: string, filePath: string) {
+ function isUrlAbsolute(url: string) {
+ return /^(?:[a-z]+:)?\/\//i.test(url);
+ }
+
+ // Image links: ![alt](relative/path)
+ content = content.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (match, alt, url) => {
+ try {
+ url = decodeURIComponent(url).trim();
+ } catch {
+ return match;
+ }
+
+ if (isUrlAbsolute(url) || url.startsWith("api/")) {
+ return match;
+ }
+
+ const target = getEntityIdFromRelativeUrl(url, filePath);
+
+ if (target.attachmentId) {
+ return `![${alt}](api/attachments/${target.attachmentId}/image/${encodeURIComponent(target.attachmentTitle || "image")})`;
+ } else if (target.noteId) {
- return `![${alt}](api/images/${target.noteId}/${path.basename(url)})`;
++ return `![${alt}](api/images/${target.noteId}/${basename(url)})`;
+ }
+ return match;
+ });
+
+ // Non-image links: [text](relative/path)
+ content = content.replace(/(?<!!)\[([^\]]*)\]\(([^)]+)\)/g, (match, text, url) => {
+ try {
+ url = decodeURIComponent(url).trim();
+ } catch {
+ return match;
+ }
+
+ if (isUrlAbsolute(url) || url.startsWith("#") || url.startsWith("api/")) {
+ return match;
+ }
+
+ const target = getEntityIdFromRelativeUrl(url, filePath);
+
+ if (target.attachmentId) {
+ return `[${text}](#root/${target.noteId}?viewMode=attachments&attachmentId=${target.attachmentId})`;
+ } else if (target.noteId) {
+ return `[${text}](#root/${target.noteId})`;
+ }
+ return match;
+ });
+
+ return content;
+ }
+
- function saveNote(filePath: string, content: string | Buffer) {
+ function saveNote(filePath: string, content: string | Uint8Array) {
const { parentNoteMeta, noteMeta, attachmentMeta } = getMeta(filePath);
if (noteMeta?.noImport) {
@@@ -556,11 -623,12 +618,15 @@@
}
}
++ const zipProvider = getZipProvider();
++
+ // Detect filename encoding once for the whole ZIP (e.g. GBK for Chinese Windows ZIPs)
- const filenameEncoding = await detectZipFilenameEncoding(fileBuffer);
++ const filenameEncoding = await zipProvider.detectFilenameEncoding(fileBuffer);
+
// we're running two passes in order to obtain critical information first (meta file and root)
const topLevelItems = new Set<string>();
- const zipProvider = getZipProvider();
- await readZipFile(fileBuffer, async (zipfile: yauzl.ZipFile, entry: yauzl.Entry) => {
+
+ await zipProvider.readZipFile(fileBuffer, async (entry, readContent) => {
const filePath = normalizeFilePath(entry.fileName);
// make sure that the meta file is loaded before the rest of the files is processed.
@@@ -573,7 -642,9 +639,7 @@@
const firstSlash = filePath.indexOf("/");
const topLevelPath = (firstSlash !== -1 ? filePath.substring(0, firstSlash) : filePath);
topLevelItems.add(topLevelPath);
- });
-
- zipfile.readEntry();
+ }, filenameEncoding);
topLevelPath = (topLevelItems.size > 1 ? "" : topLevelItems.values().next().value ?? "");
@@@ -587,7 -660,8 +653,7 @@@
}
taskContext.increaseProgressCount();
- });
- zipfile.readEntry();
+ }, filenameEncoding);
for (const noteId of createdNoteIds) {
const note = becca.getNote(noteId);
diff --cc packages/trilium-core/src/services/keyboard_actions.ts
index d9ccc678e9,0000000000..efcdf93c65
mode 100644,000000..100644
--- a/packages/trilium-core/src/services/keyboard_actions.ts
+++ b/packages/trilium-core/src/services/keyboard_actions.ts
@@@ -1,891 -1,0 +1,899 @@@
+"use strict";
+
+import optionService from "./options.js";
+import { getLog } from "./log.js";
+import { isElectron, isMac } from "./utils/index.js";
+import type { ActionKeyboardShortcut, KeyboardShortcut } from "@triliumnext/commons";
+import { t } from "i18next";
+
+function getDefaultKeyboardActions() {
+ if (!t("keyboard_actions.note-navigation")) {
+ throw new Error("Keyboard actions loaded before translations.");
+ }
+
+ const DEFAULT_KEYBOARD_ACTIONS: KeyboardShortcut[] = [
+ {
+ separator: t("keyboard_actions.note-navigation")
+ },
+ {
+ actionName: "backInNoteHistory",
+ friendlyName: t("keyboard_action_names.back-in-note-history"),
+ iconClass: "bx bxs-chevron-left",
+ // Mac has a different history navigation shortcuts - https://github.com/zadam/trilium/issues/376
+ defaultShortcuts: isMac() ? ["CommandOrControl+["] : ["Alt+Left"],
+ description: t("keyboard_actions.back-in-note-history"),
+ scope: "window"
+ },
+ {
+ actionName: "forwardInNoteHistory",
+ friendlyName: t("keyboard_action_names.forward-in-note-history"),
+ iconClass: "bx bxs-chevron-right",
+ // Mac has a different history navigation shortcuts - https://github.com/zadam/trilium/issues/376
+ defaultShortcuts: isMac() ? ["CommandOrControl+]"] : ["Alt+Right"],
+ description: t("keyboard_actions.forward-in-note-history"),
+ scope: "window"
+ },
+ {
+ actionName: "jumpToNote",
+ friendlyName: t("keyboard_action_names.jump-to-note"),
+ defaultShortcuts: ["CommandOrControl+J"],
+ description: t("keyboard_actions.open-jump-to-note-dialog"),
+ scope: "window",
+ ignoreFromCommandPalette: true
+ },
+ {
+ actionName: "openTodayNote",
+ friendlyName: t("hidden-subtree.open-today-journal-note-title"),
+ iconClass: "bx bx-calendar",
+ defaultShortcuts: [],
+ description: t("hidden-subtree.open-today-journal-note-title"),
+ scope: "window"
+ },
+ {
+ actionName: "commandPalette",
+ friendlyName: t("keyboard_action_names.command-palette"),
+ defaultShortcuts: ["CommandOrControl+Shift+J"],
+ description: t("keyboard_actions.open-command-palette"),
+ scope: "window",
+ ignoreFromCommandPalette: true
+ },
+ {
+ actionName: "scrollToActiveNote",
+ friendlyName: t("keyboard_action_names.scroll-to-active-note"),
+ defaultShortcuts: ["CommandOrControl+."],
+ iconClass: "bx bx-current-location",
+ description: t("keyboard_actions.scroll-to-active-note"),
+ scope: "window"
+ },
+ {
+ actionName: "quickSearch",
+ friendlyName: t("keyboard_action_names.quick-search"),
+ iconClass: "bx bx-search",
+ defaultShortcuts: ["CommandOrControl+S"],
+ description: t("keyboard_actions.quick-search"),
+ scope: "window"
+ },
+ {
+ actionName: "searchInSubtree",
+ friendlyName: t("keyboard_action_names.search-in-subtree"),
+ defaultShortcuts: ["CommandOrControl+Shift+S"],
+ iconClass: "bx bx-search-alt",
+ description: t("keyboard_actions.search-in-subtree"),
+ scope: "note-tree"
+ },
+ {
+ actionName: "expandSubtree",
+ friendlyName: t("keyboard_action_names.expand-subtree"),
+ defaultShortcuts: [],
+ iconClass: "bx bx-layer-plus",
+ description: t("keyboard_actions.expand-subtree"),
+ scope: "note-tree"
+ },
+ {
+ actionName: "collapseTree",
+ friendlyName: t("keyboard_action_names.collapse-tree"),
+ defaultShortcuts: ["Alt+C"],
+ iconClass: "bx bx-layer-minus",
+ description: t("keyboard_actions.collapse-tree"),
+ scope: "window"
+ },
+ {
+ actionName: "collapseSubtree",
+ friendlyName: t("keyboard_action_names.collapse-subtree"),
+ iconClass: "bx bxs-layer-minus",
+ defaultShortcuts: ["Alt+-"],
+ description: t("keyboard_actions.collapse-subtree"),
+ scope: "note-tree"
+ },
+ {
+ actionName: "sortChildNotes",
+ friendlyName: t("keyboard_action_names.sort-child-notes"),
+ iconClass: "bx bx-sort-down",
+ defaultShortcuts: ["Alt+S"],
+ description: t("keyboard_actions.sort-child-notes"),
+ scope: "note-tree"
+ },
++ {
++ actionName: "toggleArchivedNotes",
++ friendlyName: t("keyboard_action_names.toggle-archived-notes"),
++ iconClass: "bx bx-low-vision",
++ defaultShortcuts: (!isMac()) ? ["Ctrl+H"] : ["CommandOrControl+Shift+H"],
++ description: t("keyboard_actions.toggle-archived-notes"),
++ scope: "window"
++ },
+
+ {
+ separator: t("keyboard_actions.creating-and-moving-notes")
+ },
+ {
+ actionName: "createNoteAfter",
+ friendlyName: t("keyboard_action_names.create-note-after"),
+ iconClass: "bx bx-plus",
+ defaultShortcuts: ["CommandOrControl+O"],
+ description: t("keyboard_actions.create-note-after"),
+ scope: "window"
+ },
+ {
+ actionName: "createNoteInto",
+ friendlyName: t("keyboard_action_names.create-note-into"),
+ iconClass: "bx bx-plus",
+ defaultShortcuts: ["CommandOrControl+P"],
+ description: t("keyboard_actions.create-note-into"),
+ scope: "window"
+ },
+ {
+ actionName: "createNoteIntoInbox",
+ friendlyName: t("keyboard_action_names.create-note-into-inbox"),
+ iconClass: "bx bxs-inbox",
+ defaultShortcuts: ["global:CommandOrControl+Alt+P"],
+ description: t("keyboard_actions.create-note-into-inbox"),
+ scope: "window"
+ },
+ {
+ actionName: "deleteNotes",
+ friendlyName: t("keyboard_action_names.delete-notes"),
+ iconClass: "bx bx-trash",
+ defaultShortcuts: ["Delete"],
+ description: t("keyboard_actions.delete-note"),
+ scope: "note-tree"
+ },
+ {
+ actionName: "moveNoteUp",
+ friendlyName: t("keyboard_action_names.move-note-up"),
+ iconClass: "bx bx-up-arrow-alt",
+ defaultShortcuts: isMac() ? ["Alt+Up"] : ["CommandOrControl+Up"],
+ description: t("keyboard_actions.move-note-up"),
+ scope: "note-tree"
+ },
+ {
+ actionName: "moveNoteDown",
+ friendlyName: t("keyboard_action_names.move-note-down"),
+ iconClass: "bx bx-down-arrow-alt",
+ defaultShortcuts: isMac() ? ["Alt+Down"] : ["CommandOrControl+Down"],
+ description: t("keyboard_actions.move-note-down"),
+ scope: "note-tree"
+ },
+ {
+ actionName: "moveNoteUpInHierarchy",
+ friendlyName: t("keyboard_action_names.move-note-up-in-hierarchy"),
+ iconClass: "bx bx-arrow-from-bottom",
+ defaultShortcuts: isMac() ? ["Alt+Left"] : ["CommandOrControl+Left"],
+ description: t("keyboard_actions.move-note-up-in-hierarchy"),
+ scope: "note-tree"
+ },
+ {
+ actionName: "moveNoteDownInHierarchy",
+ friendlyName: t("keyboard_action_names.move-note-down-in-hierarchy"),
+ iconClass: "bx bx-arrow-from-top",
+ defaultShortcuts: isMac() ? ["Alt+Right"] : ["CommandOrControl+Right"],
+ description: t("keyboard_actions.move-note-down-in-hierarchy"),
+ scope: "note-tree"
+ },
+ {
+ actionName: "editNoteTitle",
+ friendlyName: t("keyboard_action_names.edit-note-title"),
+ iconClass: "bx bx-rename",
+ defaultShortcuts: ["Enter"],
+ description: t("keyboard_actions.edit-note-title"),
+ scope: "note-tree"
+ },
+ {
+ actionName: "editBranchPrefix",
+ friendlyName: t("keyboard_action_names.edit-branch-prefix"),
+ iconClass: "bx bx-rename",
+ defaultShortcuts: ["F2"],
+ description: t("keyboard_actions.edit-branch-prefix"),
+ scope: "note-tree"
+ },
+ {
+ actionName: "cloneNotesTo",
+ friendlyName: t("keyboard_action_names.clone-notes-to"),
+ iconClass: "bx bx-duplicate",
+ defaultShortcuts: ["CommandOrControl+Shift+C"],
+ description: t("keyboard_actions.clone-notes-to"),
+ scope: "window"
+ },
+ {
+ actionName: "moveNotesTo",
+ friendlyName: t("keyboard_action_names.move-notes-to"),
+ iconClass: "bx bx-transfer",
+ defaultShortcuts: ["CommandOrControl+Shift+X"],
+ description: t("keyboard_actions.move-notes-to"),
+ scope: "window"
+ },
+
+ {
+ separator: t("keyboard_actions.note-clipboard")
+ },
+
+ {
+ actionName: "copyNotesToClipboard",
+ friendlyName: t("keyboard_action_names.copy-notes-to-clipboard"),
+ iconClass: "bx bx-copy",
+ defaultShortcuts: ["CommandOrControl+C"],
+ description: t("keyboard_actions.copy-notes-to-clipboard"),
+ scope: "note-tree"
+ },
+ {
+ actionName: "pasteNotesFromClipboard",
+ friendlyName: t("keyboard_action_names.paste-notes-from-clipboard"),
+ iconClass: "bx bx-paste",
+ defaultShortcuts: ["CommandOrControl+V"],
+ description: t("keyboard_actions.paste-notes-from-clipboard"),
+ scope: "note-tree"
+ },
+ {
+ actionName: "cutNotesToClipboard",
+ friendlyName: t("keyboard_action_names.cut-notes-to-clipboard"),
+ iconClass: "bx bx-cut",
+ defaultShortcuts: ["CommandOrControl+X"],
+ description: t("keyboard_actions.cut-notes-to-clipboard"),
+ scope: "note-tree"
+ },
+ {
+ actionName: "selectAllNotesInParent",
+ friendlyName: t("keyboard_action_names.select-all-notes-in-parent"),
+ iconClass: "bx bx-select-multiple",
+ defaultShortcuts: ["CommandOrControl+A"],
+ description: t("keyboard_actions.select-all-notes-in-parent"),
+ scope: "note-tree"
+ },
+ {
+ actionName: "addNoteAboveToSelection",
+ friendlyName: t("keyboard_action_names.add-note-above-to-selection"),
+ defaultShortcuts: ["Shift+Up"],
+ description: t("keyboard_actions.add-note-above-to-the-selection"),
+ scope: "note-tree",
+ ignoreFromCommandPalette: true
+ },
+ {
+ actionName: "addNoteBelowToSelection",
+ friendlyName: t("keyboard_action_names.add-note-below-to-selection"),
+ defaultShortcuts: ["Shift+Down"],
+ description: t("keyboard_actions.add-note-below-to-selection"),
+ scope: "note-tree",
+ ignoreFromCommandPalette: true
+ },
+ {
+ actionName: "duplicateSubtree",
+ friendlyName: t("keyboard_action_names.duplicate-subtree"),
+ iconClass: "bx bx-outline",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.duplicate-subtree"),
+ scope: "note-tree"
+ },
+
+ {
+ separator: t("keyboard_actions.tabs-and-windows")
+ },
+ {
+ actionName: "openNewTab",
+ friendlyName: t("keyboard_action_names.open-new-tab"),
+ iconClass: "bx bx-plus",
+ defaultShortcuts: isElectron() ? ["CommandOrControl+T"] : [],
+ description: t("keyboard_actions.open-new-tab"),
+ scope: "window"
+ },
+ {
+ actionName: "closeActiveTab",
+ friendlyName: t("keyboard_action_names.close-active-tab"),
+ iconClass: "bx bx-minus",
+ defaultShortcuts: isElectron() ? ["CommandOrControl+W"] : [],
+ description: t("keyboard_actions.close-active-tab"),
+ scope: "window"
+ },
+ {
+ actionName: "reopenLastTab",
+ friendlyName: t("keyboard_action_names.reopen-last-tab"),
+ iconClass: "bx bx-undo",
+ defaultShortcuts: isElectron() ? ["CommandOrControl+Shift+T"] : [],
+ isElectronOnly: true,
+ description: t("keyboard_actions.reopen-last-tab"),
+ scope: "window"
+ },
+ {
+ actionName: "activateNextTab",
+ friendlyName: t("keyboard_action_names.activate-next-tab"),
+ iconClass: "bx bx-skip-next",
+ defaultShortcuts: isElectron() ? ["CommandOrControl+Tab", "CommandOrControl+PageDown"] : [],
+ description: t("keyboard_actions.activate-next-tab"),
+ scope: "window"
+ },
+ {
+ actionName: "activatePreviousTab",
+ friendlyName: t("keyboard_action_names.activate-previous-tab"),
+ iconClass: "bx bx-skip-previous",
+ defaultShortcuts: isElectron() ? ["CommandOrControl+Shift+Tab", "CommandOrControl+PageUp"] : [],
+ description: t("keyboard_actions.activate-previous-tab"),
+ scope: "window"
+ },
+ {
+ actionName: "openNewWindow",
+ friendlyName: t("keyboard_action_names.open-new-window"),
+ iconClass: "bx bx-window-open",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.open-new-window"),
+ scope: "window"
+ },
+ {
+ actionName: "toggleTray",
+ friendlyName: t("keyboard_action_names.toggle-system-tray-icon"),
+ iconClass: "bx bx-show",
+ defaultShortcuts: [],
+ isElectronOnly: true,
+ description: t("keyboard_actions.toggle-tray"),
+ scope: "window"
+ },
+ {
+ actionName: "toggleZenMode",
+ friendlyName: t("keyboard_action_names.toggle-zen-mode"),
+ iconClass: "bx bxs-yin-yang",
+ defaultShortcuts: ["F9"],
+ description: t("keyboard_actions.toggle-zen-mode"),
+ scope: "window"
+ },
+ {
+ actionName: "firstTab",
+ friendlyName: t("keyboard_action_names.switch-to-first-tab"),
+ iconClass: "bx bx-rectangle",
+ defaultShortcuts: ["CommandOrControl+1"],
+ description: t("keyboard_actions.first-tab"),
+ scope: "window"
+ },
+ {
+ actionName: "secondTab",
+ friendlyName: t("keyboard_action_names.switch-to-second-tab"),
+ iconClass: "bx bx-rectangle",
+ defaultShortcuts: ["CommandOrControl+2"],
+ description: t("keyboard_actions.second-tab"),
+ scope: "window"
+ },
+ {
+ actionName: "thirdTab",
+ friendlyName: t("keyboard_action_names.switch-to-third-tab"),
+ iconClass: "bx bx-rectangle",
+ defaultShortcuts: ["CommandOrControl+3"],
+ description: t("keyboard_actions.third-tab"),
+ scope: "window"
+ },
+ {
+ actionName: "fourthTab",
+ friendlyName: t("keyboard_action_names.switch-to-fourth-tab"),
+ iconClass: "bx bx-rectangle",
+ defaultShortcuts: ["CommandOrControl+4"],
+ description: t("keyboard_actions.fourth-tab"),
+ scope: "window"
+ },
+ {
+ actionName: "fifthTab",
+ friendlyName: t("keyboard_action_names.switch-to-fifth-tab"),
+ iconClass: "bx bx-rectangle",
+ defaultShortcuts: ["CommandOrControl+5"],
+ description: t("keyboard_actions.fifth-tab"),
+ scope: "window"
+ },
+ {
+ actionName: "sixthTab",
+ friendlyName: t("keyboard_action_names.switch-to-sixth-tab"),
+ iconClass: "bx bx-rectangle",
+ defaultShortcuts: ["CommandOrControl+6"],
+ description: t("keyboard_actions.sixth-tab"),
+ scope: "window"
+ },
+ {
+ actionName: "seventhTab",
+ friendlyName: t("keyboard_action_names.switch-to-seventh-tab"),
+ iconClass: "bx bx-rectangle",
+ defaultShortcuts: ["CommandOrControl+7"],
+ description: t("keyboard_actions.seventh-tab"),
+ scope: "window"
+ },
+ {
+ actionName: "eigthTab",
+ friendlyName: t("keyboard_action_names.switch-to-eighth-tab"),
+ iconClass: "bx bx-rectangle",
+ defaultShortcuts: ["CommandOrControl+8"],
+ description: t("keyboard_actions.eight-tab"),
+ scope: "window"
+ },
+ {
+ actionName: "ninthTab",
+ friendlyName: t("keyboard_action_names.switch-to-ninth-tab"),
+ iconClass: "bx bx-rectangle",
+ defaultShortcuts: ["CommandOrControl+9"],
+ description: t("keyboard_actions.ninth-tab"),
+ scope: "window"
+ },
+ {
+ actionName: "lastTab",
+ friendlyName: t("keyboard_action_names.switch-to-last-tab"),
+ iconClass: "bx bx-rectangle",
+ defaultShortcuts: ["CommandOrControl+0"],
+ description: t("keyboard_actions.last-tab"),
+ scope: "window"
+ },
+
+ {
+ separator: t("keyboard_actions.dialogs")
+ },
+ {
+ friendlyName: t("keyboard_action_names.show-note-source"),
+ actionName: "showNoteSource",
+ iconClass: "bx bx-code",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.show-note-source"),
+ scope: "window"
+ },
+ {
+ friendlyName: t("keyboard_action_names.show-options"),
+ actionName: "showOptions",
+ iconClass: "bx bx-cog",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.show-options"),
+ scope: "window"
+ },
+ {
+ friendlyName: t("keyboard_action_names.show-revisions"),
+ actionName: "showRevisions",
+ iconClass: "bx bx-history",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.show-revisions"),
+ scope: "window"
+ },
+ {
+ friendlyName: t("keyboard_action_names.show-recent-changes"),
+ actionName: "showRecentChanges",
+ iconClass: "bx bx-history",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.show-recent-changes"),
+ scope: "window"
+ },
+ {
+ friendlyName: t("keyboard_action_names.show-sql-console"),
+ actionName: "showSQLConsole",
+ iconClass: "bx bx-data",
+ defaultShortcuts: ["Alt+O"],
+ description: t("keyboard_actions.show-sql-console"),
+ scope: "window"
+ },
+ {
+ friendlyName: t("keyboard_action_names.show-backend-log"),
+ actionName: "showBackendLog",
+ iconClass: "bx bx-detail",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.show-backend-log"),
+ scope: "window"
+ },
+ {
+ friendlyName: t("keyboard_action_names.show-help"),
+ actionName: "showHelp",
+ iconClass: "bx bx-help-circle",
+ defaultShortcuts: ["F1"],
+ description: t("keyboard_actions.show-help"),
+ scope: "window"
+ },
+ {
+ friendlyName: t("keyboard_action_names.show-cheatsheet"),
+ actionName: "showCheatsheet",
+ iconClass: "bx bxs-keyboard",
+ defaultShortcuts: ["Shift+F1"],
+ description: t("keyboard_actions.show-cheatsheet"),
+ scope: "window"
+ },
+
+ {
+ separator: t("keyboard_actions.text-note-operations")
+ },
+
+ {
+ friendlyName: t("keyboard_action_names.add-link-to-text"),
+ actionName: "addLinkToText",
+ iconClass: "bx bx-link",
+ defaultShortcuts: ["CommandOrControl+L"],
+ description: t("keyboard_actions.add-link-to-text"),
+ scope: "text-detail"
+ },
+ {
+ friendlyName: t("keyboard_action_names.follow-link-under-cursor"),
+ actionName: "followLinkUnderCursor",
+ iconClass: "bx bx-link-external",
+ defaultShortcuts: ["CommandOrControl+Enter"],
+ description: t("keyboard_actions.follow-link-under-cursor"),
+ scope: "text-detail"
+ },
+ {
+ friendlyName: t("keyboard_action_names.insert-date-and-time-to-text"),
+ actionName: "insertDateTimeToText",
+ iconClass: "bx bx-calendar-event",
+ defaultShortcuts: ["Alt+T"],
+ description: t("keyboard_actions.insert-date-and-time-to-text"),
+ scope: "text-detail"
+ },
+ {
+ friendlyName: t("keyboard_action_names.paste-markdown-into-text"),
+ actionName: "pasteMarkdownIntoText",
+ iconClass: "bx bxl-markdown",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.paste-markdown-into-text"),
+ scope: "text-detail"
+ },
+ {
+ friendlyName: t("keyboard_action_names.cut-into-note"),
+ actionName: "cutIntoNote",
+ iconClass: "bx bx-cut",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.cut-into-note"),
+ scope: "text-detail"
+ },
+ {
+ friendlyName: t("keyboard_action_names.add-include-note-to-text"),
+ actionName: "addIncludeNoteToText",
+ iconClass: "bx bx-note",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.add-include-note-to-text"),
+ scope: "text-detail"
+ },
+ {
+ friendlyName: t("keyboard_action_names.edit-read-only-note"),
+ actionName: "editReadOnlyNote",
+ iconClass: "bx bx-edit-alt",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.edit-readonly-note"),
+ scope: "window"
+ },
+
+ {
+ separator: t("keyboard_actions.attributes-labels-and-relations")
+ },
+
+ {
+ friendlyName: t("keyboard_action_names.add-new-label"),
+ actionName: "addNewLabel",
+ iconClass: "bx bx-hash",
+ defaultShortcuts: ["Alt+L"],
+ description: t("keyboard_actions.add-new-label"),
+ scope: "window"
+ },
+ {
+ friendlyName: t("keyboard_action_names.add-new-relation"),
+ actionName: "addNewRelation",
+ iconClass: "bx bx-transfer",
+ defaultShortcuts: ["Alt+R"],
+ description: t("keyboard_actions.create-new-relation"),
+ scope: "window"
+ },
+
+ {
+ separator: t("keyboard_actions.ribbon-tabs")
+ },
+
+ {
+ friendlyName: t("keyboard_action_names.toggle-ribbon-tab-classic-editor"),
+ actionName: "toggleRibbonTabClassicEditor",
+ iconClass: "bx bx-text",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.toggle-classic-editor-toolbar"),
+ scope: "window"
+ },
+ {
+ actionName: "toggleRibbonTabBasicProperties",
+ friendlyName: t("keyboard_action_names.toggle-ribbon-tab-basic-properties"),
+ iconClass: "bx bx-slider",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.toggle-basic-properties"),
+ scope: "window"
+ },
+ {
+ actionName: "toggleRibbonTabBookProperties",
+ friendlyName: t("keyboard_action_names.toggle-ribbon-tab-book-properties"),
+ iconClass: "bx bx-book",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.toggle-book-properties"),
+ scope: "window"
+ },
+ {
+ actionName: "toggleRibbonTabFileProperties",
+ friendlyName: t("keyboard_action_names.toggle-ribbon-tab-file-properties"),
+ iconClass: "bx bx-file",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.toggle-file-properties"),
+ scope: "window"
+ },
+ {
+ actionName: "toggleRibbonTabImageProperties",
+ friendlyName: t("keyboard_action_names.toggle-ribbon-tab-image-properties"),
+ iconClass: "bx bx-image",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.toggle-image-properties"),
+ scope: "window"
+ },
+ {
+ actionName: "toggleRibbonTabOwnedAttributes",
+ friendlyName: t("keyboard_action_names.toggle-ribbon-tab-owned-attributes"),
+ iconClass: "bx bx-list-check",
+ defaultShortcuts: ["Alt+A"],
+ description: t("keyboard_actions.toggle-owned-attributes"),
+ scope: "window"
+ },
+ {
+ actionName: "toggleRibbonTabInheritedAttributes",
+ friendlyName: t("keyboard_action_names.toggle-ribbon-tab-inherited-attributes"),
+ iconClass: "bx bx-list-plus",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.toggle-inherited-attributes"),
+ scope: "window"
+ },
+ // TODO: Remove or change since promoted attributes have been changed.
+ {
+ actionName: "toggleRibbonTabPromotedAttributes",
+ friendlyName: t("keyboard_action_names.toggle-ribbon-tab-promoted-attributes"),
+ iconClass: "bx bx-star",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.toggle-promoted-attributes"),
+ scope: "window"
+ },
+ {
+ actionName: "toggleRibbonTabNoteMap",
+ friendlyName: t("keyboard_action_names.toggle-ribbon-tab-note-map"),
+ iconClass: "bx bxs-network-chart",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.toggle-link-map"),
+ scope: "window"
+ },
+ {
+ actionName: "toggleRibbonTabNoteInfo",
+ friendlyName: t("keyboard_action_names.toggle-ribbon-tab-note-info"),
+ iconClass: "bx bx-info-circle",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.toggle-note-info"),
+ scope: "window"
+ },
+ {
+ actionName: "toggleRibbonTabNotePaths",
+ friendlyName: t("keyboard_action_names.toggle-ribbon-tab-note-paths"),
+ iconClass: "bx bx-collection",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.toggle-note-paths"),
+ scope: "window"
+ },
+ {
+ actionName: "toggleRibbonTabSimilarNotes",
+ friendlyName: t("keyboard_action_names.toggle-ribbon-tab-similar-notes"),
+ iconClass: "bx bx-bar-chart",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.toggle-similar-notes"),
+ scope: "window"
+ },
+
+ {
+ separator: t("keyboard_actions.other")
+ },
+
+ {
+ actionName: "toggleRightPane",
+ friendlyName: t("keyboard_action_names.toggle-right-pane"),
+ iconClass: "bx bx-dock-right",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.toggle-right-pane"),
+ scope: "window"
+ },
+ {
+ actionName: "printActiveNote",
+ friendlyName: t("keyboard_action_names.print-active-note"),
+ iconClass: "bx bx-printer",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.print-active-note"),
+ scope: "window"
+ },
+ {
+ actionName: "exportAsPdf",
+ friendlyName: t("keyboard_action_names.export-active-note-as-pdf"),
+ iconClass: "bx bxs-file-pdf",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.export-as-pdf"),
+ scope: "window"
+ },
+ {
+ actionName: "openNoteExternally",
+ friendlyName: t("keyboard_action_names.open-note-externally"),
+ iconClass: "bx bx-file-find",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.open-note-externally"),
+ scope: "window"
+ },
+ {
+ actionName: "renderActiveNote",
+ friendlyName: t("keyboard_action_names.render-active-note"),
+ iconClass: "bx bx-refresh",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.render-active-note"),
+ scope: "window"
+ },
+ {
+ actionName: "runActiveNote",
+ friendlyName: t("keyboard_action_names.run-active-note"),
+ iconClass: "bx bx-play",
+ defaultShortcuts: ["CommandOrControl+Enter"],
+ description: t("keyboard_actions.run-active-note"),
+ scope: "code-detail"
+ },
+ {
+ actionName: "toggleNoteHoisting",
+ friendlyName: t("keyboard_action_names.toggle-note-hoisting"),
+ iconClass: "bx bx-chevrons-up",
+ defaultShortcuts: ["Alt+H"],
+ description: t("keyboard_actions.toggle-note-hoisting"),
+ scope: "window"
+ },
+ {
+ actionName: "unhoist",
+ friendlyName: t("keyboard_action_names.unhoist-note"),
+ iconClass: "bx bx-door-open",
+ defaultShortcuts: ["Alt+U"],
+ description: t("keyboard_actions.unhoist"),
+ scope: "window"
+ },
+ {
+ actionName: "reloadFrontendApp",
+ friendlyName: t("keyboard_action_names.reload-frontend-app"),
+ iconClass: "bx bx-refresh",
+ defaultShortcuts: ["F5", "CommandOrControl+R"],
+ description: t("keyboard_actions.reload-frontend-app"),
+ scope: "window"
+ },
+ {
+ actionName: "openDevTools",
+ friendlyName: t("keyboard_action_names.open-developer-tools"),
+ iconClass: "bx bx-bug-alt",
+ defaultShortcuts: isElectron() ? ["CommandOrControl+Shift+I"] : [],
+ isElectronOnly: true,
+ description: t("keyboard_actions.open-dev-tools"),
+ scope: "window"
+ },
+ {
+ actionName: "findInText",
+ friendlyName: t("keyboard_action_names.find-in-text"),
+ iconClass: "bx bx-search",
+ defaultShortcuts: isElectron() ? ["CommandOrControl+F"] : [],
+ description: t("keyboard_actions.find-in-text"),
+ scope: "window"
+ },
+ {
+ actionName: "toggleLeftPane",
+ friendlyName: t("keyboard_action_names.toggle-left-pane"),
+ iconClass: "bx bx-sidebar",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.toggle-left-note-tree-panel"),
+ scope: "window"
+ },
+ {
+ actionName: "toggleFullscreen",
+ friendlyName: t("keyboard_action_names.toggle-full-screen"),
+ iconClass: "bx bx-fullscreen",
+ defaultShortcuts: ["F11"],
+ description: t("keyboard_actions.toggle-full-screen"),
+ scope: "window"
+ },
+ {
+ actionName: "zoomOut",
+ friendlyName: t("keyboard_action_names.zoom-out"),
+ iconClass: "bx bx-zoom-out",
+ defaultShortcuts: isElectron() ? ["CommandOrControl+-"] : [],
+ isElectronOnly: true,
+ description: t("keyboard_actions.zoom-out"),
+ scope: "window"
+ },
+ {
+ actionName: "zoomIn",
+ friendlyName: t("keyboard_action_names.zoom-in"),
+ iconClass: "bx bx-zoom-in",
+ description: t("keyboard_actions.zoom-in"),
+ defaultShortcuts: isElectron() ? ["CommandOrControl+="] : [],
+ isElectronOnly: true,
+ scope: "window"
+ },
+ {
+ actionName: "zoomReset",
+ friendlyName: t("keyboard_action_names.reset-zoom-level"),
+ iconClass: "bx bx-search-alt",
+ description: t("keyboard_actions.reset-zoom-level"),
+ defaultShortcuts: isElectron() ? ["CommandOrControl+0"] : [],
+ isElectronOnly: true,
+ scope: "window"
+ },
+ {
+ actionName: "copyWithoutFormatting",
+ friendlyName: t("keyboard_action_names.copy-without-formatting"),
+ iconClass: "bx bx-copy-alt",
+ defaultShortcuts: ["CommandOrControl+Alt+C"],
+ description: t("keyboard_actions.copy-without-formatting"),
+ scope: "text-detail"
+ },
+ {
+ actionName: "forceSaveRevision",
+ friendlyName: t("keyboard_action_names.force-save-revision"),
+ iconClass: "bx bx-save",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.force-save-revision"),
+ scope: "window"
+ },
+ {
+ actionName: "saveNamedRevision",
+ friendlyName: t("keyboard_action_names.save-named-revision"),
+ iconClass: "bx bx-purchase-tag",
+ defaultShortcuts: [],
+ description: t("keyboard_actions.save-named-revision"),
+ scope: "window"
+ }
+ ];
+
+ /*
+ * Apply macOS-specific tweaks.
+ */
+ const platformModifier = isMac() ? "Meta" : "Ctrl";
+
+ for (const action of DEFAULT_KEYBOARD_ACTIONS) {
+ if ("defaultShortcuts" in action && action.defaultShortcuts) {
+ action.defaultShortcuts = action.defaultShortcuts.map((shortcut) => shortcut.replace("CommandOrControl", platformModifier));
+ }
+ }
+
+ return DEFAULT_KEYBOARD_ACTIONS;
+}
+
+function getKeyboardActions() {
+ const actions: KeyboardShortcut[] = JSON.parse(JSON.stringify(getDefaultKeyboardActions()));
+
+ for (const action of actions) {
+ if ("effectiveShortcuts" in action && action.effectiveShortcuts) {
+ action.effectiveShortcuts = action.defaultShortcuts ? action.defaultShortcuts.slice() : [];
+ }
+ }
+
+ const log = getLog();
+ for (const option of optionService.getOptions()) {
+ if (option.name.startsWith("keyboardShortcuts")) {
+ let actionName = option.name.substring(17);
+ actionName = actionName.charAt(0).toLowerCase() + actionName.slice(1);
+
+ const action = actions.find((ea) => "actionName" in ea && ea.actionName === actionName) as ActionKeyboardShortcut;
+
+ if (action) {
+ try {
+ action.effectiveShortcuts = JSON.parse(option.value);
+ } catch (e) {
+ log.error(`Could not parse shortcuts for action ${actionName}`);
+ }
+ } else {
+ log.info(`Keyboard action ${actionName} found in database, but not in action definition.`);
+ }
+ }
+ }
+
+ return actions;
+}
+
+export default {
+ getDefaultKeyboardActions,
+ getKeyboardActions
+};
diff --cc packages/trilium-core/src/services/notes.ts
index 5a34282615,0000000000..9816153375
mode 100644,000000..100644
--- a/packages/trilium-core/src/services/notes.ts
+++ b/packages/trilium-core/src/services/notes.ts
@@@ -1,1205 -1,0 +1,1247 @@@
+import { type AttachmentRow, type AttributeRow, type BranchRow, dayjs, type NoteRow, type NoteType } from "@triliumnext/commons";
+import fs from "fs";
+import html2plaintext from "html2plaintext";
+import { t } from "i18next";
+import url from "url";
+
+import becca from "../becca/becca.js";
+import BAttachment from "../becca/entities/battachment.js";
+import BAttribute from "../becca/entities/battribute.js";
+import BBranch from "../becca/entities/bbranch.js";
+import BNote from "../becca/entities/bnote.js";
+import { ValidationError } from "../errors.js";
+import { getLog } from "../services/log.js";
+import protectedSessionService from "../services/protected_session.js";
+import * as cls from "./context.js";
+import entityChangesService from "./entity_changes.js";
+import eventService from "./events.js";
+import imageService from "./image.js";
+import noteTypesService from "./note_types.js";
+import optionService from "./options.js";
+import request from "./request.js";
+import revisionService from "./revisions.js";
+import { sanitizeHtml } from "./sanitizer.js";
+import { getSql } from "./sql/index.js";
+import type TaskContext from "./task_context.js";
+import { decodeBase64 } from "./utils/binary.js";
+import date_utils from "./utils/date.js";
+import { newEntityId, quoteRegex, toMap, unescapeHtml } from "./utils/index.js";
+import { basename } from "./utils/path.js";
+import ws from "./ws.js";
+
+interface FoundLink {
+ name: "imageLink" | "internalLink" | "includeNoteLink" | "relationMapLink";
+ value: string;
+}
+
+interface Attachment {
+ attachmentId?: string;
+ title: string;
+}
+
+export interface NoteParams {
+ /** optionally can force specific noteId */
+ noteId?: string;
+ branchId?: string;
+ parentNoteId: string;
+ templateNoteId?: string;
+ title: string;
+ content: string | Uint8Array;
+ /** text, code, file, image, search, book, relationMap, canvas, webView */
+ type: NoteType;
+ /** default value is derived from default mimes for type */
+ mime?: string;
+ /** default is false */
+ isProtected?: boolean;
+ /** default is false */
+ isExpanded?: boolean;
+ /** default is empty string */
+ prefix?: string;
+ /** default is the last existing notePosition in a parent + 10 */
+ notePosition?: number;
+ dateCreated?: string;
+ utcDateCreated?: string;
+ ignoreForbiddenParents?: boolean;
+ target?: "into";
+ /** Attributes to be set on the note. These are set atomically on note creation, so entity changes are not sent for attributes defined here. */
+ attributes?: Omit<AttributeRow, "noteId" | "attributeId">[];
+}
+
+function getNewNotePosition(parentNote: BNote) {
+ if (parentNote.isLabelTruthy("newNotesOnTop")) {
+ const minNotePos = parentNote
+ .getChildBranches()
+ .filter((branch) => branch?.noteId !== "_hidden") // has "always last" note position
+ .reduce((min, note) => Math.min(min, note?.notePosition || 0), 0);
+
+ return minNotePos - 10;
+ }
+ const maxNotePos = parentNote
+ .getChildBranches()
+ .filter((branch) => branch?.noteId !== "_hidden") // has "always last" note position
+ .reduce((max, note) => Math.max(max, note?.notePosition || 0), 0);
+
+ return maxNotePos + 10;
+}
+
+function triggerNoteTitleChanged(note: BNote) {
+ eventService.emit(eventService.NOTE_TITLE_CHANGED, note);
+}
+
+function deriveMime(type: string, mime?: string) {
+ if (!type) {
+ throw new Error(`Note type is a required param`);
+ }
+
+ if (mime) {
+ return mime;
+ }
+
+ return noteTypesService.getDefaultMimeForNoteType(type);
+}
+
+function copyChildAttributes(parentNote: BNote, childNote: BNote) {
+ for (const attr of parentNote.getAttributes()) {
+ if (attr.name.startsWith("child:")) {
+ const name = attr.name.substring(6);
+ const hasAlreadyTemplate = childNote.hasRelation("template");
+
+ if (hasAlreadyTemplate && attr.type === "relation" && name === "template") {
+ // if the note already has a template, it means the template was chosen by the user explicitly
+ // in the menu. In that case, we should override the default templates defined in the child: attrs
+ continue;
+ }
+
+ new BAttribute({
+ noteId: childNote.noteId,
+ type: attr.type,
+ name,
+ value: attr.value,
+ position: attr.position,
+ isInheritable: attr.isInheritable
+ }).save();
+ }
+ }
+}
+
+function copyAttachments(origNote: BNote, newNote: BNote) {
+ for (const attachment of origNote.getAttachments()) {
+ if (attachment.role === "image") {
+ // Handled separately, see `checkImageAttachments`.
+ continue;
+ }
+
+ const newAttachment = new BAttachment({
+ ...attachment,
+ attachmentId: undefined,
+ ownerId: newNote.noteId
+ });
+
+ newAttachment.save();
+ }
+}
+
+function getNewNoteTitle(parentNote: BNote) {
+ let title = t("notes.new-note");
+
+ const titleTemplate = parentNote.getLabelValue("titleTemplate");
+
+ if (titleTemplate !== null) {
+ try {
+ const now = dayjs(date_utils.localNowDateTime() || new Date());
+
+ // "officially" injected values:
+ // - now
+ // - parentNote
+
+ title = eval(`\`${titleTemplate}\``);
+ } catch (e: any) {
+ getLog().error(`Title template of note '${parentNote.noteId}' failed with: ${e.message}`);
+ }
+ }
+
+ // this isn't in theory a good place to sanitize title, but this will catch a lot of XSS attempts.
+ // title is supposed to contain text only (not HTML) and be printed text only, but given the number of usages,
+ // it's difficult to guarantee correct handling in all cases
+ title = sanitizeHtml(title);
+
+ return title;
+}
+
+interface GetValidateParams {
+ parentNoteId: string;
+ type: string;
+ ignoreForbiddenParents?: boolean;
+}
+
+function getAndValidateParent(params: GetValidateParams) {
+ const parentNote = becca.notes[params.parentNoteId];
+
+ if (!parentNote) {
+ throw new ValidationError(`Parent note '${params.parentNoteId}' was not found.`);
+ }
+
+ if (parentNote.type === "launcher" && parentNote.noteId !== "_lbBookmarks") {
+ throw new ValidationError(`Creating child notes into launcher notes is not allowed.`);
+ }
+
+ if (["_lbAvailableLaunchers", "_lbVisibleLaunchers"].includes(params.parentNoteId) && params.type !== "launcher") {
+ throw new ValidationError(`Only 'launcher' notes can be created in parent '${params.parentNoteId}'`);
+ }
+
+ if (!params.ignoreForbiddenParents) {
+ if (["_lbRoot", "_hidden"].includes(parentNote.noteId)
+ || parentNote.noteId.startsWith("_lbTpl")
+ || parentNote.noteId.startsWith("_help")
+ || parentNote.isOptions()) {
+ throw new ValidationError(`Creating child notes into '${parentNote.noteId}' is not allowed.`);
+ }
+ }
+
+ return parentNote;
+}
+
+function createNewNote(params: NoteParams): {
+ note: BNote;
+ branch: BBranch;
+} {
+ const parentNote = getAndValidateParent(params);
+
+ if (params.title === null || params.title === undefined) {
+ params.title = getNewNoteTitle(parentNote);
+ }
+
+ if (params.content === null || params.content === undefined) {
+ throw new Error(`Note content must be set`);
+ }
+
+ let error;
+ if ((error = date_utils.validateLocalDateTime(params.dateCreated))) {
+ throw new Error(error);
+ }
+
+ if ((error = date_utils.validateUtcDateTime(params.utcDateCreated))) {
+ throw new Error(error);
+ }
+
+ // When creating from a template, inherit the template's type and mime if not explicitly provided.
+ // This ensures binary types (PDF, images, etc.) get the correct mime from the start.
+ if (params.templateNoteId) {
+ const templateNote = becca.getNote(params.templateNoteId);
+ if (templateNote) {
+ if (!params.mime) {
+ params.mime = templateNote.mime;
+ }
+ }
+ }
+
+ return getSql().transactional(() => {
+ let note, branch, isEntityEventsDisabled;
+
+ try {
+ isEntityEventsDisabled = cls.isEntityEventsDisabled();
+
+ if (!isEntityEventsDisabled) {
+ // it doesn't make sense to run note creation events on a partially constructed note, so
+ // defer them until note creation is completed
+ cls.disableEntityEvents();
+ }
+
+ // TODO: think about what can happen if the note already exists with the forced ID
+ // I guess on DB it's going to be fine, but becca references between entities
+ // might get messed up (two note instances for the same ID existing in the references)
+ note = new BNote({
+ noteId: params.noteId, // optionally can force specific noteId
+ title: params.title,
+ isProtected: !!params.isProtected,
+ type: params.type,
+ mime: deriveMime(params.type, params.mime),
+ dateCreated: params.dateCreated,
+ utcDateCreated: params.utcDateCreated
+ }).save();
+
+ // Create attributes atomically.
+ for (const attribute of params.attributes || []) {
+ new BAttribute({
+ ...attribute,
+ noteId: note.noteId
+ }).save();
+ }
+
+ note.setContent(params.content);
+
+ branch = new BBranch({
+ noteId: note.noteId,
+ parentNoteId: params.parentNoteId,
+ notePosition: params.notePosition !== undefined ? params.notePosition : getNewNotePosition(parentNote),
+ prefix: params.prefix || "",
+ isExpanded: !!params.isExpanded
+ }).save();
+ } finally {
+ if (!isEntityEventsDisabled) {
+ // re-enable entity events only if they were previously enabled
+ // (they can be disabled in case of import)
+ cls.enableEntityEvents();
+ }
+ }
+
+ if (params.templateNoteId) {
+ const templateNote = becca.getNote(params.templateNoteId);
+ if (!templateNote) {
+ throw new Error(`Template note '${params.templateNoteId}' does not exist.`);
+ }
+
+ // for binary content types (PDF, images, etc.), copy the template's content directly
+ // since the event handler in handlers.ts only handles string content
+ if (!templateNote.hasStringContent()) {
+ const templateContent = templateNote.getContent();
+ if (templateContent) {
+ note.setContent(templateContent);
+ }
+ }
+
+ note.addRelation("template", params.templateNoteId);
+ copyAttachments(templateNote, note);
+
+ // no special handling for ~inherit since it doesn't matter if it's assigned with the note creation or later
+ }
+
+ copyChildAttributes(parentNote, note);
+
+ eventService.emit(eventService.ENTITY_CREATED, { entityName: "notes", entity: note });
+ eventService.emit(eventService.ENTITY_CHANGED, { entityName: "notes", entity: note });
+ triggerNoteTitleChanged(note);
+ // blobs entity doesn't use "created" event
+ eventService.emit(eventService.ENTITY_CHANGED, { entityName: "blobs", entity: note });
+ eventService.emit(eventService.ENTITY_CREATED, { entityName: "branches", entity: branch });
+ eventService.emit(eventService.ENTITY_CHANGED, { entityName: "branches", entity: branch });
+ eventService.emit(eventService.CHILD_NOTE_CREATED, { childNote: note, parentNote });
+
+ getLog().info(`Created new note '${note.noteId}', branch '${branch.branchId}' of type '${note.type}', mime '${note.mime}'`);
+
+ return {
+ note,
+ branch
+ };
+ });
+}
+
+function createNewNoteWithTarget(target: "into" | "after" | "before", targetBranchId: string | undefined, params: NoteParams) {
+ if (!params.type) {
+ const parentNote = becca.notes[params.parentNoteId];
+
+ // code note type can be inherited, otherwise "text" is the default
+ params.type = parentNote.type === "code" ? "code" : "text";
+ params.mime = parentNote.type === "code" ? parentNote.mime : "text/html";
+ }
+
+ if (target === "into") {
+ return createNewNote(params);
+ } else if (target === "after" && targetBranchId) {
+ const afterBranch = becca.branches[targetBranchId];
+
+ // not updating utcDateModified to avoid having to sync whole rows
+ getSql().execute("UPDATE branches SET notePosition = notePosition + 10 WHERE parentNoteId = ? AND notePosition > ? AND isDeleted = 0", [params.parentNoteId, afterBranch.notePosition]);
+
+ params.notePosition = afterBranch.notePosition + 10;
+
+ const retObject = createNewNote(params);
+
+ entityChangesService.putNoteReorderingEntityChange(params.parentNoteId);
+
+ return retObject;
+ } else if (target === "before" && targetBranchId) {
+ const beforeBranch = becca.branches[targetBranchId];
+
+ // not updating utcDateModified to avoid having to sync whole rows
+ getSql().execute("UPDATE branches SET notePosition = notePosition - 10 WHERE parentNoteId = ? AND notePosition < ? AND isDeleted = 0", [params.parentNoteId, beforeBranch.notePosition]);
+
+ params.notePosition = beforeBranch.notePosition - 10;
+
+ const retObject = createNewNote(params);
+
+ entityChangesService.putNoteReorderingEntityChange(params.parentNoteId);
+
+ return retObject;
+ }
+ throw new Error(`Unknown target '${target}'`);
+}
+
+function protectNoteRecursively(note: BNote, protect: boolean, includingSubTree: boolean, taskContext: TaskContext<"protectNotes">) {
+ protectNote(note, protect);
+
+ taskContext.increaseProgressCount();
+
+ if (includingSubTree) {
+ for (const child of note.getChildNotes()) {
+ protectNoteRecursively(child, protect, includingSubTree, taskContext);
+ }
+ }
+}
+
+function protectNote(note: BNote, protect: boolean) {
+ if (!protectedSessionService.isProtectedSessionAvailable()) {
+ throw new Error(`Cannot (un)protect note '${note.noteId}' with protect flag '${protect}' without active protected session`);
+ }
+
+ const log = getLog();
+ try {
+ if (protect !== note.isProtected) {
+ const content = note.getContent();
+
+ note.isProtected = protect;
+ note.setContent(content, { forceSave: true });
+ }
+
+ revisionService.protectRevisions(note);
+
+ for (const attachment of note.getAttachments()) {
+ if (protect !== attachment.isProtected) {
+ try {
+ const content = attachment.getContent();
+
+ attachment.isProtected = protect;
+ attachment.setContent(content, { forceSave: true });
+ } catch (e) {
+ log.error(`Could not un/protect attachment '${attachment.attachmentId}'`);
+
+ throw e;
+ }
+ }
+ }
+ } catch (e) {
+ log.error(`Could not un/protect note '${note.noteId}'`);
+
+ throw e;
+ }
+}
+
- function checkImageAttachments(note: BNote, content: string) {
++export function checkImageAttachments(note: BNote, content: string) {
+ const foundAttachmentIds = new Set<string>();
+ let match;
+
- const imgRegExp = /src="[^"]*api\/attachments\/([a-zA-Z0-9_]+)\/image/g;
- while ((match = imgRegExp.exec(content))) {
- foundAttachmentIds.add(match[1]);
- }
-
- const linkRegExp = /href="[^"]+attachmentId=([a-zA-Z0-9_]+)/g;
- while ((match = linkRegExp.exec(content))) {
++ const patterns = note.isMarkdown()
++ ? [
++ // ![...](api/attachments/{id}/image/...) or similar markdown image syntax
++ /api\/attachments\/([a-zA-Z0-9_]+)\/image/g,
++ // [...](#root/{noteId}?viewMode=attachments&attachmentId={id})
++ /attachmentId=([a-zA-Z0-9_]+)/g
++ ]
++ : [
++ // <img src="api/attachments/{id}/image/...">
++ /src="[^"]*api\/attachments\/([a-zA-Z0-9_]+)\/image/g,
++ // <a href="...attachmentId={id}">
++ /href="[^"]+attachmentId=([a-zA-Z0-9_]+)/g
++ ];
++
++ for (const pattern of patterns) {
++ while ((match = pattern.exec(content))) {
+ foundAttachmentIds.add(match[1]);
++ }
+ }
+
+ const attachments = note.getAttachments();
+
+ for (const attachment of attachments) {
+ const attachmentInContent = attachment.attachmentId && foundAttachmentIds.has(attachment.attachmentId);
+
+ if (attachment.utcDateScheduledForErasureSince && attachmentInContent) {
+ attachment.utcDateScheduledForErasureSince = null;
+ attachment.save();
+ } else if (!attachment.utcDateScheduledForErasureSince && !attachmentInContent) {
+ attachment.utcDateScheduledForErasureSince = date_utils.utcNowDateTime();
+ attachment.save();
+ }
+ }
+
+ const existingAttachmentIds = new Set<string | undefined>(attachments.map((att) => att.attachmentId));
+ const unknownAttachmentIds = Array.from(foundAttachmentIds).filter((foundAttId) => !existingAttachmentIds.has(foundAttId));
+ const unknownAttachments = becca.getAttachments(unknownAttachmentIds);
+
+ for (const unknownAttachment of unknownAttachments) {
+ // the attachment belongs to a different note (was copy-pasted). Attachments can be linked only from the note
+ // which owns it, so either find an existing attachment having the same content or make a copy.
+ let localAttachment = note.getAttachments().find((att) => att.role === unknownAttachment.role && att.blobId === unknownAttachment.blobId);
+
+ if (localAttachment) {
+ if (localAttachment.utcDateScheduledForErasureSince) {
+ // the attachment is for sure linked now, so reset the scheduled deletion
+ localAttachment.utcDateScheduledForErasureSince = null;
+ localAttachment.save();
+ }
+
+ getLog().info(
+ `Found equivalent attachment '${localAttachment.attachmentId}' of note '${note.noteId}' for the linked foreign attachment '${unknownAttachment.attachmentId}' of note '${unknownAttachment.ownerId}'`
+ );
+ } else {
+ localAttachment = unknownAttachment.copy();
+ localAttachment.ownerId = note.noteId;
+ localAttachment.setContent(unknownAttachment.getContent(), { forceSave: true });
+
+ ws.sendMessageToAllClients({ type: "toast", message: `Attachment '${localAttachment.title}' has been copied to note '${note.title}'.` });
+ getLog().info(`Copied attachment '${unknownAttachment.attachmentId}' of note '${unknownAttachment.ownerId}' to new '${localAttachment.attachmentId}' of note '${note.noteId}'`);
+ }
+
+ // replace image links
+ content = content.replace(`api/attachments/${unknownAttachment.attachmentId}/image`, `api/attachments/${localAttachment.attachmentId}/image`);
+ // replace reference links
+ content = content.replace(
+ new RegExp(`href="[^"]+attachmentId=${unknownAttachment.attachmentId}[^"]*"`, "g"),
+ `href="#root/${localAttachment.ownerId}?viewMode=attachments&amp;attachmentId=${localAttachment.attachmentId}"`
+ );
+ }
+
+ return {
+ forceFrontendReload: unknownAttachments.length > 0,
+ content
+ };
+}
+
+function findImageLinks(content: string, foundLinks: FoundLink[]) {
+ const re = /src="[^"]*api\/images\/([a-zA-Z0-9_]+)\//g;
+ let match;
+
+ while ((match = re.exec(content))) {
+ foundLinks.push({
+ name: "imageLink",
+ value: match[1]
+ });
+ }
+
+ // removing absolute references to server to keep it working between instances,
+ // we also omit / at the beginning to keep the paths relative
+ return content.replace(/src="[^"]*\/api\/images\//g, 'src="api/images/');
+}
+
- function findInternalLinks(content: string, foundLinks: FoundLink[]) {
- const re = /href="[^"]*#root[a-zA-Z0-9_\/]*\/([a-zA-Z0-9_]+)\/?"/g;
- let match;
-
- while ((match = re.exec(content))) {
- foundLinks.push({
- name: "internalLink",
- value: match[1]
- });
- }
-
- // removing absolute references to server to keep it working between instances
- return content.replace(/href="[^"]*#root/g, 'href="#root');
- }
-
- function findIncludeNoteLinks(content: string, foundLinks: FoundLink[]) {
- const re = /<section class="include-note[^>]+data-note-id="([a-zA-Z0-9_]+)"[^>]*>/g;
- let match;
-
- while ((match = re.exec(content))) {
- foundLinks.push({
- name: "includeNoteLink",
- value: match[1]
- });
- }
-
- return content;
- }
-
+/**
+ * Extracts bookmark IDs from CKEditor bookmark anchors (`<a id="..."></a>` without href).
+ * Bookmarks are stored as labels on the note so they can be looked up without parsing content.
- * Matches id regardless of attribute order; skips anchors with href (those are regular links).
+ */
+export function findBookmarks(content: string): string[] {
- const re = /<a\b([^>]*)>(<\/a>)?/g;
++ const re = /<a\s+id="([^"]+)"[^>]*>(<\/a>)?/g;
+ const bookmarks: string[] = [];
+ let match;
+
+ while ((match = re.exec(content))) {
- const attrs = match[1];
-
+ // Skip anchors that also have an href (those are regular links, not bookmarks)
- if (/\bhref\s*=/.test(attrs)) {
++ if (match[0].includes("href=")) {
+ continue;
+ }
+
- const idMatch = /\bid\s*=\s*"([^"]+)"/.exec(attrs) ?? /\bid\s*=\s*'([^']+)'/.exec(attrs);
- if (!idMatch) {
- continue;
- }
-
- const id = idMatch[1];
++ const id = match[1];
+ if (!bookmarks.includes(id)) {
+ bookmarks.push(id);
+ }
+ }
+
+ return bookmarks;
+}
+
+function saveBookmarks(note: BNote, content: string) {
+ const foundBookmarks = findBookmarks(content);
+ const existingBookmarks = note.getOwnedLabels("internalBookmark");
+
+ for (const bookmarkId of foundBookmarks) {
+ const existing = existingBookmarks.find((l) => l.value === bookmarkId);
+
+ if (!existing) {
+ new BAttribute({
+ noteId: note.noteId,
+ type: "label",
+ name: "internalBookmark",
+ value: bookmarkId
+ }).save();
+ }
+ }
+
+ // Remove bookmarks that are no longer in the content
+ const unusedBookmarks = existingBookmarks.filter((l) => !foundBookmarks.includes(l.value));
+ for (const unused of unusedBookmarks) {
+ unused.markAsDeleted();
+ }
+}
+
++function findInternalLinks(content: string, foundLinks: FoundLink[]) {
++ const re = /href="[^"]*#root[a-zA-Z0-9_\/]*\/([a-zA-Z0-9_]+)\/?"/g;
++ let match;
++
++ while ((match = re.exec(content))) {
++ foundLinks.push({
++ name: "internalLink",
++ value: match[1]
++ });
++ }
++
++ // removing absolute references to server to keep it working between instances
++ return content.replace(/href="[^"]*#root/g, 'href="#root');
++}
++
++function findMarkdownImageLinks(content: string, foundLinks: FoundLink[]) {
++ const re = /api\/images\/([a-zA-Z0-9_]+)\//g;
++ let match;
++
++ while ((match = re.exec(content))) {
++ foundLinks.push({
++ name: "imageLink",
++ value: match[1]
++ });
++ }
++}
++
++function findMarkdownInternalLinks(content: string, foundLinks: FoundLink[]) {
++ // [text](#root/.../noteId) or [text](#root/.../noteId?query)
++ const hashRootRe = /#root[a-zA-Z0-9_/]*\/([a-zA-Z0-9_]+)/g;
++ let match;
++
++ while ((match = hashRootRe.exec(content))) {
++ foundLinks.push({
++ name: "internalLink",
++ value: match[1]
++ });
++ }
++
++ // [[noteId]] wiki-links
++ const wikiLinkRe = /\[\[([a-zA-Z0-9_]+)\]\]/g;
++
++ while ((match = wikiLinkRe.exec(content))) {
++ foundLinks.push({
++ name: "internalLink",
++ value: match[1]
++ });
++ }
++}
++
++function findIncludeNoteLinks(content: string, foundLinks: FoundLink[]) {
++ const re = /<section class="include-note[^>]+data-note-id="([a-zA-Z0-9_]+)"[^>]*>/g;
++ let match;
++
++ while ((match = re.exec(content))) {
++ foundLinks.push({
++ name: "includeNoteLink",
++ value: match[1]
++ });
++ }
++
++ return content;
++}
++
+function findRelationMapLinks(content: string, foundLinks: FoundLink[]) {
+ try {
+ const obj = JSON.parse(content);
+
+ for (const note of obj.notes) {
+ foundLinks.push({
+ name: "relationMapLink",
+ value: note.noteId
+ });
+ }
+ } catch (e: any) {
+ getLog().error(`Could not scan for relation map links: ${e.message}`);
+ }
+}
+
+const imageUrlToAttachmentIdMapping: Record<string, string> = {};
+
+async function downloadImage(noteId: string, imageUrl: string) {
+ const unescapedUrl = unescapeHtml(imageUrl);
+
+ try {
+ let imageBuffer: Uint8Array;
+
+ if (imageUrl.toLowerCase().startsWith("file://")) {
+ imageBuffer = await new Promise((res, rej) => {
+ const localFilePath = imageUrl.substring("file://".length);
+
+ return fs.readFile(localFilePath, (err, data) => {
+ if (err) {
+ rej(err);
+ } else {
+ res(data);
+ }
+ });
+ });
+ } else {
+ imageBuffer = new Uint8Array(await request.getImage(unescapedUrl));
+ }
+
+ const parsedUrl = url.parse(unescapedUrl);
+ const title = basename(parsedUrl.pathname || "");
+
+ const attachment = imageService.saveImageToAttachment(noteId, imageBuffer, title, true, true);
+
+ if (attachment.attachmentId) {
+ imageUrlToAttachmentIdMapping[imageUrl] = attachment.attachmentId;
+ } else {
+ getLog().error(`Download of '${imageUrl}' for note '${noteId}' failed due to no attachment ID.`);
+ }
+
+ getLog().info(`Download of '${imageUrl}' succeeded and was saved as image attachment '${attachment.attachmentId}' of note '${noteId}'`);
+ } catch (e: any) {
+ getLog().error(`Download of '${imageUrl}' for note '${noteId}' failed with error: ${e.message} ${e.stack}`);
+ }
+}
+
+/** url => download promise */
+const downloadImagePromises: Record<string, Promise<void>> = {};
+
+function replaceUrl(content: string, url: string, attachment: Attachment) {
+ const quotedUrl = quoteRegex(url);
+
+ return content.replace(new RegExp(`\\s+src=[\"']${quotedUrl}[\"']`, "ig"), ` src="api/attachments/${attachment.attachmentId}/image/${encodeURIComponent(attachment.title)}"`);
+}
+
+function downloadImages(noteId: string, content: string) {
+ const imageRe = /<img[^>]*?\ssrc=['"]([^'">]+)['"]/gi;
+ let imageMatch;
+
+ while ((imageMatch = imageRe.exec(content))) {
+ const url = imageMatch[1];
+ const inlineImageMatch = /^data:image\/[a-z]+;base64,/.exec(url);
+
+ if (inlineImageMatch) {
+ const imageBase64 = url.substring(inlineImageMatch[0].length);
+ const imageBuffer = decodeBase64(imageBase64);
+
+ const attachment = imageService.saveImageToAttachment(noteId, imageBuffer, "inline image", true, true);
+
+ const encodedTitle = encodeURIComponent(attachment.title);
+
+ content = `${content.substring(0, imageMatch.index)}<img src="api/attachments/${attachment.attachmentId}/image/${encodedTitle}"${content.substring(imageMatch.index + imageMatch[0].length)}`;
+ } else if (
+ !url.includes("api/images/") &&
+ !/api\/attachments\/.+\/image\/?.*/.test(url) &&
+ // this is an exception for the web clipper's "imageId"
+ (url.length !== 20 || url.toLowerCase().startsWith("http"))
+ ) {
+ if (!optionService.getOptionBool("downloadImagesAutomatically")) {
+ continue;
+ }
+
+ if (url in imageUrlToAttachmentIdMapping) {
+ const attachment = becca.getAttachment(imageUrlToAttachmentIdMapping[url]);
+
+ if (!attachment) {
+ delete imageUrlToAttachmentIdMapping[url];
+ } else {
+ content = replaceUrl(content, url, attachment);
+ continue;
+ }
+ }
+
+ if (url in downloadImagePromises) {
+ // download is already in progress
+ continue;
+ }
+
+ // this is done asynchronously, it would be too slow to wait for the download
+ // given that save can be triggered very often
+ downloadImagePromises[url] = downloadImage(noteId, url);
+ }
+ }
+
+ Promise.all(Object.values(downloadImagePromises)).then(() => {
+ setTimeout(() => {
+ // the normal expected flow of the offline image saving is that users will paste the image(s)
+ // which will get asynchronously downloaded, during that time they keep editing the note
+ // once the download is finished, the image note representing the downloaded image will be used
+ // to replace the IMG link.
+ // However, there's another flow where the user pastes the image and leaves the note before the images
+ // are downloaded and the IMG references are not updated. For this occasion we have this code
+ // which upon the download of all the images will update the note if the links have not been fixed before
+
+ cls.getContext().init(() => {
+ getSql().transactional(() => {
+ const imageNotes = becca.getNotes(Object.values(imageUrlToAttachmentIdMapping), true);
+ const log = getLog();
+
+ const origNote = becca.getNote(noteId);
+
+ if (!origNote) {
+ log.error(`Cannot find note '${noteId}' to replace image link.`);
+ return;
+ }
+
+ const origContent = origNote.getContent();
+ let updatedContent = origContent;
+
+ if (typeof updatedContent !== "string") {
+ log.error(`Note '${noteId}' has a non-string content, cannot replace image link.`);
+ return;
+ }
+
+ for (const url in imageUrlToAttachmentIdMapping) {
+ const imageNote = imageNotes.find((note) => note.noteId === imageUrlToAttachmentIdMapping[url]);
+
+ if (imageNote) {
+ updatedContent = replaceUrl(updatedContent, url, imageNote);
+ }
+ }
+
+ // update only if the links have not been already fixed.
+ if (updatedContent !== origContent) {
+ origNote.setContent(updatedContent);
+
+ asyncPostProcessContent(origNote, updatedContent);
+
+ console.log(`Fixed the image links for note '${noteId}' to the offline saved.`);
+ }
+ });
+ });
+ }, 5000);
+ });
+
+ return content;
+}
+
+function saveAttachments(note: BNote, content: string) {
+ const inlineAttachmentRe = /<a[^>]*?\shref=['"]data:([^;'">]+);base64,([^'">]+)['"][^>]*>(.*?)<\/a>/gim;
+ let attachmentMatch;
+
+ while ((attachmentMatch = inlineAttachmentRe.exec(content))) {
+ const mime = attachmentMatch[1].toLowerCase();
+
+ const base64data = attachmentMatch[2];
+ const buffer = decodeBase64(base64data);
+
+ const title = html2plaintext(attachmentMatch[3]);
+
+ const attachment = note.saveAttachment({
+ role: "file",
+ mime,
+ title,
+ content: buffer
+ });
+
+ content = `${content.substring(0, attachmentMatch.index)}<a class="reference-link" href="#root/${note.noteId}?viewMode=attachments&attachmentId=${attachment.attachmentId}">${title}</a>${content.substring(attachmentMatch.index + attachmentMatch[0].length)}`;
+ }
+
+ // removing absolute references to server to keep it working between instances,
+ // we also omit / at the beginning to keep the paths relative
+ content = content.replace(/src="[^"]*\/api\/attachments\//g, 'src="api/attachments/');
+
+ return content;
+}
+
- function saveLinks(note: BNote, content: string | Uint8Array) {
- if ((note.type !== "text" && note.type !== "relationMap") || (note.isProtected && !protectedSessionService.isProtectedSessionAvailable())) {
++
++export function saveLinks(note: BNote, content: string | Buffer) {
++ if ((note.type !== "text" && note.type !== "relationMap" && !note.isMarkdown()) || (note.isProtected && !protectedSessionService.isProtectedSessionAvailable())) {
+ return {
+ forceFrontendReload: false,
+ content
+ };
+ }
+
+ const foundLinks: FoundLink[] = [];
+ let forceFrontendReload = false;
+
+ if (note.type === "text" && typeof content === "string") {
+ content = downloadImages(note.noteId, content);
+ content = saveAttachments(note, content);
+
+ content = findImageLinks(content, foundLinks);
+ content = findInternalLinks(content, foundLinks);
+ content = findIncludeNoteLinks(content, foundLinks);
+ saveBookmarks(note, content);
+
++ ({ forceFrontendReload, content } = checkImageAttachments(note, content));
++ } else if (note.isMarkdown() && typeof content === "string") {
++ findMarkdownImageLinks(content, foundLinks);
++ findMarkdownInternalLinks(content, foundLinks);
+ ({ forceFrontendReload, content } = checkImageAttachments(note, content));
+ } else if (note.type === "relationMap" && typeof content === "string") {
+ findRelationMapLinks(content, foundLinks);
+ } else {
+ throw new Error(`Unrecognized type '${note.type}'`);
+ }
+
+ const existingLinks = note.getRelations().filter((rel) => ["internalLink", "imageLink", "relationMapLink", "includeNoteLink"].includes(rel.name));
+
+ for (const foundLink of foundLinks) {
+ const targetNote = becca.notes[foundLink.value];
+ if (!targetNote) {
+ continue;
+ }
+
+ const existingLink = existingLinks.find((existingLink) => existingLink.value === foundLink.value && existingLink.name === foundLink.name);
+
+ if (!existingLink) {
+ const newLink = new BAttribute({
+ noteId: note.noteId,
+ type: "relation",
+ name: foundLink.name,
+ value: foundLink.value
+ }).save();
+
+ existingLinks.push(newLink);
+ }
+ // else the link exists, so we don't need to do anything
+ }
+
+ // marking links as deleted if they are not present on the page anymore
+ const unusedLinks = existingLinks.filter((existingLink) => !foundLinks.some((foundLink) => existingLink.value === foundLink.value && existingLink.name === foundLink.name));
+
+ for (const unusedLink of unusedLinks) {
+ unusedLink.markAsDeleted();
+ }
+
+ return { forceFrontendReload, content };
+}
+
+function saveRevisionIfNeeded(note: BNote) {
+ // files and images are versioned separately
+ if (note.type === "file" || note.type === "image" || note.isLabelTruthy("disableVersioning")) {
+ return;
+ }
+
+ const now = new Date();
+ const revisionSnapshotTimeInterval = parseInt(optionService.getOption("revisionSnapshotTimeInterval"));
+
+ const revisionCutoff = date_utils.utcDateTimeStr(new Date(now.getTime() - revisionSnapshotTimeInterval * 1000));
+
+ const existingRevisionId = getSql().getValue("SELECT revisionId FROM revisions WHERE noteId = ? AND utcDateCreated >= ?", [note.noteId, revisionCutoff]);
+
+ const msSinceDateCreated = now.getTime() - date_utils.parseDateTime(note.utcDateCreated).getTime();
+
+ if (!existingRevisionId && msSinceDateCreated >= revisionSnapshotTimeInterval * 1000) {
+ note.saveRevision();
+ }
+}
+
+function updateNoteData(noteId: string, content: string, attachments: AttachmentRow[] = []) {
+ const note = becca.getNote(noteId);
+
+ if (!note || !note.isContentAvailable()) {
+ throw new Error(`Note '${noteId}' is not available for change!`);
+ }
+
+ saveRevisionIfNeeded(note);
+
+ const { forceFrontendReload, content: newContent } = saveLinks(note, content);
+
+ note.setContent(newContent, { forceFrontendReload });
+
+ if (attachments?.length > 0) {
+ const existingAttachmentsByTitle = toMap(note.getAttachments(), "title");
+
+ for (const { attachmentId, role, mime, title, position, content, encoding } of attachments) {
+ const decodedContent = encoding === "base64" && typeof content === "string"
+ ? decodeBase64(content) : content;
+
+ const existingAttachment = existingAttachmentsByTitle.get(title);
+ if (attachmentId || !existingAttachment) {
+ note.saveAttachment({ attachmentId, role, mime, title, content: decodedContent, position });
+ } else {
+ existingAttachment.role = role;
+ existingAttachment.mime = mime;
+ existingAttachment.position = position;
+ if (decodedContent) {
+ existingAttachment.setContent(decodedContent, { forceSave: true });
+ }
+ }
+ }
+ }
+}
+
+function undeleteNote(noteId: string, taskContext: TaskContext<"undeleteNotes">) {
+ const noteRow = getSql().getRow<NoteRow>("SELECT * FROM notes WHERE noteId = ?", [noteId]);
+
+ if (!noteRow.isDeleted || !noteRow.deleteId) {
+ getLog().error(`Note '${noteId}' is not deleted and thus cannot be undeleted.`);
+ return;
+ }
+
+ const undeletedParentBranchIds = getUndeletedParentBranchIds(noteId, noteRow.deleteId);
+
+ if (undeletedParentBranchIds.length === 0) {
+ // cannot undelete if there's no undeleted parent
+ return;
+ }
+
+ for (const parentBranchId of undeletedParentBranchIds) {
+ undeleteBranch(parentBranchId, noteRow.deleteId, taskContext);
+ }
+}
+
+function undeleteBranch(branchId: string, deleteId: string, taskContext: TaskContext<"undeleteNotes">) {
+ const sql = getSql();
+ const branchRow = sql.getRow<BranchRow>("SELECT * FROM branches WHERE branchId = ?", [branchId]);
+
+ if (!branchRow.isDeleted) {
+ return;
+ }
+
+ const noteRow = sql.getRow<NoteRow>("SELECT * FROM notes WHERE noteId = ?", [branchRow.noteId]);
+
+ if (noteRow.isDeleted && noteRow.deleteId !== deleteId) {
+ return;
+ }
+
+ new BBranch(branchRow).save();
+
+ taskContext.increaseProgressCount();
+
+ if (noteRow.isDeleted && noteRow.deleteId === deleteId) {
+ // becca entity was already created as skeleton in "new Branch()" above
+ const noteEntity = becca.getNote(noteRow.noteId);
+ if (!noteEntity) {
+ throw new Error("Unable to find the just restored branch.");
+ }
+
+ noteEntity.updateFromRow(noteRow);
+ noteEntity.save();
+
+ const attributeRows = sql.getRows<AttributeRow>(
+ `
+ SELECT * FROM attributes
+ WHERE isDeleted = 1
+ AND deleteId = ?
+ AND (noteId = ?
+ OR (type = 'relation' AND value = ?))`,
+ [deleteId, noteRow.noteId, noteRow.noteId]
+ );
+
+ for (const attributeRow of attributeRows) {
+ // relation might point to a note which hasn't been undeleted yet and would thus throw up
+ new BAttribute(attributeRow).save({ skipValidation: true });
+ }
+
+ const attachmentRows = sql.getRows<AttachmentRow>(
+ `
+ SELECT * FROM attachments
+ WHERE isDeleted = 1
+ AND deleteId = ?
+ AND ownerId = ?`,
+ [deleteId, noteRow.noteId]
+ );
+
+ for (const attachmentRow of attachmentRows) {
+ new BAttachment(attachmentRow).save();
+ }
+
+ const childBranchIds = sql.getColumn<string>(
+ `
+ SELECT branches.branchId
+ FROM branches
+ WHERE branches.isDeleted = 1
+ AND branches.deleteId = ?
+ AND branches.parentNoteId = ?`,
+ [deleteId, noteRow.noteId]
+ );
+
+ for (const childBranchId of childBranchIds) {
+ undeleteBranch(childBranchId, deleteId, taskContext);
+ }
+ }
+}
+
+/**
+ * @returns return deleted branchIds of an undeleted parent note
+ */
+function getUndeletedParentBranchIds(noteId: string, deleteId: string) {
+ return getSql().getColumn<string>(
+ `
+ SELECT branches.branchId
+ FROM branches
+ JOIN notes AS parentNote ON parentNote.noteId = branches.parentNoteId
+ WHERE branches.noteId = ?
+ AND branches.isDeleted = 1
+ AND branches.deleteId = ?
+ AND parentNote.isDeleted = 0`,
+ [noteId, deleteId]
+ );
+}
+
+function scanForLinks(note: BNote, content: string | Uint8Array) {
+ if (!note || !["text", "relationMap"].includes(note.type)) {
+ return;
+ }
+
+ try {
+ getSql().transactional(() => {
+ const { forceFrontendReload, content: newContent } = saveLinks(note, content);
+
+ if (content !== newContent) {
+ note.setContent(newContent, { forceFrontendReload });
+ }
+ });
+ } catch (e: any) {
+ getLog().error(`Could not scan for links note '${note.noteId}': ${e.message} ${e.stack}`);
+ }
+}
+
+/**
+ * Things which have to be executed after updating content, but asynchronously (separate transaction)
+ */
+async function asyncPostProcessContent(note: BNote, content: string | Uint8Array) {
+ if (cls.isMigrationRunning()) {
+ // this is rarely needed for migrations, but can cause trouble by e.g. triggering downloads
+ return;
+ }
+
+ if (note.hasStringContent() && typeof content !== "string") {
+ content = content.toString();
+ }
+
+ scanForLinks(note, content);
+}
+
+// all keys should be replaced by the corresponding values
+function replaceByMap(str: string, mapObj: Record<string, string>) {
+ if (!mapObj) {
+ return str;
+ }
+
+ const re = new RegExp(Object.keys(mapObj).join("|"), "g");
+
+ return str.replace(re, (matched) => mapObj[matched]);
+}
+
+function duplicateSubtree(origNoteId: string, newParentNoteId: string) {
+ if (origNoteId === "root") {
+ throw new Error("Duplicating root is not possible");
+ }
+
+ getLog().info(`Duplicating '${origNoteId}' subtree into '${newParentNoteId}'`);
+
+ const origNote = becca.notes[origNoteId];
+ // might be null if orig note is not in the target newParentNoteId
+ const origBranch = origNote.getParentBranches().find((branch) => branch.parentNoteId === newParentNoteId);
+
+ const noteIdMapping = getNoteIdMapping(origNote);
+
+ const res = duplicateSubtreeInner(origNote, origBranch, newParentNoteId, noteIdMapping);
+
+ const duplicateNoteSuffix = t("notes.duplicate-note-suffix");
+
+ if (!res.note.title.endsWith(duplicateNoteSuffix) && !res.note.title.startsWith(duplicateNoteSuffix)) {
+ res.note.title = t("notes.duplicate-note-title", { noteTitle: res.note.title, duplicateNoteSuffix });
+ }
+
+ res.note.save();
+
+ return res;
+}
+
+function duplicateSubtreeWithoutRoot(origNoteId: string, newNoteId: string) {
+ if (origNoteId === "root") {
+ throw new Error("Duplicating root is not possible");
+ }
+
+ const origNote = becca.getNote(origNoteId);
+ if (origNote == null) {
+ throw new Error("Unable to find note to duplicate.");
+ }
+
+ const noteIdMapping = getNoteIdMapping(origNote);
+ for (const childBranch of origNote.getChildBranches()) {
+ if (childBranch) {
+ duplicateSubtreeInner(childBranch.getNote(), childBranch, newNoteId, noteIdMapping);
+ }
+ }
+}
+
+function duplicateSubtreeInner(origNote: BNote, origBranch: BBranch | null | undefined, newParentNoteId: string, noteIdMapping: Record<string, string>) {
+ if (origNote.isProtected && !protectedSessionService.isProtectedSessionAvailable()) {
+ throw new Error(`Cannot duplicate note '${origNote.noteId}' because it is protected and protected session is not available. Enter protected session and try again.`);
+ }
+
+ const newNoteId = noteIdMapping[origNote.noteId];
+
+ function createDuplicatedBranch() {
+ return new BBranch({
+ noteId: newNoteId,
+ parentNoteId: newParentNoteId,
+ // here increasing just by 1 to make sure it's directly after original
+ notePosition: origBranch ? origBranch.notePosition + 1 : null
+ }).save();
+ }
+
+ function createDuplicatedNote() {
+ const newNote = new BNote({
+ ...origNote,
+ noteId: newNoteId,
+ dateCreated: date_utils.localNowDateTime(),
+ utcDateCreated: date_utils.utcNowDateTime()
+ }).save();
+
+ let content = origNote.getContent();
+
+ if (typeof content === "string" && ["text", "relationMap", "search"].includes(origNote.type)) {
+ // fix links in the content
+ content = replaceByMap(content, noteIdMapping);
+ }
+
+ newNote.setContent(content);
+
+ for (const attribute of origNote.getOwnedAttributes()) {
+ const attr = new BAttribute({
+ ...attribute,
+ attributeId: undefined,
+ noteId: newNote.noteId
+ });
+
+ // if relation points to within the duplicated tree then replace the target to the duplicated note
+ // if it points outside of duplicated tree then keep the original target
+ if (attr.type === "relation" && attr.value in noteIdMapping) {
+ attr.value = noteIdMapping[attr.value];
+ }
+
+ // the relation targets may not be created yet, the mapping is pre-generated
+ attr.save({ skipValidation: true });
+ }
+
+ for (const childBranch of origNote.getChildBranches()) {
+ if (childBranch) {
+ duplicateSubtreeInner(childBranch.getNote(), childBranch, newNote.noteId, noteIdMapping);
+ }
+ }
+
+ asyncPostProcessContent(newNote, content);
+
+ return newNote;
+ }
+
+ const existingNote = becca.notes[newNoteId];
+
+ if (existingNote && existingNote.title !== undefined) {
+ // checking that it's not just note's skeleton created because of Branch above
+ // note has multiple clones and was already created from another placement in the tree,
+ // so a branch is all we need for this clone
+ return {
+ note: existingNote,
+ branch: createDuplicatedBranch()
+ };
+ }
+ return {
+ // order here is important, note needs to be created first to not mess up the becca
+ note: createDuplicatedNote(),
+ branch: createDuplicatedBranch()
+ };
+
+}
+
+function getNoteIdMapping(origNote: BNote) {
+ const noteIdMapping: Record<string, string> = {};
+
+ // pregenerate new noteIds since we'll need to fix relation references even for not yet created notes
+ for (const origNoteId of origNote.getDescendantNoteIds()) {
+ noteIdMapping[origNoteId] = newEntityId();
+ }
+
+ return noteIdMapping;
+}
+
+export default {
+ createNewNote,
+ createNewNoteWithTarget,
+ updateNoteData,
+ undeleteNote,
+ protectNoteRecursively,
+ duplicateSubtree,
+ duplicateSubtreeWithoutRoot,
+ getUndeletedParentBranchIds,
+ triggerNoteTitleChanged,
+ saveRevisionIfNeeded,
+ downloadImages,
+ asyncPostProcessContent
+};
diff --cc packages/trilium-core/src/services/zip_provider.ts
index cd75d93d37,0000000000..b59eadfd71
mode 100644,000000..100644
--- a/packages/trilium-core/src/services/zip_provider.ts
+++ b/packages/trilium-core/src/services/zip_provider.ts
@@@ -1,48 -1,0 +1,57 @@@
+export interface ZipEntry {
+ fileName: string;
+}
+
+export interface ZipArchiveEntryOptions {
+ name: string;
+ date?: Date;
+}
+
+export interface ZipArchive {
+ append(content: string | Uint8Array, options: ZipArchiveEntryOptions): void;
+ pipe(destination: unknown): void;
+ finalize(): Promise<void>;
+}
+
+export interface FileStream {
+ /** An opaque writable destination that can be passed to {@link ZipArchive.pipe}. */
+ destination: unknown;
+ /** Resolves when the stream has finished writing (or rejects on error). */
+ waitForFinish(): Promise<void>;
+}
+
+export interface ZipProvider {
++ /**
++ * Detects the filename encoding used in a ZIP file by collecting all
++ * non-UTF-8-flagged entry names and running charset detection on them.
++ * Returns the detected encoding label (usable with TextDecoder), or "utf-8" as fallback.
++ */
++ detectFilenameEncoding(buffer: Uint8Array): Promise<string>;
++
+ /**
+ * Iterates over every entry in a ZIP buffer, calling `processEntry` for each one.
+ * `readContent()` inside the callback reads the raw bytes of that entry on demand.
++ * If `filenameEncoding` is provided, non-UTF-8-flagged filenames are decoded using it.
+ */
+ readZipFile(
+ buffer: Uint8Array,
- processEntry: (entry: ZipEntry, readContent: () => Promise<Uint8Array>) => Promise<void>
++ processEntry: (entry: ZipEntry, readContent: () => Promise<Uint8Array>) => Promise<void>,
++ filenameEncoding?: string
+ ): Promise<void>;
+
+ createZipArchive(): ZipArchive;
+
+ /** Creates a writable file stream for the given path. */
+ createFileStream(filePath: string): FileStream;
+}
+
+let zipProvider: ZipProvider | null = null;
+
+export function initZipProvider(provider: ZipProvider) {
+ zipProvider = provider;
+}
+
+export function getZipProvider(): ZipProvider {
+ if (!zipProvider) throw new Error("ZipProvider not initialized.");
+ return zipProvider;
+}
diff --cc packages/trilium-core/src/test/becca_easy_mocking.ts
index 7e900d3c21,0000000000..f5f6a3ebd5
mode 100644,000000..100644
--- a/packages/trilium-core/src/test/becca_easy_mocking.ts
+++ b/packages/trilium-core/src/test/becca_easy_mocking.ts
@@@ -1,134 -1,0 +1,135 @@@
+import { NoteType } from "@triliumnext/commons";
+
+import BAttachment from "../becca/entities/battachment.js";
+import BAttribute from "../becca/entities/battribute.js";
+import BBranch from "../becca/entities/bbranch.js";
+import BNote from "../becca/entities/bnote.js";
+import { randomString } from "../services/utils/index.js";
+
+type AttributeDefinitions = { [key in `#${string}`]: string; };
+type RelationDefinitions = { [key in `~${string}`]: string; };
+
+interface NoteDefinition extends AttributeDefinitions, RelationDefinitions {
+ id?: string | undefined;
+ title?: string;
+ content?: string;
+ type?: NoteType;
+ mime?: string;
+ children?: NoteDefinition[];
+ attachments?: {
+ title: string;
+ role: string;
+ mime: string;
+ }[];
+}
+
+/**
+ * Creates the given notes with the given title and optionally one or more attributes.
+ *
+ * For a label to be created, simply pass on a key prefixed with `#` and any desired value.
+ *
+ * The notes and attributes will be injected in the froca.
+ *
+ * @param notes
+ * @returns an array containing the IDs of the created notes.
+ * @example
+ * buildNotes([
+ * { title: "A", "#startDate": "2025-05-05" },
+ * { title: "B", "#startDate": "2025-05-07" }
+ * ]);
+ */
+export function buildNotes(notes: NoteDefinition[]) {
+ const ids: string[] = [];
+
+ for (const noteDef of notes) {
+ ids.push(buildNote(noteDef).noteId);
+ }
+
+ return ids;
+}
+
+export function buildNote(noteDef: NoteDefinition) {
+ const note = new BNote({
+ noteId: noteDef.id ?? randomString(12),
+ title: noteDef.title ?? "New note",
+ type: noteDef.type ?? "text",
+ mime: noteDef.mime ?? "text/html",
+ isProtected: false,
+ blobId: ""
+ });
+
+ // Handle content.
+ if (noteDef.content !== undefined) {
+ note.getContent = () => noteDef.content!;
+ }
+
+ // Handle children
+ if (noteDef.children) {
+ for (const childDef of noteDef.children) {
+ const childNote = buildNote(childDef);
+ new BBranch({
+ noteId: childNote.noteId,
+ parentNoteId: note.noteId,
+ branchId: `${note.noteId}_${childNote.noteId}`
+ });
+ }
+ }
+
+ // Handle labels and relations.
+ let position = 0;
+ for (const [ key, value ] of Object.entries(noteDef)) {
+ const attributeId = randomString(12);
+ const name = key.substring(1);
+
+ let attribute: BAttribute | null = null;
+ if (key.startsWith("#")) {
+ attribute = new BAttribute({
+ noteId: note.noteId,
+ attributeId,
+ type: "label",
+ name,
+ value,
+ position,
+ isInheritable: false
+ });
+ }
+
+ if (key.startsWith("~")) {
+ attribute = new BAttribute({
+ noteId: note.noteId,
+ attributeId,
+ type: "relation",
+ name,
+ value,
+ position,
+ isInheritable: false
+ });
+ }
+
+ if (!attribute) {
+ continue;
+ }
+
+ position++;
+ }
+
+ // Handle attachments.
+ if (noteDef.attachments) {
+ const allAttachments: BAttachment[] = [];
+ for (const { title, role, mime } of noteDef.attachments) {
+ const attachment = new BAttachment({
+ attachmentId: randomString(10),
+ ownerId: note.noteId,
+ title,
+ role,
+ mime
+ });
+ allAttachments.push(attachment);
+ }
+
++ note.getAttachments = () => allAttachments;
+ note.getAttachmentsByRole = (role) => allAttachments.filter(a => a.role === role);
+ }
+
+ return note;
+}
diff --cc pnpm-lock.yaml
index 23727c4c81,42e428a29f..f559076568
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@@ -185,17 -185,10 +185,17 @@@ importers
apps/build-docs:
+ dependencies:
+ '@triliumnext/core':
+ specifier: workspace:*
+ version: link:../../packages/trilium-core
+ '@triliumnext/server':
+ specifier: workspace:*
+ version: link:../server
devDependencies:
'@redocly/cli':
- specifier: 2.30.0
+ specifier: 2.30.4
archiver:
specifier: 7.0.1
version: 7.0.1
@@@ -432,232 -425,6 +432,232 @@@
specifier: 4.1.0
+ apps/client-standalone:
+ dependencies:
+ '@excalidraw/excalidraw':
+ specifier: 0.18.0
+ '@fullcalendar/core':
+ specifier: 6.1.20
+ version: 6.1.20
+ '@fullcalendar/daygrid':
+ specifier: 6.1.20
+ version: 6.1.20(@fullcalendar/[email protected])
+ '@fullcalendar/interaction':
+ specifier: 6.1.20
+ version: 6.1.20(@fullcalendar/[email protected])
+ '@fullcalendar/list':
+ specifier: 6.1.20
+ version: 6.1.20(@fullcalendar/[email protected])
+ '@fullcalendar/multimonth':
+ specifier: 6.1.20
+ version: 6.1.20(@fullcalendar/[email protected])
+ '@fullcalendar/timegrid':
+ specifier: 6.1.20
+ version: 6.1.20(@fullcalendar/[email protected])
+ '@maplibre/maplibre-gl-leaflet':
+ specifier: 0.1.3
+ '@mermaid-js/layout-elk':
+ specifier: 0.2.1
- version: 0.2.1([email protected])
++ version: 0.2.1([email protected])
+ '@mind-elixir/node-menu':
+ specifier: 5.0.1
+ version: 5.0.1([email protected])
+ '@popperjs/core':
+ specifier: 2.11.8
+ version: 2.11.8
+ '@preact/signals':
+ specifier: 2.9.0
+ version: 2.9.0([email protected])
+ '@sqlite.org/sqlite-wasm':
+ specifier: 3.51.1-build2
+ version: 3.51.1-build2
+ '@triliumnext/ckeditor5':
+ specifier: workspace:*
+ version: link:../../packages/ckeditor5
+ '@triliumnext/codemirror':
+ specifier: workspace:*
+ version: link:../../packages/codemirror
+ '@triliumnext/commons':
+ specifier: workspace:*
+ version: link:../../packages/commons
+ '@triliumnext/core':
+ specifier: workspace:*
+ version: link:../../packages/trilium-core
+ '@triliumnext/highlightjs':
+ specifier: workspace:*
+ version: link:../../packages/highlightjs
+ '@triliumnext/share-theme':
+ specifier: workspace:*
+ version: link:../../packages/share-theme
+ '@triliumnext/split.js':
+ specifier: workspace:*
+ version: link:../../packages/splitjs
+ '@zumer/snapdom':
+ specifier: 2.8.0
+ version: 2.8.0
+ aes-js:
+ specifier: 3.1.2
+ version: 3.1.2
+ autocomplete.js:
+ specifier: 0.38.1
+ version: 0.38.1
+ bootstrap:
+ specifier: 5.3.8
+ version: 5.3.8(@popperjs/[email protected])
+ boxicons:
+ specifier: 2.1.4
+ version: 2.1.4
+ clsx:
+ specifier: 2.1.1
+ version: 2.1.1
+ color:
+ specifier: 5.0.3
+ version: 5.0.3
+ debounce:
+ specifier: 3.0.0
+ version: 3.0.0
+ draggabilly:
+ specifier: 3.0.0
+ version: 3.0.0
+ fflate:
+ specifier: 0.8.2
+ version: 0.8.2
+ force-graph:
+ specifier: 1.51.4
+ version: 1.51.4
+ globals:
+ specifier: 17.4.0
+ version: 17.4.0
+ i18next:
- specifier: 26.0.5
- version: 26.0.5([email protected])
++ specifier: 26.0.8
++ version: 26.0.8([email protected])
+ i18next-http-backend:
+ specifier: 3.0.4
+ version: 3.0.4([email protected])
+ jquery:
+ specifier: 4.0.0
+ version: 4.0.0
+ jquery.fancytree:
+ specifier: 2.38.5
+ version: 2.38.5([email protected])
+ js-md5:
+ specifier: 0.8.3
+ version: 0.8.3
+ js-sha1:
+ specifier: 0.7.0
+ version: 0.7.0
+ js-sha256:
+ specifier: 0.11.1
+ version: 0.11.1
+ js-sha512:
+ specifier: 0.9.0
+ version: 0.9.0
+ jsplumb:
+ specifier: 2.15.6
+ version: 2.15.6
+ katex:
+ specifier: 0.16.45
+ version: 0.16.45
+ knockout:
+ specifier: 3.5.1
+ version: 3.5.1
+ leaflet:
+ specifier: 1.9.4
+ version: 1.9.4
+ leaflet-gpx:
+ specifier: 2.2.0
+ version: 2.2.0
+ mark.js:
+ specifier: 8.11.1
+ version: 8.11.1
+ marked:
+ specifier: 18.0.1
+ version: 18.0.1
+ mermaid:
- specifier: 11.14.0
- version: 11.14.0
++ specifier: 11.15.0
++ version: 11.15.0
+ mind-elixir:
+ specifier: 5.10.0
+ version: 5.10.0
+ normalize.css:
+ specifier: 8.0.1
+ version: 8.0.1
+ panzoom:
+ specifier: 9.4.4
+ version: 9.4.4
+ preact:
+ specifier: 10.29.1
+ version: 10.29.1
+ react-i18next:
+ specifier: 17.0.4
+ react-window:
+ specifier: 2.2.7
+ reveal.js:
+ specifier: 6.0.1
+ version: 6.0.1
+ scrypt-js:
+ specifier: 3.0.1
+ version: 3.0.1
+ svg-pan-zoom:
+ specifier: 3.6.2
+ version: 3.6.2
+ tabulator-tables:
+ specifier: 6.4.0
+ version: 6.4.0
+ vanilla-js-wheel-zoom:
+ specifier: 9.0.4
+ version: 9.0.4
+ devDependencies:
+ '@ckeditor/ckeditor5-inspector':
+ specifier: 5.0.0
+ version: 5.0.0
+ '@preact/preset-vite':
+ specifier: 2.10.2
+ '@types/aes-js':
+ specifier: 3.1.4
+ version: 3.1.4
+ '@types/bootstrap':
+ specifier: 5.2.10
+ version: 5.2.10
+ '@types/jquery':
+ specifier: 4.0.0
+ version: 4.0.0
+ '@types/leaflet':
+ specifier: 1.9.21
+ version: 1.9.21
+ '@types/leaflet-gpx':
+ specifier: 1.3.8
+ version: 1.3.8
+ '@types/mark.js':
+ specifier: 8.11.12
+ version: 8.11.12
+ '@types/reveal.js':
+ specifier: 5.2.2
+ version: 5.2.2
+ '@types/tabulator-tables':
+ specifier: 6.3.1
+ version: 6.3.1
+ copy-webpack-plugin:
+ specifier: 14.0.0
+ cross-env:
+ specifier: 7.0.3
+ version: 7.0.3
+ happy-dom:
+ specifier: 20.9.0
+ script-loader:
+ specifier: 0.7.2
+ version: 0.7.2
+ vite-plugin-static-copy:
+ specifier: 4.0.1
+
apps/db-compare:
dependencies:
colors:
@@@ -852,12 -597,6 +852,12 @@@
html-to-text:
specifier: 9.0.5
version: 9.0.5
+ i18next:
- specifier: 26.0.5
- version: 26.0.5([email protected])
++ specifier: 26.0.8
++ version: 26.0.8([email protected])
+ i18next-fs-backend:
+ specifier: 2.6.3
+ version: 2.6.3
js-yaml:
specifier: 4.1.1
version: 4.1.1
@@@ -1674,67 -1467,6 +1674,67 @@@
specifier: 4.1.5
+ packages/trilium-core:
+ dependencies:
+ '@braintree/sanitize-url':
+ specifier: 7.1.1
+ version: 7.1.1
+ '@triliumnext/commons':
+ specifier: workspace:*
+ version: link:../commons
+ '@triliumnext/turndown-plugin-gfm':
+ specifier: workspace:*
+ version: link:../turndown-plugin-gfm
+ async-mutex:
+ specifier: 0.5.0
+ version: 0.5.0
+ chardet:
+ specifier: 2.1.1
+ version: 2.1.1
+ escape-html:
+ specifier: 1.0.3
+ version: 1.0.3
+ i18next:
- specifier: 26.0.5
- version: 26.0.5([email protected])
++ specifier: 26.0.8
++ version: 26.0.8([email protected])
+ mime-types:
+ specifier: 3.0.2
+ version: 3.0.2
+ node-html-parser:
+ specifier: 7.1.0
+ version: 7.1.0
+ sanitize-filename:
+ specifier: 1.6.4
+ version: 1.6.4
+ sanitize-html:
+ specifier: 2.17.2
+ version: 2.17.2
+ strip-bom:
+ specifier: 5.0.0
+ version: 5.0.0
+ sucrase:
+ specifier: 3.35.1
+ version: 3.35.1
+ unescape:
+ specifier: 1.0.1
+ version: 1.0.1
+ devDependencies:
+ '@types/escape-html':
+ specifier: 1.0.4
+ version: 1.0.4
+ '@types/mime-types':
+ specifier: 3.0.1
+ version: 3.0.1
+ '@types/sanitize-html':
+ specifier: 2.16.1
+ version: 2.16.1
+
+ packages/trilium-e2e:
+ devDependencies:
+ dotenv:
+ specifier: 17.4.2
+ version: 17.4.2
+
packages/turndown-plugin-gfm:
devDependencies:
happy-dom:
@@@ -9540,12 -9146,8 +9519,12 @@@ packages
resolution: {integrity: sha512-c/c15i26VrJ4IRt5Z89DnIzCGDn9EcebibhAOjw5ibqEHsE1wLUgkPn9RDmNcUKyU87GeaL633nyJ+pplFR2ZQ==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-hjrNztw/VajQwOLsMNT1cbJiH2muO3OROCHnbehc8eY5JyD2gqz4AcMHPqgaOR59DjgUjYAYLeH699g/eWi2jw==}
+ engines: {node: '>=18'}
+
- resolution: {integrity: sha512-qoV+HK2yFl/366t2/Cb3+xxPUo5BuMynomoDmiaZBIdbs+0pYbjfZU+twLhGKp4uCZ/+NbtpVepH5bGCxRyy2g==}
+ resolution: {integrity: sha512-sepffkT8stwnIYbsMBpoCHJuJM5l98FUF2AnE07hfvE0m/qp3R586hw4jF4uadbhvg1ooIdzuu7CsfD2jzCaNA==}
engines: {node: '>=18'}
@@@ -10898,13 -10466,8 +10865,13 @@@
engines: {node: '>= 20'}
hasBin: true
+ resolution: {integrity: sha512-IILJE4Aap/KIGu4ZRCzQcYMxkhumblXnbqfQe+HAD4f982wrRAsJEGKGM653yAioS6g3Yq3yOhjrUebcrtOgRA==}
+ engines: {node: '>= 20'}
+ hasBin: true
+
- resolution: {integrity: sha512-NsmlUYBS/Zg57rgDWMYdnre6OTj4e+qq/JS2ot3KrYLSoHLw+sDu0Nm1ZGpRgYAq6c+b1ekaY5NzVchMCQnzcg==}
+ resolution: {integrity: sha512-7VT90JOkDeaRWpfjOReRGPEKn0ecdARBkDGL+tT1wZY0efPPqkUxLUSmzy/C7TIylQYJC9STISEsCHrqb/7VIA==}
engines: {node: '>= 20'}
hasBin: true
@@@ -12040,6 -11585,14 +12003,10 @@@
resolution: {integrity: sha512-pMMHxBOZKFU6HgAZ4eyGnwXF/EvPGGqUr0MnZ5+99485wwW41kW91A4LOGxSHhgugZmSChL5AlElNdwlNgcnLQ==}
engines: {node: ^10 || ^12 || >=14}
+ resolution: {integrity: sha512-SoSL4+OSEtR99LHFZQiJLkT59C5B1amGO1NzTwj7TT1qCUgUO6hxOvzkOYxD+vMrXBM3XJIKzokoERdqQq/Zmg==}
+ engines: {node: ^10 || ^12 || >=14}
+
- resolution: {integrity: sha512-7a70Nsot+EMX9fFU3064K/kdHWZqGVY+BADLyXc8Dfv+mTLLVl6JzJpPaCZ2kQL9gIJvKXSLMHhqdRRjwQeFtw==}
- engines: {node: ^10 || ^12 || >=14}
-
resolution: {integrity: sha512-b9Eb8h2eVqNE8edvKdwqkrY6O7kAwmI8kcnBv1NScolYJbo59XUF0noFq+lxbC1yN20bmC0WBEbDC5H/7ASb0A==}
engines: {node: '>=14.0.0'}
@@@ -12259,22 -11812,22 +12226,38 @@@
peerDependencies:
react: ^19.2.4
+ resolution: {integrity: sha512-hQipmK4EF0y6RO6tt6WuqnmWpWYEXmQUUzecmMBuNsIgYd3smXcG4GtYPWhvgxn0pqMOItKlEO8H24HCs5hc3g==}
+ peerDependencies:
+ i18next: '>= 26.0.1'
+ react: '>= 16.8.0'
+ react-dom: '*'
+ react-native: '*'
+ typescript: ^5 || ^6
+ peerDependenciesMeta:
+ react-dom:
+ optional: true
+ react-native:
+ optional: true
+ typescript:
+ optional: true
+
+ resolution: {integrity: sha512-rwtPXsb/zwzDafN+gytcjF5YnqGQQIRmCQ6DctBC1VSipRB8GD/MWEVrFP42vjMyuYydxWxM8CZRt+yiNuuoHg==}
+ peerDependencies:
+ i18next: '>= 26.0.10'
+ react: '>= 16.8.0'
+ react-dom: '*'
+ react-native: '*'
+ typescript: ^5 || ^6
+ peerDependenciesMeta:
+ react-dom:
+ optional: true
+ react-native:
+ optional: true
+ typescript:
+ optional: true
+
resolution: {integrity: sha512-mmRvA9aKP7zu9kVfP1AX1egX8tFlnE3DDXq92z0JTZezfOpmeQBzr77O1+mTV54OOmn+M2t6c5kFD5VnuFoM7A==}
peerDependencies:
@@@ -17155,12 -16596,6 +17124,12 @@@ snapshots
'@excalidraw/[email protected]': {}
+ '@excalidraw/[email protected]':
+ dependencies:
+ '@excalidraw/markdown-to-text': 0.1.2
- mermaid: 11.14.0
++ mermaid: 11.15.0
+ nanoid: 5.1.7
+
'@excalidraw/[email protected]':
dependencies:
'@excalidraw/markdown-to-text': 0.1.2
@@@ -25198,9 -24498,7 +25154,9 @@@
+
dependencies:
@@@ -26663,9 -25929,7 +26605,9 @@@
+
@@@ -28273,18 -27521,7 +28215,18 @@@
react: 19.2.4
scheduler: 0.27.0
+ dependencies:
+ '@babel/runtime': 7.29.2
+ html-parse-stringify: 3.0.1
- i18next: 26.0.5([email protected])
++ i18next: 26.0.8([email protected])
+ react: 19.2.4
+ use-sync-external-store: 1.6.0([email protected])
+ optionalDependencies:
+ react-dom: 19.2.4([email protected])
+ typescript: 6.0.3
+
dependencies:
'@babel/runtime': 7.29.2
html-parse-stringify: 3.0.1