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 empty columns being left behind after renaming/deleting, preserve column order after renaming
Adorian Doran07a9a9d4c2ab
diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.tsindex 86dd1f6ebd..613e37dcb3 100644--- a/apps/client/src/widgets/collections/board/api.spec.ts+++ b/apps/client/src/widgets/collections/board/api.spec.ts@@ -28,6 +28,7 @@ function createApi() {const board = parentNote ?? buildNote({ title: "Board" });const saved: BoardViewData[] = [];+ const pendingRenames = new Map<string, string | undefined>();const api = new BoardApi(new Map(),columns,@@ -36,9 +37,10 @@ function createApi(viewConfig,(newConfig) => saved.push(newConfig),() => {},+ pendingRenames,getStatusDefinition(board, statusAttribute));- return { api, saved };+ return { api, saved, pendingRenames };}describe("BoardApi column mutations", () => {@@ -73,6 +75,37 @@ describe("BoardApi column mutations", () => {expect(saved).toHaveLength(0);});+ it("records what each column it renames away or deletes became", async () => {+ const { api, pendingRenames } = createApi(+ { columns: [ { value: "To Do" }, { value: "Done" } ] },+ [ "To Do", "Done" ]+ );++ await api.renameColumn("Done", "Shipped");+ expect([ ...pendingRenames ]).toEqual([ [ "Done", "Shipped" ] ]);++ await api.removeColumn("To Do");+ expect([ ...pendingRenames ]).toEqual([ [ "Done", "Shipped" ], [ "To Do", undefined ] ]);++ // A name is only held back while its removal is still landing, never against a column the+ // user deliberately creates under it again.+ await api.addNewColumn("To Do");+ expect([ ...pendingRenames ]).toEqual([ [ "Done", "Shipped" ] ]);+ });++ it("follows a rename through when the one before it has not landed yet", async () => {+ const { api, pendingRenames } = createApi({ columns: [ { value: "Done" } ] }, [ "Done" ]);++ await api.renameColumn("Done", "Shipped");+ await api.renameColumn("Shipped", "Delivered");+ expect([ ...pendingRenames ])+ .toEqual([ [ "Done", "Delivered" ], [ "Shipped", "Delivered" ] ]);++ // Renaming back to a name still pending leaves nothing mapping it to itself.+ await api.renameColumn("Delivered", "Done");+ expect([ ...pendingRenames ]).toEqual([ [ "Shipped", "Done" ], [ "Delivered", "Done" ] ]);+ });+/*** #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.diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.tsindex ceb498bdcc..41289ac739 100644--- a/apps/client/src/widgets/collections/board/api.ts+++ b/apps/client/src/widgets/collections/board/api.ts@@ -27,6 +27,7 @@ export default class BoardApi {private viewConfig: BoardViewData,private saveConfig: (newConfig: BoardViewData) => void,private setBranchIdToEdit: (branchId: string | undefined) => void,+ private pendingRenames: Map<string, string | undefined> = new Map(),private statusDefinition?: BoardStatusDefinition) {this.isRelationMode = statusAttribute.startsWith("~");@@ -71,11 +72,14 @@ export default class BoardApi {// Add the new column to persisted data if it doesn't existif (columns.some(col => col.value === columnName)) return false;+ this.pendingRenames.delete(columnName);this.storeColumns([ ...columns, { value: columnName } ]);return true;}async removeColumn(column: string) {+ this.retireColumn(column);+// Remove the value from the notes.const noteIds = this.byColumn?.get(column)?.map(item => item.note.noteId) || [];@@ -87,6 +91,8 @@ export default class BoardApi {}async renameColumn(oldValue: string, newValue: string) {+ this.retireColumn(oldValue, newValue);+const noteIds = this.byColumn?.get(oldValue)?.map(item => item.note.noteId) || [];// Change the value in the notes.@@ -124,6 +130,31 @@ export default class BoardApi {return newColumns;}+ /**+ * Records what a column became, so that `resolveBoardColumns` reads whichever of the notes, the+ * view config and the definition has not been written yet as though it already were. That must+ * be said outright: a value the board just renamed and one added from elsewhere look the same.+ * {@link getBoardData} clears the record once no source lists the old value.+ *+ * @param newValue the name that replaced it, or `undefined` where the column was deleted.+ */+ private retireColumn(oldValue: string, newValue?: string) {+ // A rename of a column whose own rename has not landed yet has to be followed through, or+ // the old value the stale sources still carry would resolve to a name that is itself gone.+ for (const [ from, to ] of this.pendingRenames) {+ if (to === oldValue) {+ this.pendingRenames.set(from, newValue);+ }+ }++ this.pendingRenames.set(oldValue, newValue);+ if (newValue) {+ // Covers a rename back to a name still pending, whose record the loop above just turned+ // into one mapping the name to itself.+ this.pendingRenames.delete(newValue);+ }+ }+/*** Persists a new column list, into the definition the board groups by as well as into the view* config — every column change funnels through here, so the two cannot drift apart.diff --git a/apps/client/src/widgets/collections/board/columns.spec.ts b/apps/client/src/widgets/collections/board/columns.spec.tsindex 9adf7f2650..af234b200c 100644--- a/apps/client/src/widgets/collections/board/columns.spec.ts+++ b/apps/client/src/widgets/collections/board/columns.spec.ts@@ -34,6 +34,34 @@ describe("resolveBoardColumns", () => {expect(resolveBoardColumns([ "", " " ], [ " Todo " ], [ "todo" ])).toEqual([ "Todo", "todo" ]);});++ it("drops a deleted column whichever source still offers it", () => {+ expect(resolveBoardColumns(+ [ "Todo", "Done" ],+ [ "Todo", "Done" ],+ [ "Todo", "Done" ],+ new Map([ [ "Done", undefined ] ])+ )).toEqual([ "Todo" ]);+ });++ it("keeps a renamed column in the slot the old name held", () => {+ expect(resolveBoardColumns(+ [ "To Do", "Doing", "Done" ],+ [ "To Do", "In Progress", "Done" ],+ [ "To Do", "In Progress", "Done" ],+ new Map([ [ "Doing", "In Progress" ] ])+ )).toEqual([ "To Do", "In Progress", "Done" ]);+ });++ it("renames in place in a source that has caught up too, without listing it twice", () => {+ expect(resolveBoardColumns([ "Doing" ], [ "In Progress" ], [ "In Progress" ],+ new Map([ [ "Doing", "In Progress" ] ]))).toEqual([ "In Progress" ]);+ });++ it("substitutes by exact value, so a column differing only in case is untouched", () => {+ expect(resolveBoardColumns([ "Done", "done" ], [], [],+ new Map([ [ "Done", undefined ] ]))).toEqual([ "done" ]);+ });});describe("getStatusDefinition", () => {diff --git a/apps/client/src/widgets/collections/board/columns.ts b/apps/client/src/widgets/collections/board/columns.tsindex 080c398193..9cece1c940 100644--- a/apps/client/src/widgets/collections/board/columns.ts+++ b/apps/client/src/widgets/collections/board/columns.ts@@ -99,17 +99,26 @@ export function canStoreColumnsInDefinition(statusDefinition: BoardStatusDefinit* arranged before it had a definition, or a value a note still holds after the option behind it was* renamed away, both keep their place rather than taking their notes with them. Blank entries are* dropped and the comparison is exact, since two columns differing only in case are two columns.+ *+ * @param pendingRenames what the board has just renamed each column to, or `undefined` where it+ * deleted one. The three sources are written one at a time, and a refresh in+ * between would otherwise resolve the old value back and persist it, past+ * which nothing here can drop it again. Substituted rather than skipped, so a+ * renamed column keeps the slot the old name holds in a source still carrying+ * it, rather than dropping behind every option the definition leads with.*/export function resolveBoardColumns(definitionOptions: string[],persistedColumns: string[],- discoveredValues: string[]+ discoveredValues: string[],+ pendingRenames: ReadonlyMap<string, string | undefined> = new Map()): string[] {const columns: string[] = [];const seen = new Set<string>();for (const candidate of [ ...definitionOptions, ...persistedColumns, ...discoveredValues ]) {- const value = candidate.trim();+ const trimmed = candidate.trim();+ const value = pendingRenames.has(trimmed) ? pendingRenames.get(trimmed) : trimmed;if (!value || seen.has(value)) continue;seen.add(value);columns.push(value);diff --git a/apps/client/src/widgets/collections/board/data.spec.ts b/apps/client/src/widgets/collections/board/data.spec.tsindex d5f05ce2d7..21a05aafe2 100644--- a/apps/client/src/widgets/collections/board/data.spec.ts+++ b/apps/client/src/widgets/collections/board/data.spec.ts@@ -30,4 +30,112 @@ describe("Board data", () => {const noteIds = [...data.byColumn.values()].flat().map(item => item.note.noteId);expect(noteIds.length).toBe(3);});+ /**+ * The notes, the view config and the definition are written one at a time, so a refresh in+ * between reads a source that still offers the old value. Resolution being additive, anything it+ * picks up there is persisted and can never be dropped again, leaving an empty column behind.+ */+ describe("a column being renamed or deleted", () => {+ function buildBoard() {+ return buildNote({+ title: "Board",+ "#collection": "",+ "#viewType": "board",+ children: [+ { title: "First", "#status": "To Do" },+ { title: "Second", "#status": "Shipped" }+ ]+ });+ }++ it("is not resolved back from a definition that has not caught up", async () => {+ const pending = new Map([ [ "Done", "Shipped" ] ]);+ const data = await getBoardData(+ buildBoard(),+ "status",+ { columns: [ { value: "To Do" }, { value: "Shipped" } ] },+ false,+ [ "To Do", "Done" ],+ pending+ );++ expect(data.columns).toEqual([ "To Do", "Shipped" ]);+ expect(data.newPersistedData).toBeUndefined();+ expect([ ...pending.keys() ]).toEqual([ "Done" ]);+ });++ it("is not resolved back from a view config that has not caught up", async () => {+ const pending = new Map([ [ "Done", "Shipped" ] ]);+ const data = await getBoardData(+ buildBoard(),+ "status",+ { columns: [ { value: "To Do" }, { value: "Done" }, { value: "Shipped" } ] },+ false,+ [],+ pending+ );++ expect(data.columns).toEqual([ "To Do", "Shipped" ]);+ expect(data.newPersistedData?.columns?.map(c => c.value)).toEqual([ "To Do", "Shipped" ]);+ });++ it("keeps the renamed column where the old name stood", async () => {+ const board = buildNote({+ title: "Board",+ "#collection": "",+ "#viewType": "board",+ children: [+ { title: "First", "#status": "To Do" },+ { title: "Second", "#status": "In Progress" },+ { title: "Third", "#status": "Done" }+ ]+ });++ const data = await getBoardData(+ board,+ "status",+ { columns: [ { value: "To Do" }, { value: "In Progress" }, { value: "Done" } ] },+ false,+ [ "To Do", "Doing", "Done" ],+ new Map([ [ "Doing", "In Progress" ] ])+ );++ expect(data.columns).toEqual([ "To Do", "In Progress", "Done" ]);+ });++ it("files a card the bulk action has not reached under its new column", async () => {+ const board = buildNote({+ title: "Board",+ "#collection": "",+ "#viewType": "board",+ children: [+ { title: "First", "#status": "Shipped" },+ { title: "Second", "#status": "Done" }+ ]+ });++ const data = await getBoardData(+ board, "status", { columns: [ { value: "Shipped" } ] }, false, [],+ new Map([ [ "Done", "Shipped" ] ])+ );++ expect(data.columns).toEqual([ "Shipped" ]);+ expect(data.byColumn.get("Shipped")?.map(item => item.note.title))+ .toEqual([ "First", "Second" ]);+ });++ it("is forgotten once every source has caught up, so the name can be used again", async () => {+ const pending = new Map([ [ "Done", "Shipped" ] ]);+ await getBoardData(+ buildBoard(),+ "status",+ { columns: [ { value: "To Do" }, { value: "Shipped" } ] },+ false,+ [ "To Do", "Shipped" ],+ pending+ );++ expect(pending.size).toBe(0);+ });+ });});diff --git a/apps/client/src/widgets/collections/board/data.ts b/apps/client/src/widgets/collections/board/data.tsindex 3134bc567e..9cd3a72822 100644--- a/apps/client/src/widgets/collections/board/data.ts+++ b/apps/client/src/widgets/collections/board/data.ts@@ -11,13 +11,16 @@ export type ColumnMap = Map<string, {/*** @param definitionOptions the choices the board's group-by definition offers, empty when it has no* select definition of its own to lead the column order.+ * @param pendingRenames the columns the board is in the middle of renaming or deleting, cleared+ * here once no source lists them any more.*/export async function getBoardData(parentNote: FNote,groupByColumn: string,persistedData: BoardViewData,includeArchived: boolean,- definitionOptions: string[] = []+ definitionOptions: string[] = [],+ pendingRenames: Map<string, string | undefined> = new Map()) {const byColumn: ColumnMap = new Map();@@ -25,7 +28,17 @@ export async function getBoardData(await recursiveGroupBy(parentNote.getChildBranches(), byColumn, groupByColumn, includeArchived, new Set<string>());const persistedColumns = (persistedData.columns ?? []).map(c => c.value);- const columns = resolveBoardColumns(definitionOptions, persistedColumns, [ ...byColumn.keys() ]);+ const discoveredValues = [ ...byColumn.keys() ];+ const columns = resolveBoardColumns(+ definitionOptions, persistedColumns, discoveredValues, pendingRenames);++ // A value no source lists any more has finished being renamed, and holding it back further+ // would only block a column created under the same name.+ prunePendingRenames(pendingRenames, [ definitionOptions, persistedColumns, discoveredValues ]);++ // A card the bulk action has not reached yet is still filed under the old value, and belongs to+ // the column that replaced it rather than to one `columns` no longer lists.+ regroupRenamedCards(byColumn, pendingRenames);// A column the notes have nothing in is still a column, so every resolved one gets an entry.for (const column of columns) {@@ -50,6 +63,29 @@ export async function getBoardData(};}+/** Drops every pending rename whose old value none of the given column sources lists any more. */+function prunePendingRenames(pendingRenames: Map<string, string | undefined>, sources: string[][]) {+ for (const oldValue of [ ...pendingRenames.keys() ]) {+ if (!sources.some(source => source.includes(oldValue))) {+ pendingRenames.delete(oldValue);+ }+ }+}++/** Moves the cards of a renamed column over to its new name, keeping the order they were in. */+function regroupRenamedCards(+ byColumn: ColumnMap,+ pendingRenames: ReadonlyMap<string, string | undefined>+) {+ for (const [ oldValue, newValue ] of pendingRenames) {+ const items = byColumn.get(oldValue);+ if (!items || !newValue) continue;++ byColumn.delete(oldValue);+ byColumn.set(newValue, [ ...(byColumn.get(newValue) ?? []), ...items ]);+ }+}+async function recursiveGroupBy(branches: FBranch[], byColumn: ColumnMap, groupByColumn: string, includeArchived: boolean, seenNoteIds: Set<string>) {for (const branch of branches) {const note = await branch.getNote();diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsxindex 8e09bb9541..16990ef8c5 100644--- a/apps/client/src/widgets/collections/board/index.spec.tsx+++ b/apps/client/src/widgets/collections/board/index.spec.tsx@@ -5,13 +5,30 @@import { render } from "preact";import { useCallback, useState } from "preact/hooks";import { act } from "preact/test-utils";-import { afterEach, describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import Component from "../../../components/component";+import froca from "../../../services/froca";import { buildNote } from "../../../test/easy-froca";import { ParentComponent } from "../../react/react_utils";import BoardView, { BoardViewData } from ".";+// Stands in for the server: by the time the bulk action resolves, the notes carry the new value,+// which is what makes the old column empty rather than merely renamed.+vi.mock("../../../services/bulk_action", () => ({+ executeBulkActions: vi.fn(async (noteIds: string[], actions: { name: string, labelName?: string, labelValue?: string }[]) => {+ for (const noteId of noteIds) {+ for (const attribute of froca.getNoteFromCache(noteId)?.getAttributes() ?? []) {+ for (const action of actions) {+ if (action.name === "updateLabelValue" && attribute.name === action.labelName) {+ attribute.value = action.labelValue ?? "";+ }+ }+ }+ }+ })+}));+/** Drains the async chain inside `refresh()` (getBoardData → setByColumn/setColumns). */async function flush() {await new Promise((resolve) => setTimeout(resolve));@@ -125,3 +142,95 @@ describe("Board column creation", () => {expect(columnTitles(container)).toEqual([ "To Do", "Done", "In Progress" ]);});});++describe("Board column rename", () => {+ 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",+ "#label:status(inheritable)":+ "promoted,alias=Status,single,select,options=To Do;Doing;Done",+ children: [+ { id: "rcard1", title: "First", "#status": "To Do" },+ { id: "rcard2", title: "Second", "#status": "Doing" },+ { id: "rcard3", title: "Third", "#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={[ "rcard1", "rcard2", "rcard3" ]}+ initialConfig={{+ columns: [ { value: "To Do" }, { value: "Doing" }, { value: "Done" } ]+ }}+ />+ </ParentComponent.Provider>,+ mountPoint+ );+ });+ await act(async () => { await flush(); });++ return { note, container: mountPoint };+ }++ /** Renames the middle column, so a slot that is not the last one has to survive. */+ async function renameSecondColumn(container: HTMLElement, newName: string) {+ const column = container.querySelectorAll<HTMLElement>(".board-column")[1];+ await act(async () => {+ column.querySelector<HTMLElement>("h3 .edit-icon")?.click();+ await flush();+ });++ const input = column.querySelector<HTMLInputElement>("h3 input");+ if (!input) throw new Error("expected an inline editor for the column title");++ await act(async () => {+ input.focus();+ input.value = newName;+ input.blur();+ await flush();+ });+ await act(async () => { await flush(); });+ }++ it("does not leave the old name behind as an empty column", async () => {+ const { container } = await setup();+ expect(columnTitles(container)).toEqual([ "To Do", "Doing", "Done" ]);++ await renameSecondColumn(container, "In Progress");++ expect(columnTitles(container)).toEqual([ "To Do", "In Progress", "Done" ]);+ expect(saved.at(-1)?.columns?.map(c => c.value))+ .toEqual([ "To Do", "In Progress", "Done" ]);+ });++ it("keeps the cards of the renamed column under it", async () => {+ const { container } = await setup();++ await renameSecondColumn(container, "In Progress");++ const cards = [ ...container.querySelectorAll<HTMLElement>(".board-column") ]+ .map(column => [ ...column.querySelectorAll(".board-note .title") ]+ .map(el => el.textContent));+ expect(cards).toEqual([ [ "First" ], [ "Second" ], [ "Third" ] ]);+ });+});diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsxindex 2cc303850e..345a602d35 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -109,11 +109,16 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCconst [ columnNameToEdit, setColumnNameToEdit ] = useState<string>();/** Bumped when the definition changes, since it is read off the note rather than held in state. */const [ definitionRevision, setDefinitionRevision ] = useState(0);+ // A ref rather than state: `api` is rebuilt on every refresh, and the map has to outlive those+ // instances to cover a rename (see BoardApi#retireColumn). Mutating it must not re-render.+ const pendingRenamesRef = useRef(new Map<string, string | undefined>());const statusDefinition = useMemo(() => getStatusDefinition(parentNote, statusAttributeWithPrefix),[ parentNote, statusAttributeWithPrefix, definitionRevision ]);const api = useMemo(() => {- return new Api(byColumn, columns ?? [], parentNote, statusAttributeWithPrefix, viewConfig ?? {}, saveConfig, setBranchIdToEdit, statusDefinition );+ return new Api(+ byColumn, columns ?? [], parentNote, statusAttributeWithPrefix, viewConfig ?? {},+ saveConfig, setBranchIdToEdit, pendingRenamesRef.current, statusDefinition);}, [ byColumn, columns, parentNote, statusAttributeWithPrefix, viewConfig, saveConfig, setBranchIdToEdit, statusDefinition ]);// Every member is one of useState's own setters, so this value is built once and never changes// identity -- a drag cannot reach anything that reads only this.@@ -139,7 +144,9 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC}), [ branchIdToEdit, columnNameToEdit, draggedCard, draggedColumn, dropPosition, dropTarget ]);function refresh() {- getBoardData(parentNote, statusAttributeWithPrefix, viewConfig ?? {}, includeArchived, statusDefinition?.options ?? [])+ getBoardData(+ parentNote, statusAttributeWithPrefix, viewConfig ?? {}, includeArchived,+ statusDefinition?.options ?? [], pendingRenamesRef.current).then(({ byColumn, columns, newPersistedData, isInRelationMode }) => {setByColumn(byColumn);setIsRelationMode(isInRelationMode);