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: fix an issue
Adorian Doran87643d15207f
diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.tsindex af46e7a627..dc1770b3cc 100644--- a/apps/client/src/widgets/collections/board/api.spec.ts+++ b/apps/client/src/widgets/collections/board/api.spec.ts@@ -2572,7 +2572,7 @@ describe("references to a board's columns and cards", () => {async () => {const board = buildNote({ title: "Board" });const put = vi.spyOn(server, "put")- .mockResolvedValue({ id: "colOther0001" } as never);+ .mockResolvedValue({ id: "colOther0001", stored: true } as never);const { api, saved } = createApi({ columns: [ { value: "To Do", icon: "bx bx-list-ul" } ] }, [ "To Do" ], board);@@ -2591,7 +2591,8 @@ describe("references to a board's columns and cards", () => {it("names the grouping the column belongs to when asking for an id", async () => {const board = buildNote({ title: "Board" });- const put = vi.spyOn(server, "put").mockResolvedValue({ id: "colHigh00001" } as never);+ const put = vi.spyOn(server, "put")+ .mockResolvedValue({ id: "colHigh00001", stored: true } as never);const { api } = createApi({ columns: [ { value: "To Do", id: "colTodo00001" } ] }, [ "High" ], board,"priority");@@ -2601,6 +2602,21 @@ describe("references to a board's columns and cards", () => {{ groupBy: "priority", value: "High", id: expect.any(String) });});+ /**+ * The server leaves a configuration it cannot read as it stands, so that it can be repaired by+ * hand, and says it stored nothing. The board writes the id out with the rest of what it draws.+ */+ it("stores the id itself when the server reports it stored nothing", async () => {+ vi.spyOn(server, "put")+ .mockResolvedValue({ id: "colOther0001", stored: false } as never);+ const { api, saved } = createApi(+ { columns: [ { value: "To Do", icon: "bx bx-list-ul" } ] }, [ "To Do" ]);++ await expect(api.ensureColumnId("To Do")).resolves.toBe("colOther0001");+ expect(saved.at(-1)?.columns)+ .toEqual([ { value: "To Do", icon: "bx bx-list-ul", id: "colOther0001" } ]);+ });+/** 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(() => {});diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.tsindex 20feb91d33..e3cd7af46a 100644--- a/apps/client/src/widgets/collections/board/api.ts+++ b/apps/client/src/widgets/collections/board/api.ts@@ -817,7 +817,8 @@ export default class BoardApi {* 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.+ * arrived first, and says whether it stored it: a configuration the server cannot read is left+ * for the board to write out again from here.*/async ensureColumnId(column: string) {const stored = readColumnId(this.viewConfig, this.groupBy, column);@@ -827,9 +828,13 @@ export default class BoardApi {const id = newColumnId();try {- const settled = await server.put<{ id: string }>(+ const settled = await server.put<{ id: string, stored: boolean }>(`notes/${this.parentNote.noteId}/board/column-id`,{ groupBy: this.groupBy, value: column, id });+ if (settled && !settled.stored) {+ this.updateColumn(column, { id: settled.id });+ }+return settled?.id ?? id;} catch (e) {// The link still works for as long as nothing else claims the column, and the boarddiff --git a/packages/trilium-core/src/routes/api/board.spec.ts b/packages/trilium-core/src/routes/api/board.spec.tsindex acc476801e..f1eb3a7946 100644--- a/packages/trilium-core/src/routes/api/board.spec.ts+++ b/packages/trilium-core/src/routes/api/board.spec.ts@@ -125,12 +125,12 @@ describe("Board API (core)", () => {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 }>(+ const res = await api.put<{ id: string, stored: boolean }>(`/api/notes/${board.noteId}/board/column-id`,{ body: { value: "Beta", id: "colBeta00001" } });expect(res.status).toBe(200);- expect(res.body.id).toBe("colBeta00001");+ expect(res.body).toMatchObject({ id: "colBeta00001", stored: true });expect(configOf(board.noteId).columns).toEqual([{ value: "Alpha" },{ value: "Beta", color: "#ff0000", id: "colBeta00001" }@@ -142,12 +142,12 @@ describe("Board API (core)", () => {await api.put(`/api/notes/${board.noteId}/board/column-id`,{ body: { value: "Alpha", id: "colFirst0001" } });- const res = await api.put<{ id: string }>(+ const res = await api.put<{ id: string, stored: boolean }>(`/api/notes/${board.noteId}/board/column-id`,{ body: { value: "Alpha", id: "colSecond001" } });expect(res.status).toBe(200);- expect(res.body.id).toBe("colFirst0001");+ expect(res.body).toMatchObject({ id: "colFirst0001", stored: true });expect(configOf(board.noteId).columns?.[0].id).toBe("colFirst0001");});@@ -178,6 +178,33 @@ describe("Board API (core)", () => {expect(configOf(board.noteId).columns?.some(column => column.id)).toBe(false);});+ /**+ * `board.json` is the only place a column id is kept, so an id reported as stored when it+ * was not would hand the client a link that resolves to nothing. Saying so sends the client+ * to write the id itself, with the rest of the configuration the board is drawing.+ */+ it("says it stored nothing for a configuration it cannot read", async () => {+ // A board of its own per case: an attachment is added rather than replaced, and the+ // first one with the title is the one that is read.+ for (const content of [ "{ truncated", "null", "[]", "42" ]) {+ const board = await createTextNote(api, { title: "Board" });+ await api.post(`/api/notes/${board.noteId}/attachments`, {+ body: {+ title: "board.json", role: "viewConfig", mime: "application/json", content+ }+ });++ const res = await api.put<{ id: string, stored: boolean }>(+ `/api/notes/${board.noteId}/board/column-id`,+ { body: { value: "Alpha", id: "colAlpha0001" } });++ expect(res.status, content).toBe(200);+ expect(res.body, content).toMatchObject({ id: "colAlpha0001", stored: false });+ // Left as it was, so it can still be repaired by hand.+ expect(attachmentOf(board.noteId), content).toBe(content);+ }+ });+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));@@ -240,6 +267,12 @@ describe("Board API (core)", () => {return JSON.parse(attachment?.getContent().toString() ?? "{}");}+ /** The raw content of `board.json`, for a configuration no parser should be handed. */+ function attachmentOf(boardId: string) {+ return becca.getNoteOrThrow(boardId).getAttachmentByTitle("board.json")+ ?.getContent().toString();+ }+function storedColumns(boardId: string) {return configOf(boardId).columns.map(column => column.value);}diff --git a/packages/trilium-core/src/routes/api/board.ts b/packages/trilium-core/src/routes/api/board.tsindex 7cbf69fc5d..8d76478925 100644--- a/packages/trilium-core/src/routes/api/board.ts+++ b/packages/trilium-core/src/routes/api/board.ts@@ -164,7 +164,9 @@ function renameInConfig(* 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.+ * @returns the id the column now holds, which is the caller's only when it arrived first, and+ * whether it was stored. An unreadable configuration is not overwritten here, so the+ * client is told to write the id itself along with the rest of what the board is drawing.*/function ensureColumnId(req: Request<{ noteId: string }>) {const { groupBy, value, id } = req.body as EnsureColumnIdRequest;@@ -183,19 +185,18 @@ function ensureColumnId(req: Request<{ noteId: string }>) {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 parsed = parseConfig(attachment.getContent().toString());+ if (!parsed) {+ return { id, stored: false };}++ config = parsed;}const columns = config[columnsKey] ?? [];const stored = columns.find(column => column.value === value);if (typeof stored?.id === "string" && stored.id) {- return { id: stored.id };+ return { id: stored.id, stored: true };}const written = stored@@ -210,7 +211,32 @@ function ensureColumnId(req: Request<{ noteId: string }>) {content: JSON.stringify({ ...config, [columnsKey]: written })}, "title");- return { id };+ return { id, stored: true };+}+++/**+ * Reads `board.json` for {@link ensureColumnId}, or nothing where it cannot be made sense of.+ *+ * An unreadable configuration is left as it stands rather than replaced with one holding only this+ * column, so that it can still be repaired by hand. `ensureColumnId` reports it as unstored, and+ * the client writes the id with the rest of the configuration the board is drawing.+ */+function parseConfig(content: string): Partial<Record<BoardColumnsKey, StoredColumn[]>> | undefined {+ let parsed: unknown;+ try {+ parsed = JSON.parse(content);+ } catch {+ return undefined;+ }++ // `JSON.parse` returns null, a number or an array for content that is valid JSON without being+ // a configuration, none of which the columns can be read off.+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {+ return undefined;+ }++ return parsed as Partial<Record<BoardColumnsKey, StoredColumn[]>>;}export default {