Skip to content

Build your personal knowledge base with Trilium Notes

feat(table): sort a relation column by the target's title, not its noteId

Elian Doranf79ad2cf7850
diff --git a/apps/client/src/widgets/collections/table/columns.spec.ts b/apps/client/src/widgets/collections/table/columns.spec.ts
index d0bd9e074e..dd1326b7a7 100644
--- a/apps/client/src/widgets/collections/table/columns.spec.ts
+++ b/apps/client/src/widgets/collections/table/columns.spec.ts
@@ -1,5 +1,5 @@
import { act } from "preact/test-utils";
-import type { CellComponent, ColumnDefinition } from "tabulator-tables";
+import type { CellComponent, ColumnComponent, ColumnDefinition, RowComponent } from "tabulator-tables";
import { describe, expect, it, vi } from "vitest";
import options from "../../../services/options";
@@ -421,6 +421,32 @@ describe("buildColumnDefinitions — multi-valued columns", () => {
});
});
+describe("buildColumnDefinitions — relation columns", () => {
+ it("sorts by the target's title carried in the row, not by the noteId the cell stores", () => {
+ const sorter = buildColumnDefinitions({
+ info: [ { name: "assignee", type: "relation" } ],
+ movableRows: false,
+ existingColumnData: undefined,
+ rowNumberHint: 1
+ }).find((column) => column.field === "relations.assignee")?.sorter;
+ if (typeof sorter !== "function") throw new Error("expected a sorter of its own");
+
+ const column = { getField: () => "relations.assignee" } as ColumnComponent;
+ const row = (title: string | undefined) =>
+ ({ getData: () => ({ relationTitles: title === undefined ? {} : { assignee: title } }) }) as unknown as RowComponent;
+ const compare = (a: string | undefined, b: string | undefined) => Math.sign(
+ (sorter as (...args: unknown[]) => number)("idA", "idB", row(a), row(b), column, "asc", {})
+ );
+
+ // "Alpha" would come after "Beta" if the ids were what was compared.
+ expect(compare("Alpha", "Beta")).toBe(-1);
+ expect(compare("Beta", "Alpha")).toBe(1);
+ expect(compare("Alpha", "Alpha")).toBe(0);
+ // A cell without a target sorts as nothing rather than by its absence crashing the grid.
+ expect(compare(undefined, "Alpha")).toBe(-1);
+ });
+});
+
describe("formatLabelDate", () => {
it("renders dates and datetimes in the configured formatting locale", () => {
options.set("formattingLocale", "de");
diff --git a/apps/client/src/widgets/collections/table/columns.tsx b/apps/client/src/widgets/collections/table/columns.tsx
index 5aee1c57a1..2a61cd10b5 100644
--- a/apps/client/src/widgets/collections/table/columns.tsx
+++ b/apps/client/src/widgets/collections/table/columns.tsx
@@ -4,7 +4,7 @@ import { LabelType } from "@triliumnext/commons";
import clsx from "clsx";
import { JSX } from "preact";
import { useEffect, useRef, useState } from "preact/hooks";
-import type { CellComponent, ColumnDefinition, EmptyCallback, FormatterParams, RowComponent, ValueBooleanCallback, ValueVoidCallback } from "tabulator-tables";
+import type { CellComponent, ColumnComponent, ColumnDefinition, EmptyCallback, FormatterParams, RowComponent, ValueBooleanCallback, ValueVoidCallback } from "tabulator-tables";
import froca from "../../../services/froca.js";
import { safeUrlHref } from "../../../utils/url.js";
@@ -15,6 +15,7 @@ import Icon from "../../react/Icon.jsx";
import NoteAutocomplete from "../../react/NoteAutocomplete.jsx";
import { renderReactWidget } from "../../react/react_utils.jsx";
import { useGrowsUpwards } from "./grows_upwards.js";
+import type { TableData } from "./rows.js";
type ColumnType = LabelType | "relation";
@@ -99,10 +100,23 @@ const labelTypeMappings: Record<ColumnType, Partial<ColumnDefinition>> = {
},
relation: {
editor: wrapEditor(RelationEditor),
- formatter: wrapFormatter(NoteFormatter)
+ formatter: wrapFormatter(NoteFormatter),
+ // The cell's value is the target's noteId while what it shows is the target's title, so the
+ // default string sorter would order the rows by an id the user never sees. The titles are
+ // read from the row data, where they were resolved as the rows were built — a sort compares
+ // synchronously, so they could not be fetched from here.
+ sorter: (a, b, aRow, bRow, column) =>
+ relationTitle(aRow, column).localeCompare(relationTitle(bRow, column))
}
};
+/** The title a relation cell shows, carried in the row's data under the relation's own name. */
+function relationTitle(row: RowComponent, column: ColumnComponent): string {
+ const name = (column.getField() ?? "").slice("relations.".length);
+ const { relationTitles } = row.getData() as Partial<TableData>;
+ return relationTitles?.[name] ?? "";
+}
+
interface BuildColumnArgs {
info: AttributeDefinitionInformation[];
movableRows: boolean;
diff --git a/apps/client/src/widgets/collections/table/rows.spec.ts b/apps/client/src/widgets/collections/table/rows.spec.ts
index 3563553605..3b7cf35836 100644
--- a/apps/client/src/widgets/collections/table/rows.spec.ts
+++ b/apps/client/src/widgets/collections/table/rows.spec.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
+
import { buildNote } from "../../../test/easy-froca";
-import getAttributeDefinitionInformation from "./rows.js";
+import getAttributeDefinitionInformation, { buildRowDefinitions } from "./rows.js";
describe("getAttributeDefinitionInformation", () => {
it("handles attributes with colons in their names", async () => {
@@ -47,3 +48,28 @@ describe("getAttributeDefinitionInformation", () => {
]);
});
});
+
+describe("buildRowDefinitions", () => {
+ it("carries each relation target's title, so a relation column can sort by what it shows", async () => {
+ const alpha = buildNote({ title: "Alpha" });
+ const beta = buildNote({ title: "Beta" });
+ const parent = buildNote({
+ title: "Collection",
+ "#relation:assignee(inheritable)": "promoted,alias=Assignee,single",
+ children: [
+ { title: "Task 1", "~assignee": beta.noteId },
+ { title: "Task 2", "~assignee": alpha.noteId },
+ // A row without the relation sorts as nothing rather than as an id or a crash.
+ { title: "Task 3" }
+ ]
+ });
+
+ const info = getAttributeDefinitionInformation(parent);
+ const { definitions } = await buildRowDefinitions(parent, info, false);
+ expect(definitions).toMatchObject([
+ { title: "Task 1", relations: { assignee: beta.noteId }, relationTitles: { assignee: "Beta" } },
+ { title: "Task 2", relations: { assignee: alpha.noteId }, relationTitles: { assignee: "Alpha" } },
+ { title: "Task 3", relations: { assignee: null }, relationTitles: { assignee: "" } }
+ ]);
+ });
+});
diff --git a/apps/client/src/widgets/collections/table/rows.ts b/apps/client/src/widgets/collections/table/rows.ts
index e1d26ec1c4..6725b321c8 100644
--- a/apps/client/src/widgets/collections/table/rows.ts
+++ b/apps/client/src/widgets/collections/table/rows.ts
@@ -1,6 +1,7 @@
import { extractAttributeDefinitionTypeAndName, LabelType } from "@triliumnext/commons";
import FNote from "../../../entities/fnote.js";
+import froca from "../../../services/froca.js";
import type { AttributeDefinitionInformation } from "./columns.js";
export type TableData = {
@@ -9,6 +10,12 @@ export type TableData = {
title: string;
labels: Record<string, boolean | string | string[] | null>;
relations: Record<string, boolean | string | null>;
+ /**
+ * The relation targets' titles, keyed as `relations` is. A relation cell stores the target's
+ * noteId but shows its title, and a sort compares synchronously — so the title a column sorts
+ * by has to be in the row data before the table is handed it.
+ */
+ relationTitles: Record<string, string>;
branchId: string;
colorClass: string | undefined;
isArchived: boolean;
@@ -51,6 +58,7 @@ export async function buildRowDefinitions(parentNote: FNote, infos: AttributeDef
title: note.title,
labels,
relations,
+ relationTitles: {},
isArchived: note.isArchived,
branchId: branch.branchId,
colorClass: note.getColorClass()
@@ -66,6 +74,12 @@ export async function buildRowDefinitions(parentNote: FNote, infos: AttributeDef
definitions.push(def);
}
+ // Filled over the whole tree at once, from the outermost call, so the targets are fetched as
+ // one batch rather than a request per row.
+ if (currentDepth === 0) {
+ await fillRelationTitles(definitions);
+ }
+
return {
definitions,
hasSubtree,
@@ -73,6 +87,42 @@ export async function buildRowDefinitions(parentNote: FNote, infos: AttributeDef
};
}
+/**
+ * Fills each row's `relationTitles` with the titles its relation cells show, loading the targets
+ * as one batch. A relation can point at a note since deleted, or one the user may not see — such
+ * a cell shows nothing, and sorts as nothing.
+ */
+async function fillRelationTitles(definitions: TableData[]) {
+ const targetIds = new Set<string>();
+ visitRows(definitions, ({ relations }) => {
+ for (const value of Object.values(relations)) {
+ if (typeof value === "string" && value) {
+ targetIds.add(value);
+ }
+ }
+ });
+ if (targetIds.size === 0) {
+ return;
+ }
+
+ await froca.getNotes([ ...targetIds ], true);
+ visitRows(definitions, (def) => {
+ for (const [ name, value ] of Object.entries(def.relations)) {
+ const target = typeof value === "string" && value ? froca.getNoteFromCache(value) : undefined;
+ def.relationTitles[name] = target?.title ?? "";
+ }
+ });
+}
+
+function visitRows(definitions: TableData[], visit: (def: TableData) => void) {
+ for (const def of definitions) {
+ visit(def);
+ if (def._children) {
+ visitRows(def._children, visit);
+ }
+ }
+}
+
export default function getAttributeDefinitionInformation(parentNote: FNote) {
const info: AttributeDefinitionInformation[] = [];
// Nearest-wins, so a collection redefining an inherited field is described by its own definition