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: honor the board default card sorting option
Adorian Doran4a6d05b3b461
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 87daaf3ebc..91304ad064 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3520,6 +3520,7 @@"sort": "Sort","sort-manually": "Manually","sort-cards": "Sort cards",+ "sort-board-default": "Board's default","apply-sort-to-columns": "Apply to all columns","sorted-no-reorder": "Cards cannot be reordered, since this is a sorted column."},@@ -4228,6 +4229,7 @@"submit": "Apply the filter"},"sorting": {+ "default": "Default","none": "None","title": "Title","creation-date": "Creation date & time",diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.tsindex 86298d76b8..a0de5446bd 100644--- a/apps/client/src/widgets/collections/board/api.spec.ts+++ b/apps/client/src/widgets/collections/board/api.spec.ts@@ -1849,6 +1849,53 @@ describe("how a column orders its cards", () => {});});+describe("a column that takes the board's order", () => {+ /** A board holding an order of its own, which a column can be stored as taking. */+ function boardSorting() {+ return buildNote({+ title: "Board", "#sortColumns": "attr:dueDate", "#sortColumnsDescending": ""+ });+ }++ it("keeps the stored value apart from the order the column is drawn in", () => {+ const { api } = createApi(+ { columns: [ { value: "To Do", orderBy: "default" } ] }, [ "To Do" ], boardSorting());++ // What the menu marks, and what the cards are ordered by.+ expect(api.getColumnSort("To Do"))+ .toEqual({ orderBy: "default", isDescending: false });+ expect(api.getEffectiveColumnSort("To Do"))+ .toEqual({ orderBy: "attr:dueDate", isDescending: true });+ expect(api.isColumnSorted("To Do")).toBe(true);+ });++ it("keeps the manual order while the board holds none", () => {+ const { api } = createApi(+ { columns: [ { value: "To Do", orderBy: "default" } ] }, [ "To Do" ]);++ expect(api.getColumnSort("To Do").orderBy).toBe("default");+ expect(api.getEffectiveColumnSort("To Do").orderBy).toBeUndefined();+ expect(api.isColumnSorted("To Do")).toBe(false);+ });++ it("leaves a column with an order of its own alone", () => {+ const { api } = createApi(+ { columns: [ { value: "To Do", orderBy: "title", descendingOrder: true } ] },+ [ "To Do" ],+ boardSorting());++ expect(api.getEffectiveColumnSort("To Do"))+ .toEqual({ orderBy: "title", isDescending: true });+ });++ it("stores the value a pick names", async () => {+ const { api, saved } = createApi({ columns: [ { value: "To Do" } ] }, [ "To Do" ]);++ await api.setColumnSort("To Do", "default");+ expect(saved.at(-1)?.columns).toEqual([ { value: "To Do", orderBy: "default" } ]);+ });+});+describe("the order the board offers its columns", () => {beforeEach(() => vi.restoreAllMocks());diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.tsindex 1f287040d5..e40468149a 100644--- a/apps/client/src/widgets/collections/board/api.ts+++ b/apps/client/src/widgets/collections/board/api.ts@@ -18,7 +18,9 @@ import {type PromotedAttribute, resolvePromotedAttributes, storedPromotedAttributes,visiblePromotedAttributeNames} from "../promoted_attributes";-import { parseSortKey, type SortKey } from "../sorting";+import {+ DEFAULT_SORT, parseSortKey, parseStoredSortKey, type SortKey, type StoredSortKey+} from "../sorting";import { BoardColumnData, BoardViewData } from ".";import { currentCardTemplate, DEFAULT_CARD_TEMPLATES } from "./card_templates";import {@@ -621,20 +623,35 @@ export default class BoardApi {}/**- * How a column orders its cards.+ * What a column is set to order its cards by, which can be the board's own order.*- * @returns the key to sort by, absent for the manual order, and its direction.+ * @returns the stored key, absent for the manual order, and the direction stored with it. See+ * {@link getEffectiveColumnSort} for what the column is actually drawn in.*/getColumnSort(column: string) {const stored = this.viewConfig?.columns?.find(col => col.value === column);return {- orderBy: parseSortKey(stored?.orderBy),+ orderBy: parseStoredSortKey(stored?.orderBy),isDescending: !!stored?.descendingOrder};}+ /**+ * The order a column is drawn in: its own, or the board's where it takes that. A column taking+ * an order the board does not hold keeps the manual one.+ */+ getEffectiveColumnSort(column: string) {+ const stored = this.getColumnSort(column);+ if (stored.orderBy !== DEFAULT_SORT) {+ return { orderBy: stored.orderBy, isDescending: stored.isDescending };+ }++ const board = this.getDefaultSort();+ return { orderBy: board.orderBy, isDescending: board.isDescending };+ }+/** Sets what a column sorts by. Pass `undefined` for the manual order. */- async setColumnSort(column: string, orderBy: SortKey | undefined) {+ async setColumnSort(column: string, orderBy: StoredSortKey | undefined) {await this.updateColumn(column, { orderBy });}@@ -1222,7 +1239,7 @@ export default class BoardApi {/** Whether a column orders its own cards rather than keeping the order the user set. */isColumnSorted(column: string) {- return !!this.getColumnSort(column).orderBy;+ return !!this.getEffectiveColumnSort(column).orderBy;}/** Moves a card to the end of another column, where a card sent by the keyboard belongs. */diff --git a/apps/client/src/widgets/collections/board/context_menu.spec.ts b/apps/client/src/widgets/collections/board/context_menu.spec.tsindex 45a6a161b4..2f6a04ac8e 100644--- a/apps/client/src/widgets/collections/board/context_menu.spec.ts+++ b/apps/client/src/widgets/collections/board/context_menu.spec.ts@@ -71,6 +71,7 @@ describe("Board column context menu", () => {const withDefaults = Object.assign({getColumnTitle: (name: string) => name,getColumnSort: () => ({ orderBy: undefined, isDescending: false }),+ getEffectiveColumnSort: () => ({ orderBy: undefined, isDescending: false }),getPromotedAttributes: () => []}, api);openColumnContextMenu(withDefaults, event, {@@ -425,6 +426,7 @@ describe("Board column context menu", () => {function sortApi() {return {getColumnSort: () => ({ orderBy: undefined, isDescending: false }),+ getEffectiveColumnSort: () => ({ orderBy: undefined, isDescending: false }),getPromotedAttributes: () => [],setColumnSort: vi.fn(),setColumnSortDirection: vi.fn()@@ -438,19 +440,22 @@ describe("Board column context menu", () => {return entry.items ?? [];}- it("calls the unsorted order Manually rather than None", () => {- const first = sortItems(sortApi())[0];+ it("leads with the board's own order, and calls the unsorted one Manually", () => {+ const items = sortItems(sortApi());- expect(first && "title" in first ? first.title : "")- .toBe("board_view.sort-manually");+ expect(items.slice(0, 2).map(item => item && "title" in item ? item.title : ""))+ .toEqual([ "board_view.sort-board-default", "board_view.sort-manually" ]);});it("writes what is picked against the column the menu was opened on", () => {const api = sortApi();const items = sortItems(api, "Done");- pick(items[1]);- expect(api.setColumnSort).toHaveBeenCalledWith("Done", "title");+ pick(items[0]);+ expect(api.setColumnSort).toHaveBeenCalledWith("Done", "default");++ pick(items[2]);+ expect(api.setColumnSort).toHaveBeenLastCalledWith("Done", "title");pick(items.at(-1));expect(api.setColumnSortDirection).toHaveBeenCalledWith("Done", true);diff --git a/apps/client/src/widgets/collections/board/context_menu.ts b/apps/client/src/widgets/collections/board/context_menu.tsindex d865eb0f6d..08c823d41a 100644--- a/apps/client/src/widgets/collections/board/context_menu.ts+++ b/apps/client/src/widgets/collections/board/context_menu.ts@@ -257,10 +257,14 @@ export function openColumnSortMenu(api: Api, x: number, y: number, column: strin/** What the board asks the shared sort menu for, wherever it is opened. */function sortMenuOptions(api: Api, column: string): SortMenuOptions {return {- ...api.getColumnSort(column),+ orderBy: api.getColumnSort(column).orderBy,+ // The direction the column is drawn in, which the board decides for a column taking its+ // order.+ isDescending: api.getEffectiveColumnSort(column).isDescending,attributes: api.getPromotedAttributes(),// A board arranges its cards by hand rather than leaving them unsorted.noneTitle: t("board_view.sort-manually"),+ defaultTitle: t("board_view.sort-board-default"),onSelect: (orderBy) => api.setColumnSort(column, orderBy),onDirectionChange: (isDescending) => api.setColumnSortDirection(column, isDescending)};diff --git a/apps/client/src/widgets/collections/board/data.spec.ts b/apps/client/src/widgets/collections/board/data.spec.tsindex f5df4f0284..a5795157d7 100644--- a/apps/client/src/widgets/collections/board/data.spec.ts+++ b/apps/client/src/widgets/collections/board/data.spec.ts@@ -479,6 +479,22 @@ describe("sorting the cards of a column", () => {it("reads a board with no stored columns as one that sorts nothing", () => {expect(resolveColumnSorts(undefined).size).toBe(0);});++ it("gives a column stored as default the order the board holds", () => {+ const columns = [+ { value: "To Do", orderBy: "default" },+ { value: "Doing", orderBy: "title", descendingOrder: true }+ ];+ const sorts = resolveColumnSorts(+ columns, { orderBy: "attr:dueDate", isDescending: true });++ expect(sorts.get("To Do")).toEqual({ orderBy: "attr:dueDate", isDescending: true });+ // A column with an order of its own keeps it.+ expect(sorts.get("Doing")).toEqual({ orderBy: "title", isDescending: true });++ // The board holding none leaves such a column in the manual order.+ expect([ ...resolveColumnSorts(columns).keys() ]).toEqual([ "Doing" ]);+ });});describe("sortColumnMap", () => {diff --git a/apps/client/src/widgets/collections/board/data.ts b/apps/client/src/widgets/collections/board/data.tsindex c901dabbbd..517295661c 100644--- a/apps/client/src/widgets/collections/board/data.ts+++ b/apps/client/src/widgets/collections/board/data.ts@@ -3,7 +3,7 @@ import FNote from "../../../entities/fnote";import type LoadResults from "../../../services/load_results";import type { PromotedAttribute } from "../promoted_attributes";import {- parseSortKey, sortedAttributeName, sortItems, type SortContext, type SortKey+ DEFAULT_SORT, parseSortKey, sortedAttributeName, sortItems, type SortContext, type SortKey} from "../sorting";import { INBOX_COLUMN, resolveBoardColumns } from "./columns";import { BoardColumnData, BoardViewData } from "./index";@@ -81,11 +81,25 @@ export interface SortWatch {attributeNames: Set<string>;}-/** What each column sorts by, leaving out every column that keeps the manual order. */-export function resolveColumnSorts(columns: BoardColumnData[] | undefined) {+/**+ * What each column sorts by, leaving out every column that keeps the manual order.+ *+ * @param defaultSort the order the board holds, which a column stored as `default` takes. Such a+ * column keeps the manual order while the board holds none.+ */+export function resolveColumnSorts(+ columns: BoardColumnData[] | undefined, defaultSort?: ColumnSort+) {const sorts = new Map<string, ColumnSort>();for (const { value, orderBy, descendingOrder } of columns ?? []) {+ if (orderBy === DEFAULT_SORT) {+ if (defaultSort) {+ sorts.set(value, defaultSort);+ }+ continue;+ }+const key = parseSortKey(orderBy);if (key) {sorts.set(value, { orderBy: key, isDescending: !!descendingOrder });diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsxindex 5033784680..0809ee0b6b 100644--- a/apps/client/src/widgets/collections/board/index.spec.tsx+++ b/apps/client/src/widgets/collections/board/index.spec.tsx@@ -3619,8 +3619,8 @@ describe("a column that sorts its cards", () => {const items = show.mock.calls.at(-1)?.[0].items ?? [];expect(items.map(item => (item && "uiIcon" in item ? item.uiIcon : "separator"))).toEqual([- "bx bx-move-vertical", "bx bx-text", "bx bx-calendar-plus", "separator",- "bx bx-sort-up", "bx bx-sort-down"+ "bx bx-collection", "bx bx-move-vertical", "bx bx-text", "bx bx-calendar-plus",+ "separator", "bx bx-sort-up", "bx bx-sort-down"]);show.mockRestore();diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsxindex 7039546a6a..bf933d1380 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -23,13 +23,13 @@ import toast from "../../../services/toast";import { escapeHtml, isMobile } from "../../../services/utils";import { type NoteTypeOption, resolveNoteTypeOptions } from "../../../services/note_types";import { type PromotedAttributeSetting, resolvePromotedAttributes } from "../promoted_attributes";-import type { SortContext } from "../sorting";+import { parseSortKey, type SortContext } from "../sorting";import CollectionProperties from "../../note_bars/CollectionProperties";import FormTextArea from "../../react/FormTextArea";import FormTextBox from "../../react/FormTextBox";import {- useContextualShortcutHints, useNoteContext, useNoteLabelBoolean, useNoteLabelWithDefault,- useNoteTypeOptions, useTrackedElement, useTriliumEvent+ useContextualShortcutHints, useNoteContext, useNoteLabel, useNoteLabelBoolean,+ useNoteLabelWithDefault, useNoteTypeOptions, useTrackedElement, useTriliumEvent} from "../../react/hooks";import Icon from "../../react/Icon";import NoteAutocomplete from "../../react/NoteAutocomplete";@@ -290,6 +290,8 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCconst [ statusAttributeWithPrefix ] = useNoteLabelWithDefault(parentNote, "board:groupBy", DEFAULT_GROUP_BY);const [ includeArchived ] = useNoteLabelBoolean(parentNote, "includeArchived");const [ inboxEnabled ] = useNoteLabelBoolean(parentNote, "enableInboxColumn");+ const [ storedDefaultSort ] = useNoteLabel(parentNote, "sortColumns");+ const [ isDefaultDescending ] = useNoteLabelBoolean(parentNote, "sortColumnsDescending");/** Every card the board holds, which an active filter narrows before the cards are drawn. */const [ allByColumn, setAllByColumn ] = useState<ColumnMap>();const [ columns, setColumns ] = useState<string[]>();@@ -395,8 +397,14 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC() => resolvePromotedAttributes(parentNote, viewConfig?.promotedAttributes, [ statusAttribute ]),[ parentNote, viewConfig, statusAttribute, definitionRevision ]);+ // Held rather than read per column: every column taking the board's order asks for it, and the+ // labels change only when the reader picks another one.+ const defaultSort = useMemo(() => {+ const orderBy = parseSortKey(storedDefaultSort);+ return orderBy ? { orderBy, isDescending: isDefaultDescending } : undefined;+ }, [ storedDefaultSort, isDefaultDescending ]);const columnSorts = useMemo(- () => resolveColumnSorts(viewConfig?.columns), [ viewConfig ]);+ () => resolveColumnSorts(viewConfig?.columns, defaultSort), [ viewConfig, defaultSort ]);const sortContext = useMemo<SortContext>(() => ({definitions: new Map(promotedAttributes.map(attribute => [ attribute.name, attribute ])),creationDate: getCreationDate,diff --git a/apps/client/src/widgets/collections/board/properties.tsx b/apps/client/src/widgets/collections/board/properties.tsxindex aaf47efc71..6503d260c6 100644--- a/apps/client/src/widgets/collections/board/properties.tsx+++ b/apps/client/src/widgets/collections/board/properties.tsx@@ -102,6 +102,7 @@ function General({ api, note }: { api: BoardApi, note: FNote }) {isDescending={isDescending}attributes={api.getPromotedAttributes()}noneTitle={t("board_view.sort-manually")}+ hideDefaultonSelect={(orderBy) => api.setDefaultSort(orderBy)}onDirectionChange={(descending) => api.setDefaultSortDirection(descending)}/>diff --git a/apps/client/src/widgets/collections/sort_menu.spec.ts b/apps/client/src/widgets/collections/sort_menu.spec.tsindex adda691b35..1977e127b4 100644--- a/apps/client/src/widgets/collections/sort_menu.spec.ts+++ b/apps/client/src/widgets/collections/sort_menu.spec.ts@@ -10,8 +10,9 @@ import {vi.mock("../../services/i18n", () => ({ t: (key: string) => key }));describe("buildSortMenuItems", () => {- it("offers no sorting, the two built-in keys and the direction", () => {+ it("offers the collection's own order, no sorting, the built-in keys and the direction", () => {expect(icons(build())).toEqual([+ "bx bx-collection","bx bx-move-vertical","bx bx-text","bx bx-calendar-plus",@@ -21,24 +22,41 @@ describe("buildSortMenuItems", () => {]);});- 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("names both fallbacks itself, and lets the caller name them otherwise", () => {+ expect(titles(build()).slice(0, 2)).toEqual([ "sorting.default", "sorting.none" ]);+ expect(titles(build({ defaultTitle: "Board's default", noneTitle: "Manually" }))+ .slice(0, 2)).toEqual([ "Board's default", "Manually" ]);+ });++ /** The menu that sets the collection's own order has nothing above it to take one from. */+ it("leaves out the collection's own order where the caller hides it", () => {+ expect(titles(build({ hideDefault: true }))[0]).toBe("sorting.none");+ expect(icons(build({ hideDefault: true }))).not.toContain("bx bx-collection");});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[1]).toMatchObject({ trailingIcon: "bx bx-check" });+ expect(items[2]).toMatchObject({ trailingIcon: undefined });expect(items.at(-2)).toMatchObject({ enabled: false, trailingIcon: undefined });expect(items.at(-1)).toMatchObject({ enabled: false, trailingIcon: undefined });});+ /** The order comes from above with a direction of its own, so there is none to pick here. */+ it("checks the collection's own order, and offers no direction with it", () => {+ const items = build({ orderBy: "default", isDescending: true });++ expect(items[0]).toMatchObject({ trailingIcon: "bx bx-check" });+ expect(items[1]).toMatchObject({ trailingIcon: undefined });+ expect(items.at(-2)).toMatchObject({ enabled: false });+ expect(items.at(-1)).toMatchObject({ enabled: false, trailingIcon: "bx bx-check" });+ });+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[1]).toMatchObject({ trailingIcon: undefined });+ expect(ascending[2]).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 });@@ -56,14 +74,14 @@ describe("buildSortMenuItems", () => {]});- expect(titles(items).slice(3, 5)).toEqual([+ expect(titles(items).slice(4, 6)).toEqual([`<span class="sort-menu-name">Due date</span>`,`<span class="sort-menu-name">Owner</span>`]);- expect(items[3]).toMatchObject({+ expect(items[4]).toMatchObject({uiIcon: "bx bx-calendar", className: "sort-menu-item", trailingIcon: undefined});- expect(items[4]).toMatchObject({ uiIcon: "bx bx-transfer", trailingIcon: "bx bx-check" });+ expect(items[5]).toMatchObject({ uiIcon: "bx bx-transfer", trailingIcon: "bx bx-check" });});it("escapes what a crafted attribute name would plant in the menu", () => {@@ -71,26 +89,29 @@ describe("buildSortMenuItems", () => {attributes: [ attribute({ name: "x", title: `<img src=x onerror="alert(1)">` }) ]});- expect(titles(items)[3]).toBe("<span class=\"sort-menu-name\">"+ expect(titles(items)[4]).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", () => {+ it("reports the key a pick names, and no key at all for the manual order", () => {const onSelect = vi.fn();const items = build({attributes: [ attribute({ name: "dueDate", title: "Due date" }) ]}, { onSelect });- pick(items[1]);- expect(onSelect).toHaveBeenCalledWith("title");+ pick(items[0]);+ expect(onSelect).toHaveBeenCalledWith("default");pick(items[2]);- expect(onSelect).toHaveBeenCalledWith("creationDate");+ expect(onSelect).toHaveBeenCalledWith("title");pick(items[3]);+ expect(onSelect).toHaveBeenCalledWith("creationDate");++ pick(items[4]);expect(onSelect).toHaveBeenCalledWith("attr:dueDate");- pick(items[0]);+ pick(items[1]);expect(onSelect).toHaveBeenCalledWith(undefined);});@@ -113,6 +134,7 @@ describe("sortEntries", () => {const { orders, directions } = entries({ attributes });expect(orders.map((entry) => [ entry.key, entry.title, entry.icon ])).toEqual([+ [ "default", "sorting.default", "bx bx-collection" ],[ "none", "sorting.none", "bx bx-move-vertical" ],[ "title", "sorting.title", "bx bx-text" ],[ "creationDate", "sorting.creation-date", "bx bx-calendar-plus" ],@@ -122,18 +144,18 @@ describe("sortEntries", () => {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 ]);+ .toEqual([ false, 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 ]);+ .toEqual([ false, 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 ]);+ .toEqual([ false, false, false, false, true ]);expect(sorted.directions.map((entry) => entry.isSelected)).toEqual([ false, true ]);expect(sorted.directions.map((entry) => entry.isEnabled)).toEqual([ true, true ]);});@@ -143,10 +165,13 @@ describe("sortEntries", () => {const onDirectionChange = vi.fn();const { orders, directions } = entries({ attributes }, { onSelect, onDirectionChange });- orders[3].pick();+ orders[4].pick();expect(onSelect).toHaveBeenCalledWith("attr:dueDate");orders[0].pick();+ expect(onSelect).toHaveBeenLastCalledWith("default");++ orders[1].pick();expect(onSelect).toHaveBeenLastCalledWith(undefined);directions[1].pick();diff --git a/apps/client/src/widgets/collections/sort_menu.ts b/apps/client/src/widgets/collections/sort_menu.tsindex 7fa50e2b30..0a4700ef44 100644--- a/apps/client/src/widgets/collections/sort_menu.ts+++ b/apps/client/src/widgets/collections/sort_menu.ts@@ -5,19 +5,31 @@ 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, sortedAttributeName } from "./sorting";+import {+ DEFAULT_SORT, type SortKey, sortedAttributeName, type StoredSortKey+} from "./sorting";export interface SortMenuOptions {/** What the collection sorts by now, absent while it keeps the order the user arranged. */- orderBy: SortKey | undefined;+ orderBy: StoredSortKey | 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;+ /**+ * What the entry taking the collection's own order is called. "Default" unless the caller names+ * it.+ */+ defaultTitle?: string;+ /**+ * Leaves that entry out, for the menu that sets the collection's own order: there is nothing+ * above it for it to take one from.+ */+ hideDefault?: boolean;/** Called with the key picked, or `undefined` for the order the user arranges by hand. */- onSelect: (orderBy: SortKey | undefined) => void;+ onSelect: (orderBy: StoredSortKey | undefined) => void;onDirectionChange: (isDescending: boolean) => void;}@@ -41,10 +53,11 @@ export interface SortEntry {* 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+ orderBy, isDescending, attributes, noneTitle, defaultTitle, hideDefault, onSelect,+ onDirectionChange}: SortMenuOptions): { orders: SortEntry[], directions: SortEntry[] } {const order = (- key: SortKey | undefined, title: string, icon: string, isUserNamed = false+ key: StoredSortKey | undefined, title: string, icon: string, isUserNamed = false): SortEntry => ({key: key ?? "none",title,@@ -55,18 +68,23 @@ export function sortEntries({pick: () => onSelect(key)});+ // Off while the collection keeps the manual order, and while it takes the order above it,+ // which brings a direction of its own.+ const canPickDirection = !!orderBy && orderBy !== DEFAULT_SORT;const direction = (descending: boolean, title: string, icon: string): SortEntry => ({key: descending ? "descending" : "ascending",title,icon,isSelected: !!orderBy && isDescending === descending,- isEnabled: !!orderBy,+ isEnabled: canPickDirection,isUserNamed: false,pick: () => onDirectionChange(descending)});return {orders: [+ ...(hideDefault ? [] : [ order(+ DEFAULT_SORT, defaultTitle ?? t("sorting.default"), "bx bx-collection") ]),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"),diff --git a/apps/client/src/widgets/collections/sorting.ts b/apps/client/src/widgets/collections/sorting.tsindex 59d30e50d3..105858d066 100644--- a/apps/client/src/widgets/collections/sorting.ts+++ b/apps/client/src/widgets/collections/sorting.ts@@ -6,6 +6,12 @@ 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 an item stores to take the collection's own order rather than one of its own. */+export const DEFAULT_SORT = "default";++/** What one column of a collection stores: an order of its own, or the collection's. */+export type StoredSortKey = SortKey | typeof DEFAULT_SORT;+/** What the sort needs besides the notes themselves. */export interface SortContext {/** The promoted attributes by name, used to decide how each value compares. */@@ -38,6 +44,13 @@ export function parseSortKey(orderBy: string | null | undefined): SortKey | undereturn undefined;}+/** Reads a stored `orderBy` setting, the collection's own order included. */+export function parseStoredSortKey(+ orderBy: string | null | undefined+): StoredSortKey | undefined {+ return orderBy === DEFAULT_SORT ? DEFAULT_SORT : parseSortKey(orderBy);+}+/** The attribute a key sorts by, or undefined when the key names something else. */export function sortedAttributeName(key: SortKey) {return key.startsWith(ATTRIBUTE_PREFIX) ? key.substring(ATTRIBUTE_PREFIX.length) : undefined;