Skip to content

Build your personal knowledge base with Trilium Notes

client/collections/board: fix an issue

Adorian Doran870ef5cd4efa
diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.ts
index ed2b8bb692..af46e7a627 100644
--- a/apps/client/src/widgets/collections/board/api.spec.ts
+++ b/apps/client/src/widgets/collections/board/api.spec.ts
@@ -2549,60 +2549,84 @@ 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", () => {
+ it("keeps the id a column already has, without asking the server", async () => {
+ const put = vi.spyOn(server, "put");
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");
+ await expect(api.ensureColumnId("To Do")).resolves.toBe("colTodo00001");
+ await expect(api.ensureColumnId("To Do")).resolves.toBe("colTodo00001");
+ expect(put).not.toHaveBeenCalled();
// 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.
+ * all, so the first reference taken of it is what assigns one.
+ *
+ * The server reads and writes `board.json` in one request, so it decides: two clients copying a
+ * reference to the same column at once are both answered with the id that arrived first.
*/
- 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("asks the server to assign an id for a column that has none, and uses its answer",
+ async () => {
+ const board = buildNote({ title: "Board" });
+ const put = vi.spyOn(server, "put")
+ .mockResolvedValue({ id: "colOther0001" } as never);
+ const { api, saved } = createApi(
+ { columns: [ { value: "To Do", icon: "bx bx-list-ul" } ] }, [ "To Do" ], board);
+
+ await expect(api.ensureColumnId("To Do")).resolves.toBe("colOther0001");
+ expect(put).toHaveBeenCalledWith(
+ `notes/${board.noteId}/board/column-id`,
+ { groupBy: "status", value: "To Do", id: expect.any(String) });
+ // The server owns the write, so nothing is stored from here.
+ expect(saved).toEqual([]);
+
+ // The id offered is a fresh one of the right length, and is not what came back.
+ const offered = put.mock.calls.at(-1)?.[1] as { id: string };
+ expect(offered.id).toHaveLength(COLUMN_ID_LENGTH);
+ expect(offered.id).not.toBe("colOther0001");
+ });
- it("writes one grouping's ids under that grouping alone", () => {
+ it("names the grouping the column belongs to when asking for an id", async () => {
const board = buildNote({ title: "Board" });
- const { api, saved } = createApi(
+ const put = vi.spyOn(server, "put").mockResolvedValue({ id: "colHigh00001" } as never);
+ const { api } = 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" } ]);
+ await expect(api.ensureColumnId("High")).resolves.toBe("colHigh00001");
+ expect(put).toHaveBeenCalledWith(`notes/${board.noteId}/board/column-id`,
+ { groupBy: "priority", value: "High", id: expect.any(String) });
});
- 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;
+ /** The link still works for as long as nothing else claims the column. */
+ it("stores the id it generated when the server cannot be reached", async () => {
+ vi.spyOn(console, "error").mockImplementation(() => {});
+ vi.spyOn(server, "put").mockRejectedValue(new Error("offline"));
+ const { api, saved } = createApi(
+ { columns: [ { value: "To Do", icon: "bx bx-list-ul" } ] }, [ "To Do" ]);
- expect(api.getColumnReference("To Do"))
- .toBe(`#root/parent1234/${board.noteId}?column=colTodo00001`);
- expect(api.getCardReference("card00000001"))
- .toBe(`#root/parent1234/${board.noteId}?card=card00000001`);
+ const id = await api.ensureColumnId("To Do");
+ expect(id).toHaveLength(COLUMN_ID_LENGTH);
+ expect(saved.at(-1)?.columns)
+ .toEqual([ { value: "To Do", icon: "bx bx-list-ul", id } ]);
});
+ it("builds the links the menu copies, from the path the pane reached the board by",
+ async () => {
+ 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;
+
+ await expect(api.getColumnReference("To Do"))
+ .resolves.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" });
diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.ts
index 361c1f2bf9..20feb91d33 100644
--- a/apps/client/src/widgets/collections/board/api.ts
+++ b/apps/client/src/widgets/collections/board/api.ts
@@ -807,31 +807,47 @@ export default class BoardApi {
}
/**
- * The id a reference names a column by, storing one where the column has none yet.
+ * The id a reference names a column by, assigning 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.
+ *
+ * The assignment goes through the server, which reads and writes `board.json` in one request.
+ * Two clients copying a reference to the same id-less column would otherwise each generate an
+ * id and the second write would replace the first, breaking the link already copied from it.
+ * The server answers with the id the column actually holds, which is this one only when it
+ * arrived first.
*/
- ensureColumnId(column: string) {
+ async ensureColumnId(column: string) {
const stored = readColumnId(this.viewConfig, this.groupBy, column);
if (stored) {
return stored;
}
const id = newColumnId();
- this.updateColumn(column, { id });
- return id;
+ try {
+ const settled = await server.put<{ id: string }>(
+ `notes/${this.parentNote.noteId}/board/column-id`,
+ { groupBy: this.groupBy, value: column, id });
+ return settled?.id ?? id;
+ } catch (e) {
+ // The link still works for as long as nothing else claims the column, and the board
+ // writes the id out with the rest of the configuration as it draws.
+ console.error("Failed to store the board column id:", e);
+ 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.
+ * Assigning an id to 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));
+ async getColumnReference(column: string) {
+ return columnReference(this.boardNotePath, await this.ensureColumnId(column));
}
/** The link that opens this board on one of its cards, which is named by its own note id. */
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 f7edd45cb6..96a72e3d3d 100644
--- a/apps/client/src/widgets/collections/board/context_menu.spec.ts
+++ b/apps/client/src/widgets/collections/board/context_menu.spec.ts
@@ -255,24 +255,25 @@ describe("Board column context menu", () => {
* 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({ ensureColumnId: () => "colId1234567" } as unknown as BoardApi,
- { canRename: false, isCollapsed: true });
+ const items = openMenu({} as BoardApi, { canRename: false, isCollapsed: true });
expect(items[0]).not.toMatchObject({ kind: "separator" });
expect(items[0]).toMatchObject({ uiIcon: "bx bx-directions" });
});
- it("copies a link to the column, which is what stores an id for it", () => {
+ /** The id is settled by the server, so the link is awaited before it is copied. */
+ it("copies a link to the column once its id has been assigned", async () => {
const copy = vi.spyOn(clipboard, "copyTextWithToast").mockImplementation(() => {});
const api = {
- getColumnReference: (column: string) => `#root/board1234?column=id-of-${column}`
+ getColumnReference: async (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);
+ await entry.handler?.(entry, {} as never);
expect(copy).toHaveBeenCalledWith("#root/board1234?column=id-of-To Do");
});
diff --git a/apps/client/src/widgets/collections/board/context_menu.ts b/apps/client/src/widgets/collections/board/context_menu.ts
index 699c90228a..cb2ba165e0 100644
--- a/apps/client/src/widgets/collections/board/context_menu.ts
+++ b/apps/client/src/widgets/collections/board/context_menu.ts
@@ -77,7 +77,7 @@ export function openColumnContextMenu(api: Api, event: ContextMenuEvent, column:
{
title: t("board_view.copy-reference"),
uiIcon: "bx bx-directions",
- handler: () => copyTextWithToast(api.getColumnReference(column.value))
+ handler: async () => copyTextWithToast(await api.getColumnReference(column.value))
}
];
diff --git a/packages/trilium-core/src/routes/api/board.spec.ts b/packages/trilium-core/src/routes/api/board.spec.ts
index 0a08d9d648..acc476801e 100644
--- a/packages/trilium-core/src/routes/api/board.spec.ts
+++ b/packages/trilium-core/src/routes/api/board.spec.ts
@@ -115,6 +115,82 @@ describe("Board API (core)", () => {
expect(configOf(board.noteId).columns).toEqual([ { value: "High", color: "#ff0000" } ]);
});
+ /**
+ * A column reference names a column by an id rather than by the value its cards carry, which a
+ * rename rewrites. Assigning the id here rather than in the client is what settles a race: two
+ * clients copying a reference to the same column each offer an id, and both are answered with
+ * the one that arrived first.
+ */
+ describe("assigning a column its reference id", () => {
+ it("assigns the offered id to a column that has none, keeping what it holds", async () => {
+ const board = await buildBoard([ "Alpha", "Beta" ]);
+
+ const res = await api.put<{ id: string }>(
+ `/api/notes/${board.noteId}/board/column-id`,
+ { body: { value: "Beta", id: "colBeta00001" } });
+
+ expect(res.status).toBe(200);
+ expect(res.body.id).toBe("colBeta00001");
+ expect(configOf(board.noteId).columns).toEqual([
+ { value: "Alpha" },
+ { value: "Beta", color: "#ff0000", id: "colBeta00001" }
+ ]);
+ });
+
+ it("answers with the id a column already has, ignoring the one offered", async () => {
+ const board = await buildBoard([ "Alpha" ]);
+ await api.put(`/api/notes/${board.noteId}/board/column-id`,
+ { body: { value: "Alpha", id: "colFirst0001" } });
+
+ const res = await api.put<{ id: string }>(
+ `/api/notes/${board.noteId}/board/column-id`,
+ { body: { value: "Alpha", id: "colSecond001" } });
+
+ expect(res.status).toBe(200);
+ expect(res.body.id).toBe("colFirst0001");
+ expect(configOf(board.noteId).columns?.[0].id).toBe("colFirst0001");
+ });
+
+ /** A column drawn from the definition or from its cards has no stored entry to hold an id. */
+ it("writes an entry for a column the configuration does not list", async () => {
+ const board = await buildBoard([ "Alpha", "Beta" ]);
+
+ const res = await api.put<{ id: string }>(
+ `/api/notes/${board.noteId}/board/column-id`,
+ { body: { value: "Gamma", id: "colGamma0001" } });
+
+ expect(res.status).toBe(200);
+ expect(configOf(board.noteId).columns).toEqual([
+ { value: "Alpha" },
+ { value: "Beta", color: "#ff0000" },
+ { value: "Gamma", id: "colGamma0001" }
+ ]);
+ });
+
+ it("writes into the column list of the grouping it is given", async () => {
+ const board = await buildBoard([ "Alpha" ]);
+
+ await api.put(`/api/notes/${board.noteId}/board/column-id`,
+ { body: { groupBy: "priority", value: "High", id: "colHigh00001" } });
+
+ expect(configOf(board.noteId).priorityViewColumns)
+ .toEqual([ { value: "High", id: "colHigh00001" } ]);
+ expect(configOf(board.noteId).columns?.some(column => column.id)).toBe(false);
+ });
+
+ it("refuses a blank id and a missing column, without writing anything", async () => {
+ const board = await buildBoard([ "Alpha" ]);
+ const before = JSON.stringify(configOf(board.noteId));
+
+ for (const body of [ { value: "Alpha", id: " " }, { id: "colAlpha0001" } ]) {
+ const res = await api.put(`/api/notes/${board.noteId}/board/column-id`, { body });
+ expect(res.status, JSON.stringify(body)).toBe(400);
+ }
+
+ expect(JSON.stringify(configOf(board.noteId))).toBe(before);
+ });
+ });
+
/** 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" });
@@ -157,7 +233,7 @@ describe("Board API (core)", () => {
return definition.split("options=")[1]?.split(";") ?? [];
}
- type StoredColumns = { value: string, color?: string, icon?: string }[];
+ type StoredColumns = { value: string, color?: string, icon?: string, id?: string }[];
function configOf(boardId: string): Record<string, StoredColumns> & { columns: StoredColumns } {
const attachment = becca.getNoteOrThrow(boardId).getAttachmentByTitle("board.json");
diff --git a/packages/trilium-core/src/routes/api/board.ts b/packages/trilium-core/src/routes/api/board.ts
index 0cf5ad6f6c..7cbf69fc5d 100644
--- a/packages/trilium-core/src/routes/api/board.ts
+++ b/packages/trilium-core/src/routes/api/board.ts
@@ -19,6 +19,15 @@ interface RenameColumnRequest {
newValue: string;
}
+interface EnsureColumnIdRequest {
+ /** Which grouping's column list the column belongs to, as `#board:groupBy` writes it. */
+ groupBy?: string;
+ /** The value the column's cards carry, which is what identifies it in the stored list. */
+ value: string;
+ /** The id to assign if the column has none yet, generated by the client. */
+ id: string;
+}
+
/** One column as the board stores it, which holds what it is drawn with as well as its value. */
interface StoredColumn {
value: string;
@@ -147,6 +156,64 @@ function renameInConfig(
return renamed;
}
+/**
+ * Assigns a reference id to a board column, or returns the one it already has.
+ *
+ * Two clients that copy a reference to the same id-less column each generate an id of their own.
+ * Written from the client, the second write would replace the first id and break the link already
+ * copied from it. Read and written here inside one request, the first id to arrive is the one the
+ * column keeps, and the second client is answered with that same id.
+ *
+ * @returns the id the column now holds, which is the caller's only when it arrived first.
+ */
+function ensureColumnId(req: Request<{ noteId: string }>) {
+ const { groupBy, value, id } = req.body as EnsureColumnIdRequest;
+
+ if (typeof value !== "string") {
+ throw new ValidationError("The column the id belongs to is required.");
+ }
+
+ if (!id?.trim()) {
+ throw new ValidationError("A column id cannot be empty.");
+ }
+
+ const board = becca.getNoteOrThrow(req.params.noteId);
+ const columnsKey = boardColumnsKey(groupBy);
+ const attachment = board.getAttachmentByTitle(CONFIG_ATTACHMENT);
+
+ let config: Partial<Record<BoardColumnsKey, StoredColumn[]>> = {};
+ if (attachment) {
+ try {
+ config = JSON.parse(attachment.getContent().toString());
+ } catch {
+ // A configuration that cannot be read is left as it is, and the caller keeps the id
+ // it generated: the board writes the whole configuration out again as it draws.
+ return { id };
+ }
+ }
+
+ const columns = config[columnsKey] ?? [];
+ const stored = columns.find(column => column.value === value);
+ if (typeof stored?.id === "string" && stored.id) {
+ return { id: stored.id };
+ }
+
+ const written = stored
+ ? columns.map(column => column === stored ? { ...column, id } : column)
+ : [ ...columns, { value, id } ];
+
+ board.saveAttachment({
+ title: CONFIG_ATTACHMENT,
+ role: attachment?.role ?? "viewConfig",
+ mime: attachment?.mime ?? "application/json",
+ position: attachment?.position,
+ content: JSON.stringify({ ...config, [columnsKey]: written })
+ }, "title");
+
+ return { id };
+}
+
export default {
- renameColumn
+ renameColumn,
+ ensureColumnId
};
diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.ts
index 37cac188b8..2a1df91547 100644
--- a/packages/trilium-core/src/routes/index.ts
+++ b/packages/trilium-core/src/routes/index.ts
@@ -300,6 +300,7 @@ export function buildSharedApiRoutes({ route, asyncRoute, asyncRouteWithoutTrans
apiRoute(PST, "/api/sql/execute/:noteId", sqlRoute.execute);
apiRoute(PUT, "/api/notes/:noteId/board/rename-column", boardRoute.renameColumn);
+ apiRoute(PUT, "/api/notes/:noteId/board/column-id", boardRoute.ensureColumnId);
apiRoute(PST, "/api/bulk-action/execute", bulkActionRoute.execute);
apiRoute(PST, "/api/bulk-action/affected-notes", bulkActionRoute.getAffectedNoteCount);