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 the initial implementation for switchable card grouping
Adorian Doran5a395e47461f
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 729fc2b177..e1df1a873a 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3518,6 +3518,7 @@},"status-alias": "Status","filter-placeholder": "Filter board...",+ "group-by": "Group cards by","card-outside-filter": "This card is outside of the current filtering scope","sort": "Sort","sort-manually": "Manually",diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.tsindex a44aac5fdd..ad471239e0 100644--- a/apps/client/src/widgets/collections/board/api.spec.ts+++ b/apps/client/src/widgets/collections/board/api.spec.ts@@ -1143,7 +1143,7 @@ describe("BoardApi.syncColumnsToDefinition", () => {it("gives a board with no definition its own promoted select carrying the resolved columns", async () => {const { api } = createApi({}, [], buildBoard({}));- await api.syncColumnsToDefinition([ "To Do", "Done" ]);+ await api.syncColumnsToDefinition([ "To Do", "Done" ], api.groupBy);expect(definitionWritten()).toMatchObject({// The upsert endpoint, which matches the board's own attribute of this name.@@ -1166,8 +1166,8 @@ describe("BoardApi.syncColumnsToDefinition", () => {const { api } = createApi({}, [], buildBoard({}));await Promise.all([- api.syncColumnsToDefinition([ "To Do" ]),- api.syncColumnsToDefinition([ "To Do", "Done" ])+ api.syncColumnsToDefinition([ "To Do" ], api.groupBy),+ api.syncColumnsToDefinition([ "To Do", "Done" ], api.groupBy)]);expect(put).toHaveBeenCalledTimes(2);@@ -1183,7 +1183,7 @@ describe("BoardApi.syncColumnsToDefinition", () => {it("names a board grouping by its own label after that label rather than after status", async () => {const { api } = createApi({}, [], buildBoard({}), "priority");- await api.syncColumnsToDefinition([ "High" ]);+ await api.syncColumnsToDefinition([ "High" ], api.groupBy);expect(definitionWritten()).toMatchObject({name: "label:priority",@@ -1201,7 +1201,7 @@ describe("BoardApi.syncColumnsToDefinition", () => {"#label:status": "single,select,options=To Do"}));- await api.syncColumnsToDefinition([ "To Do", "Done" ]);+ await api.syncColumnsToDefinition([ "To Do", "Done" ], api.groupBy);expect(definitionWritten().value).toBe("single,select,options=To Do;Done");});@@ -1215,7 +1215,7 @@ describe("BoardApi.syncColumnsToDefinition", () => {"#label:status": "promoted,single,select,options=To Do;Done"}));- await api.syncColumnsToDefinition([ "To Do", "Done" ]);+ await api.syncColumnsToDefinition([ "To Do", "Done" ], api.groupBy);expect(put).not.toHaveBeenCalled();});@@ -1226,7 +1226,7 @@ describe("BoardApi.syncColumnsToDefinition", () => {// A note given `#status=Blocked` from the table view shows up as a column here, and the// definition has to learn about it as well.- await api.syncColumnsToDefinition([ "To Do", "Blocked" ]);+ await api.syncColumnsToDefinition([ "To Do", "Blocked" ], api.groupBy);const written = definitionWritten();expect(written.value).toBe("promoted,single,select,options=To Do;Blocked");@@ -1241,7 +1241,7 @@ describe("BoardApi.syncColumnsToDefinition", () => {"#label:status": "single,select,options=To Do;Done"}));- await api.syncColumnsToDefinition([ "Done", "To Do" ]);+ await api.syncColumnsToDefinition([ "Done", "To Do" ], api.groupBy);expect(definitionWritten().value).toBe("single,select,options=Done;To Do");});@@ -1252,7 +1252,7 @@ describe("BoardApi.syncColumnsToDefinition", () => {]);const { api } = createApi({}, [], board);- await api.syncColumnsToDefinition([ "To Do" ]);+ await api.syncColumnsToDefinition([ "To Do" ], api.groupBy);const written = definitionWritten();// The endpoint only ever matches attributes owned by this note, so the template's own row is@@ -1273,24 +1273,101 @@ describe("BoardApi.syncColumnsToDefinition", () => {const board = buildBoard(owned ?? {}, inherited ? [ inherited ] : []);const { api } = createApi({}, [], board, groupBy);- await api.syncColumnsToDefinition([ "To Do" ]);+ await api.syncColumnsToDefinition([ "To Do" ], api.groupBy);expect(put).not.toHaveBeenCalled();});it("does not invent an empty definition, but does empty one the board owns", async () => {const { api: withoutDefinition } = createApi({}, [], buildBoard({}));- await withoutDefinition.syncColumnsToDefinition([]);+ await withoutDefinition.syncColumnsToDefinition([], withoutDefinition.groupBy);expect(put).not.toHaveBeenCalled();const { api: withDefinition } = createApi({}, [], buildBoard({"#label:status": "promoted,single,select,options=To Do"}));- await withDefinition.syncColumnsToDefinition([]);+ await withDefinition.syncColumnsToDefinition([], withDefinition.groupBy);expect(definitionWritten().value).toBe("promoted,single,select");});});+describe("BoardApi column storage", () => {+ /** A board grouped by `priority`, with columns stored for it and for the default grouping. */+ function priorityBoard(byColumn: ColumnMap = new Map()) {+ return createApi({+ columns: [ { value: "To Do", icon: "bx bx-time" } ],+ priorityViewColumns: [ { value: "High", icon: "bx bx-up-arrow", limit: 3 } ]+ }, [ "High" ], buildBoard({}), "priority", byColumn);+ }++ it("reads what a column is drawn with from the grouping's own key", () => {+ const { api } = priorityBoard();++ expect(api.getColumnIcon("High")).toBe("bx bx-up-arrow");+ expect(api.getColumnLimit("High")).toBe(3);+ // The default grouping's column, which this grouping knows nothing about.+ expect(api.getColumnIcon("To Do")).toBe(DEFAULT_COLUMN_ICON);+ });++ it("stores a new column under its key, leaving the other grouping's alone", async () => {+ const { api, saved } = priorityBoard();++ await api.addNewColumn("Low");++ expect(saved.at(-1)?.priorityViewColumns?.map(col => col.value)).toEqual([ "High", "Low" ]);+ expect(saved.at(-1)?.columns).toEqual([ { value: "To Do", icon: "bx bx-time" } ]);+ });++ it("keeps a column's icon and colour out of the other grouping's list", async () => {+ const { api, saved } = priorityBoard();++ await api.setColumnIcon("High", "bx bx-star");+ await api.setColumnColor("High", "#0f0");++ expect(saved.at(-1)?.priorityViewColumns)+ .toEqual([ { value: "High", icon: "bx bx-star", color: "#0f0", limit: 3 } ]);+ expect(saved.at(-1)?.columns).toEqual([ { value: "To Do", icon: "bx bx-time" } ]);+ });++ it("removes a column from the grouping's key alone", async () => {+ const { api, saved } = priorityBoard(new Map([ [ "High", [] ] ]));++ await api.removeColumn("High");++ expect(saved.at(-1)?.priorityViewColumns).toEqual([]);+ expect(saved.at(-1)?.columns).toEqual([ { value: "To Do", icon: "bx bx-time" } ]);+ });++ it("stores the default grouping under the key every board already uses", async () => {+ const { api, saved } = createApi(+ { columns: [ { value: "To Do" } ] }, [ "To Do" ], buildBoard({}));++ await api.addNewColumn("Done");++ expect(saved.at(-1)?.columns?.map(col => col.value)).toEqual([ "To Do", "Done" ]);+ expect(Object.keys(saved.at(-1) ?? {})).not.toContain("statusViewColumns");+ });++ /**+ * The board reads for a grouping it is being switched to before the api is pointed at it, so a+ * sync answering for that read would put one grouping's columns into another's definition.+ */+ it("refuses a sync made for a grouping it is not on", async () => {+ const put = vi.spyOn(server, "put").mockResolvedValue(undefined);+ const { api } = createApi({}, [], buildBoard({}), "priority");++ await api.syncColumnsToDefinition([ "To Do", "Done" ], "status");+ expect(put).not.toHaveBeenCalled();++ await api.syncColumnsToDefinition([ "High", "Low" ], "priority");+ expect(put).toHaveBeenCalledTimes(1);+ expect(put.mock.calls[0][0]).toBe("notes/boardNote/set-attribute");+ expect(put.mock.calls[0][1]).toMatchObject({+ name: "label:priority", value: "promoted,single,select,options=High;Low"+ });+ });+});+/** A board whose definition the sync must not touch, however it came to have one. */interface UntouchableBoard {owned?: Record<string, string>;diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.tsindex 83b0294d12..c0e9dea7ae 100644--- a/apps/client/src/widgets/collections/board/api.ts+++ b/apps/client/src/widgets/collections/board/api.ts@@ -27,6 +27,7 @@ import {type BoardStatusDefinition, canStoreColumnsInDefinition, DEFAULT_COLUMN_ICON,DEFAULT_GROUP_BY, INBOX_COLUMN, INBOX_COLUMN_ICON} from "./columns";+import { readColumns, writeColumns } from "./column_storage";import { ColumnMap } from "./data";import { SORT_DESCENDING_LABEL, SORT_LABEL } from "./sort";@@ -107,6 +108,11 @@ export default class BoardApi {/** The branch last sent to the end of each column, by {@link moveToColumnEnd}. */private sentToColumnEnd = new Map<string, string>();statusAttribute: string;+ /**+ * What the board groups by, with the `#`/`~` prefix it is written with. Every column read and+ * write is keyed by it, so one grouping's columns can never be stored under another's.+ */+ groupBy: string;/** The config as the board last handed it over, against which a fresh one is recognised. */private viewConfigSource: BoardViewData | undefined;@@ -133,6 +139,7 @@ export default class BoardApi {) {this.viewConfigSource = viewConfig;this.viewConfig = viewConfig ?? {};+ this.groupBy = statusAttribute;this.isRelationMode = statusAttribute.startsWith("~");if (statusAttribute.startsWith("~") || statusAttribute.startsWith("#")) {@@ -180,6 +187,7 @@ export default class BoardApi {this.saveConfig = saveConfig;this.setBranchIdToEdit = setBranchIdToEdit;this.statusDefinition = statusDefinition;+ this.groupBy = statusAttribute;this.isRelationMode = statusAttribute.startsWith("~");this.statusAttribute = statusAttribute.replace(/^[~#]/, "");}@@ -379,7 +387,7 @@ export default class BoardApi {return;}- const columns = this.viewConfig?.columns ?? [];+ const columns = this.storedColumns;// Add the new column to persisted data if it doesn't existif (columns.some(col => col.value === columnName)) return false;@@ -420,7 +428,7 @@ export default class BoardApi {* where it is already taken, so adding several in a row cannot silently do nothing.*/async insertColumn(relativeTo: string, direction: "before" | "after") {- const stored = this.viewConfig?.columns ?? [];+ const stored = this.storedColumns;const taken = new Set([ ...this.columns, ...stored.map(col => col.value) ]);const stockName = t("board_view.new-column");@@ -484,7 +492,7 @@ export default class BoardApi {await this.retiredWhile(column, undefined,() => executeBulkActions(noteIds, [ action ], { silent: true }));- this.storeColumns((this.viewConfig?.columns ?? []).filter(col => col.value !== column));+ this.storeColumns(this.storedColumns.filter(col => col.value !== column));}async renameColumn(oldValue: string, newValue: string) {@@ -531,7 +539,7 @@ export default class BoardApi {* inbox has no value, so it uses a name stored in the config.*/getColumnTitle(column: string) {- const named = this.viewConfig?.columns?.find(col => col.value === column)?.displayName;+ const named = this.storedColumns.find(col => col.value === column)?.displayName;return named || (column === INBOX_COLUMN ? t("board_view.inbox") : column);}@@ -563,7 +571,7 @@ export default class BoardApi {return froca.getNoteFromCache(column)?.getIcon();}- const stored = this.viewConfig?.columns?.find(col => col.value === column)?.icon;+ const stored = this.storedColumns.find(col => col.value === column)?.icon;if (stored) {return stored;}@@ -576,7 +584,7 @@ export default class BoardApi {* while it carries none. The colour is stored per column in both modes, unlike the icon.*/getColumnColorClass(column: string) {- const color = this.viewConfig?.columns?.find(col => col.value === column)?.color;+ const color = this.storedColumns.find(col => col.value === column)?.color;return cssClassManager.createClassForColor(color ?? null);}@@ -611,7 +619,7 @@ export default class BoardApi {/** The note limit set for a column, absent if disabled. */getColumnLimit(column: string) {- return this.viewConfig?.columns?.find(col => col.value === column)?.limit;+ return this.storedColumns.find(col => col.value === column)?.limit;}/** Sets a column's note limit. Pass `undefined` to disable it. */@@ -627,7 +635,7 @@ export default class BoardApi {* {@link DEFAULT_SORT} against the board's own order.*/getColumnSort(column: string) {- const stored = this.viewConfig?.columns?.find(col => col.value === column);+ const stored = this.storedColumns.find(col => col.value === column);return {orderBy: parseStoredSortKey(stored?.orderBy),isDescending: !!stored?.descendingOrder@@ -696,7 +704,7 @@ export default class BoardApi {* as it stood before the first.*/async resetColumnSortsToDefault() {- const stored = this.viewConfig?.columns ?? [];+ const stored = this.storedColumns;this.updateColumns(stored.map(({ value }) => value), { orderBy: undefined, descendingOrder: false });}@@ -708,7 +716,7 @@ export default class BoardApi {/** Whether a column is archived, which the board shows only while archived notes are shown. */isColumnArchived(column: string) {- return !!this.viewConfig?.columns?.find(col => col.value === column)?.archived;+ return !!this.storedColumns.find(col => col.value === column)?.archived;}/**@@ -805,7 +813,7 @@ export default class BoardApi {/** Whether a column is stored as collapsed, which draws it as a strip without its cards. */isColumnCollapsed(column: string) {- return !!this.viewConfig?.columns?.find(col => col.value === column)?.collapsed;+ return !!this.storedColumns.find(col => col.value === column)?.collapsed;}/** Collapses a column to a strip, or opens it again. */@@ -820,7 +828,7 @@ export default class BoardApi {* carry is drawn without ever having been stored, so this is also where it gets an entry.*/async setAllColumnsCollapsed(collapsed: boolean) {- const stored = new Map((this.viewConfig?.columns ?? []).map(col => [ col.value, col ]));+ const stored = new Map(this.storedColumns.map(col => [ col.value, col ]));const order = [ ...stored.keys() ];for (const derived of this.columns) {if (!stored.has(derived)) {@@ -843,7 +851,7 @@ export default class BoardApi {/** Whether a column collapses again once it has been opened. */isColumnKeptCollapsed(column: string) {- return !!this.viewConfig?.columns?.find(col => col.value === column)?.keepCollapsed;+ return !!this.storedColumns.find(col => col.value === column)?.keepCollapsed;}/**@@ -873,12 +881,12 @@ 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>) {- this.storeColumns(this.withColumn(this.viewConfig?.columns ?? [], column, patch));+ this.storeColumns(this.withColumn(this.storedColumns, 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 ?? [];+ let next = this.storedColumns;for (const column of columns) {next = this.withColumn(next, column, patch);}@@ -943,12 +951,12 @@ export default class BoardApi {// `columns` is render state: it omits entries the view has yet to catch up with, and any// the board is hiding, such as a disabled inbox. Those are neither dropped nor appended at// the end.- const stored = this.viewConfig?.columns ?? [];- const storedColumns = new Map(stored.map(col => [ col.value, col ]));+ const stored = this.storedColumns;+ const byValue = new Map(stored.map(col => [ col.value, col ]));// Reordering only moves entries, so each keeps its stored icon instead of being rebuilt// from its name.const reordered: BoardColumnData[] =- newColumns.map(value => storedColumns.get(value) ?? { value });+ newColumns.map(value => byValue.get(value) ?? { value });// A hidden column goes back after the column it followed in the config, not at the index it// held there: the move has shifted the visible columns, so that index points elsewhere now.@@ -1073,13 +1081,18 @@ export default class BoardApi {this.saveConfig(this.viewConfig);}+ /** The columns stored for the grouping the board is on, empty where it has none yet. */+ private get storedColumns() {+ return readColumns(this.viewConfig, this.groupBy) ?? [];+ }+private storeColumns(columns: BoardColumnData[]) {- this.viewConfig = { ...this.viewConfig, columns };+ this.viewConfig = writeColumns(this.viewConfig, this.groupBy, columns);this.saveConfig(this.viewConfig);// Not awaited — every caller is the tail of a user gesture the board has already rendered —// so the failure is caught here rather than left to reject unhandled. The columns are still// in the view config, so the board is not wrong, only out of step with the definition.- this.syncColumnsToDefinition(columns.map(({ value }) => value))+ this.syncColumnsToDefinition(columns.map(({ value }) => value), this.groupBy).catch((e) => {console.error("Failed to store the board columns in the attribute definition:", e);toast.showError(t("board_view.column-definition-save-error"));@@ -1098,8 +1111,17 @@ export default class BoardApi {** Writing only on a real difference is what makes that safe to call every time: the write lands as* an entity change, which re-renders the board, which would write again.+ *+ * @param forGroupBy the grouping the columns were resolved for, with its prefix. The write is+ * dropped when the board has moved to another grouping since.*/- async syncColumnsToDefinition(columns: string[]) {+ async syncColumnsToDefinition(columns: string[], forGroupBy: string) {+ // The caller resolved these columns for one grouping, and the board can have moved to+ // another since. Writing them would put one grouping's columns into another's definition.+ if (forGroupBy !== this.groupBy) {+ return;+ }+if (this.isRelationMode || !canStoreColumnsInDefinition(this.statusDefinition)) {return;}diff --git a/apps/client/src/widgets/collections/board/column_storage.spec.ts b/apps/client/src/widgets/collections/board/column_storage.spec.tsnew file mode 100644index 0000000000..71bd88b429--- /dev/null+++ b/apps/client/src/widgets/collections/board/column_storage.spec.ts@@ -0,0 +1,97 @@+import { describe, expect, it } from "vitest";++import type { BoardViewData } from ".";+import { adoptLegacyColumns, readColumns, writeColumns } from "./column_storage";++const CONFIG: BoardViewData = {+ columns: [ { value: "To Do" }, { value: "Done", icon: "bx bx-check" } ],+ priorityViewColumns: [ { value: "High", color: "#f00" } ],+ templates: [ "type:text:text/html" ]+};++describe("readColumns", () => {+ it("reads the default grouping however it is written", () => {+ for (const groupBy of [ "status", "#status", " status " ]) {+ expect(readColumns(CONFIG, groupBy), groupBy).toBe(CONFIG.columns);+ }+ });++ it("reads every other grouping from its own key", () => {+ expect(readColumns(CONFIG, "priority")).toEqual([ { value: "High", color: "#f00" } ]);+ expect(readColumns(CONFIG, "#priority")).toEqual([ { value: "High", color: "#f00" } ]);+ });++ it("has nothing for a grouping the board has not been on, and none for no config", () => {+ expect(readColumns(CONFIG, "severity")).toBeUndefined();+ expect(readColumns(CONFIG, "~assignee")).toBeUndefined();+ expect(readColumns(undefined, "status")).toBeUndefined();+ });+});++describe("writeColumns", () => {+ it("stores one grouping without touching another's columns or the rest of the config", () => {+ const written = writeColumns(CONFIG, "priority", [ { value: "Low" } ]);++ expect(written.priorityViewColumns).toEqual([ { value: "Low" } ]);+ expect(written.columns).toBe(CONFIG.columns);+ expect(written.templates).toBe(CONFIG.templates);+ // The config the board holds is replaced rather than edited, so a render can tell+ // them apart.+ expect(CONFIG.priorityViewColumns).toEqual([ { value: "High", color: "#f00" } ]);+ });++ it("stores the default grouping under the key every board already uses", () => {+ const written = writeColumns(CONFIG, "status", [ { value: "Blocked" } ]);++ expect(written.columns).toEqual([ { value: "Blocked" } ]);+ expect(written.priorityViewColumns).toBe(CONFIG.priorityViewColumns);+ });++ it("keeps a relation apart from the label of the same name", () => {+ const written = writeColumns({}, "~priority", [ { value: "someNoteId" } ]);++ expect(written["~priorityViewColumns"]).toEqual([ { value: "someNoteId" } ]);+ expect(written.priorityViewColumns).toBeUndefined();+ });+});++describe("adoptLegacyColumns", () => {+ /** What a board grouping by something other than the default stored before this key existed. */+ const legacy: BoardViewData = {+ columns: [ { value: "High", icon: "bx bx-up-arrow" } ],+ filterQuery: "#urgent"+ };++ it("moves a pre-switching list under the grouping it belongs to and clears the old key", () => {+ const adopted = adoptLegacyColumns(legacy, "priority");++ expect(adopted).toEqual({+ priorityViewColumns: [ { value: "High", icon: "bx bx-up-arrow" } ],+ filterQuery: "#urgent"+ });+ // Left in place it would be read as the default grouping's columns the moment the board is+ // switched to it.+ expect(adopted).not.toHaveProperty("columns");+ });++ it("leaves the default grouping alone, which already owns that key", () => {+ expect(adoptLegacyColumns(legacy, "status")).toBeUndefined();+ expect(adoptLegacyColumns(legacy, "#status")).toBeUndefined();+ });++ it("leaves a board that has switched before alone, whose `columns` is the default's", () => {+ expect(adoptLegacyColumns(CONFIG, "severity")).toBeUndefined();+ });++ it("has nothing to move for a board with no stored columns", () => {+ expect(adoptLegacyColumns({ columns: [] }, "priority")).toBeUndefined();+ expect(adoptLegacyColumns({}, "priority")).toBeUndefined();+ expect(adoptLegacyColumns(undefined, "priority")).toBeUndefined();+ });++ it("carries a relation's list under a key of its own", () => {+ expect(adoptLegacyColumns(legacy, "~assignee")).toMatchObject({+ "~assigneeViewColumns": [ { value: "High", icon: "bx bx-up-arrow" } ]+ });+ });+});diff --git a/apps/client/src/widgets/collections/board/column_storage.ts b/apps/client/src/widgets/collections/board/column_storage.tsnew file mode 100644index 0000000000..9c6101e10f--- /dev/null+++ b/apps/client/src/widgets/collections/board/column_storage.ts@@ -0,0 +1,45 @@+import { boardColumnsKey, isBoardColumnsKey } from "@triliumnext/commons";++import type { BoardColumnData, BoardViewData } from ".";++/** The columns stored for one grouping, or nothing where the board has none for it yet. */+export function readColumns(+ config: BoardViewData | undefined,+ groupBy: string+): BoardColumnData[] | undefined {+ return config?.[boardColumnsKey(groupBy)];+}++/** Stores the columns of one grouping, leaving every other grouping's list as it stands. */+export function writeColumns(+ config: BoardViewData | undefined,+ groupBy: string,+ columns: BoardColumnData[]+): BoardViewData {+ return { ...config, [boardColumnsKey(groupBy)]: columns };+}++/**+ * The config with a pre-switching `columns` list moved under the grouping it belongs to, or nothing+ * where there is none to move.+ *+ * Before the grouping could be switched every board wrote its columns to `columns`, whichever+ * attribute it grouped by. That list is the current grouping's, so it is moved there and `columns`+ * is cleared: left in place, it would be read as the default grouping's columns the moment the+ * board is switched to it. A board carrying any keyed list has been switched already, and its+ * `columns` means the default grouping alone.+ */+export function adoptLegacyColumns(+ config: BoardViewData | undefined,+ groupBy: string+): BoardViewData | undefined {+ const key = boardColumnsKey(groupBy);+ if (key === "columns" || !config?.columns?.length+ || Object.keys(config).some(isBoardColumnsKey)) {+ return undefined;+ }++ const adopted: BoardViewData = { ...config, [key]: config.columns };+ delete adopted.columns;+ return adopted;+}diff --git a/apps/client/src/widgets/collections/board/columns.ts b/apps/client/src/widgets/collections/board/columns.tsindex f42b744fb7..04032f0413 100644--- a/apps/client/src/widgets/collections/board/columns.ts+++ b/apps/client/src/widgets/collections/board/columns.ts@@ -1,4 +1,4 @@-import { type DefinitionObject } from "@triliumnext/commons";+import { DEFAULT_BOARD_GROUP_BY, type DefinitionObject } from "@triliumnext/commons";import type FAttribute from "../../../entities/fattribute";import type FNote from "../../../entities/fnote";@@ -12,7 +12,7 @@ import type FNote from "../../../entities/fnote";export const BOARD_TEMPLATE_ID = "_template_board";/** The label a board groups by when `#board:groupBy` does not name one. */-export const DEFAULT_GROUP_BY = "status";+export const DEFAULT_GROUP_BY = DEFAULT_BOARD_GROUP_BY;/** The icon a column shows until one is picked for it. */export const DEFAULT_COLUMN_ICON = "bx bx-circle";diff --git a/apps/client/src/widgets/collections/board/data.spec.ts b/apps/client/src/widgets/collections/board/data.spec.tsindex a5795157d7..ca4b9176bd 100644--- a/apps/client/src/widgets/collections/board/data.spec.ts+++ b/apps/client/src/widgets/collections/board/data.spec.ts@@ -654,6 +654,64 @@ function titles(map: ColumnMap, column: string) {return (map.get(column) ?? []).map(({ note }) => note.title);}+describe("getBoardData column storage", () => {+ /** A board whose cards carry both a `status` and a `priority`. */+ function twoGroupings() {+ return buildNote({+ title: "Board",+ "#collection": "",+ "#viewType": "board",+ children: [+ { title: "First", "#status": "To Do", "#priority": "High", "#severity": "Minor" },+ { title: "Second", "#status": "Done", "#priority": "Low", "#severity": "Major" }+ ]+ });+ }++ const config = {+ columns: [ { value: "Done" }, { value: "To Do" } ],+ priorityViewColumns: [ { value: "Low", icon: "bx bx-down-arrow" }, { value: "High" } ]+ };++ it("takes the order and the icons of the grouping it is reading", async () => {+ const board = twoGroupings();++ const byStatus = await getBoardData(board, "status", config, false);+ const byPriority = await getBoardData(board, "priority", config, false);++ expect(byStatus.columns).toEqual([ "Done", "To Do" ]);+ expect(byPriority.columns).toEqual([ "Low", "High" ]);+ });++ it("writes a resolved list under its key, keeping the other grouping's", async () => {+ const board = twoGroupings();++ // Nothing is stored for `severity`, so the values the cards carry make the columns.+ const { newPersistedData } = await getBoardData(+ board, "severity", config, false);++ expect(newPersistedData?.severityViewColumns)+ .toEqual([ { value: "Minor" }, { value: "Major" } ]);+ expect(newPersistedData?.columns).toEqual(config.columns);+ expect(newPersistedData?.priorityViewColumns).toEqual(config.priorityViewColumns);+ });++ it("keeps a column's icon across a rewrite of its own grouping", async () => {+ const board = twoGroupings();++ const { newPersistedData } = await getBoardData(+ board,+ "priority",+ { ...config, priorityViewColumns: [ { value: "Low", icon: "bx bx-down-arrow" } ] },+ false,+ [ "Low", "High" ]);++ expect(newPersistedData?.priorityViewColumns).toEqual([+ { value: "Low", icon: "bx bx-down-arrow" }, { value: "High" }+ ]);+ });+});+function noteIdsOf(map: ColumnMap, column: string) {return (map.get(column) ?? []).map(({ note }) => note.noteId);}diff --git a/apps/client/src/widgets/collections/board/data.ts b/apps/client/src/widgets/collections/board/data.tsindex bb9bb87d77..410808b931 100644--- a/apps/client/src/widgets/collections/board/data.ts+++ b/apps/client/src/widgets/collections/board/data.ts@@ -6,6 +6,7 @@ import {DEFAULT_SORT, parseStoredSortKey, sortedAttributeName, sortItems, type SortContext,type SortKey} from "../sorting";+import { readColumns, writeColumns } from "./column_storage";import { INBOX_COLUMN, resolveBoardColumns } from "./columns";import { BoardColumnData, BoardViewData } from "./index";@@ -237,7 +238,8 @@ export async function getBoardData(inboxEnabled = false) {const byColumn: ColumnMap = new Map();- const storedColumnValues = (persistedData.columns ?? []).map(c => c.value);+ const storedColumns = readColumns(persistedData, groupByColumn) ?? [];+ const storedColumnValues = storedColumns.map(c => c.value);// Turning the inbox on adds it to the board, at the front. After that the entry belongs to// the config: it keeps its icon, colour and position, and turning the inbox off leaves it in// place.@@ -248,7 +250,7 @@ export async function getBoardData(// Only a board with an inbox has somewhere to put an unassigned note; on any other board such// a note is not shown at all, as before.const inbox = inboxEnabled- ? { nested: !!persistedData.columns?.find(col => col.value === INBOX_COLUMN)?.nested }+ ? { nested: !!storedColumns.find(col => col.value === INBOX_COLUMN)?.nested }: undefined;// First, scan all notes to find what columns actually exist@@ -282,17 +284,15 @@ export async function getBoardData(// or every refresh would save.const hasChanges = storedColumnValues.length !== columns.length|| storedColumnValues.some((value, index) => columns[index] !== value);- const storedColumns = indexColumnsByResolvedName(persistedData, pendingRenames);+ const byResolvedName = indexColumnsByResolvedName(storedColumns, pendingRenames);return {byColumn,columns,settledRenames,newPersistedData: hasChanges- ? {- ...persistedData,- columns: columns.map(value => storedColumns.get(value) ?? { value })- }+ ? writeColumns(persistedData, groupByColumn,+ columns.map(value => byResolvedName.get(value) ?? { value })): undefined,isInRelationMode: groupByColumn.startsWith("~")};@@ -306,12 +306,12 @@ export async function getBoardData(* to the new name, the same substitution {@link resolveBoardColumns} makes.*/function indexColumnsByResolvedName(- persistedData: BoardViewData,+ storedColumns: BoardColumnData[],pendingRenames: ReadonlyMap<string, string | undefined>) {const byName = new Map<string, BoardColumnData>();- for (const column of persistedData.columns ?? []) {+ for (const column of storedColumns) {const { value } = column;const name = pendingRenames.has(value) ? pendingRenames.get(value) : value;if (name !== undefined) {diff --git a/apps/client/src/widgets/collections/board/group_by.spec.ts b/apps/client/src/widgets/collections/board/group_by.spec.tsnew file mode 100644index 0000000000..c396e6f71e--- /dev/null+++ b/apps/client/src/widgets/collections/board/group_by.spec.ts@@ -0,0 +1,83 @@+import $ from "jquery";+import { beforeEach, describe, expect, it, vi } from "vitest";++import noteAttributeCache from "../../../services/note_attribute_cache";+import { buildNote } from "../../../test/easy-froca";+import { groupingOptions } from "./group_by";++// i18next is never initialised under test, so a translated title would come back undefined. What is+// interpolated is carried along, for the titles these tests are about.+vi.mock("../../../services/i18n", () => ({+ t: (key: string, opts?: Record<string, unknown>) =>+ opts ? `${key}:${JSON.stringify(opts)}` : key,+ translationsInitializedPromise: $.Deferred().resolve()+}));++/** A board defining two selects, a text label and a relation, all promoted to its cards. */+function buildBoard(extra: Record<string, string> = {}) {+ delete noteAttributeCache.attributes["boardNote"];++ return buildNote({+ id: "boardNote",+ title: "Board",+ "#viewType": "board",+ "#label:status(inheritable)": "promoted,alias=Status,single,select,options=To Do;Done",+ "#label:priority(inheritable)": "promoted,alias=Priority,single,select,options=High;Low",+ "#label:notes(inheritable)": "promoted,single,text",+ "#relation:assignee(inheritable)": "promoted,single",+ ...extra+ });+}++describe("groupingOptions", () => {+ let board: ReturnType<typeof buildNote>;++ beforeEach(() => {+ board = buildBoard();+ });++ it("offers the select fields and nothing else", () => {+ expect(groupingOptions(board, undefined, "status")).toEqual([+ { value: "status", title: "Status" },+ { value: "priority", title: "Priority" }+ ]);+ });++ it("offers them in the order the reader arranged the promoted attributes", () => {+ const settings = [ { name: "priority" }, { name: "status" } ];++ expect(groupingOptions(board, settings, "status").map(option => option.value))+ .toEqual([ "priority", "status" ]);+ });++ it("names the grouping in force even where no select defines it", () => {+ // A relation cannot be switched to from here, but a board on one still has to say so.+ expect(groupingOptions(board, undefined, "~assignee")[0]).toEqual({+ value: "~assignee",+ title: 'promoted_attributes.relation_name:{"name":"assignee"}'+ });++ // A label nobody defined, which reads as the name the board groups by.+ expect(groupingOptions(board, undefined, "severity")[0])+ .toEqual({ value: "severity", title: "severity" });+ });++ it("lists the grouping in force once, whichever way it is written", () => {+ const values = groupingOptions(board, undefined, "#priority").map(option => option.value);++ expect(values).toEqual([ "status", "priority" ]);+ });++ it("falls back to the default grouping for a board naming none", () => {+ expect(groupingOptions(board, undefined, "").map(option => option.value))+ .toEqual([ "status", "priority" ]);+ });++ it("offers nothing but the grouping in force on a board defining no selects", () => {+ delete noteAttributeCache.attributes["plainBoard"];+ const plain = buildNote({ id: "plainBoard", title: "Board", "#viewType": "board" });++ expect(groupingOptions(plain, undefined, "status"))+ .toEqual([ { value: "status", title: "status" } ]);+ });+});diff --git a/apps/client/src/widgets/collections/board/group_by.tsx b/apps/client/src/widgets/collections/board/group_by.tsxnew file mode 100644index 0000000000..df29e2194a--- /dev/null+++ b/apps/client/src/widgets/collections/board/group_by.tsx@@ -0,0 +1,75 @@+import { DEFAULT_BOARD_GROUP_BY, normalizeBoardGroupBy } from "@triliumnext/commons";++import type FNote from "../../../entities/fnote";+import { t } from "../../../services/i18n";+import Dropdown from "../../react/Dropdown";+import { FormListItem } from "../../react/FormList";+import Icon from "../../react/Icon";+import { type PromotedAttributeSetting, resolvePromotedAttributes } from "../promoted_attributes";++/** One attribute the board offers to group its cards by. */+export interface GroupingOption {+ /** What `#board:groupBy` carries for it, with the `~` of a relation. */+ value: string;+ /** What the reader sees: the definition's alias, or the attribute's own name. */+ title: string;+}++/** Switches which attribute the board's columns are made from. */+export default function BoardGroupBy({ options, current, onSelect }: {+ options: GroupingOption[];+ /** The grouping in force, as {@link groupingOptions} spells its value. */+ current: string;+ onSelect: (groupBy: string) => void;+}) {+ const selected = options.find(option => option.value === current);++ return (+ <Dropdown+ className="board-group-by"+ noDropdownListStyle+ title={t("board_view.group-by")}+ text={<>+ <Icon icon="bx bx-category-alt" /> + {selected?.title ?? current}+ </>}+ >+ {options.map(option => (+ <FormListItem+ key={option.value}+ onClick={() => onSelect(option.value)}+ selected={option.value === current}+ disabled={option.value === current}+ >{option.title}</FormListItem>+ ))}+ </Dropdown>+ );+}++/**+ * The attributes the board offers to group by: the select fields it defines, and the grouping in+ * force whatever defines it.+ *+ * Only a select says what its columns are, so nothing else can be grouped by from here. The current+ * grouping is listed all the same — a board grouping by a relation, or by a label nobody defined,+ * still has to name what it is grouping by.+ */+export function groupingOptions(+ note: FNote | null | undefined,+ settings: PromotedAttributeSetting[] | undefined,+ groupBy: string+): GroupingOption[] {+ const current = normalizeBoardGroupBy(groupBy) || DEFAULT_BOARD_GROUP_BY;+ const defined = resolvePromotedAttributes(note, settings);+ const options = defined+ .filter(attribute => attribute.type === "label" && attribute.labelType === "select")+ .map(attribute => ({ value: attribute.name, title: attribute.title }));++ if (!options.some(option => option.value === current)) {+ const attribute = defined.find(+ ({ type, name }) => (type === "relation" ? `~${name}` : name) === current);+ options.unshift({ value: current, title: attribute?.title ?? current.replace(/^~/, "") });+ }++ return options;+}diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsxindex 8747d5e1df..8f308bc8a5 100644--- a/apps/client/src/widgets/collections/board/index.spec.tsx+++ b/apps/client/src/widgets/collections/board/index.spec.tsx@@ -20,6 +20,7 @@ import froca from "../../../services/froca";import attributes from "../../../services/attributes";import { executeBulkActions } from "../../../services/bulk_action";import LoadResults from "../../../services/load_results";+import noteAttributeCache from "../../../services/note_attribute_cache";import searchService from "../../../services/search";import { buildNote } from "../../../test/easy-froca";import { ParentComponent } from "../../react/react_utils";@@ -3781,3 +3782,192 @@ describe("a column that sorts its cards", () => {return { board: mountPoint, host, cards: byTitle };}});++describe("Switchable board grouping", () => {+ let container: HTMLElement | undefined;++ afterEach(() => {+ saved.length = 0;+ if (container) {+ render(null, container);+ container.remove();+ container = undefined;+ }+ });++ /** Columns stored for the default grouping and for `priority`, each with its own icons. */+ const CONFIG: BoardViewData = {+ columns: [ { value: "To Do" }, { value: "Done", icon: "bx bx-check" } ],+ priorityViewColumns: [ { value: "High", icon: "bx bx-up-arrow" }, { value: "Low" } ]+ };++ async function setup(config: BoardViewData = CONFIG) {+ // `buildNote` appends to whatever the cache already holds for the id, so the previous+ // test's definitions, and the grouping it switched to, would still be on the note.+ delete noteAttributeCache.attributes["switchBoard"];++ const note = buildNote({+ id: "switchBoard",+ title: "Board",+ // The header the dropdown stands in is drawn for a collection note alone.+ type: "book",+ "#collection": "",+ "#viewType": "board",+ "#board:groupBy": "status",+ "#label:status(inheritable)": "promoted,alias=Status,single,select,options=To Do;Done",+ "#label:priority(inheritable)": "promoted,alias=Priority,single,select,options=High;Low",+ children: [+ { title: "First", "#status": "To Do", "#priority": "High" },+ { title: "Second", "#status": "Done", "#priority": "Low" }+ ]+ });++ const mountPoint = document.createElement("div");+ container = mountPoint;+ document.body.appendChild(mountPoint);++ const host = new Component();+ await act(async () => {+ render(+ <ParentComponent.Provider value={host}>+ <Harness+ note={note}+ noteIds={[ ...note.getChildNoteIds() ]}+ initialConfig={config}+ />+ </ParentComponent.Provider>,+ mountPoint+ );+ });+ await act(async () => { await flush(); });+ await act(async () => { await flush(); });++ return { note, container: mountPoint, host };+ }++ /** Writes `#board:groupBy`, the way the dropdown does, and lets the board catch up. */+ async function groupBy(note: ReturnType<typeof buildNote>, host: Component, value: string) {+ const attribute = note.getAttributes().find(attr => attr.name === "board:groupBy");+ if (!attribute) throw new Error("expected the board to carry #board:groupBy");+ attribute.value = value;++ const results = new LoadResults([ {+ entityName: "attributes",+ entityId: "groupByAttr",+ entity: {+ attributeId: "groupByAttr",+ noteId: "switchBoard",+ type: "label",+ name: "board:groupBy",+ value+ }+ } as never ]);+ results.addAttribute("groupByAttr", "other");+++ await act(async () => {+ await host.handleEvent("entitiesReloaded", { loadResults: results });+ await flush();+ });+ // The switch is committed on one pass and stored on the next.+ await act(async () => { await flush(); });+ await act(async () => { await flush(); });+ }++ function cardTitles(board: HTMLElement, column: number) {+ const columns = [ ...board.querySelectorAll(".board-column") ];+ return [ ...columns[column].querySelectorAll(".board-note .title") ]+ .map(title => title.textContent);+ }++ it("names the grouping in force and re-groups the cards when it changes", async () => {+ const { note, container, host } = await setup();++ expect(container.querySelector(".board-group-by button")?.textContent).toContain("Status");+ expect(columnTitles(container)).toEqual([ "To Do", "Done" ]);++ await groupBy(note, host, "priority");++ expect(container.querySelector(".board-group-by button")?.textContent)+ .toContain("Priority");+ expect(columnTitles(container)).toEqual([ "High", "Low" ]);+ // Drawn from the new grouping's own entries, not from the ones it replaced.+ expect(columnIcons(container)).toEqual([ "bx bx-up-arrow", DEFAULT_COLUMN_ICON ]);+ expect(cardTitles(container, 0)).toEqual([ "First" ]);+ });++ /**+ * The board reads the new grouping before it is pointed at it. A write made from that read+ * would put the columns it is leaving under the key of the one it is arriving at.+ */+ it("stores the new grouping's columns under its own key and nowhere else", async () => {+ // Nothing stored for `priority`, so the switch is what gives it a column list.+ const { note, host } = await setup({ columns: CONFIG.columns });+ saved.length = 0;++ await groupBy(note, host, "priority");++ expect(saved.length).toBeGreaterThan(0);+ for (const config of saved) {+ expect(config.priorityViewColumns?.map(col => col.value)).toEqual([ "High", "Low" ]);+ expect(config.columns).toEqual(CONFIG.columns);+ }+ });++ it("leaves the grouping it left exactly as it was", async () => {+ const { note, container, host } = await setup();++ await groupBy(note, host, "priority");+ await groupBy(note, host, "status");++ expect(columnTitles(container)).toEqual([ "To Do", "Done" ]);+ expect(columnIcons(container)).toEqual([ DEFAULT_COLUMN_ICON, "bx bx-check" ]);+ expect(saved.at(-1)?.columns ?? CONFIG.columns).toEqual(CONFIG.columns);+ });++ /**+ * Before the grouping could be switched, every board stored its columns under `columns`. Read+ * as the default grouping's, they would follow the board onto whatever it is switched to next.+ */+ it("moves a pre-switching column list under the grouping it belongs to", async () => {+ const note = buildNote({+ id: "legacyBoard",+ title: "Board",+ "#collection": "",+ "#viewType": "board",+ "#board:groupBy": "priority",+ children: [+ { title: "First", "#priority": "High" },+ { title: "Second", "#priority": "Low" }+ ]+ });++ const mountPoint = document.createElement("div");+ container = mountPoint;+ document.body.appendChild(mountPoint);++ await act(async () => {+ render(+ <ParentComponent.Provider value={new Component()}>+ <Harness+ note={note}+ noteIds={[ ...note.getChildNoteIds() ]}+ initialConfig={{+ columns: [+ { value: "Low", icon: "bx bx-down-arrow" }, { value: "High" }+ ]+ }}+ />+ </ParentComponent.Provider>,+ mountPoint+ );+ });+ await act(async () => { await flush(); });+ await act(async () => { await flush(); });++ expect(saved.at(-1)?.priorityViewColumns?.map(col => col.value)).toEqual([ "Low", "High" ]);+ expect(saved.at(-1)).not.toHaveProperty("columns");+ expect(columnTitles(mountPoint)).toEqual([ "Low", "High" ]);+ expect(columnIcons(mountPoint)).toEqual([ "bx bx-down-arrow", DEFAULT_COLUMN_ICON ]);+ });+});diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsxindex e36c0b7fc5..553154b6aa 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -9,9 +9,10 @@ import {Dispatch, StateUpdater, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState} from "preact/hooks";-import type { HighlightedTokenInfo } from "@triliumnext/commons";+import { type HighlightedTokenInfo, normalizeBoardGroupBy } from "@triliumnext/commons";import FNote from "../../../entities/fnote";+import attributes from "../../../services/attributes";import froca from "../../../services/froca";import { t } from "../../../services/i18n";import { getCreationDate, loadCreationDates } from "../../../services/note_dates";@@ -47,10 +48,12 @@ import { columnGapStandsAside, columnStandsAside, movesColumn } from "./drag_geoimport { forgetCardHeights } from "./drag_measure";import { BoardDropStateContext, DropStateStore } from "./drop_state";import BoardApi from "./api";+import { adoptLegacyColumns, readColumns } from "./column_storage";import { DEFAULT_COLUMN_ICON, DEFAULT_GROUP_BY, getStatusDefinition, INBOX_COLUMN } from "./columns";import Column, { EXPAND_MS, placeCard, settleCards } from "./column";import { currentCardTemplate, DEFAULT_CARD_TEMPLATES } from "./card_templates";import ColumnLimitDialog from "./column_limit";+import BoardGroupBy, { groupingOptions } from "./group_by";import BoardProperties from "./properties";import { openBoardContextMenu, openCreateColumnMenu } from "./context_menu";import { useBoardSort } from "./sort";@@ -72,7 +75,13 @@ export interface HoldOpen {}export interface BoardViewData {+ /**+ * The columns of the default grouping. Every other grouping keeps its own list under+ * `<attribute>ViewColumns`, so switching the grouping cannot mix two of them.+ */columns?: BoardColumnData[];+ /** @see BoardViewData.columns */+ [key: `${string}ViewColumns`]: BoardColumnData[] | undefined;/*** What a new card can be made from, as {@link NoteTypeOption} ids. Absent until the reader picks* for the board, which is what `DEFAULT_CARD_TEMPLATES` stands in for.@@ -286,9 +295,33 @@ const BOARD_HINTS: ShortcutHintDefinition = [}];-export default function BoardView({ note: parentNote, noteIds, viewConfig, saveConfig }: ViewModeProps<BoardViewData>) {+export default function BoardView({+ note: parentNote, noteIds, viewConfig: storedConfig, saveConfig+}: ViewModeProps<BoardViewData>) {const { noteContext } = useNoteContext();- const [ statusAttributeWithPrefix ] = useNoteLabelWithDefault(parentNote, "board:groupBy", DEFAULT_GROUP_BY);+ const [ requestedGroupBy, setRequestedGroupBy ] =+ useNoteLabelWithDefault(parentNote, "board:groupBy", DEFAULT_GROUP_BY);+ /**+ * The grouping the board draws and writes for.+ *+ * It follows `#board:groupBy` only once the columns of the grouping it names are resolved, so+ * no write can put one grouping's columns under another's key. A different board takes its+ * label at once: it has no previous grouping of its own to keep in step.+ */+ const [ committed, setCommitted ] = useState({ note: parentNote, groupBy: requestedGroupBy });+ const groupBy = committed.note === parentNote ? committed.groupBy : requestedGroupBy;+ // A board that has never had its grouping switched keeps its columns under `columns`. They+ // belong to the grouping it opened on, and are moved under that grouping's own key before+ // anything reads them. Read from the label the board opened with rather than from the grouping+ // in force: switching to another one must not carry the columns of the one being left.+ const openedOn = useRef({ note: parentNote, groupBy: requestedGroupBy });+ if (openedOn.current.note !== parentNote) {+ openedOn.current = { note: parentNote, groupBy: requestedGroupBy };+ }+ const openedOnGroupBy = openedOn.current.groupBy;+ const adoptedConfig = useMemo(+ () => adoptLegacyColumns(storedConfig, openedOnGroupBy), [ storedConfig, openedOnGroupBy ]);+ let viewConfig = adoptedConfig ?? storedConfig;const [ includeArchived ] = useNoteLabelBoolean(parentNote, "includeArchived");const [ inboxEnabled ] = useNoteLabelBoolean(parentNote, "enableInboxColumn");/** Every card the board holds, which an active filter narrows before the cards are drawn. */@@ -360,7 +393,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC// takes up that board's own, leaving a write still in flight to undo into the one it recorded// itself in. Done while rendering, so the `api` below is handed the map the refresh reads.useContextualShortcutHints(BOARD_HINTS);- const boardIdentity = `${parentNote.noteId}|${statusAttributeWithPrefix}`;+ const boardIdentity = `${parentNote.noteId}|${groupBy}`;if (pendingRenamesRef.current.board !== boardIdentity) {pendingRenamesRef.current = {board: boardIdentity,@@ -375,8 +408,8 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC() => (columns ?? []).filter(column => column !== INBOX_COLUMN || inboxEnabled),[ columns, inboxEnabled ]);const statusDefinition = useMemo(- () => getStatusDefinition(parentNote, statusAttributeWithPrefix),- [ parentNote, statusAttributeWithPrefix, definitionRevision ]);+ () => getStatusDefinition(parentNote, groupBy),+ [ parentNote, groupBy, definitionRevision ]);// One api for as long as the board is shown, pointed at each refresh's data rather than built// again: a new object would be a new prop on every card, and `memo` would then redraw all of// them for a move that touched one. Another board takes a new one, since this instance is@@ -389,17 +422,23 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveConQueryChanged: persistFilterQuery,collectionNoteIds: noteIds});- const statusAttribute = statusAttributeWithPrefix.replace(/^[~#]/, "");+ const statusAttribute = groupBy.replace(/^[~#]/, "");// Every promoted attribute the board defines, hidden ones included: a column can sort by a// field its cards do not draw.const promotedAttributes = useMemo(() => resolvePromotedAttributes(parentNote, viewConfig?.promotedAttributes, [ statusAttribute ]),[ parentNote, viewConfig, statusAttribute, definitionRevision ]);+ // Keyed on the label rather than on the committed grouping, so the button names what the reader+ // just picked while the columns below are still being read.+ const groupingChoices = useMemo(+ () => groupingOptions(parentNote, viewConfig?.promotedAttributes, requestedGroupBy),+ [ parentNote, viewConfig, requestedGroupBy, definitionRevision ]);+ const currentGrouping = normalizeBoardGroupBy(requestedGroupBy) || DEFAULT_GROUP_BY;const defaultSort = useBoardSort(parentNote);const columnSorts = useMemo(- () => resolveColumnSorts(viewConfig?.columns, defaultSort, usableColumns),- [ viewConfig, defaultSort, usableColumns ]);+ () => resolveColumnSorts(readColumns(viewConfig, groupBy), defaultSort, usableColumns),+ [ viewConfig, groupBy, defaultSort, usableColumns ]);const sortContext = useMemo<SortContext>(() => ({definitions: new Map(promotedAttributes.map(attribute => [ attribute.name, attribute ])),creationDate: getCreationDate,@@ -426,13 +465,13 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCapiRef.current = {board: boardIdentity,api: new Api(- byColumn, usableColumns, parentNote, statusAttributeWithPrefix, viewConfig,+ byColumn, usableColumns, parentNote, groupBy, viewConfig,saveConfig, setBranchIdToEdit, pendingRenamesRef.current.writes, statusDefinition,allByColumn, filter.keepNote)};} else {apiRef.current.api.update(- byColumn, usableColumns, parentNote, statusAttributeWithPrefix, viewConfig,+ byColumn, usableColumns, parentNote, groupBy, viewConfig,saveConfig, setBranchIdToEdit, statusDefinition, allByColumn, filter.keepNote);}const api = apiRef.current.api;@@ -505,8 +544,9 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC// Read off the config rather than off `columns`, which the resolver hands back as names alone.const storedColumns = useMemo(- () => new Map((viewConfig?.columns ?? []).map(stored => [ stored.value, stored ])),- [ viewConfig ]);+ () => new Map((readColumns(viewConfig, groupBy) ?? []).map(+ stored => [ stored.value, stored ])),+ [ viewConfig, groupBy ]);// Filtered here rather than in the resolution, which is what gets written back: dropped there,// an archived column would be erased from the config and the definition instead of kept out of@@ -579,7 +619,16 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCdraggedColumn}), [ branchIdToEdit, columnNameToEdit, draggedCard, draggedColumn ]);- function refresh() {+ /**+ * Reads the board and draws it.+ *+ * @param target the grouping to read, which defaults to what `#board:groupBy` names. Where that+ * is one the board has not moved to yet, the refresh only reads: it hands the new+ * grouping's cards and columns over and commits the switch, and the refresh that+ * commit triggers is what stores anything, with the api on the grouping it stores+ * for.+ */+ function refresh(target = requestedGroupBy) {// A move under way has already been drawn where it will land. Held here rather than at each// caller, since a card crossing columns changes both the note and the board's children, and// either of those reaches this by a path of its own.@@ -602,10 +651,17 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC// board the user has left can arrive after the next board's. What it has to say is about// sources no longer on screen, the pending renames it reports as settled included.const refreshId = ++refreshSeqRef.current;+ const isSwitching = target !== groupBy;+ // Read for the grouping being drawn. The renames belong to the grouping the board is on,+ // and its columns are not the ones being resolved here.+ const definition = isSwitching ? getStatusDefinition(parentNote, target) : statusDefinition;+ const renames = isSwitching+ ? new Map<string, string | undefined>()+ : pendingRenamesRef.current.writes.renames;getBoardData(- parentNote, statusAttributeWithPrefix, viewConfig ?? {}, includeArchived,- statusDefinition?.options ?? [], pendingRenamesRef.current.writes.renames, inboxEnabled)+ parentNote, target, viewConfig ?? {}, includeArchived,+ definition?.options ?? [], renames, inboxEnabled).then(({byColumn: allCards, columns, newPersistedData, isInRelationMode, settledRenames}) => {@@ -613,14 +669,24 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCreturn;}- for (const settled of settledRenames) {- settleColumn(pendingRenamesRef.current.writes, settled);+ if (!isSwitching) {+ for (const settled of settledRenames) {+ settleColumn(pendingRenamesRef.current.writes, settled);+ }}setAllByColumn(allCards);setIsRelationMode(isInRelationMode);setColumns(columns);+ // The cards, the columns and the api that writes for them move to the new grouping+ // together. Nothing is stored from here: the api still writes for the grouping the+ // board is leaving.+ if (isSwitching) {+ setCommitted({ note: parentNote, groupBy: target });+ return;+ }+// A column a write is carrying has already been taken out of `columns`, and the// two writes below would put that answer on disk before the notes have given it.// Only while the write runs: its record can outlast it, and the board still has to@@ -634,7 +700,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC// is changing it: it resolves a name the change has already taken away from// whichever source it has not heard about yet, and writes it back as a column.// What this board itself changes is written where it is changed.- if (newPersistedData && !viewConfig?.columns?.length) {+ if (newPersistedData && !readColumns(viewConfig, groupBy)?.length) {viewConfig = { ...newPersistedData };saveConfig(newPersistedData);}@@ -657,7 +723,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCreturn;}- api.syncColumnsToDefinition(columns)+ api.syncColumnsToDefinition(columns, groupBy).catch((e) => console.error("Failed to sync the board columns to the attribute definition:", e));});}@@ -841,10 +907,20 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC// The board is not drawn afresh for another note, so the column opened on one would otherwise// still be open on the next, over whatever that board stores for a column of the same name.- useEffect(() => selectColumn(undefined), [ parentNote, selectColumn ]);+ // The same holds across a grouping, whose columns are a different set entirely.+ useEffect(() => selectColumn(undefined), [ parentNote, groupBy, selectColumn ]);++ // Stored once, and only for a board still carrying a pre-switching column list.+ useEffect(() => {+ if (adoptedConfig) {+ saveConfig(adoptedConfig);+ }+ }, [ adoptedConfig, saveConfig ]);+ // `groupBy` is a dependency as well as `requestedGroupBy`: committing a switch is what asks for+ // the refresh that stores the new grouping's columns.useEffect(refresh, [- parentNote, noteIds, viewConfig, statusAttributeWithPrefix, statusDefinition, inboxEnabled+ parentNote, noteIds, viewConfig, requestedGroupBy, groupBy, statusDefinition, inboxEnabled]);// The drag reports where the column landed among the ones on screen, which is not where it@@ -923,7 +999,10 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCuseTriliumEvent("entitiesReloaded", ({ loadResults }) => {// The column list is read off the definition, which may be edited from the attribute panel,// another split, or a synced instance. Re-reading it re-runs the refresh through the effect.- if (loadResults.getAttributeRows().some(attr => attr.name === `label:${api.statusAttribute}`)) {+ // Any definition the board carries, not only the grouping's: the others are what it offers+ // to group by instead.+ if (loadResults.getAttributeRows().some(attr =>+ attr.name?.startsWith("label:") && attributes.isAffecting(attr, parentNote))) {setDefinitionRevision(revision => revision + 1);}@@ -948,10 +1027,17 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC<div className="board-view"><CollectionPropertiesnote={parentNote}- rightChildren={<CollectionFilterInput- filter={filter}- placeholder={t("board_view.filter-placeholder")}- />}+ rightChildren={<>+ <BoardGroupBy+ options={groupingChoices}+ current={currentGrouping}+ onSelect={setRequestedGroupBy}+ />+ <CollectionFilterInput+ filter={filter}+ placeholder={t("board_view.filter-placeholder")}+ />+ </>}/><BoardActionsContext.Provider value={boardActions}><BoardPromotedAttributesContext.Provider value={shownAttributes}>diff --git a/packages/commons/src/index.ts b/packages/commons/src/index.tsindex a543d4b899..cf140e0042 100644--- a/packages/commons/src/index.ts+++ b/packages/commons/src/index.ts@@ -25,6 +25,7 @@ export * from "./lib/dayjs.js";export * from "./lib/notes.js";export * from "./lib/onenote.js";export * from "./lib/week_utils.js";+export * from "./lib/board_columns.js";export * from "./lib/builtin_attributes.js";export { default as BUILTIN_ATTRIBUTES } from "./lib/builtin_attributes.js";// The spreadsheet modules are deliberately not re-exported here: they pull in numfmt, and thediff --git a/packages/commons/src/lib/board_columns.spec.ts b/packages/commons/src/lib/board_columns.spec.tsnew file mode 100644index 0000000000..a8a8f1cf9c--- /dev/null+++ b/packages/commons/src/lib/board_columns.spec.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from "vitest";++import {+ boardColumnsKey, DEFAULT_BOARD_GROUP_BY, isBoardColumnsKey, normalizeBoardGroupBy+} from "./board_columns.js";++describe("boardColumnsKey", () => {+ it("keeps the default grouping on the key every board used before", () => {+ for (const groupBy of [ DEFAULT_BOARD_GROUP_BY, "#status", " status ", "", " ", undefined,+ null ]) {+ expect(boardColumnsKey(groupBy), String(groupBy)).toBe("columns");+ }+ });++ it("gives every other label a key of its own", () => {+ expect(boardColumnsKey("priority")).toBe("priorityViewColumns");+ expect(boardColumnsKey("#priority")).toBe("priorityViewColumns");+ expect(boardColumnsKey(" priority ")).toBe("priorityViewColumns");+ });++ it("tells a relation apart from a label of the same name", () => {+ expect(boardColumnsKey("~status")).toBe("~statusViewColumns");+ expect(boardColumnsKey("~assignee")).toBe("~assigneeViewColumns");+ expect(boardColumnsKey("~assignee")).not.toBe(boardColumnsKey("assignee"));+ });+});++describe("normalizeBoardGroupBy", () => {+ it("drops the label prefix and keeps the relation one", () => {+ expect(normalizeBoardGroupBy("#priority")).toBe("priority");+ expect(normalizeBoardGroupBy(" # priority ")).toBe("priority");+ expect(normalizeBoardGroupBy("~assignee")).toBe("~assignee");+ expect(normalizeBoardGroupBy(undefined)).toBe("");+ });+});++describe("isBoardColumnsKey", () => {+ it("recognises a keyed column list and nothing else", () => {+ expect(isBoardColumnsKey("priorityViewColumns")).toBe(true);+ expect(isBoardColumnsKey("~assigneeViewColumns")).toBe(true);+ expect(isBoardColumnsKey("columns")).toBe(false);+ expect(isBoardColumnsKey("ViewColumns")).toBe(false);+ expect(isBoardColumnsKey("templates")).toBe(false);+ });+});diff --git a/packages/commons/src/lib/board_columns.ts b/packages/commons/src/lib/board_columns.tsnew file mode 100644index 0000000000..6c76cb4e13--- /dev/null+++ b/packages/commons/src/lib/board_columns.ts@@ -0,0 +1,31 @@+/** The label a board groups by when `#board:groupBy` does not name one. */+export const DEFAULT_BOARD_GROUP_BY = "status";++/** The key a board's column list is stored under in `board.json`. */+export type BoardColumnsKey = "columns" | `${string}ViewColumns`;++/**+ * The grouping value without the `#` a label may be written with. A relation keeps its `~`, so a+ * relation and a label of the same name are two different groupings.+ */+export function normalizeBoardGroupBy(groupBy: string | undefined | null): string {+ const trimmed = (groupBy ?? "").trim();+ return trimmed.startsWith("#") ? trimmed.substring(1).trim() : trimmed;+}++/**+ * Where `board.json` keeps the columns for one grouping.+ *+ * A board holds a column list per attribute it can group by, so switching the grouping cannot mix+ * two lists. The default grouping uses `columns`, which is where every board wrote its columns+ * before the grouping could be switched.+ */+export function boardColumnsKey(groupBy: string | undefined | null): BoardColumnsKey {+ const name = normalizeBoardGroupBy(groupBy);+ return !name || name === DEFAULT_BOARD_GROUP_BY ? "columns" : `${name}ViewColumns`;+}++/** Whether a `board.json` key holds the columns of a non-default grouping. */+export function isBoardColumnsKey(key: string): boolean {+ return key.endsWith("ViewColumns") && key.length > "ViewColumns".length;+}diff --git a/packages/trilium-core/src/routes/api/board.spec.ts b/packages/trilium-core/src/routes/api/board.spec.tsindex 676296251d..0a08d9d648 100644--- a/packages/trilium-core/src/routes/api/board.spec.ts+++ b/packages/trilium-core/src/routes/api/board.spec.ts@@ -82,6 +82,39 @@ describe("Board API (core)", () => {expect(becca.getNoteOrThrow(card.noteId).getOwnedRelationValue("status")).toBe(other.noteId);});+ /**+ * A board holds a column list per grouping, and one of them can carry a column of the same name+ * as another's. A rename belongs to the grouping it was made on and to no other.+ */+ it("renames a column of the grouping it was made on, leaving other lists alone", async () => {+ const board = await createTextNote(api, { title: "Board" });+ const card = await createTextNote(api, { parentNoteId: board.noteId, title: "Card" });+ await api.put(`/api/notes/${card.noteId}/set-attribute`,+ { body: { type: "label", name: "priority", value: "High" } });+ await api.post(`/api/notes/${board.noteId}/attachments`, {+ body: {+ title: "board.json", role: "viewConfig", mime: "application/json",+ content: JSON.stringify({+ columns: [ { value: "High", color: "#ff0000" } ],+ priorityViewColumns: [+ { value: "High", icon: "bx bx-up-arrow" }, { value: "Low" }+ ]+ })+ }+ });++ const res = await api.put<{ cards: number }>(+ `/api/notes/${board.noteId}/board/rename-column`,+ { body: { attribute: "priority", oldValue: "High", newValue: "Urgent" } });++ expect(res.status).toBe(200);+ expect(res.body.cards).toBe(1);+ expect(configOf(board.noteId).priorityViewColumns).toEqual([+ { value: "Urgent", icon: "bx bx-up-arrow" }, { value: "Low" }+ ]);+ expect(configOf(board.noteId).columns).toEqual([ { value: "High", color: "#ff0000" } ]);+ });+/** A board with one card per value given, the second column carrying a colour of its own. */async function buildBoard(values: string[]) {const board = await createTextNote(api, { title: "Board" });@@ -124,7 +157,9 @@ describe("Board API (core)", () => {return definition.split("options=")[1]?.split(";") ?? [];}- function configOf(boardId: string): { columns: { value: string, color?: string }[] } {+ type StoredColumns = { value: string, color?: string, icon?: string }[];++ function configOf(boardId: string): Record<string, StoredColumns> & { columns: StoredColumns } {const attachment = becca.getNoteOrThrow(boardId).getAttachmentByTitle("board.json");return JSON.parse(attachment?.getContent().toString() ?? "{}");}diff --git a/packages/trilium-core/src/routes/api/board.ts b/packages/trilium-core/src/routes/api/board.tsindex ee50bf98e4..0cf5ad6f6c 100644--- a/packages/trilium-core/src/routes/api/board.ts+++ b/packages/trilium-core/src/routes/api/board.ts@@ -1,4 +1,6 @@-import { promotedAttributeDefinitionParser } from "@triliumnext/commons";+import {+ type BoardColumnsKey, boardColumnsKey, promotedAttributeDefinitionParser+} from "@triliumnext/commons";import type { Request } from "express";import becca from "../../becca/becca.js";@@ -65,10 +67,14 @@ function renameColumn(req: Request<{ noteId: string }>) {renameInDefinition(board, attribute, oldValue, newValue);+ // The board keeps a column list per grouping, so the rename lands in the list of the grouping+ // it was made on.+ const columnsKey = boardColumnsKey(isRelation ? `~${attribute}` : attribute);+// Answered with, so the client that asked has the configuration as it now stands rather than// the one it read before the rename. Writing that stale one back is what used to bring the old// name to the board again a moment after it left.- return { cards, config: renameInConfig(board, oldValue, newValue) };+ return { cards, config: renameInConfig(board, columnsKey, oldValue, newValue) };}/**@@ -99,15 +105,18 @@ function renameInDefinition(board: BNote, attribute: string, oldValue: string, n/*** Renames the column in the board's stored configuration, keeping everything else it holds.*+ * @param columnsKey which grouping's column list the rename was made on.* @returns the configuration as it now stands, or nothing where the board keeps none.*/-function renameInConfig(board: BNote, oldValue: string, newValue: string) {+function renameInConfig(+ board: BNote, columnsKey: BoardColumnsKey, oldValue: string, newValue: string+) {const attachment = board.getAttachmentByTitle(CONFIG_ATTACHMENT);if (!attachment) {return undefined;}- let config: { columns?: StoredColumn[] };+ let config: Partial<Record<BoardColumnsKey, StoredColumn[]>>;try {config = JSON.parse(attachment.getContent().toString());} catch {@@ -116,13 +125,14 @@ function renameInConfig(board: BNote, oldValue: string, newValue: string) {return undefined;}- if (!config.columns?.some(column => column.value === oldValue)) {+ const columns = config[columnsKey];+ if (!columns?.some(column => column.value === oldValue)) {return config;}const renamed = {...config,- columns: config.columns.map(column =>+ [columnsKey]: columns.map(column =>column.value === oldValue ? { ...column, value: newValue } : column)};