Skip to content

Build your personal knowledge base with Trilium Notes

feat(sort): write a #sorted label level with `#`, as search's orderBy does

Elian Doran4aa0f0665128
diff --git a/apps/client/src/widgets/dialogs/sort_child_notes.spec.tsx b/apps/client/src/widgets/dialogs/sort_child_notes.spec.tsx
index 162e7ebc34..70643dda79 100644
--- a/apps/client/src/widgets/dialogs/sort_child_notes.spec.tsx
+++ b/apps/client/src/widgets/dialogs/sort_child_notes.spec.tsx
@@ -12,13 +12,13 @@ vi.mock("../../services/i18n", () => ({
}));
describe("serializeSortLevels", () => {
- it("writes each level as its key plus desc where descending, skipping a nameless label", () => {
+ it("writes each level as its key and direction, with `#` before a label, skipping a nameless label", () => {
expect(serializeSortLevels([
{ kind: "label", labelName: " priority ", direction: "desc" },
{ kind: "label", labelName: "", direction: "asc" },
{ kind: "dateCreated", labelName: "", direction: "asc" },
{ kind: "title", labelName: "ignored", direction: "desc" }
- ])).toBe("priority desc, dateCreated asc, title desc");
+ ])).toBe("#priority desc, dateCreated asc, title desc");
});
});
@@ -119,7 +119,7 @@ describe("SortChildNotesDialog", () => {
await submit();
// The first level's direction is the request's, which is what groups folders last.
expect(put).toHaveBeenCalledWith("notes/parent/sort-children", expect.objectContaining({
- sortBy: "priority desc, dateModified asc",
+ sortBy: "#priority desc, dateModified asc",
sortDirection: "desc"
}));
});
diff --git a/apps/client/src/widgets/dialogs/sort_child_notes.tsx b/apps/client/src/widgets/dialogs/sort_child_notes.tsx
index 1ab239da61..8e6c856da0 100644
--- a/apps/client/src/widgets/dialogs/sort_child_notes.tsx
+++ b/apps/client/src/widgets/dialogs/sort_child_notes.tsx
@@ -197,7 +197,11 @@ export function serializeSortLevels(levels: SortLevel[]) {
for (const level of levels) {
const key = level.kind === "label" ? level.labelName.trim() : level.kind;
if (key) {
- criteria.push({ key, descending: level.direction === "desc" });
+ criteria.push({
+ key,
+ isLabel: level.kind === "label",
+ descending: level.direction === "desc"
+ });
}
}
return serializeSortCriteria(criteria);
diff --git a/packages/commons/src/lib/sort_criteria.spec.ts b/packages/commons/src/lib/sort_criteria.spec.ts
index 8ad37b9f75..260b39bb4d 100644
--- a/packages/commons/src/lib/sort_criteria.spec.ts
+++ b/packages/commons/src/lib/sort_criteria.spec.ts
@@ -3,43 +3,67 @@ import { describe, expect, it } from "vitest";
import { parseSortCriteria, serializeSortCriteria } from "./sort_criteria.js";
describe("sort criteria", () => {
- it("parses a #sorted value into its levels", () => {
- expect(parseSortCriteria("")).toEqual([{ key: "title" }]);
- expect(parseSortCriteria(null)).toEqual([{ key: "title" }]);
- 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 }
+ it("reads a single bare key the original way: a property by name, otherwise a label", () => {
+ expect(parseSortCriteria("")).toStrictEqual([{ key: "title", isLabel: false }]);
+ expect(parseSortCriteria(null)).toStrictEqual([{ key: "title", isLabel: false }]);
+ expect(parseSortCriteria(" dateCreated ")).toStrictEqual([
+ { key: "dateCreated", isLabel: false }
]);
- // A colon is an ordinary character of a label name.
- expect(parseSortCriteria("calendar:view desc,calendar:view")).toEqual([
- { key: "calendar:view", descending: true },
- { key: "calendar:view", descending: undefined }
+ expect(parseSortCriteria("myOrder")).toStrictEqual([{ key: "myOrder", isLabel: true }]);
+ expect(parseSortCriteria("calendar:view")).toStrictEqual([
+ { key: "calendar:view", isLabel: true }
+ ]);
+ // A direction or grouping word on its own is a label name.
+ expect(parseSortCriteria("desc")).toStrictEqual([{ key: "desc", isLabel: true }]);
+ expect(parseSortCriteria("last")).toStrictEqual([{ key: "last", isLabel: true }]);
+ });
+
+ it("parses levels, with `#` before a label and a bare property", () => {
+ expect(parseSortCriteria(" #priority DESC , , #area asc, title ")).toStrictEqual([
+ { key: "priority", isLabel: true, descending: true },
+ { key: "area", isLabel: true, descending: false },
+ { key: "title", isLabel: false }
+ ]);
+ expect(parseSortCriteria("#myOrder")).toStrictEqual([{ key: "myOrder", isLabel: true }]);
+ // `#` reaches a label that shares a property's name.
+ expect(parseSortCriteria("#title desc,#calendar:view")).toStrictEqual([
+ { key: "title", isLabel: true, descending: true },
+ { key: "calendar:view", isLabel: true }
+ ]);
+ expect(parseSortCriteria("dateModified desc, title")).toStrictEqual([
+ { key: "dateModified", isLabel: false, descending: true },
+ { key: "title", isLabel: false }
+ ]);
+ // Outside a single bare key, a bare word is a property even when no such property exists.
+ expect(parseSortCriteria("priority desc, area")).toStrictEqual([
+ { key: "priority", isLabel: false, descending: true },
+ { key: "area", isLabel: false }
]);
- // A direction word on its own is a key, not a direction.
- 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 }
+ expect(parseSortCriteria("#archived last, #pinned FIRST, title")).toStrictEqual([
+ { key: "archived", isLabel: true, group: "last" },
+ { key: "pinned", isLabel: true, group: "first" },
+ { key: "title", isLabel: false }
]);
- // 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 }
+ { key: "archived", isLabel: true, group: "last" as const },
+ { key: "priority", isLabel: true, descending: true },
+ { key: "dateCreated", isLabel: false, descending: false },
+ { key: "title", isLabel: false }
];
const written = serializeSortCriteria(criteria);
- expect(written).toBe("archived last, priority desc, dateCreated asc, title");
- expect(parseSortCriteria(written)).toEqual(criteria);
+ expect(written).toBe("#archived last, #priority desc, dateCreated asc, title");
+ expect(parseSortCriteria(written)).toStrictEqual(criteria);
+
+ // A lone label keeps its `#`, which reads the same as the bare key it replaces.
+ const singles = [{ key: "myOrder", isLabel: true }, { key: "title", isLabel: false }];
+ for (const single of singles) {
+ expect(parseSortCriteria(serializeSortCriteria([single]))).toStrictEqual([single]);
+ }
});
});
diff --git a/packages/commons/src/lib/sort_criteria.ts b/packages/commons/src/lib/sort_criteria.ts
index da53538c13..a58e138762 100644
--- a/packages/commons/src/lib/sort_criteria.ts
+++ b/packages/commons/src/lib/sort_criteria.ts
@@ -1,14 +1,21 @@
/**
- * 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. A key followed by
- * `first` or `last` instead groups the children that have that label before or after the rest —
- * `archived last, title`.
+ * 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 a label on the child notes written with `#`, or a bare property: `title`, `dateCreated` or
+ * `dateModified`. A key followed by `first` or `last` instead groups the children that have that
+ * label before or after the rest — `#archived last, title`.
+ *
+ * A value that is a single bare key keeps its original meaning: a property when it names one,
+ * otherwise a label, so `#sorted=myOrder` sorts by `#myOrder`.
*/
+export const SORT_PROPERTIES = ["title", "dateCreated", "dateModified"];
+
export interface SortCriterion {
+ /** A label name where {@link isLabel} is set, a property name otherwise. */
key: string;
- /** Set by an explicit `asc`/`desc` after the key; `undefined` follows `#sortDirection`. */
+ isLabel: boolean;
+ /** Set by an explicit `asc`/`desc` after the key; absent follows `#sortDirection`. */
descending?: boolean;
/** Set by `first`/`last` after the key: groups by whether a child has the label. */
group?: "first" | "last";
@@ -16,34 +23,47 @@ export interface SortCriterion {
/** Parses a `#sorted` value into its levels; an empty value sorts by title. */
export function parseSortCriteria(value: string | null | undefined): SortCriterion[] {
+ const trimmed = (value ?? "").trim();
+ if (/^[^\s,#]+$/.test(trimmed)) {
+ return [{ key: trimmed, isLabel: !SORT_PROPERTIES.includes(trimmed) }];
+ }
+
const criteria: SortCriterion[] = [];
- for (const level of (value ?? "").split(",")) {
+ for (const level of trimmed.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 });
+ const hasSuffix = words.length > 1
+ && ["asc", "desc", "first", "last"].includes(last);
+ const name = (hasSuffix ? words.slice(0, -1) : words).join(" ");
+ const isLabel = name.startsWith("#");
+ const key = isLabel ? name.slice(1) : name;
+ if (!key) {
continue;
}
- const isDirection = words.length > 1 && (last === "asc" || last === "desc");
- const key = (isDirection ? words.slice(0, -1) : words).join(" ");
- if (key) {
- criteria.push({ key, descending: isDirection ? last === "desc" : undefined });
+
+ const criterion: SortCriterion = { key, isLabel };
+ if (hasSuffix && (last === "first" || last === "last")) {
+ criterion.group = last;
+ } else if (hasSuffix) {
+ criterion.descending = last === "desc";
}
+ criteria.push(criterion);
}
- return criteria.length > 0 ? criteria : [{ key: "title" }];
+ return criteria.length > 0 ? criteria : [{ key: "title", isLabel: false }];
}
-/** Writes levels back into the `#sorted` grammar; only a level without a direction or grouping is bare. */
+/** Writes levels back into the `#sorted` grammar, each label with its `#`. */
export function serializeSortCriteria(criteria: SortCriterion[]) {
return criteria
- .map(({ key, descending, group }) => {
+ .map(({ key, isLabel, descending, group }) => {
+ const name = isLabel ? `#${key}` : key;
if (group) {
- return `${key} ${group}`;
+ return `${name} ${group}`;
}
if (descending === undefined) {
- return key;
+ return name;
}
- return `${key} ${descending ? "desc" : "asc"}`;
+ return `${name} ${descending ? "desc" : "asc"}`;
})
.join(", ");
}
diff --git a/packages/trilium-core/src/services/handlers.spec.ts b/packages/trilium-core/src/services/handlers.spec.ts
index 2d344765b2..0892b573f1 100644
--- a/packages/trilium-core/src/services/handlers.spec.ts
+++ b/packages/trilium-core/src/services/handlers.spec.ts
@@ -113,12 +113,17 @@ describe("handlers", () => {
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");
+ addAttribute("ml-par", "label", "sorted", "#priority desc, #dueDate, title");
const unrelated = addAttribute("ml-chld", "label", "priorityNote", "x");
eventService.emit(eventService.ENTITY_CHANGED, {
entityName: "attributes", entity: unrelated
});
+ // A bare `title` is the note's title, not a label.
+ const titleLabel = addAttribute("ml-chld", "label", "title", "x");
+ eventService.emit(eventService.ENTITY_CHANGED, {
+ entityName: "attributes", entity: titleLabel
+ });
expect(sortNotesIfNeeded).not.toHaveBeenCalledWith("ml-par");
const dueDate = addAttribute("ml-chld", "label", "dueDate", "2026-01-01");
diff --git a/packages/trilium-core/src/services/handlers.ts b/packages/trilium-core/src/services/handlers.ts
index ebe1eae148..9a78829b05 100644
--- a/packages/trilium-core/src/services/handlers.ts
+++ b/packages/trilium-core/src/services/handlers.ts
@@ -197,7 +197,7 @@ function handleMaybeSortingLabel(entity: BAttribute) {
if (
entity.name === "top" ||
entity.name === "bottom" ||
- parseSortCriteria(sorted).some((criterion) => criterion.key === entity.name)
+ parseSortCriteria(sorted).some(({ key, isLabel }) => isLabel && 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.ts
index ab3e91b479..d679b35b5e 100644
--- a/packages/trilium-core/src/services/tree.spec.ts
+++ b/packages/trilium-core/src/services/tree.spec.ts
@@ -186,7 +186,7 @@ describe("Tree", () => {
{title: "d", "#priority": "1", "#area": "work"},
{title: "e", "#priority": "1", "#area": "home"}
],
- "#sorted": "priority desc, area, title desc"
+ "#sorted": "#priority desc, #area, title desc"
});
getContext().init(() => {
tree.sortNotesIfNeeded(note.noteId);
@@ -205,7 +205,7 @@ describe("Tree", () => {
{title: "top", "#top": ""},
{title: "bottom", "#bottom": ""}
],
- "#sorted": "priority asc, area",
+ "#sorted": "#priority asc, #area",
"#sortDirection": "desc"
});
getContext().init(() => {
@@ -269,7 +269,7 @@ describe("Tree", () => {
["desc", ["m", "a", "unlabelled", "also"]]
] as const) {
const note = buildNote({
- children, "#sorted": "order, area", "#sortDirection": direction
+ children, "#sorted": "#order, #area", "#sortDirection": direction
});
getContext().init(() => {
tree.sortNotesIfNeeded(note.noteId);
@@ -286,7 +286,7 @@ describe("Tree", () => {
{title: "one", "#priority": "1", "#due": "2026-01-15"},
{title: "nine", "#priority": "9", "#due": "2026-01-15"}
],
- "#sorted": "due, priority desc"
+ "#sorted": "#due, #priority desc"
});
getContext().init(() => {
tree.sortNotesIfNeeded(note.noteId);
@@ -306,9 +306,9 @@ describe("Tree", () => {
{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"]]
+ ["#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(() => {
@@ -318,6 +318,26 @@ describe("Tree", () => {
}
});
+ it("sorts by a label for `#name` and by a property for a bare name", () => {
+ const children: Parameters<typeof buildNote>[0]["children"] = [
+ {title: "b", "#title": "1", "#area": "x"},
+ {title: "a", "#title": "2", "#area": "y"}
+ ];
+ for (const [sorted, expected] of [
+ ["#title", ["b", "a"]],
+ ["title desc", ["b", "a"]],
+ ["#title desc", ["a", "b"]],
+ // A bare word that names no property ties every child, so the title decides.
+ ["area desc", ["a", "b"]]
+ ] as const) {
+ const note = buildNote({children, "#sorted": sorted});
+ 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: [
@@ -326,7 +346,7 @@ describe("Tree", () => {
{title: "bottom", "#bottom": ""},
{title: "b"}
],
- "#sorted": "archived last"
+ "#sorted": "#archived last"
});
getContext().init(() => {
tree.sortNotesIfNeeded(note.noteId);
diff --git a/packages/trilium-core/src/services/tree.ts b/packages/trilium-core/src/services/tree.ts
index ea819916cf..cda8a6ec19 100644
--- a/packages/trilium-core/src/services/tree.ts
+++ b/packages/trilium-core/src/services/tree.ts
@@ -1,6 +1,6 @@
"use strict";
-import { parseSortCriteria } from "@triliumnext/commons";
+import { parseSortCriteria, type SortCriterion } from "@triliumnext/commons";
import { getLog } from "./log.js";
import { compareSortValues } from "./utils/sort_values.js";
@@ -117,18 +117,18 @@ function sortNotes(
const notes = note.getChildNotes();
- function fetchValue(note: BNote, key: string): string | null {
- let rawValue: string | null;
+ function fetchValue(note: BNote, key: string, isLabel = true): string | null {
+ let rawValue: string | null = null;
- if (key === "title") {
+ if (isLabel) {
+ rawValue = note.getLabelValue(key);
+ } else 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 = key === "dateCreated" || key === "dateModified"
- ? note[key] ?? null
- : note.getLabelValue(key);
+ } else if (key === "dateCreated" || key === "dateModified") {
+ rawValue = note[key] ?? null;
}
return typeof rawValue === "string" ? rawValue.toLowerCase() : rawValue;
@@ -148,21 +148,26 @@ function sortNotes(
// A child without the label sorts after every child that has it, whichever direction the
// level runs in, so only the values both children have follow `descending`. Two children
// without it tie, leaving the next level to decide.
- function compareLevel(a: BNote, b: BNote, key: string, descending: boolean) {
+ function compareLevel(a: BNote, b: BNote, level: SortCriterion, descending: boolean) {
return compareSortValues(
- fetchValue(a, key),
- fetchValue(b, key),
+ fetchValue(a, level.key, level.isLabel),
+ fetchValue(b, level.key, level.isLabel),
descending ? compareReversed : compare
);
}
- // 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)) {
+ // Orders by whether each child has a truthy label (or any value of a property), ignoring
+ // the value and `reverse`.
+ function compareGroup(a: BNote, b: BNote, level: SortCriterion) {
+ const hasA = isInGroup(a, level);
+ if (hasA === isInGroup(b, level)) {
return 0;
}
- return (hasA ? -1 : 1) * (group === "last" ? -1 : 1);
+ return (hasA ? -1 : 1) * (level.group === "last" ? -1 : 1);
+ }
+
+ function isInGroup(note: BNote, { key, isLabel }: SortCriterion) {
+ return isLabel ? note.isLabelTruthy(key) : fetchValue(note, key, false) !== null;
}
notes.sort((a, b) => {
@@ -194,16 +199,16 @@ function sortNotes(
}
}
- for (const { key, descending, group } of criteria) {
- const result = group
- ? compareGroup(a, b, key, group)
- : compareLevel(a, b, key, descending ?? reverse);
+ for (const level of criteria) {
+ const result = level.group
+ ? compareGroup(a, b, level)
+ : compareLevel(a, b, level, level.descending ?? reverse);
if (result !== 0) {
return result;
}
}
- return compareLevel(a, b, "title", reverse);
+ return compareLevel(a, b, { key: "title", isLabel: false }, reverse);
});
let position = 10;