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 some issues
Adorian Doran6d6de7cc178e
diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.tsindex 86e6f4ab90..b98812c3ec 100644--- a/apps/client/src/widgets/collections/board/api.spec.ts+++ b/apps/client/src/widgets/collections/board/api.spec.ts@@ -158,8 +158,8 @@ describe("BoardApi column mutations", () => {});/**- * A record left behind by a write that never landed goes on being applied: the column would show- * under a name nothing carries, or stay hidden though it is still there.+ * A record left behind by a write that never landed goes on being applied: the column would+ * show under a name nothing carries, or stay hidden though it is still there.*/it("keeps no record of a rename or a deletion the server refused", async () => {const { api, saved, pendingRenames } = createApi(@@ -189,6 +189,50 @@ describe("BoardApi column mutations", () => {expect([ ...pendingRenames ]).toEqual([ [ "Done", "Shipped" ] ]);});+ /**+ * Two mutations can be in flight at once, so an undo has to take back what its own call did and+ * nothing else: the record of a mutation still running, or one that has already failed, is not+ * this one's to put back.+ */+ it("takes back only its own record when overlapping mutations fail", async () => {+ const { api, pendingRenames } = createApi(+ { columns: [ { value: "To Do" }, { value: "Done" } ] },+ [ "To Do", "Done" ]+ );++ // Both start before either finishes, and both are refused.+ failNextBulkAction();+ failNextBulkAction();+ const first = api.renameColumn("Done", "Shipped");+ const second = api.removeColumn("To Do");++ await expect(first).rejects.toThrow("offline");+ await expect(second).rejects.toThrow("offline");+ expect([ ...pendingRenames ]).toEqual([]);+ });++ it("leaves a mutation still in flight alone when another one fails", async () => {+ const { api, pendingRenames } = createApi(+ { columns: [ { value: "To Do" }, { value: "Done" } ] },+ [ "To Do", "Done" ]+ );++ let releaseSecond = () => {};+ vi.mocked(executeBulkActions).mockRejectedValueOnce(new Error("offline"));+ vi.mocked(executeBulkActions).mockImplementationOnce(+ () => new Promise<void>((resolve) => { releaseSecond = resolve; }));++ const failing = api.renameColumn("Done", "Shipped");+ const running = api.removeColumn("To Do");++ await expect(failing).rejects.toThrow("offline");+ // The deletion is still going; its record must have survived the other one's undo.+ expect([ ...pendingRenames ]).toEqual([ [ "To Do", undefined ] ]);++ releaseSecond();+ await running;+ });+it("follows a rename through when the one before it has not landed yet", async () => {const { api, pendingRenames } = createApi({ columns: [ { value: "Done" } ] }, [ "Done" ]);diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.tsindex 8268892c1b..3b43042315 100644--- a/apps/client/src/widgets/collections/board/api.ts+++ b/apps/client/src/widgets/collections/board/api.ts@@ -172,21 +172,18 @@ export default class BoardApi {* refresh in the middle reads the sources as they are about to be.** Taken back out if the write does not land: left in, a rename nothing carries would keep the- * column under the name it failed to take, and a deletion that failed would keep hiding a column- * that is still there, cards and all. The record is restored rather than merely dropped, since- * {@link retireColumn} may have re-pointed an earlier one that has not landed either.+ * column under the name it failed to take, and a deletion that failed would keep hiding one+ * that is still there, cards and all.*/- private async retiredWhile<T>(oldValue: string, newValue: string | undefined, write: () => Promise<T>) {- const restore = new Map(this.pendingRenames);- this.retireColumn(oldValue, newValue);+ private async retiredWhile<T>(+ oldValue: string, newValue: string | undefined, write: () => Promise<T>+ ) {+ const undoRetirement = this.retireColumn(oldValue, newValue);try {return await write();} catch (e) {- this.pendingRenames.clear();- for (const [ from, to ] of restore) {- this.pendingRenames.set(from, to);- }+ undoRetirement();throw e;}}@@ -198,22 +195,47 @@ export default class BoardApi {* {@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.+ * @returns a function putting back exactly the records this call touched. Restoring a copy of+ * the whole map instead would take back the records of another mutation still in+ * flight, and put back those of one that has already failed.*/private retireColumn(oldValue: string, newValue?: string) {+ const touched: { key: string, previous?: string, wasRecorded: boolean }[] = [];+ const remember = (key: string) => touched.push({+ key,+ previous: this.pendingRenames.get(key),+ // A deletion is recorded as `undefined`, which is not the same as no record at all.+ wasRecorded: this.pendingRenames.has(key)+ });+// 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) {+ remember(from);this.pendingRenames.set(from, newValue);}}+ remember(oldValue);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.+ remember(newValue);this.pendingRenames.delete(newValue);}++ return () => {+ for (const { key, previous, wasRecorded } of touched.reverse()) {+ if (wasRecorded) {+ this.pendingRenames.set(key, previous);+ } else {+ this.pendingRenames.delete(key);+ }+ }+ };}/**diff --git a/apps/client/src/widgets/collections/board/data.spec.ts b/apps/client/src/widgets/collections/board/data.spec.tsindex 98d4f7490f..6222248f97 100644--- a/apps/client/src/widgets/collections/board/data.spec.ts+++ b/apps/client/src/widgets/collections/board/data.spec.ts@@ -61,7 +61,7 @@ describe("Board data", () => {expect(data.columns).toEqual([ "To Do", "Shipped" ]);expect(data.newPersistedData).toBeUndefined();- expect([ ...pending.keys() ]).toEqual([ "Done" ]);+ expect(data.settledRenames).toEqual([]);});it("is not resolved back from a view config that has not caught up", async () => {@@ -172,9 +172,9 @@ describe("Board data", () => {]);});- it("is forgotten once every source has caught up, freeing the name", async () => {+ it("is reported as settled once every source has caught up, freeing the name", async () => {const pending = new Map([ [ "Done", "Shipped" ] ]);- await getBoardData(+ const data = await getBoardData(buildBoard(),"status",{ columns: [ { value: "To Do" }, { value: "Shipped" } ] },@@ -183,7 +183,10 @@ describe("Board data", () => {pending);- expect(pending.size).toBe(0);+ // Reported rather than dropped here: only the caller knows whether the board it asked+ // about is still the one on screen.+ expect(data.settledRenames).toEqual([ "Done" ]);+ expect(pending.size).toBe(1);});});});diff --git a/apps/client/src/widgets/collections/board/data.ts b/apps/client/src/widgets/collections/board/data.tsindex f024727bdf..4f95acef39 100644--- a/apps/client/src/widgets/collections/board/data.ts+++ b/apps/client/src/widgets/collections/board/data.ts@@ -11,8 +11,10 @@ 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.+ * @param pendingRenames the columns the board is in the middle of renaming or deleting. Read+ * only: which of them have landed comes back as `settledRenames`, for the+ * caller to drop once it knows the answer is still about the board it asked+ * about.*/export async function getBoardData(parentNote: FNote,@@ -20,7 +22,7 @@ export async function getBoardData(persistedData: BoardViewData,includeArchived: boolean,definitionOptions: string[] = [],- pendingRenames: Map<string, string | undefined> = new Map()+ pendingRenames: ReadonlyMap<string, string | undefined> = new Map()) {const byColumn: ColumnMap = new Map();@@ -34,7 +36,9 @@ export async function getBoardData(// 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 ]);+ const settledRenames = [ ...pendingRenames.keys() ].filter(oldValue =>+ ![ definitionOptions, persistedColumns, discoveredValues ]+ .some(source => source.includes(oldValue)));// 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.@@ -57,6 +61,7 @@ export async function getBoardData(return {byColumn,columns,+ settledRenames,newPersistedData: hasChanges? {...persistedData,@@ -91,15 +96,6 @@ function indexColumnsByResolvedName(return byName;}-/** 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,diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsxindex ee5528e1b8..5455e508d4 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -116,6 +116,8 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC// 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>());+ /** Names each refresh, so one the board has moved on from is discarded rather than applied. */+ const refreshSeqRef = useRef(0);const statusDefinition = useMemo(() => getStatusDefinition(parentNote, statusAttributeWithPrefix),[ parentNote, statusAttributeWithPrefix, definitionRevision ]);@@ -153,10 +155,21 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC}), [ branchIdToEdit, columnNameToEdit, draggedCard, draggedColumn, dropPosition, dropTarget ]);function refresh() {+ // `getBoardData` reads notes, so refreshes can resolve out of order and one issued for the+ // board the user has left can arrive after the next board's. What it has to say is about+ // sources no longer on screen, the pending renames it reports as settled included.+ const refreshId = ++refreshSeqRef.current;+getBoardData(parentNote, statusAttributeWithPrefix, viewConfig ?? {}, includeArchived,statusDefinition?.options ?? [], pendingRenamesRef.current)- .then(({ byColumn, columns, newPersistedData, isInRelationMode }) => {+ .then(({ byColumn, columns, newPersistedData, isInRelationMode, settledRenames }) => {+ if (refreshId !== refreshSeqRef.current) return;++ for (const settled of settledRenames) {+ pendingRenamesRef.current.delete(settled);+ }+setByColumn(byColumn);setIsRelationMode(isInRelationMode);setColumns(columns);@@ -183,6 +196,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC// refresh below, which is what makes it run first when both fire on the same change.useEffect(() => {pendingRenamesRef.current.clear();+ refreshSeqRef.current++;}, [ parentNote, statusAttributeWithPrefix ]);useEffect(refresh, [ parentNote, noteIds, viewConfig, statusAttributeWithPrefix, statusDefinition ]);