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/refactor: make the collection sort menu reusable
Adorian Doran4a062330145a
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 806629460b..7c1badd91d 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3506,11 +3506,7 @@"filter-placeholder": "Filter board...","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"+ "sort-manually": "Manually"},"dashboard_view": {"refresh-widget": "Refresh",@@ -4215,5 +4211,12 @@"clear": "Clear the filter","fetch-error": "The filter could not be run.","submit": "Apply the filter"+ },+ "sorting": {+ "none": "None",+ "title": "Title",+ "creation-date": "Creation date & time",+ "ascending": "Ascending",+ "descending": "Descending"}}diff --git a/apps/client/src/widgets/collections/board/context_menu.spec.ts b/apps/client/src/widgets/collections/board/context_menu.spec.tsindex ffbbe54622..d4fd6bb2c4 100644--- a/apps/client/src/widgets/collections/board/context_menu.spec.ts+++ b/apps/client/src/widgets/collections/board/context_menu.spec.ts@@ -18,6 +18,13 @@ vi.mock("../../../menus/link_context_menu", () => ({default: { getItems: () => [], handleLinkContextMenuItem: () => {} }}));+// i18next is never initialised under test, so `t` echoes the key it is given. The promise is what+// the command registry awaits as `PromotedAttributesCard` is pulled in for the attribute icons.+vi.mock("../../../services/i18n", () => ({+ t: (key: string) => key,+ translationsInitializedPromise: Promise.resolve()+}));+describe("Board column context menu", () => {let container: HTMLElement | undefined;@@ -406,117 +413,43 @@ describe("Board column context menu", () => {expect(api.setColumnColor).toHaveBeenLastCalledWith("To Do", null);});+ /**+ * The entries themselves are the shared builder's, tested in `collections/sort_menu.spec.ts`.+ * What the board answers for is the column it names and what it calls the manual order.+ */describe("the sort submenu", () => {- function sortApi(- sort: { orderBy?: string, isDescending?: boolean } = {},- attributes: Partial<PromotedAttribute>[] = []- ) {+ function sortApi() {return {- getColumnSort: () => ({ isDescending: false, ...sort }),- getPromotedAttributes: () => attributes,+ getColumnSort: () => ({ orderBy: undefined, isDescending: false }),+ getPromotedAttributes: () => [],setColumnSort: vi.fn(),setColumnSortDirection: vi.fn()} as unknown as BoardApi;}- function sortItems(api: BoardApi) {- const entry = openMenu(api)+ function sortItems(api: BoardApi, value = "To Do") {+ const entry = openMenu(api, { value, columns: [ value ] }).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" }- ]));+ it("calls the unsorted order Manually rather than None", () => {+ const first = sortItems(sortApi())[0];- expect(items[3] && "title" in items[3] ? items[3].title : "")- .toBe("<span class=\"board-column-name\">"- + "<img src=x onerror="alert(1)"></span>");+ expect(first && "title" in first ? first.title : "")+ .toBe("board_view.sort-manually");});- 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");+ it("writes what is picked against the column the menu was opened on", () => {+ const api = sortApi();+ const items = sortItems(api, "Done");- 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[1]);+ expect(api.setColumnSort).toHaveBeenCalledWith("Done", "title");pick(items.at(-1));- expect(api.setColumnSortDirection).toHaveBeenCalledWith("To Do", true);-- pick(items.at(-2));- expect(api.setColumnSortDirection).toHaveBeenCalledWith("To Do", false);+ expect(api.setColumnSortDirection).toHaveBeenCalledWith("Done", true);});function pick(item: MenuItem<unknown> | undefined) {diff --git a/apps/client/src/widgets/collections/board/context_menu.ts b/apps/client/src/widgets/collections/board/context_menu.tsindex 47ae3f3e3e..88b0876647 100644--- a/apps/client/src/widgets/collections/board/context_menu.ts+++ b/apps/client/src/widgets/collections/board/context_menu.ts@@ -11,8 +11,7 @@ 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 { buildSortMenuItems } from "../sort_menu";import Api from "./api";import { INBOX_COLUMN } from "./columns";@@ -131,7 +130,15 @@ export function openColumnContextMenu(api: Api, event: ContextMenuEvent, column:{title: t("board_view.sort"),uiIcon: "bx bx-sort-alt-2",- items: buildSortItems(api, column.value)+ items: buildSortMenuItems<string>({+ ...api.getColumnSort(column.value),+ attributes: api.getPromotedAttributes(),+ // A board arranges its cards by hand rather than leaving them unsorted.+ noneTitle: t("board_view.sort-manually"),+ onSelect: (orderBy) => api.setColumnSort(column.value, orderBy),+ onDirectionChange: (isDescending) =>+ api.setColumnSortDirection(column.value, isDescending)+ })},{title: t("board_view.set-limit"),@@ -290,62 +297,6 @@ 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/sort_menu.css b/apps/client/src/widgets/collections/sort_menu.cssnew file mode 100644index 0000000000..615e714f38--- /dev/null+++ b/apps/client/src/widgets/collections/sort_menu.css@@ -0,0 +1,10 @@+.dropdown-item.sort-menu-item {+ /* A field is named by the user, so a long name is clipped instead of widening the menu. */+ .sort-menu-name {+ display: block;+ max-width: 300px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+}diff --git a/apps/client/src/widgets/collections/sort_menu.spec.ts b/apps/client/src/widgets/collections/sort_menu.spec.tsnew file mode 100644index 0000000000..67d8dd41fb--- /dev/null+++ b/apps/client/src/widgets/collections/sort_menu.spec.ts@@ -0,0 +1,147 @@+import { describe, expect, it, vi } from "vitest";++import type { MenuItem } from "../../menus/context_menu";+import type { PromotedAttribute } from "./promoted_attributes";+import { buildSortMenuItems, type SortMenuOptions } from "./sort_menu";++// i18next is never initialised under test, so `t` echoes the key it is given. The promise is what+// the command registry awaits as `PromotedAttributesCard` is pulled in for the attribute icons.+vi.mock("../../services/i18n", () => ({+ t: (key: string) => key,+ translationsInitializedPromise: Promise.resolve()+}));++describe("buildSortMenuItems", () => {+ it("offers no sorting, the two built-in keys and the direction", () => {+ expect(icons(build())).toEqual([+ "bx bx-move-vertical",+ "bx bx-text",+ "bx bx-calendar-plus",+ "separator",+ "bx bx-sort-up",+ "bx bx-sort-down"+ ]);+ });++ it("calls the entry for no sorting None, and lets the caller name it otherwise", () => {+ expect(titles(build())[0]).toBe("sorting.none");+ expect(titles(build({ noneTitle: "Manually" }))[0]).toBe("Manually");+ });++ it("checks no sorting while nothing is sorted, and offers no direction", () => {+ const items = build();++ 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 it sorts by, and the direction it sorts in", () => {+ const ascending = build({ 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 = build({ orderBy: "title", isDescending: true });+ expect(descending.at(-2)).toMatchObject({ trailingIcon: undefined });+ expect(descending.at(-1)).toMatchObject({ trailingIcon: "bx bx-check" });+ });++ it("lists the attributes under the built-in keys, each with its own icon", () => {+ const items = build({+ orderBy: "attr:owner",+ attributes: [+ attribute({ name: "dueDate", title: "Due date", labelType: "date" }),+ attribute({ name: "owner", title: "Owner", type: "relation" })+ ]+ });++ expect(titles(items).slice(3, 5)).toEqual([+ `<span class="sort-menu-name">Due date</span>`,+ `<span class="sort-menu-name">Owner</span>`+ ]);+ expect(items[3]).toMatchObject({+ uiIcon: "bx bx-calendar", className: "sort-menu-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 = build({+ attributes: [ attribute({ name: "x", title: `<img src=x onerror="alert(1)">` }) ]+ });++ expect(titles(items)[3]).toBe("<span class=\"sort-menu-name\">"+ + "<img src=x onerror="alert(1)"></span>");+ });++ it("reports the key a pick names, and no key at all for the first entry", () => {+ const onSelect = vi.fn();+ const items = build({+ attributes: [ attribute({ name: "dueDate", title: "Due date" }) ]+ }, { onSelect });++ pick(items[1]);+ expect(onSelect).toHaveBeenCalledWith("title");++ pick(items[2]);+ expect(onSelect).toHaveBeenCalledWith("creationDate");++ pick(items[3]);+ expect(onSelect).toHaveBeenCalledWith("attr:dueDate");++ pick(items[0]);+ expect(onSelect).toHaveBeenCalledWith(undefined);+ });++ it("reports the direction a pick names", () => {+ const onDirectionChange = vi.fn();+ const items = build({ orderBy: "title" }, { onDirectionChange });++ pick(items.at(-1));+ expect(onDirectionChange).toHaveBeenCalledWith(true);++ pick(items.at(-2));+ expect(onDirectionChange).toHaveBeenCalledWith(false);+ });+});++function build(+ options: Partial<SortMenuOptions> = {},+ handlers: Partial<Pick<SortMenuOptions, "onSelect" | "onDirectionChange">> = {}+) {+ return buildSortMenuItems<string>({+ orderBy: undefined,+ isDescending: false,+ attributes: [],+ onSelect: handlers.onSelect ?? (() => {}),+ onDirectionChange: handlers.onDirectionChange ?? (() => {}),+ ...options+ });+}++function attribute(fields: Partial<PromotedAttribute> & { name: string }): PromotedAttribute {+ return {+ definitionName: `label:${fields.name}`,+ type: "label",+ title: fields.name,+ hidden: false,+ definitionValue: "",+ isOwned: true,+ isInheritable: true,+ ...fields+ };+}++const titles = (items: MenuItem<string>[]) =>+ items.map(item => (item && "title" in item ? item.title : "separator"));++const icons = (items: MenuItem<string>[]) =>+ items.map(item => (item && "uiIcon" in item ? item.uiIcon : "separator"));++function pick(item: MenuItem<string> | undefined) {+ if (!item || !("handler" in item)) throw new Error("expected a menu entry");+ item.handler?.(item, {} as never);+}diff --git a/apps/client/src/widgets/collections/sort_menu.ts b/apps/client/src/widgets/collections/sort_menu.tsnew file mode 100644index 0000000000..f6d5d7417d--- /dev/null+++ b/apps/client/src/widgets/collections/sort_menu.ts@@ -0,0 +1,79 @@+import "./sort_menu.css";++import type { MenuItem } from "../../menus/context_menu";+import { t } from "../../services/i18n";+import { escapeHtml } from "../../services/utils";+import { promotedAttributeType } from "../react/PromotedAttributesCard";+import type { PromotedAttribute } from "./promoted_attributes";+import type { SortKey } from "./sorting";++export interface SortMenuOptions {+ /** What the collection sorts by now, absent while it keeps the order the user arranged. */+ orderBy: SortKey | undefined;+ /** Whether that order runs backwards. */+ isDescending: boolean;+ /** The fields offered besides the title and the creation date, in the order they are shown. */+ attributes: PromotedAttribute[];+ /** What the entry for no sorting is called. "None" unless the caller names it. */+ noneTitle?: string;+ /** Called with the key picked, or `undefined` for the order the user arranges by hand. */+ onSelect: (orderBy: SortKey | undefined) => void;+ onDirectionChange: (isDescending: boolean) => void;+}++/**+ * The entries a collection offers for how it orders its items.+ *+ * Built as a submenu for the caller to hang wherever it belongs. The direction sits at the foot,+ * disabled while nothing is sorted.+ */+export function buildSortMenuItems<T>({+ orderBy, isDescending, attributes, noneTitle, onSelect, onDirectionChange+}: SortMenuOptions): MenuItem<T>[] {+ const checkFor = (key: SortKey | undefined) => (key === orderBy ? "bx bx-check" : undefined);++ return [+ {+ title: noneTitle ?? t("sorting.none"),+ uiIcon: "bx bx-move-vertical",+ trailingIcon: checkFor(undefined),+ handler: () => onSelect(undefined)+ },+ {+ title: t("sorting.title"),+ uiIcon: "bx bx-text",+ trailingIcon: checkFor("title"),+ handler: () => onSelect("title")+ },+ {+ title: t("sorting.creation-date"),+ uiIcon: "bx bx-calendar-plus",+ trailingIcon: checkFor("creationDate"),+ handler: () => onSelect("creationDate")+ },+ ...attributes.map<MenuItem<T>>((attribute) => ({+ // The menu reads a title as markup, and an alias is the user's own text. The box is+ // what clips a long one rather than letting it widen the menu.+ title: `<span class="sort-menu-name">${escapeHtml(attribute.title)}</span>`,+ className: "sort-menu-item",+ uiIcon: promotedAttributeType(attribute).icon,+ trailingIcon: checkFor(`attr:${attribute.name}`),+ handler: () => onSelect(`attr:${attribute.name}`)+ })),+ { kind: "separator" },+ {+ title: t("sorting.ascending"),+ uiIcon: "bx bx-sort-up",+ enabled: !!orderBy,+ trailingIcon: orderBy && !isDescending ? "bx bx-check" : undefined,+ handler: () => onDirectionChange(false)+ },+ {+ title: t("sorting.descending"),+ uiIcon: "bx bx-sort-down",+ enabled: !!orderBy,+ trailingIcon: orderBy && isDescending ? "bx bx-check" : undefined,+ handler: () => onDirectionChange(true)+ }+ ];+}