Skip to content

Build your personal knowledge base with Trilium Notes

feat(onenote): replace the flat section picker with a tri-state checkbox tree

Elian Doran36994869021b
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 8d4b0beddb..ce41cca7b7 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -273,6 +273,8 @@
"select_sections": "Select the sections to import",
"select_sections_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",
+ "import_count_one": "Import {{count}} section",
+ "import_count_other": "Import {{count}} sections",
"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/import_dialog.css b/apps/client/src/widgets/dialogs/import/import_dialog.css
index c4ce2d7736..ef892e4341 100644
--- a/apps/client/src/widgets/dialogs/import/import_dialog.css
+++ b/apps/client/src/widgets/dialogs/import/import_dialog.css
@@ -89,31 +89,16 @@
}
.onenote-notebooks {
- display: flex;
- flex-direction: column;
- gap: 1em;
max-height: 45vh;
overflow-y: auto;
- }
-
- .onenote-notebook {
- display: flex;
- flex-direction: column;
- 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;
- }
+ /* Notebooks are the tree's roots; set them apart like the headings they replaced. */
+ > .checkbox-tree {
+ gap: 0.5em;
+ }
- .onenote-section-group-title {
- color: var(--muted-text-color);
- font-size: 0.9em;
- font-weight: bold;
+ > .checkbox-tree > .checkbox-tree-container > .checkbox-tree-row .form-check-label {
+ font-weight: bold;
+ }
}
}
diff --git a/apps/client/src/widgets/dialogs/import/onenote.tsx b/apps/client/src/widgets/dialogs/import/onenote.tsx
index eca3010713..9093e99bf1 100644
--- a/apps/client/src/widgets/dialogs/import/onenote.tsx
+++ b/apps/client/src/widgets/dialogs/import/onenote.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useRef, useState } from "preact/hooks";
+import { useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks";
import { t } from "../../../services/i18n.js";
import onenoteImport, { buildSectionSelections, type OneNoteAccount, type OneNoteContainer, type OneNoteDeviceLogin, type OneNoteNotebook, orderedChildren } from "../../../services/onenote_import.js";
@@ -6,7 +6,7 @@ import toast from "../../../services/toast.js";
import { isElectron, randomString } from "../../../services/utils.js";
import Button from "../../react/Button.js";
import { Card, CardSection } from "../../react/Card.js";
-import FormCheckbox from "../../react/FormCheckbox.js";
+import CheckboxTree, { type CheckboxTreeNode } from "../../react/CheckboxTree.js";
import { useTriliumOptionBool } from "../../react/hooks.js";
import LoadingSpinner from "../../react/LoadingSpinner.js";
import NoItems from "../../react/NoItems.js";
@@ -156,17 +156,11 @@ function OneNotePanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPa
setPhase("disconnected");
}, [stopPolling]);
- const toggleSection = useCallback((id: string, checked: boolean) => {
- setSelectedIds((prev) => {
- const next = new Set(prev);
- if (checked) {
- next.add(id);
- } else {
- next.delete(id);
- }
- return next;
- });
- }, []);
+ const treeNodes = useMemo(() => notebooks.map((notebook): CheckboxTreeNode => ({
+ id: notebook.id,
+ label: notebook.title,
+ children: buildTreeNodes(notebook)
+ })), [notebooks]);
const doImport = useCallback(async () => {
const sections = buildSectionSelections(notebooks, selectedIds);
@@ -193,18 +187,19 @@ function OneNotePanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPa
doImportRef.current = doImport;
// Surface the import button in the dialog's pinned footer once notebooks are loaded; the other
- // phases set it to null so the connect screens show no footer.
- const importDisabled = selectedIds.size === 0;
+ // phases set it to null so the connect screens show no footer. The button carries the selection
+ // count as feedback that a bulk (notebook/group) toggle selected what the user expected.
+ const selectedCount = selectedIds.size;
useEffect(() => {
setFooter(phase !== "ready" ? null : (
<Button
- text={t("onenote_import.import")}
+ text={selectedCount > 0 ? t("onenote_import.import_count", { count: selectedCount }) : t("onenote_import.import")}
kind="primary"
- disabled={importDisabled}
+ disabled={selectedCount === 0}
onClick={() => void doImportRef.current()}
/>
));
- }, [phase, importDisabled, setFooter]);
+ }, [phase, selectedCount, setFooter]);
if (phase === "checking") {
return (
@@ -260,12 +255,7 @@ function OneNotePanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPa
<>
<OptionsRow name="onenote-sections" label={t("onenote_import.select_sections")} description={t("onenote_import.select_sections_hint")} stacked>
<div className="onenote-notebooks">
- {notebooks.map((notebook) => (
- <div className="onenote-notebook" key={notebook.id}>
- <strong>{notebook.title}</strong>
- <SectionTree container={notebook} selectedIds={selectedIds} onToggle={toggleSection} />
- </div>
- ))}
+ <CheckboxTree nodes={treeNodes} selectedIds={selectedIds} onChange={setSelectedIds} />
</div>
</OptionsRow>
<OptionsRowWithToggle
@@ -290,34 +280,14 @@ function OneNotePanel({ parentNoteId, closeDialog, setFooter }: ImportProviderPa
);
}
-/** Renders a notebook's (or section group's) sections as checkboxes and recurses into nested section
- * groups. Sections and groups are interleaved in creation-date order so the picker mirrors the OneNote
- * left rail (which the API can't reproduce exactly — see the order caveat above the list). */
-function SectionTree({ container, selectedIds, onToggle }: {
- container: OneNoteContainer;
- selectedIds: Set<string>;
- onToggle: (id: string, checked: boolean) => void;
-}) {
- return (
- <>
- {orderedChildren(container).map((child) => (child.type === "section"
- ? (
- <FormCheckbox
- key={child.section.id}
- name={`onenote-section-${child.section.id}`}
- label={child.section.title}
- currentValue={selectedIds.has(child.section.id)}
- onChange={(checked) => onToggle(child.section.id, checked)}
- />
- )
- : (
- <div className="onenote-section-group" key={child.group.id}>
- <span className="onenote-section-group-title">{child.group.title}</span>
- <SectionTree container={child.group} selectedIds={selectedIds} onToggle={onToggle} />
- </div>
- )))}
- </>
- );
+/** Maps a notebook's (or section group's) children onto picker tree nodes: sections become leaves,
+ * section groups become (recursed) containers. Sections and groups are interleaved in creation-date
+ * order so the picker mirrors the OneNote left rail (which the API can't reproduce exactly — see the
+ * order caveat above the list). */
+function buildTreeNodes(container: OneNoteContainer): CheckboxTreeNode[] {
+ return orderedChildren(container).map((child) => (child.type === "section"
+ ? { id: child.section.id, label: child.section.title }
+ : { id: child.group.id, label: child.group.title, children: buildTreeNodes(child.group) }));
}
const provider: ImportProvider = {
diff --git a/apps/client/src/widgets/react/CheckboxTree.css b/apps/client/src/widgets/react/CheckboxTree.css
new file mode 100644
index 0000000000..242e40db34
--- /dev/null
+++ b/apps/client/src/widgets/react/CheckboxTree.css
@@ -0,0 +1,68 @@
+ul.checkbox-tree,
+.checkbox-tree ul.checkbox-tree-level {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 0.25em;
+}
+
+.checkbox-tree {
+ /* Nested levels indent past the parent's caret and pick up a guide line. */
+ .checkbox-tree-container > .checkbox-tree-level {
+ margin-top: 0.25em;
+ margin-inline-start: 0.6em;
+ padding-inline-start: 1em;
+ border-inline-start: 1px solid var(--main-border-color);
+ }
+
+ .checkbox-tree-row {
+ display: flex;
+ align-items: center;
+ gap: 0.25em;
+
+ .form-checkbox {
+ min-width: 0;
+ }
+ }
+
+ .checkbox-tree-caret {
+ flex-shrink: 0;
+ width: 1.5em;
+ /* Center the icon glyph itself: without this the button lays the oversized icon out on the
+ text baseline, leaving the chevron visibly high against the checkbox row. */
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ align-self: center;
+ line-height: 1;
+ padding: 0;
+ border: none;
+ background: none;
+ color: var(--main-text-color);
+ cursor: pointer;
+
+ .arrow {
+ font-size: 1.2em;
+ line-height: 1;
+ transition: transform 150ms ease-in;
+
+ &.expanded {
+ transform: rotate(90deg);
+ }
+ }
+ }
+
+ /* Leaves have no caret; keep their checkboxes aligned with sibling containers'. */
+ .checkbox-tree-leaf {
+ padding-inline-start: calc(1.5em + 0.25em);
+ }
+
+ .checkbox-tree-count {
+ flex-shrink: 0;
+ color: var(--muted-text-color);
+ border: 1px solid var(--main-border-color);
+ font-weight: normal;
+ }
+}
diff --git a/apps/client/src/widgets/react/CheckboxTree.spec.tsx b/apps/client/src/widgets/react/CheckboxTree.spec.tsx
new file mode 100644
index 0000000000..5328c60faf
--- /dev/null
+++ b/apps/client/src/widgets/react/CheckboxTree.spec.tsx
@@ -0,0 +1,165 @@
+import { render } from "preact";
+import { useState } from "preact/hooks";
+import { act } from "preact/test-utils";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import CheckboxTree, { type CheckboxTreeNode } from "./CheckboxTree";
+
+/**
+ * Work ─┬─ Meetings (leaf)
+ * ├─ Projects (leaf)
+ * └─ Archive ─┬─ Old plans (leaf)
+ * └─ Newer plans (leaf)
+ * Empty notebook (container without any descendant leaves)
+ */
+const NODES: CheckboxTreeNode[] = [
+ {
+ id: "work",
+ label: "Work",
+ children: [
+ { id: "meetings", label: "Meetings" },
+ { id: "projects", label: "Projects" },
+ {
+ id: "archive",
+ label: "Archive",
+ children: [
+ { id: "plansOld", label: "Old plans" },
+ { id: "plansNew", label: "Newer plans" }
+ ]
+ }
+ ]
+ },
+ { id: "empty", label: "Empty notebook", children: [] }
+];
+
+let container: HTMLDivElement | undefined;
+
+function mount(vnode: Parameters<typeof render>[0]) {
+ const target = document.createElement("div");
+ container = target;
+ document.body.appendChild(target);
+ void act(() => render(vnode, target));
+ return target;
+}
+
+afterEach(() => {
+ if (container) {
+ render(null, container);
+ container.remove();
+ container = undefined;
+ }
+});
+
+/** Clicks inside act() so Preact flushes the resulting re-render before assertions run. */
+function click(el: HTMLElement | null | undefined) {
+ expect(el, "click target").not.toBeNull();
+ void act(() => el?.click());
+}
+
+function checkboxFor(root: HTMLElement, id: string): HTMLInputElement {
+ const input = root.querySelector<HTMLInputElement>(`input[id^="checkbox-tree-${id}"]`);
+ if (!input) {
+ throw new Error(`no checkbox for ${id}`);
+ }
+ return input;
+}
+
+/** Renders the tree with its selection state held in a component, the way callers use it. */
+function Harness({ initialSelection = [], onChange }: { initialSelection?: string[]; onChange?: (next: Set<string>) => void }) {
+ const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set(initialSelection));
+ return (
+ <CheckboxTree
+ nodes={NODES}
+ selectedIds={selectedIds}
+ onChange={(next) => {
+ setSelectedIds(next);
+ onChange?.(next);
+ }}
+ />
+ );
+}
+
+describe("CheckboxTree", () => {
+ it("derives container states from selected leaves: unchecked → indeterminate → checked", () => {
+ const root = mount(<Harness />);
+ const work = () => checkboxFor(root, "work");
+
+ expect(work().checked).toBe(false);
+ expect(work().indeterminate).toBe(false);
+
+ click(checkboxFor(root, "meetings"));
+ expect(work().checked).toBe(false);
+ expect(work().indeterminate).toBe(true);
+
+ // Selecting a partially selected container selects the remainder, everywhere beneath it.
+ click(work());
+ expect(work().checked).toBe(true);
+ expect(work().indeterminate).toBe(false);
+ expect(checkboxFor(root, "archive").checked).toBe(true);
+ expect(checkboxFor(root, "projects").checked).toBe(true);
+ });
+
+ it("toggles all descendant leaves through a container and reports the full selection", () => {
+ const onChange = vi.fn();
+ const root = mount(<Harness onChange={onChange} />);
+
+ click(checkboxFor(root, "work"));
+ expect(onChange).toHaveBeenLastCalledWith(new Set(["meetings", "projects", "plansOld", "plansNew"]));
+
+ // A fully selected container deselects everything beneath it.
+ click(checkboxFor(root, "work"));
+ expect(onChange).toHaveBeenLastCalledWith(new Set());
+ });
+
+ it("keeps leaf toggling independent and unchecks the container when its last leaf is dropped", () => {
+ const onChange = vi.fn();
+ const root = mount(<Harness initialSelection={["meetings"]} onChange={onChange} />);
+
+ click(checkboxFor(root, "projects"));
+ expect(onChange).toHaveBeenLastCalledWith(new Set(["meetings", "projects"]));
+
+ click(checkboxFor(root, "meetings"));
+ click(checkboxFor(root, "projects"));
+ expect(onChange).toHaveBeenLastCalledWith(new Set());
+ expect(checkboxFor(root, "work").indeterminate).toBe(false);
+ });
+
+ it("disables containers without descendant leaves and gives them no caret", () => {
+ const root = mount(<Harness />);
+ const empty = checkboxFor(root, "empty");
+
+ expect(empty.disabled).toBe(true);
+ const emptyRow = empty.closest(".checkbox-tree-row");
+ expect(emptyRow?.querySelector("button.checkbox-tree-caret")).toBeNull();
+ });
+
+ it("expands roots by default, collapses deeper containers behind a caret with a count badge", () => {
+ const root = mount(<Harness initialSelection={["plansOld"]} />);
+
+ // Root level is expanded (its leaves are rendered), the nested group is not.
+ expect(root.querySelector(`input[id^="checkbox-tree-meetings"]`)).not.toBeNull();
+ expect(root.querySelector(`input[id^="checkbox-tree-plansOld"]`)).toBeNull();
+
+ // The collapsed group still surfaces its hidden selection as "selected / total".
+ const archiveRow = checkboxFor(root, "archive").closest(".checkbox-tree-row");
+ expect(archiveRow?.querySelector(".checkbox-tree-count")?.textContent).toBe("1 / 2");
+ expect(checkboxFor(root, "archive").indeterminate).toBe(true);
+
+ // Expanding reveals the leaves and hides the badge; collapsing restores it.
+ const caret = archiveRow?.querySelector<HTMLButtonElement>("button.checkbox-tree-caret");
+ expect(caret?.getAttribute("aria-expanded")).toBe("false");
+ click(caret);
+ expect(caret?.getAttribute("aria-expanded")).toBe("true");
+ expect(root.querySelector(`input[id^="checkbox-tree-plansOld"]`)).not.toBeNull();
+ expect(root.querySelector(".checkbox-tree-count")).toBeNull();
+ click(caret);
+ expect(root.querySelector(`input[id^="checkbox-tree-plansOld"]`)).toBeNull();
+ expect(root.querySelector(".checkbox-tree-count")?.textContent).toBe("1 / 2");
+ });
+
+ it("shows plain totals on collapsed containers without any selection", () => {
+ const root = mount(<Harness />);
+ const archiveRow = checkboxFor(root, "archive").closest(".checkbox-tree-row");
+ expect(archiveRow?.querySelector(".checkbox-tree-count")?.textContent).toBe("2");
+ });
+});
diff --git a/apps/client/src/widgets/react/CheckboxTree.tsx b/apps/client/src/widgets/react/CheckboxTree.tsx
new file mode 100644
index 0000000000..81413dd52b
--- /dev/null
+++ b/apps/client/src/widgets/react/CheckboxTree.tsx
@@ -0,0 +1,154 @@
+import "./CheckboxTree.css";
+
+import clsx from "clsx";
+import { useMemo, useState } from "preact/hooks";
+
+import SimpleBadge from "./Badge";
+import FormCheckbox from "./FormCheckbox";
+import Icon from "./Icon";
+
+export interface CheckboxTreeNode {
+ id: string;
+ label: string;
+ /** Present (possibly empty) on container nodes; absent on selectable leaves. */
+ children?: CheckboxTreeNode[];
+}
+
+interface CheckboxTreeProps {
+ nodes: CheckboxTreeNode[];
+ /** Selected leaf ids — the single source of truth; container checkbox states are derived from it. */
+ selectedIds: Set<string>;
+ onChange(next: Set<string>): void;
+ /** Containers shallower than this many levels start expanded. Defaults to 1 (root containers only). */
+ defaultExpandedDepth?: number;
+}
+
+/**
+ * A tree of checkboxes for picking a subset of leaves out of a hierarchy. Leaves toggle themselves;
+ * containers show a tri-state checkbox (checked / indeterminate / unchecked) derived from their
+ * descendant leaves and toggle all of them at once. Containers can be collapsed, in which case a
+ * badge keeps the selection visible as "selected / total" leaf counts.
+ *
+ * Selection is controlled: the caller owns the set of selected leaf ids and receives the whole next
+ * set on every change. Node ids must be unique across the entire tree.
+ */
+export default function CheckboxTree({ nodes, selectedIds, onChange, defaultExpandedDepth = 1 }: CheckboxTreeProps) {
+ const leafIdsByContainer = useMemo(() => {
+ const map = new Map<string, string[]>();
+ collectLeafIds(nodes, map);
+ return map;
+ }, [nodes]);
+
+ // Expansion is tracked as per-node overrides on top of the depth-based default rather than as a
+ // set of expanded ids, so nodes arriving after mount (async loads) still get the default.
+ const [expandOverrides, setExpandOverrides] = useState<ReadonlyMap<string, boolean>>(new Map());
+
+ const toggleExpanded = (id: string, expandedByDefault: boolean) => {
+ setExpandOverrides((prev) => {
+ const next = new Map(prev);
+ next.set(id, !(prev.get(id) ?? expandedByDefault));
+ return next;
+ });
+ };
+
+ const toggleLeaf = (id: string, checked: boolean) => {
+ const next = new Set(selectedIds);
+ if (checked) {
+ next.add(id);
+ } else {
+ next.delete(id);
+ }
+ onChange(next);
+ };
+
+ // A partially selected container selects the remainder (the file-picker convention);
+ // only a fully selected one deselects.
+ const toggleContainer = (leafIds: string[], allSelected: boolean) => {
+ const next = new Set(selectedIds);
+ for (const id of leafIds) {
+ if (allSelected) {
+ next.delete(id);
+ } else {
+ next.add(id);
+ }
+ }
+ onChange(next);
+ };
+
+ const renderLevel = (levelNodes: CheckboxTreeNode[], depth: number) => (
+ <ul className={clsx("checkbox-tree-level", { "checkbox-tree": depth === 0 })}>
+ {levelNodes.map((node) => {
+ if (!node.children) {
+ return (
+ <li key={node.id} className="checkbox-tree-leaf">
+ <FormCheckbox
+ name={`checkbox-tree-${node.id}`}
+ label={node.label}
+ currentValue={selectedIds.has(node.id)}
+ onChange={(checked) => toggleLeaf(node.id, checked)}
+ />
+ </li>
+ );
+ }
+
+ const leafIds = leafIdsByContainer.get(node.id) ?? [];
+ const selectedCount = leafIds.reduce((count, id) => count + (selectedIds.has(id) ? 1 : 0), 0);
+ const allSelected = leafIds.length > 0 && selectedCount === leafIds.length;
+ const expandedByDefault = depth < defaultExpandedDepth;
+ const expanded = node.children.length > 0 && (expandOverrides.get(node.id) ?? expandedByDefault);
+
+ return (
+ <li key={node.id} className="checkbox-tree-container">
+ <div className="checkbox-tree-row">
+ {node.children.length > 0
+ ? (
+ <button
+ type="button"
+ className="checkbox-tree-caret tn-low-profile"
+ aria-expanded={expanded}
+ aria-label={node.label}
+ onClick={() => toggleExpanded(node.id, expandedByDefault)}
+ >
+ <Icon className={clsx("arrow", { expanded })} icon="bx bx-chevron-right" />
+ </button>
+ )
+ : <span className="checkbox-tree-caret" />}
+ <FormCheckbox
+ name={`checkbox-tree-${node.id}`}
+ label={node.label}
+ currentValue={allSelected}
+ indeterminate={selectedCount > 0 && !allSelected}
+ disabled={leafIds.length === 0}
+ onChange={() => toggleContainer(leafIds, allSelected)}
+ />
+ {!expanded && leafIds.length > 0 && (
+ <SimpleBadge
+ className="checkbox-tree-count"
+ title={selectedCount > 0 ? `${selectedCount} / ${leafIds.length}` : `${leafIds.length}`}
+ />
+ )}
+ </div>
+ {expanded && renderLevel(node.children, depth + 1)}
+ </li>
+ );
+ })}
+ </ul>
+ );
+
+ return renderLevel(nodes, 0);
+}
+
+/** Fills `map` with each container's transitive leaf ids and returns the ids for the given level. */
+function collectLeafIds(nodes: CheckboxTreeNode[], map: Map<string, string[]>): string[] {
+ const leafIds: string[] = [];
+ for (const node of nodes) {
+ if (node.children) {
+ const childLeafIds = collectLeafIds(node.children, map);
+ map.set(node.id, childLeafIds);
+ leafIds.push(...childLeafIds);
+ } else {
+ leafIds.push(node.id);
+ }
+ }
+ return leafIds;
+}
diff --git a/apps/client/src/widgets/react/FormCheckbox.tsx b/apps/client/src/widgets/react/FormCheckbox.tsx
index e20dea0f48..4df3f03a48 100644
--- a/apps/client/src/widgets/react/FormCheckbox.tsx
+++ b/apps/client/src/widgets/react/FormCheckbox.tsx
@@ -13,15 +13,27 @@ interface FormCheckboxProps {
*/
hint?: string;
currentValue: boolean;
+ /**
+ * Shows the native mixed state (a dash), e.g. for a parent whose children are partially selected.
+ * `indeterminate` is a DOM property only (there is no HTML attribute), so it is applied via a ref.
+ */
+ indeterminate?: boolean;
disabled?: boolean;
onChange(newValue: boolean): void;
containerStyle?: CSSProperties;
}
-export default function FormCheckbox({ name, disabled, label, currentValue, onChange, hint, containerStyle }: FormCheckboxProps) {
+export default function FormCheckbox({ name, disabled, label, currentValue, indeterminate, onChange, hint, containerStyle }: FormCheckboxProps) {
const labelRef = useRef<HTMLLabelElement>(null);
+ const inputRef = useRef<HTMLInputElement>(null);
const id = useUniqueName(name);
+ useEffect(() => {
+ if (inputRef.current) {
+ inputRef.current.indeterminate = indeterminate ?? false;
+ }
+ }, [indeterminate]);
+
useEffect(() => {
if (!hint || !labelRef.current) return;
@@ -54,6 +66,7 @@ export default function FormCheckbox({ name, disabled, label, currentValue, onCh
>
<input
id={id}
+ ref={inputRef}
className="form-check-input"
type="checkbox"
name={id}