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
client: create a shared collection sorting module
Adorian Doranff0bf9f84965
diff --git a/apps/client/src/services/note-dates.spec.ts b/apps/client/src/services/note_dates.spec.tssimilarity index 97%rename from apps/client/src/services/note-dates.spec.tsrename to apps/client/src/services/note_dates.spec.tsindex c07b1d7409..0c82a60910 100644--- a/apps/client/src/services/note-dates.spec.ts+++ b/apps/client/src/services/note_dates.spec.ts@@ -1,6 +1,6 @@import { beforeEach, describe, expect, it, vi } from "vitest";-import { getCreationDate, loadCreationDates } from "./note-dates";+import { getCreationDate, loadCreationDates } from "./note_dates";import server from "./server";/** Names notes uniquely per test: the cache is module-level and is never emptied. */diff --git a/apps/client/src/services/note-dates.ts b/apps/client/src/services/note_dates.tssimilarity index 100%rename from apps/client/src/services/note-dates.tsrename to apps/client/src/services/note_dates.tsdiff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.tsindex 6045a9b0cd..b2fc9a2138 100644--- a/apps/client/src/widgets/collections/board/api.spec.ts+++ b/apps/client/src/widgets/collections/board/api.spec.ts@@ -1779,3 +1779,71 @@ describe("the promoted attributes a card shows", () => {.toEqual([ { name: "dueDate" }, { name: "owner", hidden: true } ]);});});++describe("how a column orders its cards", () => {+ it("reads a column nobody has sorted as the order the user arranged", () => {+ const { api } = createApi({ columns: [ { value: "To Do" } ] }, [ "To Do" ]);++ expect(api.getColumnSort("To Do")).toEqual({ orderBy: undefined, isDescending: false });+ expect(api.getColumnSort("Unwritten")).toEqual({ orderBy: undefined, isDescending: false });+ });++ it("stores what a column sorts by, and clears it back to the manual order", async () => {+ const { api, saved } = createApi(+ { columns: [ { value: "To Do", icon: "bx bx-list-ul" }, { value: "Done" } ] },+ [ "To Do", "Done" ]);++ await api.setColumnSort("To Do", "attr:dueDate");+ expect(saved.at(-1)?.columns).toEqual([+ { value: "To Do", icon: "bx bx-list-ul", orderBy: "attr:dueDate" },+ { value: "Done" }+ ]);+ expect(api.getColumnSort("To Do"))+ .toEqual({ orderBy: "attr:dueDate", isDescending: false });++ // Strict, so the assertion catches the key being stored as undefined rather than dropped.+ await api.setColumnSort("To Do", undefined);+ expect(saved.at(-1)?.columns)+ .toStrictEqual([ { value: "To Do", icon: "bx bx-list-ul" }, { value: "Done" } ]);+ });++ it("stores the direction and clears it rather than storing it false", async () => {+ const { api, saved } = createApi({ columns: [ { value: "To Do" } ] }, [ "To Do" ]);++ await api.setColumnSort("To Do", "title");+ await api.setColumnSortDirection("To Do", true);+ expect(saved.at(-1)?.columns)+ .toEqual([ { value: "To Do", orderBy: "title", descendingOrder: true } ]);+ expect(api.getColumnSort("To Do")).toEqual({ orderBy: "title", isDescending: true });++ await api.setColumnSortDirection("To Do", false);+ expect(saved.at(-1)?.columns).toStrictEqual([ { value: "To Do", orderBy: "title" } ]);+ });++ it("keeps the direction while the key changes, and reads a stale key as manual", async () => {+ const { api, saved } = createApi(+ { columns: [ { value: "To Do", orderBy: "creationDate", descendingOrder: true } ] },+ [ "To Do" ]);++ expect(api.getColumnSort("To Do"))+ .toEqual({ orderBy: "creationDate", isDescending: true });++ await api.setColumnSort("To Do", "title");+ expect(saved.at(-1)?.columns)+ .toEqual([ { value: "To Do", orderBy: "title", descendingOrder: true } ]);++ // A key written by a newer version, or by hand, leaves the column in the manual order.+ const stale = createApi(+ { columns: [ { value: "To Do", orderBy: "dateModified" } ] }, [ "To Do" ]);+ expect(stale.api.getColumnSort("To Do").orderBy).toBeUndefined();+ });++ it("writes an entry for a column that has none yet, where the board draws it", async () => {+ const { api, saved } = createApi(+ { columns: [ { value: "To Do" } ] }, [ "To Do", "Doing", "Done" ]);++ await api.setColumnSort("Doing", "title");+ expect(saved.at(-1)?.columns)+ .toEqual([ { value: "To Do" }, { value: "Doing", orderBy: "title" } ]);+ });+});diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.tsindex ded9c542d9..6390ec57d3 100644--- a/apps/client/src/widgets/collections/board/api.ts+++ b/apps/client/src/widgets/collections/board/api.ts@@ -18,6 +18,7 @@ import {type PromotedAttribute, resolvePromotedAttributes, storedPromotedAttributes,visiblePromotedAttributeNames} from "../promoted_attributes";+import { parseSortKey, type SortKey } from "../sorting";import { BoardColumnData, BoardViewData } from ".";import { currentCardTemplate, DEFAULT_CARD_TEMPLATES } from "./card_templates";import {@@ -615,6 +616,29 @@ export default class BoardApi {await this.updateColumn(column, { limit });}+ /**+ * How a column orders its cards.+ *+ * @returns the key to sort by, absent for the manual order, and its direction.+ */+ getColumnSort(column: string) {+ const stored = this.viewConfig?.columns?.find(col => col.value === column);+ return {+ orderBy: parseSortKey(stored?.orderBy),+ isDescending: !!stored?.descendingOrder+ };+ }++ /** Sets what a column sorts by. Pass `undefined` for the order the user arranges by hand. */+ async setColumnSort(column: string, orderBy: SortKey | undefined) {+ await this.updateColumn(column, { orderBy });+ }++ /** Sets whether a column's order runs backwards. */+ async setColumnSortDirection(column: string, isDescending: boolean) {+ await this.updateColumn(column, { descendingOrder: isDescending });+ }+/** Whether the inbox also collects notes deeper than the board's direct children. */async setInboxNested(nested: boolean) {await this.updateColumn(INBOX_COLUMN, { nested });@@ -797,6 +821,8 @@ export default class BoardApi {if (!updated.keepCollapsed) delete updated.keepCollapsed;if (!updated.displayName) delete updated.displayName;if (!updated.limit) delete updated.limit;+ if (!updated.orderBy) delete updated.orderBy;+ if (!updated.descendingOrder) delete updated.descendingOrder;return updated;};diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsxindex 1e1242158a..6fb4f1c4d5 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -115,6 +115,13 @@ export interface BoardColumnData {displayName?: string;/** The note limit, absent if disabled. */limit?: number;+ /**+ * How the column orders its cards, as `SortKey` in `collections/sorting` spells it. Absent for+ * the manual order, which is the order of the board's children.+ */+ orderBy?: string;+ /** Whether that order runs backwards. Absent while it runs forwards. */+ descendingOrder?: boolean;}interface CardDrag {diff --git a/apps/client/src/widgets/collections/sorting.spec.ts b/apps/client/src/widgets/collections/sorting.spec.tsnew file mode 100644index 0000000000..5559cdfdaf--- /dev/null+++ b/apps/client/src/widgets/collections/sorting.spec.ts@@ -0,0 +1,231 @@+import { describe, expect, it } from "vitest";++import type FNote from "../../entities/fnote";+import froca from "../../services/froca";+import { buildNote } from "../../test/easy-froca";+import type { PromotedAttribute } from "./promoted_attributes";+import { parseSortKey, sortItems, type SortContext, type SortKey } from "./sorting";++/** The label type a definition declares, or "relation" when the field is a relation. */+type FieldType = PromotedAttribute["labelType"] | "relation";++interface Item {+ note: FNote;+ createdAt?: number;+}++/** One note to sort, with the single attribute the tests give it. */+interface ItemDraft {+ title: string;+ createdAt?: number;+ "#field"?: string;+ "~field"?: string;+}++describe("parseSortKey", () => {+ it("reads the keys a column can be sorted by", () => {+ expect(parseSortKey("title")).toBe("title");+ expect(parseSortKey("creationDate")).toBe("creationDate");+ expect(parseSortKey("attr:priority")).toBe("attr:priority");+ });++ it("reads everything else as the manual order", () => {+ for (const orderBy of [ undefined, null, "", "none", "attr:", "dateModified" ]) {+ expect(parseSortKey(orderBy)).toBeUndefined();+ }+ });+});++describe("sortItems", () => {+ it("sorts titles as the user reads them, digits included", () => {+ const items = build([+ { title: "Task 10" }, { title: "task 2" }, { title: "Alpha" }+ ]);++ expect(titles(sort(items, "title"))).toEqual([ "Alpha", "task 2", "Task 10" ]);+ expect(titles(sort(items, "title", true))).toEqual([ "Task 10", "task 2", "Alpha" ]);+ });++ it("sorts by creation date", () => {+ const items = build([+ { title: "Second", createdAt: 200 },+ { title: "First", createdAt: 100 },+ { title: "Third", createdAt: 300 }+ ]);++ expect(titles(sort(items, "creationDate"))).toEqual([ "First", "Second", "Third" ]);+ expect(titles(sort(items, "creationDate", true))).toEqual([ "Third", "Second", "First" ]);+ });++ it("compares text attributes as text and numbers as numbers", () => {+ const text = build([+ { title: "A", "#field": "beta" },+ { title: "B", "#field": "alpha" }+ ]);+ expect(titles(sort(text, "attr:field", false, "text"))).toEqual([ "B", "A" ]);++ const numbers = build([+ { title: "A", "#field": "10" },+ { title: "B", "#field": "9" },+ { title: "C", "#field": "-3.5" }+ ]);+ expect(titles(sort(numbers, "attr:field", false, "number"))).toEqual([ "C", "B", "A" ]);+ });++ it("sorts dates, date-times and times by the instant they name", () => {+ const dates = build([+ { title: "A", "#field": "2026-02-01" },+ { title: "B", "#field": "2025-12-31" }+ ]);+ expect(titles(sort(dates, "attr:field", false, "date"))).toEqual([ "B", "A" ]);++ const dateTimes = build([+ { title: "A", "#field": "2026-01-05T18:00" },+ { title: "B", "#field": "2026-01-05T09:30" }+ ]);+ expect(titles(sort(dateTimes, "attr:field", false, "datetime"))).toEqual([ "B", "A" ]);++ const times = build([+ { title: "A", "#field": "10:00" },+ { title: "B", "#field": "09:59:30" },+ { title: "C", "#field": "9:05" }+ ]);+ expect(titles(sort(times, "attr:field", false, "time"))).toEqual([ "C", "B", "A" ]);+ });++ it("sorts false before true, and reads a label with no value as true", () => {+ const items = build([+ { title: "Bare", "#field": "" },+ { title: "True", "#field": "true" },+ { title: "False", "#field": "false" }+ ]);++ expect(titles(sort(items, "attr:field", false, "boolean")))+ .toEqual([ "False", "Bare", "True" ]);+ });++ it("sorts colours by hue and leaves grey with the items that have no value", () => {+ const items = build([+ { title: "Blue", "#field": "#0000ff" },+ { title: "Red", "#field": "red" },+ { title: "Grey", "#field": "#808080" },+ { title: "Green", "#field": "#00ff00" }+ ]);++ expect(titles(sort(items, "attr:field", false, "color")))+ .toEqual([ "Red", "Green", "Blue", "Grey" ]);+ });++ it("sorts relations by the title of the note they point at", () => {+ const zoe = buildNote({ title: "Zoe" });+ const adam = buildNote({ title: "Adam" });+ const items = build([+ { title: "A", "~field": zoe.noteId },+ { title: "B", "~field": adam.noteId },+ { title: "C", "~field": "unknownNoteId" }+ ]);++ // The unknown target falls back to its ID, which sorts among the titles.+ expect(titles(sort(items, "attr:field", false, "relation"))).toEqual([ "B", "C", "A" ]);+ });++ it("keeps items with no value last in both directions", () => {+ const items = build([+ { title: "None" },+ { title: "Beta", "#field": "beta" },+ { title: "Empty", "#field": "" },+ { title: "Alpha", "#field": "alpha" }+ ]);++ expect(titles(sort(items, "attr:field", false, "text")))+ .toEqual([ "Alpha", "Beta", "None", "Empty" ]);+ expect(titles(sort(items, "attr:field", true, "text")))+ .toEqual([ "Beta", "Alpha", "None", "Empty" ]);+ });++ it("breaks a tie on the creation date, ascending in both directions", () => {+ const items = build([+ { title: "Late", "#field": "same", createdAt: 300 },+ { title: "Early", "#field": "same", createdAt: 100 },+ { title: "Middle", "#field": "same", createdAt: 200 }+ ]);++ expect(titles(sort(items, "attr:field", false, "text")))+ .toEqual([ "Early", "Middle", "Late" ]);+ expect(titles(sort(items, "attr:field", true, "text")))+ .toEqual([ "Early", "Middle", "Late" ]);+ });++ it("falls back to the given order when neither the value nor the date decides", () => {+ const items = build([+ { title: "Third" }, { title: "First" }, { title: "Second" }+ ]);++ expect(titles(sort(items, "attr:field", false, "text")))+ .toEqual([ "Third", "First", "Second" ]);+ });++ it("returns the array it was given when the items are already in order", () => {+ const ordered = build([ { title: "Alpha" }, { title: "Beta" } ]);+ expect(sort(ordered, "title")).toBe(ordered);++ const reversed = build([ { title: "Beta" }, { title: "Alpha" } ]);+ expect(sort(reversed, "title")).not.toBe(reversed);+ });++ it("reads an unparseable value as no value at all", () => {+ const valid = {+ number: "1",+ date: "2026-01-05",+ datetime: "2026-01-05T09:30",+ time: "09:30",+ color: "#ff0000"+ };++ for (const [ type, value ] of Object.entries(valid)) {+ const items = build([+ { title: "Broken", "#field": "not a value" },+ { title: "Fine", "#field": value }+ ]);++ expect(titles(sort(items, "attr:field", false, type as FieldType)))+ .toEqual([ "Fine", "Broken" ]);+ }+ });+});++function build(drafts: ItemDraft[]) {+ return drafts.map(({ createdAt, ...noteDef }) => ({ note: buildNote(noteDef), createdAt }));+}++function sort(items: Item[], key: SortKey, isDescending = false, fieldType?: FieldType) {+ const dates = new Map(items.map(({ note, createdAt }) => [ note.noteId, createdAt ]));+ const definitions = new Map<string, PromotedAttribute>();++ if (fieldType) {+ const isRelation = fieldType === "relation";+ definitions.set("field", {+ name: "field",+ definitionName: isRelation ? "relation:field" : "label:field",+ type: isRelation ? "relation" : "label",+ title: "Field",+ hidden: false,+ definitionValue: "",+ labelType: isRelation ? undefined : fieldType,+ isOwned: true,+ isInheritable: true+ });+ }++ const context: SortContext = {+ definitions,+ creationDate: (noteId) => dates.get(noteId),+ noteTitle: (noteId) => froca.notes[noteId]?.title+ };++ return sortItems(items, key, isDescending, context);+}++function titles(items: Item[]) {+ return items.map(({ note }) => note.title);+}diff --git a/apps/client/src/widgets/collections/sorting.ts b/apps/client/src/widgets/collections/sorting.tsnew file mode 100644index 0000000000..31e2d85f0b--- /dev/null+++ b/apps/client/src/widgets/collections/sorting.ts@@ -0,0 +1,158 @@+import Color from "color";++import type FNote from "../../entities/fnote";+import type { PromotedAttribute } from "./promoted_attributes";++/** What a collection orders its items by. `attr:` names one of its promoted attributes. */+export type SortKey = "title" | "creationDate" | `attr:${string}`;++/** What the sort needs besides the notes themselves. */+export interface SortContext {+ /** The promoted attributes by name, used to decide how each value compares. */+ definitions: ReadonlyMap<string, PromotedAttribute>;+ /** The creation time of a note in milliseconds, or undefined until it is loaded. */+ creationDate: (noteId: string) => number | undefined;+ /** The title of a relation target, or undefined if that note is not in froca. */+ noteTitle: (noteId: string) => string | undefined;+}++/** A value two items are compared by, or undefined when an item has none. */+type SortValue = string | number | undefined;++const ATTRIBUTE_PREFIX = "attr:";++/**+ * Reads a stored `orderBy` setting.+ *+ * @returns the key to sort by, or undefined when the items keep the order the user arranged.+ */+export function parseSortKey(orderBy: string | null | undefined): SortKey | undefined {+ if (orderBy === "title" || orderBy === "creationDate") {+ return orderBy;+ }++ if (orderBy?.startsWith(ATTRIBUTE_PREFIX) && orderBy.length > ATTRIBUTE_PREFIX.length) {+ return orderBy as SortKey;+ }++ return undefined;+}++/**+ * Orders items by one key, breaking ties on the creation date and then on the given order.+ *+ * An item with no value for the key sorts last in both directions. Returns the same array when+ * the items are already in order, so a caller can compare identities.+ */+export function sortItems<T extends { note: FNote }>(+ items: T[], key: SortKey, isDescending: boolean, context: SortContext+): T[] {+ const direction = isDescending ? -1 : 1;+ const entries = items.map((item, index) => ({+ item,+ index,+ value: sortValueOf(item.note, key, context),+ createdAt: context.creationDate(item.note.noteId)+ }));++ entries.sort((a, b) => {+ const primary = compareValues(a.value, b.value);+ if (primary !== 0) {+ // Only defined values reverse, so an item with no value stays last either way.+ const isDefined = a.value !== undefined && b.value !== undefined;+ return isDefined ? primary * direction : primary;+ }++ return compareValues(a.createdAt, b.createdAt) || a.index - b.index;+ });++ return entries.every((entry, index) => entry.index === index)+ ? items+ : entries.map(({ item }) => item);+}++/** Compares text as the user reads it, so "Task 10" sorts after "Task 9". */+const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });++function compareValues(a: SortValue, b: SortValue) {+ if (a === undefined || b === undefined) {+ return a === b ? 0 : (a === undefined ? 1 : -1);+ }++ if (typeof a === "number" && typeof b === "number") {+ return a - b;+ }++ return collator.compare(String(a), String(b));+}++function sortValueOf(note: FNote, key: SortKey, context: SortContext): SortValue {+ if (key === "title") {+ return note.title;+ }++ if (key === "creationDate") {+ return context.creationDate(note.noteId);+ }++ const name = key.substring(ATTRIBUTE_PREFIX.length);+ const definition = context.definitions.get(name);++ if (definition?.type === "relation") {+ const targetId = note.getRelationValue(name);+ return targetId ? context.noteTitle(targetId) ?? targetId : undefined;+ }++ // Uses the first value of a multi-value attribute, which is the one a card draws.+ const label = note.getLabel(name);+ if (!label) {+ return undefined;+ }++ // Trilium reads a label written without a value as true, so `#done` sorts as true.+ if (definition?.labelType === "boolean") {+ return label.value === "false" ? 0 : 1;+ }++ return label.value ? labelValueOf(label.value, definition?.labelType) : undefined;+}++function labelValueOf(value: string, labelType: string | undefined): SortValue {+ switch (labelType) {+ case "number":+ return toNumber(parseFloat(value));+ case "date":+ case "datetime":+ return toNumber(Date.parse(value));+ case "time":+ return secondsOfDay(value);+ case "color":+ return hueOf(value);+ default:+ return value;+ }+}++function toNumber(value: number) {+ return Number.isNaN(value) ? undefined : value;+}++/** Converts the `HH:MM` and `HH:MM:SS` values a time field writes into seconds. */+function secondsOfDay(value: string) {+ const parts = /^(\d{1,2}):(\d{2})(?::(\d{2}))?$/.exec(value.trim());+ if (!parts) {+ return undefined;+ }++ return Number(parts[1]) * 3600 + Number(parts[2]) * 60 + Number(parts[3] ?? 0);+}++/** The hue of a colour. Grey has none, so it sorts with the items that have no value. */+function hueOf(value: string) {+ try {+ const color = Color(value.toLowerCase()).hsl();+ return color.saturationl() > 0 ? color.hue() : undefined;+ } catch {+ return undefined;+ }+}