Skip to content

Build your personal knowledge base with Trilium Notes

feat(sort): compare levels the way a search's orderBy does

BeatLink6b35bff42304
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 767d03712b..9f343574b4 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -510,6 +510,7 @@
"descending": "Descending",
"folders": "Folders",
"sort_folders_at_top": "sort folders at the top",
+ "folders_follow_first_level": "At the bottom instead when the first level is descending.",
"natural_sort": "Natural Sort",
"sort_with_respect_to_different_character_sorting": "sort with respect to different character sorting and collation rules in different languages or regions.",
"natural_sort_language": "Natural sort language",
diff --git a/apps/client/src/widgets/dialogs/sort_child_notes.tsx b/apps/client/src/widgets/dialogs/sort_child_notes.tsx
index dfe0106822..1d1ba12722 100644
--- a/apps/client/src/widgets/dialogs/sort_child_notes.tsx
+++ b/apps/client/src/widgets/dialogs/sort_child_notes.tsx
@@ -68,9 +68,10 @@ export default function SortChildNotesDialog() {
];
async function onSubmit() {
+ // The first level's direction also decides where folders group and how ties break.
await server.put(`notes/${parentNoteId}/sort-children`, {
sortBy: serializeSortLevels(levels),
- sortDirection: "asc",
+ sortDirection: levels[0].direction,
foldersFirst,
sortNatural,
sortLocale
@@ -159,6 +160,7 @@ export default function SortChildNotesDialog() {
<h5>{t("sort_child_notes.folders")}</h5>
<FormCheckbox
label={t("sort_child_notes.sort_folders_at_top")}
+ hint={t("sort_child_notes.folders_follow_first_level")}
name="sort-folders-first"
currentValue={foldersFirst} onChange={setFoldersFirst}
/>
diff --git a/packages/trilium-core/src/services/search/expressions/order_by_and_limit.ts b/packages/trilium-core/src/services/search/expressions/order_by_and_limit.ts
index 32943422d2..a292b16447 100644
--- a/packages/trilium-core/src/services/search/expressions/order_by_and_limit.ts
+++ b/packages/trilium-core/src/services/search/expressions/order_by_and_limit.ts
@@ -1,6 +1,7 @@
"use strict";
import type BNote from "../../../becca/entities/bnote.js";
+import { compareSortValues, isDate, isNumber } from "../../utils/sort_values.js";
import NoteSet from "../note_set.js";
import type SearchContext from "../search_context.js";
import Expression from "./expression.js";
@@ -45,47 +46,13 @@ class OrderByAndLimitExp extends Expression {
notes.sort((a, b) => {
for (const { valueExtractor, smaller, larger } of this.orderDefinitions) {
- let valA: string | number | Date | null = valueExtractor.extract(a);
- let valB: string | number | Date | null = valueExtractor.extract(b);
-
- if (valA === undefined) {
- valA = null;
- }
-
- if (valB === undefined) {
- valB = null;
- }
-
- if (valA === null && valB === null) {
- // neither has attribute at all
- continue;
- } else if (valB === null) {
- return smaller;
- } else if (valA === null) {
- return larger;
- }
-
- // if both are dates, then parse them for dates comparison
- if (typeof valA === "string" && this.isDate(valA) && typeof valB === "string" && this.isDate(valB)) {
- valA = new Date(valA);
- valB = new Date(valB);
- }
-
- // if both are numbers, then parse them for numerical comparison
- else if (typeof valA === "string" && this.isNumber(valA) && typeof valB === "string" && this.isNumber(valB)) {
- valA = parseFloat(valA);
- valB = parseFloat(valB);
+ const result = compareSortValues(
+ valueExtractor.extract(a),
+ valueExtractor.extract(b)
+ );
+ if (result !== 0) {
+ return result < 0 ? smaller : larger;
}
-
- if (!valA && !valB) {
- // the attribute value is empty/zero in both notes so continue to the next order definition
- continue;
- } else if (valA < valB) {
- return smaller;
- } else if (valA > valB) {
- return larger;
- }
- // else the values are equal and continue to next order definition
}
return 0;
@@ -102,18 +69,11 @@ class OrderByAndLimitExp extends Expression {
}
isDate(date: number | string) {
- return !isNaN(new Date(date).getTime());
+ return isDate(date);
}
isNumber(x: number | string) {
- if (typeof x === "number") {
- return true;
- } else if (typeof x === "string") {
- // isNaN will return false for blank string
- return x.trim() !== "" && !isNaN(parseInt(x, 10));
- } else {
- return false;
- }
+ return isNumber(x);
}
}
diff --git a/packages/trilium-core/src/services/tree.spec.ts b/packages/trilium-core/src/services/tree.spec.ts
index 3a41dbbb9d..e7d913be9f 100644
--- a/packages/trilium-core/src/services/tree.spec.ts
+++ b/packages/trilium-core/src/services/tree.spec.ts
@@ -255,19 +255,41 @@ describe("Tree", () => {
expect(orderedTitles).toStrictEqual(["top1", "top2", "b", "a", "bottom2", "bottom1"]);
});
- it("sorts a child without the level's label by its title in the label's place", () => {
+ it("counts a missing label as the largest value; the next level breaks a double miss", () => {
+ const children: Parameters<typeof buildNote>[0]["children"] = [
+ {title: "m", "#order": "z"},
+ {title: "unlabelled", "#area": "b"},
+ {title: "also", "#area": "a"},
+ {title: "a", "#order": "b"}
+ ];
+ for (const [direction, expected] of [
+ ["asc", ["a", "m", "also", "unlabelled"]],
+ ["desc", ["unlabelled", "also", "m", "a"]]
+ ] as const) {
+ const note = buildNote({
+ children, "#sorted": "order, area", "#sortDirection": direction
+ });
+ getContext().init(() => {
+ tree.sortNotesIfNeeded(note.noteId);
+ });
+ expect(note.children.map((child) => child.title)).toStrictEqual([...expected]);
+ }
+ });
+
+ it("compares numbers and dates as such rather than as text", () => {
const note = buildNote({
children: [
- {title: "m", "#order": "z"},
- {title: "unlabelled"},
- {title: "a", "#order": "b"}
+ {title: "ten", "#priority": "10", "#due": "2026-02-01"},
+ {title: "two", "#priority": "2", "#due": "2026-02-01"},
+ {title: "one", "#priority": "1", "#due": "2026-01-15"},
+ {title: "nine", "#priority": "9", "#due": "2026-01-15"}
],
- "#sorted": "order"
+ "#sorted": "due, priority desc"
});
getContext().init(() => {
tree.sortNotesIfNeeded(note.noteId);
});
const orderedTitles = note.children.map((child) => child.title);
- expect(orderedTitles).toStrictEqual(["a", "unlabelled", "m"]);
+ expect(orderedTitles).toStrictEqual(["nine", "one", "ten", "two"]);
});
});
diff --git a/packages/trilium-core/src/services/tree.ts b/packages/trilium-core/src/services/tree.ts
index 520413fb13..1b8431f506 100644
--- a/packages/trilium-core/src/services/tree.ts
+++ b/packages/trilium-core/src/services/tree.ts
@@ -3,6 +3,7 @@
import { parseSortCriteria } from "@triliumnext/commons";
import { getLog } from "./log.js";
+import { compareSortValues } from "./utils/sort_values.js";
import BBranch from "../becca/entities/bbranch.js";
import entityChangesService from "./entity_changes.js";
import becca from "../becca/becca.js";
@@ -129,11 +130,10 @@ function sortNotes(
return a < b ? -1 : a > b ? 1 : 0;
}
- // A child without the level's label sorts by its title in that label's place.
+ // The same rules as a search's orderBy: a child without the label counts as the largest
+ // value, two without it tie, and dates and numbers compare as such rather than as text.
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);
+ const result = compareSortValues(fetchValue(a, key), fetchValue(b, key), compare);
return descending ? -result : result;
}
diff --git a/packages/trilium-core/src/services/utils/sort_values.ts b/packages/trilium-core/src/services/utils/sort_values.ts
new file mode 100644
index 0000000000..a5e519e8e8
--- /dev/null
+++ b/packages/trilium-core/src/services/utils/sort_values.ts
@@ -0,0 +1,62 @@
+/**
+ * Orders two sort values the way a search's `orderBy` and the tree sort both do: a missing value
+ * counts as the largest, two missing or empty values tie so the next level decides, and values that
+ * both read as dates or as numbers compare chronologically or numerically rather than as text.
+ */
+
+export type SortValue = string | number | null | undefined;
+
+type StringComparator = (a: string, b: string) => number;
+
+const compareStringsPlainly: StringComparator = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
+
+/** Returns a negative number when `a` sorts first ascending, positive when `b` does, 0 on a tie. */
+export function compareSortValues(
+ a: SortValue,
+ b: SortValue,
+ compareStrings = compareStringsPlainly
+) {
+ const valA = a ?? null;
+ const valB = b ?? null;
+ if (valA === null && valB === null) {
+ return 0;
+ }
+ if (valB === null) {
+ return -1;
+ }
+ if (valA === null) {
+ return 1;
+ }
+ if (typeof valA === "string" && typeof valB === "string") {
+ if (isDate(valA) && isDate(valB)) {
+ return compareNumbers(new Date(valA).getTime(), new Date(valB).getTime());
+ }
+ if (isNumber(valA) && isNumber(valB)) {
+ return compareNumbers(parseFloat(valA), parseFloat(valB));
+ }
+ return valA === "" && valB === "" ? 0 : compareStrings(valA, valB);
+ }
+ if (typeof valA === "number" && typeof valB === "number") {
+ return compareNumbers(valA, valB);
+ }
+ return valA < valB ? -1 : valA > valB ? 1 : 0;
+}
+
+function compareNumbers(a: number, b: number) {
+ if (!a && !b) {
+ return 0;
+ }
+ return a < b ? -1 : a > b ? 1 : 0;
+}
+
+export function isDate(date: number | string) {
+ return !isNaN(new Date(date).getTime());
+}
+
+export function isNumber(x: number | string) {
+ if (typeof x === "number") {
+ return true;
+ }
+ // isNaN returns false for a blank string.
+ return typeof x === "string" && x.trim() !== "" && !isNaN(parseInt(x, 10));
+}