Skip to content

Build your personal knowledge base with Trilium Notes

fix(board): keep a deleted grouping attribute from coming back (closes #12064)

Rowee131aea731e0e85
diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.ts
index 3d29859e19..4ea051409a 100644
--- a/apps/client/src/widgets/collections/board/api.spec.ts
+++ b/apps/client/src/widgets/collections/board/api.spec.ts
@@ -101,7 +101,7 @@ function createApi(
allByColumn,
keepNote
);
- return { api, board, saved, editing, pendingRenames: pending.renames };
+ return { api, board, saved, editing, pending, pendingRenames: pending.renames };
}
/** Cards named by their note id, which is all the operations under test read them for. */
@@ -2166,6 +2166,81 @@ describe("the promoted attributes a card shows", () => {
});
});
+describe("deleting the attribute of a grouping", () => {
+ /**
+ * Left in `board.json`, the columns of a deleted grouping are written back into a new
+ * definition by `syncColumnsToDefinition` once the board groups by it again.
+ */
+ it("drops the stored columns of the grouping once deleted, leaving the rest", async () => {
+ const { api, saved } = createApi({
+ columns: [ { value: "To Do" }, { value: "Done" } ],
+ testViewColumns: [ { value: "A" } ],
+ filterQuery: "#urgent"
+ }, [ "A" ], undefined, "test");
+ const savedDuringDeletion: number[] = [];
+
+ await api.deleteGrouping("status", async () => { savedDuringDeletion.push(saved.length); });
+
+ expect(savedDuringDeletion).toEqual([ 0 ]);
+ expect(saved).toEqual([ { testViewColumns: [ { value: "A" } ], filterQuery: "#urgent" } ]);
+ });
+
+ /**
+ * A refresh that lands while the definition is being deleted still reads the stored columns,
+ * and would write them into a new definition; `pending.inFlight` holds its writes back.
+ */
+ it("counts as a write on the board while the definition is deleted", async () => {
+ const { api, pending, saved } = createApi(
+ { columns: [ { value: "To Do" } ] }, [ "To Do" ]);
+ let inFlightDuringDeletion = 0;
+
+ await api.deleteGrouping("status", async () => {
+ inFlightDuringDeletion = pending.inFlight;
+ });
+
+ expect(inFlightDuringDeletion).toBe(1);
+ expect(saved).toEqual([ {} ]);
+ expect(pending.inFlight).toBe(0);
+ });
+
+ /**
+ * A refresh that started during the deletion reads the old columns, and can resolve after
+ * `pending.inFlight` drops back to 0. `hasStoredSince()` tells the board not to write them.
+ */
+ it("reports the config read before the deletion as replaced, until the board draws the new one",
+ async () => {
+ const config = { columns: [ { value: "To Do" } ] };
+ const { api, board, saved } = createApi(config, [ "To Do" ]);
+ expect(api.hasStoredSince(config)).toBe(false);
+
+ await api.deleteGrouping("status", async () => {});
+ expect(api.hasStoredSince(config)).toBe(true);
+
+ const [ stored ] = saved;
+ api.update(new Map(), [], board, "status", stored, () => {}, () => {});
+ expect(api.hasStoredSince(stored)).toBe(false);
+ });
+
+ it("keeps the columns of a grouping whose deletion failed, and stops counting it", async () => {
+ const { api, pending, saved } = createApi(
+ { columns: [ { value: "To Do" } ] }, [ "To Do" ]);
+
+ await expect(api.deleteGrouping("status", async () => { throw new Error("offline"); }))
+ .rejects.toThrow("offline");
+
+ expect(saved).toEqual([]);
+ expect(pending.inFlight).toBe(0);
+ });
+
+ it("writes nothing for a grouping that stores no columns", async () => {
+ const { api, saved } = createApi({ columns: [ { value: "To Do" } ] }, [ "To Do" ]);
+
+ await api.deleteGrouping("priority", async () => {});
+
+ expect(saved).toEqual([]);
+ });
+});
+
describe("how a column orders its cards", () => {
/** Storing nothing is what takes the board's order, so a fresh column reads as taking it. */
it("reads a column nobody has sorted as taking the board's order", () => {
diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.ts
index f96973b450..842e20fb8d 100644
--- a/apps/client/src/widgets/collections/board/api.ts
+++ b/apps/client/src/widgets/collections/board/api.ts
@@ -30,7 +30,7 @@ import {
DEFAULT_CARD_TEMPLATES, DEFAULT_COLUMN_ICON, DEFAULT_COLUMN_WIDTH, DEFAULT_GROUP_BY, INBOX_COLUMN,
INBOX_COLUMN_ICON, parseColumnWidth
} from "./columns";
-import { readColumns, writeColumns } from "./column_storage";
+import { readColumns, removeColumns, writeColumns } from "./column_storage";
import { cardNotes, ColumnItem, ColumnMap } from "./data";
import {
cardReference, ColumnReferenceLabel, columnReference, newColumnId, readColumnId
@@ -160,6 +160,8 @@ export default class BoardApi {
/** The config as the board last handed it over, against which a fresh one is recognised. */
private viewConfigSource: BoardViewData | undefined;
private viewConfig: BoardViewData;
+ /** `viewConfig` as last taken from the board, before the api stored a config of its own. */
+ private drawnConfig: BoardViewData;
constructor(
private byColumn: ColumnMap | undefined,
@@ -182,6 +184,7 @@ export default class BoardApi {
) {
this.viewConfigSource = viewConfig;
this.viewConfig = viewConfig ?? {};
+ this.drawnConfig = this.viewConfig;
this.groupBy = statusAttribute;
this.isRelationMode = statusAttribute.startsWith("~");
@@ -226,6 +229,7 @@ export default class BoardApi {
if (viewConfig !== this.viewConfigSource) {
this.viewConfigSource = viewConfig;
this.viewConfig = viewConfig ?? {};
+ this.drawnConfig = this.viewConfig;
}
this.saveConfig = saveConfig;
this.setBranchIdToEdit = setBranchIdToEdit;
@@ -583,6 +587,7 @@ export default class BoardApi {
if (renamed?.config) {
this.viewConfig = renamed.config;
this.viewConfigSource = renamed.config;
+ this.drawnConfig = renamed.config;
}
}
@@ -1023,6 +1028,40 @@ export default class BoardApi {
this.storeConfig({ promotedAttributes: storedPromotedAttributes(attributes) });
}
+ /**
+ * Whether the api stored a config after the board drew `config`.
+ *
+ * A refresh resolves its columns from the config of the render that started it. Once this
+ * returns `true`, those columns can be ones the api has since removed, so the refresh must not
+ * write them.
+ */
+ hasStoredSince(config: BoardViewData | undefined) {
+ return config !== this.viewConfigSource || this.viewConfig !== this.drawnConfig;
+ }
+
+ /**
+ * Runs `deletion`, which deletes the attribute a grouping is made from, then drops the columns
+ * stored for that grouping so that `syncColumnsToDefinition()` cannot write them back into a
+ * new definition.
+ *
+ * Counted in `pending.inFlight` while `deletion` runs. A refresh that resolves later still
+ * holds the old config, and `hasStoredSince()` keeps it from writing.
+ */
+ async deleteGrouping(groupBy: string, deletion: () => Promise<void>) {
+ this.pending.inFlight++;
+
+ try {
+ await deletion();
+ const removed = removeColumns(this.viewConfig, groupBy);
+ if (removed) {
+ this.viewConfig = removed;
+ this.saveConfig(removed);
+ }
+ } finally {
+ this.pending.inFlight--;
+ }
+ }
+
/** Sets what the board offers. An empty set would leave nothing to make a card from. */
async setCardTemplateIds(templates: string[]) {
if (!templates.length) {
diff --git a/apps/client/src/widgets/collections/board/column_storage.spec.ts b/apps/client/src/widgets/collections/board/column_storage.spec.ts
index 71bd88b429..89bcb05d8d 100644
--- a/apps/client/src/widgets/collections/board/column_storage.spec.ts
+++ b/apps/client/src/widgets/collections/board/column_storage.spec.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import type { BoardViewData } from ".";
-import { adoptLegacyColumns, readColumns, writeColumns } from "./column_storage";
+import { adoptLegacyColumns, readColumns, removeColumns, writeColumns } from "./column_storage";
const CONFIG: BoardViewData = {
columns: [ { value: "To Do" }, { value: "Done", icon: "bx bx-check" } ],
@@ -55,6 +55,42 @@ describe("writeColumns", () => {
});
});
+describe("removeColumns", () => {
+ it("drops one grouping's columns without touching another's or the rest of the config", () => {
+ const removed = removeColumns(CONFIG, "priority");
+
+ expect(removed).not.toHaveProperty("priorityViewColumns");
+ expect(removed?.columns).toBe(CONFIG.columns);
+ expect(removed?.templates).toBe(CONFIG.templates);
+ expect(CONFIG.priorityViewColumns).toEqual([ { value: "High", color: "#f00" } ]);
+ });
+
+ it("drops the default grouping's columns from the key every board already uses", () => {
+ for (const groupBy of [ "status", "#status" ]) {
+ const removed = removeColumns(CONFIG, groupBy);
+
+ expect(removed, groupBy).not.toHaveProperty("columns");
+ expect(removed?.priorityViewColumns, groupBy).toBe(CONFIG.priorityViewColumns);
+ }
+ });
+
+ it("keeps a relation apart from the label of the same name", () => {
+ const config: BoardViewData = {
+ "priorityViewColumns": [ { value: "High" } ],
+ "~priorityViewColumns": [ { value: "someNoteId" } ]
+ };
+
+ expect(removeColumns(config, "~priority")).toEqual({
+ priorityViewColumns: [ { value: "High" } ]
+ });
+ });
+
+ it("has nothing to write where the grouping stores no columns", () => {
+ expect(removeColumns(CONFIG, "severity")).toBeUndefined();
+ expect(removeColumns(undefined, "status")).toBeUndefined();
+ });
+});
+
describe("adoptLegacyColumns", () => {
/** What a board grouping by something other than the default stored before this key existed. */
const legacy: BoardViewData = {
diff --git a/apps/client/src/widgets/collections/board/column_storage.ts b/apps/client/src/widgets/collections/board/column_storage.ts
index 9c6101e10f..5e14772ad0 100644
--- a/apps/client/src/widgets/collections/board/column_storage.ts
+++ b/apps/client/src/widgets/collections/board/column_storage.ts
@@ -19,6 +19,26 @@ export function writeColumns(
return { ...config, [boardColumnsKey(groupBy)]: columns };
}
+/**
+ * The config without the columns of one grouping, or nothing where it stores none for it.
+ *
+ * Used when the attribute a grouping is made from is deleted: `syncColumnsToDefinition` would
+ * otherwise write the stored columns into a new definition once the board groups by it again.
+ */
+export function removeColumns(
+ config: BoardViewData | undefined,
+ groupBy: string
+): BoardViewData | undefined {
+ const key = boardColumnsKey(groupBy);
+ if (!config || !(key in config)) {
+ return undefined;
+ }
+
+ const removed: BoardViewData = { ...config };
+ delete removed[key];
+ return removed;
+}
+
/**
* The config with a pre-switching `columns` list moved under the grouping it belongs to, or nothing
* where there is none to move.
diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsx
index f29dabe34a..dddc3656ee 100644
--- a/apps/client/src/widgets/collections/board/index.tsx
+++ b/apps/client/src/widgets/collections/board/index.tsx
@@ -970,6 +970,12 @@ function Board({
return;
}
+ // The api stored a config after this refresh started, such as one without the
+ // columns of a deleted grouping. The columns read here can be the removed ones.
+ if (api.hasStoredSince(viewConfig)) {
+ return;
+ }
+
// Only to give a board that keeps no column list one to begin with. Written on
// every refresh instead, this is what a client reads the board with while another
// is changing it: it resolves a name the change has already taken away from
diff --git a/apps/client/src/widgets/collections/board/properties.spec.tsx b/apps/client/src/widgets/collections/board/properties.spec.tsx
index cefa7499ee..69a9137d26 100644
--- a/apps/client/src/widgets/collections/board/properties.spec.tsx
+++ b/apps/client/src/widgets/collections/board/properties.spec.tsx
@@ -55,10 +55,12 @@ vi.mock("../../react/TemplateSelectionCard", () => ({
// The card is tested in its own spec; what this dialog decides is the words it passes and where
// onChange writes.
vi.mock("../../react/PromotedAttributesCard", () => ({
- default: ({ heading, instruction, note, settings, onChange }: {
+ default: ({ heading, instruction, note, settings, onChange, runDeletion }: {
heading: string, instruction: string, note: FNote,
settings: { name: string }[] | undefined,
- onChange: (attributes: PromotedAttribute[]) => void
+ onChange: (attributes: PromotedAttribute[]) => void,
+ runDeletion?: (deletion: () => Promise<void>, type: "label" | "relation", name: string)
+ => Promise<void>
}) => (
<div
className="attributes-stub"
@@ -67,10 +69,23 @@ vi.mock("../../react/PromotedAttributesCard", () => ({
data-note={note.noteId}
data-settings={settings?.map((setting) => setting.name).join(",")}
onClick={() => onChange([ { name: "dueDate", hidden: true } as PromotedAttribute ])}
- />
+ >
+ <button className="delete-label" onClick={(e) => {
+ e.stopPropagation();
+ runDeletion?.(async () => { deletions.push("label:status"); }, "label", "status");
+ }} />
+ <button className="delete-relation" onClick={(e) => {
+ e.stopPropagation();
+ runDeletion?.(
+ async () => { deletions.push("relation:assignee"); }, "relation", "assignee");
+ }} />
+ </div>
)
}));
+/** The deletions the card stub handed to `runDeletion`, in the order the board ran them. */
+const deletions: string[] = [];
+
describe("Board properties", () => {
let container: HTMLElement;
let stored: string[][];
@@ -82,6 +97,8 @@ describe("Board properties", () => {
let sorting: string[];
/** The widths the board was asked to draw its columns at. */
let widths: string[];
+ /** The groupings whose attribute the board was asked to delete. */
+ let forgotten: string[];
/** Draws the dialog again, for a test that changed what the board says. */
let draw: () => void;
@@ -91,6 +108,8 @@ describe("Board properties", () => {
toggled = [];
sorting = [];
widths = [];
+ forgotten = [];
+ deletions.length = 0;
labels = { includeArchived: "true" };
container = document.createElement("div");
document.body.appendChild(container);
@@ -126,7 +145,11 @@ describe("Board properties", () => {
sorting.push(`descending:${isDescending}`);
},
resetColumnSortsToDefault: async () => { sorting.push("reset"); },
- setColumnWidth: async (width: string) => { widths.push(width); }
+ setColumnWidth: async (width: string) => { widths.push(width); },
+ deleteGrouping: async (groupBy: string, deletion: () => Promise<void>) => {
+ forgotten.push(groupBy);
+ await deletion();
+ }
} as unknown as BoardApi;
draw = () => act(() => {
@@ -316,6 +339,16 @@ describe("Board properties", () => {
expect(storedAttributes).toEqual([ [ { name: "dueDate", hidden: true } ] ]);
});
+ it("leaves deleting an attribute to the board, which drops its stored columns", async () => {
+ const card = dialog()?.querySelector<HTMLElement>(".attributes-stub");
+ await act(async () => { card?.querySelector<HTMLElement>(".delete-label")?.click(); });
+ await act(async () => { card?.querySelector<HTMLElement>(".delete-relation")?.click(); });
+
+ expect(forgotten).toEqual([ "status", "~assignee" ]);
+ expect(deletions).toEqual([ "label:status", "relation:assignee" ]);
+ expect(storedAttributes).toEqual([]);
+ });
+
it("writes what the card answers with back to the board", () => {
act(() => { dialog()?.querySelector<HTMLElement>(".templates-stub")?.click(); });
diff --git a/apps/client/src/widgets/collections/board/properties.tsx b/apps/client/src/widgets/collections/board/properties.tsx
index e9f80ad46d..e307e371ff 100644
--- a/apps/client/src/widgets/collections/board/properties.tsx
+++ b/apps/client/src/widgets/collections/board/properties.tsx
@@ -30,6 +30,10 @@ export default function BoardProperties({ api, note, shown, onClose }: {
(templates: string[]) => api.setCardTemplateIds(templates), [ api ]);
const storeAttributes = useCallback(
(attributes: PromotedAttribute[]) => api.setPromotedAttributes(attributes), [ api ]);
+ const deleteGrouping = useCallback(
+ (deletion: () => Promise<void>, type: "label" | "relation", name: string) =>
+ api.deleteGrouping(type === "relation" ? `~${name}` : name, deletion),
+ [ api ]);
return (
<CollectionPropertiesDialog
@@ -50,6 +54,7 @@ export default function BoardProperties({ api, note, shown, onClose }: {
drawnByCollection={[ api.statusAttribute ]}
itemNotes={api.getCardNotes()}
onChange={storeAttributes}
+ runDeletion={deleteGrouping}
/>
<TemplateSelectionCard
diff --git a/apps/client/src/widgets/react/PromotedAttributesCard.spec.tsx b/apps/client/src/widgets/react/PromotedAttributesCard.spec.tsx
index 904fea29c6..74d5d7ecd5 100644
--- a/apps/client/src/widgets/react/PromotedAttributesCard.spec.tsx
+++ b/apps/client/src/widgets/react/PromotedAttributesCard.spec.tsx
@@ -86,10 +86,17 @@ describe("PromotedAttributesCard", () => {
let itemNotes: FNote[] | undefined;
let unarrangedHidden: boolean | undefined;
let omitDrawn: boolean | undefined;
+ /** Wraps the card's deletion where a test hands one, recording what it was called with. */
+ let runDeletion: ((deletion: () => Promise<void>, type: "label" | "relation", name: string)
+ => Promise<void>) | undefined;
+ /** What `runDeletion` was called with, and whether the definition was gone before and after. */
+ let wrapped: { type: string, name: string, removedBefore: boolean, removedAfter: boolean }[];
beforeEach(() => {
vi.clearAllMocks();
stored = [];
+ runDeletion = undefined;
+ wrapped = [];
settings = undefined;
drawnByCollection = undefined;
itemNotes = undefined;
@@ -406,6 +413,35 @@ describe("PromotedAttributesCard", () => {
expect(mocks.removeOwned).toHaveBeenCalledWith(NOTE, "label", "label:dueDate");
});
+ /** A board drops the columns it stores for a grouping in the same write. */
+ it("hands the deletion to a collection that wraps one, from either button", async () => {
+ runDeletion = async (deletion, type, name) => {
+ const removedBefore = mocks.removeOwned.mock.calls.length > 0;
+ await deletion();
+ wrapped.push({
+ type, name, removedBefore, removedAfter: mocks.removeOwned.mock.calls.length > 0
+ });
+ };
+ draw();
+
+ await act(async () => {
+ segments()[0].querySelector<HTMLElement>(".promoted-attribute-delete")?.click();
+ await flush();
+ });
+ edit(1);
+ await act(async () => {
+ mocks.detail.callbacks.onDelete();
+ await flush();
+ });
+
+ expect(wrapped).toEqual([
+ { type: "label", name: "dueDate", removedBefore: false, removedAfter: true },
+ { type: "label", name: "owner", removedBefore: true, removedAfter: true }
+ ]);
+ expect(mocks.bulk).toHaveBeenCalledTimes(2);
+ expect(mocks.removeOwned).toHaveBeenCalledWith(NOTE, "label", "label:owner");
+ });
+
it("leaves everything alone where the reader said no", async () => {
mocks.confirm.mockResolvedValue(false);
draw();
@@ -547,6 +583,7 @@ describe("PromotedAttributesCard", () => {
unarrangedHidden={unarrangedHidden}
omitDrawn={omitDrawn}
onChange={(attributes) => stored.push(attributes)}
+ runDeletion={runDeletion}
/>
</ParentComponent.Provider>,
container);
diff --git a/apps/client/src/widgets/react/PromotedAttributesCard.tsx b/apps/client/src/widgets/react/PromotedAttributesCard.tsx
index 77db39c267..7e16b67100 100644
--- a/apps/client/src/widgets/react/PromotedAttributesCard.tsx
+++ b/apps/client/src/widgets/react/PromotedAttributesCard.tsx
@@ -68,6 +68,13 @@ export interface PromotedAttributesCardProps {
omitDrawn?: boolean;
/** Called with the whole list after every change, for the caller to store. */
onChange: (attributes: PromotedAttribute[]) => void;
+ /**
+ * Runs the deletion of a definition and its values, for a caller that keeps settings of its own
+ * for the attribute and must update them in the same write, such as the columns a board stores
+ * for a grouping. Without it, the card runs the deletion itself.
+ */
+ runDeletion?: (
+ deletion: () => Promise<void>, type: "label" | "relation", name: string) => Promise<void>;
}
/**
@@ -79,7 +86,7 @@ export interface PromotedAttributesCardProps {
*/
export default function PromotedAttributesCard({
heading, instruction, note, settings, drawnByCollection, itemNotes, unarrangedHidden, omitDrawn,
- onChange
+ onChange, runDeletion
}: PromotedAttributesCardProps) {
const resolve = (stored: PromotedAttributeSetting[] | undefined) => resolvePromotedAttributes(
note, stored, drawnByCollection, itemNotes, { unarrangedHidden })
@@ -235,9 +242,12 @@ export default function PromotedAttributesCard({
*/
const erase = useCallback(async (definitionName: string) => {
const [ type, name ] = extractAttributeDefinitionTypeAndName(definitionName);
- await deleteAttributeInSubtree(note.noteId, type, name);
- await removeOwnedAttributesByNameOrType(note, "label", definitionName);
- }, [ note ]);
+ const deletion = async () => {
+ await deleteAttributeInSubtree(note.noteId, type, name);
+ await removeOwnedAttributesByNameOrType(note, "label", definitionName);
+ };
+ await (runDeletion ? runDeletion(deletion, type, name) : deletion());
+ }, [ note, runDeletion ]);
/** Deletes the definition the editor was opened on. */
const removeEdited = useCallback(async () => {