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(board): give newly created boards their own status definition
Elian Doranf8d5e90e1251
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 448c56e799..427e6c3479 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3001,7 +3001,8 @@"edit-note-title": "Click to edit note title","edit-column-title": "Click to edit column title","column-already-exists": "This column already exists on the board.",- "column-definition-save-error": "The columns were saved on the board, but could not be saved to the status attribute."+ "column-definition-save-error": "The columns were saved on the board, but could not be saved to the status attribute.",+ "status-alias": "Status"},"dashboard_view": {"refresh-widget": "Refresh",diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.tsindex 53f1e4e2a5..e375577846 100644--- a/apps/client/src/widgets/collections/board/api.spec.ts+++ b/apps/client/src/widgets/collections/board/api.spec.ts@@ -1,24 +1,42 @@-import { describe, expect, it, vi } from "vitest";+import { beforeEach, describe, expect, it, vi } from "vitest";+import FAttribute from "../../../entities/fattribute";import FNote from "../../../entities/fnote";+import froca from "../../../services/froca";+import noteAttributeCache from "../../../services/note_attribute_cache";+import server from "../../../services/server";import { buildNote } from "../../../test/easy-froca";import { BoardViewData } from ".";import BoardApi from "./api";+import { BOARD_TEMPLATE_ID, getStatusDefinition } from "./columns";vi.mock("../../../services/bulk_action", () => ({executeBulkActions: vi.fn(async () => {})}));-function createApi(viewConfig: BoardViewData, columns: string[], parentNote?: FNote) {+vi.mock("../../../services/i18n", () => ({+ // i18next is never initialised under test, so the real `t` yields nothing and the alias would+ // silently vanish from the definitions asserted below rather than being checked.+ t: (key: string) => (key === "board_view.status-alias" ? "Status" : key)+}));++function createApi(+ viewConfig: BoardViewData,+ columns: string[],+ parentNote?: FNote,+ statusAttribute = "status"+) {+ const board = parentNote ?? buildNote({ title: "Board" });const saved: BoardViewData[] = [];const api = new BoardApi(new Map(),columns,- parentNote ?? buildNote({ title: "Board" }),- "status",+ board,+ statusAttribute,viewConfig,(newConfig) => saved.push(newConfig),- () => {}+ () => {},+ getStatusDefinition(board, statusAttribute));return { api, saved };}@@ -70,3 +88,191 @@ describe("BoardApi column mutations", () => {expect(saved.at(-1)?.columns?.map(col => col.value)).toEqual([ "Done", "To Do", "In Progress" ]);});});++/**+ * Migration 0240 only ever saw the boards that existed when the document was upgraded, and+ * `_template_board` no longer defines the status label, so a board created afterwards has no+ * definition at all until the board view writes one from the columns it resolved.+ */+describe("BoardApi.syncColumnsToDefinition", () => {+ let put: ReturnType<typeof vi.spyOn>;++ beforeEach(() => {+ // Without restoring first, each spy wraps the previous one and the calls accumulate.+ vi.restoreAllMocks();+ put = vi.spyOn(server, "put").mockResolvedValue(undefined);+ });++ function definitionWritten() {+ const [ url, body ] = put.mock.calls.at(-1) ?? [];+ return { url, ...(body as Record<string, unknown> | undefined) } as {+ url?: string;+ attributeId?: string;+ type?: string;+ name?: string;+ value?: string;+ isInheritable?: boolean;+ };+ }++ it("gives a board with no definition its own promoted select carrying the resolved columns", async () => {+ const { api } = createApi({}, [], buildBoard({}));++ await api.syncColumnsToDefinition([ "To Do", "Done" ]);++ expect(definitionWritten()).toMatchObject({+ url: "notes/boardNote/attribute",+ // No id: the board owns nothing yet, so the route creates the attribute.+ attributeId: undefined,+ type: "label",+ name: "label:status",+ // Promoted, so the column a card sits in is a field the card actually shows.+ value: "promoted,alias=Status,single,select,options=To Do;Done",+ isInheritable: true+ });+ });++ it("names a board grouping by its own label after that label rather than after status", async () => {+ const { api } = createApi({}, [], buildBoard({}), "priority");++ await api.syncColumnsToDefinition([ "High" ]);++ expect(definitionWritten()).toMatchObject({+ name: "label:priority",+ // Still promoted, but unaliased — "Status" is only the name of the default label.+ value: "promoted,single,select,options=High"+ });+ });++ /**+ * Migration 0240 leaves a board that never showed a Status field without one, so re-promoting it+ * here would make a field appear on every card of a board that had deliberately gone without.+ */+ it("keeps an existing definition unpromoted rather than promoting it on the way past", async () => {+ const { api } = createApi({}, [], buildBoard({+ "#label:status": "single,select,options=To Do"+ }));++ await api.syncColumnsToDefinition([ "To Do", "Done" ]);++ expect(definitionWritten().value).toBe("single,select,options=To Do;Done");+ });++ /**+ * The write lands as an entity change, which re-renders the board, which syncs again — so a board+ * whose definition already says what it shows has to write nothing, or it never stops.+ */+ it("writes nothing when the definition already offers exactly those columns", async () => {+ const { api } = createApi({}, [], buildBoard({+ "#label:status": "promoted,single,select,options=To Do;Done"+ }));++ await api.syncColumnsToDefinition([ "To Do", "Done" ]);++ expect(put).not.toHaveBeenCalled();+ });++ it("updates its own definition in place when a column appeared from outside the board", async () => {+ const board = buildBoard({ "#label:status": "promoted,single,select,options=To Do" });+ const { api } = createApi({}, [], board);++ // A note given `#status=Blocked` from the table view shows up as a column here, and the+ // definition has to learn about it as well.+ await api.syncColumnsToDefinition([ "To Do", "Blocked" ]);++ const written = definitionWritten();+ expect(written.value).toBe("promoted,single,select,options=To Do;Blocked");+ // Reusing the id updates the board's own row rather than adding a second definition.+ expect(written.attributeId).toBe(board.getOwnedAttributes()[1]?.attributeId);+ });++ it("keeps a differently ordered list, since the order is the one the user arranged", async () => {+ const { api } = createApi({}, [], buildBoard({+ "#label:status": "single,select,options=To Do;Done"+ }));++ await api.syncColumnsToDefinition([ "Done", "To Do" ]);++ expect(definitionWritten().value).toBe("single,select,options=Done;To Do");+ });++ it("copies a definition it does not own into one of its own rather than editing it", async () => {+ const board = buildBoard({}, [+ { noteId: BOARD_TEMPLATE_ID, name: "label:status", value: "promoted,single,text" }+ ]);+ const { api } = createApi({}, [], board);++ await api.syncColumnsToDefinition([ "To Do" ]);++ const written = definitionWritten();+ expect(written.attributeId).toBeUndefined();+ // What the template said is kept, so a board whose field was promoted keeps a promoted field.+ expect(written.value).toBe("promoted,single,select,options=To Do");+ });++ it.each<[ string, string, UntouchableBoard ]>([+ [ "grouping by a relation", "~status", {} ],+ [ "a definition owned by an ancestor", "status", {+ inherited: { noteId: "someAncestor", name: "label:status", value: "promoted,single,text" }+ } ],+ [ "a multi-valued definition", "status", { owned: { "#label:status": "promoted,multi,text" } } ],+ [ "a definition typed as something else", "status", { owned: { "#label:status": "promoted,single,date" } } ]+ ])("leaves the definition alone for %s", async (_label, groupBy, { owned, inherited }) => {+ const board = buildBoard(owned ?? {}, inherited ? [ inherited ] : []);+ const { api } = createApi({}, [], board, groupBy);++ await api.syncColumnsToDefinition([ "To Do" ]);++ expect(put).not.toHaveBeenCalled();+ });++ it("does not invent an empty definition, but does empty one the board owns", async () => {+ const { api: withoutDefinition } = createApi({}, [], buildBoard({}));+ await withoutDefinition.syncColumnsToDefinition([]);+ expect(put).not.toHaveBeenCalled();++ const { api: withDefinition } = createApi({}, [], buildBoard({+ "#label:status": "promoted,single,select,options=To Do"+ }));+ await withDefinition.syncColumnsToDefinition([]);+ expect(definitionWritten().value).toBe("promoted,single,select");+ });+});++/** A board whose definition the sync must not touch, however it came to have one. */+interface UntouchableBoard {+ owned?: Record<string, string>;+ inherited?: { noteId: string; name: string; value: string };+}++/**+ * A board note, optionally reached by definitions it does not own.+ *+ * Froca's mock does not resolve templates, so an inherited definition is pushed onto the note's+ * attribute cache directly — after the owned ones, which is the order `__getCachedAttributes`+ * produces and which the nearest-wins deduplication depends on.+ */+function buildBoard(+ ownedAttributes: Record<string, string>,+ inheritedDefinitions: { noteId: string; name: string; value: string }[] = []+): FNote {+ // buildNote appends to whatever the cache already holds for the id, so the previous test's+ // definitions would otherwise still be on the note.+ delete noteAttributeCache.attributes["boardNote"];++ const board = buildNote({ id: "boardNote", title: "Board", "#viewType": "board", ...ownedAttributes });++ for (const [ index, { noteId, name, value } ] of inheritedDefinitions.entries()) {+ noteAttributeCache.attributes[board.noteId].push(new FAttribute(froca, {+ noteId,+ attributeId: `inherited${index}`,+ type: "label",+ name,+ value,+ position: index,+ isInheritable: true+ }));+ }++ return board;+}diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.tsindex 1562d5af62..584c39f148 100644--- a/apps/client/src/widgets/collections/board/api.ts+++ b/apps/client/src/widgets/collections/board/api.ts@@ -1,4 +1,4 @@-import { BulkAction, promotedAttributeDefinitionParser } from "@triliumnext/commons";+import { BulkAction, type DefinitionObject, promotedAttributeDefinitionParser } from "@triliumnext/commons";import appContext from "../../../components/app_context";import FNote from "../../../entities/fnote";@@ -11,7 +11,7 @@ import note_create from "../../../services/note_create";import server from "../../../services/server";import toast from "../../../services/toast";import { BoardColumnData, BoardViewData } from ".";-import { type BoardStatusDefinition, canStoreColumnsInDefinition } from "./columns";+import { type BoardStatusDefinition, canStoreColumnsInDefinition, DEFAULT_GROUP_BY } from "./columns";import { ColumnMap } from "./data";export default class BoardApi {@@ -138,7 +138,7 @@ export default class BoardApi {// Not awaited — every caller is the tail of a user gesture the board has already rendered —// so the failure is caught here rather than left to reject unhandled. The columns are still// in the view config, so the board is not wrong, only out of step with the definition.- this.storeColumnsInDefinition(columns.map(({ value }) => value))+ this.syncColumnsToDefinition(columns.map(({ value }) => value)).catch((e) => {console.error("Failed to store the board columns in the attribute definition:", e);toast.showError(t("board_view.column-definition-save-error"));@@ -146,28 +146,57 @@ export default class BoardApi {}/**- * Writes the columns into the board's own definition, so that the same list is what the promoted- * field offers, what the table view's dropdown offers, and what the board shows.+ * Brings the board's own definition in line with the columns it shows, so that the same list is+ * what the promoted field offers, what the table view's dropdown offers, and what the board shows.*- * Where the board has no definition of its own the write creates one — a copy of the template's,- * which every board shares and which therefore cannot hold one board's columns. The copy keeps- * what the original said, so a board whose Status field was promoted keeps a promoted field and- * one that never had a field does not gain one.+ * Called both when the user changes a column and on every render, because a column can appear+ * without the board's column UI ever being used: a note given a new value from the table view, a+ * script or a synced instance shows up as a column here, and the definition has to learn about it+ * too. The render call is also what gives a newly created board its definition — nothing else+ * would, since migration 0240 only ever saw the boards that existed when it ran.+ *+ * Writing only on a real difference is what makes that safe to call every time: the write lands as+ * an entity change, which re-renders the board, which would write again.*/- private async storeColumnsInDefinition(options: string[]) {+ async syncColumnsToDefinition(columns: string[]) {if (this.isRelationMode || !canStoreColumnsInDefinition(this.statusDefinition)) {return;}+ // A board showing nothing has no column list to describe and must not gain an empty+ // definition; one that already owns one is still emptied, since that is its last column going.+ if (!columns.length && !this.statusDefinition?.isOwned) {+ return;+ }++ const current = this.statusDefinition?.options ?? [];+ const isUpToDate = this.statusDefinition?.definition.labelType === "select"+ && current.length === columns.length+ && current.every((option, index) => option === columns[index]);+ if (isUpToDate) {+ return;+ }++ // What a board with no definition of its own is given. Promoted, because the column a card+ // sits in is the point of the board, and a field that is not promoted is one the card never+ // shows — the status would be reachable only by dragging the card. Named only where the name+ // is ours to give: a board grouping by anything else is named by its own label.+ const created: DefinitionObject = {+ isPromoted: true,+ promotedAlias: this.statusAttribute === DEFAULT_GROUP_BY ? t("board_view.status-alias") : undefined+ };++ // An existing definition is updated as it stands, so a board deliberately left unpromoted —+ // by the user, or by migration 0240 where it had no field to begin with — does not gain one.const definition = {- ...this.statusDefinition?.definition,+ ...(this.statusDefinition?.definition ?? created),labelType: "select" as const,- selectOptions: options+ selectOptions: columns};await server.put(`notes/${this.parentNote.noteId}/attribute`, {- // Only an attribute the board owns can be updated; a definition reached through the- // template is copied instead, which the route does when given no id.+ // Only an attribute the board owns can be updated; anything else is copied into one of+ // the board's own, which the route does when given no id.attributeId: this.statusDefinition?.isOwned? this.statusDefinition.attribute.attributeId: undefined,diff --git a/apps/client/src/widgets/collections/board/columns.ts b/apps/client/src/widgets/collections/board/columns.tsindex 6239fb1178..080c398193 100644--- a/apps/client/src/widgets/collections/board/columns.ts+++ b/apps/client/src/widgets/collections/board/columns.ts@@ -4,12 +4,16 @@ import type FAttribute from "../../../entities/fattribute";import type FNote from "../../../entities/fnote";/**- * The definition every template-created board inherits. It is shared by every board in the document,- * so its options would be everyone's options — a board writes columns only into a definition of its- * own, taking a copy from this one when it has none.+ * The template every board is created from. It no longer defines the status label — it is shared by+ * every board in the document, so its options would be everyone's options — but documents that have+ * not yet had the hidden subtree re-checked, and peers syncing from an older instance, can still be+ * carrying the definition it used to hold. A board is allowed to copy that one into its own.*/export const BOARD_TEMPLATE_ID = "_template_board";+/** The label a board groups by when `#board:groupBy` does not name one. */+export const DEFAULT_GROUP_BY = "status";+export interface BoardStatusDefinition {/** The definition attribute, wherever it is owned. */attribute: FAttribute;@@ -62,6 +66,9 @@ export function getStatusDefinition(parentNote: FNote, groupBy: string): BoardSt* than this board: a copy here would quietly change the field for everything under the board. One* that says its values are dates, or that a note may hold several at once, is not describing* something a column list can stand in for. Those boards keep their columns in the attachment alone.+ *+ * Having none at all is the ordinary case for a board created now, and the answer is yes: the+ * definition the board writes is its own from the start.*/export function canStoreColumnsInDefinition(statusDefinition: BoardStatusDefinition | undefined): boolean {if (!statusDefinition) {diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsxindex a7c15dfc3c..9a823a5eb9 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -17,7 +17,7 @@ import { onWheelHorizontalScroll } from "../../widget_utils";import { ViewModeProps } from "../interface";import Api from "./api";import BoardApi from "./api";-import { getStatusDefinition } from "./columns";+import { DEFAULT_GROUP_BY, getStatusDefinition } from "./columns";import Column from "./column";import { ColumnMap, getBoardData } from "./data";@@ -49,7 +49,7 @@ interface BoardViewContextData {export const BoardViewContext = createContext<BoardViewContextData | undefined>(undefined);export default function BoardView({ note: parentNote, noteIds, viewConfig, saveConfig }: ViewModeProps<BoardViewData>) {- const [ statusAttributeWithPrefix ] = useNoteLabelWithDefault(parentNote, "board:groupBy", "status");+ const [ statusAttributeWithPrefix ] = useNoteLabelWithDefault(parentNote, "board:groupBy", DEFAULT_GROUP_BY);const [ includeArchived ] = useNoteLabelBoolean(parentNote, "includeArchived");const [ byColumn, setByColumn ] = useState<ColumnMap>();const [ columns, setColumns ] = useState<string[]>();@@ -101,6 +101,15 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCviewConfig = { ...newPersistedData };saveConfig(newPersistedData);}++ // The columns the board settled on are the options its definition should offer. This+ // is what gives a board created after migration 0240 ran a definition at all, and what+ // keeps one that gained a column from outside the board's own UI up to date. It writes+ // only when the two actually differ, so the re-render its own write causes stops here.+ // Reported rather than surfaced: nothing the user did is failing, and a board that+ // cannot write it re-tries on the next render, which would toast on each one.+ api.syncColumnsToDefinition(columns)+ .catch((e) => console.error("Failed to sync the board columns to the attribute definition:", e));});}diff --git a/packages/trilium-core/src/migrations/0240__migrate_board_status_to_select.ts b/packages/trilium-core/src/migrations/0240__migrate_board_status_to_select.tsindex 61c727648f..9c4ac4c60c 100644--- a/packages/trilium-core/src/migrations/0240__migrate_board_status_to_select.ts+++ b/packages/trilium-core/src/migrations/0240__migrate_board_status_to_select.ts@@ -12,15 +12,19 @@ import { unwrapStringOrBuffer } from "../services/utils/binary";* Gives every board its own `select` definition for the label it groups by, seeded with the columns* the board already shows, so the column list stops living only in the `board.json` attachment.*- * Boards created from the template inherit their `label:status` definition from `_template_board`,- * which every board in the document shares — one option list there would be everyone's option list.- * The copy this migration writes is owned by the board, so the options are the board's own; the- * template's definition is then removed from the hidden subtree definition, which `enforceAttributes`- * deletes from `_template_board` on the next startup. That ordering is automatic: the hidden subtree- * is not checked until the migrations have finished.+ * Boards reaching this migration were created from `_template_board` and inherit their `label:status`+ * definition from it, which every board in the document shares — one option list there would be+ * everyone's option list. The copy this migration writes is owned by the board, so the options are the+ * board's own; the template no longer declares the definition at all, so `enforceAttributes` deletes+ * the inherited one from `_template_board` on the next startup. That ordering is automatic: the hidden+ * subtree is not checked until the migrations have finished, so the copies are taken first.** A board is left exactly as it is whenever the copy would be wrong or unsafe — see* {@link SkipReason} — and the board view keeps reading `board.json` for those.+ *+ * This runs once, against the boards that exist when the document is upgraded. Boards created+ * afterwards get their definition from the board view instead, which writes the columns it resolves+ * into one (see `BoardApi#syncColumnsToDefinition`).*/export default () => {getContext().init(() => {diff --git a/packages/trilium-core/src/services/hidden_subtree_templates.spec.ts b/packages/trilium-core/src/services/hidden_subtree_templates.spec.tsindex 80d30d3084..c62f1810de 100644--- a/packages/trilium-core/src/services/hidden_subtree_templates.spec.ts+++ b/packages/trilium-core/src/services/hidden_subtree_templates.spec.ts@@ -170,8 +170,9 @@ describe("buildHiddenSubtreeTemplates", () => {const templates = buildHiddenSubtreeTemplates();const board = childById(templates, "_template_board");- const statusDefinition = board.attributes?.find((a) => a.name === "label:status");- expect(statusDefinition?.isInheritable).toBe(true);+ // The status definition belongs to each board, not to the template every board shares: one+ // option list here would be everyone's option list. Boards write their own.+ expect(board.attributes?.some((a) => a.name === "label:status")).toBe(false);const childIds = (board.children ?? []).map((c) => c.id);expect(childIds).toEqual([diff --git a/packages/trilium-core/src/services/hidden_subtree_templates.ts b/packages/trilium-core/src/services/hidden_subtree_templates.tsindex 5e81c9fca9..7a838fffb4 100644--- a/packages/trilium-core/src/services/hidden_subtree_templates.ts+++ b/packages/trilium-core/src/services/hidden_subtree_templates.ts@@ -247,13 +247,13 @@ export default function buildHiddenSubtreeTemplates() {name: "hidePromotedAttributes",type: "label"},- hideSubtreeAttributes,- {- name: "label:status",- type: "label",- value: `promoted,alias=${t("hidden_subtree_templates.status")},single,text`,- isInheritable: true- }+ hideSubtreeAttributes+ // Deliberately no `label:status`: the columns a board shows are the options of a+ // select definition, and a definition here would be shared by every board in the+ // document — one board's columns would be everyone's. Each board owns its own+ // instead, written by the board view once it knows its columns (see+ // BoardApi#syncColumnsToDefinition) and by migration 0240 for boards that predate+ // it. `enforceAttributes` deletes the definition this template used to carry.],children: [{