Skip to content

Build your personal knowledge base with Trilium Notes

client/collections/board: add support for column/card references

Adorian Doran6271f3ac0f8c
diff --git a/apps/client/src/services/link.spec.ts b/apps/client/src/services/link.spec.ts
index 02361d45f7..3f7a1072fd 100644
--- a/apps/client/src/services/link.spec.ts
+++ b/apps/client/src/services/link.spec.ts
@@ -144,6 +144,14 @@ describe("parseNavigationStateFromUrl", () => {
warn.mockRestore();
});
+ it("carries a board reference through, for the column and for the card", () => {
+ const column = parseNavigationStateFromUrl("#root/aaaaaaaaaaaa?column=colTodo00001");
+ expect((column as any).viewScope).toMatchObject({ column: "colTodo00001" });
+
+ const card = parseNavigationStateFromUrl("#root/aaaaaaaaaaaa?card=card00000001");
+ expect((card as any).viewScope).toMatchObject({ card: "card00000001" });
+ });
+
it("returns empty object when the note path does not match the id pattern", () => {
// hash present at index 0, but the path is too short to be a valid note id
expect(parseNavigationStateFromUrl("#ab")).toStrictEqual({});
@@ -169,6 +177,21 @@ describe("calculateHash", () => {
expect(hash).toBe("#root/abc?ntxId=n1&hoistedNoteId=h1&viewMode=source&attachmentId=att%201");
});
+ it("writes a board reference back into the hash it was read from", () => {
+ const hash = calculateHash({
+ notePath: "root/abc",
+ viewScope: { column: "colTodo00001" }
+ } as any);
+ expect(hash).toBe("#root/abc?column=colTodo00001");
+ // Read back, the path spelled out at the length a note id is checked against.
+ const read = `http://localhost:8080/#root/aaaaaaaaaaaa${hash.slice("#root/abc".length)}`;
+ expect(parseNavigationStateFromUrl(read))
+ .toMatchObject({ viewScope: { column: "colTodo00001" } });
+
+ expect(calculateHash({ notePath: "root/abc", viewScope: { card: "card00000001" } } as any))
+ .toBe("#root/abc?card=card00000001");
+ });
+
it("omits params that are at their defaults", () => {
const hash = calculateHash({
notePath: "root/abc",
diff --git a/apps/client/src/services/link.ts b/apps/client/src/services/link.ts
index 31049fcbb8..f35ca9d36b 100644
--- a/apps/client/src/services/link.ts
+++ b/apps/client/src/services/link.ts
@@ -75,6 +75,16 @@ export interface ViewScope {
* by the destination type widget (mirrors `bookmark` semantics).
*/
searchTerms?: string[];
+ /**
+ * The id of the board column a reference points at, which the board reveals once it has drawn
+ * it. Consumed once, as `bookmark` is.
+ */
+ column?: string;
+ /**
+ * The note id of the board card a reference points at, revealed the same way {@link column}
+ * is.
+ */
+ card?: string;
}
/**
@@ -97,7 +107,7 @@ const NOTE_PATH_PATTERN = /^[_a-z0-9]{4,}(\/[_a-z0-9]{4,})*$/i;
const MAX_SPLIT_PANES_IN_HASH = 8;
/** Hash parameters that belong to a pane's view scope rather than to the window as a whole. */
-const VIEW_SCOPE_PARAMS = ["viewMode", "attachmentId", "bookmark"];
+const VIEW_SCOPE_PARAMS = ["viewMode", "attachmentId", "bookmark", "column", "card"];
interface CreateLinkOptions {
title?: string;
@@ -234,6 +244,8 @@ export function calculateHash(
hoistedNoteId && hoistedNoteId !== "root" ? { hoistedNoteId } : null,
viewScope.viewMode && viewScope.viewMode !== "default" ? { viewMode: viewScope.viewMode } : null,
viewScope.attachmentId ? { attachmentId: viewScope.attachmentId } : null,
+ viewScope.column ? { column: viewScope.column } : null,
+ viewScope.card ? { card: viewScope.card } : null,
viewScope.searchTerms?.length
? { searchTerms: viewScope.searchTerms.map(encodeURIComponent).join(",") }
: null,
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 7172334414..617602fa46 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3474,6 +3474,10 @@
"show-archived-notes": "Show archived cards/columns",
"general": "General",
"show-archived": "Show archived cards and columns",
+ "copy-reference": "Copy reference",
+ "reference-column-missing": "That column is no longer on this board.",
+ "reference-archived": "That item is archived, so the board is not showing it.",
+ "reference-missing": "That item is no longer on this board.",
"properties": "Board properties",
"properties-title": "Board properties",
"card-templates": "Card templates",
diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.ts
index e119d7ca8c..ed2b8bb692 100644
--- a/apps/client/src/widgets/collections/board/api.spec.ts
+++ b/apps/client/src/widgets/collections/board/api.spec.ts
@@ -1,6 +1,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import appContext from "../../../components/app_context";
+import type NoteContext from "../../../components/note_context";
import FAttribute from "../../../entities/fattribute";
import type FBranch from "../../../entities/fbranch";
import branches from "../../../services/branches";
@@ -20,6 +21,7 @@ import BoardApi, { getPendingWrites, PendingColumnWrites } from "./api";
import { ColumnItem, ColumnMap } from "./data";
import { BOARD_TEMPLATE_ID, DEFAULT_COLUMN_ICON, getStatusDefinition, INBOX_COLUMN } from "./columns";
import { DEFAULT_CARD_TEMPLATES } from "./card_templates";
+import { COLUMN_ID_LENGTH } from "./reference";
vi.mock("../../../services/bulk_action", () => ({
executeBulkActions: vi.fn(async () => {})
@@ -202,7 +204,7 @@ describe("BoardApi column mutations", () => {
expect(saved.at(-1)?.columns)
.toEqual([
- { value: "board_view.new-column" },
+ { value: "board_view.new-column", id: expect.any(String) },
{ value: "To Do", icon: "bx bx-list-ul", color: "#e64d4d" }
]);
});
@@ -1686,11 +1688,14 @@ describe("collapsing a column", () => {
const { api, saved } = createApi({ columns: [ { value: "To Do" } ] }, [ "To Do" ]);
await api.addNewColumn("Blocked", false, "bx bx-star");
- expect(saved.at(-1)?.columns)
- .toEqual([ { value: "To Do" }, { value: "Blocked", icon: "bx bx-star" } ]);
+ expect(saved.at(-1)?.columns).toEqual([
+ { value: "To Do" },
+ { value: "Blocked", icon: "bx bx-star", id: expect.any(String) }
+ ]);
await api.addNewColumn("Doing", true, "bx bx-run");
- expect(saved.at(-1)?.columns?.[0]).toEqual({ value: "Doing", icon: "bx bx-run" });
+ expect(saved.at(-1)?.columns?.[0])
+ .toEqual({ value: "Doing", icon: "bx bx-run", id: expect.any(String) });
});
/**
@@ -2542,3 +2547,68 @@ describe("the columns as the right pane lists them", () => {
]);
});
});
+
+describe("references to a board's columns and cards", () => {
+ it("keeps the id a column already has, so the link stays the same", () => {
+ const { api, saved } = createApi(
+ { columns: [ { value: "To Do", id: "colTodo00001" } ] }, [ "To Do" ]);
+
+ expect(api.ensureColumnId("To Do")).toBe("colTodo00001");
+ expect(api.ensureColumnId("To Do")).toBe("colTodo00001");
+ // Nothing to store, so the board is left alone.
+ expect(saved).toEqual([]);
+ });
+
+ /**
+ * A column drawn from the definition or from a value its cards carry has no stored entry at
+ * all, so the first reference taken of it is what writes one.
+ */
+ it("stores an id for a column that has none, keeping what it already holds", () => {
+ const { api, saved } = createApi(
+ { columns: [ { value: "To Do", icon: "bx bx-list-ul" } ] }, [ "To Do", "Done" ]);
+
+ const todo = api.ensureColumnId("To Do");
+ expect(todo).toHaveLength(COLUMN_ID_LENGTH);
+ expect(saved.at(-1)?.columns)
+ .toEqual([ { value: "To Do", icon: "bx bx-list-ul", id: todo } ]);
+
+ const done = api.ensureColumnId("Done");
+ expect(done).not.toBe(todo);
+ expect(saved.at(-1)?.columns).toEqual([
+ { value: "To Do", icon: "bx bx-list-ul", id: todo },
+ { value: "Done", id: done }
+ ]);
+ });
+
+ it("writes one grouping's ids under that grouping alone", () => {
+ const board = buildNote({ title: "Board" });
+ const { api, saved } = createApi(
+ { columns: [ { value: "To Do", id: "colTodo00001" } ] }, [ "High" ], board,
+ "priority");
+
+ const high = api.ensureColumnId("High");
+ expect(saved.at(-1)?.priorityViewColumns).toEqual([ { value: "High", id: high } ]);
+ expect(saved.at(-1)?.columns).toEqual([ { value: "To Do", id: "colTodo00001" } ]);
+ });
+
+ it("builds the links the menu copies, from the path the pane reached the board by", () => {
+ const board = buildNote({ title: "Board" });
+ const { api } = createApi(
+ { columns: [ { value: "To Do", id: "colTodo00001" } ] }, [ "To Do" ], board);
+ api.noteContext = { notePath: `root/parent1234/${board.noteId}` } as NoteContext;
+
+ expect(api.getColumnReference("To Do"))
+ .toBe(`#root/parent1234/${board.noteId}?column=colTodo00001`);
+ expect(api.getCardReference("card00000001"))
+ .toBe(`#root/parent1234/${board.noteId}?card=card00000001`);
+ });
+
+ /** A board drawn outside a pane, such as in a note preview, still has itself to name. */
+ it("falls back to the board's own id where the pane names no path", () => {
+ const board = buildNote({ title: "Board" });
+ const { api } = createApi({}, [], board);
+
+ expect(api.getCardReference("card00000001"))
+ .toBe(`#${board.noteId}?card=card00000001`);
+ });
+});
diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.ts
index 59cdc4a5dd..361c1f2bf9 100644
--- a/apps/client/src/widgets/collections/board/api.ts
+++ b/apps/client/src/widgets/collections/board/api.ts
@@ -31,6 +31,7 @@ import {
} from "./columns";
import { readColumns, writeColumns } from "./column_storage";
import { ColumnItem, ColumnMap } from "./data";
+import { cardReference, columnReference, newColumnId, readColumnId } from "./reference";
import { SORT_DESCENDING_LABEL, SORT_LABEL } from "./sort";
/** Which end of a column a new card is made at. */
@@ -408,7 +409,10 @@ export default class BoardApi {
// The icon goes in with the column rather than after it: a write of its own would be a
// second refresh of the board for a column that has only just been drawn.
- const added: BoardColumnData = icon ? { value: columnName, icon } : { value: columnName };
+ const added: BoardColumnData = { value: columnName, id: newColumnId() };
+ if (icon) {
+ added.icon = icon;
+ }
if (!atStart) {
this.storeColumns([ ...columns, added ]);
@@ -464,9 +468,11 @@ export default class BoardApi {
order.splice(
neighbour < 0 ? order.length : neighbour + (direction === "after" ? 1 : 0), 0, name);
- // Entries carry more than their name, so each is moved rather than rebuilt.
+ // Entries carry more than their name, so each is moved rather than rebuilt. The new one is
+ // the only one written from scratch, and is the only one given an id.
const byValue = new Map(stored.map(col => [ col.value, col ]));
- this.storeColumns(order.map(value => byValue.get(value) ?? { value }));
+ this.storeColumns(order.map(value =>
+ byValue.get(value) ?? (value === name ? { value, id: newColumnId() } : { value })));
return name;
}
@@ -800,6 +806,44 @@ export default class BoardApi {
await this.updateColumn(INBOX_COLUMN, { nested });
}
+ /**
+ * The id a reference names a column by, storing one where the column has none yet.
+ *
+ * A column with no stored entry at all is given one here: it is drawn from the definition or
+ * from a value its cards carry, and until something is stored for it there is nothing to hold
+ * an id.
+ */
+ ensureColumnId(column: string) {
+ const stored = readColumnId(this.viewConfig, this.groupBy, column);
+ if (stored) {
+ return stored;
+ }
+
+ const id = newColumnId();
+ this.updateColumn(column, { id });
+ return id;
+ }
+
+ /**
+ * The link that opens this board on one of its columns, which the menu copies.
+ *
+ * Storing an id for a column that has none is what makes the link outlive a rename, so copying
+ * a reference writes to `board.json` where nothing has been stored for the column yet.
+ */
+ getColumnReference(column: string) {
+ return columnReference(this.boardNotePath, this.ensureColumnId(column));
+ }
+
+ /** The link that opens this board on one of its cards, which is named by its own note id. */
+ getCardReference(noteId: string) {
+ return cardReference(this.boardNotePath, noteId);
+ }
+
+ /** How a link names the board: the path the pane reached it by, or the board alone. */
+ private get boardNotePath() {
+ return this.noteContext?.notePath ?? this.parentNote.noteId;
+ }
+
/** Whether a column is archived, which the board shows only while archived notes are shown. */
isColumnArchived(column: string) {
return !!this.storedColumns.find(col => col.value === column)?.archived;
diff --git a/apps/client/src/widgets/collections/board/context_menu.spec.ts b/apps/client/src/widgets/collections/board/context_menu.spec.ts
index e3820f3093..f7edd45cb6 100644
--- a/apps/client/src/widgets/collections/board/context_menu.spec.ts
+++ b/apps/client/src/widgets/collections/board/context_menu.spec.ts
@@ -5,6 +5,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import type { CommandNames } from "../../../components/app_context";
import contextMenu, { ContextMenuEvent, MenuItem } from "../../../menus/context_menu";
import branches from "../../../services/branches";
+import * as clipboard from "../../../services/clipboard_ext";
import dialog from "../../../services/dialog";
import FNote from "../../../entities/fnote";
import type { PromotedAttribute } from "../promoted_attributes";
@@ -240,7 +241,7 @@ describe("Board column context menu", () => {
const titled = openMenu({} as BoardApi).filter(item => item && "uiIcon" in item);
expect(titled.map(item => "uiIcon" in item ? item.uiIcon : undefined))
.toEqual([
- "bx bx-edit-alt",
+ "bx bx-edit-alt", "bx bx-directions",
"bx bx-plus", "bx bx-link", "bx bx-columns",
"bx bx-collapse-horizontal", "bx bx-lock-alt", "bx bx-sort-alt-2",
"bx bx-tachometer",
@@ -249,12 +250,30 @@ describe("Board column context menu", () => {
]);
});
- /** A collapsed column offers no rename, so the group above the first divider is empty. */
+ /**
+ * A collapsed column offers no rename, so the reference is all its leading group holds. The
+ * menu still opens on an entry rather than on the divider that closes the group.
+ */
it("opens on an entry rather than a divider when it has nothing to rename", () => {
- const items = openMenu({} as BoardApi, { canRename: false, isCollapsed: true });
+ const items = openMenu({ ensureColumnId: () => "colId1234567" } as unknown as BoardApi,
+ { canRename: false, isCollapsed: true });
expect(items[0]).not.toMatchObject({ kind: "separator" });
- expect(items[0]).toMatchObject({ uiIcon: "bx bx-plus" });
+ expect(items[0]).toMatchObject({ uiIcon: "bx bx-directions" });
+ });
+
+ it("copies a link to the column, which is what stores an id for it", () => {
+ const copy = vi.spyOn(clipboard, "copyTextWithToast").mockImplementation(() => {});
+ const api = {
+ getColumnReference: (column: string) => `#root/board1234?column=id-of-${column}`
+ } as unknown as BoardApi;
+
+ const entry = openMenu(api, { value: "To Do" }).find(item =>
+ item && "uiIcon" in item && item.uiIcon === "bx bx-directions");
+ if (!entry || !("handler" in entry)) throw new Error("expected a copy-reference entry");
+
+ entry.handler?.(entry, {} as never);
+ expect(copy).toHaveBeenCalledWith("#root/board1234?column=id-of-To Do");
});
/** Every place offered has to actually move the column, or the menu promises nothing. */
@@ -570,6 +589,40 @@ describe("Board item context menu", () => {
.toEqual([ "bx bx-list-plus", "bx bx-empty", "bx bx-outline" ]);
});
+ it("copies a link to the card, which the card's own note id names", () => {
+ const copy = vi.spyOn(clipboard, "copyTextWithToast").mockImplementation(() => {});
+ const note = buildNote({ title: "Card" }) as FNote;
+ const api = {
+ columns: [],
+ isColumnArchived: () => false,
+ getColumnIcon: () => DEFAULT_COLUMN_ICON,
+ getColumnColorClass: () => "",
+ getCardReference: (noteId: string) => `#root/board1234?card=${noteId}`
+ } as unknown as BoardApi;
+
+ const entry = openItemMenu(api, "To Do", vi.fn(), vi.fn(), 2, vi.fn(), [ note ])
+ .find(item => item && "uiIcon" in item && item.uiIcon === "bx bx-directions");
+ if (!entry || !("handler" in entry)) throw new Error("expected a copy-reference entry");
+
+ entry.handler?.(entry, {} as never);
+ expect(copy).toHaveBeenCalledWith(`#root/board1234?card=${note.noteId}`);
+ });
+
+ /** A whole selection has no one card to make a link to, so the entry is left out. */
+ it("offers no reference for a selection of several cards", () => {
+ const api = {
+ columns: [],
+ isColumnArchived: () => false,
+ getColumnIcon: () => DEFAULT_COLUMN_ICON,
+ getColumnColorClass: () => ""
+ } as unknown as BoardApi;
+ const notes = [ buildNote({ title: "One" }), buildNote({ title: "Two" }) ] as FNote[];
+
+ const icons = openItemMenu(api, "To Do", vi.fn(), vi.fn(), 2, vi.fn(), notes)
+ .map(item => (item && "uiIcon" in item ? item.uiIcon : undefined));
+ expect(icons).not.toContain("bx bx-directions");
+ });
+
it("says nothing about moving up the card already at the head", () => {
const api = {
columns: [],
@@ -635,7 +688,8 @@ describe("Board item context menu", () => {
/** Where the entries a card is opened and named with end, which the next group follows. */
function lastOfLeadingGroup(items: MenuItem<unknown>[]) {
- return items.findIndex(item => item && "title" in item && item.title === "Open note");
+ return items.findIndex(item =>
+ item && "title" in item && item.title === "board_view.copy-reference");
}
it("copies a card into the board, after the one it was made from", async () => {
diff --git a/apps/client/src/widgets/collections/board/context_menu.ts b/apps/client/src/widgets/collections/board/context_menu.ts
index 04e53b1434..699c90228a 100644
--- a/apps/client/src/widgets/collections/board/context_menu.ts
+++ b/apps/client/src/widgets/collections/board/context_menu.ts
@@ -8,6 +8,7 @@ import NoteColorPicker from "../../../menus/custom-items/NoteColorPicker";
import link_context_menu from "../../../menus/link_context_menu";
import attributes from "../../../services/attributes";
import branches from "../../../services/branches";
+import { copyTextWithToast } from "../../../services/clipboard_ext";
import dialog from "../../../services/dialog";
import { t } from "../../../services/i18n";
import { shared } from "../../../services/note_set";
@@ -72,7 +73,12 @@ export function openColumnContextMenu(api: Api, event: ContextMenuEvent, column:
uiIcon: "bx bx-subdirectory-right",
checked: !!column.nested,
handler: () => api.setInboxNested(!column.nested)
- } ] : [])
+ } ] : []),
+ {
+ title: t("board_view.copy-reference"),
+ uiIcon: "bx bx-directions",
+ handler: () => copyTextWithToast(api.getColumnReference(column.value))
+ }
];
contextMenu.show({
@@ -527,6 +533,11 @@ export function openNoteContextMenu(api: Api, event: ContextMenuEvent, target: N
handler: () => api.startEditing(branchId)
},
link_context_menu.getOpenNoteItem(event),
+ {
+ title: t("board_view.copy-reference"),
+ uiIcon: "bx bx-directions",
+ handler: () => copyTextWithToast(api.getCardReference(note.noteId))
+ },
{ kind: "separator" }
];
diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsx
index de97aa86a0..7b78d6f3d6 100644
--- a/apps/client/src/widgets/collections/board/index.tsx
+++ b/apps/client/src/widgets/collections/board/index.tsx
@@ -64,6 +64,7 @@ import { currentCardTemplate, DEFAULT_CARD_TEMPLATES } from "./card_templates";
import ColumnLimitDialog from "./column_limit";
import BoardGroupBy, { groupingOptions } from "./group_by";
import BoardProperties from "./properties";
+import { useBoardReference } from "./reference";
import { openBoardContextMenu, openCreateColumnMenu } from "./context_menu";
import { useBoardSort } from "./sort";
import {
@@ -109,6 +110,11 @@ export interface BoardViewData {
export interface BoardColumnData {
value: string;
+ /**
+ * What a reference to the column names it by, which survives a rename as `value` does not.
+ * Assigned when the column is created, or the first time a reference asks for one.
+ */
+ id?: string;
/** The icon class shown before the title, absent until one is picked. */
icon?: string;
/** The CSS colour the column is tinted with, absent until one is picked. */
@@ -654,6 +660,22 @@ export default function BoardView({
}), [ api, shownColumns, byColumn, storedColumns, isInRelationMode ]);
useSetContextData(noteContext, "boardColumns", outline);
+ // A `?column=` or `?card=` link opened the board on one of them, which is revealed once it is
+ // drawn. Given `shownColumns` rather than every column, so a column left out because it is
+ // archived is reported as such instead of being waited for.
+ useBoardReference({
+ noteId: parentNote.noteId,
+ noteContext,
+ api,
+ viewConfig,
+ groupBy,
+ setGroupBy: setRequestedGroupBy,
+ columns: columns && shownColumns,
+ includeArchived,
+ selectColumn,
+ containerRef
+ });
+
// Neither the creation dates the tie-break needs nor the targets of a sorted relation come
// with the board. Both are fetched here, and `sortRevision` redraws it once they land.
useEffect(() => {
diff --git a/apps/client/src/widgets/collections/board/reference.spec.tsx b/apps/client/src/widgets/collections/board/reference.spec.tsx
new file mode 100644
index 0000000000..28369dbf08
--- /dev/null
+++ b/apps/client/src/widgets/collections/board/reference.spec.tsx
@@ -0,0 +1,366 @@
+/**
+ * References to a board's columns and cards: the links themselves, and what the board does when it
+ * is opened by one.
+ */
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import Component from "../../../components/component";
+import type NoteContext from "../../../components/note_context";
+import attributes from "../../../services/attributes";
+import type { ViewScope } from "../../../services/link";
+import toast from "../../../services/toast";
+import { buildNote } from "../../../test/easy-froca";
+import { ParentComponent } from "../../react/react_utils";
+import BoardView, { type BoardViewData } from ".";
+import {
+ cardReference, columnReference, COLUMN_ID_LENGTH, findColumnById, newColumnId, readColumnId
+} from "./reference";
+
+vi.mock("../../../menus/link_context_menu", () => ({
+ default: {
+ getQuickEditItem: () => ({ title: "Quick edit" }),
+ getOpenNoteItem: () => ({ title: "Open note", items: [] }),
+ handleLinkContextMenuItem: () => {}
+ }
+}));
+
+// i18next is never initialised under test, so every label would read as undefined.
+vi.mock("../../../services/i18n", () => ({
+ t: (key: string) => key,
+ translationsInitializedPromise: Promise.resolve(),
+ getCurrentLanguage: () => "en"
+}));
+
+const TODO_ID = "colTodo00001";
+const DONE_ID = "colDone00001";
+const HIGH_ID = "colHigh00001";
+
+describe("board reference links", () => {
+ it("names a column and a card in a note path the app can follow", () => {
+ expect(columnReference("root/board123", TODO_ID)).toBe(`#root/board123?column=${TODO_ID}`);
+ expect(cardReference("root/board123", "card00000001"))
+ .toBe("#root/board123?card=card00000001");
+ });
+
+ it("escapes what a column id could otherwise end the parameter with", () => {
+ expect(columnReference("root/board123", "a b&c=d")).toBe("#root/board123?column=a%20b%26c%3Dd");
+ });
+
+ it("mints ids of a note id's length, and distinct ones", () => {
+ const ids = new Set(Array.from({ length: 200 }, () => newColumnId()));
+ expect(ids.size).toBe(200);
+ for (const id of ids) {
+ expect(id).toHaveLength(COLUMN_ID_LENGTH);
+ }
+ });
+});
+
+describe("finding a column by its id", () => {
+ const config: BoardViewData = {
+ columns: [ { value: "To Do", id: TODO_ID }, { value: "Done", id: DONE_ID } ],
+ priorityViewColumns: [ { value: "High", id: HIGH_ID } ],
+ template: "text"
+ };
+
+ it("names the grouping that owns the column, the default one included", () => {
+ expect(findColumnById(config, TODO_ID)).toEqual({ groupBy: "status", value: "To Do" });
+ expect(findColumnById(config, HIGH_ID)).toEqual({ groupBy: "priority", value: "High" });
+ });
+
+ it("answers with nothing for an id no grouping holds, and for no config at all", () => {
+ expect(findColumnById(config, "colGone00001")).toBeUndefined();
+ expect(findColumnById(config, "")).toBeUndefined();
+ expect(findColumnById(undefined, TODO_ID)).toBeUndefined();
+ });
+
+ it("looks past the keys that hold something other than columns", () => {
+ // `template` is a string, and a key whose value is not a list of columns must not be walked
+ // as though it were.
+ expect(() => findColumnById(config, TODO_ID)).not.toThrow();
+ expect(findColumnById({ template: "text" } as BoardViewData, TODO_ID)).toBeUndefined();
+ });
+
+ it("reads the id stored for one grouping's column", () => {
+ expect(readColumnId(config, "status", "To Do")).toBe(TODO_ID);
+ expect(readColumnId(config, "priority", "High")).toBe(HIGH_ID);
+ expect(readColumnId(config, "status", "High")).toBeUndefined();
+ expect(readColumnId(undefined, "status", "To Do")).toBeUndefined();
+ });
+});
+
+describe("opening a board by a reference", () => {
+ let container: HTMLElement | undefined;
+ let messages: string[] = [];
+ let idSeed = 0;
+ /** The component each mount was drawn under, for a test that draws a second board into it. */
+ const mounted = new Map<HTMLElement, Component>();
+
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ messages = [];
+ vi.spyOn(toast, "showMessage").mockImplementation((message) => {
+ messages.push(String(message));
+ });
+ // happy-dom lays nothing out, so what a reveal scrolls is only ever asked for.
+ vi.spyOn(Element.prototype, "scrollIntoView").mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ if (container) {
+ render(null, container);
+ container.remove();
+ container = undefined;
+ }
+ });
+
+ it("puts the focus on the column a reference names", async () => {
+ const { mountPoint } = await renderBoard({ column: DONE_ID });
+
+ expect(focusedColumn(mountPoint)).toBe("Done");
+ expect(messages).toEqual([]);
+ });
+
+ it("clears the reference as it reads it, so a restored tab does not jump again", async () => {
+ const { viewScope, mountPoint } = await renderBoard({ column: DONE_ID });
+
+ expect(viewScope.column).toBeUndefined();
+ expect(viewScope.card).toBeUndefined();
+
+ // Nothing left to act on, so a later draw leaves the focus where the reader put it.
+ mountPoint.querySelector<HTMLElement>(".board-column h3")?.focus();
+ await settle();
+ expect(focusedColumn(mountPoint)).toBe("To Do");
+ });
+
+ it("puts the focus on the card a reference names", async () => {
+ const { mountPoint, second } = await renderBoard({ card: undefined }, (ids) => ({
+ card: ids.second
+ }));
+
+ expect(document.activeElement).toBe(
+ mountPoint.querySelector(`.board-note[data-note-id="${second}"]`));
+ });
+
+ it("opens a collapsed column a reference names, without storing it as open", async () => {
+ const saved: BoardViewData[] = [];
+ const { mountPoint } = await renderBoard({ column: DONE_ID }, undefined, {
+ columns: [
+ { value: "To Do", id: TODO_ID },
+ { value: "Done", id: DONE_ID, collapsed: true }
+ ]
+ }, false, saved);
+
+ expect(columnNamed(mountPoint, "Done")?.classList.contains("collapsed")).toBe(false);
+ expect(focusedColumn(mountPoint)).toBe("Done");
+ // A peek, so `collapsed` is left standing and the column shuts again on the next selection.
+ expect(saved).toEqual([]);
+ });
+
+ it("opens a collapsed column to show the card inside it", async () => {
+ const { mountPoint, second } = await renderBoard({}, (ids) => ({ card: ids.second }), {
+ columns: [
+ { value: "To Do", id: TODO_ID },
+ { value: "Done", id: DONE_ID, collapsed: true }
+ ]
+ });
+
+ const done = columnNamed(mountPoint, "Done");
+ expect(done?.classList.contains("collapsed")).toBe(false);
+ expect(document.activeElement).toBe(
+ mountPoint.querySelector(`.board-note[data-note-id="${second}"]`));
+ });
+
+ it("switches the board to the grouping that owns the column", async () => {
+ const setLabel = vi.spyOn(attributes, "setLabel").mockResolvedValue(undefined);
+
+ await renderBoard({ column: HIGH_ID }, undefined, {
+ columns: [ { value: "To Do", id: TODO_ID } ],
+ priorityViewColumns: [ { value: "High", id: HIGH_ID } ]
+ });
+
+ expect(setLabel).toHaveBeenCalledWith(expect.any(String), "board:groupBy", "priority");
+ // Asked for once, however many times the board draws while the label comes back.
+ expect(setLabel.mock.calls.filter(([ , name ]) => name === "board:groupBy")).toHaveLength(1);
+ });
+
+ it("says so when the column a reference names is no longer on the board", async () => {
+ await renderBoard({ column: "colGone00001" });
+
+ expect(messages).toEqual([ "board_view.reference-column-missing" ]);
+ });
+
+ it("says an archived column is not being shown rather than waiting for it", async () => {
+ await renderBoard({ column: DONE_ID }, undefined, {
+ columns: [
+ { value: "To Do", id: TODO_ID },
+ { value: "Done", id: DONE_ID, archived: true }
+ ]
+ });
+
+ expect(messages).toEqual([ "board_view.reference-archived" ]);
+ expect(columnNamed(container as HTMLElement, "Done")).toBeFalsy();
+ });
+
+ it("says an archived card is not being shown", async () => {
+ const { second } = await renderBoard({}, (ids) => ({ card: ids.second }), undefined, true);
+
+ expect(messages).toEqual([ "board_view.reference-archived" ]);
+ expect(second).toBeTruthy();
+ });
+
+ it("says a card the board does not hold at all is missing", async () => {
+ await renderBoard({ card: "card99999999" });
+
+ expect(messages).toEqual([ "board_view.reference-missing" ]);
+ });
+
+ /**
+ * `BoardView` is drawn unkeyed, so moving from one board to another reuses the instance. A
+ * reference that never settled, because the column it names is still being waited for, would
+ * otherwise be taken up by whichever board came next.
+ */
+ it("drops a reference the board it was taken for has been left", async () => {
+ // Its grouping is switched to, which the label never comes back for here, so the reference
+ // is still waiting when the next board is drawn.
+ vi.spyOn(attributes, "setLabel").mockResolvedValue(undefined);
+ const { mountPoint, note } = await renderBoard({ column: HIGH_ID }, undefined, {
+ columns: [ { value: "To Do", id: TODO_ID } ],
+ priorityViewColumns: [ { value: "High", id: HIGH_ID } ]
+ });
+
+ const next = buildNote({
+ title: "Other board",
+ type: "book",
+ "#collection": "",
+ "#viewType": "board",
+ children: [ { title: "Elsewhere", "#status": "High" } ]
+ });
+ expect(next.noteId).not.toBe(note.noteId);
+
+ await act(async () => {
+ render(
+ <ParentComponent.Provider value={parentOf(mountPoint)}>
+ <BoardView
+ note={next}
+ notePath={`root/${next.noteId}`}
+ noteIds={[ ...next.getChildNoteIds() ]}
+ highlightedTokens={null}
+ viewConfig={{ columns: [ { value: "High", id: HIGH_ID } ] }}
+ saveConfig={() => {}}
+ media="screen"
+ onReady={() => {}}
+ />
+ </ParentComponent.Provider>,
+ mountPoint
+ );
+ });
+ await settle();
+
+ // The board that followed holds a column of that very id, and is left alone all the same.
+ expect(focusedColumn(mountPoint)).toBeUndefined();
+ expect(messages).toEqual([]);
+ });
+
+ /** The provider the board was mounted under, so the second render keeps the same one. */
+ function parentOf(mountPoint: HTMLElement) {
+ return mounted.get(mountPoint) as Component;
+ }
+
+ /**
+ * Draws a board of two cards, one under each column, opened with the given view scope.
+ *
+ * @param scopeFor names a card by the ids the board was built with, which are only known once
+ * the notes exist.
+ */
+ async function renderBoard(
+ scope: ViewScope,
+ scopeFor?: (ids: { first: string, second: string }) => ViewScope,
+ config: BoardViewData = {
+ columns: [ { value: "To Do", id: TODO_ID }, { value: "Done", id: DONE_ID } ]
+ },
+ archiveSecond = false,
+ saved?: BoardViewData[]
+ ) {
+ const first = `refCard${idSeed++}`;
+ const second = `refCard${idSeed++}`;
+ const note = buildNote({
+ title: "Board",
+ type: "book",
+ "#collection": "",
+ "#viewType": "board",
+ children: [
+ { id: first, title: "First", "#status": "To Do" },
+ {
+ id: second,
+ title: "Second",
+ "#status": "Done",
+ ...(archiveSecond ? { "#archived": "" } : {})
+ }
+ ]
+ });
+
+ const viewScope: ViewScope = { ...scope, ...(scopeFor?.({ first, second }) ?? {}) };
+ const component = new Component();
+ Object.assign(component, {
+ noteContext: {
+ viewScope,
+ notePath: `root/${note.noteId}`,
+ setContextData: () => {},
+ clearContextData: () => {}
+ } as unknown as NoteContext
+ });
+
+ const mountPoint = document.createElement("div");
+ container = mountPoint;
+ document.body.appendChild(mountPoint);
+
+ await act(async () => {
+ render(
+ <ParentComponent.Provider value={component}>
+ <BoardView
+ note={note}
+ notePath={`root/${note.noteId}`}
+ noteIds={[ first, second ]}
+ highlightedTokens={null}
+ viewConfig={config}
+ saveConfig={(written) => saved?.push(written)}
+ media="screen"
+ onReady={() => {}}
+ />
+ </ParentComponent.Provider>,
+ mountPoint
+ );
+ });
+ await settle();
+ mounted.set(mountPoint, component);
+
+ return { note, mountPoint, viewScope, first, second };
+ }
+});
+
+/** The title of the column whose heading holds the focus, or nothing where none does. */
+function focusedColumn(container: HTMLElement) {
+ const heading = [ ...container.querySelectorAll<HTMLElement>(".board-column h3") ]
+ .find(candidate => candidate === document.activeElement);
+ return heading?.querySelector(".title")?.textContent ?? undefined;
+}
+
+function columnNamed(container: HTMLElement, title: string) {
+ return [ ...container.querySelectorAll<HTMLElement>(".board-column") ]
+ .find(column => column.querySelector(".title")?.textContent === title);
+}
+
+/**
+ * Lets the board draw and the reveal find what it is waiting for: the reveal polls a frame at a
+ * time, and the board resolves its columns a tick after it mounts.
+ */
+async function settle() {
+ for (let round = 0; round < 6; round++) {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve));
+ await new Promise((resolve) => requestAnimationFrame(resolve));
+ });
+ }
+}
diff --git a/apps/client/src/widgets/collections/board/reference.ts b/apps/client/src/widgets/collections/board/reference.ts
new file mode 100644
index 0000000000..1bf5dfc63f
--- /dev/null
+++ b/apps/client/src/widgets/collections/board/reference.ts
@@ -0,0 +1,303 @@
+/**
+ * References to one column or one card of a board, as a link the reader can copy and follow.
+ *
+ * A reference is a note path with one parameter on it, `?column=` or `?card=`, which `link.ts`
+ * carries in the pane's view scope the same way `?bookmark=` is carried. The board reads it once as
+ * it draws and reveals what it names; see {@link useBoardReference}.
+ *
+ * A card is named by its note id, which it already has. A column is named by an id of its own,
+ * stored in `board.json` beside the rest of what the column is drawn with, because the value its
+ * cards carry is rewritten whenever the column is renamed.
+ */
+
+import { boardColumnsKey, boardGroupByFromColumnsKey } from "@triliumnext/commons";
+import type { RefObject } from "preact";
+import { useEffect, useRef } from "preact/hooks";
+
+import type NoteContext from "../../../components/note_context";
+import froca from "../../../services/froca";
+import { t } from "../../../services/i18n";
+import toast from "../../../services/toast";
+import { randomString } from "../../../services/utils";
+import type { BoardColumnData, BoardViewData } from ".";
+import type BoardApi from "./api";
+import { askForCard } from "./windowing";
+
+/** How long a column id is, matching the length of a note id so the two read alike. */
+export const COLUMN_ID_LENGTH = 12;
+
+/** How many frames the reveal waits for the board to draw what a reference names. */
+const REVEAL_TRIES = 30;
+
+/** A fresh column id. `randomString` rather than `crypto.randomUUID`, which needs a secure context. */
+export function newColumnId() {
+ return randomString(COLUMN_ID_LENGTH);
+}
+
+/** Where a column reference points: the grouping that owns the column, and the column itself. */
+export interface ColumnReferenceTarget {
+ /** The grouping the column belongs to, as `#board:groupBy` writes it. */
+ groupBy: string;
+ /** The value the column's cards carry, which is what the board draws it by. */
+ value: string;
+}
+
+/**
+ * Finds the column an id names, in whichever grouping stores it.
+ *
+ * Every grouping keeps a column list of its own, so an id can belong to a grouping other than the
+ * one the board is showing. The board switches to the grouping named here rather than reporting the
+ * column missing.
+ */
+export function findColumnById(
+ config: BoardViewData | undefined, id: string
+): ColumnReferenceTarget | undefined {
+ if (!config || !id) {
+ return undefined;
+ }
+
+ for (const [ key, value ] of Object.entries(config)) {
+ const groupBy = boardGroupByFromColumnsKey(key);
+ if (!groupBy || !Array.isArray(value)) {
+ continue;
+ }
+
+ const column = (value as BoardColumnData[]).find(candidate => candidate?.id === id);
+ if (column) {
+ return { groupBy, value: column.value };
+ }
+ }
+
+ return undefined;
+}
+
+/** The stored id of a column of one grouping, or nothing where it has none yet. */
+export function readColumnId(
+ config: BoardViewData | undefined, groupBy: string, value: string
+): string | undefined {
+ const columns = config?.[boardColumnsKey(groupBy)] as BoardColumnData[] | undefined;
+ return columns?.find(column => column.value === value)?.id;
+}
+
+/** The link that opens a board on one of its columns. */
+export function columnReference(notePath: string, columnId: string) {
+ return `#${notePath}?column=${encodeURIComponent(columnId)}`;
+}
+
+/** The link that opens a board on one of its cards. */
+export function cardReference(notePath: string, noteId: string) {
+ return `#${notePath}?card=${encodeURIComponent(noteId)}`;
+}
+
+/**
+ * What a reference the board has taken off its view scope points at, and which board it was
+ * taken for: `BoardView` is drawn unkeyed, so moving to another board reuses the instance and a
+ * reference still waiting for its column must not settle on the board that followed.
+ */
+type BoardReferenceTarget = { board: string } & (
+ | { kind: "column"; id: string }
+ | { kind: "card"; noteId: string }
+);
+
+export interface BoardReferenceOptions {
+ /** The board the reference is settled against. */
+ noteId: string;
+ /** The pane the board is drawn in, whose view scope carries the reference. */
+ noteContext: NoteContext | null | undefined;
+ api: BoardApi;
+ /** The board's stored configuration, which every grouping's columns are read from. */
+ viewConfig: BoardViewData | undefined;
+ /** The grouping the board draws for. */
+ groupBy: string;
+ /** Switches the board to another grouping, by writing `#board:groupBy`. */
+ setGroupBy: (groupBy: string) => void;
+ /** The columns the board draws, absent until they are resolved. */
+ columns: string[] | undefined;
+ /** Whether the board draws archived columns and cards. */
+ includeArchived: boolean;
+ /** Draws a collapsed column open, without storing it as open. */
+ selectColumn: (column: string) => void;
+ /** The board's own element, which what is revealed is looked for in. */
+ containerRef: RefObject<HTMLElement>;
+}
+
+/**
+ * Reveals the column or card a reference names, once the board has drawn it.
+ *
+ * The reference is taken off the view scope and cleared as soon as it is read, so that it fires
+ * once: a pane stores its view scope in the tab's state, and an unconsumed parameter would jump the
+ * board again every time the tab is restored. What it names is then waited for rather than looked
+ * for at once, because the columns are resolved a moment after the board mounts, a grouping switch
+ * takes another round, and a long column draws only the slice of cards around what is in view.
+ */
+export function useBoardReference({
+ noteId, noteContext, api, viewConfig, groupBy, setGroupBy, columns, includeArchived,
+ selectColumn, containerRef
+}: BoardReferenceOptions) {
+ const target = useRef<BoardReferenceTarget | null>(null);
+ /** The grouping a column reference has already asked for, so the switch is requested once. */
+ const switchedTo = useRef<string | null>(null);
+
+ // No dependency list: the reference is settled against whatever the board has drawn so far, and
+ // every render is a chance that what it names is now there.
+ useEffect(() => {
+ const viewScope = noteContext?.viewScope;
+ if (viewScope?.column || viewScope?.card) {
+ target.current = viewScope.column
+ ? { board: noteId, kind: "column", id: viewScope.column }
+ : { board: noteId, kind: "card", noteId: viewScope.card ?? "" };
+ switchedTo.current = null;
+ viewScope.column = undefined;
+ viewScope.card = undefined;
+ }
+
+ const pending = target.current;
+ if (pending && pending.board !== noteId) {
+ target.current = null;
+ return;
+ }
+
+ if (!pending || !columns || !containerRef.current) {
+ return;
+ }
+
+ const settled = pending.kind === "column"
+ ? settleColumn(pending.id)
+ : settleCard(pending.noteId);
+ if (settled) {
+ target.current = null;
+ }
+ });
+
+ /** @returns whether the reference is done with, a report of its own counting as done. */
+ function settleColumn(id: string) {
+ const found = findColumnById(viewConfig, id);
+ if (!found) {
+ toast.showMessage(t("board_view.reference-column-missing"), undefined, "bx bx-columns");
+ return true;
+ }
+
+ // The column belongs to another grouping, so the board is switched to it and the reference
+ // settled on the round that follows. Asked for once: the label takes a moment to come back
+ // through froca, and every render in between would ask again.
+ if (found.groupBy !== groupBy) {
+ if (switchedTo.current !== found.groupBy) {
+ switchedTo.current = found.groupBy;
+ setGroupBy(found.groupBy);
+ }
+ return false;
+ }
+
+ if (!columns?.includes(found.value)) {
+ reportMissing(api.isColumnArchived(found.value), "bx bx-columns");
+ return true;
+ }
+
+ revealColumn(found.value);
+ return true;
+ }
+
+ /** @returns whether the reference is done with. */
+ function settleCard(noteId: string) {
+ const column = api.getCardColumn(noteId);
+ if (column === undefined) {
+ const note = froca.getNoteFromCache(noteId);
+ reportMissing(!!note?.isArchived, "bx bx-card");
+ return true;
+ }
+
+ // A collapsed column keeps its cards in the page without drawing them, so the card is
+ // focusable before it can be seen. The column is peeked open rather than stored as open:
+ // the reader is being shown one card, not rearranging the board.
+ if (api.isColumnCollapsed(column)) {
+ selectColumn(column);
+ }
+
+ const index = api.getColumnNoteIds(column).indexOf(noteId);
+ revealCard(noteId, column, Math.max(index, 0));
+ return true;
+ }
+
+ /** Says why what a reference names is not on the board, which is usually that it is archived. */
+ function reportMissing(isArchived: boolean, icon: string) {
+ toast.showMessage(
+ isArchived && !includeArchived
+ ? t("board_view.reference-archived")
+ : t("board_view.reference-missing"),
+ undefined,
+ icon);
+ }
+
+ function revealColumn(value: string) {
+ if (api.isColumnCollapsed(value)) {
+ selectColumn(value);
+ }
+
+ waitFor(() => {
+ const column = containerRef.current?.querySelector<HTMLElement>(
+ `.board-column[data-column="${quoteForSelector(value)}"]`);
+ // Waited for open rather than focused where it stands: focus arriving on a column that
+ // is not yet the active one closes the peek just asked for (see Column#handleFocusIn).
+ if (!column || column.classList.contains("collapsed")) {
+ return null;
+ }
+
+ return column.querySelector<HTMLElement>("h3");
+ }, reveal);
+ }
+
+ function revealCard(noteId: string, column: string, index: number) {
+ waitFor(
+ () => {
+ const container = containerRef.current;
+ const card = findCardElement(container, noteId);
+ if (!card && container) {
+ // The card sits outside the slice a long column draws, so the column is asked
+ // to draw it before there is anything to reveal.
+ askForCard(container, column, index);
+ }
+
+ return card;
+ },
+ reveal);
+ }
+}
+
+/** Puts what a reference names in view and on the focus, which is how it is picked out. */
+function reveal(element: HTMLElement) {
+ element.focus({ preventScroll: true });
+ element.scrollIntoView({ block: "center", inline: "center", behavior: "smooth" });
+}
+
+/**
+ * Runs `find` each frame until it answers with an element, for at most {@link REVEAL_TRIES} frames.
+ *
+ * The board draws the columns a moment after it mounts, and a windowed column draws a card a frame
+ * after it is asked to, so what a reference names is rarely in the page on the first look.
+ */
+function waitFor(
+ find: () => HTMLElement | null, then: (element: HTMLElement) => void, tries = REVEAL_TRIES
+) {
+ const found = find();
+ if (found) {
+ then(found);
+ return;
+ }
+
+ if (tries > 0) {
+ requestAnimationFrame(() => waitFor(find, then, tries - 1));
+ }
+}
+
+/** Found by the note it stands for rather than by where it sits, as the keyboard walk finds it. */
+function findCardElement(container: HTMLElement | null, noteId: string) {
+ return container?.querySelector<HTMLElement>(`.board-note[data-note-id="${noteId}"]`) ?? null;
+}
+
+/**
+ * A column value as a quoted attribute selector can carry it. Column values are user text, and a
+ * quote or a backslash in one would end the selector's string rather than fail to match.
+ */
+function quoteForSelector(value: string) {
+ return value.replace(/[\\"]/g, "\\$&");
+}
diff --git a/packages/commons/src/lib/board_columns.spec.ts b/packages/commons/src/lib/board_columns.spec.ts
index a8a8f1cf9c..cfce377265 100644
--- a/packages/commons/src/lib/board_columns.spec.ts
+++ b/packages/commons/src/lib/board_columns.spec.ts
@@ -1,7 +1,8 @@
import { describe, expect, it } from "vitest";
import {
- boardColumnsKey, DEFAULT_BOARD_GROUP_BY, isBoardColumnsKey, normalizeBoardGroupBy
+ boardColumnsKey, boardGroupByFromColumnsKey, DEFAULT_BOARD_GROUP_BY, isBoardColumnsKey,
+ normalizeBoardGroupBy
} from "./board_columns.js";
describe("boardColumnsKey", () => {
@@ -43,3 +44,23 @@ describe("isBoardColumnsKey", () => {
expect(isBoardColumnsKey("templates")).toBe(false);
});
});
+
+describe("boardGroupByFromColumnsKey", () => {
+ it("names the grouping a stored column list belongs to", () => {
+ expect(boardGroupByFromColumnsKey("columns")).toBe(DEFAULT_BOARD_GROUP_BY);
+ expect(boardGroupByFromColumnsKey("priorityViewColumns")).toBe("priority");
+ expect(boardGroupByFromColumnsKey("~assigneeViewColumns")).toBe("~assignee");
+ });
+
+ it("answers with nothing for a key holding something else", () => {
+ for (const key of [ "templates", "ViewColumns", "filterQuery", "" ]) {
+ expect(boardGroupByFromColumnsKey(key), key).toBeUndefined();
+ }
+ });
+
+ it("round-trips every grouping through boardColumnsKey", () => {
+ for (const groupBy of [ DEFAULT_BOARD_GROUP_BY, "priority", "~assignee" ]) {
+ expect(boardGroupByFromColumnsKey(boardColumnsKey(groupBy)), groupBy).toBe(groupBy);
+ }
+ });
+});
diff --git a/packages/commons/src/lib/board_columns.ts b/packages/commons/src/lib/board_columns.ts
index 6c76cb4e13..282ddbc482 100644
--- a/packages/commons/src/lib/board_columns.ts
+++ b/packages/commons/src/lib/board_columns.ts
@@ -29,3 +29,18 @@ export function boardColumnsKey(groupBy: string | undefined | null): BoardColumn
export function isBoardColumnsKey(key: string): boolean {
return key.endsWith("ViewColumns") && key.length > "ViewColumns".length;
}
+
+/**
+ * Which grouping a `board.json` key holds the columns of, or nothing where it holds none.
+ *
+ * The reverse of {@link boardColumnsKey}, for reading a board's stored columns without knowing
+ * which grouping they belong to: a column reference names a column alone, and the board has to
+ * find which of its groupings owns it.
+ */
+export function boardGroupByFromColumnsKey(key: string): string | undefined {
+ if (key === "columns") {
+ return DEFAULT_BOARD_GROUP_BY;
+ }
+
+ return isBoardColumnsKey(key) ? key.slice(0, -"ViewColumns".length) : undefined;
+}