Skip to content

Build your personal knowledge base with Trilium Notes

client/collections/board: add a default sort options

Adorian Doranda36f0d3c48c
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index daf41c8474..87daaf3ebc 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3519,6 +3519,8 @@
"card-outside-filter": "This card is outside of the current filtering scope",
"sort": "Sort",
"sort-manually": "Manually",
+ "sort-cards": "Sort cards",
+ "apply-sort-to-columns": "Apply to all columns",
"sorted-no-reorder": "Cards cannot be reordered, since this is a sorted column."
},
"dashboard_view": {
diff --git a/apps/client/src/widgets/collections/SortDropdown.css b/apps/client/src/widgets/collections/SortDropdown.css
new file mode 100644
index 0000000000..949dc81023
--- /dev/null
+++ b/apps/client/src/widgets/collections/SortDropdown.css
@@ -0,0 +1,6 @@
+.dropdown.sort-dropdown > button {
+ /* Parts the direction the order runs from the order it names. */
+ > .tn-icon {
+ margin-inline-end: 8px;
+ }
+}
diff --git a/apps/client/src/widgets/collections/SortDropdown.tsx b/apps/client/src/widgets/collections/SortDropdown.tsx
new file mode 100644
index 0000000000..9a57aa8045
--- /dev/null
+++ b/apps/client/src/widgets/collections/SortDropdown.tsx
@@ -0,0 +1,53 @@
+import "./SortDropdown.css";
+
+import clsx from "clsx";
+
+import Dropdown from "../react/Dropdown";
+import { FormDropdownDivider, FormListItem } from "../react/FormList";
+import Icon from "../react/Icon";
+import { type SortEntry, sortEntries, type SortMenuOptions, sortMenuTitle } from "./sort_menu";
+
+/**
+ * The order a collection puts its items in, picked from a dropdown.
+ *
+ * The same entries the sort menu offers, for a settings card: a control there is read alongside the
+ * toggles and fields around it, which a button opening a context menu is not.
+ */
+export default function SortDropdown({
+ className, ...options
+}: SortMenuOptions & { className?: string }) {
+ const { orderBy, isDescending, attributes, noneTitle } = options;
+ const { orders, directions } = sortEntries(options);
+
+ return (
+ <Dropdown
+ className={clsx("sort-dropdown", className)}
+ text={<>
+ <Icon icon={isDescending ? "bx bx-sort-down" : "bx bx-sort-up"} />
+ {sortMenuTitle({ orderBy, attributes, noneTitle })}
+ </>}
+ mobileBottomSheet
+ // The card the dropdown stands in is a backdrop root, which would otherwise flatten the
+ // menu's blur into a tint.
+ portalToBody
+ >
+ {orders.map(renderEntry)}
+ <FormDropdownDivider />
+ {directions.map(renderEntry)}
+ </Dropdown>
+ );
+}
+
+function renderEntry(entry: SortEntry) {
+ return (
+ <FormListItem
+ key={entry.key}
+ icon={entry.icon}
+ selected={entry.isSelected}
+ disabled={!entry.isEnabled}
+ onClick={entry.pick}
+ >
+ {entry.title}
+ </FormListItem>
+ );
+}
diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.ts
index d5940364b2..86298d76b8 100644
--- a/apps/client/src/widgets/collections/board/api.spec.ts
+++ b/apps/client/src/widgets/collections/board/api.spec.ts
@@ -1849,6 +1849,91 @@ describe("how a column orders its cards", () => {
});
});
+describe("the order the board offers its columns", () => {
+ beforeEach(() => vi.restoreAllMocks());
+
+ it("reads the labels the board carries, and a board with none as the manual order", () => {
+ const plain = createApi({}, []);
+ expect(plain.api.getDefaultSort()).toEqual({ orderBy: undefined, isDescending: false });
+
+ const { api } = createApi({}, [], buildNote({
+ title: "Board",
+ "#sortColumns": "attr:dueDate",
+ "#sortColumnsDescending": ""
+ }));
+ expect(api.getDefaultSort()).toEqual({ orderBy: "attr:dueDate", isDescending: true });
+ });
+
+ // A key written by hand, or by a newer version, leaves the board offering the manual order.
+ it("reads a key it does not know as the manual order", () => {
+ const { api } = createApi({}, [], buildNote({
+ title: "Board", "#sortColumns": "dateModified"
+ }));
+
+ expect(api.getDefaultSort().orderBy).toBeUndefined();
+ });
+
+ it("writes what is picked to the board note, and takes the label off for the manual order",
+ async () => {
+ const setAttribute = vi.spyOn(attributes, "setAttribute")
+ .mockResolvedValue(undefined as never);
+ const setBoolean = vi.spyOn(attributes, "setBooleanWithInheritance")
+ .mockResolvedValue(undefined as never);
+ const { api, board } = createApi({}, []);
+
+ await api.setDefaultSort("title");
+ expect(setAttribute).toHaveBeenCalledWith(board, "label", "sortColumns", "title");
+
+ await api.setDefaultSort(undefined);
+ expect(setAttribute).toHaveBeenLastCalledWith(board, "label", "sortColumns", null);
+
+ await api.setDefaultSortDirection(true);
+ expect(setBoolean).toHaveBeenCalledWith(board, "sortColumnsDescending", true);
+ });
+
+ it("hands the order to every column at once, keeping what else each one holds", async () => {
+ const { api, saved } = createApi(
+ {
+ columns: [
+ { value: "To Do", icon: "bx bx-list-ul", orderBy: "creationDate" },
+ { value: "Done", descendingOrder: true }
+ ]
+ },
+ [ "To Do", "Doing", "Done" ],
+ buildNote({
+ title: "Board", "#sortColumns": "title", "#sortColumnsDescending": ""
+ }));
+
+ await api.applyDefaultSortToColumns();
+
+ // One write for the board, and the column with no entry of its own gains one where it is
+ // drawn rather than at the end.
+ expect(saved.length).toBe(1);
+ expect(saved.at(-1)?.columns).toEqual([
+ { value: "To Do", icon: "bx bx-list-ul", orderBy: "title", descendingOrder: true },
+ { value: "Doing", orderBy: "title", descendingOrder: true },
+ { value: "Done", orderBy: "title", descendingOrder: true }
+ ]);
+ });
+
+ it("puts every column back to the manual order where that is what the board holds", async () => {
+ const { api, saved } = createApi(
+ {
+ columns: [
+ { value: "To Do", orderBy: "title" },
+ { value: "Done", orderBy: "title", descendingOrder: true }
+ ]
+ },
+ [ "To Do", "Done" ]);
+
+ await api.applyDefaultSortToColumns();
+
+ // Strict, so the assertion catches the keys being stored as undefined rather than dropped.
+ expect(saved.at(-1)?.columns)
+ .toStrictEqual([ { value: "To Do" }, { value: "Done" } ]);
+ });
+});
+
/**
* A sorted column places its own cards, so nothing writes a branch position for one. The branch
* order is the order the reader arranged, which the column goes back to when it is sorted by hand
diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.ts
index e729624d2b..1f287040d5 100644
--- a/apps/client/src/widgets/collections/board/api.ts
+++ b/apps/client/src/widgets/collections/board/api.ts
@@ -30,6 +30,10 @@ import { ColumnMap } from "./data";
/** Which end of a column a new card is made at. */
export type CardPlacement = "top" | "bottom";
+/** The labels the board keeps the order it offers its columns in. */
+const SORT_LABEL = "sortColumns";
+const SORT_DESCENDING_LABEL = "sortColumnsDescending";
+
/** One write's claim on a column, held until that write lands or is taken back. */
interface ColumnClaim {
/**
@@ -639,6 +643,41 @@ export default class BoardApi {
await this.updateColumn(column, { descendingOrder: isDescending });
}
+ /**
+ * The order the board holds for its columns, kept on the board note rather than in the view
+ * config: it is a preference to apply, not something a column is drawn by.
+ */
+ getDefaultSort() {
+ return {
+ orderBy: parseSortKey(this.parentNote?.getLabelValue(SORT_LABEL)),
+ isDescending: !!this.parentNote?.isLabelTruthy(SORT_DESCENDING_LABEL)
+ };
+ }
+
+ /** Sets what the board offers to sort by. Pass `undefined` for the manual order. */
+ async setDefaultSort(orderBy: SortKey | undefined) {
+ if (!this.parentNote) return;
+ await attributes.setAttribute(this.parentNote, "label", SORT_LABEL, orderBy ?? null);
+ }
+
+ /** Sets whether the order the board offers runs backwards. */
+ async setDefaultSortDirection(isDescending: boolean) {
+ if (!this.parentNote) return;
+ await attributes.setBooleanWithInheritance(
+ this.parentNote, SORT_DESCENDING_LABEL, isDescending);
+ }
+
+ /**
+ * Gives every column the order the board holds, replacing whatever each column sorted by.
+ *
+ * Written in one go: `updateColumn` rewrites the whole config, so a run of them would each
+ * report the board as it stood before the first.
+ */
+ async applyDefaultSortToColumns() {
+ const { orderBy, isDescending } = this.getDefaultSort();
+ this.updateColumns(this.columns, { orderBy, 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 });
@@ -811,7 +850,23 @@ export default class BoardApi {
* a note carries is shown without ever being written, so the first pick for it creates one.
*/
private updateColumn(column: string, patch: Partial<BoardColumnData>) {
- const columns = this.viewConfig?.columns ?? [];
+ this.storeColumns(this.withColumn(this.viewConfig?.columns ?? [], column, patch));
+ }
+
+ /** The same for several columns at once, written as one config. */
+ private updateColumns(columns: string[], patch: Partial<BoardColumnData>) {
+ let next = this.viewConfig?.columns ?? [];
+ for (const column of columns) {
+ next = this.withColumn(next, column, patch);
+ }
+
+ this.storeColumns(next);
+ }
+
+ /** The columns as they read with the patch applied to one of them. */
+ private withColumn(
+ columns: BoardColumnData[], column: string, patch: Partial<BoardColumnData>
+ ): BoardColumnData[] {
const patched = (stored: BoardColumnData): BoardColumnData => {
const updated = { ...stored, ...patch };
if (!updated.icon) delete updated.icon;
@@ -827,8 +882,7 @@ export default class BoardApi {
};
if (columns.some(col => col.value === column)) {
- this.storeColumns(columns.map(col => col.value === column ? patched(col) : col));
- return;
+ return columns.map(col => col.value === column ? patched(col) : col);
}
// A column with no entry yet is written where the board draws it, after the last column
@@ -845,7 +899,7 @@ export default class BoardApi {
const placed = [ ...columns ];
placed.splice(at, 0, patched({ value: column }));
- this.storeColumns(placed);
+ return placed;
}
reorderColumn(fromIndex: number, toIndex: number) {
diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsx
index 5060f7ae83..a04501180a 100644
--- a/apps/client/src/widgets/collections/board/column.tsx
+++ b/apps/client/src/widgets/collections/board/column.tsx
@@ -718,8 +718,8 @@ export default function Column({
* @param atOnce whether the card is already standing where it is being put, as at a lift or a drop.
*/
/**
- * Where a menu opened from a button belongs: at the pointer, or against the button itself when a
- * keyboard press opened it and carries no pointer position.
+ * Where a menu opened from a button stands: at the pointer for a press, and below the button for a
+ * keyboard, which reports no position of its own.
*/
function menuOrigin(e: JSX.TargetedMouseEvent<HTMLElement>): [ number, number ] {
if (e.detail) {
diff --git a/apps/client/src/widgets/collections/board/properties.spec.tsx b/apps/client/src/widgets/collections/board/properties.spec.tsx
index e40af958db..09f8ad8ffc 100644
--- a/apps/client/src/widgets/collections/board/properties.spec.tsx
+++ b/apps/client/src/widgets/collections/board/properties.spec.tsx
@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type FNote from "../../../entities/fnote";
import type { PromotedAttribute } from "../promoted_attributes";
+import type { SortKey } from "../sorting";
import BoardApi from "./api";
import BoardProperties from "./properties";
@@ -56,23 +57,28 @@ describe("Board properties", () => {
let stored: string[][];
let storedAttributes: PromotedAttribute[][];
let toggled: [ string, boolean ][];
- /** What the board shows, which the General card reads from the note's own labels. */
- let shownOnBoard: Record<string, boolean>;
+ /** What the board's own labels say, which the General card reads. */
+ let labels: Record<string, string>;
+ /** What the board was asked to do with the order it holds. */
+ let sorting: string[];
+ /** Draws the dialog again, for a test that changed what the board says. */
+ let draw: () => void;
beforeEach(() => {
stored = [];
storedAttributes = [];
toggled = [];
- shownOnBoard = { enableInboxColumn: false, includeArchived: true };
+ sorting = [];
+ labels = { includeArchived: "true" };
container = document.createElement("div");
document.body.appendChild(container);
const board = {
noteId: "board1",
- isLabelTruthy: (name: string) => !!shownOnBoard[name],
- getLabelValue: (name: string) => shownOnBoard[name] ? "true" : "false",
+ isLabelTruthy: (name: string) => !!labels[name] && labels[name] !== "false",
+ getLabelValue: (name: string) => labels[name] ?? null,
getLabel: () => undefined,
- hasLabel: (name: string) => name in shownOnBoard
+ hasLabel: (name: string) => name in labels
} as unknown as FNote;
const api = {
@@ -83,10 +89,22 @@ describe("Board properties", () => {
getStoredPromotedAttributes: () => [ { name: "dueDate" }, { name: "owner" } ],
setPromotedAttributes: async (attributes: PromotedAttribute[]) => {
storedAttributes.push(attributes);
- }
+ },
+ getPromotedAttributes: () => [ { name: "dueDate", title: "Due" } ],
+ getDefaultSort: () => ({
+ orderBy: labels.sortColumns as SortKey | undefined,
+ isDescending: !!labels.sortColumnsDescending
+ }),
+ setDefaultSort: async (orderBy: SortKey | undefined) => {
+ sorting.push(`sort:${orderBy ?? "none"}`);
+ },
+ setDefaultSortDirection: async (isDescending: boolean) => {
+ sorting.push(`descending:${isDescending}`);
+ },
+ applyDefaultSortToColumns: async () => { sorting.push("apply"); }
} as unknown as BoardApi;
- act(() => {
+ draw = () => act(() => {
render(
<BoardProperties
api={api}
@@ -96,6 +114,7 @@ describe("Board properties", () => {
/>,
container);
});
+ draw();
});
afterEach(() => {
@@ -133,7 +152,7 @@ describe("Board properties", () => {
it("draws a segment for each, reading what the board's labels say", () => {
const rows = general()?.querySelectorAll(".tn-card-section") ?? [];
- expect(rows.length).toBe(2);
+ expect(rows.length).toBe(3);
expect(toggleAt(0)?.classList.contains("on")).toBe(false);
expect(toggleAt(1)?.classList.contains("on")).toBe(true);
});
@@ -145,15 +164,44 @@ describe("Board properties", () => {
expect(toggled).toEqual([ [ "inbox", true ], [ "archived", false ] ]);
});
- function general() {
- return dialog()?.querySelector<HTMLElement>(".board-properties-general");
- }
-
function toggleAt(index: number) {
return general()?.querySelectorAll<HTMLElement>(".switch-button")[index];
}
});
+ describe("the order it offers its columns", () => {
+ it("names the order the board holds, and which way it runs", () => {
+ expect(picker()?.textContent).toContain("board_view.sort-manually");
+ expect(picker()?.querySelector(".bx-sort-up")).toBeTruthy();
+ });
+
+ it("names the attribute as the board names it, and turns the arrow over", () => {
+ labels = { sortColumns: "attr:dueDate", sortColumnsDescending: "true" };
+ // Drawn afresh: the labels are read as the card mounts, and a redraw of the same card
+ // would keep what it read the first time.
+ act(() => { render(null, container); });
+ draw();
+
+ expect(picker()?.textContent).toContain("Due");
+ expect(picker()?.querySelector(".bx-sort-down")).toBeTruthy();
+ });
+
+ it("hands the order to every column when asked to", () => {
+ act(() => { applyButton()?.click(); });
+
+ expect(sorting).toEqual([ "apply" ]);
+ });
+
+ function picker() {
+ return general()?.querySelector<HTMLElement>(".board-sort-picker");
+ }
+
+ function applyButton() {
+ return [ ...general()?.querySelectorAll<HTMLElement>("button") ?? [] ]
+ .find(button => button.textContent?.includes("board_view.apply-sort-to-columns"));
+ }
+ });
+
it("holds the promoted attributes, in the board's own words and from its own config", () => {
const card = dialog()?.querySelector<HTMLElement>(".attributes-stub");
@@ -178,4 +226,8 @@ describe("Board properties", () => {
function dialog() {
return document.querySelector<HTMLElement>(".board-properties-dialog");
}
+
+ function general() {
+ return dialog()?.querySelector<HTMLElement>(".board-properties-general");
+ }
});
diff --git a/apps/client/src/widgets/collections/board/properties.tsx b/apps/client/src/widgets/collections/board/properties.tsx
index 08d9b18502..aaf47efc71 100644
--- a/apps/client/src/widgets/collections/board/properties.tsx
+++ b/apps/client/src/widgets/collections/board/properties.tsx
@@ -4,13 +4,16 @@ import { useCallback } from "preact/hooks";
import type FNote from "../../../entities/fnote";
import { t } from "../../../services/i18n";
+import Button from "../../react/Button";
import { Card, OptionCardSection } from "../../react/Card";
import FormToggle from "../../react/FormToggle";
-import { useNoteLabelBoolean } from "../../react/hooks";
+import { useNoteLabel, useNoteLabelBoolean } from "../../react/hooks";
import Modal from "../../react/Modal";
import PromotedAttributesCard from "../../react/PromotedAttributesCard";
import TemplateSelectionCard from "../../react/TemplateSelectionCard";
import type { PromotedAttribute } from "../promoted_attributes";
+import SortDropdown from "../SortDropdown";
+import { parseSortKey } from "../sorting";
import BoardApi from "./api";
/** The board's settings, other than its columns and cards. */
@@ -62,6 +65,9 @@ export default function BoardProperties({ api, note, shown, onClose }: {
function General({ api, note }: { api: BoardApi, note: FNote }) {
const [ inboxShown ] = useNoteLabelBoolean(note, "enableInboxColumn");
const [ archivedShown ] = useNoteLabelBoolean(note, "includeArchived");
+ // Read off the board's own labels, so the dropdown follows what is picked in it.
+ const [ storedSort ] = useNoteLabel(note, "sortColumns");
+ const [ isDescending ] = useNoteLabelBoolean(note, "sortColumnsDescending");
return (
<Card className="board-properties-general" heading={t("board_view.general")}>
@@ -85,6 +91,26 @@ function General({ api, note }: { api: BoardApi, note: FNote }) {
onChange={(shown) => api.setArchivedShown(shown)}
/>
</OptionCardSection>
+
+ <OptionCardSection
+ name="board-sort-cards"
+ label={t("board_view.sort-cards")}
+ >
+ <SortDropdown
+ className="board-sort-picker"
+ orderBy={parseSortKey(storedSort)}
+ isDescending={isDescending}
+ attributes={api.getPromotedAttributes()}
+ noneTitle={t("board_view.sort-manually")}
+ onSelect={(orderBy) => api.setDefaultSort(orderBy)}
+ onDirectionChange={(descending) => api.setDefaultSortDirection(descending)}
+ />
+
+ <Button
+ text={t("board_view.apply-sort-to-columns")}
+ onClick={() => api.applyDefaultSortToColumns()}
+ />
+ </OptionCardSection>
</Card>
);
}
diff --git a/apps/client/src/widgets/collections/sort_menu.spec.ts b/apps/client/src/widgets/collections/sort_menu.spec.ts
index ba6339b4fb..adda691b35 100644
--- a/apps/client/src/widgets/collections/sort_menu.spec.ts
+++ b/apps/client/src/widgets/collections/sort_menu.spec.ts
@@ -2,7 +2,9 @@ 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";
+import {
+ buildSortMenuItems, sortEntries, sortMenuTitle, type SortMenuOptions
+} from "./sort_menu";
// i18next is never initialised under test, so `t` echoes the key it is given.
vi.mock("../../services/i18n", () => ({ t: (key: string) => key }));
@@ -104,6 +106,86 @@ describe("buildSortMenuItems", () => {
});
});
+describe("sortEntries", () => {
+ const attributes = [ attribute({ name: "dueDate", title: "Due date" }) ];
+
+ it("offers the orders a collection can take, each named and iconed once", () => {
+ const { orders, directions } = entries({ attributes });
+
+ expect(orders.map((entry) => [ entry.key, entry.title, entry.icon ])).toEqual([
+ [ "none", "sorting.none", "bx bx-move-vertical" ],
+ [ "title", "sorting.title", "bx bx-text" ],
+ [ "creationDate", "sorting.creation-date", "bx bx-calendar-plus" ],
+ // Named as the collection names it, and worn by the icon of what it holds.
+ [ "attr:dueDate", "Due date", "bx bx-text" ]
+ ]);
+ expect(directions.map((entry) => entry.key)).toEqual([ "ascending", "descending" ]);
+ // Only a name the user wrote is escaped and clipped where a menu draws it.
+ expect(orders.map((entry) => entry.isUserNamed))
+ .toEqual([ false, false, false, true ]);
+ });
+
+ it("marks the order the collection is in, and turns the direction off while it has none", () => {
+ const unsorted = entries({ attributes });
+ expect(unsorted.orders.map((entry) => entry.isSelected))
+ .toEqual([ true, false, false, false ]);
+ expect(unsorted.directions.map((entry) => entry.isEnabled)).toEqual([ false, false ]);
+
+ const sorted = entries({ attributes, orderBy: "attr:dueDate", isDescending: true });
+ expect(sorted.orders.map((entry) => entry.isSelected))
+ .toEqual([ false, false, false, true ]);
+ expect(sorted.directions.map((entry) => entry.isSelected)).toEqual([ false, true ]);
+ expect(sorted.directions.map((entry) => entry.isEnabled)).toEqual([ true, true ]);
+ });
+
+ it("reports what a pick names", () => {
+ const onSelect = vi.fn();
+ const onDirectionChange = vi.fn();
+ const { orders, directions } = entries({ attributes }, { onSelect, onDirectionChange });
+
+ orders[3].pick();
+ expect(onSelect).toHaveBeenCalledWith("attr:dueDate");
+
+ orders[0].pick();
+ expect(onSelect).toHaveBeenLastCalledWith(undefined);
+
+ directions[1].pick();
+ expect(onDirectionChange).toHaveBeenCalledWith(true);
+ });
+
+ function entries(
+ options: Partial<SortMenuOptions> = {},
+ handlers: Partial<Pick<SortMenuOptions, "onSelect" | "onDirectionChange">> = {}
+ ) {
+ return sortEntries({
+ orderBy: undefined,
+ isDescending: false,
+ attributes: [],
+ onSelect: handlers.onSelect ?? (() => {}),
+ onDirectionChange: handlers.onDirectionChange ?? (() => {}),
+ ...options
+ });
+ }
+});
+
+describe("sortMenuTitle", () => {
+ const attributes = [ attribute({ name: "dueDate", title: "Due date" }) ];
+
+ it("names the built-in keys, and the manual order by what the caller calls it", () => {
+ expect(sortMenuTitle({ orderBy: undefined, attributes })).toBe("sorting.none");
+ expect(sortMenuTitle({ orderBy: undefined, attributes, noneTitle: "Manually" }))
+ .toBe("Manually");
+ expect(sortMenuTitle({ orderBy: "title", attributes })).toBe("sorting.title");
+ expect(sortMenuTitle({ orderBy: "creationDate", attributes }))
+ .toBe("sorting.creation-date");
+ });
+
+ it("names an attribute as the collection names it, and an unknown one by its own name", () => {
+ expect(sortMenuTitle({ orderBy: "attr:dueDate", attributes })).toBe("Due date");
+ expect(sortMenuTitle({ orderBy: "attr:owner", attributes })).toBe("owner");
+ });
+});
+
function build(
options: Partial<SortMenuOptions> = {},
handlers: Partial<Pick<SortMenuOptions, "onSelect" | "onDirectionChange">> = {}
diff --git a/apps/client/src/widgets/collections/sort_menu.ts b/apps/client/src/widgets/collections/sort_menu.ts
index 7e0778daae..7fa50e2b30 100644
--- a/apps/client/src/widgets/collections/sort_menu.ts
+++ b/apps/client/src/widgets/collections/sort_menu.ts
@@ -5,7 +5,7 @@ import { t } from "../../services/i18n";
import { escapeHtml } from "../../services/utils";
import { promotedAttributeIcon } from "../attribute_widgets/attribute_types";
import type { PromotedAttribute } from "./promoted_attributes";
-import type { SortKey } from "./sorting";
+import { type SortKey, sortedAttributeName } from "./sorting";
export interface SortMenuOptions {
/** What the collection sorts by now, absent while it keeps the order the user arranged. */
@@ -21,59 +21,122 @@ export interface SortMenuOptions {
onDirectionChange: (isDescending: boolean) => void;
}
+/** One order a collection can be put in, however it is offered. */
+export interface SortEntry {
+ /** Tells the entries apart in a list: the stored key, or the direction it names. */
+ key: string;
+ title: string;
+ icon: string;
+ /** Whether the collection is in this order now. */
+ isSelected: boolean;
+ /** Whether it can be picked. The direction is off while nothing is sorted. */
+ isEnabled: boolean;
+ /** Whether the title is the user's own text, which a menu escapes and clips. */
+ isUserNamed: boolean;
+ pick: () => void;
+}
+
+/**
+ * What a collection offers to order its items by, and the two directions, for a menu or a dropdown
+ * to draw. Both surfaces read the same entries, so an order offered in one is offered in the other.
+ */
+export function sortEntries({
+ orderBy, isDescending, attributes, noneTitle, onSelect, onDirectionChange
+}: SortMenuOptions): { orders: SortEntry[], directions: SortEntry[] } {
+ const order = (
+ key: SortKey | undefined, title: string, icon: string, isUserNamed = false
+ ): SortEntry => ({
+ key: key ?? "none",
+ title,
+ icon,
+ isSelected: key === orderBy,
+ isEnabled: true,
+ isUserNamed,
+ pick: () => onSelect(key)
+ });
+
+ const direction = (descending: boolean, title: string, icon: string): SortEntry => ({
+ key: descending ? "descending" : "ascending",
+ title,
+ icon,
+ isSelected: !!orderBy && isDescending === descending,
+ isEnabled: !!orderBy,
+ isUserNamed: false,
+ pick: () => onDirectionChange(descending)
+ });
+
+ return {
+ orders: [
+ order(undefined, noneTitle ?? t("sorting.none"), "bx bx-move-vertical"),
+ order("title", t("sorting.title"), "bx bx-text"),
+ order("creationDate", t("sorting.creation-date"), "bx bx-calendar-plus"),
+ ...attributes.map((attribute) => order(
+ `attr:${attribute.name}`,
+ attribute.title,
+ promotedAttributeIcon(attribute),
+ true))
+ ],
+ directions: [
+ direction(false, t("sorting.ascending"), "bx bx-sort-up"),
+ direction(true, t("sorting.descending"), "bx bx-sort-down")
+ ]
+ };
+}
+
+/**
+ * What the order a collection is sorted by is called, for a control standing in for the menu.
+ *
+ * A key naming an attribute the collection no longer defines reads as the bare name: it is still
+ * what the items are ordered by, and there is no title left to show for it.
+ */
+export function sortMenuTitle(
+ { orderBy, attributes, noneTitle }: Pick<SortMenuOptions, "orderBy" | "attributes" | "noneTitle">
+): string {
+ const { orders } = sortEntries({
+ orderBy,
+ attributes,
+ noneTitle,
+ isDescending: false,
+ onSelect: () => {},
+ onDirectionChange: () => {}
+ });
+
+ const current = orders.find((entry) => entry.isSelected);
+ if (current) {
+ return current.title;
+ }
+
+ return orderBy ? sortedAttributeName(orderBy) ?? orderBy : orders[0].title;
+}
+
/**
* The entries a collection offers for how it orders its items.
*
* 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);
+export function buildSortMenuItems<T>(options: SortMenuOptions): MenuItem<T>[] {
+ const { orders, directions } = sortEntries(options);
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
- // clips a long one instead of widening the menu.
- title: `<span class="sort-menu-name">${escapeHtml(attribute.title)}</span>`,
- className: "sort-menu-item",
- uiIcon: promotedAttributeIcon(attribute),
- trailingIcon: checkFor(`attr:${attribute.name}`),
- handler: () => onSelect(`attr:${attribute.name}`)
- })),
+ ...orders.map((entry) => toMenuItem<T>(entry)),
{ 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)
- }
+ ...directions.map((entry) => toMenuItem<T>(entry))
];
}
+
+/** One entry as a menu reads it: a title of markup, the mark at the trailing edge. */
+function toMenuItem<T>(entry: SortEntry): MenuItem<T> {
+ return {
+ // A name the user wrote is escaped into the text it is meant to be, and boxed so that
+ // `sort_menu.css` clips a long one instead of widening the menu.
+ title: entry.isUserNamed
+ ? `<span class="sort-menu-name">${escapeHtml(entry.title)}</span>`
+ : entry.title,
+ className: entry.isUserNamed ? "sort-menu-item" : undefined,
+ uiIcon: entry.icon,
+ enabled: entry.isEnabled,
+ trailingIcon: entry.isSelected ? "bx bx-check" : undefined,
+ handler: () => entry.pick()
+ };
+}
diff --git a/packages/commons/src/lib/builtin_attributes.ts b/packages/commons/src/lib/builtin_attributes.ts
index 9e24086f20..8bddc6c36c 100644
--- a/packages/commons/src/lib/builtin_attributes.ts
+++ b/packages/commons/src/lib/builtin_attributes.ts
@@ -269,6 +269,9 @@ const BUILTIN_ATTRIBUTES = [
{ type: "label", name: "maxNestingDepth", valueType: "number", hasUserValue: true },
{ type: "label", name: "includeArchived", valueType: "boolean", hasUserValue: true },
{ type: "label", name: "enableInboxColumn", valueType: "boolean", hasUserValue: true },
+ // The order a board offers for its columns, which its properties apply to every column at once.
+ { type: "label", name: "sortColumns", valueType: "text", hasUserValue: true },
+ { type: "label", name: "sortColumnsDescending", valueType: "boolean", hasUserValue: true },
// FullCalendar's own view names, which is what the calendar hands back when the view is switched.
{ type: "label", name: "calendar:view", valueType: "select", hasUserValue: true, selectOptions: [
"timeGridDay", "timeGridWeek", "dayGridMonth", "multiMonthYear", "listMonth"