Skip to content

Build your personal knowledge base with Trilium Notes

feat(import): order OneNote sections by creation date and refine the picker

Elian Doran640f694a4dde
diff --git a/apps/client/src/services/onenote_import.spec.ts b/apps/client/src/services/onenote_import.spec.ts
index 81cf02fdb3..fea3181a0f 100644
--- a/apps/client/src/services/onenote_import.spec.ts
+++ b/apps/client/src/services/onenote_import.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { buildSectionSelections, type OneNoteNotebook } from "./onenote_import.js";
+import { buildSectionSelections, type OneNoteNotebook, orderedChildren } from "./onenote_import.js";
const NOTEBOOKS: OneNoteNotebook[] = [
{
@@ -8,19 +8,20 @@ const NOTEBOOKS: OneNoteNotebook[] = [
title: "Notebook 1",
createdDateTime: "2020-01-01T00:00:00Z",
lastModifiedDateTime: "2020-02-01T00:00:00Z",
- sections: [{ id: "s1", title: "Direct section" }],
+ sections: [{ id: "s1", title: "Direct section", createdDateTime: "2020-01-01T00:00:00Z" }],
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" }],
+ sections: [{ id: "s2", title: "In group A", createdDateTime: "2020-03-15T00:00:00Z" }],
sectionGroups: [
{
id: "g2",
title: "Subgroup B",
- sections: [{ id: "s3", title: "In subgroup B" }],
+ createdDateTime: "2020-05-01T00:00:00Z",
+ sections: [{ id: "s3", title: "In subgroup B", createdDateTime: "2020-06-01T00:00:00Z" }],
sectionGroups: []
}
]
@@ -29,6 +30,38 @@ const NOTEBOOKS: OneNoteNotebook[] = [
}
];
+// A container whose sections and groups are deliberately out of creation order in their source arrays,
+// so a correct interleave has to re-sort across both: by date the rail reads early, group, late.
+const INTERLEAVE: OneNoteNotebook[] = [
+ {
+ id: "nb",
+ title: "NB",
+ sections: [
+ { id: "late", title: "Late", createdDateTime: "2020-05-01T00:00:00Z" },
+ { id: "early", title: "Early", createdDateTime: "2020-01-01T00:00:00Z" }
+ ],
+ sectionGroups: [
+ {
+ id: "grp",
+ title: "Group",
+ createdDateTime: "2020-03-01T00:00:00Z",
+ sections: [{ id: "in", title: "In group", createdDateTime: "2020-02-01T00:00:00Z" }],
+ sectionGroups: []
+ }
+ ]
+ }
+];
+
+const describeChild = (notebooks: OneNoteNotebook[]) => orderedChildren(notebooks[0]).map((c) => (c.type === "section" ? `section:${c.section.id}` : `group:${c.group.id}`));
+
+describe("orderedChildren", () => {
+ it("interleaves sections and groups in creation-date order, by each item's own date", () => {
+ // sections[] is [late, early] and the group is dated between them; the group's own date (not its
+ // contents') decides its slot, so the rail order is early, group, late.
+ expect(describeChild(INTERLEAVE)).toEqual(["section:early", "group:grp", "section:late"]);
+ });
+});
+
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"]));
@@ -54,9 +87,10 @@ describe("buildSectionSelections", () => {
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"]);
+ it("emits selected sections in interleaved rail order and ignores unselected ones", () => {
+ // 'in' lives in a group dated between 'early' and 'late', so it must appear between them.
+ const selections = buildSectionSelections(INTERLEAVE, new Set(["early", "in", "late"]));
+ expect(selections.map((s) => s.id)).toEqual(["early", "in", "late"]);
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 5ea2af1ba5..6521bc0eda 100644
--- a/apps/client/src/services/onenote_import.ts
+++ b/apps/client/src/services/onenote_import.ts
@@ -92,18 +92,27 @@ export default {
runImport
};
+export type OneNoteContainer = OneNoteNotebook | OneNoteSectionGroup;
+
+/** A container's direct child in the OneNote left rail — either a section or a (nested) section group. */
+export type OneNoteChild = { type: "section"; section: OneNoteSection } | { type: "group"; group: OneNoteSectionGroup };
+
/**
* 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.
+ * folder nesting. Children are visited in OneNote rail order (see orderedChildren), so the resulting
+ * note tree is created in that order; section groups contribute structure only and are never selectable.
*/
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)) {
+ const visit = (container: OneNoteContainer, notebook: OneNoteNotebook, groupPath: OneNoteFolderRef[]) => {
+ for (const child of orderedChildren(container)) {
+ if (child.type === "group") {
+ const { group } = child;
+ visit(group, notebook, [...groupPath, { id: group.id, title: group.title, createdDateTime: group.createdDateTime, lastModifiedDateTime: group.lastModifiedDateTime }]);
+ } else if (selectedIds.has(child.section.id)) {
+ const { section } = child;
selections.push({
id: section.id,
title: section.title,
@@ -117,9 +126,6 @@ export function buildSectionSelections(notebooks: OneNoteNotebook[], selectedIds
});
}
}
- 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) {
@@ -128,3 +134,23 @@ export function buildSectionSelections(notebooks: OneNoteNotebook[], selectedIds
return selections;
}
+
+/**
+ * Returns a container's direct children — its sections and section groups — interleaved into a single
+ * list ordered by creation date. OneNote shows sections and groups intermixed in one ordered rail but
+ * the Graph API exposes no ordering field for them, so creation date is a best-effort approximation
+ * (see the order caveat shown in the picker). Pages keep their exact order (they do carry one).
+ */
+export function orderedChildren(container: OneNoteContainer): OneNoteChild[] {
+ const children: OneNoteChild[] = [
+ ...container.sections.map((section): OneNoteChild => ({ type: "section", section })),
+ ...container.sectionGroups.map((group): OneNoteChild => ({ type: "group", group }))
+ ];
+ // ISO-8601 timestamps sort lexicographically = chronologically; the sort is stable, so children
+ // sharing a timestamp keep the API's alphabetical order as a tiebreak.
+ return children.sort((a, b) => orderKey(a).localeCompare(orderKey(b)));
+}
+
+function orderKey(child: OneNoteChild): string {
+ return (child.type === "section" ? child.section.createdDateTime : child.group.createdDateTime) ?? "";
+}
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index dae60a5c89..637e5bd7cd 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -245,6 +245,8 @@
"load_failed": "Could not load your OneNote notebooks.",
"no_notebooks": "No notebooks were found in this account.",
"select_sections": "Select the sections to import:",
+ "order_hint_title": "Approximate section order",
+ "order_hint": "OneNote doesn't include the original ordering in the import data, so sections and groups are sorted by creation date and may not match how they appear in OneNote.",
"import": "Import selected",
"attach_source": "Attach original HTML (debug)",
"attach_source_hint": "Saves each page's unmodified OneNote HTML as an attachment on the imported note, for comparing against the converted result."
diff --git a/apps/client/src/widgets/dialogs/import_provider.css b/apps/client/src/widgets/dialogs/import_provider.css
index 2d538f00be..08432d5a03 100644
--- a/apps/client/src/widgets/dialogs/import_provider.css
+++ b/apps/client/src/widgets/dialogs/import_provider.css
@@ -84,10 +84,4 @@
font-size: 0.9em;
font-weight: bold;
}
-
- .onenote-actions {
- display: flex;
- justify-content: flex-end;
- margin-top: 1em;
- }
}
diff --git a/apps/client/src/widgets/dialogs/import_provider.tsx b/apps/client/src/widgets/dialogs/import_provider.tsx
index 34c33c9e98..9147b6ae67 100644
--- a/apps/client/src/widgets/dialogs/import_provider.tsx
+++ b/apps/client/src/widgets/dialogs/import_provider.tsx
@@ -1,6 +1,7 @@
import "./import_provider.css";
-import { useState } from "preact/hooks";
+import type { ComponentChildren } from "preact";
+import { useCallback, useState } from "preact/hooks";
import { t } from "../../services/i18n.js";
import Button from "../react/Button.js";
@@ -17,23 +18,31 @@ import { importProviders } from "./import_providers/index.js";
export default function ImportProviderDialog() {
const [parentNoteId, setParentNoteId] = useState<string>();
const [providerId, setProviderId] = useState<string>();
+ const [footer, setFooter] = useState<ComponentChildren>(null);
const [shown, setShown] = useState(false);
useTriliumEvent("showImportProviderDialog", ({ noteId }) => {
setParentNoteId(noteId);
setProviderId(undefined);
+ setFooter(null);
setShown(true);
});
const provider = importProviders.find((p) => p.id === providerId);
+ // Stable so the chosen provider's panel can safely memoize on it (an inline arrow would change every
+ // render, defeating the panel's useCallback/useEffect dependencies).
+ const closeDialog = useCallback(() => setShown(false), []);
+
return (
<Modal
className="import-provider-dialog"
size="lg"
scrollable
title={provider ? provider.name : t("import_provider.title")}
- header={provider && <Button text={t("import_provider.back")} kind="lowProfile" size="small" icon="bx-arrow-back" onClick={() => setProviderId(undefined)} />}
+ header={provider && <Button text={t("import_provider.back")} kind="lowProfile" size="small" icon="bx-arrow-back" onClick={() => { setProviderId(undefined); setFooter(null); }} />}
+ footer={footer}
+ footerAlignment="between"
onHidden={() => setShown(false)}
show={shown}
>
@@ -52,7 +61,7 @@ export default function ImportProviderDialog() {
</div>
)}
- {provider && parentNoteId && <provider.Panel parentNoteId={parentNoteId} closeDialog={() => setShown(false)} />}
+ {provider && parentNoteId && <provider.Panel parentNoteId={parentNoteId} closeDialog={closeDialog} setFooter={setFooter} />}
</Modal>
);
}
diff --git a/apps/client/src/widgets/dialogs/import_providers/onenote.tsx b/apps/client/src/widgets/dialogs/import_providers/onenote.tsx
index 97c7f0a4a0..b675c61461 100644
--- a/apps/client/src/widgets/dialogs/import_providers/onenote.tsx
+++ b/apps/client/src/widgets/dialogs/import_providers/onenote.tsx
@@ -4,6 +4,7 @@ import { t } from "../../../services/i18n.js";
import onenoteImport, { buildSectionSelections, type OneNoteAccount, type OneNoteContainer, type OneNoteNotebook, orderedChildren } from "../../../services/onenote_import.js";
import toast from "../../../services/toast.js";
import { isElectron, randomString } from "../../../services/utils.js";
+import { ExtendedAdmonition } from "../../react/Admonition.js";
import Button from "../../react/Button.js";
import FormCheckbox from "../../react/FormCheckbox.js";
import LoadingSpinner from "../../react/LoadingSpinner.js";
@@ -11,7 +12,7 @@ import type { ImportProvider, ImportProviderPanelProps } from "./types.js";
type Phase = "checking" | "disconnected" | "connecting" | "ready";
-function OneNotePanel({ parentNoteId, closeDialog }: ImportProviderPanelProps) {
+function OneNotePanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPanelProps) {
const [phase, setPhase] = useState<Phase>("checking");
const [account, setAccount] = useState<OneNoteAccount | null>(null);
const [notebooks, setNotebooks] = useState<OneNoteNotebook[]>([]);
@@ -128,6 +129,38 @@ function OneNotePanel({ parentNoteId, closeDialog }: ImportProviderPanelProps) {
}
}, [notebooks, selectedIds, parentNoteId, debug, closeDialog]);
+ // Keep the latest import handler in a ref so the footer effect below depends only on the values the
+ // footer actually shows (all primitives), never on doImport's identity. Depending on doImport — which
+ // changes on every selection — would re-push a new footer to the parent on each keystroke, and since
+ // the parent re-renders us back, that closes an infinite update loop.
+ const doImportRef = useRef(doImport);
+ doImportRef.current = doImport;
+
+ // Surface the primary actions in the dialog's pinned footer once notebooks are loaded; the other
+ // phases (and unmounting, below) clear it so the picker and connect screens show no footer.
+ const importDisabled = selectedIds.size === 0;
+ useEffect(() => {
+ setFooter(phase !== "ready" ? null : (
+ <>
+ <FormCheckbox
+ name="onenote-debug"
+ label={t("onenote_import.attach_source")}
+ hint={t("onenote_import.attach_source_hint")}
+ currentValue={debug}
+ onChange={setDebug}
+ />
+ <Button
+ text={t("onenote_import.import")}
+ kind="primary"
+ disabled={importDisabled}
+ onClick={() => void doImportRef.current()}
+ />
+ </>
+ ));
+ }, [phase, debug, importDisabled, setFooter]);
+
+ useEffect(() => () => setFooter(null), [setFooter]);
+
if (phase === "checking") {
return <div className="onenote-panel"><LoadingSpinner /></div>;
}
@@ -155,10 +188,6 @@ function OneNotePanel({ parentNoteId, closeDialog }: ImportProviderPanelProps) {
: (
<>
<p>{t("onenote_import.select_sections")}</p>
- <p className="onenote-order-hint">
- <span className="bx bx-info-circle" />
- {t("onenote_import.order_hint")}
- </p>
<div className="onenote-notebooks">
{notebooks.map((notebook) => (
<div className="onenote-notebook" key={notebook.id}>
@@ -167,24 +196,11 @@ function OneNotePanel({ parentNoteId, closeDialog }: ImportProviderPanelProps) {
</div>
))}
</div>
+ <ExtendedAdmonition type="note" icon="bx bx-info-circle" title={t("onenote_import.order_hint_title")}>
+ {t("onenote_import.order_hint")}
+ </ExtendedAdmonition>
</>
)}
-
- <div className="onenote-actions">
- <FormCheckbox
- name="onenote-debug"
- label={t("onenote_import.attach_source")}
- hint={t("onenote_import.attach_source_hint")}
- currentValue={debug}
- onChange={setDebug}
- />
- <Button
- text={t("onenote_import.import")}
- kind="primary"
- disabled={selectedIds.size === 0}
- onClick={doImport}
- />
- </div>
</div>
);
}
diff --git a/apps/client/src/widgets/dialogs/import_providers/types.ts b/apps/client/src/widgets/dialogs/import_providers/types.ts
index 5c125a3186..f06241f0fb 100644
--- a/apps/client/src/widgets/dialogs/import_providers/types.ts
+++ b/apps/client/src/widgets/dialogs/import_providers/types.ts
@@ -1,10 +1,12 @@
-import type { ComponentType } from "preact";
+import type { ComponentChildren, ComponentType } from "preact";
export interface ImportProviderPanelProps {
/** The note the imported tree should be created under. */
parentNoteId: string;
/** Closes the surrounding import dialog (e.g. once the import has been kicked off). */
closeDialog: () => void;
+ /** Renders content (e.g. the primary action) into the dialog's pinned modal footer; pass null to clear. */
+ setFooter: (footer: ComponentChildren) => void;
}
/**