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: prevent a column to be renamed if that name is already used by another column
Adorian Doran402a827091ae
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 5a3ec68ac3..538c74992d 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3494,6 +3494,7 @@"change-note-icon": "Change icon","column-menu": "Column menu","column-already-exists": "This column already exists on the board.",+ "column-name-taken": "The column named “{{- column}}” already exists.","column-definition-save-error": "The columns were saved on the board, but could not be saved to the status attribute.","save-error": "The change could not be saved.","hints": {diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.tsindex ffe8f24470..97e88f7e95 100644--- a/apps/client/src/widgets/collections/board/api.spec.ts+++ b/apps/client/src/widgets/collections/board/api.spec.ts@@ -1883,6 +1883,62 @@ describe("renaming a column that names itself", () => {});});+describe("renaming a column to a name already taken", () => {+ /**+ * A column is identified by the name its cards carry, so writing another column's name over it+ * would merge the two. The rename is refused and reported instead.+ */+ it("refuses the rename, says so and leaves both columns alone", async () => {+ const { api, saved } = createApi(+ { columns: [ { value: "To Do" }, { value: "Done" } ] }, [ "To Do", "Done" ]);+ const put = vi.spyOn(server, "put").mockResolvedValue(undefined);+ const message = vi.spyOn(toast, "showMessage").mockReturnValue(undefined);++ expect(await api.setColumnTitle("To Do", "Done")).toBe(false);++ expect(message).toHaveBeenCalledWith(+ "board_view.column-name-taken", undefined, "bx bx-duplicate");+ expect(put).not.toHaveBeenCalled();+ expect(saved).toEqual([]);+ });++ /**+ * The name a column is known by, not only the value its cards carry: the inbox has no value+ * and is named by `displayName`, so a second column under that name reads as a duplicate.+ */+ it("counts a column with no cards yet, and the name the inbox goes by", async () => {+ const { api, saved } = createApi(+ {+ columns: [+ { value: "", displayName: "Unsorted" },+ { value: "To Do" },+ { value: "Done" }+ ]+ },+ // "Done" is stored but holds no cards, so the board does not derive it.+ [ "", "To Do" ]+ );+ vi.spyOn(server, "put").mockResolvedValue(undefined);+ vi.spyOn(toast, "showMessage").mockReturnValue(undefined);++ expect(await api.setColumnTitle("To Do", "Done")).toBe(false);+ expect(await api.setColumnTitle("To Do", "Unsorted")).toBe(false);+ expect(await api.setColumnTitle("", "Done")).toBe(false);+ expect(saved).toEqual([]);+ });++ it("takes a free name, and a column keeping the one it has", async () => {+ const { api } = createApi(+ { columns: [ { value: "To Do" }, { value: "Done" } ] }, [ "To Do", "Done" ]);+ const put = vi.spyOn(server, "put").mockResolvedValue(undefined);++ await api.setColumnTitle("To Do", "Doing");+ await api.setColumnTitle("Done", "Done");++ expect(put).toHaveBeenCalledTimes(2);+ });+});+describe("filing a card under the inbox", () => {/*** Landing in the inbox means carrying no value at all. A relation the card takes from elsewherediff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.tsindex fe62cb00ff..b73fca0a45 100644--- a/apps/client/src/widgets/collections/board/api.ts+++ b/apps/client/src/widgets/collections/board/api.ts@@ -561,15 +561,43 @@ export default class BoardApi {* Most columns are identified by the value their cards carry, so renaming writes that value* to every card in the column. The inbox has no value, so it stores a display name instead and* its cards are left untouched.+ *+ * @returns `false` when nothing was written, which keeps the caller's editor open: the name+ * is blank, or another column already uses it and renaming would merge the two.*/- async setColumnTitle(column: string, title: string) {- if (!title.trim()) {- return;+ setColumnTitle(column: string, title: string): false | void | Promise<void> {+ const name = title.trim();+ if (!name) {+ return false;+ }++ if (this.isColumnNameTaken(name, column)) {+ toast.showMessage(t("board_view.column-name-taken", { column: name }), undefined,+ "bx bx-duplicate");+ return false;}return column === INBOX_COLUMN- ? this.updateColumn(column, { displayName: title.trim() })- : this.renameColumn(column, title);+ ? this.updateColumn(column, { displayName: name })+ : this.renameColumn(column, name);+ }++ /**+ * Whether a column other than `except` already uses a name.+ *+ * Checks the columns on the board and the stored ones, so an empty column counts too. Titles+ * are compared as well as values: the inbox is named by `displayName`, which reads as the same+ * name to the user.+ */+ private isColumnNameTaken(name: string, except: string) {+ const values = new Set([ ...this.columns, ...this.storedColumns.map(col => col.value) ]);+ for (const value of values) {+ if (value !== except && (value === name || this.getColumnTitle(value) === name)) {+ return true;+ }+ }++ return false;}/**diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsxindex e6635951b5..536581e754 100644--- a/apps/client/src/widgets/collections/board/index.spec.tsx+++ b/apps/client/src/widgets/collections/board/index.spec.tsx@@ -1471,6 +1471,28 @@ describe("Board column rename", () => {await act(async () => { await flush(); });}+ /**+ * Two columns under one name would be merged by the rename, which a reader who has forgotten+ * the other column does not expect. The name is refused, and the editor stays open on it.+ */+ it("refuses a name another column already has and keeps the editor open", async () => {+ const { container } = await setup();+ const put = vi.spyOn(server, "put").mockResolvedValue(undefined);+ const message = vi.spyOn(toast, "showMessage").mockReturnValue(undefined);++ await renameColumnAt(container, 1, "Done");++ expect(message).toHaveBeenCalledWith(+ "board_view.column-name-taken:{\"column\":\"Done\"}", undefined, "bx bx-duplicate");+ expect(put).not.toHaveBeenCalled();++ const columns = container.querySelectorAll<HTMLElement>(".board-column");+ expect(columns).toHaveLength(3);+ // The column being renamed shows the editor in place of its title.+ expect(columnTitles(container)).toEqual([ "To Do", "Done" ]);+ expect(columns[1].querySelector<HTMLInputElement>("h3 input")?.value).toBe("Done");+ });+/*** The cards, the stored columns and the definition are renamed together by the server, so that* no client reads the board while they disagree and writes the old name back. What the boarddiff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsxindex f4019ed4e4..28e0de6c3b 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -1536,7 +1536,11 @@ export function TitleEditor({}: {currentValue?: string;placeholder?: string;- save: (newValue: string, atStart?: boolean) => void | Promise<void>;+ /**+ * Writes what was typed. Returns `false` to refuse it, which keeps the editor open on what it+ * holds so the reader can correct it.+ */+ save: (newValue: string, atStart?: boolean) => false | void | Promise<void>;dismiss: () => void;isNewItem?: boolean;mode?: "normal" | "multiline" | "relation";@@ -1678,8 +1682,9 @@ export function TitleEditor({// editor opened by a press on the thing it edits, rather than from something focused,// has nowhere to send it, so Enter says here what that blur would have said.const typed = inputRef.current?.value ?? "";- if (e.key === "Enter" && typed.trim() && (typed !== currentValue || isNewItem)) {- commit(typed);+ if (e.key === "Enter" && typed.trim() && (typed !== currentValue || isNewItem)+ && !commit(typed)) {+ return;}dismiss();@@ -1701,7 +1706,10 @@ export function TitleEditor({return;}- commit(value, atStart);+ if (!commit(value, atStart)) {+ input?.focus();+ return;+ }if (handsOver) {hasHandedOver.current = true;@@ -1782,21 +1790,36 @@ export function TitleEditor({}if (!shouldDismiss.current && newValue.trim() && (newValue !== currentValue || isNewItem)) {- commit(newValue);+ if (!commit(newValue)) {+ // The field stays open, so the focus this blur took off it has to come back.+ inputRef.current?.focus();+ return;+ }+dismissOnNextRefreshRef.current = true;} else {dismiss();}};- // The editor is closing either way, and what a save writes has already been put back by- // whatever could not write it; all that is left is to say so rather than to reject unhandled,- // which is what a save reaching nobody used to do.+ /**+ * Saves what was typed and reports whether `save` accepted it.+ *+ * A refusal is reported by `save` itself, which is what knows why it refused. A save that+ * fails later is reported here instead of rejecting unhandled: the editor has closed by then,+ * and whatever could not be written has already been put back.+ */function commit(newValue: string, atStart?: boolean) {- Promise.resolve(save(newValue, atStart)).catch((e) => {+ const outcome = save(newValue, atStart);+ if (outcome === false) {+ return false;+ }++ Promise.resolve(outcome).catch((e) => {console.error("Failed to save what the board editor was given:", e);toast.showError(t("board_view.save-error"));});+ return true;}if (mode !== "relation") {@@ -1908,7 +1931,10 @@ export function TitleEditor({}}onBlur={() => dismiss()}noteIdChanged={(newValue) => {- save(newValue);+ if (newValue && !commit(newValue)) {+ return;+ }+dismiss();}}/>