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
feat(sort): group children by a label with `first`/`last` in #sorted
Elian Doran59b81cc68cd8
diff --git a/packages/commons/src/lib/sort_criteria.spec.ts b/packages/commons/src/lib/sort_criteria.spec.tsindex a12d26592f..8ad37b9f75 100644--- a/packages/commons/src/lib/sort_criteria.spec.ts+++ b/packages/commons/src/lib/sort_criteria.spec.ts@@ -21,14 +21,25 @@ describe("sort criteria", () => {expect(parseSortCriteria("desc")).toEqual([{ key: "desc", descending: undefined }]);});+ it("parses a grouping level written as a key followed by `first` or `last`", () => {+ expect(parseSortCriteria("archived last, pinned FIRST, title")).toStrictEqual([+ { key: "archived", group: "last" },+ { key: "pinned", group: "first" },+ { key: "title", descending: undefined }+ ]);+ // A grouping word on its own is a key, not a grouping.+ expect(parseSortCriteria("last")).toStrictEqual([{ key: "last", descending: undefined }]);+ });+it("writes levels back so that they parse to the same thing", () => {const criteria = [+ { key: "archived", group: "last" as const },{ key: "priority", descending: true },{ key: "dateCreated", descending: false },{ key: "title", descending: undefined }];const written = serializeSortCriteria(criteria);- expect(written).toBe("priority desc, dateCreated asc, title");+ expect(written).toBe("archived last, priority desc, dateCreated asc, title");expect(parseSortCriteria(written)).toEqual(criteria);});});diff --git a/packages/commons/src/lib/sort_criteria.ts b/packages/commons/src/lib/sort_criteria.tsindex 3edfc82f6e..da53538c13 100644--- a/packages/commons/src/lib/sort_criteria.ts+++ b/packages/commons/src/lib/sort_criteria.ts@@ -1,13 +1,17 @@/*** The grammar of the `#sorted` label: comma-separated sort keys, each optionally followed by `asc`* or `desc`, the way a search's `orderBy` is written — `priority desc, dueDate, title`. A key is- * `title`, `dateCreated`, `dateModified` or the name of a label on the child notes.+ * `title`, `dateCreated`, `dateModified` or the name of a label on the child notes. A key followed by+ * `first` or `last` instead groups the children that have that label before or after the rest —+ * `archived last, title`.*/export interface SortCriterion {key: string;/** Set by an explicit `asc`/`desc` after the key; `undefined` follows `#sortDirection`. */descending?: boolean;+ /** Set by `first`/`last` after the key: groups by whether a child has the label. */+ group?: "first" | "last";}/** Parses a `#sorted` value into its levels; an empty value sorts by title. */@@ -16,6 +20,10 @@ export function parseSortCriteria(value: string | null | undefined): SortCriterifor (const level of (value ?? "").split(",")) {const words = level.trim().split(/\s+/);const last = words[words.length - 1].toLowerCase();+ if (words.length > 1 && (last === "first" || last === "last")) {+ criteria.push({ key: words.slice(0, -1).join(" "), group: last });+ continue;+ }const isDirection = words.length > 1 && (last === "asc" || last === "desc");const key = (isDirection ? words.slice(0, -1) : words).join(" ");if (key) {@@ -25,10 +33,13 @@ export function parseSortCriteria(value: string | null | undefined): SortCriterireturn criteria.length > 0 ? criteria : [{ key: "title" }];}-/** Writes levels back into the `#sorted` grammar; only a level without a direction is bare. */+/** Writes levels back into the `#sorted` grammar; only a level without a direction or grouping is bare. */export function serializeSortCriteria(criteria: SortCriterion[]) {return criteria- .map(({ key, descending }) => {+ .map(({ key, descending, group }) => {+ if (group) {+ return `${key} ${group}`;+ }if (descending === undefined) {return key;}diff --git a/packages/trilium-core/src/services/tree.spec.ts b/packages/trilium-core/src/services/tree.spec.tsindex 761a29cbdd..ab3e91b479 100644--- a/packages/trilium-core/src/services/tree.spec.ts+++ b/packages/trilium-core/src/services/tree.spec.ts@@ -297,6 +297,44 @@ describe("Tree", () => {expect(orderedTitles).toStrictEqual(["nine", "one", "two", "ten"]);});+ it("groups the children that have a label last or first, whatever the direction", () => {+ const children: Parameters<typeof buildNote>[0]["children"] = [+ {title: "b", "#archived": ""},+ {title: "c"},+ {title: "d", "#archived": "false"},+ {title: "a", "#archived": "", "#pinned": ""},+ {title: "e", "#pinned": "yes"}+ ];+ for (const [sorted, direction, expected] of [+ ["archived last", "asc", ["c", "d", "e", "a", "b"]],+ ["archived last", "desc", ["e", "d", "c", "b", "a"]],+ ["pinned first, archived last", "asc", ["e", "a", "c", "d", "b"]]+ ] as const) {+ const note = buildNote({children, "#sorted": sorted, "#sortDirection": direction});+ getContext().init(() => {+ tree.sortNotesIfNeeded(note.noteId);+ });+ expect(note.children.map((child) => child.title)).toStrictEqual([...expected]);+ }+ });++ it("keeps #top and #bottom outside a grouping level", () => {+ const note = buildNote({+ children: [+ {title: "archived top", "#top": "", "#archived": ""},+ {title: "a", "#archived": ""},+ {title: "bottom", "#bottom": ""},+ {title: "b"}+ ],+ "#sorted": "archived last"+ });+ getContext().init(() => {+ tree.sortNotesIfNeeded(note.noteId);+ });+ const orderedTitles = note.children.map((child) => child.title);+ expect(orderedTitles).toStrictEqual(["archived top", "b", "a", "bottom"]);+ });+it("orders the same children the same way whatever order they start in", () => {const titles = Array.from({length: 53}, (_, index) => `Week ${index + 1}`);const orders = [titles, [...titles].reverse()].map((startingOrder) => {diff --git a/packages/trilium-core/src/services/tree.ts b/packages/trilium-core/src/services/tree.tsindex 51fce019ea..ea819916cf 100644--- a/packages/trilium-core/src/services/tree.ts+++ b/packages/trilium-core/src/services/tree.ts@@ -92,7 +92,8 @@ function wouldAddingBranchCreateCycle(parentNoteId: string, childNoteId: string)/*** Sorts the children of `parentNoteId` by the levels of `sortBy`; `reverse` is the direction of a- * level without its own, of the folders grouping and of ties, never of `#top` and `#bottom`.+ * level without its own, of the folders grouping and of ties, never of `#top`, `#bottom` or a+ * `first`/`last` grouping level.*/function sortNotes(parentNoteId: string,@@ -155,6 +156,15 @@ function sortNotes();}+ // Orders by whether each child has a truthy `key` label, ignoring its value and `reverse`.+ function compareGroup(a: BNote, b: BNote, key: string, group: "first" | "last") {+ const hasA = a.isLabelTruthy(key);+ if (hasA === b.isLabelTruthy(key)) {+ return 0;+ }+ return (hasA ? -1 : 1) * (group === "last" ? -1 : 1);+ }+notes.sort((a, b) => {const topA = fetchValue(a, "top");const topB = fetchValue(b, "top");@@ -184,8 +194,10 @@ function sortNotes(}}- for (const { key, descending } of criteria) {- const result = compareLevel(a, b, key, descending ?? reverse);+ for (const { key, descending, group } of criteria) {+ const result = group+ ? compareGroup(a, b, key, group)+ : compareLevel(a, b, key, descending ?? reverse);if (result !== 0) {return result;}