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/collections/board: add sorting options in the column menu
Adorian Doranc6b352f8f82d
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex dfb34e9573..806629460b 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3504,7 +3504,13 @@},"status-alias": "Status","filter-placeholder": "Filter board...",- "card-outside-filter": "This card is outside of the current filtering scope"+ "card-outside-filter": "This card is outside of the current filtering scope",+ "sort": "Sort",+ "sort-manually": "Manually",+ "sort-by-title": "Title",+ "sort-by-creation-date": "Creation date & time",+ "sort-ascending": "Ascending",+ "sort-descending": "Descending"},"dashboard_view": {"refresh-widget": "Refresh",diff --git a/apps/client/src/widgets/collections/board/context_menu.spec.ts b/apps/client/src/widgets/collections/board/context_menu.spec.tsindex d10bb5aed2..ea27953e2d 100644--- a/apps/client/src/widgets/collections/board/context_menu.spec.ts+++ b/apps/client/src/widgets/collections/board/context_menu.spec.ts@@ -7,6 +7,7 @@ import contextMenu, { ContextMenuEvent, MenuItem } from "../../../menus/context_import branches from "../../../services/branches";import dialog from "../../../services/dialog";import FNote from "../../../entities/fnote";+import type { PromotedAttribute } from "../promoted_attributes";import { buildNote } from "../../../test/easy-froca";import BoardApi from "./api";import { DEFAULT_COLUMN_ICON } from "./columns";@@ -54,8 +55,13 @@ describe("Board column context menu", () => {pageY: 0} as ContextMenuEvent;- // Every column menu asks what a column is called; a test says so only when that matters.- const withDefaults = Object.assign({ getColumnTitle: (name: string) => name }, api);+ // Every column menu asks what a column is called, how it is sorted and what it can sort+ // by; a test answers only where that is what it is about.+ const withDefaults = Object.assign({+ getColumnTitle: (name: string) => name,+ getColumnSort: () => ({ orderBy: undefined, isDescending: false }),+ getPromotedAttributes: () => []+ }, api);openColumnContextMenu(withDefaults, event, {value: "To Do",columns: [ "To Do" ],@@ -224,7 +230,8 @@ describe("Board column context menu", () => {.toEqual(["bx bx-edit-alt", "bx bx-collapse-horizontal", "bx bx-lock-alt", "bx bx-tachometer","bx bx-plus", "bx bx-link",- "bx bx-columns", "bx bx-horizontal-left", "bx bx-archive", "bx bx-trash"+ "bx bx-columns", "bx bx-sort-alt-2", "bx bx-horizontal-left", "bx bx-archive",+ "bx bx-trash"]);});@@ -388,6 +395,125 @@ describe("Board column context menu", () => {await act(async () => picker.querySelector<HTMLElement>(".color-cell-reset")?.click());expect(api.setColumnColor).toHaveBeenLastCalledWith("To Do", null);});++ describe("the sort submenu", () => {+ function sortApi(+ sort: { orderBy?: string, isDescending?: boolean } = {},+ attributes: Partial<PromotedAttribute>[] = []+ ) {+ return {+ getColumnSort: () => ({ isDescending: false, ...sort }),+ getPromotedAttributes: () => attributes,+ setColumnSort: vi.fn(),+ setColumnSortDirection: vi.fn()+ } as unknown as BoardApi;+ }++ function sortItems(api: BoardApi) {+ const entry = openMenu(api)+ .find(item => item && "uiIcon" in item && item.uiIcon === "bx bx-sort-alt-2");+ if (!entry || !("items" in entry)) throw new Error("expected a sort entry");+ return entry.items ?? [];+ }++ const titles = (items: MenuItem<unknown>[]) =>+ items.map(item => (item && "title" in item ? item.title : "separator"));++ // i18next is never initialised under test, so the entries are read by their icons.+ const icons = (items: MenuItem<unknown>[]) =>+ items.map(item => (item && "uiIcon" in item ? item.uiIcon : "separator"));++ it("offers the manual order, the two built-in keys and the direction", () => {+ expect(icons(sortItems(sortApi()))).toEqual([+ "bx bx-move-vertical",+ "bx bx-text",+ "bx bx-calendar-plus",+ "separator",+ "bx bx-sort-up",+ "bx bx-sort-down"+ ]);+ });++ it("checks the manual order while the column keeps it, and offers no direction", () => {+ const items = sortItems(sortApi());++ expect(items[0]).toMatchObject({ trailingIcon: "bx bx-check" });+ expect(items[1]).toMatchObject({ trailingIcon: undefined });+ expect(items.at(-2)).toMatchObject({ enabled: false, trailingIcon: undefined });+ expect(items.at(-1)).toMatchObject({ enabled: false, trailingIcon: undefined });+ });++ it("checks the key the column sorts by, and the direction it sorts in", () => {+ const ascending = sortItems(sortApi({ orderBy: "title" }));+ expect(ascending[0]).toMatchObject({ trailingIcon: undefined });+ expect(ascending[1]).toMatchObject({ trailingIcon: "bx bx-check" });+ expect(ascending.at(-2)).toMatchObject({ enabled: true, trailingIcon: "bx bx-check" });+ expect(ascending.at(-1)).toMatchObject({ enabled: true, trailingIcon: undefined });++ const descending = sortItems(sortApi({ orderBy: "title", isDescending: true }));+ expect(descending.at(-2)).toMatchObject({ trailingIcon: undefined });+ expect(descending.at(-1)).toMatchObject({ trailingIcon: "bx bx-check" });+ });++ it("lists the promoted attributes under the built-in keys, each with its own icon", () => {+ const items = sortItems(sortApi({ orderBy: "attr:owner" }, [+ { name: "dueDate", title: "Due date", type: "label", labelType: "date" },+ { name: "owner", title: "Owner", type: "relation" }+ ]));++ expect(titles(items).slice(3, 5)).toEqual([+ `<span class="board-column-name">Due date</span>`,+ `<span class="board-column-name">Owner</span>`+ ]);+ expect(items[3]).toMatchObject({+ uiIcon: "bx bx-calendar", className: "board-column-item", trailingIcon: undefined+ });+ expect(items[4]).toMatchObject({+ uiIcon: "bx bx-transfer", trailingIcon: "bx bx-check"+ });+ });++ it("escapes what a crafted attribute name would plant in the menu", () => {+ const items = sortItems(sortApi({}, [+ { name: "x", title: `<img src=x onerror="alert(1)">`, type: "label" }+ ]));++ expect(items[3] && "title" in items[3] ? items[3].title : "")+ .toBe("<span class=\"board-column-name\">"+ + "<img src=x onerror="alert(1)"></span>");+ });++ it("writes the key a pick names, and clears it back to the manual order", () => {+ const api = sortApi(+ { orderBy: "title" }, [ { name: "dueDate", title: "Due date", type: "label" } ]);+ const items = sortItems(api);++ pick(items[2]);+ expect(api.setColumnSort).toHaveBeenCalledWith("To Do", "creationDate");++ pick(items[3]);+ expect(api.setColumnSort).toHaveBeenCalledWith("To Do", "attr:dueDate");++ pick(items[0]);+ expect(api.setColumnSort).toHaveBeenCalledWith("To Do", undefined);+ });++ it("writes the direction a pick names", () => {+ const api = sortApi({ orderBy: "title" });+ const items = sortItems(api);++ pick(items.at(-1));+ expect(api.setColumnSortDirection).toHaveBeenCalledWith("To Do", true);++ pick(items.at(-2));+ expect(api.setColumnSortDirection).toHaveBeenCalledWith("To Do", false);+ });++ function pick(item: MenuItem<unknown> | undefined) {+ if (!item || !("handler" in item)) throw new Error("expected a menu entry");+ item.handler?.(item, {} as never);+ }+ });});describe("Board item context menu", () => {diff --git a/apps/client/src/widgets/collections/board/context_menu.ts b/apps/client/src/widgets/collections/board/context_menu.tsindex 145f198855..d6dba8ee09 100644--- a/apps/client/src/widgets/collections/board/context_menu.ts+++ b/apps/client/src/widgets/collections/board/context_menu.ts@@ -11,6 +11,8 @@ import { getArchiveMenuItem } from "../../../menus/context_menu_utils";import { t } from "../../../services/i18n";import { escapeHtml } from "../../../services/utils";import ColorPicker from "../../react/ColorPicker";+import { promotedAttributeType } from "../../react/PromotedAttributesCard";+import type { SortKey } from "../sorting";import Api from "./api";import { INBOX_COLUMN } from "./columns";@@ -125,6 +127,11 @@ export function openColumnContextMenu(api: Api, event: ContextMenuEvent, column:]},{ kind: "separator" },+ {+ title: t("board_view.sort"),+ uiIcon: "bx bx-sort-alt-2",+ items: buildSortItems(api, column.value)+ },{title: t("board_view.move-column"),uiIcon: "bx bx-horizontal-left",@@ -276,6 +283,62 @@ export function openCreateColumnMenu(x: number, y: number, create: (atStart: boo});}+/**+ * How a column orders its cards: by hand, or by one of the fields the board holds.+ *+ * The direction sits at the foot, disabled while the column is ordered by hand.+ */+function buildSortItems(api: Api, column: string): MenuItem<string>[] {+ const { orderBy, isDescending } = api.getColumnSort(column);+ const checkFor = (key: SortKey | undefined) => (key === orderBy ? "bx bx-check" : undefined);++ const attributes = api.getPromotedAttributes().map<MenuItem<string>>((attribute) => ({+ // Boxed and escaped as the column names are: the alias is the user's own text.+ title: `<span class="board-column-name">${escapeHtml(attribute.title)}</span>`,+ className: "board-column-item",+ uiIcon: promotedAttributeType(attribute).icon,+ trailingIcon: checkFor(`attr:${attribute.name}`),+ handler: () => api.setColumnSort(column, `attr:${attribute.name}`)+ }));++ return [+ {+ title: t("board_view.sort-manually"),+ uiIcon: "bx bx-move-vertical",+ trailingIcon: checkFor(undefined),+ handler: () => api.setColumnSort(column, undefined)+ },+ {+ title: t("board_view.sort-by-title"),+ uiIcon: "bx bx-text",+ trailingIcon: checkFor("title"),+ handler: () => api.setColumnSort(column, "title")+ },+ {+ title: t("board_view.sort-by-creation-date"),+ uiIcon: "bx bx-calendar-plus",+ trailingIcon: checkFor("creationDate"),+ handler: () => api.setColumnSort(column, "creationDate")+ },+ ...attributes,+ { kind: "separator" },+ {+ title: t("board_view.sort-ascending"),+ uiIcon: "bx bx-sort-up",+ enabled: !!orderBy,+ trailingIcon: orderBy && !isDescending ? "bx bx-check" : undefined,+ handler: () => api.setColumnSortDirection(column, false)+ },+ {+ title: t("board_view.sort-descending"),+ uiIcon: "bx bx-sort-down",+ enabled: !!orderBy,+ trailingIcon: orderBy && isDescending ? "bx bx-check" : undefined,+ handler: () => api.setColumnSortDirection(column, true)+ }+ ];+}+/*** Where a column can be moved, each entry named by the column it would follow.*diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsxindex 2ca6355ee8..380ceb77eb 100644--- a/apps/client/src/widgets/collections/board/index.spec.tsx+++ b/apps/client/src/widgets/collections/board/index.spec.tsx@@ -3567,6 +3567,42 @@ describe("a column that sorts its cards", () => {expect(cardTitlesIn(board, 0)).toEqual([ "Beta", "Alpha", "Delta" ]);});+ it("reorders the column as soon as the sort is picked from its menu", async () => {+ const { board } = await renderSortedBoard({});+ expect(cardTitlesIn(board, 0)).toEqual([ "Delta", "Beta", "Alpha" ]);++ await pickSort(board, "bx bx-text");+ expect(cardTitlesIn(board, 0)).toEqual([ "Alpha", "Beta", "Delta" ]);++ await pickSort(board, "bx bx-sort-down");+ expect(cardTitlesIn(board, 0)).toEqual([ "Delta", "Beta", "Alpha" ]);++ await pickSort(board, "bx bx-move-vertical");+ expect(saved.at(-1)?.columns?.[0]).toStrictEqual({ value: "To Do", descendingOrder: true });+ expect(cardTitlesIn(board, 0)).toEqual([ "Delta", "Beta", "Alpha" ]);+ });++ /** Opens the first column's menu and picks the sort entry carrying the given icon. */+ async function pickSort(board: HTMLElement, icon: string) {+ const show = vi.spyOn(contextMenu, "show").mockImplementation(async () => {});+ board.querySelector(".board-column h3")+ ?.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true }));++ const sort = (show.mock.calls.at(-1)?.[0].items ?? []).find(item =>+ item && "uiIcon" in item && item.uiIcon === "bx bx-sort-alt-2");+ if (!sort || !("items" in sort)) throw new Error("expected a sort entry");++ const entry = (sort.items ?? []).find(item =>+ item && "uiIcon" in item && item.uiIcon === icon);+ if (!entry || !("handler" in entry)) throw new Error(`expected a ${icon} entry`);++ await act(async () => {+ entry.handler?.(entry, {} as never);+ await flush();+ });+ show.mockRestore();+ }+/** The note row a rename produces, which is what the card reads its new title from. */function noteRenamed(noteId: string, title: string) {const results = new LoadResults([ {diff --git a/apps/client/src/widgets/react/PromotedAttributesCard.tsx b/apps/client/src/widgets/react/PromotedAttributesCard.tsxindex 4411ab802c..19e466e819 100644--- a/apps/client/src/widgets/react/PromotedAttributesCard.tsx+++ b/apps/client/src/widgets/react/PromotedAttributesCard.tsx@@ -81,7 +81,7 @@ export default function PromotedAttributesCard({const items = useMemo(() => shown.map((attribute) => ({key: attribute.name,caption: attribute.title,- icon: typeOf(attribute).icon+ icon: promotedAttributeType(attribute).icon})), [ shown ]);const store = useCallback((next: PromotedAttribute[]) => {@@ -208,7 +208,7 @@ export default function PromotedAttributesCard({<BadgeclassName="promoted-attribute-type"- text={typeOf(attribute).title}+ text={promotedAttributeType(attribute).title}outline/>@@ -272,7 +272,7 @@ export default function PromotedAttributesCard({}/** The kind entry for an attribute: its `labelType`, or the relation kind for a relation. */-function typeOf(attribute: PromotedAttribute) {+export function promotedAttributeType(attribute: PromotedAttribute) {const kind = attribute.type === "relation"? RELATION_DEFINITION_TYPE: attribute.labelType ?? "text";