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(core): sort child notes by several criteria at once
BeatLink433a238751b4
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex d695d3e2c9..e352f6e22f 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -571,8 +571,8 @@"run_on_instance": "Define which trilium instance should run this on. Default to all instances.","run_at_hour": "On which hour should this run. Should be used together with <code>#run=hourly</code>. Can be defined multiple times for more runs during the day.","disable_inclusion": "Scripts with this label won't be included into parent script execution.",- "sorted": "Keeps child notes sorted by title alphabetically.",- "sort_direction": "Direction <code>#sorted</code> orders the child notes in: <code>desc</code> for descending, anything else for ascending. Ignored unless <code>#sorted</code> is set.",+ "sorted": "Keeps child notes sorted by title alphabetically. A value sorts by other criteria instead: comma-separated levels of <code>title</code>, <code>dateCreated</code>, <code>dateModified</code> or a label name, each with an optional <code>:asc</code> or <code>:desc</code>, e.g. <code>priority:desc,dueDate</code>.",+ "sort_direction": "Direction <code>#sorted</code> orders the child notes in: <code>desc</code> for descending, anything else for ascending. A level with its own <code>:asc</code>/<code>:desc</code> ignores it. Ignored unless <code>#sorted</code> is set.","sort_folders_first": "Folders (notes with children) should be sorted on top.","top": "Keep given note on top in its parent (applies only on sorted parents).","hide_promoted_attributes": "Hide promoted attributes on this note.",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.mdindex c695a3cac9..f4dad4cc09 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@@ -24,11 +24,11 @@ Child notes can be automatically sorted by attaching specific [labels](../../Adv<tbody><tr><td><code spellcheck="false">#sorted</code></td>- <td><p>Keeps child notes sorted by title alphabetically.</p><p>When given a value, it will sort by the value of another label instead. If one of the child notes doesn't have the specified label, the title will be used for them instead.</p></td>+ <td><p>Keeps child notes sorted by title alphabetically.</p><p>When given a value, it will sort by other criteria instead: a comma-separated list of levels, each <code spellcheck="false">title</code>, <code spellcheck="false">dateCreated</code>, <code spellcheck="false">dateModified</code> or the name of a label on the child notes, optionally followed by <code spellcheck="false">:asc</code> or <code spellcheck="false">:desc</code>. For example <code spellcheck="false">#sorted="priority:desc,dueDate"</code> sorts by priority, highest first, and notes of equal priority by due date. If one of the child notes doesn't have a level's label, its title is used in its place.</p></td></tr><tr><td><code spellcheck="false">#sortDirection</code></td>- <td><p>If <code spellcheck="false">sorted</code> is applied, specifies the direction of the sort:</p><ul><li><code spellcheck="false">ASC</code>, ascending (default)</li><li><code spellcheck="false">DESC</code>, descending</li></ul></td>+ <td><p>If <code spellcheck="false">sorted</code> is applied, specifies the direction of the sort:</p><ul><li><code spellcheck="false">ASC</code>, ascending (default)</li><li><code spellcheck="false">DESC</code>, descending</li></ul><p>A level of <code spellcheck="false">sorted</code> with its own <code spellcheck="false">:asc</code> or <code spellcheck="false">:desc</code> keeps that direction regardless.</p></td></tr><tr><td><code spellcheck="false">#sortFoldersFirst</code></td>@@ -61,6 +61,7 @@ Sorting is done by comparing note properties or specific labels on child notes.* **Default Sorting**: If `#sorted` has no value, notes are sorted alphabetically.* **Property Sorting**: If `#sorted` is set to `title`, `dateModified`, or `dateCreated`, notes are sorted based on the specified property.* **Label Sorting**: If `#sorted` has any other value, this value is treated as the name of a child note's label, and sorting is based on the values of this label. For example, setting `#sorted=myOrder` on the parent note and using `#myOrder=001`, `#myOrder=002`, etc., on child notes.+ * **Multi-Level Sorting**: Several of the above can be combined, separated by commas; each level is applied only where the previous ones are equal. Every level can carry its own direction with `:asc` or `:desc`, otherwise it follows `#sortDirection`. For example `#sorted="priority:desc,area,dateCreated"` sorts by priority, highest first, then by area, then by creation date.4. **Alphabetical Sorting**: Used as a last resort when other criteria result in equality.All comparisons are made string-wise (e.g., "1" \< "2" or "2020-10-10" < "2021-01-15", but also "2" \> "10").\ No newline at end of filediff --git a/packages/trilium-core/src/services/backend_script_api.ts b/packages/trilium-core/src/services/backend_script_api.tsindex af5a901b81..797bd8609e 100644--- a/packages/trilium-core/src/services/backend_script_api.ts+++ b/packages/trilium-core/src/services/backend_script_api.ts@@ -344,9 +344,11 @@ export interface Api {sortNotes(parentNoteId: string,sortConfig: {- /** 'title', 'dateCreated', 'dateModified' or a label name- * See {@link https://triliumnext.github.io/Docs/Wiki/sorting.html} for details. */+ /** Comma-separated levels of 'title', 'dateCreated', 'dateModified' or a label name, each with an+ * optional ':asc' or ':desc' flag, e.g. 'priority:desc,dueDate'. The format is that of the+ * #sorted label, see the "Sorting Notes" page of the User Guide. */sortBy?: string;+ /** Sorts the levels without a flag of their own descending. */reverse?: boolean;foldersFirst?: boolean;}diff --git a/packages/trilium-core/src/services/handlers.spec.ts b/packages/trilium-core/src/services/handlers.spec.tsindex c09842b66a..8a4ec524e7 100644--- a/packages/trilium-core/src/services/handlers.spec.ts+++ b/packages/trilium-core/src/services/handlers.spec.ts@@ -111,6 +111,19 @@ describe("handlers", () => {expect(sortNotesIfNeeded).toHaveBeenCalledWith("p");});+ it("re-sorts the parent only when the changed label is one of the #sorted levels", () => {+ buildNote({ id: "ml-par", children: [{ id: "ml-chld" }] });+ addAttribute("ml-par", "label", "sorted", "priority:desc,dueDate");++ const unrelated = addAttribute("ml-chld", "label", "priorityNote", "x");+ eventService.emit(eventService.ENTITY_CHANGED, { entityName: "attributes", entity: unrelated });+ expect(sortNotesIfNeeded).not.toHaveBeenCalledWith("ml-par");++ const dueDate = addAttribute("ml-chld", "label", "dueDate", "2026-01-01");+ eventService.emit(eventService.ENTITY_CHANGED, { entityName: "attributes", entity: dueDate });+ expect(sortNotesIfNeeded).toHaveBeenCalledWith("ml-par");+ });+it("re-sorts the parent when a sort-affecting label (e.g. 'top') changes", () => {buildNote({ id: "par", children: [{ id: "chld" }] });addAttribute("par", "label", "sorted", "title");diff --git a/packages/trilium-core/src/services/handlers.ts b/packages/trilium-core/src/services/handlers.tsindex f4c828aaa1..d47c3fc008 100644--- a/packages/trilium-core/src/services/handlers.ts+++ b/packages/trilium-core/src/services/handlers.ts@@ -1,7 +1,7 @@import eventService from "./events.js";import { isScriptingEnabled } from "./scripting_guard.js";import scriptService from "./script.js";-import treeService from "./tree.js";+import treeService, { parseSortCriteria } from "./tree.js";import noteService from "./notes.js";import becca from "../becca/becca.js";import BAttribute from "../becca/entities/battribute.js";@@ -193,9 +193,9 @@ function handleMaybeSortingLabel(entity: BAttribute) {}if (- sorted.includes(entity.name) || // hacky check if this label is used in the sortentity.name === "top" ||- entity.name === "bottom"+ entity.name === "bottom" ||+ parseSortCriteria(sorted).some((criterion) => criterion.key === entity.name)) {treeService.sortNotesIfNeeded(parentNote.noteId);}diff --git a/packages/trilium-core/src/services/tree.spec.ts b/packages/trilium-core/src/services/tree.spec.tsindex 363edfa530..16cd1dd860 100644--- a/packages/trilium-core/src/services/tree.spec.ts+++ b/packages/trilium-core/src/services/tree.spec.ts@@ -3,7 +3,7 @@ import {note, NoteBuilder} from "../test/becca_mocking.js";import becca from "../becca/becca.js";import BBranch from "../becca/entities/bbranch.js";import BNote from "../becca/entities/bnote.js";-import tree from "./tree.js";+import tree, { parseSortCriteria } from "./tree.js";import {buildNote} from "../test/becca_easy_mocking.js";import { getContext } from "./context.js";@@ -176,4 +176,57 @@ describe("Tree", () => {expect(orderedTitles).toStrictEqual(["top", "1", "2", "3", "10", "20", "bottom"]);})++ it("sorts by several levels, each with its own direction", () => {+ const note = buildNote({+ children: [+ {title: "c", "#priority": "1", "#area": "home"},+ {title: "b", "#priority": "2", "#area": "work"},+ {title: "a", "#priority": "2", "#area": "home"},+ {title: "d", "#priority": "1", "#area": "work"},+ {title: "e", "#priority": "1", "#area": "home"}+ ],+ "#sorted": "priority:desc, area, title:desc"+ });+ getContext().init(() => {+ tree.sortNotesIfNeeded(note.noteId);+ });+ const orderedTitles = note.children.map((child) => child.title);+ expect(orderedTitles).toStrictEqual(["a", "b", "e", "c", "d"]);+ });++ it("applies #sortDirection to the levels without a direction of their own and to the title tiebreak", () => {+ const note = buildNote({+ children: [+ {title: "a", "#priority": "1"},+ {title: "b", "#priority": "2"},+ {title: "c", "#priority": "2"},+ {title: "top", "#top": ""},+ {title: "bottom", "#bottom": ""}+ ],+ "#sorted": "priority:asc,dateCreated",+ "#sortDirection": "desc"+ });+ getContext().init(() => {+ tree.sortNotesIfNeeded(note.noteId);+ });+ const orderedTitles = note.children.map((child) => child.title);+ expect(orderedTitles).toStrictEqual(["top", "a", "c", "b", "bottom"]);+ });++ it("parses a #sorted value into its levels", () => {+ expect(parseSortCriteria("")).toEqual([{ key: "title", descending: undefined }]);+ expect(parseSortCriteria(null)).toEqual([{ key: "title", descending: undefined }]);+ expect(parseSortCriteria("myOrder")).toEqual([{ key: "myOrder", descending: undefined }]);+ expect(parseSortCriteria(" priority : DESC , , area:asc, title ")).toEqual([+ { key: "priority", descending: true },+ { key: "area", descending: false },+ { key: "title", descending: undefined }+ ]);+ // A colon inside a label name is not a direction flag.+ expect(parseSortCriteria("calendar:view:desc,calendar:view")).toEqual([+ { key: "calendar:view", descending: true },+ { key: "calendar:view", descending: undefined }+ ]);+ });});diff --git a/packages/trilium-core/src/services/tree.ts b/packages/trilium-core/src/services/tree.tsindex 50e52cd212..5ad4fe6fb2 100644--- a/packages/trilium-core/src/services/tree.ts+++ b/packages/trilium-core/src/services/tree.ts@@ -77,10 +77,39 @@ function wouldAddingBranchCreateCycle(parentNoteId: string, childNoteId: string)return parentAncestorNoteIds.some((parentAncestorNoteId) => childSubtreeNoteIds.has(parentAncestorNoteId));}-function sortNotes(parentNoteId: string, customSortBy: string = "title", reverse = false, foldersFirst = false, sortNatural = false, _sortLocale?: string | null) {- if (!customSortBy) {- customSortBy = "title";+export interface SortCriterion {+ /** `title`, `dateCreated`, `dateModified` or the name of a label on the child notes. */+ key: string;+ /** Set by an explicit `:asc`/`:desc` flag; `undefined` follows the parent's `#sortDirection`. */+ descending?: boolean;+}++/**+ * Parses a `#sorted` value such as `priority:desc,dueDate,title` into its levels: comma-separated sort+ * keys, each optionally followed by `:asc` or `:desc`. An empty value sorts by title.+ */+export function parseSortCriteria(value: string | null | undefined): SortCriterion[] {+ const criteria: SortCriterion[] = [];+ for (const level of (value ?? "").split(",")) {+ // Only a trailing flag is a direction, so a label name that contains a colon still works as a key.+ const separator = level.lastIndexOf(":");+ const flag = separator === -1 ? "" : level.slice(separator + 1).trim().toLowerCase();+ const isDirection = flag === "asc" || flag === "desc";+ const key = (isDirection ? level.slice(0, separator) : level).trim();+ if (key) {+ criteria.push({ key, descending: isDirection ? flag === "desc" : undefined });+ }}+ return criteria.length > 0 ? criteria : [{ key: "title" }];+}++/**+ * Sorts the children of `parentNoteId` by the levels of `sortBy` (see {@link parseSortCriteria}); a level+ * without its own direction and the final title tiebreak follow `reverse`. `#top`, `#bottom` and folders+ * take precedence over every level and ignore the direction.+ */+function sortNotes(parentNoteId: string, sortBy: string = "title", reverse = false, foldersFirst = false, sortNatural = false, _sortLocale?: string | null) {+ const criteria = parseSortCriteria(sortBy);// sortLocale can not be empty string or null value, default value must be set to undefined.const sortLocale = _sortLocale || undefined;@@ -94,85 +123,73 @@ function sortNotes(parentNoteId: string, customSortBy: string = "title", reverseconst notes = note.getChildNotes();- function normalize<T>(obj: T | string) {- return obj && typeof obj === "string" ? obj.toLowerCase() : obj;- }+ function fetchValue(note: BNote, key: string): string | null {+ let rawValue: string | null;- notes.sort((a, b) => {-- function fetchValue(note: BNote, key: string) {- let rawValue: string | null;-- if (key === "title") {- const branch = note.getParentBranches().find((branch) => branch.parentNoteId === parentNoteId);- const prefix = branch?.prefix;- rawValue = prefix ? `${prefix} - ${note.title}` : note.title;- } else {- rawValue = ["dateCreated", "dateModified"].includes(key) ? (note as any)[key] : note.getLabelValue(key);- }-- return normalize(rawValue);+ if (key === "title") {+ const branch = note.getParentBranches().find((branch) => branch.parentNoteId === parentNoteId);+ const prefix = branch?.prefix;+ rawValue = prefix ? `${prefix} - ${note.title}` : note.title;+ } else {+ rawValue = ["dateCreated", "dateModified"].includes(key) ? (note as any)[key] : note.getLabelValue(key);}- function compare(a: string, b: string) {- if (!sortNatural) {- // alphabetical sort- return b === null || b === undefined || a < b ? -1 : 1;- } else {- // natural sort- return a.localeCompare(b, sortLocale, { numeric: true, sensitivity: "base" });- }+ return typeof rawValue === "string" ? rawValue.toLowerCase() : rawValue;+ }++ function compare(a: string, b: string) {+ if (sortNatural) {+ return a.localeCompare(b, sortLocale, { numeric: true, sensitivity: "base" });}+ return a < b ? -1 : a > b ? 1 : 0;+ }- const topAEl = fetchValue(a, "top");- const topBEl = fetchValue(b, "top");+ // A child without the level's label sorts by its title in that label's place.+ function compareLevel(a: BNote, b: BNote, key: string, descending: boolean) {+ const valueA = fetchValue(a, key) ?? fetchValue(a, "title") ?? "";+ const valueB = fetchValue(b, key) ?? fetchValue(b, "title") ?? "";+ const result = compare(valueA, valueB);+ return descending ? -result : result;+ }- if (topAEl !== topBEl) {- if (topAEl === null) return reverse ? -1 : 1;- if (topBEl === null) return reverse ? 1 : -1;+ notes.sort((a, b) => {+ const topA = fetchValue(a, "top");+ const topB = fetchValue(b, "top");- // since "top" should not be reversible, we'll reverse it once more to nullify this effect- return compare(topAEl, topBEl) * (reverse ? -1 : 1);+ if (topA !== topB) {+ if (topA === null) return 1;+ if (topB === null) return -1;+ return compare(topA, topB);}- const bottomAEl = fetchValue(a, "bottom");- const bottomBEl = fetchValue(b, "bottom");+ const bottomA = fetchValue(a, "bottom");+ const bottomB = fetchValue(b, "bottom");- if (bottomAEl !== bottomBEl) {- if (bottomAEl === null) return reverse ? 1 : -1;- if (bottomBEl === null) return reverse ? -1 : 1;-- // since "bottom" should not be reversible, we'll reverse it once more to nullify this effect- return compare(bottomBEl, bottomAEl) * (reverse ? -1 : 1);+ if (bottomA !== bottomB) {+ if (bottomA === null) return -1;+ if (bottomB === null) return 1;+ return compare(bottomB, bottomA);}if (foldersFirst) {const aHasChildren = a.hasChildren();const bHasChildren = b.hasChildren();- if ((aHasChildren && !bHasChildren) || (!aHasChildren && bHasChildren)) {- // exactly one note of the two is a directory, so the sorting will be done based on this status+ if (aHasChildren !== bHasChildren) {return aHasChildren ? -1 : 1;}}- const customAEl = fetchValue(a, customSortBy) ?? fetchValue(a, "title") as string;- const customBEl = fetchValue(b, customSortBy) ?? fetchValue(b, "title") as string;-- if (customAEl !== customBEl) {- return compare(customAEl, customBEl);+ for (const { key, descending } of criteria) {+ const result = compareLevel(a, b, key, descending ?? reverse);+ if (result !== 0) {+ return result;+ }}- const titleAEl = fetchValue(a, "title") as string;- const titleBEl = fetchValue(b, "title") as string;-- return compare(titleAEl, titleBEl);+ return compareLevel(a, b, "title", reverse);});- if (reverse) {- notes.reverse();- }-let position = 10;let someBranchUpdated = false;