Skip to content

Build your personal knowledge base with Trilium Notes

fix(sort): compare a tree sort level as text, not as a guessed type

Elian Doran5b701ef3f624
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Sorting Notes.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Sorting Notes.html
index 1c827d358e..e939d7c59c 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Sorting Notes.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Sorting Notes.html
@@ -127,6 +127,5 @@
<li><strong>Alphabetical Sorting</strong>: Used as a last resort when other
criteria result in equality.</li>
</ol>
-<p>Two values that both read as numbers compare numerically (2 before 10)
- and two that both read as dates compare chronologically, as in a search's <code
- spellcheck="false">orderBy</code>; anything else compares as text.</p>
\ No newline at end of file
+<p>All comparisons are made string-wise (e.g., "1" &lt; "2" or "2020-10-10"
+ &lt; "2021-01-15", but also "2" &gt; "10").</p>
\ No newline at end of file
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 203055f0e6..4de3872b9b 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
@@ -64,4 +64,4 @@ Sorting is done by comparing note properties or specific labels 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 as a word after the name, `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.
-Two values that both read as numbers compare numerically (2 before 10) and two that both read as dates compare chronologically, as in a search's `orderBy`; anything else compares as text.
\ No newline at end of file
+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 file
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 a292b16447..e461d3c080 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,7 +1,7 @@
"use strict";
import type BNote from "../../../becca/entities/bnote.js";
-import { compareSortValues, isDate, isNumber } from "../../utils/sort_values.js";
+import { compareSortValues } from "../../utils/sort_values.js";
import NoteSet from "../note_set.js";
import type SearchContext from "../search_context.js";
import Expression from "./expression.js";
@@ -48,7 +48,8 @@ class OrderByAndLimitExp extends Expression {
for (const { valueExtractor, smaller, larger } of this.orderDefinitions) {
const result = compareSortValues(
valueExtractor.extract(a),
- valueExtractor.extract(b)
+ valueExtractor.extract(b),
+ compareValues
);
if (result !== 0) {
return result < 0 ? smaller : larger;
@@ -77,4 +78,42 @@ class OrderByAndLimitExp extends Expression {
}
}
+/**
+ * Compares two values an `orderBy` found on both notes: values that both read as dates compare
+ * chronologically and values that both read as numbers numerically, anything else as text.
+ */
+function compareValues(a: string | number, b: string | number) {
+ let valA: string | number | Date = a;
+ let valB: string | number | Date = b;
+
+ if (typeof valA === "string" && typeof valB === "string") {
+ if (isDate(valA) && isDate(valB)) {
+ valA = new Date(valA);
+ valB = new Date(valB);
+ } else if (isNumber(valA) && isNumber(valB)) {
+ valA = parseFloat(valA);
+ valB = parseFloat(valB);
+ }
+ }
+
+ if (!valA && !valB) {
+ // The value is empty or zero on both notes, so the next order definition decides.
+ return 0;
+ }
+
+ return valA < valB ? -1 : valA > valB ? 1 : 0;
+}
+
+function isDate(date: number | string) {
+ return !isNaN(new Date(date).getTime());
+}
+
+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));
+}
+
export default OrderByAndLimitExp;
diff --git a/packages/trilium-core/src/services/tree.spec.ts b/packages/trilium-core/src/services/tree.spec.ts
index e7d913be9f..c2de5f8efb 100644
--- a/packages/trilium-core/src/services/tree.spec.ts
+++ b/packages/trilium-core/src/services/tree.spec.ts
@@ -276,7 +276,7 @@ describe("Tree", () => {
}
});
- it("compares numbers and dates as such rather than as text", () => {
+ it("compares every level as text, as a single-key #sorted does", () => {
const note = buildNote({
children: [
{title: "ten", "#priority": "10", "#due": "2026-02-01"},
@@ -289,7 +289,25 @@ describe("Tree", () => {
getContext().init(() => {
tree.sortNotesIfNeeded(note.noteId);
});
+ // Within each due date, "9" sorts after "1" and "2" after "10", descending to nine, one
+ // and two, ten. #sortNatural is what orders a level's numbers by their value.
const orderedTitles = note.children.map((child) => child.title);
- expect(orderedTitles).toStrictEqual(["nine", "one", "ten", "two"]);
+ expect(orderedTitles).toStrictEqual(["nine", "one", "two", "ten"]);
+ });
+
+ 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) => {
+ const note = buildNote({
+ children: startingOrder.map((title) => ({title})),
+ "#sorted": ""
+ });
+ getContext().init(() => {
+ tree.sortNotesIfNeeded(note.noteId);
+ });
+ return note.children.map((child) => child.title);
+ });
+ expect(orders[0]).toStrictEqual(orders[1]);
+ expect(orders[0].slice(0, 4)).toStrictEqual(["Week 1", "Week 10", "Week 11", "Week 12"]);
});
});
diff --git a/packages/trilium-core/src/services/tree.ts b/packages/trilium-core/src/services/tree.ts
index 1b8431f506..e76a30d1ca 100644
--- a/packages/trilium-core/src/services/tree.ts
+++ b/packages/trilium-core/src/services/tree.ts
@@ -130,8 +130,8 @@ function sortNotes(
return a < b ? -1 : a > b ? 1 : 0;
}
- // 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.
+ // A child without the label counts as the largest value, and two without it tie so the
+ // next level decides.
function compareLevel(a: BNote, b: BNote, key: string, descending: boolean) {
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
index a5e519e8e8..80d33a3382 100644
--- a/packages/trilium-core/src/services/utils/sort_values.ts
+++ b/packages/trilium-core/src/services/utils/sort_values.ts
@@ -1,23 +1,21 @@
/**
- * 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.
+ * Orders two sort values the way a search's `orderBy` and the tree sort both do: a value one note
+ * lacks counts as the largest, and two missing values tie so the next level decides. Each caller
+ * passes how its own present values compare.
*/
-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);
+/** Compares two values that are both present. */
+export type ValueComparator<T extends string | number> = (a: T, b: T) => number;
/** 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
+export function compareSortValues<T extends string | number>(
+ a: T | null | undefined,
+ b: T | null | undefined,
+ compareValues: ValueComparator<T>
) {
const valA = a ?? null;
const valB = b ?? null;
+
if (valA === null && valB === null) {
return 0;
}
@@ -27,36 +25,6 @@ export function compareSortValues(
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));
+ return compareValues(valA, valB);
}