Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(import): preserve source order under an inherited #newNotesOnTop
Elian Doran541528a1cb1c
diff --git a/apps/server/src/services/import/onenote/importer.spec.ts b/apps/server/src/services/import/onenote/importer.spec.tsindex 509954dead..f94763a970 100644--- a/apps/server/src/services/import/onenote/importer.spec.ts+++ b/apps/server/src/services/import/onenote/importer.spec.ts@@ -198,6 +198,47 @@ describe("importSelection (real DB)", () => {expect(content).toContain(`href="#root/${badNote?.noteId}"`);});+ it("preserves the OneNote page order even when #newNotesOnTop is inherited onto the target", async () => {+ graphMock.listPages.mockResolvedValue([+ { id: "1-ord-a", title: "Order Page A", level: 0 },+ { id: "1-ord-b", title: "Order Page B", level: 0 },+ { id: "1-ord-c", title: "Order Page C", level: 0 }+ ]);+ graphMock.getPageContent.mockResolvedValue({ html: "<p>hi</p>", inkml: "" });++ // The label the user reported: inheritable on the import target, so every note created during the+ // import (root, section, pages) sees it. Without explicit positions it would invert the page order.+ const parent = cls.init(() => {+ const note = noteService.createNewNote({+ parentNoteId: "root",+ title: "order parent",+ content: "",+ type: "text",+ mime: "text/html"+ }).note;+ note.addLabel("newNotesOnTop", "", true);+ return note;+ });++ await cls.init(() => importSelection({+ getAccessToken: () => Promise.resolve("token"),+ parentNoteId: parent.noteId,+ sections: [{ id: "sec-order", title: "Order Section", groupPath: [], notebookId: "nb-order", notebookTitle: "Order Notebook" }],+ taskId: "task-order"+ }));++ // Order lives in notePosition (becca's in-memory `children` is insertion order); the tree sorts+ // by it the way the client does. With the newNotesOnTop default each page would land above the+ // last (positions -10, -20, -30 → C, B, A); the fix's explicit ascending positions keep A, B, C.+ const sectionNote = Object.values(becca.notes).find((note) => note.title === "Order Section");+ const orderedTitles = sectionNote+ ?.getChildBranches()+ .slice()+ .sort((a, b) => a.notePosition - b.notePosition)+ .map((branch) => branch.getNote().title);+ expect(orderedTitles).toEqual(["Order Page A", "Order Page B", "Order Page C"]);+ });+it("aborts the import when too many consecutive pages fail (systemic failure)", async () => {graphMock.listPages.mockResolvedValue(Array.from({ length: 8 }, (_, i) => ({ id: `1-cb${i}`, title: `CB Page ${i}`, level: 0 }))diff --git a/apps/server/src/services/import/onenote/importer.ts b/apps/server/src/services/import/onenote/importer.tsindex 1f0087dfde..a4d176f48f 100644--- a/apps/server/src/services/import/onenote/importer.ts+++ b/apps/server/src/services/import/onenote/importer.ts@@ -6,7 +6,7 @@*/import type { OneNoteFolderRef, OneNoteSectionSelection } from "@triliumnext/commons";-import { becca, binary_utils, type BNote, date_utils, getLog, imageService, note_service as noteService, protected_session as protectedSession, TaskContext } from "@triliumnext/core";+import { becca, binary_utils, type BNote, cls, date_utils, getLog, imageService, note_service as noteService, protected_session as protectedSession, TaskContext } from "@triliumnext/core";import { t } from "i18next";import { parse } from "node-html-parser";@@ -181,6 +181,10 @@ function createNotes(parentNoteId: string, sections: FetchedSection[], debug: boconst rootNote = createFolder(parentNoteId, t("onenote_import.root-title"));rootNote.addLabel("iconClass", "bx bx-import");+ // Root created; keep the OneNote notebooks/sections/pages in their display order under an inherited+ // #newNotesOnTop (the root above still floats to the top of the target). See cls.setImportOrderPreserved.+ cls.setImportOrderPreserved(true);+// Created page notes with their content-so-far (resources/ink applied), plus a map from each// page's OneNote page-id GUID to its imported note (and title) — both feed the link-resolution pass.const createdPages: { note: BNote; original: string; content: string; page: FetchedPage }[] = [];diff --git a/packages/trilium-core/src/services/context.ts b/packages/trilium-core/src/services/context.tsindex fefe0f6bde..2282910d91 100644--- a/packages/trilium-core/src/services/context.ts+++ b/packages/trilium-core/src/services/context.ts@@ -73,6 +73,24 @@ export function isMigrationRunning() {return !!getContext().get("migrationRunning");}+/**+ * While an import materializes its content tree, a `#newNotesOnTop` label inherited onto the import target+ * would otherwise make {@link getNewNotePosition} insert each created note *above* the previous one, silently+ * reversing the source order. Importers turn this on to keep imported content in its original order.+ *+ * It is turned on deliberately *after* an importer has created its own top-level root note, so that single+ * root note still honours `newNotesOnTop` and floats to the top of the target (the reason users set the+ * label) — only the content *underneath* it is order-preserved. The flag lives for the import's CLS context+ * only, so it never needs clearing (each import runs in its own context, like `disableEntityEvents`).+ */+export function setImportOrderPreserved(preserved: boolean) {+ getContext().set("importOrderPreserved", !!preserved);+}++export function isImportOrderPreserved() {+ return !!getContext().get("importOrderPreserved");+}+export function putEntityChange(entityChange: EntityChange) {if (getContext().get("ignoreEntityChangeIds")) {return;diff --git a/packages/trilium-core/src/services/import/anytype/importer.ts b/packages/trilium-core/src/services/import/anytype/importer.tsindex b87129da54..bef0f58512 100644--- a/packages/trilium-core/src/services/import/anytype/importer.ts+++ b/packages/trilium-core/src/services/import/anytype/importer.ts@@ -31,6 +31,7 @@ import { parse } from "node-html-parser";import type BNote from "../../../becca/entities/bnote.js";import cloningService from "../../cloning.js";+import * as cls from "../../context.js";import imageService from "../../image.js";import noteService from "../../notes.js";import protectedSessionService from "../../protected_session.js";@@ -329,6 +330,10 @@ function createNotes(importRootNote: BNote, pages: ParsedObject[], targets: Map<}rootNote.addLabel("iconClass", "bx bx-import");+ // Root created; keep the imported pages/collections in order under an inherited #newNotesOnTop (the root+ // above still floats to the top of the target). See cls.setImportOrderPreserved.+ cls.setImportOrderPreserved(true);+// Each member's primary parent is the first collection that lists it (a collection itself stays at the// root, so it's never reparented — it's cloned into an owning collection by the membership pass below).const collectionPageIds = new Set(pages.filter((page) => page.collection).map((page) => page.id));diff --git a/packages/trilium-core/src/services/import/enex.ts b/packages/trilium-core/src/services/import/enex.tsindex ac0d3fc246..004b368fec 100644--- a/packages/trilium-core/src/services/import/enex.ts+++ b/packages/trilium-core/src/services/import/enex.ts@@ -1,6 +1,7 @@import type { AttributeType } from "@triliumnext/commons";import type BNote from "../../becca/entities/bnote.js";+import * as cls from "../context.js";import * as utils from "../utils/index.js";import imageService from "../image.js";import { getLog } from "../log.js";@@ -74,6 +75,10 @@ async function importEnex(taskContext: TaskContext<"importNotes">, file: File, pisProtected: parentNote.isProtected && protectedSessionService.isProtectedSessionAvailable()}).note;+ // Root created; keep the imported notes in their ENEX order under an inherited #newNotesOnTop (the root+ // above still floats to the top of the target). See cls.setImportOrderPreserved.+ cls.setImportOrderPreserved(true);+function extractContent(content: string, tasks: EnexTask[] = []) {const openingNoteIndex = content.indexOf("<en-note>");diff --git a/packages/trilium-core/src/services/import/import_order.spec.ts b/packages/trilium-core/src/services/import/import_order.spec.tsnew file mode 100644index 0000000000..b58ed3ad22--- /dev/null+++ b/packages/trilium-core/src/services/import/import_order.spec.ts@@ -0,0 +1,93 @@+import { beforeAll, describe, expect, it } from "vitest";++import becca from "../../becca/becca.js";+import { getContext } from "../context.js";+import noteService from "../notes.js";+import sql_init from "../sql_init.js";+import TaskContext from "../task_context.js";+import type { File } from "./common.js";+import importFile, { type ImportOptions } from "./dispatch.js";++const options: ImportOptions = {+ safeImport: true,+ shrinkImages: false,+ textImportedAsText: true,+ codeImportedAsCode: true,+ spreadsheetImportedAsSpreadsheet: true,+ explodeArchives: true, // required so a `.enex` routes to the ENEX importer rather than being kept as a single file+ replaceUnderscoresWithSpaces: false+};++/** An ENEX export whose notes appear in a fixed document order; the importer creates them in that order. */+function orderedEnex(titles: string[]): string {+ const notes = titles+ .map(+ (title) => ` <note>+ <title>${title}</title>+ <created>20200101T000000Z</created>+ <content><![CDATA[<?xml version="1.0" encoding="UTF-8" standalone="no"?>+<!DOCTYPE en-note SYSTEM "http://xml.evernote.com/pub/enml2.dtd"><en-note><div>${title}</div></en-note>]]></content>+ </note>`+ )+ .join("\n");+ return `<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE en-export SYSTEM "http://xml.evernote.com/pub/evernote-export4.dtd">+<en-export export-date="20260101T000000Z" application="Evernote" version="11">+${notes}+</en-export>`;+}++describe("import ordering (via the import dispatcher)", () => {+ beforeAll(async () => {+ sql_init.initializeDb();+ await sql_init.dbReady;+ });++ // Regression guard for the whole import path — not one importer. A `#newNotesOnTop` label inherited onto+ // the import target (the user's own root, say) makes createNewNote insert each new note *above* the last,+ // which silently reverses every importer's output. ENEX stands in here for any importer that builds its+ // tree with plain createNewNote calls (enex, keep, obsidian, notion, anytype, opml, onenote); only the+ // generic zip importer is immune, because it restores explicit positions from the export metadata.+ it("preserves the imported note order even when #newNotesOnTop is inherited onto the target", async () => {+ const enex = orderedEnex(["Order Note A", "Order Note B", "Order Note C"]);++ const orderedTitles = await new Promise<(string | undefined)[]>((resolve, reject) => {+ void getContext().init(async () => {+ try {+ // The label the user reported: inheritable on the import target, so every note the import+ // creates below it (the ENEX root and its children) inherits it.+ const parent = noteService.createNewNote({+ parentNoteId: "root",+ title: "import-order target",+ content: "",+ type: "text",+ mime: "text/html"+ }).note;+ parent.addLabel("newNotesOnTop", "", true);++ const taskContext = TaskContext.getInstance("import-order", "importNotes", options);+ const file: File = { originalname: "Ordered.enex", mimetype: "application/enex+xml", buffer: Buffer.from(enex) };+ const importRoot = await importFile(taskContext, file, parent, options);+ if (!importRoot || Array.isArray(importRoot)) {+ throw new Error("ENEX import did not return a root note");+ }++ // Order lives in notePosition (becca's in-memory `children` is insertion order); the tree+ // sorts by it the way the client renders it. Without the fix each note lands above the last+ // (positions -10, -20, -30 → C, B, A); the fix keeps the ENEX document order A, B, C.+ const titles = becca+ .getNoteOrThrow(importRoot.noteId)+ .getChildBranches()+ .slice()+ .sort((a, b) => a.notePosition - b.notePosition)+ .map((branch) => branch.getNote().title);+ resolve(titles);+ } catch (e) {+ reject(e);+ }+ });+ });++ expect(orderedTitles).toEqual(["Order Note A", "Order Note B", "Order Note C"]);+ });+});diff --git a/packages/trilium-core/src/services/import/keep/importer.ts b/packages/trilium-core/src/services/import/keep/importer.tsindex d2c06a4e2f..d5c0561b26 100644--- a/packages/trilium-core/src/services/import/keep/importer.ts+++ b/packages/trilium-core/src/services/import/keep/importer.ts@@ -16,6 +16,7 @@import { t } from "i18next";import type BNote from "../../../becca/entities/bnote.js";+import * as cls from "../../context.js";import imageService from "../../image.js";import noteService from "../../notes.js";import protectedSessionService from "../../protected_session.js";@@ -218,6 +219,10 @@ function createNotes(importRootNote: BNote, notes: ParsedNote[], binaries: Map<sconst rootNote = noteService.createNewNote({ parentNoteId: importRootNote.noteId, title: t("keep_import.root-title"), content: "", type: "text", mime: "text/html", isProtected }).note;rootNote.addLabel("iconClass", "bx bx-import");+ // Root created; keep the imported notes in export order under an inherited #newNotesOnTop (the root above+ // still floats to the top of the target). See cls.setImportOrderPreserved.+ cls.setImportOrderPreserved(true);+for (const parsed of notes) {const { note } = noteService.createNewNote({parentNoteId: rootNote.noteId,diff --git a/packages/trilium-core/src/services/import/notion/importer.ts b/packages/trilium-core/src/services/import/notion/importer.tsindex 29feef86f0..02d542b579 100644--- a/packages/trilium-core/src/services/import/notion/importer.ts+++ b/packages/trilium-core/src/services/import/notion/importer.ts@@ -18,6 +18,7 @@ import { t } from "i18next";import { type HTMLElement, parse } from "node-html-parser";import type BNote from "../../../becca/entities/bnote.js";+import * as cls from "../../context.js";import imageService from "../../image.js";import noteService from "../../notes.js";import protectedSessionService from "../../protected_session.js";@@ -196,6 +197,10 @@ function createNotes(importRootNote: BNote, pages: ParsedPage[], resources: Map<const rootNote = noteService.createNewNote({ parentNoteId: importRootNote.noteId, title: t("notion_import.root-title"), content: "", type: "text", mime: "text/html", isProtected }).note;rootNote.addLabel("iconClass", "bx bx-import");+ // Root created; keep the imported pages in export order under an inherited #newNotesOnTop (the root above+ // still floats to the top of the target). See cls.setImportOrderPreserved.+ cls.setImportOrderPreserved(true);+const noteByFolder = new Map<string, BNote>();const targetByPageId = new Map<string, LinkTarget>();const created: { note: BNote; content: string; page: ParsedPage }[] = [];diff --git a/packages/trilium-core/src/services/import/obsidian/importer.ts b/packages/trilium-core/src/services/import/obsidian/importer.tsindex 4541805376..6e147808c9 100644--- a/packages/trilium-core/src/services/import/obsidian/importer.ts+++ b/packages/trilium-core/src/services/import/obsidian/importer.ts@@ -35,6 +35,7 @@import { t } from "i18next";import type BNote from "../../../becca/entities/bnote.js";+import * as cls from "../../context.js";import noteService from "../../notes.js";import protectedSessionService from "../../protected_session.js";import type TaskContext from "../../task_context.js";@@ -131,6 +132,10 @@ function createNotes(importRootNote: BNote, notes: VaultNote[], attachments: Mapconst rootNote = noteService.createNewNote({ parentNoteId: importRootNote.noteId, title: rootTitle, content: "", type: "text", mime: "text/html", isProtected }).note;rootNote.addLabel("iconClass", "bx bx-import");+ // Root created; keep the vault's notes/folders in order under an inherited #newNotesOnTop (the root above+ // still floats to the top of the target). See cls.setImportOrderPreserved.+ cls.setImportOrderPreserved(true);+const attachmentIndex = buildAttachmentIndex(attachments);const shrinkImages = !!taskContext.data?.shrinkImages;// Folder path (POSIX) -> its container note. The empty path maps to the import root.diff --git a/packages/trilium-core/src/services/import/opml.ts b/packages/trilium-core/src/services/import/opml.tsindex 370d150f5c..f094585f5a 100644--- a/packages/trilium-core/src/services/import/opml.ts+++ b/packages/trilium-core/src/services/import/opml.ts@@ -1,6 +1,7 @@import xml2js from "xml2js";import type BNote from "../../becca/entities/bnote.js";+import * as cls from "../context.js";import noteService from "../../services/notes.js";import protectedSessionService from "../protected_session.js";import type TaskContext from "../task_context.js";@@ -85,6 +86,11 @@ async function importOpml(taskContext: TaskContext<"importNotes">, fileBuffer: sconst outlines = xml.opml.body[0].outline || [];let returnNote: BNote | null = null;+ // Unlike the other importers, OPML has no single wrapper root — its top-level outlines are imported+ // directly under the target. So order-preservation covers the whole import (including those top-level+ // outlines), otherwise an inherited #newNotesOnTop would reverse them. See cls.setImportOrderPreserved.+ cls.setImportOrderPreserved(true);+for (const outline of outlines) {const note = importOutline(outline, parentNote.noteId);diff --git a/packages/trilium-core/src/services/import/zip.spec.ts b/packages/trilium-core/src/services/import/zip.spec.tsindex e1a65b256e..28397c24e5 100644--- a/packages/trilium-core/src/services/import/zip.spec.ts+++ b/packages/trilium-core/src/services/import/zip.spec.ts@@ -8,6 +8,7 @@ import { PassThrough } from "stream";import zip, { removeTriliumTags } from "./zip.js";import becca from "../../becca/becca.js";import BNote from "../../becca/entities/bnote.js";+import noteService from "../notes.js";import TaskContext from "../task_context.js";import sql_init from "../sql_init.js";import { trimIndentation } from "@triliumnext/commons";@@ -472,6 +473,37 @@ describe("processNoteContent", () => {expect(becca.getBranchFromChildAndParent("root", "root")).toBeFalsy();});+ it("keeps a folder zip's entries in archive order under an inherited #newNotesOnTop (no position metadata)", async () => {+ // A plain folder zip carries no !!!meta.json, so its notes have no stored positions and fall back to+ // getNewNotePosition. With #newNotesOnTop inherited onto the target that default would reverse them+ // (each note inserted above the last); the import must preserve the archive order instead.+ const zipBuffer = await createZipBuffer({ "a.txt": "first", "b.txt": "second", "c.txt": "third" });++ const orderedTitles = await new Promise<(string | undefined)[]>((resolve, reject) => {+ void getContext().init(async () => {+ try {+ const parent = noteService.createNewNote({ parentNoteId: "root", title: "zip-order target", content: "", type: "text", mime: "text/html" }).note;+ parent.addLabel("newNotesOnTop", "", true);++ const taskContext = TaskContext.getInstance("import-zip-order", "importNotes", { textImportedAsText: true });+ await zip.importZip(taskContext, zipBuffer, parent);++ // Sort by notePosition the way the tree renders it (becca's `children` is insertion order).+ const titles = parent+ .getChildBranches()+ .slice()+ .sort((a, b) => a.notePosition - b.notePosition)+ .map((branch) => branch.getNote().title);+ resolve(titles);+ } catch (e) {+ reject(e);+ }+ });+ });++ expect(orderedTitles).toEqual(["a.txt", "b.txt", "c.txt"]);+ });+it("imports a CSV entry as a plain file note when the spreadsheet option is off", async () => {const zipBuffer = await createZipBuffer({ "csv_as_file_sample.csv": "a,b\r\n1,2" });const { rootNote } = await testImportBuffer(zipBuffer, "import-csv-off", { spreadsheetImportedAsSpreadsheet: false });diff --git a/packages/trilium-core/src/services/import/zip.ts b/packages/trilium-core/src/services/import/zip.tsindex 413439505c..6bf3c3689d 100644--- a/packages/trilium-core/src/services/import/zip.ts+++ b/packages/trilium-core/src/services/import/zip.ts@@ -7,6 +7,7 @@ import BAttachment from "../../becca/entities/battachment.js";import BAttribute from "../../becca/entities/battribute.js";import BBranch from "../../becca/entities/bbranch.js";import type BNote from "../../becca/entities/bnote.js";+import * as cls from "../context.js";import attributeService from "../../services/attributes.js";import { getLog } from "../../services/log.js";import noteService from "../../services/notes.js";@@ -75,6 +76,19 @@ async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSoulet topLevelPath = "";const createdNoteIds = new Set<string>();+ // Records the first created note as the de-facto import root (its position is deliberately left to float+ // per any inherited #newNotesOnTop — see the notePosition logic below). Once it exists, order-preservation+ // is turned on so the remaining entries keep their archive order: this only matters for a non-Trilium+ // folder zip, which carries no position metadata, since a Trilium export restores explicit positions for+ // every non-root note and so never consults getNewNotePosition. See cls.setImportOrderPreserved.+ function trackFirstNote(note: BNote) {+ if (firstNote) {+ return;+ }+ firstNote = note;+ cls.setImportOrderPreserved(true);+ }+function getNewNoteId(origNoteId: string) {if (!origNoteId.trim()) {// this probably shouldn't happen, but still good to have this precaution@@ -305,7 +319,7 @@ async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSousaveAttributes(note, noteMeta);- firstNote = firstNote || note;+ trackFirstNote(note);return noteId;}@@ -644,7 +658,7 @@ async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSou}if (opts?.preserveIds || isImportRootNote) {- firstNote = firstNote || note;+ trackFirstNote(note);}} else {if (detectedType as string === "geoMap") {@@ -691,7 +705,7 @@ async function importZip(taskContext: TaskContext<"importNotes">, source: ZipSounote.addLabel(attribute.name, attribute.value);}- firstNote = firstNote || note;+ trackFirstNote(note);}if (!noteMeta && (type === "file" || type === "image")) {diff --git a/packages/trilium-core/src/services/notes.ts b/packages/trilium-core/src/services/notes.tsindex 6492fd20a7..bc91299f2d 100644--- a/packages/trilium-core/src/services/notes.ts+++ b/packages/trilium-core/src/services/notes.ts@@ -74,7 +74,10 @@ export interface NoteParams {}function getNewNotePosition(parentNote: BNote) {- if (parentNote.isLabelTruthy("newNotesOnTop")) {+ // An import that preserves its source order suspends newNotesOnTop for the content it creates, so an+ // inherited `#newNotesOnTop` on the import target doesn't reverse the imported tree (see+ // {@link cls.setImportOrderPreserved}).+ if (!cls.isImportOrderPreserved() && parentNote.isLabelTruthy("newNotesOnTop")) {const minNotePos = parentNote.getChildBranches().filter((branch) => branch?.noteId !== "_hidden") // has "always last" note position