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
fix(collections/board): new column not rendering until the view is re-entered, closes #10689
Elian Doranb892da1f54cd
diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.tsnew file mode 100644index 0000000000..53f1e4e2a5--- /dev/null+++ b/apps/client/src/widgets/collections/board/api.spec.ts@@ -0,0 +1,72 @@+import { describe, expect, it, vi } from "vitest";++import FNote from "../../../entities/fnote";+import { buildNote } from "../../../test/easy-froca";+import { BoardViewData } from ".";+import BoardApi from "./api";++vi.mock("../../../services/bulk_action", () => ({+ executeBulkActions: vi.fn(async () => {})+}));++function createApi(viewConfig: BoardViewData, columns: string[], parentNote?: FNote) {+ const saved: BoardViewData[] = [];+ const api = new BoardApi(+ new Map(),+ columns,+ parentNote ?? buildNote({ title: "Board" }),+ "status",+ viewConfig,+ (newConfig) => saved.push(newConfig),+ () => {}+ );+ return { api, saved };+}++describe("BoardApi column mutations", () => {+ /**+ * #10689: the view re-renders off the identity of the config object it is handed+ * (`useEffect(refresh, [ …, viewConfig ])`). A mutator that edits the config in place and saves+ * the same reference persists the change but never redraws the board.+ */+ it("hands the caller a new config object rather than mutating in place", async () => {+ const viewConfig: BoardViewData = { columns: [ { value: "To Do" }, { value: "Done" } ] };+ const { api, saved } = createApi(viewConfig, [ "To Do", "Done" ]);++ await api.addNewColumn("In Progress");+ await api.renameColumn("Done", "Shipped");+ await api.removeColumn("To Do");++ expect(saved).toHaveLength(3);+ for (const config of saved) {+ expect(config).not.toBe(viewConfig);+ expect(config.columns).not.toBe(viewConfig.columns);+ }+ expect(saved.map(config => config.columns?.map(col => col.value))).toEqual([+ [ "To Do", "Done", "In Progress" ],+ [ "To Do", "Shipped", "In Progress" ],+ [ "Shipped", "In Progress" ]+ ]);+ });++ it("does not save anything for a duplicate column", async () => {+ const { api, saved } = createApi({ columns: [ { value: "To Do" } ] }, [ "To Do" ]);+ expect(await api.addNewColumn("To Do")).toBe(false);+ expect(saved).toHaveLength(0);+ });++ /**+ * #10689 (second symptom): `columns` is derived render state, so it can lag behind the persisted+ * config. Rebuilding the whole config from it drops every column it has not caught up with.+ */+ it("preserves persisted columns missing from the derived column list", () => {+ const { api, saved } = createApi(+ { columns: [ { value: "To Do" }, { value: "Done" }, { value: "In Progress" } ] },+ [ "To Do", "Done" ]+ );++ api.reorderColumn(0, 2);++ expect(saved.at(-1)?.columns?.map(col => col.value)).toEqual([ "Done", "To Do", "In Progress" ]);+ });+});diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.tsindex 525f74d6f1..ef9dc0ca15 100644--- a/apps/client/src/widgets/collections/board/api.ts+++ b/apps/client/src/widgets/collections/board/api.ts@@ -9,7 +9,7 @@ import froca from "../../../services/froca";import { t } from "../../../services/i18n";import note_create from "../../../services/note_create";import server from "../../../services/server";-import { BoardViewData } from ".";+import { BoardColumnData, BoardViewData } from ".";import { ColumnMap } from "./data";export default class BoardApi {@@ -64,19 +64,11 @@ export default class BoardApi {return;}- if (!this.viewConfig) {- this.viewConfig = {};- }-- if (!this.viewConfig.columns) {- this.viewConfig.columns = [];- }+ const columns = this.viewConfig?.columns ?? [];// Add the new column to persisted data if it doesn't exist- const existingColumn = this.viewConfig.columns.find(col => col.value === columnName);- if (existingColumn) return false;- this.viewConfig.columns.push({ value: columnName });- this.saveConfig(this.viewConfig);+ if (columns.some(col => col.value === columnName)) return false;+ this.storeColumns([ ...columns, { value: columnName } ]);return true;}@@ -88,8 +80,7 @@ export default class BoardApi {? { name: "deleteRelation", relationName: this.statusAttribute }: { name: "deleteLabel", labelName: this.statusAttribute };await executeBulkActions(noteIds, [ action ]);- this.viewConfig.columns = (this.viewConfig.columns ?? []).filter(col => col.value !== column);- this.saveConfig(this.viewConfig);+ this.storeColumns((this.viewConfig?.columns ?? []).filter(col => col.value !== column));}async renameColumn(oldValue: string, newValue: string) {@@ -102,12 +93,8 @@ export default class BoardApi {await executeBulkActions(noteIds, [ action ]);// Rename the column in the persisted data.- for (const column of this.viewConfig.columns || []) {- if (column.value === oldValue) {- column.value = newValue;- }- }- this.saveConfig(this.viewConfig);+ this.storeColumns((this.viewConfig?.columns ?? [])+ .map(col => col.value === oldValue ? { ...col, value: newValue } : col));}reorderColumn(fromIndex: number, toIndex: number) {@@ -125,16 +112,27 @@ export default class BoardApi {newColumns.splice(adjustedToIndex, 0, movedColumn);- // Update view config with new column order- const newViewConfig = {- ...this.viewConfig,- columns: newColumns.map(col => ({ value: col }))- };+ // `columns` is derived render state and can lag behind the persisted config (it is rebuilt+ // only once the view re-renders), so anything it hasn't caught up with yet is kept at the+ // end instead of being dropped from the config.+ const missingColumns = (this.viewConfig?.columns ?? []).filter(col => !newColumns.includes(col.value));+ this.storeColumns([ ...newColumns.map(value => ({ value })), ...missingColumns ]);- this.saveConfig(newViewConfig);return newColumns;}+ /**+ * Persists a new column list.+ *+ * The config is always replaced with a fresh object instead of being edited in place: the board+ * re-renders off the identity of the config it was handed, so an in-place edit would be written+ * to disk but stay invisible until the view is re-entered.+ */+ private storeColumns(columns: BoardColumnData[]) {+ this.viewConfig = { ...this.viewConfig, columns };+ this.saveConfig(this.viewConfig);+ }+async insertRowAtPosition(column: string,relativeToBranchId: string,diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsxnew file mode 100644index 0000000000..8e09bb9541--- /dev/null+++ b/apps/client/src/widgets/collections/board/index.spec.tsx@@ -0,0 +1,127 @@+/**+ * Regression test for #10689: a newly added board column is persisted but not rendered until the+ * view is re-entered, and a subsequent column reorder then deletes it again.+ */+import { render } from "preact";+import { useCallback, useState } from "preact/hooks";+import { act } from "preact/test-utils";+import { afterEach, describe, expect, it } from "vitest";++import Component from "../../../components/component";+import { buildNote } from "../../../test/easy-froca";+import { ParentComponent } from "../../react/react_utils";+import BoardView, { BoardViewData } from ".";++/** Drains the async chain inside `refresh()` (getBoardData → setByColumn/setColumns). */+async function flush() {+ await new Promise((resolve) => setTimeout(resolve));+}++const saved: BoardViewData[] = [];++/**+ * Mirrors how `useViewModeConfig` feeds the board: `saveConfig` publishes a *new wrapper* around the+ * config it was handed, so the `viewConfig` prop only changes identity if the caller passed a new+ * object. That is exactly the condition the board's refresh effect depends on.+ */+function Harness({ note, noteIds, initialConfig }: { note: ReturnType<typeof buildNote>, noteIds: string[], initialConfig: BoardViewData }) {+ const [ state, setState ] = useState<{ config: BoardViewData }>({ config: initialConfig });+ const saveConfig = useCallback((config: BoardViewData) => {+ saved.push(config);+ setState({ config });+ }, []);++ return (+ <BoardView+ note={note}+ notePath={`root/${note.noteId}`}+ noteIds={noteIds}+ highlightedTokens={null}+ viewConfig={state.config}+ saveConfig={saveConfig}+ media="screen"+ onReady={() => {}}+ />+ );+}++function columnTitles(container: HTMLElement) {+ return [ ...container.querySelectorAll(".board-column h3 .title") ].map(el => el.textContent);+}++describe("Board column creation", () => {+ let container: HTMLElement | undefined;++ afterEach(() => {+ saved.length = 0;+ if (container) {+ render(null, container);+ container.remove();+ container = undefined;+ }+ });++ async function setup() {+ const note = buildNote({+ title: "Board",+ "#collection": "",+ "#viewType": "board",+ children: [+ { id: "card1", title: "First", "#status": "To Do" },+ { id: "card2", title: "Second", "#status": "Done" }+ ]+ });++ const mountPoint = document.createElement("div");+ container = mountPoint;+ document.body.appendChild(mountPoint);++ await act(async () => {+ render(+ <ParentComponent.Provider value={new Component()}>+ <Harness note={note} noteIds={[ "card1", "card2" ]} initialConfig={{ columns: [ { value: "To Do" }, { value: "Done" } ] }} />+ </ParentComponent.Provider>,+ mountPoint+ );+ });+ await act(async () => {+ await flush();+ });++ return { note, container: mountPoint };+ }++ /** Clicks "Add column", types a name and blurs the editor, as the user would. */+ async function addColumn(container: HTMLElement, name: string) {+ await act(async () => {+ container.querySelector<HTMLElement>(".board-add-column")?.click();+ await flush();+ });++ const input = container.querySelector<HTMLInputElement>(".board-add-column input");+ if (!input) throw new Error("expected an inline editor for the new column");++ await act(async () => {+ input.focus();+ input.value = name;+ input.blur();+ await flush();+ });++ // The save re-publishes the config, which re-runs the (async) board refresh; that lands in a+ // later tick than the one `act` flushed above.+ await act(async () => {+ await flush();+ });+ }++ it("renders a newly added column without leaving the view", async () => {+ const { container } = await setup();+ expect(columnTitles(container)).toEqual([ "To Do", "Done" ]);++ await addColumn(container, "In Progress");++ expect(saved.at(-1)?.columns?.map(c => c.value)).toEqual([ "To Do", "Done", "In Progress" ]);+ expect(columnTitles(container)).toEqual([ "To Do", "Done", "In Progress" ]);+ });+});