Skip to content

Build your personal knowledge base with Trilium Notes

feat(client): build multi-level sorts in the sort dialog

BeatLink9df592493ae7
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index e352f6e22f..d3a88bd8d3 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -496,10 +496,14 @@
"sort_child_notes": {
"sort_children_by": "Sort children by...",
"sorting_criteria": "Sorting criteria",
+ "sorting_criteria_description": "Notes are sorted by the first level; the next level only decides between notes the previous ones left equal.",
"title": "title",
"date_created": "date created",
"date_modified": "date modified",
- "sorting_direction": "Sorting direction",
+ "label": "label",
+ "label_name": "Label name",
+ "add_level": "Add level",
+ "remove_level": "Remove level",
"ascending": "ascending",
"descending": "descending",
"folders": "Folders",
diff --git a/apps/client/src/widgets/dialogs/sort_child_notes.css b/apps/client/src/widgets/dialogs/sort_child_notes.css
new file mode 100644
index 0000000000..7c7aae9c88
--- /dev/null
+++ b/apps/client/src/widgets/dialogs/sort_child_notes.css
@@ -0,0 +1,33 @@
+.modal.sort-child-notes-dialog {
+ .sort-levels-description {
+ color: var(--muted-text-color);
+ margin-bottom: 8px;
+ }
+
+ .sort-levels {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ margin-bottom: 8px;
+ }
+
+ .sort-level {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+
+ .sort-level-kind {
+ flex: 0 0 11em;
+ }
+
+ .sort-level-label {
+ flex: 1 1 8em;
+ min-width: 0;
+ }
+
+ .tn-segmented-choice {
+ margin-inline-start: auto;
+ flex-shrink: 0;
+ }
+ }
+}
diff --git a/apps/client/src/widgets/dialogs/sort_child_notes.spec.tsx b/apps/client/src/widgets/dialogs/sort_child_notes.spec.tsx
new file mode 100644
index 0000000000..318eb5ff3f
--- /dev/null
+++ b/apps/client/src/widgets/dialogs/sort_child_notes.spec.tsx
@@ -0,0 +1,117 @@
+import { act } from "preact/test-utils";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import Component from "../../components/component";
+import server from "../../services/server";
+import { renderInto } from "../../test/render";
+import { ParentComponent } from "../react/react_utils";
+import SortChildNotesDialog, { serializeSortLevels } from "./sort_child_notes";
+
+vi.mock("../../services/i18n", () => ({
+ t: (key: string) => key
+}));
+
+describe("serializeSortLevels", () => {
+ it("writes each level as key:direction, skipping a label level with no name", () => {
+ expect(serializeSortLevels([
+ { kind: "label", labelName: " priority ", descending: true },
+ { kind: "label", labelName: "", descending: false },
+ { kind: "dateCreated", labelName: "", descending: false },
+ { kind: "title", labelName: "ignored", descending: true }
+ ])).toBe("priority:desc,dateCreated:asc,title:desc");
+ });
+});
+
+describe("SortChildNotesDialog", () => {
+ let host: Component;
+ let container: HTMLElement;
+ let put: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(async () => {
+ host = new Component();
+ put = vi.spyOn(server, "put").mockResolvedValue(undefined);
+ container = renderInto(
+ <ParentComponent.Provider value={host}>
+ <SortChildNotesDialog />
+ </ParentComponent.Provider>
+ );
+ await act(async () => {
+ void host.handleEventInChildren("sortChildNotes", { noteId: "parent", selectedOrActiveBranchIds: [] });
+ });
+ });
+
+ function levels() {
+ return [ ...container.querySelectorAll(".sort-level") ];
+ }
+
+ async function click(element: Element | null | undefined) {
+ if (!element) throw new Error("Nothing to click.");
+ await act(async () => {
+ element.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ });
+ }
+
+ async function choose(select: HTMLSelectElement | null, value: string) {
+ if (!select) throw new Error("No select to change.");
+ await act(async () => {
+ select.value = value;
+ select.dispatchEvent(new Event("change", { bubbles: true }));
+ });
+ }
+
+ async function type(input: HTMLInputElement | null, value: string) {
+ if (!input) throw new Error("No input to type into.");
+ await act(async () => {
+ input.value = value;
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ }
+
+ function buttonTitled(scope: Element, title: string) {
+ return [ ...scope.querySelectorAll("button") ].find((button) => button.textContent?.trim() === title);
+ }
+
+ async function submit() {
+ const form = container.querySelector("form");
+ if (!form) throw new Error("The dialog has no form.");
+ await act(async () => {
+ form.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
+ });
+ }
+
+ it("starts with one level and sends the classic single-criterion sort", async () => {
+ expect(levels()).toHaveLength(1);
+ await submit();
+ expect(put).toHaveBeenCalledWith("notes/parent/sort-children", expect.objectContaining({
+ sortBy: "title:asc",
+ foldersFirst: false,
+ sortNatural: false
+ }));
+ });
+
+ it("builds a multi-level criteria string from the added levels", async () => {
+ await click(container.querySelector(".sort-level-add"));
+ await click(container.querySelector(".sort-level-add"));
+ expect(levels()).toHaveLength(3);
+
+ const [ first, second, third ] = levels();
+ await choose(first.querySelector("select"), "label");
+ await type(first.querySelector<HTMLInputElement>(".sort-level-label"), "priority");
+ await click(buttonTitled(first, "sort_child_notes.descending"));
+ await choose(second.querySelector("select"), "dateModified");
+
+ // Removing the last level leaves the first two as they were set.
+ await click(third.querySelector(".sort-level-remove"));
+ expect(levels()).toHaveLength(2);
+
+ await submit();
+ expect(put).toHaveBeenCalledWith("notes/parent/sort-children", expect.objectContaining({
+ sortBy: "priority:desc,dateModified:asc"
+ }));
+ });
+
+ it("keeps the only level from being removed", () => {
+ const remove = levels()[0].querySelector<HTMLButtonElement>(".sort-level-remove[disabled]");
+ expect(remove).not.toBeNull();
+ });
+});
diff --git a/apps/client/src/widgets/dialogs/sort_child_notes.tsx b/apps/client/src/widgets/dialogs/sort_child_notes.tsx
index 89f79dca00..71ca188964 100644
--- a/apps/client/src/widgets/dialogs/sort_child_notes.tsx
+++ b/apps/client/src/widgets/dialogs/sort_child_notes.tsx
@@ -1,18 +1,32 @@
+import "./sort_child_notes.css";
+
import { useState } from "preact/hooks";
import { t } from "../../services/i18n";
+import ActionButton from "../react/ActionButton";
import Button from "../react/Button";
import FormCheckbox from "../react/FormCheckbox";
-import FormRadioGroup from "../react/FormRadioGroup";
+import FormSelect from "../react/FormSelect";
import FormTextBox from "../react/FormTextBox";
import Modal from "../react/Modal";
+import SegmentedChoice from "../react/SegmentedChoice";
import server from "../../services/server";
import FormGroup from "../react/FormGroup";
import { useTriliumEvent } from "../react/hooks";
+type SortKind = "title" | "dateCreated" | "dateModified" | "label";
+
+interface SortLevel {
+ kind: SortKind;
+ /** The label the level sorts by; only read where {@link kind} is `label`. */
+ labelName: string;
+ descending: boolean;
+}
+
+const NEW_LEVEL: SortLevel = { kind: "title", labelName: "", descending: false };
+
export default function SortChildNotesDialog() {
const [ parentNoteId, setParentNoteId ] = useState<string>();
- const [ sortBy, setSortBy ] = useState("title");
- const [ sortDirection, setSortDirection ] = useState("asc");
+ const [ levels, setLevels ] = useState<SortLevel[]>([ NEW_LEVEL ]);
const [ foldersFirst, setFoldersFirst ] = useState(false);
const [ sortNatural, setSortNatural ] = useState(false);
const [ sortLocale, setSortLocale ] = useState("");
@@ -25,10 +39,14 @@ export default function SortChildNotesDialog() {
setShown(true);
});
+ function updateLevel(index: number, change: Partial<SortLevel>) {
+ setLevels(levels.map((level, i) => (i === index ? { ...level, ...change } : level)));
+ }
+
async function onSubmit() {
- await server.put(`notes/${parentNoteId}/sort-children`, {
- sortBy,
- sortDirection,
+ await server.put(`notes/${parentNoteId}/sort-children`, {
+ sortBy: serializeSortLevels(levels),
+ sortDirection: "asc",
foldersFirst,
sortNatural,
sortLocale
@@ -41,7 +59,7 @@ export default function SortChildNotesDialog() {
<Modal
className="sort-child-notes-dialog"
title={t("sort_child_notes.sort_children_by")}
- size="lg" maxWidth={500}
+ size="lg" maxWidth={560}
onSubmit={onSubmit}
onHidden={() => setShown(false)}
show={shown}
@@ -51,25 +69,56 @@ export default function SortChildNotesDialog() {
</>}
>
<h5>{t("sort_child_notes.sorting_criteria")}</h5>
- <FormRadioGroup
- name="sort-by"
- values={[
- { value: "title", label: t("sort_child_notes.title") },
- { value: "dateCreated", label: t("sort_child_notes.date_created") },
- { value: "dateModified", label: t("sort_child_notes.date_modified") }
- ]}
- currentValue={sortBy} onChange={setSortBy}
- />
- <br/>
-
- <h5>{t("sort_child_notes.sorting_direction")}</h5>
- <FormRadioGroup
- name="sort-direction"
- values={[
- { value: "asc", label: t("sort_child_notes.ascending") },
- { value: "desc", label: t("sort_child_notes.descending") }
- ]}
- currentValue={sortDirection} onChange={setSortDirection}
+ <p className="sort-levels-description">{t("sort_child_notes.sorting_criteria_description")}</p>
+ <div className="sort-levels">
+ {levels.map((level, index) => (
+ <div className="sort-level" key={index}>
+ <FormSelect
+ className="sort-level-kind"
+ values={[
+ { key: "title", title: t("sort_child_notes.title") },
+ { key: "dateCreated", title: t("sort_child_notes.date_created") },
+ { key: "dateModified", title: t("sort_child_notes.date_modified") },
+ { key: "label", title: t("sort_child_notes.label") }
+ ]}
+ keyProperty="key"
+ titleProperty="title"
+ currentValue={level.kind}
+ onChange={(kind) => updateLevel(index, { kind: kind as SortKind })}
+ />
+ {level.kind === "label" && (
+ <FormTextBox
+ className="sort-level-label"
+ placeholder={t("sort_child_notes.label_name")}
+ required
+ currentValue={level.labelName}
+ onChange={(labelName) => updateLevel(index, { labelName })}
+ />
+ )}
+ <SegmentedChoice
+ options={[
+ { value: "asc", label: t("sort_child_notes.ascending") },
+ { value: "desc", label: t("sort_child_notes.descending") }
+ ]}
+ currentValue={level.descending ? "desc" : "asc"}
+ onChange={(direction) => updateLevel(index, { descending: direction === "desc" })}
+ />
+ <ActionButton
+ className="sort-level-remove"
+ icon="bx bx-x"
+ text={t("sort_child_notes.remove_level")}
+ disabled={levels.length === 1}
+ onClick={() => setLevels(levels.filter((_, i) => i !== index))}
+ />
+ </div>
+ ))}
+ </div>
+ <Button
+ className="sort-level-add"
+ icon="bx bx-plus"
+ text={t("sort_child_notes.add_level")}
+ size="small"
+ onClick={() => setLevels([ ...levels, NEW_LEVEL ])}
/>
<br/>
@@ -93,3 +142,12 @@ export default function SortChildNotesDialog() {
</Modal>
)
}
+
+/** Writes the levels in the `#sorted` format the server parses, e.g. `priority:desc,title:asc`. */
+export function serializeSortLevels(levels: SortLevel[]) {
+ return levels
+ .map((level) => ({ ...level, key: level.kind === "label" ? level.labelName.trim() : level.kind }))
+ .filter((level) => level.key)
+ .map((level) => `${level.key}:${level.descending ? "desc" : "asc"}`)
+ .join(",");
+}
diff --git a/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Sorting Notes.md b/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Sorting Notes.md
index f4dad4cc09..3e6cbfe1c1 100644
--- a/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Sorting Notes.md
+++ b/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Sorting Notes.md
@@ -5,8 +5,8 @@ You can sort notes by right-clicking the parent note in the <a class="reference
The sorting dialog allows:
-* Sorting by title, creation or modification date.
-* Changing sorting direction can also be adjusted (ascending or descending).
+* Sorting by title, creation or modification date, or by the value of a label on the child notes.
+* Sorting by several such criteria in turn, each ascending or descending: the next level only decides between notes the previous ones left equal.
* Ensuring folders are displayed at the top.
* Natural sort, based on the sorting rules of a particular language.