Skip to content

Build your personal knowledge base with Trilium Notes

feat(import): nest OneNote section groups as folders

Elian Doran26736993c397
diff --git a/apps/client/src/services/onenote_import.spec.ts b/apps/client/src/services/onenote_import.spec.ts
new file mode 100644
index 0000000000..81cf02fdb3
--- /dev/null
+++ b/apps/client/src/services/onenote_import.spec.ts
@@ -0,0 +1,64 @@
+import { describe, expect, it } from "vitest";
+
+import { buildSectionSelections, type OneNoteNotebook } from "./onenote_import.js";
+
+const NOTEBOOKS: OneNoteNotebook[] = [
+ {
+ id: "nb1",
+ title: "Notebook 1",
+ createdDateTime: "2020-01-01T00:00:00Z",
+ lastModifiedDateTime: "2020-02-01T00:00:00Z",
+ sections: [{ id: "s1", title: "Direct section" }],
+ sectionGroups: [
+ {
+ id: "g1",
+ title: "Group A",
+ createdDateTime: "2020-03-01T00:00:00Z",
+ lastModifiedDateTime: "2020-04-01T00:00:00Z",
+ sections: [{ id: "s2", title: "In group A" }],
+ sectionGroups: [
+ {
+ id: "g2",
+ title: "Subgroup B",
+ sections: [{ id: "s3", title: "In subgroup B" }],
+ sectionGroups: []
+ }
+ ]
+ }
+ ]
+ }
+];
+
+describe("buildSectionSelections", () => {
+ it("returns a top-level section with an empty group path and its notebook metadata", () => {
+ const [selection, ...rest] = buildSectionSelections(NOTEBOOKS, new Set(["s1"]));
+ expect(rest).toHaveLength(0);
+ expect(selection).toMatchObject({
+ id: "s1",
+ title: "Direct section",
+ groupPath: [],
+ notebookId: "nb1",
+ notebookTitle: "Notebook 1",
+ notebookCreatedDateTime: "2020-01-01T00:00:00Z",
+ notebookLastModifiedDateTime: "2020-02-01T00:00:00Z"
+ });
+ });
+
+ it("carries the section-group ancestry (outermost first) for nested sections", () => {
+ const inGroup = buildSectionSelections(NOTEBOOKS, new Set(["s2"]));
+ expect(inGroup[0].groupPath).toEqual([
+ { id: "g1", title: "Group A", createdDateTime: "2020-03-01T00:00:00Z", lastModifiedDateTime: "2020-04-01T00:00:00Z" }
+ ]);
+
+ const inSubgroup = buildSectionSelections(NOTEBOOKS, new Set(["s3"]));
+ expect(inSubgroup[0].groupPath.map((g) => g.id)).toEqual(["g1", "g2"]);
+ });
+
+ it("emits selected sections in tree order and ignores unselected ones", () => {
+ const selections = buildSectionSelections(NOTEBOOKS, new Set(["s3", "s1"]));
+ expect(selections.map((s) => s.id)).toEqual(["s1", "s3"]);
+
+ expect(buildSectionSelections(NOTEBOOKS, new Set())).toEqual([]);
+ expect(buildSectionSelections(NOTEBOOKS, new Set(["does-not-exist"]))).toEqual([]);
+ });
+});
diff --git a/apps/client/src/services/onenote_import.ts b/apps/client/src/services/onenote_import.ts
index 97ceb51994..5ea2af1ba5 100644
--- a/apps/client/src/services/onenote_import.ts
+++ b/apps/client/src/services/onenote_import.ts
@@ -22,12 +22,30 @@ export interface OneNoteSection {
lastModifiedDateTime?: string;
}
+export interface OneNoteSectionGroup {
+ id: string;
+ title: string;
+ createdDateTime?: string;
+ lastModifiedDateTime?: string;
+ sections: OneNoteSection[];
+ sectionGroups: OneNoteSectionGroup[];
+}
+
export interface OneNoteNotebook {
id: string;
title: string;
createdDateTime?: string;
lastModifiedDateTime?: string;
sections: OneNoteSection[];
+ sectionGroups: OneNoteSectionGroup[];
+}
+
+/** Mirrors `OneNoteFolderRef` on the server. */
+export interface OneNoteFolderRef {
+ id: string;
+ title: string;
+ createdDateTime?: string;
+ lastModifiedDateTime?: string;
}
/** Mirrors `SectionSelection` on the server. */
@@ -36,6 +54,7 @@ export interface OneNoteSectionSelection {
title: string;
createdDateTime?: string;
lastModifiedDateTime?: string;
+ groupPath: OneNoteFolderRef[];
notebookId: string;
notebookTitle: string;
notebookCreatedDateTime?: string;
@@ -72,3 +91,40 @@ export default {
getNotebooks,
runImport
};
+
+/**
+ * Flattens the selected sections out of the notebook tree, tagging each with its notebook and the
+ * section-group path (notebook root → the section's immediate group) the server needs to recreate the
+ * folder nesting. Sections are emitted in tree order; section groups contribute structure only and are
+ * never selectable themselves.
+ */
+export function buildSectionSelections(notebooks: OneNoteNotebook[], selectedIds: Set<string>): OneNoteSectionSelection[] {
+ const selections: OneNoteSectionSelection[] = [];
+
+ const visit = (container: OneNoteNotebook | OneNoteSectionGroup, notebook: OneNoteNotebook, groupPath: OneNoteFolderRef[]) => {
+ for (const section of container.sections) {
+ if (selectedIds.has(section.id)) {
+ selections.push({
+ id: section.id,
+ title: section.title,
+ createdDateTime: section.createdDateTime,
+ lastModifiedDateTime: section.lastModifiedDateTime,
+ groupPath,
+ notebookId: notebook.id,
+ notebookTitle: notebook.title,
+ notebookCreatedDateTime: notebook.createdDateTime,
+ notebookLastModifiedDateTime: notebook.lastModifiedDateTime
+ });
+ }
+ }
+ for (const group of container.sectionGroups) {
+ visit(group, notebook, [...groupPath, { id: group.id, title: group.title, createdDateTime: group.createdDateTime, lastModifiedDateTime: group.lastModifiedDateTime }]);
+ }
+ };
+
+ for (const notebook of notebooks) {
+ visit(notebook, notebook, []);
+ }
+
+ return selections;
+}
diff --git a/apps/client/src/widgets/dialogs/import_provider.css b/apps/client/src/widgets/dialogs/import_provider.css
index dda7c48257..2d538f00be 100644
--- a/apps/client/src/widgets/dialogs/import_provider.css
+++ b/apps/client/src/widgets/dialogs/import_provider.css
@@ -70,6 +70,21 @@
gap: 0.25em;
}
+ .onenote-section-group {
+ display: flex;
+ flex-direction: column;
+ gap: 0.25em;
+ padding-left: 1.25em;
+ border-left: 1px solid var(--main-border-color);
+ margin-left: 0.25em;
+ }
+
+ .onenote-section-group-title {
+ color: var(--muted-text-color);
+ font-size: 0.9em;
+ font-weight: bold;
+ }
+
.onenote-actions {
display: flex;
justify-content: flex-end;
diff --git a/apps/client/src/widgets/dialogs/import_providers/onenote.tsx b/apps/client/src/widgets/dialogs/import_providers/onenote.tsx
index 0fcc477a8d..2323a2dfdc 100644
--- a/apps/client/src/widgets/dialogs/import_providers/onenote.tsx
+++ b/apps/client/src/widgets/dialogs/import_providers/onenote.tsx
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useRef, useState } from "preact/hooks";
import { t } from "../../../services/i18n.js";
-import onenoteImport, { type OneNoteAccount, type OneNoteNotebook, type OneNoteSectionSelection } from "../../../services/onenote_import.js";
+import onenoteImport, { buildSectionSelections, type OneNoteAccount, type OneNoteNotebook, type OneNoteSectionGroup } from "../../../services/onenote_import.js";
import toast from "../../../services/toast.js";
import { isElectron, randomString } from "../../../services/utils.js";
import Button from "../../react/Button.js";
@@ -97,23 +97,7 @@ function OneNotePanel({ parentNoteId, closeDialog }: ImportProviderPanelProps) {
}, []);
const doImport = useCallback(async () => {
- const sections: OneNoteSectionSelection[] = [];
- for (const notebook of notebooks) {
- for (const section of notebook.sections) {
- if (selectedIds.has(section.id)) {
- sections.push({
- id: section.id,
- title: section.title,
- createdDateTime: section.createdDateTime,
- lastModifiedDateTime: section.lastModifiedDateTime,
- notebookId: notebook.id,
- notebookTitle: notebook.title,
- notebookCreatedDateTime: notebook.createdDateTime,
- notebookLastModifiedDateTime: notebook.lastModifiedDateTime
- });
- }
- }
- }
+ const sections = buildSectionSelections(notebooks, selectedIds);
if (!sections.length) {
return;
}
@@ -160,15 +144,7 @@ function OneNotePanel({ parentNoteId, closeDialog }: ImportProviderPanelProps) {
{notebooks.map((notebook) => (
<div className="onenote-notebook" key={notebook.id}>
<strong>{notebook.title}</strong>
- {notebook.sections.map((section) => (
- <FormCheckbox
- key={section.id}
- name={`onenote-section-${section.id}`}
- label={section.title}
- currentValue={selectedIds.has(section.id)}
- onChange={(checked) => toggleSection(section.id, checked)}
- />
- ))}
+ <SectionTree container={notebook} selectedIds={selectedIds} onToggle={toggleSection} />
</div>
))}
</div>
@@ -194,6 +170,34 @@ function OneNotePanel({ parentNoteId, closeDialog }: ImportProviderPanelProps) {
);
}
+/** Renders a notebook's (or section group's) sections as checkboxes and recurses into nested section
+ * groups, so the OneNote folder structure is mirrored in the picker. */
+function SectionTree({ container, selectedIds, onToggle }: {
+ container: OneNoteNotebook | OneNoteSectionGroup;
+ selectedIds: Set<string>;
+ onToggle: (id: string, checked: boolean) => void;
+}) {
+ return (
+ <>
+ {container.sections.map((section) => (
+ <FormCheckbox
+ key={section.id}
+ name={`onenote-section-${section.id}`}
+ label={section.title}
+ currentValue={selectedIds.has(section.id)}
+ onChange={(checked) => onToggle(section.id, checked)}
+ />
+ ))}
+ {container.sectionGroups.map((group) => (
+ <div className="onenote-section-group" key={group.id}>
+ <span className="onenote-section-group-title">{group.title}</span>
+ <SectionTree container={group} selectedIds={selectedIds} onToggle={onToggle} />
+ </div>
+ ))}
+ </>
+ );
+}
+
const provider: ImportProvider = {
id: "onenote",
name: t("onenote_import.name"),
diff --git a/apps/server/src/services/import/onenote/graph.ts b/apps/server/src/services/import/onenote/graph.ts
index 563d504528..a11b4bbed1 100644
--- a/apps/server/src/services/import/onenote/graph.ts
+++ b/apps/server/src/services/import/onenote/graph.ts
@@ -21,12 +21,22 @@ export interface OneNoteSection {
lastModifiedDateTime?: string;
}
+export interface OneNoteSectionGroup {
+ id: string;
+ title: string;
+ createdDateTime?: string;
+ lastModifiedDateTime?: string;
+ sections: OneNoteSection[];
+ sectionGroups: OneNoteSectionGroup[];
+}
+
export interface OneNoteNotebook {
id: string;
title: string;
createdDateTime?: string;
lastModifiedDateTime?: string;
sections: OneNoteSection[];
+ sectionGroups: OneNoteSectionGroup[];
}
export interface OneNotePage {
@@ -49,8 +59,9 @@ export async function getAccount(accessToken: string): Promise<GraphAccount> {
}
/**
- * Returns the notebooks with all of their sections, including those nested inside section groups
- * (flattened with a "Group / Subgroup / Section" title).
+ * Returns the notebooks with their direct sections and a tree of section groups — each group carrying
+ * its own sections and nested groups — mirroring the OneNote structure so the importer can recreate it
+ * as nested folders.
*
* The initial call expands each notebook's sections and whether it has any section groups, so the
* common case (no section groups) is a single round-trip. Only notebooks/groups that actually contain
@@ -62,38 +73,40 @@ export async function listNotebooks(accessToken: string): Promise<OneNoteNoteboo
const notebooks = await graphGetAll<RawNotebook>(accessToken, url);
return Promise.all(
- notebooks.map(async (notebook) => {
- const direct = (notebook.sections ?? []).map((s) => ({ id: s.id, title: s.displayName, createdDateTime: s.createdDateTime, lastModifiedDateTime: s.lastModifiedDateTime }));
- const grouped = notebook.sectionGroups?.length && notebook.sectionGroupsUrl ? await sectionsFromSectionGroups(accessToken, notebook.sectionGroupsUrl, "") : [];
- return {
- id: notebook.id,
- title: notebook.displayName,
- createdDateTime: notebook.createdDateTime,
- lastModifiedDateTime: notebook.lastModifiedDateTime,
- sections: [...direct, ...grouped]
- };
- })
+ notebooks.map(async (notebook) => ({
+ id: notebook.id,
+ title: notebook.displayName,
+ createdDateTime: notebook.createdDateTime,
+ lastModifiedDateTime: notebook.lastModifiedDateTime,
+ sections: mapSections(notebook.sections),
+ sectionGroups: notebook.sectionGroups?.length && notebook.sectionGroupsUrl ? await fetchSectionGroups(accessToken, notebook.sectionGroupsUrl) : []
+ }))
);
}
/**
- * Fetches the section groups under `sectionGroupsUrl` (a notebook's or section group's link) and
- * returns their sections, recursing into nested groups. Sibling groups are fetched in parallel, and a
- * further round-trip happens only for groups that actually have children.
+ * Fetches the section groups under `sectionGroupsUrl` (a notebook's or section group's link) as a tree,
+ * each group carrying its own sections and nested groups. Sibling groups are fetched in parallel, and a
+ * further round-trip happens only for groups that actually have nested groups.
*/
-async function sectionsFromSectionGroups(accessToken: string, sectionGroupsUrl: string, prefix: string): Promise<OneNoteSection[]> {
- const url = appendQuery(sectionGroupsUrl, "$select=id,displayName,sectionGroupsUrl&$expand=sections($select=id,displayName,createdDateTime,lastModifiedDateTime),sectionGroups($select=id)");
+async function fetchSectionGroups(accessToken: string, sectionGroupsUrl: string): Promise<OneNoteSectionGroup[]> {
+ const url = appendQuery(sectionGroupsUrl, "$select=id,displayName,createdDateTime,lastModifiedDateTime,sectionGroupsUrl&$expand=sections($select=id,displayName,createdDateTime,lastModifiedDateTime),sectionGroups($select=id)");
const groups = await graphGetAll<RawSectionGroup>(accessToken, url);
- const perGroup = await Promise.all(
- groups.map(async (group) => {
- const path = prefix ? `${prefix} / ${group.displayName}` : group.displayName;
- const direct = (group.sections ?? []).map((s) => ({ id: s.id, title: `${path} / ${s.displayName}`, createdDateTime: s.createdDateTime, lastModifiedDateTime: s.lastModifiedDateTime }));
- const nested = group.sectionGroups?.length && group.sectionGroupsUrl ? await sectionsFromSectionGroups(accessToken, group.sectionGroupsUrl, path) : [];
- return [...direct, ...nested];
- })
+ return Promise.all(
+ groups.map(async (group) => ({
+ id: group.id,
+ title: group.displayName,
+ createdDateTime: group.createdDateTime,
+ lastModifiedDateTime: group.lastModifiedDateTime,
+ sections: mapSections(group.sections),
+ sectionGroups: group.sectionGroups?.length && group.sectionGroupsUrl ? await fetchSectionGroups(accessToken, group.sectionGroupsUrl) : []
+ }))
);
- return perGroup.flat();
+}
+
+function mapSections(raw: RawSection[] | undefined): OneNoteSection[] {
+ return (raw ?? []).map((s) => ({ id: s.id, title: s.displayName, createdDateTime: s.createdDateTime, lastModifiedDateTime: s.lastModifiedDateTime }));
}
function appendQuery(url: string, query: string): string {
@@ -179,13 +192,20 @@ export async function getResource(accessToken: string, url: string): Promise<{ c
return { content: buffer, contentType: response.headers.get("content-type") ?? "application/octet-stream" };
}
+interface RawSection {
+ id: string;
+ displayName: string;
+ createdDateTime?: string;
+ lastModifiedDateTime?: string;
+}
+
interface RawNotebook {
id: string;
displayName: string;
createdDateTime?: string;
lastModifiedDateTime?: string;
sectionGroupsUrl?: string;
- sections?: { id: string; displayName: string; createdDateTime?: string; lastModifiedDateTime?: string }[];
+ sections?: RawSection[];
/** id-only, requested just to detect whether the notebook has section groups to follow. */
sectionGroups?: { id: string }[];
}
@@ -193,8 +213,10 @@ interface RawNotebook {
interface RawSectionGroup {
id: string;
displayName: string;
+ createdDateTime?: string;
+ lastModifiedDateTime?: string;
sectionGroupsUrl?: string;
- sections?: { id: string; displayName: string; createdDateTime?: string; lastModifiedDateTime?: string }[];
+ sections?: RawSection[];
/** id-only, requested just to detect whether the group has nested section groups to follow. */
sectionGroups?: { id: string }[];
}
diff --git a/apps/server/src/services/import/onenote/importer.ts b/apps/server/src/services/import/onenote/importer.ts
index 9701e57999..29601ddfe1 100644
--- a/apps/server/src/services/import/onenote/importer.ts
+++ b/apps/server/src/services/import/onenote/importer.ts
@@ -15,6 +15,14 @@ import graph, { type OneNotePage } from "./graph.js";
import { inkmlToSvg } from "./inkml.js";
import { type LinkTarget, rewritePageLinks } from "./links.js";
+/** A section group on the path from the notebook down to a selected section, recreated as a folder. */
+export interface OneNoteFolderRef {
+ id: string;
+ title: string;
+ createdDateTime?: string;
+ lastModifiedDateTime?: string;
+}
+
export interface SectionSelection {
id: string;
title: string;
@@ -22,6 +30,8 @@ export interface SectionSelection {
createdDateTime?: string;
/** OneNote's section last-modified timestamp (ISO 8601), preserved on the imported section folder. */
lastModifiedDateTime?: string;
+ /** Section groups from the notebook root down to this section's immediate group (empty if none). */
+ groupPath: OneNoteFolderRef[];
notebookId: string;
notebookTitle: string;
/** OneNote's notebook creation timestamp (ISO 8601), preserved on the imported notebook folder. */
@@ -65,6 +75,7 @@ interface FetchedSection {
title: string;
createdDateTime?: string;
lastModifiedDateTime?: string;
+ groupPath: OneNoteFolderRef[];
notebookId: string;
notebookTitle: string;
notebookCreatedDateTime?: string;
@@ -107,6 +118,7 @@ export async function importSelection({ accessToken, parentNoteId, sections, tas
title: section.title,
createdDateTime: section.createdDateTime,
lastModifiedDateTime: section.lastModifiedDateTime,
+ groupPath: section.groupPath,
notebookId: section.notebookId,
notebookTitle: section.notebookTitle,
notebookCreatedDateTime: section.notebookCreatedDateTime,
@@ -140,20 +152,32 @@ function createNotes(parentNoteId: string, sections: FetchedSection[], debug: bo
const createdPages: { note: BNote; original: string; content: string; page: FetchedPage }[] = [];
const targetByPageId = new Map<string, LinkTarget>();
- // Group selected sections under a note per notebook so the original hierarchy is preserved. Keyed by
- // the OneNote notebook id rather than the title, so notebooks that happen to share a title stay apart.
- const notebookNotes = new Map<string, string>();
+ // Recreate the OneNote hierarchy as folder notes: a folder per notebook, then a folder per section
+ // group on the path down to the section, then the section itself. Folders are keyed by their OneNote
+ // id (globally unique) so a notebook/group shared by several selected sections is created once, and
+ // notebooks/groups that happen to share a title stay apart.
+ const folderNotes = new Map<string, string>();
+
+ const ensureFolder = (parentId: string, ref: OneNoteFolderRef, iconClass: string) => {
+ let noteId = folderNotes.get(ref.id);
+ if (!noteId) {
+ const folder = createFolder(parentId, ref.title);
+ folder.addLabel("iconClass", iconClass);
+ applyOriginalDates(folder, ref.createdDateTime, ref.lastModifiedDateTime);
+ noteId = folder.noteId;
+ folderNotes.set(ref.id, noteId);
+ }
+ return noteId;
+ };
+
for (const section of sections) {
- let notebookNoteId = notebookNotes.get(section.notebookId);
- if (!notebookNoteId) {
- const notebookNote = createFolder(rootNote.noteId, section.notebookTitle);
- notebookNote.addLabel("iconClass", "bx bx-book");
- applyOriginalDates(notebookNote, section.notebookCreatedDateTime, section.notebookLastModifiedDateTime);
- notebookNoteId = notebookNote.noteId;
- notebookNotes.set(section.notebookId, notebookNoteId);
+ const notebookRef: OneNoteFolderRef = { id: section.notebookId, title: section.notebookTitle, createdDateTime: section.notebookCreatedDateTime, lastModifiedDateTime: section.notebookLastModifiedDateTime };
+ let containerNoteId = ensureFolder(rootNote.noteId, notebookRef, "bx bx-book");
+ for (const group of section.groupPath) {
+ containerNoteId = ensureFolder(containerNoteId, group, "bx bx-folder");
}
- const sectionNote = createFolder(notebookNoteId, section.title);
+ const sectionNote = createFolder(containerNoteId, section.title);
applyOriginalDates(sectionNote, section.createdDateTime, section.lastModifiedDateTime);
// OneNote pages carry an indentation level (subpages); preserve it by parenting each page under